aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authordvshkurko <dvshkurko@yandex-team.ru>2022-02-10 16:45:51 +0300
committerDaniil Cherednik <dcherednik@yandex-team.ru>2022-02-10 16:45:51 +0300
commit321ee9bce31ec6e238be26dbcbe539cffa2c3309 (patch)
tree14407a2757cbf29eb97e266b7f07e851f971000c
parent2f6ca198245aeffd5e2d82b65927c2465b68b4f5 (diff)
downloadydb-321ee9bce31ec6e238be26dbcbe539cffa2c3309.tar.gz
Restoring authorship annotation for <dvshkurko@yandex-team.ru>. Commit 1 of 2.
-rw-r--r--build/docs/empty/ya.make10
-rw-r--r--build/plugins/java.py18
-rw-r--r--build/scripts/c_templates/svn_interface.c314
-rw-r--r--build/scripts/c_templates/svnversion.h78
-rw-r--r--build/scripts/c_templates/ya.make10
-rw-r--r--build/scripts/compile_java.py18
-rwxr-xr-xbuild/scripts/fetch_from.py62
-rw-r--r--build/scripts/fetch_from_external.py2
-rw-r--r--build/scripts/fetch_from_mds.py2
-rwxr-xr-xbuild/scripts/fetch_from_sandbox.py158
-rw-r--r--build/scripts/go_tool.py12
-rw-r--r--build/scripts/link_exe.py36
-rw-r--r--build/scripts/run_msvc_wine.py6
-rw-r--r--build/scripts/vcs_info.py500
-rw-r--r--build/scripts/ya.make4
-rw-r--r--build/ya.conf.json26
-rw-r--r--build/ya.make2
-rw-r--r--build/ymake.core.conf142
-rwxr-xr-xbuild/ymake_conf.py142
-rw-r--r--contrib/libs/c-ares/CHANGES472
-rw-r--r--contrib/libs/c-ares/RELEASE-NOTES2
-rw-r--r--contrib/libs/c-ares/RELEASE-PROCEDURE.md106
-rw-r--r--contrib/libs/c-ares/acountry/ya.make60
-rw-r--r--contrib/libs/c-ares/adig/ya.make60
-rw-r--r--contrib/libs/c-ares/ahost/ya.make60
-rw-r--r--contrib/libs/c-ares/ares.h4
-rw-r--r--contrib/libs/c-ares/ares_android.c194
-rw-r--r--contrib/libs/c-ares/ares_android.h2
-rw-r--r--contrib/libs/c-ares/ares_config.h18
-rw-r--r--contrib/libs/c-ares/ares_create_query.c10
-rw-r--r--contrib/libs/c-ares/ares_destroy.c12
-rw-r--r--contrib/libs/c-ares/ares_gethostbyname.c14
-rw-r--r--contrib/libs/c-ares/ares_getnameinfo.c22
-rw-r--r--contrib/libs/c-ares/ares_init.c378
-rw-r--r--contrib/libs/c-ares/ares_library_init.c26
-rw-r--r--contrib/libs/c-ares/ares_options.c12
-rw-r--r--contrib/libs/c-ares/ares_parse_ptr_reply.c8
-rw-r--r--contrib/libs/c-ares/ares_private.h38
-rw-r--r--contrib/libs/c-ares/ares_process.c54
-rw-r--r--contrib/libs/c-ares/ares_rules.h2
-rw-r--r--contrib/libs/c-ares/ares_search.c14
-rw-r--r--contrib/libs/c-ares/ares_send.c12
-rw-r--r--contrib/libs/c-ares/ares_strsplit.c348
-rw-r--r--contrib/libs/c-ares/ares_strsplit.h86
-rw-r--r--contrib/libs/c-ares/config-win32.h2
-rw-r--r--contrib/libs/c-ares/inet_ntop.c2
-rw-r--r--contrib/libs/c-ares/test/ares-test-init.cc1318
-rw-r--r--contrib/libs/c-ares/test/ares-test-internal.cc970
-rw-r--r--contrib/libs/c-ares/test/ares-test-live.cc1258
-rw-r--r--contrib/libs/c-ares/test/ares-test-misc.cc1026
-rw-r--r--contrib/libs/c-ares/test/ares-test-mock.cc2314
-rw-r--r--contrib/libs/c-ares/test/ares-test-ns.cc398
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-a.cc714
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-aaaa.cc380
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-mx.cc282
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-naptr.cc296
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-ns.cc238
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-ptr.cc498
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-soa.cc214
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-srv.cc576
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse-txt.cc532
-rw-r--r--contrib/libs/c-ares/test/ares-test-parse.cc438
-rw-r--r--contrib/libs/c-ares/test/ares-test.cc1396
-rw-r--r--contrib/libs/c-ares/test/ares-test.h858
-rw-r--r--contrib/libs/c-ares/test/config.h162
-rw-r--r--contrib/libs/c-ares/test/dns-proto-test.cc262
-rw-r--r--contrib/libs/c-ares/test/dns-proto.cc1276
-rw-r--r--contrib/libs/c-ares/test/dns-proto.h484
-rw-r--r--contrib/libs/c-ares/test/ya.make104
-rw-r--r--contrib/libs/c-ares/ya.make30
-rw-r--r--contrib/libs/grpc/AUTHORS8
-rw-r--r--contrib/libs/grpc/BUILD.gn2288
-rw-r--r--contrib/libs/grpc/BUILDING.md204
-rw-r--r--contrib/libs/grpc/CODE-OF-CONDUCT.md6
-rw-r--r--contrib/libs/grpc/CONCEPTS.md126
-rw-r--r--contrib/libs/grpc/CONTRIBUTING.md254
-rw-r--r--contrib/libs/grpc/GOVERNANCE.md2
-rw-r--r--contrib/libs/grpc/MAINTAINERS.md166
-rw-r--r--contrib/libs/grpc/MANIFEST.md46
-rw-r--r--contrib/libs/grpc/NOTICE.txt26
-rw-r--r--contrib/libs/grpc/README.md164
-rw-r--r--contrib/libs/grpc/TROUBLESHOOTING.md84
-rw-r--r--contrib/libs/grpc/grpc++/ya.make54
-rw-r--r--contrib/libs/grpc/grpc++_error_details/ya.make58
-rw-r--r--contrib/libs/grpc/grpc++_reflection/ya.make58
-rw-r--r--contrib/libs/grpc/grpc++_unsecure/ya.make58
-rw-r--r--contrib/libs/grpc/grpc/ya.make16
-rw-r--r--contrib/libs/grpc/grpc_unsecure/ya.make70
-rw-r--r--contrib/libs/grpc/grpcpp_channelz/ya.make60
-rw-r--r--contrib/libs/grpc/include/grpc/grpc.h24
-rw-r--r--contrib/libs/grpc/include/grpc/grpc_security.h360
-rw-r--r--contrib/libs/grpc/include/grpc/grpc_security_constants.h2
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/byte_buffer.h26
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/gpr_types.h2
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h56
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h208
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/slice.h2
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/status.h4
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/sync_generic.h2
-rw-r--r--contrib/libs/grpc/include/grpc/impl/codegen/sync_posix.h36
-rw-r--r--contrib/libs/grpc/include/grpc/slice.h6
-rw-r--r--contrib/libs/grpc/include/grpcpp/channel.h2
-rw-r--r--contrib/libs/grpc/include/grpcpp/create_channel_posix.h2
-rw-r--r--contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h8
-rw-r--r--contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin_impl.h82
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h84
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/async_unary_call.h2
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h50
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h112
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h40
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h36
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h22
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h6
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h6
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h8
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h10
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/delegating_channel.h166
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h10
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h16
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/message_allocator.h146
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/method_handler.h90
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_reader.h18
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_writer.h2
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/proto_utils.h22
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h24
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/security/auth_context.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback_handlers.h1330
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/server_context.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h12
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h82
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h44
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/status_code_enum.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/codegen/sync.h302
-rw-r--r--contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/security/credentials.h6
-rw-r--r--contrib/libs/grpc/include/grpcpp/security/cronet_credentials.h56
-rw-r--r--contrib/libs/grpc/include/grpcpp/security/server_credentials.h4
-rw-r--r--contrib/libs/grpc/include/grpcpp/security/tls_credentials_options.h562
-rw-r--r--contrib/libs/grpc/include/grpcpp/support/channel_arguments.h2
-rw-r--r--contrib/libs/grpc/include/grpcpp/support/message_allocator.h48
-rw-r--r--contrib/libs/grpc/include/grpcpp/support/method_handler.h48
-rw-r--r--contrib/libs/grpc/include/grpcpp/support/validate_service_config.h70
-rw-r--r--contrib/libs/grpc/include/grpcpp/test/default_reactor_test_peer.h106
-rw-r--r--contrib/libs/grpc/include/grpcpp/test/mock_stream.h2
-rw-r--r--contrib/libs/grpc/include/grpcpp/test/server_context_test_spouse.h6
-rw-r--r--contrib/libs/grpc/src/compiler/config.h2
-rw-r--r--contrib/libs/grpc/src/compiler/config_protobuf.h92
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_generator.cc298
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_generator.h6
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_generator_helpers.h2
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_plugin.cc2
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_plugin.h280
-rw-r--r--contrib/libs/grpc/src/compiler/csharp_generator.cc12
-rw-r--r--contrib/libs/grpc/src/compiler/csharp_generator_helpers.h2
-rw-r--r--contrib/libs/grpc/src/compiler/grpc_cpp_plugin/ya.make56
-rw-r--r--contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make50
-rw-r--r--contrib/libs/grpc/src/compiler/grpc_python_plugin/ya.make56
-rw-r--r--contrib/libs/grpc/src/compiler/node_generator_helpers.h2
-rw-r--r--contrib/libs/grpc/src/compiler/objective_c_generator.cc142
-rw-r--r--contrib/libs/grpc/src/compiler/objective_c_generator.h22
-rw-r--r--contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h12
-rw-r--r--contrib/libs/grpc/src/compiler/php_generator_helpers.h2
-rw-r--r--contrib/libs/grpc/src/compiler/protobuf_plugin.h30
-rw-r--r--contrib/libs/grpc/src/compiler/python_generator.cc92
-rw-r--r--contrib/libs/grpc/src/compiler/python_generator.h2
-rw-r--r--contrib/libs/grpc/src/compiler/python_generator_helpers.h40
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h2
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h30
-rw-r--r--contrib/libs/grpc/src/core/README.md2
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/README.md14
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.cc132
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.h72
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.cc52
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.h18
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc38
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc4740
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h48
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc36
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h26
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.cc44
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.h24
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc14
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h84
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc32
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc208
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h50
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc134
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc190
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.h10
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc162
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h610
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc122
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc918
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h14
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc26
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h24
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc58
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc20
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h32
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc116
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h24
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc362
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc292
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h226
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/cds.cc432
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h4
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h6
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc78
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h18
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc16
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper.h28
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.cc92
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h48
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc100
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h94
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc156
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc224
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h20
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc310
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc6
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc848
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc210
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h16
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc8
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc74
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc4
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc56
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h58
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc100
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc254
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h44
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc122
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc200
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h20
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.cc46
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.h22
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc180
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h80
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.cc514
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.h194
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.cc10
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.h4
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.cc144
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.h180
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc692
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h274
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_interface.h188
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h6
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_idle/client_idle_filter.cc880
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc66
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h6
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc90
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc36
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc168
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc148
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc146
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc154
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.h56
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc38
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.cc220
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h60
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create.cc78
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc204
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc14
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc8
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h8
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.cc14
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h8
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc18
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc950
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc10
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc2
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.h30
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc76
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc18
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h6
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc14
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc28
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h18
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc22
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.h4
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc8
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h2
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc1016
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h48
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc402
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h24
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc60
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h120
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc20
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h18
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h144
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc250
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_lists.cc6
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.cc56
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc128
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc202
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.c36
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.h58
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.c132
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.h324
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.c54
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.h104
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.c886
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h2602
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.c54
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.h104
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.c44
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.h96
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.c156
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.h320
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.c54
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h104
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.c212
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h420
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.c66
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.h132
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c96
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h162
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c358
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h1000
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c84
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h192
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c72
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h154
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c256
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h612
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c104
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h152
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.c802
-rw-r--r--contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.h2894
-rw-r--r--contrib/libs/grpc/src/core/lib/avl/avl.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_args.cc78
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_args.h84
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_stack.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_stack.h56
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_trace.cc16
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_trace.h8
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channelz.cc364
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channelz.h168
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc116
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channelz_registry.h20
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/connected_channel.cc46
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/context.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker.cc22
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker.h8
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression.cc34
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression_args.cc268
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression_args.h112
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression_internal.cc34
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression_internal.h18
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/message_compress.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.cc18
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/trace.cc26
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/trace.h34
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/alloc.cc8
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/arena.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env_linux.cc30
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env_posix.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env_windows.cc14
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log.cc18
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log_linux.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log_posix.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string.cc54
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string.h22
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc122
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_posix.cc26
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_precise.cc246
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_precise.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/README.md2
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/arena.cc206
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/arena.h240
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/atomic.h146
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/debug_location.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/fork.cc58
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/fork.h36
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/global_config.h192
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/global_config_custom.h58
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/global_config_env.cc258
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/global_config_env.h262
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/global_config_generic.h88
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/host_port.cc164
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/host_port.h84
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/map.h96
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/memory.h20
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/mpscq.cc216
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/mpscq.h196
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/orphanable.h28
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h218
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/sync.h252
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/thd.h108
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc116
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc110
-rw-r--r--contrib/libs/grpc/src/core/lib/http/httpcli.cc12
-rw-r--r--contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc34
-rw-r--r--contrib/libs/grpc/src/core/lib/http/parser.cc8
-rw-r--r--contrib/libs/grpc/src/core/lib/http/parser.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc18
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h12
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc178
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h162
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc74
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/closure.h82
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/combiner.cc92
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/combiner.h62
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_posix.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_windows.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/error.cc58
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/error.h66
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/error_internal.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc122
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc188
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc90
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc58
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h30
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc156
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor.cc96
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor.h18
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.cc366
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.h350
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.cc274
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.h298
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc8
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc28
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr.h14
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc24
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc12
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h18
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc28
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc22
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc32
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/poller/eventmanager_interface.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc32
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/port.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/python_util.h92
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.cc14
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_windows.cc12
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc246
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc58
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h8
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc42
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h18
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc8
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_windows.cc14
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc64
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc516
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h42
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_custom.cc46
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc156
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_windows.cc38
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc62
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc14
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc54
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc40
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc42
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/udp_server.h12
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc24
-rw-r--r--contrib/libs/grpc/src/core/lib/security/context/security_context.cc12
-rw-r--r--contrib/libs/grpc/src/core/lib/security/context/security_context.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc96
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc14
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/credentials.h16
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc18
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc8
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.cc12
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc450
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h34
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc26
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc46
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc56
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h128
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc66
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h10
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc56
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h40
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc100
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc290
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h74
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.cc64
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/auth_filters.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc144
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc30
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc202
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h8
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc40
-rw-r--r--contrib/libs/grpc/src/core/lib/security/util/json_util.cc16
-rw-r--r--contrib/libs/grpc/src/core/lib/security/util/json_util.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/b64.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/b64.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/percent_encoding.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice.cc434
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc120
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_intern.cc386
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_internal.h602
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.cc20
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_traits.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_utils.h382
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/api_trace.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/byte_buffer_reader.cc34
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call.cc308
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call.h18
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call_log_batch.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel.cc194
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel.h92
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel_ping.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue.cc480
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue.h12
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init.cc150
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init_secure.cc4
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/lame_client.cc92
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/server.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc36
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/validate_metadata.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc6
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h4
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/byte_stream.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/byte_stream.h12
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc194
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/connectivity_state.h160
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/error_utils.cc42
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata.cc872
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata.h612
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc158
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata_batch.h78
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/static_metadata.cc1748
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/static_metadata.h398
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_conversion.cc2
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_metadata.cc22
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_metadata.h36
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc16
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h8
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport.cc88
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport.h162
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport_impl.h2
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport_op_string.cc10
-rw-r--r--contrib/libs/grpc/src/core/lib/ya.make116
-rw-r--r--contrib/libs/grpc/src/core/plugin_registry/grpc_plugin_registry.cc12
-rw-r--r--contrib/libs/grpc/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc12
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc2
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc770
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h2
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc2
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h2
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc452
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h10
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h10
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc20
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h8
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc150
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h70
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc452
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc288
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc20
-rw-r--r--contrib/libs/grpc/src/core/tsi/fake_transport_security.cc20
-rw-r--r--contrib/libs/grpc/src/core/tsi/local_transport_security.cc16
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session.h4
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc2
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc24
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h8
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc2
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc94
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl_transport_security.h56
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/BUILD26
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/multi-domain.pem8
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc10
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security_grpc.h8
-rwxr-xr-xcontrib/libs/grpc/src/cpp/README.md40
-rw-r--r--contrib/libs/grpc/src/cpp/client/channel_cc.cc64
-rw-r--r--contrib/libs/grpc/src/cpp/client/client_context.cc60
-rw-r--r--contrib/libs/grpc/src/cpp/client/client_interceptor.cc20
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel.cc36
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel_internal.cc6
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel_internal.h6
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel_posix.cc12
-rw-r--r--contrib/libs/grpc/src/cpp/client/credentials_cc.cc2
-rw-r--r--contrib/libs/grpc/src/cpp/client/insecure_credentials.cc12
-rw-r--r--contrib/libs/grpc/src/cpp/client/secure_credentials.cc380
-rw-r--r--contrib/libs/grpc/src/cpp/client/secure_credentials.h34
-rw-r--r--contrib/libs/grpc/src/cpp/codegen/codegen_init.cc2
-rw-r--r--contrib/libs/grpc/src/cpp/common/alarm.cc36
-rw-r--r--contrib/libs/grpc/src/cpp/common/channel_arguments.cc36
-rw-r--r--contrib/libs/grpc/src/cpp/common/channel_filter.h16
-rw-r--r--contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc8
-rw-r--r--contrib/libs/grpc/src/cpp/common/core_codegen.cc18
-rw-r--r--contrib/libs/grpc/src/cpp/common/tls_credentials_options.cc488
-rw-r--r--contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.cc282
-rw-r--r--contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.h112
-rw-r--r--contrib/libs/grpc/src/cpp/common/validate_service_config.cc72
-rw-r--r--contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc2
-rw-r--r--contrib/libs/grpc/src/cpp/server/channel_argument_option.cc8
-rw-r--r--contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc44
-rw-r--r--contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc18
-rw-r--r--contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h8
-rw-r--r--contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.cc188
-rw-r--r--contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.h138
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc90
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h14
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/health_check_service_server_builder_option.cc2
-rw-r--r--contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc2
-rw-r--r--contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc8
-rw-r--r--contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc36
-rw-r--r--contrib/libs/grpc/src/cpp/server/secure_server_credentials.h22
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_builder.cc142
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_callback.cc74
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_cc.cc842
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_context.cc84
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_posix.cc2
-rw-r--r--contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc66
-rw-r--r--contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h22
-rw-r--r--contrib/libs/grpc/src/cpp/util/error_details.cc30
-rw-r--r--contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto4
-rw-r--r--contrib/libs/grpc/src/proto/grpc/channelz/ya.make34
-rw-r--r--contrib/libs/grpc/src/proto/grpc/core/ya.make30
-rw-r--r--contrib/libs/grpc/src/proto/grpc/gcp/altscontext.proto100
-rw-r--r--contrib/libs/grpc/src/proto/grpc/gcp/handshaker.proto468
-rw-r--r--contrib/libs/grpc/src/proto/grpc/gcp/transport_security_common.proto92
-rw-r--r--contrib/libs/grpc/src/proto/grpc/health/v1/ya.make30
-rw-r--r--contrib/libs/grpc/src/proto/grpc/http_over_grpc/http_over_grpc.proto102
-rw-r--r--contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/ya.make32
-rw-r--r--contrib/libs/grpc/src/proto/grpc/status/ya.make32
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/control.proto22
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make48
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto6
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/messages.proto54
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/metrics.proto2
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto102
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto984
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto366
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/orca_load_report_for_test.proto116
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make56
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/ya.make78
-rw-r--r--contrib/libs/grpc/src/python/grpcio/README.rst26
-rw-r--r--contrib/libs/grpc/src/python/grpcio/commands.py54
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/__init__.py450
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_channel.py1128
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_common.py100
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_compression.py110
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi8
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pxd.pxi36
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pyx.pxi122
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pxd.pxi100
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pyx.pxi160
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pxd.pxi36
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pyx.pxi48
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pxd.pxi44
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pyx.pxi58
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/iomgr.pyx.pxi446
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pxd.pxi44
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pyx.pxi88
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pxd.pxi108
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pyx.pxi256
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pxd.pxi42
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pyx.pxi68
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pxd.pxi88
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi454
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi2
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi6
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi8
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi100
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi14
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi14
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi54
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi56
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi96
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi24
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi2
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pxd.pxi240
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pyx.pxi118
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi12
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi2
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi52
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi14
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi2
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi12
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pxd.pxi46
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pyx.pxi72
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd28
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx46
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py162
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_server.py330
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py30
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/experimental/aio/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py434
-rw-r--r--contrib/libs/grpc/src/python/grpcio/ya.make28
-rw-r--r--contrib/libs/grpc/src/python/grpcio_channelz/README.rst34
-rw-r--r--contrib/libs/grpc/src/python/grpcio_channelz/setup.py12
-rw-r--r--contrib/libs/grpc/src/python/grpcio_channelz/ya.make84
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/README.rst16
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py140
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/setup.py10
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/ya.make84
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/README.rst16
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/setup.py10
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/ya.make84
-rw-r--r--contrib/libs/grpc/src/python/grpcio_status/README.rst34
-rw-r--r--contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py4
-rw-r--r--contrib/libs/grpc/src/python/grpcio_status/setup.py8
-rw-r--r--contrib/libs/grpc/src/python/grpcio_status/ya.make80
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/README.rst16
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_service.py4
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py18
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/setup.py6
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/commands.py578
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/grpc_version.py32
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/setup.py178
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/__init__.py42
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/_loader.py212
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/_result.py800
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/_runner.py474
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/_sanity_test.py88
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/bazel_namespace_package_hack.py80
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/_channelz_servicer_test.py918
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/fork/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/fork/_fork_interop_test.py296
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/fork/client.py112
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/fork/methods.py882
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/_health_servicer_test.py522
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/http2/negative_http2_client.py278
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py88
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_intraop_test_case.py102
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_secure_intraop_test.py94
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/client.py140
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/methods.py906
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/resources.py84
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/server.py94
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/interop/service.py172
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_client.py396
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_server.py78
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/client_runner.py176
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/histogram.py140
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/qps_worker.py84
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/qps/worker_server.py352
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py390
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/status/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/status/_grpc_status_test.py348
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/stress/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/stress/client.py266
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/stress/metrics_server.py90
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/stress/test_runner.py110
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/stress/unary_stream_benchmark.py194
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_common.py86
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_testing_common.py66
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_application.py468
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_test.py616
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_application.py190
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_test.py414
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_time_test.py326
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/testing/proto/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py302
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py226
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_context_test.py332
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py164
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py116
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py440
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py302
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py190
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_compression_test.py742
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py140
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py442
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py140
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py246
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py144
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py252
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py240
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py480
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py98
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py804
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py104
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py122
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py248
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py170
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py466
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py410
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py46
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py108
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py1290
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py268
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py470
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py138
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py198
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py1228
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py404
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py472
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py136
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py518
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py194
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py190
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py886
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py96
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py150
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_session_cache_test.py212
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py224
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py400
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py282
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py60
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py638
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py64
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_implementations_test.py106
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py108
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py186
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py80
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md30
-rwxr-xr-xcontrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem4
-rwxr-xr-xcontrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key4
-rwxr-xr-xcontrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem4
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py152
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py90
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py194
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py202
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py146
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py114
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py226
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py264
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py68
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/__init__.py42
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/_sanity_test.py54
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/benchmark/server.py82
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/__init__.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_base.py46
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_server.py50
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/call_test.py118
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/channel_test.py104
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/init_test.py42
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/server_test.py208
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/ya.make258
-rw-r--r--contrib/libs/grpc/test/core/util/cmdline.cc596
-rw-r--r--contrib/libs/grpc/test/core/util/cmdline.h158
-rw-r--r--contrib/libs/grpc/test/core/util/cmdline_test.cc962
-rw-r--r--contrib/libs/grpc/test/core/util/debugger_macros.cc114
-rw-r--r--contrib/libs/grpc/test/core/util/debugger_macros.h54
-rw-r--r--contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc260
-rwxr-xr-xcontrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh36
-rw-r--r--contrib/libs/grpc/test/core/util/fuzzer_util.cc164
-rw-r--r--contrib/libs/grpc/test/core/util/fuzzer_util.h98
-rw-r--r--contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl54
-rw-r--r--contrib/libs/grpc/test/core/util/grpc_profiler.cc90
-rw-r--r--contrib/libs/grpc/test/core/util/grpc_profiler.h50
-rw-r--r--contrib/libs/grpc/test/core/util/histogram.cc460
-rw-r--r--contrib/libs/grpc/test/core/util/histogram.h124
-rw-r--r--contrib/libs/grpc/test/core/util/histogram_test.cc326
-rw-r--r--contrib/libs/grpc/test/core/util/lsan_suppressions.txt12
-rw-r--r--contrib/libs/grpc/test/core/util/memory_counters.cc338
-rw-r--r--contrib/libs/grpc/test/core/util/memory_counters.h106
-rw-r--r--contrib/libs/grpc/test/core/util/mock_endpoint.cc280
-rw-r--r--contrib/libs/grpc/test/core/util/mock_endpoint.h58
-rw-r--r--contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc96
-rw-r--r--contrib/libs/grpc/test/core/util/parse_hexstring.cc112
-rw-r--r--contrib/libs/grpc/test/core/util/parse_hexstring.h52
-rw-r--r--contrib/libs/grpc/test/core/util/passthru_endpoint.cc442
-rw-r--r--contrib/libs/grpc/test/core/util/passthru_endpoint.h86
-rw-r--r--contrib/libs/grpc/test/core/util/port.cc256
-rw-r--r--contrib/libs/grpc/test/core/util/port.h88
-rw-r--r--contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc110
-rw-r--r--contrib/libs/grpc/test/core/util/port_server_client.cc430
-rw-r--r--contrib/libs/grpc/test/core/util/port_server_client.h60
-rw-r--r--contrib/libs/grpc/test/core/util/reconnect_server.cc228
-rw-r--r--contrib/libs/grpc/test/core/util/reconnect_server.h88
-rwxr-xr-xcontrib/libs/grpc/test/core/util/run_with_poller.sh38
-rw-r--r--contrib/libs/grpc/test/core/util/slice_splitter.cc252
-rw-r--r--contrib/libs/grpc/test/core/util/slice_splitter.h106
-rw-r--r--contrib/libs/grpc/test/core/util/subprocess.h72
-rw-r--r--contrib/libs/grpc/test/core/util/subprocess_posix.cc200
-rw-r--r--contrib/libs/grpc/test/core/util/subprocess_windows.cc252
-rw-r--r--contrib/libs/grpc/test/core/util/test_config.cc708
-rw-r--r--contrib/libs/grpc/test/core/util/test_config.h114
-rw-r--r--contrib/libs/grpc/test/core/util/test_lb_policies.cc386
-rw-r--r--contrib/libs/grpc/test/core/util/test_lb_policies.h64
-rw-r--r--contrib/libs/grpc/test/core/util/test_tcp_server.cc210
-rw-r--r--contrib/libs/grpc/test/core/util/test_tcp_server.h72
-rw-r--r--contrib/libs/grpc/test/core/util/tracer_util.cc62
-rw-r--r--contrib/libs/grpc/test/core/util/tracer_util.h64
-rw-r--r--contrib/libs/grpc/test/core/util/trickle_endpoint.cc416
-rw-r--r--contrib/libs/grpc/test/core/util/trickle_endpoint.h64
-rw-r--r--contrib/libs/grpc/test/core/util/tsan_suppressions.txt26
-rw-r--r--contrib/libs/grpc/test/core/util/ubsan_suppressions.txt50
-rw-r--r--contrib/libs/grpc/test/core/util/ya.make86
-rw-r--r--contrib/libs/grpc/test/cpp/README-iOS.md104
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/async_end2end_test.cc3730
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/channelz_service_test.cc1530
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/client_callback_end2end_test.cc2546
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/client_crash_test.cc288
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/client_crash_test_server.cc158
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/client_interceptors_end2end_test.cc2036
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/client_lb_end2end_test.cc3524
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/end2end_test.cc4348
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/exception_test.cc246
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/filter_end2end_test.cc676
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/generic_end2end_test.cc838
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/grpclb_end2end_test.cc3514
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/health/ya.make62
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc724
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/hybrid_end2end_test.cc1924
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc308
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/interceptors_util.h594
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/mock_test.cc832
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/nonblocking_test.cc380
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/proto_server_reflection_test.cc290
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/raw_end2end_test.cc740
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_builder_plugin_test.cc516
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_crash_test.cc312
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_crash_test_client.cc142
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_early_return_test.cc460
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make60
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc1384
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_load_reporting_end2end_test.cc368
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/shutdown_test.cc334
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/streaming_throughput_test.cc386
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc194
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h112
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc1028
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_service_impl.h218
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/thread/ya.make_60
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/thread_stress_test.cc882
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/time_change_test.cc724
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/ya.make112
-rw-r--r--contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc12
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_call.h2
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_call_test.cc4
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_credentials.cc4
-rw-r--r--contrib/libs/grpc/test/cpp/util/create_test_channel.cc182
-rw-r--r--contrib/libs/grpc/test/cpp/util/create_test_channel.h58
-rw-r--r--contrib/libs/grpc/test/cpp/util/grpc_tool.cc16
-rw-r--r--contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc6
-rw-r--r--contrib/libs/grpc/test/cpp/util/metrics_server.cc4
-rw-r--r--contrib/libs/grpc/test/cpp/util/metrics_server.h4
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_file_parser.h4
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc18
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h2
-rw-r--r--contrib/libs/grpc/test/cpp/util/slice_test.cc12
-rw-r--r--contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc76
-rw-r--r--contrib/libs/grpc/test/cpp/util/ya.make6
-rw-r--r--contrib/libs/grpc/third_party/address_sorting/address_sorting.c750
-rw-r--r--contrib/libs/grpc/third_party/address_sorting/address_sorting_internal.h140
-rw-r--r--contrib/libs/grpc/third_party/address_sorting/address_sorting_posix.c194
-rw-r--r--contrib/libs/grpc/third_party/address_sorting/address_sorting_windows.c190
-rw-r--r--contrib/libs/grpc/third_party/address_sorting/include/address_sorting/address_sorting.h226
-rw-r--r--contrib/libs/grpc/third_party/address_sorting/ya.make44
-rw-r--r--contrib/libs/grpc/third_party/upb/README.md268
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/decode.c224
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/decode.h42
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/encode.c512
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/encode.h42
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/msg.c98
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/msg.h110
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/port.c52
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/port_def.inc286
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/port_undef.inc40
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/table.c1650
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/table.int.h910
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/upb.c274
-rw-r--r--contrib/libs/grpc/third_party/upb/upb/upb.h434
-rw-r--r--contrib/libs/grpc/third_party/upb/ya.make38
-rw-r--r--contrib/libs/grpc/tools/README.md46
-rw-r--r--contrib/libs/grpc/tools/codegen/core/gen_hpack_tables.cc704
-rw-r--r--contrib/libs/grpc/tools/codegen/core/gen_hpack_tables/ya.make60
-rw-r--r--contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters.cc132
-rw-r--r--contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters/ya.make40
-rw-r--r--contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables.cc138
-rw-r--r--contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables/ya.make40
-rw-r--r--contrib/libs/grpc/ya.make68
-rw-r--r--contrib/libs/ya.make2
-rw-r--r--contrib/python/Jinja2/py2/jinja2/loaders.py2
-rw-r--r--contrib/python/Jinja2/py3/jinja2/loaders.py2
-rw-r--r--contrib/python/MarkupSafe/py2/.dist-info/METADATA206
-rw-r--r--contrib/python/MarkupSafe/py2/.dist-info/top_level.txt2
-rw-r--r--contrib/python/MarkupSafe/py2/ya.make10
-rw-r--r--contrib/python/MarkupSafe/py3/.dist-info/METADATA138
-rw-r--r--contrib/python/MarkupSafe/py3/.dist-info/top_level.txt2
-rw-r--r--contrib/python/MarkupSafe/py3/ya.make10
-rw-r--r--contrib/python/setuptools/py2/pkg_resources/__init__.py10
-rw-r--r--contrib/python/setuptools/py3/pkg_resources/__init__.py8
-rw-r--r--contrib/python/traitlets/py2/tests/ya.make24
-rw-r--r--contrib/python/traitlets/py2/traitlets/tests/_warnings.py214
-rw-r--r--contrib/python/traitlets/py2/traitlets/tests/test_traitlets.py4836
-rw-r--r--contrib/python/traitlets/py2/traitlets/tests/test_traitlets_enum.py362
-rw-r--r--contrib/python/traitlets/py2/traitlets/tests/utils.py76
-rw-r--r--contrib/python/traitlets/py2/ya.make6
-rw-r--r--contrib/python/traitlets/py3/traitlets/tests/_warnings.py194
-rw-r--r--contrib/python/traitlets/py3/traitlets/tests/test_traitlets.py4608
-rw-r--r--contrib/python/traitlets/py3/traitlets/tests/test_traitlets_enum.py354
-rw-r--r--contrib/python/traitlets/py3/traitlets/tests/utils.py78
-rw-r--r--contrib/python/traitlets/py3/ya.make6
-rw-r--r--contrib/python/traitlets/ya.make4
-rw-r--r--contrib/python/ya.make48
-rw-r--r--contrib/restricted/boost/libs/filesystem/ya.make2
-rw-r--r--contrib/restricted/boost/libs/python/ya.make2
-rw-r--r--contrib/restricted/googletest/googlemock/gmock_main/ya.make28
-rw-r--r--contrib/restricted/googletest/googlemock/ya.make24
-rw-r--r--contrib/restricted/googletest/googletest/gtest_main/ya.make26
-rw-r--r--contrib/restricted/googletest/googletest/src/gtest-death-test.cc22
-rw-r--r--contrib/restricted/googletest/googletest/src/gtest-port.cc4
-rw-r--r--contrib/restricted/googletest/googletest/src/gtest.cc8
-rw-r--r--contrib/restricted/googletest/googletest/ya.make20
-rw-r--r--contrib/tools/protoc/plugins/grpc_cpp/ya.make6
-rw-r--r--contrib/tools/protoc/plugins/grpc_python/ya.make6
-rw-r--r--contrib/tools/yasm/frontends/yasm/yasm.c74
-rw-r--r--contrib/tools/yasm/libyasm/dbgfmt.h18
-rw-r--r--contrib/tools/yasm/libyasm/objfmt.h18
-rw-r--r--contrib/tools/yasm/libyasm/replace_path.c108
-rw-r--r--contrib/tools/yasm/libyasm/section.c8
-rw-r--r--contrib/tools/yasm/libyasm/section.h2
-rw-r--r--contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-info.c22
-rw-r--r--contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-line.c30
-rw-r--r--contrib/tools/yasm/modules/init_plugin.c40
-rw-r--r--contrib/tools/yasm/modules/objfmts/coff/coff-objfmt.c12
-rw-r--r--contrib/tools/yasm/modules/objfmts/elf/elf-objfmt.c24
-rw-r--r--contrib/tools/yasm/util.h4
-rw-r--r--library/cpp/grpc/client/grpc_client_low.h4
-rw-r--r--library/cpp/grpc/server/grpc_request.h4
-rw-r--r--library/cpp/svnversion/svn_interface.c2
-rw-r--r--library/cpp/svnversion/svnversion.h8
-rw-r--r--library/cpp/svnversion/test/main.cpp56
-rw-r--r--library/cpp/svnversion/test/ya.make6
-rw-r--r--library/cpp/svnversion/ya.make8
-rw-r--r--library/python/fs/__init__.py54
-rw-r--r--library/python/fs/test/test_fs.py46
-rw-r--r--library/python/fs/test/ya.make2
-rw-r--r--library/python/pytest/plugins/ya.py52
-rw-r--r--library/python/runtime_py3/importer.pxi2
-rw-r--r--library/python/strings/strings.py54
-rw-r--r--library/python/strings/ut/test_strings.py58
-rw-r--r--library/python/strings/ut/ya.make2
-rw-r--r--library/python/strings/ya.make2
-rw-r--r--library/python/svn_version/__init__.py2
-rw-r--r--library/python/svn_version/__svn_version.pyx24
-rw-r--r--library/python/svn_version/ut/lib/test_simple.py14
-rw-r--r--library/python/symbols/libc/syms.cpp4
-rw-r--r--library/python/testing/yatest_common/ya.make2
-rw-r--r--library/python/testing/yatest_common/yatest/common/path.py60
-rw-r--r--library/python/testing/yatest_common/yatest/common/runtime.py18
-rw-r--r--tools/rescompressor/main.cpp90
-rw-r--r--util/folder/dirut.cpp2
-rw-r--r--util/network/pair.cpp36
-rw-r--r--util/network/pair.h2
-rw-r--r--util/system/daemon.cpp32
-rw-r--r--util/system/daemon.h12
-rw-r--r--util/system/daemon_ut.cpp184
-rw-r--r--util/system/file.cpp6
-rw-r--r--util/system/file_lock.cpp2
-rw-r--r--util/system/flock.cpp2
-rw-r--r--util/system/pipe.cpp44
-rw-r--r--util/system/pipe.h10
-rw-r--r--util/system/shellcommand.cpp16
-rw-r--r--util/system/ut/ya.make2
-rwxr-xr-xya.bat172
-rw-r--r--ydb/core/grpc_streaming/grpc_streaming.h4
-rw-r--r--ydb/core/grpc_streaming/grpc_streaming_ut.cpp4
1121 files changed, 99268 insertions, 99268 deletions
diff --git a/build/docs/empty/ya.make b/build/docs/empty/ya.make
index 3540411405..694964e428 100644
--- a/build/docs/empty/ya.make
+++ b/build/docs/empty/ya.make
@@ -1,5 +1,5 @@
-UNION()
-
-OWNER(g:ymake)
-
-END()
+UNION()
+
+OWNER(g:ymake)
+
+END()
diff --git a/build/plugins/java.py b/build/plugins/java.py
index 16fc126734..c40e184295 100644
--- a/build/plugins/java.py
+++ b/build/plugins/java.py
@@ -180,15 +180,15 @@ def onjava_module(unit, *args):
ymake.report_configure_error('{}: JDK export supported only for JAVA_PROGRAM module type'.format(unit.path()))
data['WITH_JDK'] = extract_macro_calls(unit, 'WITH_JDK_VALUE', args_delim)
- if not data['EXTERNAL_JAR']:
- has_processor = extract_macro_calls(unit, 'GENERATE_VCS_JAVA_INFO_NODEP', args_delim)
- data['EMBED_VCS'] = [[str(has_processor and has_processor[0] and has_processor[0][0])]]
- # FORCE_VCS_INFO_UPDATE is responsible for setting special value of VCS_INFO_DISABLE_CACHE__NO_UID__
- macro_val = extract_macro_calls(unit, 'FORCE_VCS_INFO_UPDATE', args_delim)
- macro_str = macro_val[0][0] if macro_val and macro_val[0] and macro_val[0][0] else ''
- if macro_str and macro_str == 'yes':
- data['VCS_INFO_DISABLE_CACHE__NO_UID__'] = macro_val
-
+ if not data['EXTERNAL_JAR']:
+ has_processor = extract_macro_calls(unit, 'GENERATE_VCS_JAVA_INFO_NODEP', args_delim)
+ data['EMBED_VCS'] = [[str(has_processor and has_processor[0] and has_processor[0][0])]]
+ # FORCE_VCS_INFO_UPDATE is responsible for setting special value of VCS_INFO_DISABLE_CACHE__NO_UID__
+ macro_val = extract_macro_calls(unit, 'FORCE_VCS_INFO_UPDATE', args_delim)
+ macro_str = macro_val[0][0] if macro_val and macro_val[0] and macro_val[0][0] else ''
+ if macro_str and macro_str == 'yes':
+ data['VCS_INFO_DISABLE_CACHE__NO_UID__'] = macro_val
+
for java_srcs_args in data['JAVA_SRCS']:
external = None
diff --git a/build/scripts/c_templates/svn_interface.c b/build/scripts/c_templates/svn_interface.c
index d8bdd1a70d..45cb2b09b5 100644
--- a/build/scripts/c_templates/svn_interface.c
+++ b/build/scripts/c_templates/svn_interface.c
@@ -1,79 +1,79 @@
-// Used indirectly. See build/scripts/vcs_info.py
-// ya-bin dump vcs-info > vcs.json
+// Used indirectly. See build/scripts/vcs_info.py
+// ya-bin dump vcs-info > vcs.json
// python build/scripts/vcs_info.py vcs.json out.c build/scripts/c_templates/svn_interface.c <any_prefix>library/cpp/svnversion<any_suffix>
-
-
-#include "build/scripts/c_templates/svnversion.h"
-
-#define STR1(x) #x
-#define STR2(x) STR1(x)
-
-const char* GetProgramSvnVersion() {
-#if defined(REVISION)
-// for package systems generating from svn export but providing REVISION macro
-#define STRREVISION STR2(REVISION)
-#define REVISIONINFO "r" STRREVISION
-#if defined(PROGRAM_VERSION)
- return PROGRAM_VERSION "\n\n" REVISIONINFO;
-#else
- return REVISIONINFO " "__DATE__
- " "__TIME__;
-#endif
-#elif defined(PROGRAM_VERSION)
- return PROGRAM_VERSION;
-#else
- return "No program version found";
-#endif
-}
-
-const char* GetArcadiaSourcePath() {
-#if defined(ARCADIA_SOURCE_PATH)
- return ARCADIA_SOURCE_PATH;
-#else
- return "";
-#endif
-}
-
-const char* GetArcadiaSourceUrl() {
-#if defined(ARCADIA_SOURCE_URL)
- return ARCADIA_SOURCE_URL;
-#else
- return "";
-#endif
-}
-
-int GetArcadiaLastChangeNum() {
-#if defined(ARCADIA_SOURCE_LAST_CHANGE)
- return ARCADIA_SOURCE_LAST_CHANGE;
-#else
- return 0;
-#endif
-}
-
-const char* GetArcadiaLastChange() {
-#if defined(ARCADIA_SOURCE_LAST_CHANGE)
- return STR2(ARCADIA_SOURCE_LAST_CHANGE);
-#else
- return "";
-#endif
-}
-
-const char* GetArcadiaLastAuthor() {
-#if defined(ARCADIA_SOURCE_LAST_AUTHOR)
- return ARCADIA_SOURCE_LAST_AUTHOR;
-#else
- return "";
-#endif
-}
-
-int GetProgramSvnRevision() {
-#if defined(ARCADIA_SOURCE_REVISION)
- return ARCADIA_SOURCE_REVISION;
-#else
- return 0;
-#endif
-}
-
+
+
+#include "build/scripts/c_templates/svnversion.h"
+
+#define STR1(x) #x
+#define STR2(x) STR1(x)
+
+const char* GetProgramSvnVersion() {
+#if defined(REVISION)
+// for package systems generating from svn export but providing REVISION macro
+#define STRREVISION STR2(REVISION)
+#define REVISIONINFO "r" STRREVISION
+#if defined(PROGRAM_VERSION)
+ return PROGRAM_VERSION "\n\n" REVISIONINFO;
+#else
+ return REVISIONINFO " "__DATE__
+ " "__TIME__;
+#endif
+#elif defined(PROGRAM_VERSION)
+ return PROGRAM_VERSION;
+#else
+ return "No program version found";
+#endif
+}
+
+const char* GetArcadiaSourcePath() {
+#if defined(ARCADIA_SOURCE_PATH)
+ return ARCADIA_SOURCE_PATH;
+#else
+ return "";
+#endif
+}
+
+const char* GetArcadiaSourceUrl() {
+#if defined(ARCADIA_SOURCE_URL)
+ return ARCADIA_SOURCE_URL;
+#else
+ return "";
+#endif
+}
+
+int GetArcadiaLastChangeNum() {
+#if defined(ARCADIA_SOURCE_LAST_CHANGE)
+ return ARCADIA_SOURCE_LAST_CHANGE;
+#else
+ return 0;
+#endif
+}
+
+const char* GetArcadiaLastChange() {
+#if defined(ARCADIA_SOURCE_LAST_CHANGE)
+ return STR2(ARCADIA_SOURCE_LAST_CHANGE);
+#else
+ return "";
+#endif
+}
+
+const char* GetArcadiaLastAuthor() {
+#if defined(ARCADIA_SOURCE_LAST_AUTHOR)
+ return ARCADIA_SOURCE_LAST_AUTHOR;
+#else
+ return "";
+#endif
+}
+
+int GetProgramSvnRevision() {
+#if defined(ARCADIA_SOURCE_REVISION)
+ return ARCADIA_SOURCE_REVISION;
+#else
+ return 0;
+#endif
+}
+
const char* GetVCSDirty()
{
#if defined(DIRTY)
@@ -83,33 +83,33 @@ const char* GetVCSDirty()
#endif
}
-const char* GetProgramHash() {
-#if defined(ARCADIA_SOURCE_HG_HASH)
- return ARCADIA_SOURCE_HG_HASH;
-#else
- return "";
-#endif
-}
-
-const char* GetProgramCommitId() {
-#if defined(ARCADIA_SOURCE_REVISION)
- if (ARCADIA_SOURCE_REVISION <= 0) {
- return GetProgramHash();
- }
- return STR2(ARCADIA_SOURCE_REVISION);
-#else
- return GetProgramHash();
-#endif
-}
-
-const char* GetProgramScmData() {
-#if defined(SCM_DATA)
- return SCM_DATA;
-#else
- return "";
-#endif
-}
-
+const char* GetProgramHash() {
+#if defined(ARCADIA_SOURCE_HG_HASH)
+ return ARCADIA_SOURCE_HG_HASH;
+#else
+ return "";
+#endif
+}
+
+const char* GetProgramCommitId() {
+#if defined(ARCADIA_SOURCE_REVISION)
+ if (ARCADIA_SOURCE_REVISION <= 0) {
+ return GetProgramHash();
+ }
+ return STR2(ARCADIA_SOURCE_REVISION);
+#else
+ return GetProgramHash();
+#endif
+}
+
+const char* GetProgramScmData() {
+#if defined(SCM_DATA)
+ return SCM_DATA;
+#else
+ return "";
+#endif
+}
+
const char* GetProgramShortVersionData() {
#if defined(SVN_REVISION) && defined(SVN_TIME)
return STR2(SVN_REVISION) " (" SVN_TIME ")";
@@ -118,30 +118,30 @@ const char* GetProgramShortVersionData() {
#endif
}
-const char* GetProgramBuildUser() {
-#if defined(BUILD_USER)
- return BUILD_USER;
-#else
- return "";
-#endif
-}
-
-const char* GetProgramBuildHost() {
-#if defined(BUILD_HOST)
- return BUILD_HOST;
-#else
- return "";
-#endif
-}
-
-const char* GetProgramBuildDate() {
-#if defined(BUILD_DATE)
- return BUILD_DATE;
-#else
- return "";
-#endif
-}
-
+const char* GetProgramBuildUser() {
+#if defined(BUILD_USER)
+ return BUILD_USER;
+#else
+ return "";
+#endif
+}
+
+const char* GetProgramBuildHost() {
+#if defined(BUILD_HOST)
+ return BUILD_HOST;
+#else
+ return "";
+#endif
+}
+
+const char* GetProgramBuildDate() {
+#if defined(BUILD_DATE)
+ return BUILD_DATE;
+#else
+ return "";
+#endif
+}
+
int GetProgramBuildTimestamp() {
#if defined(BUILD_TIMESTAMP)
return BUILD_TIMESTAMP;
@@ -151,34 +151,34 @@ int GetProgramBuildTimestamp() {
}
-const char* GetVCS() {
-#if defined(VCS)
- return VCS;
-#else
- return "";
-#endif
-}
-
-const char* GetBranch() {
-#if defined(BRANCH)
- return BRANCH;
-#else
- return "";
-#endif
-}
-
-int GetArcadiaPatchNumber() {
-#if defined(ARCADIA_PATCH_NUMBER)
- return ARCADIA_PATCH_NUMBER;
-#else
- return 42;
-#endif
-}
-
-const char* GetTag() {
-#if defined(ARCADIA_TAG)
- return ARCADIA_TAG;
-#else
- return "";
-#endif
-}
+const char* GetVCS() {
+#if defined(VCS)
+ return VCS;
+#else
+ return "";
+#endif
+}
+
+const char* GetBranch() {
+#if defined(BRANCH)
+ return BRANCH;
+#else
+ return "";
+#endif
+}
+
+int GetArcadiaPatchNumber() {
+#if defined(ARCADIA_PATCH_NUMBER)
+ return ARCADIA_PATCH_NUMBER;
+#else
+ return 42;
+#endif
+}
+
+const char* GetTag() {
+#if defined(ARCADIA_TAG)
+ return ARCADIA_TAG;
+#else
+ return "";
+#endif
+}
diff --git a/build/scripts/c_templates/svnversion.h b/build/scripts/c_templates/svnversion.h
index 7aece931aa..3cc1adab35 100644
--- a/build/scripts/c_templates/svnversion.h
+++ b/build/scripts/c_templates/svnversion.h
@@ -1,42 +1,42 @@
-#pragma once
-
-// Permit compilation with NO_UTIL():
-// util/system/compiler.h
-#if !defined(Y_HIDDEN)
-#if defined(__GNUC__)
-#define Y_HIDDEN __attribute__((visibility("hidden")))
-#else
-#define Y_HIDDEN
-#endif
-#endif
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-const char* GetProgramSvnVersion() Y_HIDDEN; // verbose multiline message
-void PrintProgramSvnVersion() Y_HIDDEN;
-const char* GetArcadiaSourcePath() Y_HIDDEN; // "/home/myltsev/arcadia"
-const char* GetArcadiaSourceUrl() Y_HIDDEN; // "svn+ssh://arcadia.yandex.ru/arc/trunk/arcadia"
-const char* GetArcadiaLastChange() Y_HIDDEN; // "2902074"
-int GetArcadiaLastChangeNum() Y_HIDDEN; // 2902074
-const char* GetArcadiaLastAuthor() Y_HIDDEN; // "dieash"
-int GetProgramSvnRevision() Y_HIDDEN; // 2902074
+#pragma once
+
+// Permit compilation with NO_UTIL():
+// util/system/compiler.h
+#if !defined(Y_HIDDEN)
+#if defined(__GNUC__)
+#define Y_HIDDEN __attribute__((visibility("hidden")))
+#else
+#define Y_HIDDEN
+#endif
+#endif
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+const char* GetProgramSvnVersion() Y_HIDDEN; // verbose multiline message
+void PrintProgramSvnVersion() Y_HIDDEN;
+const char* GetArcadiaSourcePath() Y_HIDDEN; // "/home/myltsev/arcadia"
+const char* GetArcadiaSourceUrl() Y_HIDDEN; // "svn+ssh://arcadia.yandex.ru/arc/trunk/arcadia"
+const char* GetArcadiaLastChange() Y_HIDDEN; // "2902074"
+int GetArcadiaLastChangeNum() Y_HIDDEN; // 2902074
+const char* GetArcadiaLastAuthor() Y_HIDDEN; // "dieash"
+int GetProgramSvnRevision() Y_HIDDEN; // 2902074
const char* GetVCSDirty() Y_HIDDEN;
-const char* GetProgramHash() Y_HIDDEN;
-const char* GetProgramCommitId() Y_HIDDEN;
-void PrintSvnVersionAndExit(int argc, char* argv[]) Y_HIDDEN;
-void PrintSvnVersionAndExitEx(int argc, char* argv[], const char* opts) Y_HIDDEN;
-void PrintSvnVersionAndExit0() Y_HIDDEN;
-const char* GetProgramScmData() Y_HIDDEN; // verbose multiline message
+const char* GetProgramHash() Y_HIDDEN;
+const char* GetProgramCommitId() Y_HIDDEN;
+void PrintSvnVersionAndExit(int argc, char* argv[]) Y_HIDDEN;
+void PrintSvnVersionAndExitEx(int argc, char* argv[], const char* opts) Y_HIDDEN;
+void PrintSvnVersionAndExit0() Y_HIDDEN;
+const char* GetProgramScmData() Y_HIDDEN; // verbose multiline message
const char* GetProgramShortVersionData() Y_HIDDEN;
-const char* GetProgramBuildUser() Y_HIDDEN;
-const char* GetProgramBuildHost() Y_HIDDEN;
-const char* GetProgramBuildDate() Y_HIDDEN;
+const char* GetProgramBuildUser() Y_HIDDEN;
+const char* GetProgramBuildHost() Y_HIDDEN;
+const char* GetProgramBuildDate() Y_HIDDEN;
int GetProgramBuildTimestamp() Y_HIDDEN;
-const char* GetVCS() Y_HIDDEN;
-const char* GetBranch() Y_HIDDEN;
-const char* GetTag() Y_HIDDEN;
-int GetArcadiaPatchNumber() Y_HIDDEN;
-#if defined(__cplusplus)
-}
-#endif
+const char* GetVCS() Y_HIDDEN;
+const char* GetBranch() Y_HIDDEN;
+const char* GetTag() Y_HIDDEN;
+int GetArcadiaPatchNumber() Y_HIDDEN;
+#if defined(__cplusplus)
+}
+#endif
diff --git a/build/scripts/c_templates/ya.make b/build/scripts/c_templates/ya.make
index b395e11021..306077cc96 100644
--- a/build/scripts/c_templates/ya.make
+++ b/build/scripts/c_templates/ya.make
@@ -1,7 +1,7 @@
OWNER(g:ymake)
-LIBRARY(dummy-vcs)
-NO_PLATFORM()
-
-SRCS(svn_interface.c)
-END()
+LIBRARY(dummy-vcs)
+NO_PLATFORM()
+
+SRCS(svn_interface.c)
+END()
diff --git a/build/scripts/compile_java.py b/build/scripts/compile_java.py
index e95869e853..ad3164355d 100644
--- a/build/scripts/compile_java.py
+++ b/build/scripts/compile_java.py
@@ -12,7 +12,7 @@ def parse_args(args):
parser = optparse.OptionParser()
parser.add_option('--javac-bin')
parser.add_option('--jar-bin')
- parser.add_option('--vcs-mf')
+ parser.add_option('--vcs-mf')
parser.add_option('--package-prefix')
parser.add_option('--jar-output')
parser.add_option('--srcs-jar-output')
@@ -76,10 +76,10 @@ def main():
with zipfile.ZipFile(s) as zf:
zf.extractall(classes_dir)
- if opts.vcs_mf:
- sp.check_call([opts.jar_bin, 'cfm', opts.jar_output, opts.vcs_mf, os.curdir], cwd=classes_dir)
- else:
- sp.check_call([opts.jar_bin, 'cfM', opts.jar_output, os.curdir], cwd=classes_dir)
+ if opts.vcs_mf:
+ sp.check_call([opts.jar_bin, 'cfm', opts.jar_output, opts.vcs_mf, os.curdir], cwd=classes_dir)
+ else:
+ sp.check_call([opts.jar_bin, 'cfM', opts.jar_output, os.curdir], cwd=classes_dir)
if opts.srcs_jar_output:
for s in jsrcs:
@@ -92,10 +92,10 @@ def main():
shutil.copyfile(s, d)
- if opts.vcs_mf:
- sp.check_call([opts.jar_bin, 'cfm', opts.srcs_jar_output, opts.vcs_mf, os.curdir], cwd=sources_dir)
- else:
- sp.check_call([opts.jar_bin, 'cfM', opts.srcs_jar_output, os.curdir], cwd=sources_dir)
+ if opts.vcs_mf:
+ sp.check_call([opts.jar_bin, 'cfm', opts.srcs_jar_output, opts.vcs_mf, os.curdir], cwd=sources_dir)
+ else:
+ sp.check_call([opts.jar_bin, 'cfM', opts.srcs_jar_output, os.curdir], cwd=sources_dir)
if __name__ == '__main__':
diff --git a/build/scripts/fetch_from.py b/build/scripts/fetch_from.py
index db4fea50bf..96f3acd589 100755
--- a/build/scripts/fetch_from.py
+++ b/build/scripts/fetch_from.py
@@ -4,7 +4,7 @@ import hashlib
import json
import logging
import os
-import platform
+import platform
import random
import shutil
import socket
@@ -27,7 +27,7 @@ def add_common_arguments(parser):
parser.add_argument('--untar-to')
parser.add_argument('--rename', action='append', default=[], metavar='FILE', help='rename FILE to the corresponding output')
parser.add_argument('--executable', action='store_true', help='make outputs executable')
- parser.add_argument('--log-path')
+ parser.add_argument('--log-path')
parser.add_argument('-v', '--verbose', action='store_true', default=os.environ.get('YA_VERBOSE_FETCHER'), help='increase stderr verbosity')
parser.add_argument('outputs', nargs='*', default=[])
@@ -90,36 +90,36 @@ class OutputNotExistError(Exception):
pass
-def setup_logging(args, base_name):
- def makedirs(path):
- try:
- os.makedirs(path)
- except OSError:
- pass
-
- if args.log_path:
- log_file_name = args.log_path
- else:
- log_file_name = base_name + ".log"
-
- args.abs_log_path = os.path.abspath(log_file_name)
- makedirs(os.path.dirname(args.abs_log_path))
- logging.basicConfig(filename=args.abs_log_path, level=logging.DEBUG)
+def setup_logging(args, base_name):
+ def makedirs(path):
+ try:
+ os.makedirs(path)
+ except OSError:
+ pass
+
+ if args.log_path:
+ log_file_name = args.log_path
+ else:
+ log_file_name = base_name + ".log"
+
+ args.abs_log_path = os.path.abspath(log_file_name)
+ makedirs(os.path.dirname(args.abs_log_path))
+ logging.basicConfig(filename=args.abs_log_path, level=logging.DEBUG)
if args.verbose:
logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
-
-
+
+
def is_temporary(e):
- def is_broken(e):
- return isinstance(e, urllib2.HTTPError) and e.code in (410, 404)
+ def is_broken(e):
+ return isinstance(e, urllib2.HTTPError) and e.code in (410, 404)
if is_broken(e):
return False
-
+
if isinstance(e, (BadChecksumFetchError, IncompleteFetchError, urllib2.URLError, socket.error)):
return True
-
+
import error
return error.is_temporary_error(e)
@@ -293,16 +293,16 @@ def fetch_url(url, unpack, resource_file_name, expected_md5=None, expected_sha1=
def chmod(filename, mode):
- if platform.system().lower() == 'windows':
- # https://docs.microsoft.com/en-us/windows/win32/fileio/hard-links-and-junctions:
- # hard to reset read-only attribute for removal if there are multiple hardlinks
- return
+ if platform.system().lower() == 'windows':
+ # https://docs.microsoft.com/en-us/windows/win32/fileio/hard-links-and-junctions:
+ # hard to reset read-only attribute for removal if there are multiple hardlinks
+ return
stat = os.stat(filename)
if stat.st_mode & 0o777 != mode:
try:
os.chmod(filename, mode)
except OSError:
- import pwd
+ import pwd
sys.stderr.write("{} st_mode: {} pwuid: {}\n".format(filename, stat.st_mode, pwd.getpwuid(os.stat(filename).st_uid)))
raise
@@ -356,9 +356,9 @@ def process(fetched_file, file_name, args, remove=True):
logging.info('Renaming %s to %s', src, dst)
if os.path.exists(dst):
raise ResourceUnpackingError("Target file already exists ({} -> {})".format(src, dst))
- if remove:
- rename_or_copy_and_remove(src, dst)
- else:
+ if remove:
+ rename_or_copy_and_remove(src, dst)
+ else:
hardlink_or_copy(src, dst)
for path in args.outputs:
diff --git a/build/scripts/fetch_from_external.py b/build/scripts/fetch_from_external.py
index d4ed6f4221..c7202d2ed2 100644
--- a/build/scripts/fetch_from_external.py
+++ b/build/scripts/fetch_from_external.py
@@ -18,7 +18,7 @@ def parse_args():
def main(args):
external_file = args.external_file.rstrip('.external')
if os.path.isfile(args.resource_file):
- fetch_from.process(args.resource_file, os.path.basename(args.resource_file), args, False)
+ fetch_from.process(args.resource_file, os.path.basename(args.resource_file), args, False)
return
error = None
diff --git a/build/scripts/fetch_from_mds.py b/build/scripts/fetch_from_mds.py
index 5e4e656394..7ab993fc31 100644
--- a/build/scripts/fetch_from_mds.py
+++ b/build/scripts/fetch_from_mds.py
@@ -37,7 +37,7 @@ def main(args):
if __name__ == '__main__':
args = parse_args()
- fetch_from.setup_logging(args, os.path.basename(__file__))
+ fetch_from.setup_logging(args, os.path.basename(__file__))
try:
main(args)
diff --git a/build/scripts/fetch_from_sandbox.py b/build/scripts/fetch_from_sandbox.py
index a99542e174..5408ca05af 100755
--- a/build/scripts/fetch_from_sandbox.py
+++ b/build/scripts/fetch_from_sandbox.py
@@ -15,7 +15,7 @@ import fetch_from
ORIGIN_SUFFIX = '?origin=fetch-from-sandbox'
MDS_PREFIX = 'http://storage-int.mds.yandex.net/get-sandbox/'
-TEMPORARY_ERROR_CODES = (429, 500, 503, 504)
+TEMPORARY_ERROR_CODES = (429, 500, 503, 504)
def parse_args():
@@ -23,7 +23,7 @@ def parse_args():
fetch_from.add_common_arguments(parser)
parser.add_argument('--resource-id', type=int, required=True)
parser.add_argument('--custom-fetcher')
- parser.add_argument('--resource-file')
+ parser.add_argument('--resource-file')
return parser.parse_args()
@@ -35,33 +35,33 @@ class UnsupportedProtocolException(Exception):
pass
-def _sky_path():
- return "/usr/local/bin/sky"
+def _sky_path():
+ return "/usr/local/bin/sky"
-def _is_skynet_avaliable():
- if not os.path.exists(_sky_path()):
- return False
- try:
- subprocess.check_output([_sky_path(), "--version"])
- return True
- except subprocess.CalledProcessError:
- return False
- except OSError:
- return False
-
-
-def download_by_skynet(resource_info, file_name):
+def _is_skynet_avaliable():
+ if not os.path.exists(_sky_path()):
+ return False
+ try:
+ subprocess.check_output([_sky_path(), "--version"])
+ return True
+ except subprocess.CalledProcessError:
+ return False
+ except OSError:
+ return False
+
+
+def download_by_skynet(resource_info, file_name):
def sky_get(skynet_id, target_dir, timeout=None):
cmd_args = [_sky_path(), 'get', "-N", "Backbone", "--user", "--wait", "--dir", target_dir, skynet_id]
if timeout is not None:
cmd_args += ["--timeout", str(timeout)]
- logging.info('Call skynet with args: %s', cmd_args)
+ logging.info('Call skynet with args: %s', cmd_args)
stdout = subprocess.check_output(cmd_args).strip()
logging.debug('Skynet call with args %s is finished, result is %s', cmd_args, stdout)
return stdout
- if not _is_skynet_avaliable():
+ if not _is_skynet_avaliable():
raise UnsupportedProtocolException("Skynet is not available")
skynet_id = resource_info.get("skynet_id")
@@ -94,7 +94,7 @@ def _urlopen(url, data=None, headers=None):
logging.warning('failed to fetch URL %s with HTTP code %d: %s', url, e.code, e)
retry_after = int(e.headers.get('Retry-After', str(retry_after)))
- if e.code not in TEMPORARY_ERROR_CODES:
+ if e.code not in TEMPORARY_ERROR_CODES:
raise
except Exception as e:
@@ -141,9 +141,9 @@ def fetch(resource_id, custom_fetcher):
)
raise
- if resource_info.get('state', 'DELETED') != 'READY':
- raise ResourceInfoError("Resource {} is not READY".format(resource_id))
-
+ if resource_info.get('state', 'DELETED') != 'READY':
+ raise ResourceInfoError("Resource {} is not READY".format(resource_id))
+
logging.info('Resource %s info %s', str(resource_id), json.dumps(resource_info))
resource_file_name = os.path.basename(resource_info["file_name"])
@@ -159,15 +159,15 @@ def fetch(resource_id, custom_fetcher):
random.shuffle(storage_links)
return storage_links
- skynet = _is_skynet_avaliable()
-
- if not skynet:
- logging.info("Skynet is not available, will try other protocols")
-
+ skynet = _is_skynet_avaliable()
+
+ if not skynet:
+ logging.info("Skynet is not available, will try other protocols")
+
def iter_tries():
- if skynet:
- yield lambda: download_by_skynet(resource_info, resource_file_name)
-
+ if skynet:
+ yield lambda: download_by_skynet(resource_info, resource_file_name)
+
if custom_fetcher:
yield lambda: fetch_via_script(custom_fetcher, resource_id)
@@ -191,78 +191,78 @@ def fetch(resource_id, custom_fetcher):
try:
fetched_file = action()
break
- except UnsupportedProtocolException:
- pass
- except subprocess.CalledProcessError as e:
+ except UnsupportedProtocolException:
+ pass
+ except subprocess.CalledProcessError as e:
logging.warning('failed to fetch resource %s with subprocess: %s', resource_id, e)
- time.sleep(i)
- except urllib2.HTTPError as e:
+ time.sleep(i)
+ except urllib2.HTTPError as e:
logging.warning('failed to fetch resource %s with HTTP code %d: %s', resource_id, e.code, e)
- if e.code not in TEMPORARY_ERROR_CODES:
- exc_info = exc_info or sys.exc_info()
- time.sleep(i)
+ if e.code not in TEMPORARY_ERROR_CODES:
+ exc_info = exc_info or sys.exc_info()
+ time.sleep(i)
except Exception as e:
logging.exception(e)
exc_info = exc_info or sys.exc_info()
time.sleep(i)
else:
- if exc_info:
- raise exc_info[0], exc_info[1], exc_info[2]
- else:
- raise Exception("No available protocol and/or server to fetch resource")
+ if exc_info:
+ raise exc_info[0], exc_info[1], exc_info[2]
+ else:
+ raise Exception("No available protocol and/or server to fetch resource")
return fetched_file, resource_info['file_name']
-def _get_resource_info_from_file(resource_file):
- if resource_file is None or not os.path.exists(resource_file):
- return None
-
- RESOURCE_INFO_JSON = "resource_info.json"
- RESOURCE_CONTENT_FILE_NAME = "resource"
-
- resource_dir, resource_file = os.path.split(resource_file)
- if resource_file != RESOURCE_CONTENT_FILE_NAME:
- return None
-
- resource_json = os.path.join(resource_dir, RESOURCE_INFO_JSON)
- if not os.path.isfile(resource_json):
- return None
-
- try:
- with open(resource_json, 'r') as j:
- resource_info = json.load(j)
- resource_info['file_name'] # check consistency
- return resource_info
- except:
- logging.debug('Invalid %s in %s', RESOURCE_INFO_JSON, resource_dir)
-
- return None
-
-
+def _get_resource_info_from_file(resource_file):
+ if resource_file is None or not os.path.exists(resource_file):
+ return None
+
+ RESOURCE_INFO_JSON = "resource_info.json"
+ RESOURCE_CONTENT_FILE_NAME = "resource"
+
+ resource_dir, resource_file = os.path.split(resource_file)
+ if resource_file != RESOURCE_CONTENT_FILE_NAME:
+ return None
+
+ resource_json = os.path.join(resource_dir, RESOURCE_INFO_JSON)
+ if not os.path.isfile(resource_json):
+ return None
+
+ try:
+ with open(resource_json, 'r') as j:
+ resource_info = json.load(j)
+ resource_info['file_name'] # check consistency
+ return resource_info
+ except:
+ logging.debug('Invalid %s in %s', RESOURCE_INFO_JSON, resource_dir)
+
+ return None
+
+
def main(args):
custom_fetcher = os.environ.get('YA_CUSTOM_FETCHER')
- resource_info = _get_resource_info_from_file(args.resource_file)
- if resource_info:
- fetched_file = args.resource_file
- file_name = resource_info['file_name']
- else:
- # This code should be merged to ya and removed.
- fetched_file, file_name = fetch(args.resource_id, custom_fetcher)
+ resource_info = _get_resource_info_from_file(args.resource_file)
+ if resource_info:
+ fetched_file = args.resource_file
+ file_name = resource_info['file_name']
+ else:
+ # This code should be merged to ya and removed.
+ fetched_file, file_name = fetch(args.resource_id, custom_fetcher)
- fetch_from.process(fetched_file, file_name, args, remove=not custom_fetcher and not resource_info)
+ fetch_from.process(fetched_file, file_name, args, remove=not custom_fetcher and not resource_info)
if __name__ == '__main__':
args = parse_args()
- fetch_from.setup_logging(args, os.path.basename(__file__))
+ fetch_from.setup_logging(args, os.path.basename(__file__))
try:
main(args)
except Exception as e:
logging.exception(e)
- print >>sys.stderr, open(args.abs_log_path).read()
+ print >>sys.stderr, open(args.abs_log_path).read()
sys.stderr.flush()
import error
diff --git a/build/scripts/go_tool.py b/build/scripts/go_tool.py
index c1e98b20c0..a25a871a94 100644
--- a/build/scripts/go_tool.py
+++ b/build/scripts/go_tool.py
@@ -474,12 +474,12 @@ def do_link_exe(args):
compile_args.output = os.path.join(args.output_root, 'main.a')
compile_args.real_import_path = compile_args.import_path
compile_args.import_path = 'main'
-
- if args.vcs and os.path.isfile(compile_args.vcs):
- build_info = os.path.join('library', 'go', 'core', 'buildinfo')
+
+ if args.vcs and os.path.isfile(compile_args.vcs):
+ build_info = os.path.join('library', 'go', 'core', 'buildinfo')
if any([x.startswith(build_info) for x in compile_args.peers]):
- compile_args.go_srcs.append(compile_args.vcs)
-
+ compile_args.go_srcs.append(compile_args.vcs)
+
do_link_lib(compile_args)
cmd = [args.go_link, '-o', args.output]
import_config_name = create_import_config(args.peers + args.non_local_peers, False, args.import_map, args.module_map)
@@ -814,7 +814,7 @@ if __name__ == '__main__':
parser.add_argument('++asm-flags', nargs='*')
parser.add_argument('++compile-flags', nargs='*')
parser.add_argument('++link-flags', nargs='*')
- parser.add_argument('++vcs', nargs='?', default=None)
+ parser.add_argument('++vcs', nargs='?', default=None)
parser.add_argument('++vet', nargs='?', const=True, default=False)
parser.add_argument('++vet-flags', nargs='*', default=None)
parser.add_argument('++vet-info-ext', default=vet_info_ext)
diff --git a/build/scripts/link_exe.py b/build/scripts/link_exe.py
index f469e3b442..d89528b6fa 100644
--- a/build/scripts/link_exe.py
+++ b/build/scripts/link_exe.py
@@ -1,6 +1,6 @@
import sys
import subprocess
-import optparse
+import optparse
from process_whole_archive_option import ProcessWholeArchiveOption
@@ -15,19 +15,19 @@ def get_leaks_suppressions(cmd):
return supp, newcmd
-musl_libs = '-lc', '-lcrypt', '-ldl', '-lm', '-lpthread', '-lrt', '-lutil'
-
-
-def fix_cmd(musl, c):
+musl_libs = '-lc', '-lcrypt', '-ldl', '-lm', '-lpthread', '-lrt', '-lutil'
+
+
+def fix_cmd(musl, c):
return [i for i in c if (not musl or i not in musl_libs) and not i.endswith('.ios.interface') and not i.endswith('.pkg.fake')]
-
-
+
+
def gen_default_suppressions(inputs, output, source_root):
import collections
import os
supp_map = collections.defaultdict(set)
- for filename in inputs:
+ for filename in inputs:
sanitizer = os.path.basename(filename).split('.', 1)[0]
with open(os.path.join(source_root, filename)) as src:
for line in src:
@@ -36,17 +36,17 @@ def gen_default_suppressions(inputs, output, source_root):
continue
supp_map[sanitizer].add(line)
- with open(output, "wb") as dst:
+ with open(output, "wb") as dst:
for supp_type, supps in supp_map.items():
dst.write('extern "C" const char *__%s_default_suppressions() {\n' % supp_type)
dst.write(' return "{}";\n'.format('\\n'.join(sorted(supps))))
dst.write('}\n')
-def parse_args():
- parser = optparse.OptionParser()
- parser.disable_interspersed_args()
- parser.add_option('--musl', action='store_true')
+def parse_args():
+ parser = optparse.OptionParser()
+ parser.disable_interspersed_args()
+ parser.add_option('--musl', action='store_true')
parser.add_option('--custom-step')
parser.add_option('--python')
parser.add_option('--source-root')
@@ -54,13 +54,13 @@ def parse_args():
parser.add_option('--linker-output')
parser.add_option('--whole-archive-peers', action='append')
parser.add_option('--whole-archive-libs', action='append')
- return parser.parse_args()
-
-
+ return parser.parse_args()
+
+
if __name__ == '__main__':
- opts, args = parse_args()
+ opts, args = parse_args()
- cmd = fix_cmd(opts.musl, args)
+ cmd = fix_cmd(opts.musl, args)
cmd = ProcessWholeArchiveOption(opts.arch, opts.whole_archive_peers, opts.whole_archive_libs).construct_cmd(cmd)
if opts.custom_step:
diff --git a/build/scripts/run_msvc_wine.py b/build/scripts/run_msvc_wine.py
index 439d1f8831..ed2660f3b8 100644
--- a/build/scripts/run_msvc_wine.py
+++ b/build/scripts/run_msvc_wine.py
@@ -407,7 +407,7 @@ def process_free_args(args, wine, bld_root, mode):
else:
result.append(process_arg(arg))
return pwa.ProcessWholeArchiveOption('WINDOWS', wa_peers, wa_libs).construct_cmd(result)
-
+
def run_main():
parser = argparse.ArgumentParser()
parser.add_argument('wine', action='store')
@@ -507,8 +507,8 @@ def run_main():
# non-zero return code - bad, return it immediately
if rc:
- print >>sys.stderr, '##win_cmd##' + ' '.join(cmd)
- print >>sys.stderr, '##args##' + ' '.join(free_args)
+ print >>sys.stderr, '##win_cmd##' + ' '.join(cmd)
+ print >>sys.stderr, '##args##' + ' '.join(free_args)
return rc
# check for output existence(if we expect it!) and real length
diff --git a/build/scripts/vcs_info.py b/build/scripts/vcs_info.py
index 319d1b4631..fa7376e739 100644
--- a/build/scripts/vcs_info.py
+++ b/build/scripts/vcs_info.py
@@ -1,16 +1,16 @@
-import base64
-import json
-import os
-import re
-import sys
-import shutil
-import tempfile
-import textwrap
-import zipfile
-
-
-class _Formatting(object):
- @staticmethod
+import base64
+import json
+import os
+import re
+import sys
+import shutil
+import tempfile
+import textwrap
+import zipfile
+
+
+class _Formatting(object):
+ @staticmethod
def is_str(strval):
if sys.version_info >= (3, 0, 0):
return isinstance(strval, (bytes,str))
@@ -25,266 +25,266 @@ class _Formatting(object):
return isinstance(strval, unicode)
@staticmethod
- def escape_special_symbols(strval):
+ def escape_special_symbols(strval):
encoding_needed = _Formatting.encoding_needed(strval)
c_str = strval.encode('utf-8') if encoding_needed else strval
retval = b""
- for c in c_str:
+ for c in c_str:
if sys.version_info >= (3, 0, 0):
c = bytes([c])
- if c in ("\\", "\""):
- retval += "\\" + c
- elif ord(c) < ord(' '):
+ if c in ("\\", "\""):
+ retval += "\\" + c
+ elif ord(c) < ord(' '):
retval += c.decode('latin-1').encode('unicode_escape')
- else:
- retval += c
+ else:
+ retval += c
return retval.decode('utf-8') if encoding_needed else retval
-
- @staticmethod
- def escape_line_feed(strval, indent=' '):
- return strval.replace(r'\n', '\\n"\\\n' + indent + '"')
-
- @staticmethod
+
+ @staticmethod
+ def escape_line_feed(strval, indent=' '):
+ return strval.replace(r'\n', '\\n"\\\n' + indent + '"')
+
+ @staticmethod
def escape_trigraphs(strval):
return strval.replace(r'?', '\\?')
@staticmethod
- def escaped_define(strkey, val):
- name = "#define " + strkey + " "
+ def escaped_define(strkey, val):
+ name = "#define " + strkey + " "
if _Formatting.is_str(val):
- define = "\"" + _Formatting.escape_line_feed(
+ define = "\"" + _Formatting.escape_line_feed(
_Formatting.escape_trigraphs(_Formatting.escape_special_symbols(val))) + "\""
- else:
- define = str(val)
- return name + define
-
- @staticmethod
- def escaped_go_map_key(strkey, strval):
+ else:
+ define = str(val)
+ return name + define
+
+ @staticmethod
+ def escaped_go_map_key(strkey, strval):
if _Formatting.is_str(strval):
- return ' ' + '"' + strkey + '": "' + _Formatting.escape_special_symbols(strval) + '",'
- else:
- return ' ' + '"' + strkey + '": "' + str(strval) + '",'
-
-
-def get_default_json():
- return json.loads('''{
+ return ' ' + '"' + strkey + '": "' + _Formatting.escape_special_symbols(strval) + '",'
+ else:
+ return ' ' + '"' + strkey + '": "' + str(strval) + '",'
+
+
+def get_default_json():
+ return json.loads('''{
"ARCADIA_SOURCE_HG_HASH": "0000000000000000000000000000000000000000",
"ARCADIA_SOURCE_LAST_AUTHOR": "<UNKNOWN>",
- "ARCADIA_SOURCE_LAST_CHANGE": -1,
- "ARCADIA_SOURCE_PATH": "/",
- "ARCADIA_SOURCE_REVISION": -1,
- "ARCADIA_SOURCE_URL": "",
- "BRANCH": "unknown-vcs-branch",
- "BUILD_DATE": "",
+ "ARCADIA_SOURCE_LAST_CHANGE": -1,
+ "ARCADIA_SOURCE_PATH": "/",
+ "ARCADIA_SOURCE_REVISION": -1,
+ "ARCADIA_SOURCE_URL": "",
+ "BRANCH": "unknown-vcs-branch",
+ "BUILD_DATE": "",
"BUILD_TIMESTAMP": 0,
- "BUILD_HOST": "localhost",
- "BUILD_USER": "nobody",
+ "BUILD_HOST": "localhost",
+ "BUILD_USER": "nobody",
"PROGRAM_VERSION": "Arc info:\\n Branch: unknown-vcs-branch\\n Commit: 0000000000000000000000000000000000000000\\n Author: <UNKNOWN>\\n Summary: No VCS\\n\\n",
"SCM_DATA": "Arc info:\\n Branch: unknown-vcs-branch\\n Commit: 0000000000000000000000000000000000000000\\n Author: <UNKNOWN>\\n Summary: No VCS\\n",
- "VCS": "arc",
- "ARCADIA_PATCH_NUMBER": 0,
- "ARCADIA_TAG": ""
-}''')
-
-
-def get_json(file_name):
- try:
- with open(file_name, 'r') as f:
- out = json.load(f)
-
- # TODO: check 'tar+svn' parsing
- for i in ['ARCADIA_SOURCE_REVISION', 'ARCADIA_SOURCE_LAST_CHANGE', 'SVN_REVISION']:
+ "VCS": "arc",
+ "ARCADIA_PATCH_NUMBER": 0,
+ "ARCADIA_TAG": ""
+}''')
+
+
+def get_json(file_name):
+ try:
+ with open(file_name, 'r') as f:
+ out = json.load(f)
+
+ # TODO: check 'tar+svn' parsing
+ for i in ['ARCADIA_SOURCE_REVISION', 'ARCADIA_SOURCE_LAST_CHANGE', 'SVN_REVISION']:
if i in out and _Formatting.is_str(out[i]):
- try:
- out[i] = int(out[i])
- except:
- out[i] = -1
- return out
- except:
- return get_default_json()
-
-
-def print_c(json_file, output_file, argv):
- """ params:
- json file
- output file
- $(SOURCE_ROOT)/build/scripts/c_templates/svn_interface.c"""
- def gen_header(info):
- lines = []
- for k, v in info.items():
- lines.append(_Formatting.escaped_define(k, v))
- return lines
-
- interface = argv[0]
-
- with open(interface) as c:
- c_file = c.read()
- with open(output_file, 'w') as f:
+ try:
+ out[i] = int(out[i])
+ except:
+ out[i] = -1
+ return out
+ except:
+ return get_default_json()
+
+
+def print_c(json_file, output_file, argv):
+ """ params:
+ json file
+ output file
+ $(SOURCE_ROOT)/build/scripts/c_templates/svn_interface.c"""
+ def gen_header(info):
+ lines = []
+ for k, v in info.items():
+ lines.append(_Formatting.escaped_define(k, v))
+ return lines
+
+ interface = argv[0]
+
+ with open(interface) as c:
+ c_file = c.read()
+ with open(output_file, 'w') as f:
header = '\n'.join(gen_header(json_file))
if sys.version_info < (3, 0, 0):
header = header.encode('utf-8')
f.write(header + '\n' + c_file)
-
-
-def merge_java_content(old_content, json_file):
- new_content, names = print_java_mf(json_file)
-
- def split_to_sections(content):
- sections = []
- cur_section = []
- for l in content:
- if l.rstrip():
- cur_section.append(l)
- else:
- sections.append(cur_section)
- cur_section = []
-
- if cur_section: # should not be needed according to format specification
- sections.append(cur_section)
-
- return sections
-
- def drop_duplicate_entries(main_section, names):
- header = re.compile('^([A-Za-z0-9][A-Za-z0-9_-]*): .*$')
- new_main_section = []
- for l in main_section:
- match = header.match(l)
- # duplicate entry
- if match:
- skip = match.group(1) in names
-
- if not skip:
- new_main_section.append(l)
- return new_main_section
-
- if old_content:
- sections = split_to_sections(old_content)
- sections[0] = drop_duplicate_entries(sections[0], names)
- else:
- sections = [['Manifest-Version: 1.0\n']]
-
- sections[0].extend(map(lambda x: x + '\n', new_content))
-
- return ''.join(map(lambda x: ''.join(x), sections)) + '\n'
-
-
-def merge_java_mf_jar(json_file, out_manifest, jar_file):
- try:
- temp_dir = tempfile.mkdtemp()
- try:
- with zipfile.ZipFile(jar_file, 'r') as jar:
- jar.extract(os.path.join('META-INF', 'MANIFEST.MF'), path=temp_dir)
- except KeyError:
- pass
-
- merge_java_mf_dir(json_file, out_manifest, temp_dir)
- finally:
- shutil.rmtree(temp_dir)
-
-
-def merge_java_mf_dir(json_file, out_manifest, input_dir):
- manifest = os.path.join(input_dir, 'META-INF', 'MANIFEST.MF')
-
- old_lines = []
- if os.path.isfile(manifest):
- with open(manifest, 'r') as f:
- old_lines = f.readlines()
-
- with open(out_manifest, 'w') as f:
- f.write(merge_java_content(old_lines, json_file))
-
-
-def merge_java_mf(json_file, out_manifest, input):
- if zipfile.is_zipfile(input):
- merge_java_mf_jar(json_file, out_manifest, input)
- elif os.path.isdir(input):
- merge_java_mf_dir(json_file, out_manifest, input)
-
-
-def print_java_mf(info):
- wrapper = textwrap.TextWrapper(subsequent_indent=' ',
- break_long_words=True,
- replace_whitespace=False,
- drop_whitespace=False)
- names = set()
-
- def wrap(key, val):
- names.add(key[:-2])
- if not val:
- return []
- return wrapper.wrap(key + val)
-
- lines = wrap('Program-Version-String: ', base64.b64encode(info['PROGRAM_VERSION'].encode('utf-8')))
- lines += wrap('SCM-String: ', base64.b64encode(info['SCM_DATA'].encode('utf-8')))
- lines += wrap('Arcadia-Source-Path: ', info['ARCADIA_SOURCE_PATH'])
- lines += wrap('Arcadia-Source-URL: ', info['ARCADIA_SOURCE_URL'])
- lines += wrap('Arcadia-Source-Revision: ', str(info['ARCADIA_SOURCE_REVISION']))
- lines += wrap('Arcadia-Source-Hash: ', info['ARCADIA_SOURCE_HG_HASH'].rstrip())
- lines += wrap('Arcadia-Source-Last-Change: ', str(info['ARCADIA_SOURCE_LAST_CHANGE']))
- lines += wrap('Arcadia-Source-Last-Author: ', info['ARCADIA_SOURCE_LAST_AUTHOR'])
- lines += wrap('Build-User: ', info['BUILD_USER'])
- lines += wrap('Build-Host: ', info['BUILD_HOST'])
- lines += wrap('Version-Control-System: ', info['VCS'])
- lines += wrap('Branch: ', info['BRANCH'])
- lines += wrap('Arcadia-Tag: ', info.get('ARCADIA_TAG', ''))
- lines += wrap('Arcadia-Patch-Number: ', str(info.get('ARCADIA_PATCH_NUMBER', 42)))
- if 'SVN_REVISION' in info:
- lines += wrap('SVN-Revision: ', str(info['SVN_REVISION']))
- lines += wrap('SVN-Arcroot: ', info['SVN_ARCROOT'])
- lines += wrap('SVN-Time: ', info['SVN_TIME'])
- lines += wrap('Build-Date: ', info['BUILD_DATE'])
+
+
+def merge_java_content(old_content, json_file):
+ new_content, names = print_java_mf(json_file)
+
+ def split_to_sections(content):
+ sections = []
+ cur_section = []
+ for l in content:
+ if l.rstrip():
+ cur_section.append(l)
+ else:
+ sections.append(cur_section)
+ cur_section = []
+
+ if cur_section: # should not be needed according to format specification
+ sections.append(cur_section)
+
+ return sections
+
+ def drop_duplicate_entries(main_section, names):
+ header = re.compile('^([A-Za-z0-9][A-Za-z0-9_-]*): .*$')
+ new_main_section = []
+ for l in main_section:
+ match = header.match(l)
+ # duplicate entry
+ if match:
+ skip = match.group(1) in names
+
+ if not skip:
+ new_main_section.append(l)
+ return new_main_section
+
+ if old_content:
+ sections = split_to_sections(old_content)
+ sections[0] = drop_duplicate_entries(sections[0], names)
+ else:
+ sections = [['Manifest-Version: 1.0\n']]
+
+ sections[0].extend(map(lambda x: x + '\n', new_content))
+
+ return ''.join(map(lambda x: ''.join(x), sections)) + '\n'
+
+
+def merge_java_mf_jar(json_file, out_manifest, jar_file):
+ try:
+ temp_dir = tempfile.mkdtemp()
+ try:
+ with zipfile.ZipFile(jar_file, 'r') as jar:
+ jar.extract(os.path.join('META-INF', 'MANIFEST.MF'), path=temp_dir)
+ except KeyError:
+ pass
+
+ merge_java_mf_dir(json_file, out_manifest, temp_dir)
+ finally:
+ shutil.rmtree(temp_dir)
+
+
+def merge_java_mf_dir(json_file, out_manifest, input_dir):
+ manifest = os.path.join(input_dir, 'META-INF', 'MANIFEST.MF')
+
+ old_lines = []
+ if os.path.isfile(manifest):
+ with open(manifest, 'r') as f:
+ old_lines = f.readlines()
+
+ with open(out_manifest, 'w') as f:
+ f.write(merge_java_content(old_lines, json_file))
+
+
+def merge_java_mf(json_file, out_manifest, input):
+ if zipfile.is_zipfile(input):
+ merge_java_mf_jar(json_file, out_manifest, input)
+ elif os.path.isdir(input):
+ merge_java_mf_dir(json_file, out_manifest, input)
+
+
+def print_java_mf(info):
+ wrapper = textwrap.TextWrapper(subsequent_indent=' ',
+ break_long_words=True,
+ replace_whitespace=False,
+ drop_whitespace=False)
+ names = set()
+
+ def wrap(key, val):
+ names.add(key[:-2])
+ if not val:
+ return []
+ return wrapper.wrap(key + val)
+
+ lines = wrap('Program-Version-String: ', base64.b64encode(info['PROGRAM_VERSION'].encode('utf-8')))
+ lines += wrap('SCM-String: ', base64.b64encode(info['SCM_DATA'].encode('utf-8')))
+ lines += wrap('Arcadia-Source-Path: ', info['ARCADIA_SOURCE_PATH'])
+ lines += wrap('Arcadia-Source-URL: ', info['ARCADIA_SOURCE_URL'])
+ lines += wrap('Arcadia-Source-Revision: ', str(info['ARCADIA_SOURCE_REVISION']))
+ lines += wrap('Arcadia-Source-Hash: ', info['ARCADIA_SOURCE_HG_HASH'].rstrip())
+ lines += wrap('Arcadia-Source-Last-Change: ', str(info['ARCADIA_SOURCE_LAST_CHANGE']))
+ lines += wrap('Arcadia-Source-Last-Author: ', info['ARCADIA_SOURCE_LAST_AUTHOR'])
+ lines += wrap('Build-User: ', info['BUILD_USER'])
+ lines += wrap('Build-Host: ', info['BUILD_HOST'])
+ lines += wrap('Version-Control-System: ', info['VCS'])
+ lines += wrap('Branch: ', info['BRANCH'])
+ lines += wrap('Arcadia-Tag: ', info.get('ARCADIA_TAG', ''))
+ lines += wrap('Arcadia-Patch-Number: ', str(info.get('ARCADIA_PATCH_NUMBER', 42)))
+ if 'SVN_REVISION' in info:
+ lines += wrap('SVN-Revision: ', str(info['SVN_REVISION']))
+ lines += wrap('SVN-Arcroot: ', info['SVN_ARCROOT'])
+ lines += wrap('SVN-Time: ', info['SVN_TIME'])
+ lines += wrap('Build-Date: ', info['BUILD_DATE'])
if 'BUILD_TIMESTAMP' in info:
lines += wrap('Build-Timestamp: ', str(info['BUILD_TIMESTAMP']))
- return lines, names
-
-
-def print_java(json_file, output_file, argv):
- """ params:
- json file
- output file
- file"""
- input = argv[0] if argv else os.curdir
- merge_java_mf(json_file, output_file, input)
-
-
-def print_go(json_file, output_file):
- def gen_map(info):
- lines = []
- for k, v in info.items():
- lines.append(_Formatting.escaped_go_map_key(k, v))
- return lines
-
- with open(output_file, 'w') as f:
- f.write('\n'.join([
- 'package main',
- 'import ("a.yandex-team.ru/library/go/core/buildinfo")',
- 'var buildinfomap = map[string]string {'] + gen_map(json_file) + ['}'] +
- ['func init() {',
- ' buildinfo.InitBuildInfo(buildinfomap)',
- '}']
- ).encode('utf-8') + '\n')
-
-
-if __name__ == '__main__':
- if 'output-go' in sys.argv:
- lang = 'Go'
- sys.argv.remove('output-go')
- elif 'output-java' in sys.argv:
- lang = 'Java'
- sys.argv.remove('output-java')
- else:
- lang = 'C'
-
- if 'no-vcs' in sys.argv:
- sys.argv.remove('no-vcs')
- json_file = get_default_json()
- else:
- json_name = sys.argv[1]
- json_file = get_json(json_name)
-
- if lang == 'Go':
- print_go(json_file, sys.argv[2])
- elif lang == 'Java':
- print_java(json_file, sys.argv[2], sys.argv[3:])
- else:
- print_c(json_file, sys.argv[2], sys.argv[3:])
+ return lines, names
+
+
+def print_java(json_file, output_file, argv):
+ """ params:
+ json file
+ output file
+ file"""
+ input = argv[0] if argv else os.curdir
+ merge_java_mf(json_file, output_file, input)
+
+
+def print_go(json_file, output_file):
+ def gen_map(info):
+ lines = []
+ for k, v in info.items():
+ lines.append(_Formatting.escaped_go_map_key(k, v))
+ return lines
+
+ with open(output_file, 'w') as f:
+ f.write('\n'.join([
+ 'package main',
+ 'import ("a.yandex-team.ru/library/go/core/buildinfo")',
+ 'var buildinfomap = map[string]string {'] + gen_map(json_file) + ['}'] +
+ ['func init() {',
+ ' buildinfo.InitBuildInfo(buildinfomap)',
+ '}']
+ ).encode('utf-8') + '\n')
+
+
+if __name__ == '__main__':
+ if 'output-go' in sys.argv:
+ lang = 'Go'
+ sys.argv.remove('output-go')
+ elif 'output-java' in sys.argv:
+ lang = 'Java'
+ sys.argv.remove('output-java')
+ else:
+ lang = 'C'
+
+ if 'no-vcs' in sys.argv:
+ sys.argv.remove('no-vcs')
+ json_file = get_default_json()
+ else:
+ json_name = sys.argv[1]
+ json_file = get_json(json_name)
+
+ if lang == 'Go':
+ print_go(json_file, sys.argv[2])
+ elif lang == 'Java':
+ print_java(json_file, sys.argv[2], sys.argv[3:])
+ else:
+ print_c(json_file, sys.argv[2], sys.argv[3:])
diff --git a/build/scripts/ya.make b/build/scripts/ya.make
index 710165e40d..a4830bec08 100644
--- a/build/scripts/ya.make
+++ b/build/scripts/ya.make
@@ -54,7 +54,7 @@ TEST_SRCS(
java_pack_to_file.py
link_asrc.py
link_dyn_lib.py
- link_exe.py
+ link_exe.py
link_fat_obj.py
link_lib.py
llvm_opt_wrapper.py
@@ -83,7 +83,7 @@ TEST_SRCS(
tared_protoc.py
touch.py
unpacking_jtest_runner.py
- vcs_info.py
+ vcs_info.py
with_coverage.py
with_crash_on_timeout.py
with_pathsep_resolve.py
diff --git a/build/ya.conf.json b/build/ya.conf.json
index 5f7cc875d6..69c2d86ff0 100644
--- a/build/ya.conf.json
+++ b/build/ya.conf.json
@@ -4646,14 +4646,14 @@
}
]
},
- "ya-tc": {
- "tools": {
+ "ya-tc": {
+ "tools": {
"ya-tc": {
"bottle": "ya-tc",
"executable": "ya-tc"
}
- },
- "platforms": [
+ },
+ "platforms": [
{
"host": {
"os": "LINUX"
@@ -4666,8 +4666,8 @@
},
"default": true
}
- ]
- },
+ ]
+ },
"crypta": {
"tools": {
"crypta": {
@@ -7304,17 +7304,17 @@
]
}
},
- "ya-tc": {
- "formula": {
+ "ya-tc": {
+ "formula": {
"sandbox_id": 981372621,
- "match": "ya-tc"
- },
- "executable": {
+ "match": "ya-tc"
+ },
+ "executable": {
"ya-tc": [
"ya-tc"
]
- }
- },
+ }
+ },
"crypta": {
"formula": {
"sandbox_id": 550700694,
diff --git a/build/ya.make b/build/ya.make
index 407b8f13e0..e9a5f2bb4d 100644
--- a/build/ya.make
+++ b/build/ya.make
@@ -22,7 +22,7 @@ END()
RECURSE(
conf_fatal_error
config
- docs/empty
+ docs/empty
external_resources
platform/java
platform/local_so
diff --git a/build/ymake.core.conf b/build/ymake.core.conf
index 081833998b..c0a48d946b 100644
--- a/build/ymake.core.conf
+++ b/build/ymake.core.conf
@@ -437,7 +437,7 @@ when ($SANITIZER_TYPE) {
# tag:internal
### @usage: CHECK_CONFIG_H(<conf_header>) # internal
###
-### This internal macro adds checking code for configuration header in external (contrib) library.
+### This internal macro adds checking code for configuration header in external (contrib) library.
### The check is needed to avoid conflicts on certain types and functions available in arcadia.
###
### @see https://a.yandex-team.ru/arc/trunk/arcadia/build/scripts/check_config_h.py for exact details
@@ -928,8 +928,8 @@ when ($JAVA_PROTO_RUNTIME == "javalite") {
otherwise {
_JAVA_PROTO_OUT_ARG=--java_out=
JAVA_PROTOBUF_PEERS=contrib/java/com/google/protobuf/protobuf-java/${JAVA_PROTO_RUNTIME_VERSION}
- JAVA_GRPC_STUB=contrib/java/io/grpc/grpc-stub/1.26.0
- JAVA_GRPC_PROTOBUF=contrib/java/io/grpc/grpc-protobuf/1.26.0
+ JAVA_GRPC_STUB=contrib/java/io/grpc/grpc-stub/1.26.0
+ JAVA_GRPC_PROTOBUF=contrib/java/io/grpc/grpc-protobuf/1.26.0
}
# tag:proto tag:java-specific
@@ -952,7 +952,7 @@ macro XS_PROTO(File, Dir, Outputs...) {
# tag:proto tag:fbs
### @usage: PROTO2FBS(InputProto)
###
-### Produce flatbuf schema out of protobuf description.
+### Produce flatbuf schema out of protobuf description.
macro PROTO2FBS(File) {
.CMD=${cwd:BINDIR} ${tool:"contrib/tools/flatc"} -I . -I ${ARCADIA_ROOT} --proto ${input:File} ${output;hide;nopath;noext:File.fbs} ${kv;hide:"p FBS"} ${kv;hide:"pc yellow"}
}
@@ -1290,8 +1290,8 @@ module _BASE_UNIT: _BARE_UNIT {
when ($MUSL == "yes") {
CFLAGS += -D_musl_
- LINK_DYN_LIB_FLAGS += --musl
- LINK_SCRIPT_EXE_FLAGS += --musl
+ LINK_DYN_LIB_FLAGS += --musl
+ LINK_SCRIPT_EXE_FLAGS += --musl
PEERDIR+=contrib/libs/musl/include
}
@@ -1656,10 +1656,10 @@ module _BASE_PROGRAM: _LINK_UNIT {
when ($CLANG_COVERAGE && $CLANG_COVERAGE != "no") {
PEERDIR+=library/cpp/testing/dump_clang_coverage
}
-
- when ($IDE_MSVS == "yes") {
- PEERDIR+=build/scripts/c_templates
- }
+
+ when ($IDE_MSVS == "yes") {
+ PEERDIR+=build/scripts/c_templates
+ }
when ($_CUSTOM_LINK_STEP_SCRIPT) {
LINK_SCRIPT_EXE_FLAGS+=--python=$YMAKE_PYTHON --custom-step=${input:_CUSTOM_LINK_STEP_SCRIPT}
@@ -2037,7 +2037,7 @@ TEST_DATA_VALUE=
### Specifies the path to the data necessary test.
### Valid values are: arcadia/<path> , arcadia_tests_data/<path> and sbr://<resource_id>.
### In the latter case resource will be brought to the working directory of the test before it is started
-###
+###
### Used only inside TEST modules.
###
### Documentation: https://wiki.yandex-team.ru/yatool/test/#dannyeizrepozitorija
@@ -2268,7 +2268,7 @@ module GTEST_UGLY: _BASE_PROGRAM {
###
### @example:
###
-### EXECTEST()
+### EXECTEST()
### OWNER(g:yatool)
###
### RUN(
@@ -2940,9 +2940,9 @@ multimodule DYNAMIC_LIBRARY {
### @example:
### Consider the file to ya.make:
###
-### LIBRARY()
+### LIBRARY()
### GLOBAL_SRCS(foo.cpp bar.cpp)
-### END()
+### END()
###
### @see: [SRCS()](#macro_SRCS)
macro GLOBAL_SRCS(Files...) {
@@ -2957,10 +2957,10 @@ macro GLOBAL_SRCS(Files...) {
###
### @example:
###
-### LIBRARY()
+### LIBRARY()
### SET(MAKE_IT_GLOBAL GLOBAL)
### ALL_SRCS(${MAKE_IT_GLOBAL} foo.cpp bar.cpp)
-### END()
+### END()
###
### @see: [GLOBAL_SRCS()](#macro_GLOBAL_SRCS), [SRCS()](#macro_SRCS)
macro ALL_SRCS(GLOBAL?"GLOBAL":"", Files...) {
@@ -3405,7 +3405,7 @@ macro EMBED_JAVA_VCS_INFO() {
### @usage: EXTERNAL_JAVA_LIBRARY() #internal
###
### EXTERNAL_JAVA_LIBRARY() is a module for creating a .jar file using non-Java code (generators etc.)
-### Unlike regular JAVA_LIBRARY this module doesn't produce .pom file, so it cannot be exported to Maven itself.
+### Unlike regular JAVA_LIBRARY this module doesn't produce .pom file, so it cannot be exported to Maven itself.
### PEERDIR it from JAVA_LIBRARY or JAVA_PROGRAM for export to Maven.
module EXTERNAL_JAVA_LIBRARY: _BASE_UNIT {
.EXTS=.jsrc .java .jar .mf
@@ -4491,13 +4491,13 @@ macro TEST_CWD(Arg) {
MAKE_UBERJAR_VALUE=
### @usage: UBERJAR()
###
-### UBERJAR is a single all-in-one jar-archive that includes all its Java dependencies (reachable PEERDIR).
+### UBERJAR is a single all-in-one jar-archive that includes all its Java dependencies (reachable PEERDIR).
### It also supports shading classes inside the archive by moving them to a different package (similar to the maven-shade-plugin).
### Use UBERJAR inside JAVA_PROGRAM module.
###
### You can use the following macros to configure the archive:
### 1. UBERJAR_HIDING_PREFIX prefix for classes to shade (classes remain in their packages by default)
-### 2. UBERJAR_HIDE_EXCLUDE_PATTERN exclude classes matching this patterns from shading (if enabled).
+### 2. UBERJAR_HIDE_EXCLUDE_PATTERN exclude classes matching this patterns from shading (if enabled).
### 3. UBERJAR_PATH_EXCLUDE_PREFIX the prefix for classes that should not get into the jar archive (all classes are placed into the archive by default)
### 4. UBERJAR_MANIFEST_TRANSFORMER_MAIN add ManifestResourceTransformer class to uberjar processing and specify main-class
### 5. UBERJAR_MANIFEST_TRANSFORMER_ATTRIBUTE add ManifestResourceTransformer class to uberjar processing and specify some attribute
@@ -4708,15 +4708,15 @@ JAVA_SRCS_VALUE=
### Keywords:
### 1. X SRCDIR - specify the directory x is performed relatively to search the source code for these patterns. If there is no SRCDIR, the source will be searched relative to the module directory.
### 2. PACKAGE_PREFIX x - use if source paths relative to the SRCDIR does not coincide with the full class names. For example, if all sources of module are in the same package, you can create a directory package/name , and just put the source code in the SRCDIR and specify PACKAGE_PREFIX package.name.
-###
+###
### @example:
-### - example/ya.make
+### - example/ya.make
###
### JAVA_PROGRAM()
### JAVA_SRCS(SRCDIR src/main/java **/*)
### END()
###
-### - example/src/main/java/ru/yandex/example/HelloWorld.java
+### - example/src/main/java/ru/yandex/example/HelloWorld.java
###
### package ru.yandex.example;
### public class HelloWorld {
@@ -4753,15 +4753,15 @@ TEST_CLASSPATH_MANAGED=
# tag:java-specific
DEPENDENCY_MANAGEMENT_VALUE=
-### @usage: DEPENDENCY_MANAGEMENT(path/to/lib1 path/to/lib2 ...)
-###
+### @usage: DEPENDENCY_MANAGEMENT(path/to/lib1 path/to/lib2 ...)
+###
### Lock version of the library from the contrib/java at some point, so that all unversioned PEERDIRs to this library refer to the specified version.
###
### For example, if the moduse has PEERDIR (contrib/java/junit/junit), and
### 1. specifies DEPENDENCY_MANAGEMENT(contrib/java/junit/junit/4.12),
### the PEERDIR is automatically replaced by contrib/java/junit/junit/4.12;
### 2. doesn't specify DEPENDENCY_MANAGEMENT, PEERDIR automatically replaced
-### with the default from contrib/java/junit/junit/ya.make.
+### with the default from contrib/java/junit/junit/ya.make.
### These defaults are always there and are supported by maven-import, which puts
### there the maximum version available in contrib/java.
###
@@ -4988,7 +4988,7 @@ macro JAR_EXCLUDE(Filters...) {
### The final artifact is provided when SANDBOX_TASK is referred to by DEPENDS and BUNDLE macros.
### As PEERDIR target, it works like regular PY2_LIBRARY with predefined dependencies on Sandbox SDK to allow code reuse among SANDBOX_TASKs.
###
-### Currently Sandbox supports only Python 2.x, so both variants will be compatible only with Python 2.x modules
+### Currently Sandbox supports only Python 2.x, so both variants will be compatible only with Python 2.x modules
### and will select multimodule variants accordingly.
###
### Documentation: https://wiki.yandex-team.ru/sandbox/tasks/binary
@@ -5263,19 +5263,19 @@ macro ADD_PERL_MODULE(Dir, Module) {
### - LF_YT - Allocator selection for YT (https://a.yandex-team.ru/arc/trunk/arcadia/library/cpp/lfalloc/yt/ya.make)
### - LF_DBG - Debug allocator selection (https://a.yandex-team.ru/arc/trunk/arcadia/library/cpp/lfalloc/dbg/ya.make)
### - YT - The YTAlloc allocator (https://a.yandex-team.ru/arc/trunk/arcadia/library/cpp/ytalloc/impl/ya.make)
-### - J - The JEMalloc allocator (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/jemalloc)
-### - B - The balloc allocator named Pyotr Popov and Anton Samokhvalov
-### - Discussion: https://ironpeter.at.yandex-team.ru/replies.xml?item_no=126
+### - J - The JEMalloc allocator (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/jemalloc)
+### - B - The balloc allocator named Pyotr Popov and Anton Samokhvalov
+### - Discussion: https://ironpeter.at.yandex-team.ru/replies.xml?item_no=126
### - Code: https://a.yandex-team.ru/arc/trunk/arcadia/library/cpp/balloc
-### - BM - The balloc for market (agri@ commits from july 2018 till November 2018 saved)
-### - C - Like B, but can be disabled for each thread to LF or SYSTEM one (B can be disabled only to SYSTEM)
+### - BM - The balloc for market (agri@ commits from july 2018 till November 2018 saved)
+### - C - Like B, but can be disabled for each thread to LF or SYSTEM one (B can be disabled only to SYSTEM)
### - MIM - Microsoft's mimalloc (actual version) (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/mimalloc)
### - TCMALLOC - Google TCMalloc (actual version) (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/tcmalloc)
-### - GOOGLE - Google TCMalloc (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/galloc)
-### - LOCKLESS - Allocator based upon lockless queues (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/lockless)
-### - SYSTEM - Use target system allocator
-### - FAKE - Don't link with any allocator
-###
+### - GOOGLE - Google TCMalloc (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/galloc)
+### - LOCKLESS - Allocator based upon lockless queues (https://a.yandex-team.ru/arc/trunk/arcadia/library/malloc/lockless)
+### - SYSTEM - Use target system allocator
+### - FAKE - Don't link with any allocator
+###
### More about allocators in Arcadia: https://wiki.yandex-team.ru/arcadia/allocators/
macro ALLOCATOR(Alloc) {
SET(ALLOCATOR $Alloc)
@@ -5584,7 +5584,7 @@ macro JOIN_SRCS(Out, Src...) {
###
### Join set of sources into single file named Out and send it for further processing as if it were listed as SRCS(GLOBAL Out).
### This macro doesn't place all file into Out, it emits #include<Src>... Use the for C++ source files only.
-### You should specify file name with the extension as Out. Further processing will be done according to this extension.
+### You should specify file name with the extension as Out. Further processing will be done according to this extension.
macro JOIN_SRCS_GLOBAL(Out, Src...) {
.CMD=$YMAKE_PYTHON ${input:"build/scripts/gen_join_srcs.py"} ${output;noauto:Out} --ya-start-command-file ${input;rootrel:Src} --ya-end-command-file ${output_include;hide:Src} ${kv;hide:"p JS"} ${kv;hide:"pc magenta"}
SRCS(GLOBAL $Out)
@@ -5594,7 +5594,7 @@ macro JOIN_SRCS_GLOBAL(Out, Src...) {
###
### Join set of sources into single file named Out and send it for further processing as if it were listed as SRCS(GLOBAL Out).
### This macro places all files into single file, so will work with any sources.
-### You should specify file name with the extension as Out. Further processing will be done according to this extension.
+### You should specify file name with the extension as Out. Further processing will be done according to this extension.
macro FLAT_JOIN_SRCS_GLOBAL(Out, Src...) {
.CMD=$YMAKE_PYTHON ${input:"build/scripts/fs_tools.py"} cat ${output;noauto:Out} --ya-start-command-file ${input:Src} --ya-end-command-file ${output_include;hide:Src} ${kv;hide:"p JS"} ${kv;hide:"pc magenta"}
SRCS(GLOBAL $Out)
@@ -5812,7 +5812,7 @@ macro _SRC("asp", SRC, SRCFLAGS...) {
# tag:src-processing
macro _SRC("rl6", SRC, SRCFLAGS...) {
- .CMD=$RUN_NO_SANITIZE ${tool:"contrib/tools/ragel6"} $RAGEL6_FLAGS ${SRCFLAGS} -L -I${ARCADIA_ROOT} -o ${output;nopath;noext;defext=.rl6.cpp:SRC} ${input:SRC} ${kv;hide:"p R6"} ${kv;hide:"pc yellow"}
+ .CMD=$RUN_NO_SANITIZE ${tool:"contrib/tools/ragel6"} $RAGEL6_FLAGS ${SRCFLAGS} -L -I${ARCADIA_ROOT} -o ${output;nopath;noext;defext=.rl6.cpp:SRC} ${input:SRC} ${kv;hide:"p R6"} ${kv;hide:"pc yellow"}
.SEM=target_ragel_lexers PRIVATE ${input:SRC} ${output;hide;suf=.o:SRC} $RAGEL6_FLAGS ${SRCFLAGS} && set_global_flags RAGEL_FLAGS -L -I $S/ && conan_require ragel/6.10 && conan_import '"bin, ragel* -> ./bin"' && modules_required yandex_common.cmake
}
@@ -6153,9 +6153,9 @@ macro SRC(FILE, FLAGS...) {
###
### @example:
###
-### LIBRARY(test_global)
+### LIBRARY(test_global)
### SRCS(GLOBAL foo.cpp)
-### END()
+### END()
###
### This will produce foo.o and feed it to any PROGRAM/DLL module transitively depending on test_global library. The library itself will be empty and won't produce .a file.
macro SRCS(FILES...) {
@@ -6446,20 +6446,20 @@ VCS_C_OBJ_RR=$MODDIR/__vcs_version__.c$OBJECT_SUF
VCS_C=$BINDIR/__vcs_version__.c
VCS_GO=$BINDIR/__vcs_version__.go
VCS_JAVA=$BINDIR/__vcs_version__.mf
-VCS_INFO_DISABLE_CACHE__NO_UID__=
-YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__=
-CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__=
-CL_MACRO_INFO_DISABLE_CACHE__NO_UID__=
+VCS_INFO_DISABLE_CACHE__NO_UID__=
+YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__=
+CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__=
+CL_MACRO_INFO_DISABLE_CACHE__NO_UID__=
YASM_DEBUG_INFO=
CL_DEBUG_INFO=
CL_MACRO_INFO=
-when ($FORCE_VCS_INFO_UPDATE == "yes") {
- VCS_INFO_DISABLE_CACHE__NO_UID__=${hide;kv:"disable_cache"}
-}
-### Works for pyton too.
-GENERATE_VCS_C_INFO_NODEP=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} $(VCS)/vcs.json $VCS_C ${input:"build/scripts/c_templates/svn_interface.c"} $VCS_INFO_DISABLE_CACHE__NO_UID__ && $_SRC_c_nodeps($VCS_C, $VCS_C_OBJ, $(SOURCE_ROOT))
-GENERATE_VCS_GO_INFO_NODEP=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} output-go $(VCS)/vcs.json $VCS_GO $VCS_INFO_DISABLE_CACHE__NO_UID__
-GENERATE_VCS_JAVA_INFO_NODEP=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} output-java $(VCS)/vcs.json $VCS_JAVA $VCS_INFO_DISABLE_CACHE__NO_UID__
+when ($FORCE_VCS_INFO_UPDATE == "yes") {
+ VCS_INFO_DISABLE_CACHE__NO_UID__=${hide;kv:"disable_cache"}
+}
+### Works for pyton too.
+GENERATE_VCS_C_INFO_NODEP=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} $(VCS)/vcs.json $VCS_C ${input:"build/scripts/c_templates/svn_interface.c"} $VCS_INFO_DISABLE_CACHE__NO_UID__ && $_SRC_c_nodeps($VCS_C, $VCS_C_OBJ, $(SOURCE_ROOT))
+GENERATE_VCS_GO_INFO_NODEP=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} output-go $(VCS)/vcs.json $VCS_GO $VCS_INFO_DISABLE_CACHE__NO_UID__
+GENERATE_VCS_JAVA_INFO_NODEP=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} output-java $(VCS)/vcs.json $VCS_JAVA $VCS_INFO_DISABLE_CACHE__NO_UID__
macro UPDATE_VCS_JAVA_INFO_NODEP(Jar) {
.CMD=$YMAKE_PYTHON ${input:"build/scripts/vcs_info.py"} output-java $(VCS)/vcs.json $VCS_JAVA $Jar $VCS_INFO_DISABLE_CACHE__NO_UID__
}
@@ -6494,7 +6494,7 @@ macro CFG_VARS() {
### @usage: CONFIGURE_FILE(from to)
###
### Copy file with the replacement of configuration variables in form of @ANY_CONF_VAR@ with their values.
-### The values are collected during configure stage, while replacement itself happens during build stage.
+### The values are collected during configure stage, while replacement itself happens during build stage.
### Used implicitly for .in-files processing.
macro CONFIGURE_FILE(Src, Dst) {
.CMD=$YMAKE_PYTHON ${input:"build/scripts/configure_file.py"} ${input:Src} ${output;addincl:Dst} $CFG_VARS ${kv;hide:"p CF"} ${kv;hide:"pc yellow"}
@@ -6610,7 +6610,7 @@ macro NO_OPTIMIZE() {
}
### @usage: NO_COMPILER_WARNINGS()
-### Disable all compiler warnings in the module.
+### Disable all compiler warnings in the module.
### Priorities: NO_COMPILER_WARNINGS > NO_WERROR > WERROR_MODE > WERROR.
macro NO_COMPILER_WARNINGS() {
ENABLE(NO_COMPILER_WARNINGS)
@@ -6638,15 +6638,15 @@ macro NO_WSHADOW() {
}
# tag:internal
-### @usage: NO_PLATFORM_RESOURCES() # internal
-### Exclude dependency on platform resources libraries.
+### @usage: NO_PLATFORM_RESOURCES() # internal
+### Exclude dependency on platform resources libraries.
### Most probably you'll never need this. If you think you need, please contact devtools@ for assistance.
macro NO_PLATFORM_RESOURCES() {
ENABLE(NOPLATFORM_RESOURCES)
}
# tag:internal tag:codenav
-### @usage: NO_CODENAVIGATION() # internal
+### @usage: NO_CODENAVIGATION() # internal
### Disable codenaviagtion for a module. Needed to avoid PEERDIR loops in codenavigation support.
### Most probably you'll never need this. If you think you need, please contact devtools@ for assistance.
macro NO_CODENAVIGATION() {
@@ -6714,7 +6714,7 @@ macro USE_UTIL() {
# tag:deprecated
### @usage: NO_JOIN_SRC() # deprecated, does-nothing
-### This macro currently does nothing. This is default behavior which cannot be overridden at module level.
+### This macro currently does nothing. This is default behavior which cannot be overridden at module level.
macro NO_JOIN_SRC() {
ENABLE(UNUSED_MACRO)
}
@@ -6945,18 +6945,18 @@ SCHEEME2_STRUCT_INFO_FLAGS=-f "const static ui32 RecordSig" -u "RecordSig" --gcc
### 2. Use an environment variable - DATAWORK_SCHEEME_EXPORT_FLAGS that allows to specify flags to tools/structparser
###
### @example:
-###
-### SET(DATAWORK_SCHEEME_EXPORT_FLAGS --final_only -m "::")
-###
+###
+### SET(DATAWORK_SCHEEME_EXPORT_FLAGS --final_only -m "::")
+###
### all options are passed to structparser (in this example --final_only - do not export heirs with public base that contains the required field,,- m "::" only from the root namespace)
### sets in extra option
###
### @example:
-###
+###
### SET(EXTRACT_STRUCT_INFO_FLAGS -f \"const static ui32 RecordSig\"
### -u \"RecordSig\" -n${scheeme_name}SchemeInfo ----gcc44_no_typename no_complex_overloaded_func_export
-### ${DATAWORK_SCHEEME_EXPORT_FLAGS})
-###
+### ${DATAWORK_SCHEEME_EXPORT_FLAGS})
+###
### for compatibility with C++ compiler and the external environment.
### See tools/structparser for more details.
macro GEN_SCHEEME2(ScheemeName, FromFile) {
@@ -6988,7 +6988,7 @@ macro SYMLINK(From, To) {
###
### For absolute paths use ${ARCADIA_ROOT} and ${ARCADIA_BUILD_ROOT}, or
### ${CURDIR} and ${BINDIR} which are expanded where the outputs are used.
-### Note that Tool is always built for the host platform, so be careful to provide that tool can be built for all Arcadia major host platforms (Linux, MacOS and Windows).
+### Note that Tool is always built for the host platform, so be careful to provide that tool can be built for all Arcadia major host platforms (Linux, MacOS and Windows).
macro RUN_PROGRAM(Tool, IN{input}[], OUT{output}[], OUT_NOAUTO{output}[], TOOL{tool}[], OUTPUT_INCLUDES[], IN_DEPS[], STDOUT="", STDOUT_NOAUTO="", CWD="", ENV[], REQUIREMENTS[], Args...) {
.CMD=${cwd:CWD} ${env:ENV} ${tool:Tool} $Args ${input;hide:IN} ${input;hide:IN_DEPS} ${output_include;hide:OUTPUT_INCLUDES} ${tool;hide:TOOL} ${output;hide:OUT} ${output;noauto;hide:OUT_NOAUTO} ${output;stdout:STDOUT} ${output;stdout;noauto:STDOUT_NOAUTO} ${requirements;hide:REQUIREMENTS} ${requirements;hide:"network:restricted"} ${kv;hide:"p PR"} ${kv;hide:"pc yellow"} ${kv;hide:"show_out"}
}
@@ -7050,7 +7050,7 @@ macro _RUN_JAVA(IN{input}[], OUT{output}[], OUT_NOAUTO{output}[], OUTPUT_INCLUDE
### @usage: FROM_SANDBOX([FILE] resource_id [AUTOUPDATED script] [RENAME <resource files>] OUT_[NOAUTO] <output files> [EXECUTABLE] [OUTPUT_INCLUDES <include files>])
###
### Download the resource from the Sandbox, unpack (if not explicitly specified word FILE) and add OUT files to the build. EXECUTABLE makes them executable.
-### You may specify extra dependencies that output files bring using OUTPUT_INCLUDES. The change of these may e.g. lead to recompilation of .cpp files extracted from resource.
+### You may specify extra dependencies that output files bring using OUTPUT_INCLUDES. The change of these may e.g. lead to recompilation of .cpp files extracted from resource.
### If there is no default processing for OUT files or you need process them specially use OUT_NOAUTO instead of OUT.
###
### It is disallowed to specify directory as OUT/OUT_NOAUTO since all outputs of commands shall be known to build system.
@@ -7063,7 +7063,7 @@ macro _RUN_JAVA(IN{input}[], OUT{output}[], OUT_NOAUTO{output}[], OUTPUT_INCLUDE
### RENAME RESOURCE allows to rename the resource without specifying its file name.
###
### If AUTOUPDATED is specified than macro will be regularly updated according to autoupdate script. The dedicated Sandbox task scans the arcadia and
-### changes resource_ids in such macros if newer resource of specified type is available. Note that the task seeks AUTOUPDATED in specific position,
+### changes resource_ids in such macros if newer resource of specified type is available. Note that the task seeks AUTOUPDATED in specific position,
### so you shall place it immediately after resource_id.
macro FROM_SANDBOX(Id, OUT{output}[], OUT_NOAUTO{output}[], OUTPUT_INCLUDES[], FILE?"--copy-to-dir":"--untar-to", AUTOUPDATED="", PREFIX=".", RENAME[], EXECUTABLE?"--executable":"", SBR="sbr:", REQUIREMENTS[]) {
.CMD=${hide:SANDBOX_FAKEID} ${cwd:BINDIR} ${resource;pre=$SBR:Id} $YMAKE_PYTHON ${input:"build/scripts/fetch_from_sandbox.py"} --resource-file $(RESOURCE_ROOT)/sbr/$Id/resource --resource-id $Id $FILE $PREFIX ${pre=--rename :RENAME} $EXECUTABLE -- $OUT $OUT_NOAUTO ${input;hide:"build/scripts/fetch_from.py"} ${output_include;hide:OUTPUT_INCLUDES} ${output;hide:OUT} ${output;noauto;hide:OUT_NOAUTO} ${requirements;hide:REQUIREMENTS} ${requirements;hide:"network:full"} ${kv;hide:"p SB"} ${kv;hide:"pc yellow"} ${kv;hide:"show_out"}
@@ -7983,7 +7983,7 @@ CGO2_LDFLAGS_VALUE=
# tag:go-specific
GO_ASM_FLAGS_VALUE=
### @usage: GO_ASM_FLAGS(flags)
-### Add the specified flags to the go asm compile command line.
+### Add the specified flags to the go asm compile command line.
macro GO_ASM_FLAGS(Flags...) {
SET_APPEND(GO_ASM_FLAGS_VALUE $Flags)
}
@@ -8364,7 +8364,7 @@ otherwise {
# tag:go-specific tag:internal
### @usage _GO_BASE_UNIT # internal
###
-### The base module of all golang modules. Defines common properties, dependencies and rules for go build.
+### The base module of all golang modules. Defines common properties, dependencies and rules for go build.
module _GO_BASE_UNIT: _BASE_UNIT {
.EXTS=.go .gosrc .o .obj .a .symabis .mf
.CMD=TOUCH_UNIT
@@ -8713,7 +8713,7 @@ macro JAVA_IGNORE_CLASSPATH_CLASH_FOR(Args...) {
# tag:python-specific
### @usage: PY_SRCS({| CYTHON_C} { | TOP_LEVEL | NAMESPACE ns} Files...)
###
-### Build specified Python sources according to Arcadia binary Python build. Basically creates precompiled and source resources keyed with module paths.
+### Build specified Python sources according to Arcadia binary Python build. Basically creates precompiled and source resources keyed with module paths.
### The resources eventually are linked into final program and can be accessed as regular Python modules.
### This custom loader linked into the program will add them to sys.meta_path.
###
@@ -8806,7 +8806,7 @@ multimodule PY23_LIBRARY {
# tag:python-specific
### @usage: PY23_NATIVE_LIBRARY([name])
###
-### Build LIBRARY compatible with either Python 2.x or Python 3.x depending on incoming PEERDIR.
+### Build LIBRARY compatible with either Python 2.x or Python 3.x depending on incoming PEERDIR.
###
### This multimodule doesn't depend on Arcadia Python binary build. It is intended only for C++ code and cannot contain PY_SRCS and USE_PYTHON2 macros.
### Use these multimodule instead of PY23_LIBRARY if the C++ extension defined in it will be used in PY2MODULE.
diff --git a/build/ymake_conf.py b/build/ymake_conf.py
index 30219eb85e..6b3c2df8f2 100755
--- a/build/ymake_conf.py
+++ b/build/ymake_conf.py
@@ -556,7 +556,7 @@ class Build(object):
@property
def with_ndebug(self):
- return self.build_type in ('release', 'minsizerel', 'valgrind-release', 'profile', 'gprof', 'debugnoasserts')
+ return self.build_type in ('release', 'minsizerel', 'valgrind-release', 'profile', 'gprof', 'debugnoasserts')
@property
def is_valgrind(self):
@@ -1547,11 +1547,11 @@ class GnuCompiler(Compiler):
FSTACK += -fstack-check
}''')
- c_builtins = [
+ c_builtins = [
"-Wno-builtin-macro-redefined",
'-D__DATE__=\\""Sep 31 2019\\""',
'-D__TIME__=\\"00:00:00\\"',
- ]
+ ]
compiler_supports_macro_prefix_map = (
self.tc.is_clang and self.tc.version_at_least(10) or
self.tc.is_gcc and self.tc.version_at_least(8)
@@ -1568,31 +1568,31 @@ class GnuCompiler(Compiler):
# XXX this macro substitution breaks __FILE__ in included sources
'-D__FILE__=\\""${input;qe;rootrel:SRC}\\""',
]
- c_debug_map = [
- # XXX does not support non-normalized paths
- "-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
- "-fdebug-prefix-map=${ARCADIA_ROOT}=/-S",
- "-fdebug-prefix-map=$(TOOL_ROOT)=/-T",
- ]
- c_debug_map_cl = c_debug_map + [
- "-Xclang", "-fdebug-compilation-dir", "-Xclang", "/tmp",
- ]
- c_debug_map_light = [
- # XXX does not support non-normalized paths
- "-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
- ]
- c_debug_map_light_cl = c_debug_map_light + [
- "-Xclang", "-fdebug-compilation-dir", "-Xclang", "/tmp",
- ]
- yasm_debug_map = [
- # XXX does not support non-normalized paths
- "--replace=${ARCADIA_BUILD_ROOT}=/-B",
- "--replace=${ARCADIA_ROOT}=/-S",
- "--replace=$(TOOL_ROOT)=/-T"
- ]
- emit_big('''
+ c_debug_map = [
+ # XXX does not support non-normalized paths
+ "-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
+ "-fdebug-prefix-map=${ARCADIA_ROOT}=/-S",
+ "-fdebug-prefix-map=$(TOOL_ROOT)=/-T",
+ ]
+ c_debug_map_cl = c_debug_map + [
+ "-Xclang", "-fdebug-compilation-dir", "-Xclang", "/tmp",
+ ]
+ c_debug_map_light = [
+ # XXX does not support non-normalized paths
+ "-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
+ ]
+ c_debug_map_light_cl = c_debug_map_light + [
+ "-Xclang", "-fdebug-compilation-dir", "-Xclang", "/tmp",
+ ]
+ yasm_debug_map = [
+ # XXX does not support non-normalized paths
+ "--replace=${ARCADIA_BUILD_ROOT}=/-B",
+ "--replace=${ARCADIA_ROOT}=/-S",
+ "--replace=$(TOOL_ROOT)=/-T"
+ ]
+ emit_big('''
when ($FORCE_CONSISTENT_DEBUG == "yes") {{
- when ($CLANG == "yes") {{
+ when ($CLANG == "yes") {{
CL_DEBUG_INFO={c_debug_cl}
}}
otherwise {{
@@ -1602,37 +1602,37 @@ class GnuCompiler(Compiler):
}}
elsewhen ($CONSISTENT_DEBUG == "yes") {{
when ($CLANG == "yes") {{
- CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_cl}
- }}
- otherwise {{
- CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug}
- }}
- YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug}
- }}
- elsewhen ($CONSISTENT_DEBUG_LIGHT == "yes") {{
- when ($CLANG == "yes") {{
- CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_light_cl}
- }}
- otherwise {{
- CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_light}
- }}
- YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug_light}
- }}
-
+ CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_cl}
+ }}
+ otherwise {{
+ CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug}
+ }}
+ YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug}
+ }}
+ elsewhen ($CONSISTENT_DEBUG_LIGHT == "yes") {{
+ when ($CLANG == "yes") {{
+ CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_light_cl}
+ }}
+ otherwise {{
+ CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_light}
+ }}
+ YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug_light}
+ }}
+
when ($FORCE_CONSISTENT_BUILD == "yes") {{
CL_MACRO_INFO={macro}
}}
elsewhen ($CONSISTENT_BUILD == "yes") {{
- CL_MACRO_INFO_DISABLE_CACHE__NO_UID__={macro}
- }}
- '''.format(c_debug=' '.join(c_debug_map),
- c_debug_cl=' '.join(c_debug_map_cl),
- yasm_debug=' '.join(yasm_debug_map),
- c_debug_light=' '.join(c_debug_map_light), # build_root substitution only
- c_debug_light_cl=' '.join(c_debug_map_light_cl), # build_root substitution only
- yasm_debug_light=yasm_debug_map[0], # build_root substitution only
- macro=' '.join(c_builtins)))
-
+ CL_MACRO_INFO_DISABLE_CACHE__NO_UID__={macro}
+ }}
+ '''.format(c_debug=' '.join(c_debug_map),
+ c_debug_cl=' '.join(c_debug_map_cl),
+ yasm_debug=' '.join(yasm_debug_map),
+ c_debug_light=' '.join(c_debug_map_light), # build_root substitution only
+ c_debug_light_cl=' '.join(c_debug_map_light_cl), # build_root substitution only
+ yasm_debug_light=yasm_debug_map[0], # build_root substitution only
+ macro=' '.join(c_builtins)))
+
# TODO(somov): Check whether this specific architecture is needed.
if self.target.arch == 'i386':
append('CFLAGS', '-march=pentiumpro')
@@ -1715,8 +1715,8 @@ class GnuCompiler(Compiler):
'$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
'&& $COMPILER_TIME_TRACE_POSTPROCESS',
]
- c_args_nodeps = [c if c != '$GCC_COMPILE_FLAGS' else '$EXTRA_C_FLAGS -c -o ${OUTFILE} ${SRC} ${pre=-I:INC}' for c in c_args if c not in ignore_c_args_no_deps]
-
+ c_args_nodeps = [c if c != '$GCC_COMPILE_FLAGS' else '$EXTRA_C_FLAGS -c -o ${OUTFILE} ${SRC} ${pre=-I:INC}' for c in c_args if c not in ignore_c_args_no_deps]
+
emit('_SRC_C_NODEPS_CMD', ' '.join(c_args_nodeps))
emit('_SRC_CPP_CMD', ' '.join(cxx_args))
emit('_SRC_C_CMD', ' '.join(c_args))
@@ -1755,12 +1755,12 @@ class Linker(object):
self.tc = tc
self.build = build
self.type = self._get_default_linker_type()
-
+
def _get_default_linker_type(self):
if not self.tc.is_from_arcadia:
# External (e.g. system) toolchain: disable linker selection logic
return None
-
+
if self.build.target.is_android:
# Android toolchain is NDK, LLD works on all supported platforms
return Linker.LLD
@@ -1810,8 +1810,8 @@ class LD(Linker):
self.strip = self.tc.strip
self.objcopy = self.tc.objcopy
- self.musl = Setting('MUSL', convert=to_bool)
-
+ self.musl = Setting('MUSL', convert=to_bool)
+
if self.ar is None:
if target.is_apple:
# Use libtool. cctools ar does not understand -M needed for archive merging
@@ -1867,23 +1867,23 @@ class LD(Linker):
else:
self.ld_icf_flag = ''
- if self.musl.value:
- self.ld_flags.extend(['-Wl,--no-as-needed'])
+ if self.musl.value:
+ self.ld_flags.extend(['-Wl,--no-as-needed'])
if self.tc.is_gcc:
# MUSL_BFD: musl build uses --no-dynamic-linker linker flag
# which gold doesn't know about. And we can only specify linker
# type, not it's path as we do for Clang through linker selector.
self.ld_flags.append('-fuse-ld=bfd')
- elif target.is_linux:
+ elif target.is_linux:
self.ld_flags.extend(['-ldl', '-lrt', '-Wl,--no-as-needed'])
if self.tc.is_gcc:
self.ld_flags.extend(('-Wl,-Bstatic', '-latomic', '-Wl,-Bdynamic'))
- elif target.is_android:
+ elif target.is_android:
self.ld_flags.extend(['-ldl', '-Wl,--no-as-needed'])
if self.type == Linker.LLD and target.android_api < 29:
# https://github.com/android/ndk/issues/1196
self.ld_flags.append('-Wl,--no-rosegment')
- elif target.is_macos:
+ elif target.is_macos:
self.ld_flags.append('-Wl,-no_deduplicate')
if not self.tc.is_clang:
self.ld_flags.append('-Wl,-no_compact_unwind')
@@ -1989,10 +1989,10 @@ class LD(Linker):
emit('C_LIBRARY_PATH')
emit('C_SYSTEM_LIBRARIES_INTERCEPT')
- if self.musl.value:
- emit('C_SYSTEM_LIBRARIES', '-nostdlib')
- else:
- emit('C_SYSTEM_LIBRARIES', self.use_stdlib, self.thread_library, self.sys_lib, '-lc')
+ if self.musl.value:
+ emit('C_SYSTEM_LIBRARIES', '-nostdlib')
+ else:
+ emit('C_SYSTEM_LIBRARIES', self.use_stdlib, self.thread_library, self.sys_lib, '-lc')
emit('START_WHOLE_ARCHIVE_VALUE', self.whole_archive)
emit('END_WHOLE_ARCHIVE_VALUE', self.no_whole_archive)
@@ -2142,7 +2142,7 @@ class LD(Linker):
else:
emit('LINK_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
emit('LINK_EXEC_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_EXEC_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
- emit('SWIG_DLL_JAR_CMD', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_SWIG_DLL_JAR_CMD && $DWARF_COMMAND')
+ emit('SWIG_DLL_JAR_CMD', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_SWIG_DLL_JAR_CMD && $DWARF_COMMAND')
tail_link_lib = '$AUTO_INPUT ${requirements;hide:LIB_REQUIREMENTS} ${kv;hide:"p AR"} $TOOLCHAIN_ENV ${kv;hide:"pc light-red"} ${kv;hide:"show_out"}'
if is_positive("TIDY"):
@@ -2534,7 +2534,7 @@ class MSVCCompiler(MSVC, Compiler):
if not self.tc.ide_msvs:
def include_flag(path):
- return '{flag}"{path}"'.format(path=path, flag='/I ' if not self.tc.use_clang else '-imsvc')
+ return '{flag}"{path}"'.format(path=path, flag='/I ' if not self.tc.use_clang else '-imsvc')
for name in ('shared', 'ucrt', 'um', 'winrt'):
flags.append(include_flag(os.path.join(self.tc.kit_includes, name)))
diff --git a/contrib/libs/c-ares/CHANGES b/contrib/libs/c-ares/CHANGES
index f6652caaa0..a0ad09fd31 100644
--- a/contrib/libs/c-ares/CHANGES
+++ b/contrib/libs/c-ares/CHANGES
@@ -554,242 +554,242 @@ Brad House (24 Dec 2019)
Daniel Stenberg (24 Oct 2018)
- ares_library_init_android.3: minor syntax edits, fixed AVAILABILITY
-Version 1.15.0 (23 Oct 2018)
-
-Brad House (23 Oct 2018)
-- last minute 1.15.0 addition
-
-- [Ben Noordhuis brought this change]
-
- Report ARES_ENOTFOUND for .onion domain names as per RFC7686. (#228)
-
- Quoting RFC 7686:
-
- Name Resolution APIs and Libraries (...) MUST either respond
- to requests for .onion names by resolving them according to
- [tor-rendezvous] or by responding with NXDOMAIN.
-
- A legacy client may inadvertently attempt to resolve a .onion
- name through the DNS. This causes a disclosure that the client
- is attempting to use Tor to reach a specific service. Malicious
- resolvers could be engineered to capture and record such leaks,
- which might have very adverse consequences for the well-being
- of the user.
-
- Bug: #196
- Fix By: Ben Noordhuis @bnoordhuis
-
-- prepare for c-ares 1.15.0 release
-
-- AIX Build Fix
-
- AIX attempts to include both nameser_compat.h and onameser_compat.h. It appears
- the proper fix is to define _USE_IRS so that only nameser_compat.h is used.
-
- Bug: #224
- Fix By: Brad House (@bradh352)
-
-- Fix crash in ares_dup() due to new ARES_OPT_RESOLVCONF
-
- ares_dup() calls ares_init_options() by making its own fake option
- mask since the original mask isn't stored but ARES_OPT_RESOLVCONF
- was always set, instead of conditionally set. This caused a crash
- because ares_strdup() isn't NULL-safe if no custom path was set.
-
- Made ares_dup() set ARES_OPT_RESOLVCONF conditionally.
-
- Fix By: Brad House (@bradh352)
-
-- [Sarat Addepalli brought this change]
-
- Add ares_init_options() configurability for path to resolv.conf file
-
- Add resolvconf_path to end of struct ares_options with ARES_OPT_RESOLVCONF option
- so on Unix-like systems a custom path can be specified. If no path is specified,
- /etc/resolv.conf is used like normal.
-
- Fix By: Sarat Addepalli @SirR4T
- Fixes Bug: #220
- Review By: Brad House @bradh352
-
-- remove stale variables
-
-- fix prototype name for ares_strsplit_free()
-
-- add missing prototype
-
-- simplify ares_strsplit() and create ares_strsplit_free() helper function
-
-- missing ares_strsplit.h from HHEADERS for inclusion in distribution
-
-- [Ruslan Baratov brought this change]
-
- Add CARES_BUILD_TOOLS CMake option (#214)
-
- Add ability to exclude building of tools (adig, ahost, acountry) in CMake. This should also close #200.
-
- Fix By: Ruslan Baratov (@ruslo)
- Bug: #200
-
-- [flyingdutchman23 brought this change]
-
- Style. Whitespace cleanup. (#213)
-
- Small whitespace cleanups.
-
- Fix By: @flyingdutchman23
-
-- [John Schember brought this change]
-
- Android: Support for domain search suffix (#211)
-
- Fixes issue #207. Uses LinkProperties.getDomains() to get a list of search domains and adds them to the suffix list. This also adds a new helper function to split strings into an array based on multiple delimiters replacing multiple other functions for dealing with string splitting.
-
- Submitter: John Schember (@user-none)
- Fixes: #207
- Approved-by: Brad House (@bradh352)
-
-- [afalin brought this change]
-
- Improve DNS suffixes extracting from WinNT registry (#202)
-
- Join all global and connection specific suffix lists. Use 'HKLM\Software\Policies\Microsoft\Windows NT\DNSClient\SearchList', 'HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\Domain' as global suffix lists.
-
- Fix By: @afalin
-
-- Be consistent with indention in CMakeLists.txt
-
- The imported TRANSFORM_MAKEFILE_INC function from curl used space indention
- but the rest of the file used tabs. Go ahead and make it tabs for
- consistency as well.
-
- Committed By: Brad House
-
-- [flyingdutchman23 brought this change]
-
- Fix modern gcc warning: argument to 'sizeof' in 'strncpy' call is the same expression as the source
-
- Silence warning about using src to determine number of bytes to copy.
- In this case it doesn't matter whether it is `src` or `dest`. So there
- is no functionality change.
-
- Bug: #210
- Fix By: @flyingdutchman23
-
-- [Andi Schnebinger brought this change]
-
- fix stringop-overflow warning of GCC (#201)
-
- When using a modern GCC to compile c-ares, there is a stringop-overflow warning.
- This patch simply silences the false-positive warning, there is no actual code flaw.
-
- Bug: https://github.com/c-ares/c-ares/pull/201
- Fixed By: Andi Schnebinger @Iniesta8
-
-GitHub (18 May 2018)
-- [David Drysdale brought this change]
-
- travis: do coverage in "coverage" build (#195)
-
- Fixes #194, a mistake from commit a255081f2c3c ("travis: Only do
- coverage/distcheck on normal build")
-
-Brad House (17 May 2018)
-- [Brad Spencer brought this change]
-
- Apply the IPv6 server blacklist to all nameserver sources, not just Windows (#193)
-
- For #164, I mentioned that it seemed like the IPv6 nameserver blacklist should apply to all OSes. In a mailing list post, @bradh352 agreed and suggested that I file a PR to make it so.
-
- This moves the blacklist check from being Windows-specific to being a general feature of config_nameservers(), no matter the nameserver source. It also simplifies the ares_ipv6_server_blacklisted() implementation to not parse and re-parse the blacklisted IPv6 addresses from strings on every check. I think they're almost as easy to read as a sequence of hex bytes in an array initializer, and it's definitely less work on each trip through the code.
-
- Fix By: Brad Spencer @b-spencer
- PR: https://github.com/c-ares/c-ares/pull/193
-
-- [Brad Spencer brought this change]
-
- Fix warnings emitted by MSVC when using -W4 (#192)
-
- These changes fix a few warnings emitted by recent versions of MSVC when compiling with -W4. Half of the changes are in Windows-specific code, and the other half should be safe no matter the compiler or OS.
-
- The allocation function change is probably the only one that needs explanation. MSVC gives warnings about the function pointers not being stable across DLL boundaries or something to that effect, so for Windows, I've made them be called indirectly, which at least made the compiler happy. I can't say I've tested every linking combination on Windows with them before or after the change, but it seems harmless.
-
- Fix By: Brad Spencer @b-spencer
- PR: https://github.com/c-ares/c-ares/pull/192
-
-- [David Hotham brought this change]
-
- Prevent changing name servers while queries are outstanding (#191)
-
- Changing name servers doesn't work, per #41. Better to return an error code than to crash.
-
- Fix-by: David Hotham @dimbleby
-
-David Drysdale (15 May 2018)
-- [Tobias Nießen brought this change]
-
- Fix comment in ares_rules.h (#189)
-
-Brad House (6 May 2018)
-- [Brad Spencer brought this change]
-
- Harden and rationalize c-ares timeout computation (#187)
-
- * Harden and rationalize c-ares timeout computation
- * Remove the rand() part of the timeout calculation completely.
-
- When c-ares sends a DNS query, it computes the timeout for that request as follows:
-
- timeplus = channel->timeout << (query->try_count / channel->nservers);
- timeplus = (timeplus * (9 + (rand () & 7))) / 16;
- I see two issues with this code. Firstly, when either try_count or channel->timeout are large enough, this can end up as an illegal shift.
-
- Secondly, the algorithm for adding the random timeout (added in 2009) is surprising. The original commit that introduced this algorithm says it was done to avoid a "packet storm". But, the algorithm appears to only reduce the timeout by an amount proportional to the scaled timeout's magnitude. It isn't clear to me that, for example, cutting a 30 second timeout almost in half to roughly 17 seconds is appropriate. Even with the default timeout of 5000 ms, this algorithm computes values between 2812 ms and 5000 ms, which is enough to cause a slightly latent DNS response to get spuriously dropped.
-
- If preventing the timers from all expiring at the same time really is desirable, then it seems better to extend the timeout by a small factor so that the application gets at least the timeout it asked for, and maybe a little more. In my experience, this is common practice for timeouts: applications expect that a timeout will happen at or after the designated time (but not before), allowing for delay in detecting and reporting the timeout. Furthermore, it seems like the timeout shouldn't be extended by very much (we don't want a 30 second timeout changing into a 45 second timeout, either).
-
- Consider also the documentation of channel->timeout in ares_init_options():
-
- The number of milliseconds each name server is given to respond to a query on the first try. (After the first try, the timeout algorithm becomes more complicated, but scales linearly with the value of timeout.) The default is five seconds.
-
- In the current implementation, even the first try does not use the value that the user supplies; it will use anywhere between 56% and 100% of that value.
-
- The attached patch attempts to address all of these concerns without trying to make the algorithm much more sophisticated. After performing a safe shift, this patch simply adds a small random timeout to the computed value of between 0 ms and 511 ms. I could see limiting the random amount to be no greater than a proportion of the configured magnitude, but I can't see scaling the random with the overall computed timeout. As far as I understand, the goal is just to schedule retries "not at the same exact time", so a small difference seems sufficient.
-
- UPDATE: randomization removed.
-
- Closes PR #187
- Fix by: Brad Spencer
-
-- distribute ares_android.h
-
- Distribute ares_android.h when a release distribution package is
- created.
-
- Reported By: Andrey Khranovsky
- Bug: https://c-ares.haxx.se/mail/c-ares-archive-2018-04/0000.shtml
-
-- ares_set_servers_csv() on failure should not leave channel in a bad state
-
- If bad data is passed to ares_set_servers_csv() or
- ares_set_servers_ports_csv() it will clear the existing channel
- configured DNS servers, then a call to ares_send() will fail due
- to a bad malloc which may have undefined behavior.
-
- The fix now only clears existing servers on success. An additional
- sanity check was added in ares_send() to ensure nservers >= 1 or
- will result in ARES_ESERVFAIL.
-
- Bug: https://c-ares.haxx.se/mail/c-ares-archive-2018-03/0000.shtml
- Reported-by: Francisco Sedano Crippa
-
-- docs: Not all manpages are listed
-
- Some docs aren't installed or not showing up on
- https://c-ares.haxx.se/docs.html
- due to not being listed in Makefile.inc. Add missing docs and
- ensure docs are alphabetized.
-
+Version 1.15.0 (23 Oct 2018)
+
+Brad House (23 Oct 2018)
+- last minute 1.15.0 addition
+
+- [Ben Noordhuis brought this change]
+
+ Report ARES_ENOTFOUND for .onion domain names as per RFC7686. (#228)
+
+ Quoting RFC 7686:
+
+ Name Resolution APIs and Libraries (...) MUST either respond
+ to requests for .onion names by resolving them according to
+ [tor-rendezvous] or by responding with NXDOMAIN.
+
+ A legacy client may inadvertently attempt to resolve a .onion
+ name through the DNS. This causes a disclosure that the client
+ is attempting to use Tor to reach a specific service. Malicious
+ resolvers could be engineered to capture and record such leaks,
+ which might have very adverse consequences for the well-being
+ of the user.
+
+ Bug: #196
+ Fix By: Ben Noordhuis @bnoordhuis
+
+- prepare for c-ares 1.15.0 release
+
+- AIX Build Fix
+
+ AIX attempts to include both nameser_compat.h and onameser_compat.h. It appears
+ the proper fix is to define _USE_IRS so that only nameser_compat.h is used.
+
+ Bug: #224
+ Fix By: Brad House (@bradh352)
+
+- Fix crash in ares_dup() due to new ARES_OPT_RESOLVCONF
+
+ ares_dup() calls ares_init_options() by making its own fake option
+ mask since the original mask isn't stored but ARES_OPT_RESOLVCONF
+ was always set, instead of conditionally set. This caused a crash
+ because ares_strdup() isn't NULL-safe if no custom path was set.
+
+ Made ares_dup() set ARES_OPT_RESOLVCONF conditionally.
+
+ Fix By: Brad House (@bradh352)
+
+- [Sarat Addepalli brought this change]
+
+ Add ares_init_options() configurability for path to resolv.conf file
+
+ Add resolvconf_path to end of struct ares_options with ARES_OPT_RESOLVCONF option
+ so on Unix-like systems a custom path can be specified. If no path is specified,
+ /etc/resolv.conf is used like normal.
+
+ Fix By: Sarat Addepalli @SirR4T
+ Fixes Bug: #220
+ Review By: Brad House @bradh352
+
+- remove stale variables
+
+- fix prototype name for ares_strsplit_free()
+
+- add missing prototype
+
+- simplify ares_strsplit() and create ares_strsplit_free() helper function
+
+- missing ares_strsplit.h from HHEADERS for inclusion in distribution
+
+- [Ruslan Baratov brought this change]
+
+ Add CARES_BUILD_TOOLS CMake option (#214)
+
+ Add ability to exclude building of tools (adig, ahost, acountry) in CMake. This should also close #200.
+
+ Fix By: Ruslan Baratov (@ruslo)
+ Bug: #200
+
+- [flyingdutchman23 brought this change]
+
+ Style. Whitespace cleanup. (#213)
+
+ Small whitespace cleanups.
+
+ Fix By: @flyingdutchman23
+
+- [John Schember brought this change]
+
+ Android: Support for domain search suffix (#211)
+
+ Fixes issue #207. Uses LinkProperties.getDomains() to get a list of search domains and adds them to the suffix list. This also adds a new helper function to split strings into an array based on multiple delimiters replacing multiple other functions for dealing with string splitting.
+
+ Submitter: John Schember (@user-none)
+ Fixes: #207
+ Approved-by: Brad House (@bradh352)
+
+- [afalin brought this change]
+
+ Improve DNS suffixes extracting from WinNT registry (#202)
+
+ Join all global and connection specific suffix lists. Use 'HKLM\Software\Policies\Microsoft\Windows NT\DNSClient\SearchList', 'HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\Domain' as global suffix lists.
+
+ Fix By: @afalin
+
+- Be consistent with indention in CMakeLists.txt
+
+ The imported TRANSFORM_MAKEFILE_INC function from curl used space indention
+ but the rest of the file used tabs. Go ahead and make it tabs for
+ consistency as well.
+
+ Committed By: Brad House
+
+- [flyingdutchman23 brought this change]
+
+ Fix modern gcc warning: argument to 'sizeof' in 'strncpy' call is the same expression as the source
+
+ Silence warning about using src to determine number of bytes to copy.
+ In this case it doesn't matter whether it is `src` or `dest`. So there
+ is no functionality change.
+
+ Bug: #210
+ Fix By: @flyingdutchman23
+
+- [Andi Schnebinger brought this change]
+
+ fix stringop-overflow warning of GCC (#201)
+
+ When using a modern GCC to compile c-ares, there is a stringop-overflow warning.
+ This patch simply silences the false-positive warning, there is no actual code flaw.
+
+ Bug: https://github.com/c-ares/c-ares/pull/201
+ Fixed By: Andi Schnebinger @Iniesta8
+
+GitHub (18 May 2018)
+- [David Drysdale brought this change]
+
+ travis: do coverage in "coverage" build (#195)
+
+ Fixes #194, a mistake from commit a255081f2c3c ("travis: Only do
+ coverage/distcheck on normal build")
+
+Brad House (17 May 2018)
+- [Brad Spencer brought this change]
+
+ Apply the IPv6 server blacklist to all nameserver sources, not just Windows (#193)
+
+ For #164, I mentioned that it seemed like the IPv6 nameserver blacklist should apply to all OSes. In a mailing list post, @bradh352 agreed and suggested that I file a PR to make it so.
+
+ This moves the blacklist check from being Windows-specific to being a general feature of config_nameservers(), no matter the nameserver source. It also simplifies the ares_ipv6_server_blacklisted() implementation to not parse and re-parse the blacklisted IPv6 addresses from strings on every check. I think they're almost as easy to read as a sequence of hex bytes in an array initializer, and it's definitely less work on each trip through the code.
+
+ Fix By: Brad Spencer @b-spencer
+ PR: https://github.com/c-ares/c-ares/pull/193
+
+- [Brad Spencer brought this change]
+
+ Fix warnings emitted by MSVC when using -W4 (#192)
+
+ These changes fix a few warnings emitted by recent versions of MSVC when compiling with -W4. Half of the changes are in Windows-specific code, and the other half should be safe no matter the compiler or OS.
+
+ The allocation function change is probably the only one that needs explanation. MSVC gives warnings about the function pointers not being stable across DLL boundaries or something to that effect, so for Windows, I've made them be called indirectly, which at least made the compiler happy. I can't say I've tested every linking combination on Windows with them before or after the change, but it seems harmless.
+
+ Fix By: Brad Spencer @b-spencer
+ PR: https://github.com/c-ares/c-ares/pull/192
+
+- [David Hotham brought this change]
+
+ Prevent changing name servers while queries are outstanding (#191)
+
+ Changing name servers doesn't work, per #41. Better to return an error code than to crash.
+
+ Fix-by: David Hotham @dimbleby
+
+David Drysdale (15 May 2018)
+- [Tobias Nießen brought this change]
+
+ Fix comment in ares_rules.h (#189)
+
+Brad House (6 May 2018)
+- [Brad Spencer brought this change]
+
+ Harden and rationalize c-ares timeout computation (#187)
+
+ * Harden and rationalize c-ares timeout computation
+ * Remove the rand() part of the timeout calculation completely.
+
+ When c-ares sends a DNS query, it computes the timeout for that request as follows:
+
+ timeplus = channel->timeout << (query->try_count / channel->nservers);
+ timeplus = (timeplus * (9 + (rand () & 7))) / 16;
+ I see two issues with this code. Firstly, when either try_count or channel->timeout are large enough, this can end up as an illegal shift.
+
+ Secondly, the algorithm for adding the random timeout (added in 2009) is surprising. The original commit that introduced this algorithm says it was done to avoid a "packet storm". But, the algorithm appears to only reduce the timeout by an amount proportional to the scaled timeout's magnitude. It isn't clear to me that, for example, cutting a 30 second timeout almost in half to roughly 17 seconds is appropriate. Even with the default timeout of 5000 ms, this algorithm computes values between 2812 ms and 5000 ms, which is enough to cause a slightly latent DNS response to get spuriously dropped.
+
+ If preventing the timers from all expiring at the same time really is desirable, then it seems better to extend the timeout by a small factor so that the application gets at least the timeout it asked for, and maybe a little more. In my experience, this is common practice for timeouts: applications expect that a timeout will happen at or after the designated time (but not before), allowing for delay in detecting and reporting the timeout. Furthermore, it seems like the timeout shouldn't be extended by very much (we don't want a 30 second timeout changing into a 45 second timeout, either).
+
+ Consider also the documentation of channel->timeout in ares_init_options():
+
+ The number of milliseconds each name server is given to respond to a query on the first try. (After the first try, the timeout algorithm becomes more complicated, but scales linearly with the value of timeout.) The default is five seconds.
+
+ In the current implementation, even the first try does not use the value that the user supplies; it will use anywhere between 56% and 100% of that value.
+
+ The attached patch attempts to address all of these concerns without trying to make the algorithm much more sophisticated. After performing a safe shift, this patch simply adds a small random timeout to the computed value of between 0 ms and 511 ms. I could see limiting the random amount to be no greater than a proportion of the configured magnitude, but I can't see scaling the random with the overall computed timeout. As far as I understand, the goal is just to schedule retries "not at the same exact time", so a small difference seems sufficient.
+
+ UPDATE: randomization removed.
+
+ Closes PR #187
+ Fix by: Brad Spencer
+
+- distribute ares_android.h
+
+ Distribute ares_android.h when a release distribution package is
+ created.
+
+ Reported By: Andrey Khranovsky
+ Bug: https://c-ares.haxx.se/mail/c-ares-archive-2018-04/0000.shtml
+
+- ares_set_servers_csv() on failure should not leave channel in a bad state
+
+ If bad data is passed to ares_set_servers_csv() or
+ ares_set_servers_ports_csv() it will clear the existing channel
+ configured DNS servers, then a call to ares_send() will fail due
+ to a bad malloc which may have undefined behavior.
+
+ The fix now only clears existing servers on success. An additional
+ sanity check was added in ares_send() to ensure nservers >= 1 or
+ will result in ARES_ESERVFAIL.
+
+ Bug: https://c-ares.haxx.se/mail/c-ares-archive-2018-03/0000.shtml
+ Reported-by: Francisco Sedano Crippa
+
+- docs: Not all manpages are listed
+
+ Some docs aren't installed or not showing up on
+ https://c-ares.haxx.se/docs.html
+ due to not being listed in Makefile.inc. Add missing docs and
+ ensure docs are alphabetized.
+
Version 1.14.0 (16 Feb 2018)
Daniel Stenberg (16 Feb 2018)
diff --git a/contrib/libs/c-ares/RELEASE-NOTES b/contrib/libs/c-ares/RELEASE-NOTES
index 7a9d75fe78..a4cad95883 100644
--- a/contrib/libs/c-ares/RELEASE-NOTES
+++ b/contrib/libs/c-ares/RELEASE-NOTES
@@ -9,7 +9,7 @@ Changes:
o Allow TXT records on CHAOS qclass. Used for retriving things like
version.bind, version.server, authoris.bind, hostname.bind, and id.server.
[3]
-
+
Bug fixes:
o Fix Windows Unicode incompatibilities with ares_getaddrinfo() [1]
o Silence false cast-align compiler warnings due to valid casts of
diff --git a/contrib/libs/c-ares/RELEASE-PROCEDURE.md b/contrib/libs/c-ares/RELEASE-PROCEDURE.md
index b2fe58639b..5688ca8db0 100644
--- a/contrib/libs/c-ares/RELEASE-PROCEDURE.md
+++ b/contrib/libs/c-ares/RELEASE-PROCEDURE.md
@@ -1,53 +1,53 @@
-c-ares release procedure - how to do a release
-==============================================
-
-in the source code repo
------------------------
-
-- edit `RELEASE-NOTES` to be accurate
-
-- edit `Makefile.am`'s `CARES_VERSION_INFO`, and `CMakeLists.txt`'s
- `CARES_LIB_VERSIONINFO` set to the same value to denote the current shared
- object versioning.
-
-- make sure all relevant changes are committed on the master branch
-
-- tag the git repo in this style: `git tag -a cares-1_14_0` -a annotates the
- tag and we use underscores instead of dots in the version number.
-
-- run "./maketgz 1.14.0" to build the release tarball. It is important that
- you run this on a machine with the correct set of autotools etc installed
- as this is what then will be shipped and used by most users on *nix like
- systems.
-
-- push the git commits and the new tag
-
-- gpg sign the tarball
-
-- upload the resulting files to https://c-ares.haxx.se/download/
-
-- update `ares_version.h` for the next version
-
-in the c-ares-www repo
-----------------------
-
-- edit `index.t` (version number and date),
-
-- edit `changelog.t` (add the new release in there)
-
-- commit all local changes
-
-- tag the repo with the same tag as used for the source repo
-
-- push the git commits and the new tag
-
-inform
-------
-
-- send an email to the c-ares mailing list. Insert the RELEASE-NOTES into the
- mail.
-
-celebrate
----------
-
-- suitable beverage intake is encouraged for the festivities
+c-ares release procedure - how to do a release
+==============================================
+
+in the source code repo
+-----------------------
+
+- edit `RELEASE-NOTES` to be accurate
+
+- edit `Makefile.am`'s `CARES_VERSION_INFO`, and `CMakeLists.txt`'s
+ `CARES_LIB_VERSIONINFO` set to the same value to denote the current shared
+ object versioning.
+
+- make sure all relevant changes are committed on the master branch
+
+- tag the git repo in this style: `git tag -a cares-1_14_0` -a annotates the
+ tag and we use underscores instead of dots in the version number.
+
+- run "./maketgz 1.14.0" to build the release tarball. It is important that
+ you run this on a machine with the correct set of autotools etc installed
+ as this is what then will be shipped and used by most users on *nix like
+ systems.
+
+- push the git commits and the new tag
+
+- gpg sign the tarball
+
+- upload the resulting files to https://c-ares.haxx.se/download/
+
+- update `ares_version.h` for the next version
+
+in the c-ares-www repo
+----------------------
+
+- edit `index.t` (version number and date),
+
+- edit `changelog.t` (add the new release in there)
+
+- commit all local changes
+
+- tag the repo with the same tag as used for the source repo
+
+- push the git commits and the new tag
+
+inform
+------
+
+- send an email to the c-ares mailing list. Insert the RELEASE-NOTES into the
+ mail.
+
+celebrate
+---------
+
+- suitable beverage intake is encouraged for the festivities
diff --git a/contrib/libs/c-ares/acountry/ya.make b/contrib/libs/c-ares/acountry/ya.make
index 58b533d30c..6498a62c0e 100644
--- a/contrib/libs/c-ares/acountry/ya.make
+++ b/contrib/libs/c-ares/acountry/ya.make
@@ -1,35 +1,35 @@
-# Generated by devtools/yamaker.
-
-PROGRAM(acountry)
-
+# Generated by devtools/yamaker.
+
+PROGRAM(acountry)
+
OWNER(max42 g:cpp-contrib)
-
-LICENSE(MIT)
-
-PEERDIR(
- contrib/libs/c-ares
-)
-
-ADDINCL(
- contrib/libs/c-ares
-)
-
-NO_COMPILER_WARNINGS()
-
+
+LICENSE(MIT)
+
+PEERDIR(
+ contrib/libs/c-ares
+)
+
+ADDINCL(
+ contrib/libs/c-ares
+)
+
+NO_COMPILER_WARNINGS()
+
CFLAGS(
-DHAVE_CONFIG_H
)
-SRCDIR(contrib/libs/c-ares)
-
-IF (NOT DLL_FOR)
- CFLAGS(
- -DCARES_STATICLIB
- )
-ENDIF()
-
-SRCS(
- acountry.c
-)
-
-END()
+SRCDIR(contrib/libs/c-ares)
+
+IF (NOT DLL_FOR)
+ CFLAGS(
+ -DCARES_STATICLIB
+ )
+ENDIF()
+
+SRCS(
+ acountry.c
+)
+
+END()
diff --git a/contrib/libs/c-ares/adig/ya.make b/contrib/libs/c-ares/adig/ya.make
index 1c8404ebee..11a0b23f38 100644
--- a/contrib/libs/c-ares/adig/ya.make
+++ b/contrib/libs/c-ares/adig/ya.make
@@ -1,35 +1,35 @@
-# Generated by devtools/yamaker.
-
-PROGRAM(adig)
-
+# Generated by devtools/yamaker.
+
+PROGRAM(adig)
+
OWNER(max42 g:cpp-contrib)
-
-LICENSE(MIT)
-
-PEERDIR(
- contrib/libs/c-ares
-)
-
-ADDINCL(
- contrib/libs/c-ares
-)
-
-NO_COMPILER_WARNINGS()
-
+
+LICENSE(MIT)
+
+PEERDIR(
+ contrib/libs/c-ares
+)
+
+ADDINCL(
+ contrib/libs/c-ares
+)
+
+NO_COMPILER_WARNINGS()
+
CFLAGS(
-DHAVE_CONFIG_H
)
-SRCDIR(contrib/libs/c-ares)
-
-IF (NOT DLL_FOR)
- CFLAGS(
- -DCARES_STATICLIB
- )
-ENDIF()
-
-SRCS(
- adig.c
-)
-
-END()
+SRCDIR(contrib/libs/c-ares)
+
+IF (NOT DLL_FOR)
+ CFLAGS(
+ -DCARES_STATICLIB
+ )
+ENDIF()
+
+SRCS(
+ adig.c
+)
+
+END()
diff --git a/contrib/libs/c-ares/ahost/ya.make b/contrib/libs/c-ares/ahost/ya.make
index 299e3f211c..955acf5247 100644
--- a/contrib/libs/c-ares/ahost/ya.make
+++ b/contrib/libs/c-ares/ahost/ya.make
@@ -1,35 +1,35 @@
-# Generated by devtools/yamaker.
-
-PROGRAM(ahost)
-
+# Generated by devtools/yamaker.
+
+PROGRAM(ahost)
+
OWNER(max42 g:cpp-contrib)
-
-LICENSE(MIT)
-
-PEERDIR(
- contrib/libs/c-ares
-)
-
-ADDINCL(
- contrib/libs/c-ares
-)
-
-NO_COMPILER_WARNINGS()
-
+
+LICENSE(MIT)
+
+PEERDIR(
+ contrib/libs/c-ares
+)
+
+ADDINCL(
+ contrib/libs/c-ares
+)
+
+NO_COMPILER_WARNINGS()
+
CFLAGS(
-DHAVE_CONFIG_H
)
-SRCDIR(contrib/libs/c-ares)
-
-IF (NOT DLL_FOR)
- CFLAGS(
- -DCARES_STATICLIB
- )
-ENDIF()
-
-SRCS(
- ahost.c
-)
-
-END()
+SRCDIR(contrib/libs/c-ares)
+
+IF (NOT DLL_FOR)
+ CFLAGS(
+ -DCARES_STATICLIB
+ )
+ENDIF()
+
+SRCS(
+ ahost.c
+)
+
+END()
diff --git a/contrib/libs/c-ares/ares.h b/contrib/libs/c-ares/ares.h
index 3f8a6954d0..97ff396ed9 100644
--- a/contrib/libs/c-ares/ares.h
+++ b/contrib/libs/c-ares/ares.h
@@ -167,7 +167,7 @@ extern "C" {
#define ARES_OPT_ROTATE (1 << 14)
#define ARES_OPT_EDNSPSZ (1 << 15)
#define ARES_OPT_NOROTATE (1 << 16)
-#define ARES_OPT_RESOLVCONF (1 << 17)
+#define ARES_OPT_RESOLVCONF (1 << 17)
#define ARES_OPT_MAXTIMEOUTMS (1 << 18)
#define ARES_OPT_JITTER (1 << 19)
@@ -281,7 +281,7 @@ struct ares_options {
struct apattern *sortlist;
int nsort;
int ednspsz;
- char *resolvconf_path;
+ char *resolvconf_path;
};
struct hostent;
diff --git a/contrib/libs/c-ares/ares_android.c b/contrib/libs/c-ares/ares_android.c
index 5b00b8065c..750a855665 100644
--- a/contrib/libs/c-ares/ares_android.c
+++ b/contrib/libs/c-ares/ares_android.c
@@ -30,8 +30,8 @@ static jmethodID android_cm_active_net_mid = NULL;
static jmethodID android_cm_link_props_mid = NULL;
/* LinkProperties.getDnsServers */
static jmethodID android_lp_dns_servers_mid = NULL;
-/* LinkProperties.getDomains */
-static jmethodID android_lp_domains_mid = NULL;
+/* LinkProperties.getDomains */
+static jmethodID android_lp_domains_mid = NULL;
/* List.size */
static jmethodID android_list_size_mid = NULL;
/* List.get */
@@ -141,12 +141,12 @@ int ares_library_init_android(jobject connectivity_manager)
if (android_lp_dns_servers_mid == NULL)
goto cleanup;
- /* getDomains in API 21. */
- android_lp_domains_mid = jni_get_method_id(env, obj_cls, "getDomains",
- "()Ljava/lang/String;");
- if (android_lp_domains_mid == NULL)
- goto cleanup;
-
+ /* getDomains in API 21. */
+ android_lp_domains_mid = jni_get_method_id(env, obj_cls, "getDomains",
+ "()Ljava/lang/String;");
+ if (android_lp_domains_mid == NULL)
+ goto cleanup;
+
(*env)->DeleteLocalRef(env, obj_cls);
obj_cls = jni_get_class(env, "java/util/List");
if (obj_cls == NULL)
@@ -181,7 +181,7 @@ cleanup:
android_cm_active_net_mid = NULL;
android_cm_link_props_mid = NULL;
android_lp_dns_servers_mid = NULL;
- android_lp_domains_mid = NULL;
+ android_lp_domains_mid = NULL;
android_list_size_mid = NULL;
android_list_get_mid = NULL;
android_ia_host_addr_mid = NULL;
@@ -222,7 +222,7 @@ void ares_library_cleanup_android(void)
android_cm_active_net_mid = NULL;
android_cm_link_props_mid = NULL;
android_lp_dns_servers_mid = NULL;
- android_lp_domains_mid = NULL;
+ android_lp_domains_mid = NULL;
android_list_size_mid = NULL;
android_list_get_mid = NULL;
android_ia_host_addr_mid = NULL;
@@ -351,93 +351,93 @@ done:
(*android_jvm)->DetachCurrentThread(android_jvm);
return dns_list;
}
-
-char *ares_get_android_search_domains_list(void)
-{
- JNIEnv *env = NULL;
- jobject active_network = NULL;
- jobject link_properties = NULL;
- jstring domains = NULL;
- const char *domain;
- int res;
- char *domain_list = NULL;
- int need_detatch = 0;
-
- if (android_jvm == NULL || android_connectivity_manager == NULL)
- {
- return NULL;
- }
-
- if (android_cm_active_net_mid == NULL || android_cm_link_props_mid == NULL ||
- android_lp_domains_mid == NULL)
- {
- return NULL;
- }
-
- res = (*android_jvm)->GetEnv(android_jvm, (void **)&env, JNI_VERSION_1_6);
- if (res == JNI_EDETACHED)
- {
- env = NULL;
- res = (*android_jvm)->AttachCurrentThread(android_jvm, &env, NULL);
- need_detatch = 1;
- }
- if (res != JNI_OK || env == NULL)
- goto done;
-
- /* JNI below is equivalent to this Java code.
- import android.content.Context;
- import android.net.ConnectivityManager;
- import android.net.LinkProperties;
-
- ConnectivityManager cm = (ConnectivityManager)this.getApplicationContext()
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- Network an = cm.getActiveNetwork();
- LinkProperties lp = cm.getLinkProperties(an);
- String domains = lp.getDomains();
- for (String domain: domains.split(",")) {
- String d = domain;
- }
-
- Note: The JNI ConnectivityManager object and all method IDs were previously
- initialized in ares_library_init_android.
- */
-
- active_network = (*env)->CallObjectMethod(env, android_connectivity_manager,
- android_cm_active_net_mid);
- if (active_network == NULL)
- goto done;
-
- link_properties =
- (*env)->CallObjectMethod(env, android_connectivity_manager,
- android_cm_link_props_mid, active_network);
- if (link_properties == NULL)
- goto done;
-
- /* Get the domains. It is a common separated list of domains to search. */
- domains = (*env)->CallObjectMethod(env, link_properties,
- android_lp_domains_mid);
- if (domains == NULL)
- goto done;
-
- /* Split on , */
- domain = (*env)->GetStringUTFChars(env, domains, 0);
- domain_list = ares_strdup(domain);
- (*env)->ReleaseStringUTFChars(env, domains, domain);
- (*env)->DeleteLocalRef(env, domains);
-
-done:
- if ((*env)->ExceptionOccurred(env))
- (*env)->ExceptionClear(env);
-
- if (link_properties != NULL)
- (*env)->DeleteLocalRef(env, link_properties);
- if (active_network != NULL)
- (*env)->DeleteLocalRef(env, active_network);
-
- if (need_detatch)
- (*android_jvm)->DetachCurrentThread(android_jvm);
- return domain_list;
-}
+
+char *ares_get_android_search_domains_list(void)
+{
+ JNIEnv *env = NULL;
+ jobject active_network = NULL;
+ jobject link_properties = NULL;
+ jstring domains = NULL;
+ const char *domain;
+ int res;
+ char *domain_list = NULL;
+ int need_detatch = 0;
+
+ if (android_jvm == NULL || android_connectivity_manager == NULL)
+ {
+ return NULL;
+ }
+
+ if (android_cm_active_net_mid == NULL || android_cm_link_props_mid == NULL ||
+ android_lp_domains_mid == NULL)
+ {
+ return NULL;
+ }
+
+ res = (*android_jvm)->GetEnv(android_jvm, (void **)&env, JNI_VERSION_1_6);
+ if (res == JNI_EDETACHED)
+ {
+ env = NULL;
+ res = (*android_jvm)->AttachCurrentThread(android_jvm, &env, NULL);
+ need_detatch = 1;
+ }
+ if (res != JNI_OK || env == NULL)
+ goto done;
+
+ /* JNI below is equivalent to this Java code.
+ import android.content.Context;
+ import android.net.ConnectivityManager;
+ import android.net.LinkProperties;
+
+ ConnectivityManager cm = (ConnectivityManager)this.getApplicationContext()
+ .getSystemService(Context.CONNECTIVITY_SERVICE);
+ Network an = cm.getActiveNetwork();
+ LinkProperties lp = cm.getLinkProperties(an);
+ String domains = lp.getDomains();
+ for (String domain: domains.split(",")) {
+ String d = domain;
+ }
+
+ Note: The JNI ConnectivityManager object and all method IDs were previously
+ initialized in ares_library_init_android.
+ */
+
+ active_network = (*env)->CallObjectMethod(env, android_connectivity_manager,
+ android_cm_active_net_mid);
+ if (active_network == NULL)
+ goto done;
+
+ link_properties =
+ (*env)->CallObjectMethod(env, android_connectivity_manager,
+ android_cm_link_props_mid, active_network);
+ if (link_properties == NULL)
+ goto done;
+
+ /* Get the domains. It is a common separated list of domains to search. */
+ domains = (*env)->CallObjectMethod(env, link_properties,
+ android_lp_domains_mid);
+ if (domains == NULL)
+ goto done;
+
+ /* Split on , */
+ domain = (*env)->GetStringUTFChars(env, domains, 0);
+ domain_list = ares_strdup(domain);
+ (*env)->ReleaseStringUTFChars(env, domains, domain);
+ (*env)->DeleteLocalRef(env, domains);
+
+done:
+ if ((*env)->ExceptionOccurred(env))
+ (*env)->ExceptionClear(env);
+
+ if (link_properties != NULL)
+ (*env)->DeleteLocalRef(env, link_properties);
+ if (active_network != NULL)
+ (*env)->DeleteLocalRef(env, active_network);
+
+ if (need_detatch)
+ (*android_jvm)->DetachCurrentThread(android_jvm);
+ return domain_list;
+}
#else
/* warning: ISO C forbids an empty translation unit */
typedef int dummy_make_iso_compilers_happy;
diff --git a/contrib/libs/c-ares/ares_android.h b/contrib/libs/c-ares/ares_android.h
index 93fb75f585..99ca0223b6 100644
--- a/contrib/libs/c-ares/ares_android.h
+++ b/contrib/libs/c-ares/ares_android.h
@@ -19,7 +19,7 @@
#if defined(ANDROID) || defined(__ANDROID__)
char **ares_get_android_server_list(size_t max_servers, size_t *num_servers);
-char *ares_get_android_search_domains_list(void);
+char *ares_get_android_search_domains_list(void);
void ares_library_cleanup_android(void);
#endif
diff --git a/contrib/libs/c-ares/ares_config.h b/contrib/libs/c-ares/ares_config.h
index 6695a6ad21..13b9922074 100644
--- a/contrib/libs/c-ares/ares_config.h
+++ b/contrib/libs/c-ares/ares_config.h
@@ -122,10 +122,10 @@
#undef HAVE_GETSERVBYPORT_R
#endif
-#if defined(__ANDROID__)
-#undef HAVE_GETSERVBYPORT_R
-#endif
-
+#if defined(__ANDROID__)
+#undef HAVE_GETSERVBYPORT_R
+#endif
+
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
@@ -254,8 +254,8 @@
/* Define to 1 if you have the strcmpi function. */
/* #undef HAVE_STRCMPI */
-/* Potential ares_malloc/ares_free mismatch in ares_strdup.c/ares_strsplit.c. */
-/* #undef HAVE_STRDUP */
+/* Potential ares_malloc/ares_free mismatch in ares_strdup.c/ares_strsplit.c. */
+/* #undef HAVE_STRDUP */
/* Define to 1 if you have the stricmp function. */
/* #undef HAVE_STRICMP */
@@ -370,7 +370,7 @@
#define PACKAGE_NAME "c-ares"
/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "c-ares 1.15.0"
+#define PACKAGE_STRING "c-ares 1.15.0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "c-ares"
@@ -379,7 +379,7 @@
#define PACKAGE_URL ""
/* Define to the version of this package. */
-#define PACKAGE_VERSION "1.15.0"
+#define PACKAGE_VERSION "1.15.0"
/* a suitable file/device to read random data from */
#define RANDOM_FILE "/dev/urandom"
@@ -491,7 +491,7 @@
/* #undef USE_BLOCKING_SOCKETS */
/* Version number of package */
-#define VERSION "1.15.0"
+#define VERSION "1.15.0"
/* Define to avoid automatic inclusion of winsock.h */
/* #undef WIN32_LEAN_AND_MEAN */
diff --git a/contrib/libs/c-ares/ares_create_query.c b/contrib/libs/c-ares/ares_create_query.c
index 9efce17cfa..d60e1f25ef 100644
--- a/contrib/libs/c-ares/ares_create_query.c
+++ b/contrib/libs/c-ares/ares_create_query.c
@@ -98,10 +98,10 @@ int ares_create_query(const char *name, int dnsclass, int type,
*buflenp = 0;
*bufp = NULL;
- /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
- if (ares__is_onion_domain(name))
- return ARES_ENOTFOUND;
-
+ /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
+ if (ares__is_onion_domain(name))
+ return ARES_ENOTFOUND;
+
/* Allocate a memory area for the maximum size this packet might need. +2
* is for the length byte and zero termination if no dots or ecscaping is
* used.
@@ -192,7 +192,7 @@ int ares_create_query(const char *name, int dnsclass, int type,
* specified in RFC 1035 ("To simplify implementations, the total length of
* a domain name (i.e., label octets and label length octets) is restricted
* to 255 octets or less."). */
- if (buflen > (size_t)(MAXCDNAME + HFIXEDSZ + QFIXEDSZ +
+ if (buflen > (size_t)(MAXCDNAME + HFIXEDSZ + QFIXEDSZ +
(max_udp_size ? EDNSFIXEDSZ : 0))) {
ares_free (buf);
return ARES_EBADNAME;
diff --git a/contrib/libs/c-ares/ares_destroy.c b/contrib/libs/c-ares/ares_destroy.c
index fed2009ab3..97427d41da 100644
--- a/contrib/libs/c-ares/ares_destroy.c
+++ b/contrib/libs/c-ares/ares_destroy.c
@@ -36,8 +36,8 @@ void ares_destroy_options(struct ares_options *options)
ares_free(options->sortlist);
if(options->lookups)
ares_free(options->lookups);
- if(options->resolvconf_path)
- ares_free(options->resolvconf_path);
+ if(options->resolvconf_path)
+ ares_free(options->resolvconf_path);
}
void ares_destroy(ares_channel channel)
@@ -46,7 +46,7 @@ void ares_destroy(ares_channel channel)
struct query *query;
struct list_node* list_head;
struct list_node* list_node;
-
+
if (!channel)
return;
@@ -87,9 +87,9 @@ void ares_destroy(ares_channel channel)
if (channel->lookups)
ares_free(channel->lookups);
- if (channel->resolvconf_path)
- ares_free(channel->resolvconf_path);
-
+ if (channel->resolvconf_path)
+ ares_free(channel->resolvconf_path);
+
ares_free(channel);
}
diff --git a/contrib/libs/c-ares/ares_gethostbyname.c b/contrib/libs/c-ares/ares_gethostbyname.c
index ecd03e7931..a3b58be74f 100644
--- a/contrib/libs/c-ares/ares_gethostbyname.c
+++ b/contrib/libs/c-ares/ares_gethostbyname.c
@@ -95,13 +95,13 @@ void ares_gethostbyname(ares_channel channel, const char *name, int family,
return;
}
- /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
- if (ares__is_onion_domain(name))
- {
- callback(arg, ARES_ENOTFOUND, 0, NULL);
- return;
- }
-
+ /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
+ if (ares__is_onion_domain(name))
+ {
+ callback(arg, ARES_ENOTFOUND, 0, NULL);
+ return;
+ }
+
if (fake_hostent(name, family, callback, arg))
return;
diff --git a/contrib/libs/c-ares/ares_getnameinfo.c b/contrib/libs/c-ares/ares_getnameinfo.c
index 53f91ca845..b63bfe9819 100644
--- a/contrib/libs/c-ares/ares_getnameinfo.c
+++ b/contrib/libs/c-ares/ares_getnameinfo.c
@@ -440,14 +440,14 @@ STATIC_TESTABLE char *ares_striendstr(const char *s1, const char *s2)
}
return (char *)c1_begin;
}
-
-int ares__is_onion_domain(const char *name)
-{
- if (ares_striendstr(name, ".onion"))
- return 1;
-
- if (ares_striendstr(name, ".onion."))
- return 1;
-
- return 0;
-}
+
+int ares__is_onion_domain(const char *name)
+{
+ if (ares_striendstr(name, ".onion"))
+ return 1;
+
+ if (ares_striendstr(name, ".onion."))
+ return 1;
+
+ return 0;
+}
diff --git a/contrib/libs/c-ares/ares_init.c b/contrib/libs/c-ares/ares_init.c
index e06265c6a2..70d49b94e3 100644
--- a/contrib/libs/c-ares/ares_init.c
+++ b/contrib/libs/c-ares/ares_init.c
@@ -172,7 +172,7 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
channel->sock_config_cb_data = NULL;
channel->sock_funcs = NULL;
channel->sock_func_cb_data = NULL;
- channel->resolvconf_path = NULL;
+ channel->resolvconf_path = NULL;
channel->last_server = 0;
channel->last_timeout_processed = (time_t)now.tv_sec;
@@ -240,14 +240,14 @@ done:
/* Something failed; clean up memory we may have allocated. */
if (channel->servers)
ares_free(channel->servers);
- if (channel->ndomains != -1)
- ares_strsplit_free(channel->domains, channel->ndomains);
+ if (channel->ndomains != -1)
+ ares_strsplit_free(channel->domains, channel->ndomains);
if (channel->sortlist)
ares_free(channel->sortlist);
if(channel->lookups)
ares_free(channel->lookups);
- if(channel->resolvconf_path)
- ares_free(channel->resolvconf_path);
+ if(channel->resolvconf_path)
+ ares_free(channel->resolvconf_path);
ares_free(channel);
return status;
}
@@ -301,7 +301,7 @@ int ares_dup(ares_channel *dest, ares_channel src)
(*dest)->sock_func_cb_data = src->sock_func_cb_data;
strncpy((*dest)->local_dev_name, src->local_dev_name,
- sizeof((*dest)->local_dev_name));
+ sizeof((*dest)->local_dev_name));
(*dest)->local_ip4 = src->local_ip4;
memcpy((*dest)->local_ip6, src->local_ip6, sizeof(src->local_ip6));
@@ -357,9 +357,9 @@ int ares_save_options(ares_channel channel, struct ares_options *options,
ARES_OPT_JITTER);
(*optmask) |= (channel->rotate ? ARES_OPT_ROTATE : ARES_OPT_NOROTATE);
- if (channel->resolvconf_path)
- (*optmask) |= ARES_OPT_RESOLVCONF;
-
+ if (channel->resolvconf_path)
+ (*optmask) |= ARES_OPT_RESOLVCONF;
+
/* Copy easy stuff */
options->flags = channel->flags;
@@ -435,13 +435,13 @@ int ares_save_options(ares_channel channel, struct ares_options *options,
}
options->nsort = channel->nsort;
- /* copy path for resolv.conf file */
- if (channel->resolvconf_path) {
- options->resolvconf_path = ares_strdup(channel->resolvconf_path);
- if (!options->resolvconf_path)
- return ARES_ENOMEM;
- }
-
+ /* copy path for resolv.conf file */
+ if (channel->resolvconf_path) {
+ options->resolvconf_path = ares_strdup(channel->resolvconf_path);
+ if (!options->resolvconf_path)
+ return ARES_ENOMEM;
+ }
+
return ARES_SUCCESS;
}
@@ -557,14 +557,14 @@ static int init_by_options(ares_channel channel,
channel->nsort = options->nsort;
}
- /* Set path for resolv.conf file, if given. */
- if ((optmask & ARES_OPT_RESOLVCONF) && !channel->resolvconf_path)
- {
- channel->resolvconf_path = ares_strdup(options->resolvconf_path);
- if (!channel->resolvconf_path && options->resolvconf_path)
- return ARES_ENOMEM;
- }
-
+ /* Set path for resolv.conf file, if given. */
+ if ((optmask & ARES_OPT_RESOLVCONF) && !channel->resolvconf_path)
+ {
+ channel->resolvconf_path = ares_strdup(options->resolvconf_path);
+ if (!channel->resolvconf_path && options->resolvconf_path)
+ return ARES_ENOMEM;
+ }
+
channel->optmask = optmask;
return ARES_SUCCESS;
@@ -1211,7 +1211,7 @@ static int get_DNS_AdaptersAddresses(char **outptr)
/* Allocate room for another address, if necessary, else skip. */
if(addressesIndex == addressesSize) {
const size_t newSize = addressesSize + 4;
- Address * const newMem =
+ Address * const newMem =
(Address*)ares_realloc(addresses, sizeof(Address) * newSize);
if(newMem == NULL) {
continue;
@@ -1231,7 +1231,7 @@ static int get_DNS_AdaptersAddresses(char **outptr)
}
else
{
- addresses[addressesIndex].metric = (ULONG)-1;
+ addresses[addressesIndex].metric = (ULONG)-1;
}
/* Record insertion index to make qsort stable */
@@ -1268,12 +1268,12 @@ static int get_DNS_AdaptersAddresses(char **outptr)
/* Save the address as the next element in addresses. */
addresses[addressesIndex].metric =
getBestRouteMetric(&ipaaEntry->Luid,
- (SOCKADDR_INET*)(namesrvr.sa),
+ (SOCKADDR_INET*)(namesrvr.sa),
ipaaEntry->Ipv6Metric);
}
else
{
- addresses[addressesIndex].metric = (ULONG)-1;
+ addresses[addressesIndex].metric = (ULONG)-1;
}
/* Record insertion index to make qsort stable */
@@ -1318,7 +1318,7 @@ static int get_DNS_AdaptersAddresses(char **outptr)
done:
ares_free(addresses);
-
+
if (ipaa)
ares_free(ipaa);
@@ -1369,7 +1369,7 @@ static int get_DNS_Windows(char **outptr)
*
* Returns 1 and sets *outptr when returning a dynamically allocated string.
*
- * Implementation supports Windows Server 2003 and newer
+ * Implementation supports Windows Server 2003 and newer
*/
static int get_SuffixList_Windows(char **outptr)
{
@@ -1388,80 +1388,80 @@ static int get_SuffixList_Windows(char **outptr)
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
KEY_READ, &hKey) == ERROR_SUCCESS)
{
- get_REG_SZ(hKey, SEARCHLIST_KEY, outptr);
- if (get_REG_SZ(hKey, DOMAIN_KEY, &p))
- {
- commajoin(outptr, p);
- ares_free(p);
- p = NULL;
- }
- RegCloseKey(hKey);
- }
-
- if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NT_DNSCLIENT, 0,
- KEY_READ, &hKey) == ERROR_SUCCESS)
- {
- if (get_REG_SZ(hKey, SEARCHLIST_KEY, &p))
- {
- commajoin(outptr, p);
- ares_free(p);
- p = NULL;
- }
+ get_REG_SZ(hKey, SEARCHLIST_KEY, outptr);
+ if (get_REG_SZ(hKey, DOMAIN_KEY, &p))
+ {
+ commajoin(outptr, p);
+ ares_free(p);
+ p = NULL;
+ }
RegCloseKey(hKey);
}
+ if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NT_DNSCLIENT, 0,
+ KEY_READ, &hKey) == ERROR_SUCCESS)
+ {
+ if (get_REG_SZ(hKey, SEARCHLIST_KEY, &p))
+ {
+ commajoin(outptr, p);
+ ares_free(p);
+ p = NULL;
+ }
+ RegCloseKey(hKey);
+ }
+
/* 2. Connection Specific Search List composed of:
* a. Primary DNS Suffix */
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_DNSCLIENT, 0,
KEY_READ, &hKey) == ERROR_SUCCESS)
{
- if (get_REG_SZ(hKey, PRIMARYDNSSUFFIX_KEY, &p))
- {
- commajoin(outptr, p);
- ares_free(p);
- p = NULL;
- }
+ if (get_REG_SZ(hKey, PRIMARYDNSSUFFIX_KEY, &p))
+ {
+ commajoin(outptr, p);
+ ares_free(p);
+ p = NULL;
+ }
RegCloseKey(hKey);
}
/* b. Interface SearchList, Domain, DhcpDomain */
- if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY "\\" INTERFACES_KEY, 0,
+ if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY "\\" INTERFACES_KEY, 0,
KEY_READ, &hKey) == ERROR_SUCCESS)
{
- for(;;)
+ for(;;)
{
- keyNameBuffSize = sizeof(keyName);
- if (RegEnumKeyExA(hKey, keyIdx++, keyName, &keyNameBuffSize,
- 0, NULL, NULL, NULL)
- != ERROR_SUCCESS)
- break;
- if (RegOpenKeyExA(hKey, keyName, 0, KEY_QUERY_VALUE, &hKeyEnum)
- != ERROR_SUCCESS)
- continue;
+ keyNameBuffSize = sizeof(keyName);
+ if (RegEnumKeyExA(hKey, keyIdx++, keyName, &keyNameBuffSize,
+ 0, NULL, NULL, NULL)
+ != ERROR_SUCCESS)
+ break;
+ if (RegOpenKeyExA(hKey, keyName, 0, KEY_QUERY_VALUE, &hKeyEnum)
+ != ERROR_SUCCESS)
+ continue;
/* p can be comma separated (SearchList) */
- if (get_REG_SZ(hKeyEnum, SEARCHLIST_KEY, &p))
- {
- commajoin(outptr, p);
- ares_free(p);
- p = NULL;
- }
- if (get_REG_SZ(hKeyEnum, DOMAIN_KEY, &p))
- {
- commajoin(outptr, p);
- ares_free(p);
- p = NULL;
- }
- if (get_REG_SZ(hKeyEnum, DHCPDOMAIN_KEY, &p))
+ if (get_REG_SZ(hKeyEnum, SEARCHLIST_KEY, &p))
{
- commajoin(outptr, p);
- ares_free(p);
- p = NULL;
+ commajoin(outptr, p);
+ ares_free(p);
+ p = NULL;
}
- RegCloseKey(hKeyEnum);
+ if (get_REG_SZ(hKeyEnum, DOMAIN_KEY, &p))
+ {
+ commajoin(outptr, p);
+ ares_free(p);
+ p = NULL;
+ }
+ if (get_REG_SZ(hKeyEnum, DHCPDOMAIN_KEY, &p))
+ {
+ commajoin(outptr, p);
+ ares_free(p);
+ p = NULL;
+ }
+ RegCloseKey(hKeyEnum);
}
- RegCloseKey(hKey);
+ RegCloseKey(hKey);
}
-
+
return *outptr != NULL;
}
@@ -1558,7 +1558,7 @@ static int init_by_resolv_conf(ares_channel channel)
#elif defined(ANDROID) || defined(__ANDROID__)
unsigned int i;
char **dns_servers;
- char *domains;
+ char *domains;
size_t num_servers;
/* Use the Android connectivity manager to get a list
@@ -1583,12 +1583,12 @@ static int init_by_resolv_conf(ares_channel channel)
}
ares_free(dns_servers);
}
- if (channel->ndomains == -1)
- {
- domains = ares_get_android_search_domains_list();
- set_search(channel, domains);
- ares_free(domains);
- }
+ if (channel->ndomains == -1)
+ {
+ domains = ares_get_android_search_domains_list();
+ set_search(channel, domains);
+ ares_free(domains);
+ }
# ifdef HAVE___SYSTEM_PROPERTY_GET
/* Old way using the system property still in place as
@@ -1679,7 +1679,7 @@ static int init_by_resolv_conf(ares_channel channel)
size_t linesize;
int error;
int update_domains;
- const char *resolvconf_path;
+ const char *resolvconf_path;
/* Don't read resolv.conf and friends if we don't have to */
if (ARES_CONFIG_CHECK(channel))
@@ -1688,14 +1688,14 @@ static int init_by_resolv_conf(ares_channel channel)
/* Only update search domains if they're not already specified */
update_domains = (channel->ndomains == -1);
- /* Support path for resolvconf filename set by ares_init_options */
- if(channel->resolvconf_path) {
- resolvconf_path = channel->resolvconf_path;
- } else {
- resolvconf_path = PATH_RESOLV_CONF;
- }
-
- fp = fopen(resolvconf_path, "r");
+ /* Support path for resolvconf filename set by ares_init_options */
+ if(channel->resolvconf_path) {
+ resolvconf_path = channel->resolvconf_path;
+ } else {
+ resolvconf_path = PATH_RESOLV_CONF;
+ }
+
+ fp = fopen(resolvconf_path, "r");
if (fp) {
while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
{
@@ -1706,10 +1706,10 @@ static int init_by_resolv_conf(ares_channel channel)
else if ((p = try_config(line, "search", ';')) && update_domains)
status = set_search(channel, p);
else if ((p = try_config(line, "nameserver", ';')) &&
- channel->nservers == -1)
+ channel->nservers == -1)
status = config_nameserver(&servers, &nservers, p);
else if ((p = try_config(line, "sortlist", ';')) &&
- channel->nsort == -1)
+ channel->nsort == -1)
status = config_sortlist(&sortlist, &nsort, p);
else if ((p = try_config(line, "options", ';')))
status = set_options(channel, p);
@@ -1729,7 +1729,7 @@ static int init_by_resolv_conf(ares_channel channel)
break;
default:
DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
- error, strerror(error)));
+ error, strerror(error)));
DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
status = ARES_EFILE;
}
@@ -1997,11 +1997,11 @@ static int init_by_defaults(ares_channel channel)
ares_free(channel->lookups);
channel->lookups = NULL;
}
-
- if(channel->resolvconf_path) {
- ares_free(channel->resolvconf_path);
- channel->resolvconf_path = NULL;
- }
+
+ if(channel->resolvconf_path) {
+ ares_free(channel->resolvconf_path);
+ channel->resolvconf_path = NULL;
+ }
}
if(hostname)
@@ -2071,76 +2071,76 @@ static int config_lookup(ares_channel channel, const char *str,
#endif /* !WIN32 & !WATT32 & !ANDROID & !__ANDROID__ & !CARES_USE_LIBRESOLV */
#ifndef WATT32
-/* Validate that the ip address matches the subnet (network base and network
- * mask) specified. Addresses are specified in standard Network Byte Order as
- * 16 bytes, and the netmask is 0 to 128 (bits).
- */
-static int ares_ipv6_subnet_matches(const unsigned char netbase[16],
- unsigned char netmask,
- const unsigned char ipaddr[16])
-{
- unsigned char mask[16] = { 0 };
- unsigned char i;
-
- /* Misuse */
- if (netmask > 128)
- return 0;
-
- /* Quickly set whole bytes */
- memset(mask, 0xFF, netmask / 8);
-
- /* Set remaining bits */
- if(netmask % 8) {
- mask[netmask / 8] = (unsigned char)(0xff << (8 - (netmask % 8)));
- }
-
- for (i=0; i<16; i++) {
- if ((netbase[i] & mask[i]) != (ipaddr[i] & mask[i]))
- return 0;
- }
-
- return 1;
-}
-
-/* Return true iff the IPv6 ipaddr is blacklisted. */
-static int ares_ipv6_server_blacklisted(const unsigned char ipaddr[16])
-{
- /* A list of blacklisted IPv6 subnets. */
- const struct {
- const unsigned char netbase[16];
- unsigned char netmask;
- } blacklist[] = {
- /* fec0::/10 was deprecated by [RFC3879] in September 2004. Formerly a
- * Site-Local scoped address prefix. These are never valid DNS servers,
- * but are known to be returned at least sometimes on Windows and Android.
- */
- {
- {
- 0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
- },
- 10
- }
- };
- size_t i;
-
- /* See if ipaddr matches any of the entries in the blacklist. */
- for (i = 0; i < sizeof(blacklist) / sizeof(blacklist[0]); ++i) {
- if (ares_ipv6_subnet_matches(
- blacklist[i].netbase, blacklist[i].netmask, ipaddr))
- return 1;
- }
- return 0;
-}
-
-/* Add the IPv4 or IPv6 nameservers in str (separated by commas) to the
- * servers list, updating servers and nservers as required.
- *
- * This will silently ignore blacklisted IPv6 nameservers as detected by
- * ares_ipv6_server_blacklisted().
- *
- * Returns an error code on failure, else ARES_SUCCESS.
- */
+/* Validate that the ip address matches the subnet (network base and network
+ * mask) specified. Addresses are specified in standard Network Byte Order as
+ * 16 bytes, and the netmask is 0 to 128 (bits).
+ */
+static int ares_ipv6_subnet_matches(const unsigned char netbase[16],
+ unsigned char netmask,
+ const unsigned char ipaddr[16])
+{
+ unsigned char mask[16] = { 0 };
+ unsigned char i;
+
+ /* Misuse */
+ if (netmask > 128)
+ return 0;
+
+ /* Quickly set whole bytes */
+ memset(mask, 0xFF, netmask / 8);
+
+ /* Set remaining bits */
+ if(netmask % 8) {
+ mask[netmask / 8] = (unsigned char)(0xff << (8 - (netmask % 8)));
+ }
+
+ for (i=0; i<16; i++) {
+ if ((netbase[i] & mask[i]) != (ipaddr[i] & mask[i]))
+ return 0;
+ }
+
+ return 1;
+}
+
+/* Return true iff the IPv6 ipaddr is blacklisted. */
+static int ares_ipv6_server_blacklisted(const unsigned char ipaddr[16])
+{
+ /* A list of blacklisted IPv6 subnets. */
+ const struct {
+ const unsigned char netbase[16];
+ unsigned char netmask;
+ } blacklist[] = {
+ /* fec0::/10 was deprecated by [RFC3879] in September 2004. Formerly a
+ * Site-Local scoped address prefix. These are never valid DNS servers,
+ * but are known to be returned at least sometimes on Windows and Android.
+ */
+ {
+ {
+ 0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ },
+ 10
+ }
+ };
+ size_t i;
+
+ /* See if ipaddr matches any of the entries in the blacklist. */
+ for (i = 0; i < sizeof(blacklist) / sizeof(blacklist[0]); ++i) {
+ if (ares_ipv6_subnet_matches(
+ blacklist[i].netbase, blacklist[i].netmask, ipaddr))
+ return 1;
+ }
+ return 0;
+}
+
+/* Add the IPv4 or IPv6 nameservers in str (separated by commas) to the
+ * servers list, updating servers and nservers as required.
+ *
+ * This will silently ignore blacklisted IPv6 nameservers as detected by
+ * ares_ipv6_server_blacklisted().
+ *
+ * Returns an error code on failure, else ARES_SUCCESS.
+ */
static int config_nameserver(struct server_state **servers, int *nservers,
char *str)
{
@@ -2175,10 +2175,10 @@ static int config_nameserver(struct server_state **servers, int *nservers,
/* Convert textual address to binary format. */
if (ares_inet_pton(AF_INET, txtaddr, &host.addrV4) == 1)
host.family = AF_INET;
- else if (ares_inet_pton(AF_INET6, txtaddr, &host.addrV6) == 1
- /* Silently skip blacklisted IPv6 servers. */
- && !ares_ipv6_server_blacklisted(
- (const unsigned char *)&host.addrV6))
+ else if (ares_inet_pton(AF_INET6, txtaddr, &host.addrV6) == 1
+ /* Silently skip blacklisted IPv6 servers. */
+ && !ares_ipv6_server_blacklisted(
+ (const unsigned char *)&host.addrV6))
host.family = AF_INET6;
else
continue;
@@ -2301,22 +2301,22 @@ static int config_sortlist(struct apattern **sortlist, int *nsort,
static int set_search(ares_channel channel, const char *str)
{
- size_t cnt;
+ size_t cnt;
if(channel->ndomains != -1) {
/* LCOV_EXCL_START: all callers check ndomains == -1 */
/* if we already have some domains present, free them first */
- ares_strsplit_free(channel->domains, channel->ndomains);
+ ares_strsplit_free(channel->domains, channel->ndomains);
channel->domains = NULL;
channel->ndomains = -1;
} /* LCOV_EXCL_STOP */
channel->domains = ares_strsplit(str, ", ", 1, &cnt);
- channel->ndomains = (int)cnt;
- if (channel->domains == NULL || channel->ndomains == 0) {
- channel->domains = NULL;
- channel->ndomains = -1;
- }
+ channel->ndomains = (int)cnt;
+ if (channel->domains == NULL || channel->ndomains == 0) {
+ channel->domains = NULL;
+ channel->ndomains = -1;
+ }
return ARES_SUCCESS;
}
diff --git a/contrib/libs/c-ares/ares_library_init.c b/contrib/libs/c-ares/ares_library_init.c
index 3c7ad37200..982312f7fd 100644
--- a/contrib/libs/c-ares/ares_library_init.c
+++ b/contrib/libs/c-ares/ares_library_init.c
@@ -43,19 +43,19 @@ static unsigned int ares_initialized;
static int ares_init_flags;
/* library-private global vars with visibility across the whole library */
-#if defined(WIN32)
-/* We need indirections to handle Windows DLL rules. */
-static void *default_malloc(size_t size) { return malloc(size); }
-static void *default_realloc(void *p, size_t size) { return realloc(p, size); }
-static void default_free(void *p) { free(p); }
-#else
-# define default_malloc malloc
-# define default_realloc realloc
-# define default_free free
-#endif
-void *(*ares_malloc)(size_t size) = default_malloc;
-void *(*ares_realloc)(void *ptr, size_t size) = default_realloc;
-void (*ares_free)(void *ptr) = default_free;
+#if defined(WIN32)
+/* We need indirections to handle Windows DLL rules. */
+static void *default_malloc(size_t size) { return malloc(size); }
+static void *default_realloc(void *p, size_t size) { return realloc(p, size); }
+static void default_free(void *p) { free(p); }
+#else
+# define default_malloc malloc
+# define default_realloc realloc
+# define default_free free
+#endif
+void *(*ares_malloc)(size_t size) = default_malloc;
+void *(*ares_realloc)(void *ptr, size_t size) = default_realloc;
+void (*ares_free)(void *ptr) = default_free;
#ifdef USE_WINSOCK
static HMODULE hnd_iphlpapi;
diff --git a/contrib/libs/c-ares/ares_options.c b/contrib/libs/c-ares/ares_options.c
index de49de4625..aff083c292 100644
--- a/contrib/libs/c-ares/ares_options.c
+++ b/contrib/libs/c-ares/ares_options.c
@@ -153,9 +153,9 @@ int ares_set_servers(ares_channel channel,
if (!channel)
return ARES_ENODATA;
- if (!ares__is_list_empty(&channel->all_queries))
- return ARES_ENOTIMP;
-
+ if (!ares__is_list_empty(&channel->all_queries))
+ return ARES_ENOTIMP;
+
ares__destroy_servers_state(channel);
for (srvr = servers; srvr; srvr = srvr->next)
@@ -205,9 +205,9 @@ int ares_set_servers_ports(ares_channel channel,
if (!channel)
return ARES_ENODATA;
- if (!ares__is_list_empty(&channel->all_queries))
- return ARES_ENOTIMP;
-
+ if (!ares__is_list_empty(&channel->all_queries))
+ return ARES_ENOTIMP;
+
ares__destroy_servers_state(channel);
for (srvr = servers; srvr; srvr = srvr->next)
diff --git a/contrib/libs/c-ares/ares_parse_ptr_reply.c b/contrib/libs/c-ares/ares_parse_ptr_reply.c
index 0e2b064bb4..0c08dfb933 100644
--- a/contrib/libs/c-ares/ares_parse_ptr_reply.c
+++ b/contrib/libs/c-ares/ares_parse_ptr_reply.c
@@ -57,7 +57,7 @@ int ares_parse_ptr_reply(const unsigned char *abuf, int alen, const void *addr,
int aliascnt = 0;
int alias_alloc = 8;
char ** aliases;
- size_t rr_data_len;
+ size_t rr_data_len;
/* Set *host to NULL for all failure cases. */
*host = NULL;
@@ -133,15 +133,15 @@ int ares_parse_ptr_reply(const unsigned char *abuf, int alen, const void *addr,
if (hostname)
ares_free(hostname);
hostname = rr_data;
- rr_data_len = strlen(rr_data)+1;
- aliases[aliascnt] = ares_malloc(rr_data_len * sizeof(char));
+ rr_data_len = strlen(rr_data)+1;
+ aliases[aliascnt] = ares_malloc(rr_data_len * sizeof(char));
if (!aliases[aliascnt])
{
ares_free(rr_name);
status = ARES_ENOMEM;
break;
}
- strncpy(aliases[aliascnt], rr_data, rr_data_len);
+ strncpy(aliases[aliascnt], rr_data, rr_data_len);
aliascnt++;
if (aliascnt >= alias_alloc) {
char **ptr;
diff --git a/contrib/libs/c-ares/ares_private.h b/contrib/libs/c-ares/ares_private.h
index 3312ed1932..3c40da8ed1 100644
--- a/contrib/libs/c-ares/ares_private.h
+++ b/contrib/libs/c-ares/ares_private.h
@@ -57,19 +57,19 @@
#if defined(WIN32) && !defined(WATT32)
-#define WIN_NS_9X "System\\CurrentControlSet\\Services\\VxD\\MSTCP"
-#define WIN_NS_NT_KEY "System\\CurrentControlSet\\Services\\Tcpip\\Parameters"
-#define WIN_DNSCLIENT "Software\\Policies\\Microsoft\\System\\DNSClient"
-#define WIN_NT_DNSCLIENT "Software\\Policies\\Microsoft\\Windows NT\\DNSClient"
-#define NAMESERVER "NameServer"
-#define DHCPNAMESERVER "DhcpNameServer"
-#define DATABASEPATH "DatabasePath"
-#define WIN_PATH_HOSTS "\\hosts"
-#define SEARCHLIST_KEY "SearchList"
+#define WIN_NS_9X "System\\CurrentControlSet\\Services\\VxD\\MSTCP"
+#define WIN_NS_NT_KEY "System\\CurrentControlSet\\Services\\Tcpip\\Parameters"
+#define WIN_DNSCLIENT "Software\\Policies\\Microsoft\\System\\DNSClient"
+#define WIN_NT_DNSCLIENT "Software\\Policies\\Microsoft\\Windows NT\\DNSClient"
+#define NAMESERVER "NameServer"
+#define DHCPNAMESERVER "DhcpNameServer"
+#define DATABASEPATH "DatabasePath"
+#define WIN_PATH_HOSTS "\\hosts"
+#define SEARCHLIST_KEY "SearchList"
#define PRIMARYDNSSUFFIX_KEY "PrimaryDNSSuffix"
-#define INTERFACES_KEY "Interfaces"
-#define DOMAIN_KEY "Domain"
-#define DHCPDOMAIN_KEY "DhcpDomain"
+#define INTERFACES_KEY "Interfaces"
+#define DOMAIN_KEY "Domain"
+#define DHCPDOMAIN_KEY "DhcpDomain"
#elif defined(WATT32)
@@ -106,7 +106,7 @@
#endif
#include "ares_strdup.h"
-#include "ares_strsplit.h"
+#include "ares_strsplit.h"
#ifndef HAVE_STRCASECMP
# include "ares_strcasecmp.h"
@@ -333,14 +333,14 @@ struct ares_channeldata {
const struct ares_socket_functions * sock_funcs;
void *sock_func_cb_data;
-
- /* Path for resolv.conf file, configurable via ares_options */
- char *resolvconf_path;
+
+ /* Path for resolv.conf file, configurable via ares_options */
+ char *resolvconf_path;
};
-/* Does the domain end in ".onion" or ".onion."? Case-insensitive. */
-int ares__is_onion_domain(const char *name);
-
+/* Does the domain end in ".onion" or ".onion."? Case-insensitive. */
+int ares__is_onion_domain(const char *name);
+
/* Memory management functions */
extern void *(*ares_malloc)(size_t size);
extern void *(*ares_realloc)(void *ptr, size_t size);
diff --git a/contrib/libs/c-ares/ares_process.c b/contrib/libs/c-ares/ares_process.c
index 25095d0f05..034cd2c4ae 100644
--- a/contrib/libs/c-ares/ares_process.c
+++ b/contrib/libs/c-ares/ares_process.c
@@ -53,7 +53,7 @@
#include <assert.h>
#include <fcntl.h>
-#include <limits.h>
+#include <limits.h>
#include "ares.h"
#include "ares_dns.h"
@@ -872,32 +872,32 @@ void ares__send_query(ares_channel channel, struct query *query,
return;
}
}
-
- /* For each trip through the entire server list, double the channel's
- * assigned timeout, avoiding overflow. If channel->timeout is negative,
- * leave it as-is, even though that should be impossible here.
- */
- timeplus = channel->timeout;
- {
- /* How many times do we want to double it? Presume sane values here. */
- const int shift = query->try_count / channel->nservers;
-
- /* Is there enough room to shift timeplus left that many times?
- *
- * To find out, confirm that all of the bits we'll shift away are zero.
- * Stop considering a shift if we get to the point where we could shift
- * a 1 into the sign bit (i.e. when shift is within two of the bit
- * count).
- *
- * This has the side benefit of leaving negative numbers unchanged.
- */
- if(shift <= (int)(sizeof(int) * CHAR_BIT - 1)
- && (timeplus >> (sizeof(int) * CHAR_BIT - 1 - shift)) == 0)
- {
- timeplus <<= shift;
- }
- }
-
+
+ /* For each trip through the entire server list, double the channel's
+ * assigned timeout, avoiding overflow. If channel->timeout is negative,
+ * leave it as-is, even though that should be impossible here.
+ */
+ timeplus = channel->timeout;
+ {
+ /* How many times do we want to double it? Presume sane values here. */
+ const int shift = query->try_count / channel->nservers;
+
+ /* Is there enough room to shift timeplus left that many times?
+ *
+ * To find out, confirm that all of the bits we'll shift away are zero.
+ * Stop considering a shift if we get to the point where we could shift
+ * a 1 into the sign bit (i.e. when shift is within two of the bit
+ * count).
+ *
+ * This has the side benefit of leaving negative numbers unchanged.
+ */
+ if(shift <= (int)(sizeof(int) * CHAR_BIT - 1)
+ && (timeplus >> (sizeof(int) * CHAR_BIT - 1 - shift)) == 0)
+ {
+ timeplus <<= shift;
+ }
+ }
+
if (channel->maxtimeout != -1 && timeplus > channel->maxtimeout)
timeplus = channel->maxtimeout;
diff --git a/contrib/libs/c-ares/ares_rules.h b/contrib/libs/c-ares/ares_rules.h
index cac23cf2e3..628b80b1b7 100644
--- a/contrib/libs/c-ares/ares_rules.h
+++ b/contrib/libs/c-ares/ares_rules.h
@@ -83,7 +83,7 @@
/*
* Verify that the size previously defined and expected for
- * ares_socklen_t is actually the same as the one reported
+ * ares_socklen_t is actually the same as the one reported
* by sizeof() at compile time.
*/
diff --git a/contrib/libs/c-ares/ares_search.c b/contrib/libs/c-ares/ares_search.c
index c4b0424f5b..4f5268dfe3 100644
--- a/contrib/libs/c-ares/ares_search.c
+++ b/contrib/libs/c-ares/ares_search.c
@@ -52,13 +52,13 @@ void ares_search(ares_channel channel, const char *name, int dnsclass,
const char *p;
int status, ndots;
- /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
- if (ares__is_onion_domain(name))
- {
- callback(arg, ARES_ENOTFOUND, 0, NULL, 0);
- return;
- }
-
+ /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
+ if (ares__is_onion_domain(name))
+ {
+ callback(arg, ARES_ENOTFOUND, 0, NULL, 0);
+ return;
+ }
+
/* If name only yields one domain to search, then we don't have
* to keep extra state, so just do an ares_query().
*/
diff --git a/contrib/libs/c-ares/ares_send.c b/contrib/libs/c-ares/ares_send.c
index f4f1f95119..cc87a9dfa7 100644
--- a/contrib/libs/c-ares/ares_send.c
+++ b/contrib/libs/c-ares/ares_send.c
@@ -60,12 +60,12 @@ void ares_send(ares_channel channel, const unsigned char *qbuf, int qlen,
callback(arg, ARES_ENOMEM, 0, NULL, 0);
return;
}
- if (channel->nservers < 1)
- {
- ares_free(query);
- callback(arg, ARES_ESERVFAIL, 0, NULL, 0);
- return;
- }
+ if (channel->nservers < 1)
+ {
+ ares_free(query);
+ callback(arg, ARES_ESERVFAIL, 0, NULL, 0);
+ return;
+ }
query->server_info = ares_malloc(channel->nservers *
sizeof(query->server_info[0]));
if (!query->server_info)
diff --git a/contrib/libs/c-ares/ares_strsplit.c b/contrib/libs/c-ares/ares_strsplit.c
index b57a30f2a9..1a4ba444f9 100644
--- a/contrib/libs/c-ares/ares_strsplit.c
+++ b/contrib/libs/c-ares/ares_strsplit.c
@@ -1,174 +1,174 @@
-/* Copyright (C) 2018 by John Schember <john@nachtimwald.com>
- *
- * Permission to use, copy, modify, and distribute this
- * software and its documentation for any purpose and without
- * fee is hereby granted, provided that the above copyright
- * notice appear in all copies and that both that copyright
- * notice and this permission notice appear in supporting
- * documentation, and that the name of M.I.T. not be used in
- * advertising or publicity pertaining to distribution of the
- * software without specific, written prior permission.
- * M.I.T. makes no representations about the suitability of
- * this software for any purpose. It is provided "as is"
- * without express or implied warranty.
- */
-
-#include "ares_setup.h"
-#include "ares_strsplit.h"
-#include "ares.h"
-#include "ares_private.h"
-
-static int list_contains(char * const *list, size_t num_elem, const char *str, int insensitive)
-{
- size_t len;
- size_t i;
-
- len = strlen(str);
- for (i=0; i<num_elem; i++)
- {
- if (insensitive)
- {
-#ifdef WIN32
- if (strnicmp(list[i], str, len) == 0)
-#else
- if (strncasecmp(list[i], str, len) == 0)
-#endif
- return 1;
- }
- else
- {
- if (strncmp(list[i], str, len) == 0)
- return 1;
- }
- }
-
- return 0;
-}
-
-static int is_delim(char c, const char *delims, size_t num_delims)
-{
- size_t i;
-
- for (i=0; i<num_delims; i++)
- {
- if (c == delims[i])
- return 1;
- }
- return 0;
-}
-
-
-void ares_strsplit_free(char **elms, size_t num_elm)
-{
- size_t i;
-
- if (elms == NULL)
- return;
-
- for (i=0; i<num_elm; i++)
- ares_free(elms[i]);
- ares_free(elms);
-}
-
-
-char **ares_strsplit(const char *in, const char *delms, int make_set, size_t *num_elm)
-{
- char *parsestr;
- char **temp;
- char **out;
- size_t cnt;
- size_t nelms;
- size_t in_len;
- size_t num_delims;
- size_t i;
-
- if (in == NULL || delms == NULL || num_elm == NULL)
- return NULL;
-
- *num_elm = 0;
-
- in_len = strlen(in);
- num_delims = strlen(delms);
-
- /* Figure out how many elements. */
- nelms = 1;
- for (i=0; i<in_len; i++)
- {
- if (is_delim(in[i], delms, num_delims))
- {
- nelms++;
- }
- }
-
- /* Copy of input so we can cut it up. */
- parsestr = ares_strdup(in);
- if (parsestr == NULL)
- return NULL;
-
- /* Temporary array to store locations of start of each element
- * within parsestr. */
- temp = ares_malloc(nelms * sizeof(*temp));
- if (temp == NULL)
- {
- ares_free(parsestr);
- return NULL;
- }
- temp[0] = parsestr;
- cnt = 1;
- for (i=0; i<in_len && cnt<nelms; i++)
- {
- if (!is_delim(parsestr[i], delms, num_delims))
- continue;
-
- /* Replace sep with NULL. */
- parsestr[i] = '\0';
- /* Add the pointer to the array of elements */
- temp[cnt] = parsestr+i+1;
- cnt++;
- }
-
- /* Copy each element to our output array. */
- out = ares_malloc(nelms * sizeof(*out));
- if (out == NULL)
- {
- ares_free(parsestr);
- ares_free(temp);
- return NULL;
- }
-
- nelms = 0;
- for (i=0; i<cnt; i++)
- {
- if (temp[i][0] == '\0')
- continue;
-
- if (make_set && list_contains(out, nelms, temp[i], 1))
- continue;
-
- out[nelms] = ares_strdup(temp[i]);
- if (out[nelms] == NULL)
- {
- ares_strsplit_free(out, nelms);
- ares_free(parsestr);
- ares_free(temp);
- return NULL;
- }
- nelms++;
- }
-
-
- /* If there are no elements don't return an empty allocated
- * array. */
- if (nelms == 0)
- {
- ares_strsplit_free(out, nelms);
- out = NULL;
- }
-
- /* Get the true number of elements (recalculated because of make_set) */
- *num_elm = nelms;
-
- ares_free(parsestr);
- ares_free(temp);
- return out;
-}
+/* Copyright (C) 2018 by John Schember <john@nachtimwald.com>
+ *
+ * Permission to use, copy, modify, and distribute this
+ * software and its documentation for any purpose and without
+ * fee is hereby granted, provided that the above copyright
+ * notice appear in all copies and that both that copyright
+ * notice and this permission notice appear in supporting
+ * documentation, and that the name of M.I.T. not be used in
+ * advertising or publicity pertaining to distribution of the
+ * software without specific, written prior permission.
+ * M.I.T. makes no representations about the suitability of
+ * this software for any purpose. It is provided "as is"
+ * without express or implied warranty.
+ */
+
+#include "ares_setup.h"
+#include "ares_strsplit.h"
+#include "ares.h"
+#include "ares_private.h"
+
+static int list_contains(char * const *list, size_t num_elem, const char *str, int insensitive)
+{
+ size_t len;
+ size_t i;
+
+ len = strlen(str);
+ for (i=0; i<num_elem; i++)
+ {
+ if (insensitive)
+ {
+#ifdef WIN32
+ if (strnicmp(list[i], str, len) == 0)
+#else
+ if (strncasecmp(list[i], str, len) == 0)
+#endif
+ return 1;
+ }
+ else
+ {
+ if (strncmp(list[i], str, len) == 0)
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+static int is_delim(char c, const char *delims, size_t num_delims)
+{
+ size_t i;
+
+ for (i=0; i<num_delims; i++)
+ {
+ if (c == delims[i])
+ return 1;
+ }
+ return 0;
+}
+
+
+void ares_strsplit_free(char **elms, size_t num_elm)
+{
+ size_t i;
+
+ if (elms == NULL)
+ return;
+
+ for (i=0; i<num_elm; i++)
+ ares_free(elms[i]);
+ ares_free(elms);
+}
+
+
+char **ares_strsplit(const char *in, const char *delms, int make_set, size_t *num_elm)
+{
+ char *parsestr;
+ char **temp;
+ char **out;
+ size_t cnt;
+ size_t nelms;
+ size_t in_len;
+ size_t num_delims;
+ size_t i;
+
+ if (in == NULL || delms == NULL || num_elm == NULL)
+ return NULL;
+
+ *num_elm = 0;
+
+ in_len = strlen(in);
+ num_delims = strlen(delms);
+
+ /* Figure out how many elements. */
+ nelms = 1;
+ for (i=0; i<in_len; i++)
+ {
+ if (is_delim(in[i], delms, num_delims))
+ {
+ nelms++;
+ }
+ }
+
+ /* Copy of input so we can cut it up. */
+ parsestr = ares_strdup(in);
+ if (parsestr == NULL)
+ return NULL;
+
+ /* Temporary array to store locations of start of each element
+ * within parsestr. */
+ temp = ares_malloc(nelms * sizeof(*temp));
+ if (temp == NULL)
+ {
+ ares_free(parsestr);
+ return NULL;
+ }
+ temp[0] = parsestr;
+ cnt = 1;
+ for (i=0; i<in_len && cnt<nelms; i++)
+ {
+ if (!is_delim(parsestr[i], delms, num_delims))
+ continue;
+
+ /* Replace sep with NULL. */
+ parsestr[i] = '\0';
+ /* Add the pointer to the array of elements */
+ temp[cnt] = parsestr+i+1;
+ cnt++;
+ }
+
+ /* Copy each element to our output array. */
+ out = ares_malloc(nelms * sizeof(*out));
+ if (out == NULL)
+ {
+ ares_free(parsestr);
+ ares_free(temp);
+ return NULL;
+ }
+
+ nelms = 0;
+ for (i=0; i<cnt; i++)
+ {
+ if (temp[i][0] == '\0')
+ continue;
+
+ if (make_set && list_contains(out, nelms, temp[i], 1))
+ continue;
+
+ out[nelms] = ares_strdup(temp[i]);
+ if (out[nelms] == NULL)
+ {
+ ares_strsplit_free(out, nelms);
+ ares_free(parsestr);
+ ares_free(temp);
+ return NULL;
+ }
+ nelms++;
+ }
+
+
+ /* If there are no elements don't return an empty allocated
+ * array. */
+ if (nelms == 0)
+ {
+ ares_strsplit_free(out, nelms);
+ out = NULL;
+ }
+
+ /* Get the true number of elements (recalculated because of make_set) */
+ *num_elm = nelms;
+
+ ares_free(parsestr);
+ ares_free(temp);
+ return out;
+}
diff --git a/contrib/libs/c-ares/ares_strsplit.h b/contrib/libs/c-ares/ares_strsplit.h
index e00fd14dd5..93f7948a77 100644
--- a/contrib/libs/c-ares/ares_strsplit.h
+++ b/contrib/libs/c-ares/ares_strsplit.h
@@ -1,43 +1,43 @@
-#ifndef HEADER_CARES_STRSPLIT_H
-#define HEADER_CARES_STRSPLIT_H
-
-/* Copyright (C) 2018 by John Schember <john@nachtimwald.com>
- *
- * Permission to use, copy, modify, and distribute this
- * software and its documentation for any purpose and without
- * fee is hereby granted, provided that the above copyright
- * notice appear in all copies and that both that copyright
- * notice and this permission notice appear in supporting
- * documentation, and that the name of M.I.T. not be used in
- * advertising or publicity pertaining to distribution of the
- * software without specific, written prior permission.
- * M.I.T. makes no representations about the suitability of
- * this software for any purpose. It is provided "as is"
- * without express or implied warranty.
- */
-
-#include "ares_setup.h"
-
-/* Split a string on delem skipping empty elements.
- *
- * param in String to split.
- * param delims String of characters to treat as a delimitor.
- * Each character in the string is a delimitor so
- * there can be multiple delimitors to split on.
- * E.g. ", " will split on all comma's and spaces.
- * param make_set Have the list be a Set where there are no
- * duplicate entries. 1 for true, 0 or false.
- * param num_elm Return parameter of the number of elements
- * in the result array.
- *
- * returns an allocated array of allocated string elements.
- *
- */
-char **ares_strsplit(const char *in, const char *delms, int make_set, size_t *num_elm);
-
-/* Frees the result returned from ares_strsplit(). */
-void ares_strsplit_free(char **elms, size_t num_elm);
-
-
-#endif /* HEADER_CARES_STRSPLIT_H */
-
+#ifndef HEADER_CARES_STRSPLIT_H
+#define HEADER_CARES_STRSPLIT_H
+
+/* Copyright (C) 2018 by John Schember <john@nachtimwald.com>
+ *
+ * Permission to use, copy, modify, and distribute this
+ * software and its documentation for any purpose and without
+ * fee is hereby granted, provided that the above copyright
+ * notice appear in all copies and that both that copyright
+ * notice and this permission notice appear in supporting
+ * documentation, and that the name of M.I.T. not be used in
+ * advertising or publicity pertaining to distribution of the
+ * software without specific, written prior permission.
+ * M.I.T. makes no representations about the suitability of
+ * this software for any purpose. It is provided "as is"
+ * without express or implied warranty.
+ */
+
+#include "ares_setup.h"
+
+/* Split a string on delem skipping empty elements.
+ *
+ * param in String to split.
+ * param delims String of characters to treat as a delimitor.
+ * Each character in the string is a delimitor so
+ * there can be multiple delimitors to split on.
+ * E.g. ", " will split on all comma's and spaces.
+ * param make_set Have the list be a Set where there are no
+ * duplicate entries. 1 for true, 0 or false.
+ * param num_elm Return parameter of the number of elements
+ * in the result array.
+ *
+ * returns an allocated array of allocated string elements.
+ *
+ */
+char **ares_strsplit(const char *in, const char *delms, int make_set, size_t *num_elm);
+
+/* Frees the result returned from ares_strsplit(). */
+void ares_strsplit_free(char **elms, size_t num_elm);
+
+
+#endif /* HEADER_CARES_STRSPLIT_H */
+
diff --git a/contrib/libs/c-ares/config-win32.h b/contrib/libs/c-ares/config-win32.h
index da7eba44d8..f1737636e8 100644
--- a/contrib/libs/c-ares/config-win32.h
+++ b/contrib/libs/c-ares/config-win32.h
@@ -251,7 +251,7 @@
# define _CRT_NONSTDC_NO_DEPRECATE 1
#endif
-/* Set the Target to Vista. However, any symbols required above Win2000
+/* Set the Target to Vista. However, any symbols required above Win2000
* should be loaded via LoadLibrary() */
#if defined(_MSC_VER) && (_MSC_VER >= 1500)
# define VS2008_MIN_TARGET 0x0600
diff --git a/contrib/libs/c-ares/inet_ntop.c b/contrib/libs/c-ares/inet_ntop.c
index 1935a871ce..a3617d8c15 100644
--- a/contrib/libs/c-ares/inet_ntop.c
+++ b/contrib/libs/c-ares/inet_ntop.c
@@ -180,7 +180,7 @@ inet_ntop6(const unsigned char *src, char *dst, size_t size)
tp += sprintf(tp, "%x", words[i]);
}
/* Was it a trailing run of 0x00's? */
- if (best.base != -1 && (best.base + best.len) == (NS_IN6ADDRSZ / NS_INT16SZ))
+ if (best.base != -1 && (best.base + best.len) == (NS_IN6ADDRSZ / NS_INT16SZ))
*tp++ = ':';
*tp++ = '\0';
diff --git a/contrib/libs/c-ares/test/ares-test-init.cc b/contrib/libs/c-ares/test/ares-test-init.cc
index 842b0e15ac..d20a1e7e6f 100644
--- a/contrib/libs/c-ares/test/ares-test-init.cc
+++ b/contrib/libs/c-ares/test/ares-test-init.cc
@@ -1,247 +1,247 @@
-#include "ares-test.h"
-
-// library initialization is only needed for windows builds
-#ifdef WIN32
-#define EXPECTED_NONINIT ARES_ENOTINITIALIZED
-#else
-#define EXPECTED_NONINIT ARES_SUCCESS
-#endif
-
-namespace ares {
-namespace test {
-
-TEST(LibraryInit, Basic) {
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
- EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
- EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
- ares_library_cleanup();
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
-}
-
-TEST(LibraryInit, UnexpectedCleanup) {
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
- ares_library_cleanup();
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
-}
-
-TEST(LibraryInit, DISABLED_InvalidParam) {
- // TODO: police flags argument to ares_library_init()
- EXPECT_EQ(ARES_EBADQUERY, ares_library_init(ARES_LIB_INIT_ALL << 2));
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
- ares_library_cleanup();
-}
-
-TEST(LibraryInit, Nested) {
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
- EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
- EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
- EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
- EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
- ares_library_cleanup();
- EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
- ares_library_cleanup();
- EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
-}
-
-TEST(LibraryInit, BasicChannelInit) {
- EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- EXPECT_NE(nullptr, channel);
- ares_destroy(channel);
- ares_library_cleanup();
-}
-
-TEST_F(LibraryTest, OptionsChannelInit) {
- struct ares_options opts = {0};
- int optmask = 0;
- opts.flags = ARES_FLAG_USEVC | ARES_FLAG_PRIMARY;
- optmask |= ARES_OPT_FLAGS;
- opts.timeout = 2000;
- optmask |= ARES_OPT_TIMEOUTMS;
- opts.tries = 2;
- optmask |= ARES_OPT_TRIES;
- opts.ndots = 4;
- optmask |= ARES_OPT_NDOTS;
- opts.udp_port = 54;
- optmask |= ARES_OPT_UDP_PORT;
- opts.tcp_port = 54;
- optmask |= ARES_OPT_TCP_PORT;
- opts.socket_send_buffer_size = 514;
- optmask |= ARES_OPT_SOCK_SNDBUF;
- opts.socket_receive_buffer_size = 514;
- optmask |= ARES_OPT_SOCK_RCVBUF;
- opts.ednspsz = 1280;
- optmask |= ARES_OPT_EDNSPSZ;
- opts.nservers = 2;
- opts.servers = (struct in_addr *)malloc(opts.nservers * sizeof(struct in_addr));
- opts.servers[0].s_addr = htonl(0x01020304);
- opts.servers[1].s_addr = htonl(0x02030405);
- optmask |= ARES_OPT_SERVERS;
- opts.ndomains = 2;
- opts.domains = (char **)malloc(opts.ndomains * sizeof(char *));
- opts.domains[0] = strdup("example.com");
- opts.domains[1] = strdup("example2.com");
- optmask |= ARES_OPT_DOMAINS;
- opts.lookups = strdup("b");
- optmask |= ARES_OPT_LOOKUPS;
- optmask |= ARES_OPT_ROTATE;
- opts.resolvconf_path = strdup("/etc/resolv.conf");
- optmask |= ARES_OPT_RESOLVCONF;
-
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
- EXPECT_NE(nullptr, channel);
-
- ares_channel channel2 = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_dup(&channel2, channel));
-
- struct ares_options opts2 = {0};
- int optmask2 = 0;
- EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel2, &opts2, &optmask2));
-
- // Note that not all opts-settable fields are saved (e.g.
- // ednspsz, socket_{send,receive}_buffer_size).
- EXPECT_EQ(opts.flags, opts2.flags);
- EXPECT_EQ(opts.timeout, opts2.timeout);
- EXPECT_EQ(opts.tries, opts2.tries);
- EXPECT_EQ(opts.ndots, opts2.ndots);
- EXPECT_EQ(opts.udp_port, opts2.udp_port);
- EXPECT_EQ(opts.tcp_port, opts2.tcp_port);
- EXPECT_EQ(1, opts2.nservers); // Truncated by ARES_FLAG_PRIMARY
- EXPECT_EQ(opts.servers[0].s_addr, opts2.servers[0].s_addr);
- EXPECT_EQ(opts.ndomains, opts2.ndomains);
- EXPECT_EQ(std::string(opts.domains[0]), std::string(opts2.domains[0]));
- EXPECT_EQ(std::string(opts.domains[1]), std::string(opts2.domains[1]));
- EXPECT_EQ(std::string(opts.lookups), std::string(opts2.lookups));
- EXPECT_EQ(std::string(opts.resolvconf_path), std::string(opts2.resolvconf_path));
-
- ares_destroy_options(&opts);
- ares_destroy_options(&opts2);
- ares_destroy(channel);
- ares_destroy(channel2);
-}
-
-TEST_F(LibraryTest, ChannelAllocFail) {
- ares_channel channel;
- for (int ii = 1; ii <= 25; ii++) {
- ClearFails();
- SetAllocFail(ii);
- channel = nullptr;
- int rc = ares_init(&channel);
- // The number of allocations depends on local environment, so don't expect ENOMEM.
- if (rc == ARES_ENOMEM) {
- EXPECT_EQ(nullptr, channel);
- } else {
- ares_destroy(channel);
- }
- }
-}
-
-TEST_F(LibraryTest, OptionsChannelAllocFail) {
- struct ares_options opts = {0};
- int optmask = 0;
- opts.flags = ARES_FLAG_USEVC;
- optmask |= ARES_OPT_FLAGS;
- opts.timeout = 2;
- optmask |= ARES_OPT_TIMEOUT;
- opts.tries = 2;
- optmask |= ARES_OPT_TRIES;
- opts.ndots = 4;
- optmask |= ARES_OPT_NDOTS;
- opts.udp_port = 54;
- optmask |= ARES_OPT_UDP_PORT;
- opts.tcp_port = 54;
- optmask |= ARES_OPT_TCP_PORT;
- opts.socket_send_buffer_size = 514;
- optmask |= ARES_OPT_SOCK_SNDBUF;
- opts.socket_receive_buffer_size = 514;
- optmask |= ARES_OPT_SOCK_RCVBUF;
- opts.ednspsz = 1280;
- optmask |= ARES_OPT_EDNSPSZ;
- opts.nservers = 2;
- opts.servers = (struct in_addr *)malloc(opts.nservers * sizeof(struct in_addr));
- opts.servers[0].s_addr = htonl(0x01020304);
- opts.servers[1].s_addr = htonl(0x02030405);
- optmask |= ARES_OPT_SERVERS;
- opts.ndomains = 2;
- opts.domains = (char **)malloc(opts.ndomains * sizeof(char *));
- opts.domains[0] = strdup("example.com");
- opts.domains[1] = strdup("example2.com");
- optmask |= ARES_OPT_DOMAINS;
- opts.lookups = strdup("b");
- optmask |= ARES_OPT_LOOKUPS;
- optmask |= ARES_OPT_ROTATE;
- opts.resolvconf_path = strdup("/etc/resolv.conf");
- optmask |= ARES_OPT_RESOLVCONF;
-
- ares_channel channel = nullptr;
- for (int ii = 1; ii <= 8; ii++) {
- ClearFails();
- SetAllocFail(ii);
- int rc = ares_init_options(&channel, &opts, optmask);
- if (rc == ARES_ENOMEM) {
- EXPECT_EQ(nullptr, channel);
- } else {
- EXPECT_EQ(ARES_SUCCESS, rc);
- ares_destroy(channel);
- channel = nullptr;
- }
- }
- ClearFails();
-
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
- EXPECT_NE(nullptr, channel);
-
- // Add some servers and a sortlist for flavour.
- EXPECT_EQ(ARES_SUCCESS,
- ares_set_servers_csv(channel, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel, "1.2.3.4 2.3.4.5"));
-
- ares_channel channel2 = nullptr;
- for (int ii = 1; ii <= 18; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_dup(&channel2, channel)) << ii;
- EXPECT_EQ(nullptr, channel2) << ii;
- }
-
- struct ares_options opts2;
- int optmask2 = 0;
- for (int ii = 1; ii <= 6; ii++) {
- memset(&opts2, 0, sizeof(opts2));
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_save_options(channel, &opts2, &optmask2)) << ii;
- // May still have allocations even after ARES_ENOMEM return code.
- ares_destroy_options(&opts2);
- }
- ares_destroy_options(&opts);
- ares_destroy(channel);
-}
-
-TEST_F(LibraryTest, FailChannelInit) {
- EXPECT_EQ(ARES_SUCCESS,
- ares_library_init_mem(ARES_LIB_INIT_ALL,
- &LibraryTest::amalloc,
- &LibraryTest::afree,
- &LibraryTest::arealloc));
- SetAllocFail(1);
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_ENOMEM, ares_init(&channel));
- EXPECT_EQ(nullptr, channel);
- ares_library_cleanup();
-}
-
-#ifndef WIN32
-TEST_F(LibraryTest, EnvInit) {
- ares_channel channel = nullptr;
- EnvValue v1("LOCALDOMAIN", "this.is.local");
- EnvValue v2("RES_OPTIONS", "options debug ndots:3 retry:3 rotate retrans:2");
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- ares_destroy(channel);
-}
-
+#include "ares-test.h"
+
+// library initialization is only needed for windows builds
+#ifdef WIN32
+#define EXPECTED_NONINIT ARES_ENOTINITIALIZED
+#else
+#define EXPECTED_NONINIT ARES_SUCCESS
+#endif
+
+namespace ares {
+namespace test {
+
+TEST(LibraryInit, Basic) {
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+ EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
+ EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
+ ares_library_cleanup();
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+}
+
+TEST(LibraryInit, UnexpectedCleanup) {
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+ ares_library_cleanup();
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+}
+
+TEST(LibraryInit, DISABLED_InvalidParam) {
+ // TODO: police flags argument to ares_library_init()
+ EXPECT_EQ(ARES_EBADQUERY, ares_library_init(ARES_LIB_INIT_ALL << 2));
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+ ares_library_cleanup();
+}
+
+TEST(LibraryInit, Nested) {
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+ EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
+ EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
+ EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
+ EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
+ ares_library_cleanup();
+ EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
+ ares_library_cleanup();
+ EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
+}
+
+TEST(LibraryInit, BasicChannelInit) {
+ EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ EXPECT_NE(nullptr, channel);
+ ares_destroy(channel);
+ ares_library_cleanup();
+}
+
+TEST_F(LibraryTest, OptionsChannelInit) {
+ struct ares_options opts = {0};
+ int optmask = 0;
+ opts.flags = ARES_FLAG_USEVC | ARES_FLAG_PRIMARY;
+ optmask |= ARES_OPT_FLAGS;
+ opts.timeout = 2000;
+ optmask |= ARES_OPT_TIMEOUTMS;
+ opts.tries = 2;
+ optmask |= ARES_OPT_TRIES;
+ opts.ndots = 4;
+ optmask |= ARES_OPT_NDOTS;
+ opts.udp_port = 54;
+ optmask |= ARES_OPT_UDP_PORT;
+ opts.tcp_port = 54;
+ optmask |= ARES_OPT_TCP_PORT;
+ opts.socket_send_buffer_size = 514;
+ optmask |= ARES_OPT_SOCK_SNDBUF;
+ opts.socket_receive_buffer_size = 514;
+ optmask |= ARES_OPT_SOCK_RCVBUF;
+ opts.ednspsz = 1280;
+ optmask |= ARES_OPT_EDNSPSZ;
+ opts.nservers = 2;
+ opts.servers = (struct in_addr *)malloc(opts.nservers * sizeof(struct in_addr));
+ opts.servers[0].s_addr = htonl(0x01020304);
+ opts.servers[1].s_addr = htonl(0x02030405);
+ optmask |= ARES_OPT_SERVERS;
+ opts.ndomains = 2;
+ opts.domains = (char **)malloc(opts.ndomains * sizeof(char *));
+ opts.domains[0] = strdup("example.com");
+ opts.domains[1] = strdup("example2.com");
+ optmask |= ARES_OPT_DOMAINS;
+ opts.lookups = strdup("b");
+ optmask |= ARES_OPT_LOOKUPS;
+ optmask |= ARES_OPT_ROTATE;
+ opts.resolvconf_path = strdup("/etc/resolv.conf");
+ optmask |= ARES_OPT_RESOLVCONF;
+
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
+ EXPECT_NE(nullptr, channel);
+
+ ares_channel channel2 = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_dup(&channel2, channel));
+
+ struct ares_options opts2 = {0};
+ int optmask2 = 0;
+ EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel2, &opts2, &optmask2));
+
+ // Note that not all opts-settable fields are saved (e.g.
+ // ednspsz, socket_{send,receive}_buffer_size).
+ EXPECT_EQ(opts.flags, opts2.flags);
+ EXPECT_EQ(opts.timeout, opts2.timeout);
+ EXPECT_EQ(opts.tries, opts2.tries);
+ EXPECT_EQ(opts.ndots, opts2.ndots);
+ EXPECT_EQ(opts.udp_port, opts2.udp_port);
+ EXPECT_EQ(opts.tcp_port, opts2.tcp_port);
+ EXPECT_EQ(1, opts2.nservers); // Truncated by ARES_FLAG_PRIMARY
+ EXPECT_EQ(opts.servers[0].s_addr, opts2.servers[0].s_addr);
+ EXPECT_EQ(opts.ndomains, opts2.ndomains);
+ EXPECT_EQ(std::string(opts.domains[0]), std::string(opts2.domains[0]));
+ EXPECT_EQ(std::string(opts.domains[1]), std::string(opts2.domains[1]));
+ EXPECT_EQ(std::string(opts.lookups), std::string(opts2.lookups));
+ EXPECT_EQ(std::string(opts.resolvconf_path), std::string(opts2.resolvconf_path));
+
+ ares_destroy_options(&opts);
+ ares_destroy_options(&opts2);
+ ares_destroy(channel);
+ ares_destroy(channel2);
+}
+
+TEST_F(LibraryTest, ChannelAllocFail) {
+ ares_channel channel;
+ for (int ii = 1; ii <= 25; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ channel = nullptr;
+ int rc = ares_init(&channel);
+ // The number of allocations depends on local environment, so don't expect ENOMEM.
+ if (rc == ARES_ENOMEM) {
+ EXPECT_EQ(nullptr, channel);
+ } else {
+ ares_destroy(channel);
+ }
+ }
+}
+
+TEST_F(LibraryTest, OptionsChannelAllocFail) {
+ struct ares_options opts = {0};
+ int optmask = 0;
+ opts.flags = ARES_FLAG_USEVC;
+ optmask |= ARES_OPT_FLAGS;
+ opts.timeout = 2;
+ optmask |= ARES_OPT_TIMEOUT;
+ opts.tries = 2;
+ optmask |= ARES_OPT_TRIES;
+ opts.ndots = 4;
+ optmask |= ARES_OPT_NDOTS;
+ opts.udp_port = 54;
+ optmask |= ARES_OPT_UDP_PORT;
+ opts.tcp_port = 54;
+ optmask |= ARES_OPT_TCP_PORT;
+ opts.socket_send_buffer_size = 514;
+ optmask |= ARES_OPT_SOCK_SNDBUF;
+ opts.socket_receive_buffer_size = 514;
+ optmask |= ARES_OPT_SOCK_RCVBUF;
+ opts.ednspsz = 1280;
+ optmask |= ARES_OPT_EDNSPSZ;
+ opts.nservers = 2;
+ opts.servers = (struct in_addr *)malloc(opts.nservers * sizeof(struct in_addr));
+ opts.servers[0].s_addr = htonl(0x01020304);
+ opts.servers[1].s_addr = htonl(0x02030405);
+ optmask |= ARES_OPT_SERVERS;
+ opts.ndomains = 2;
+ opts.domains = (char **)malloc(opts.ndomains * sizeof(char *));
+ opts.domains[0] = strdup("example.com");
+ opts.domains[1] = strdup("example2.com");
+ optmask |= ARES_OPT_DOMAINS;
+ opts.lookups = strdup("b");
+ optmask |= ARES_OPT_LOOKUPS;
+ optmask |= ARES_OPT_ROTATE;
+ opts.resolvconf_path = strdup("/etc/resolv.conf");
+ optmask |= ARES_OPT_RESOLVCONF;
+
+ ares_channel channel = nullptr;
+ for (int ii = 1; ii <= 8; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ int rc = ares_init_options(&channel, &opts, optmask);
+ if (rc == ARES_ENOMEM) {
+ EXPECT_EQ(nullptr, channel);
+ } else {
+ EXPECT_EQ(ARES_SUCCESS, rc);
+ ares_destroy(channel);
+ channel = nullptr;
+ }
+ }
+ ClearFails();
+
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
+ EXPECT_NE(nullptr, channel);
+
+ // Add some servers and a sortlist for flavour.
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_set_servers_csv(channel, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel, "1.2.3.4 2.3.4.5"));
+
+ ares_channel channel2 = nullptr;
+ for (int ii = 1; ii <= 18; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_dup(&channel2, channel)) << ii;
+ EXPECT_EQ(nullptr, channel2) << ii;
+ }
+
+ struct ares_options opts2;
+ int optmask2 = 0;
+ for (int ii = 1; ii <= 6; ii++) {
+ memset(&opts2, 0, sizeof(opts2));
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_save_options(channel, &opts2, &optmask2)) << ii;
+ // May still have allocations even after ARES_ENOMEM return code.
+ ares_destroy_options(&opts2);
+ }
+ ares_destroy_options(&opts);
+ ares_destroy(channel);
+}
+
+TEST_F(LibraryTest, FailChannelInit) {
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_library_init_mem(ARES_LIB_INIT_ALL,
+ &LibraryTest::amalloc,
+ &LibraryTest::afree,
+ &LibraryTest::arealloc));
+ SetAllocFail(1);
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_ENOMEM, ares_init(&channel));
+ EXPECT_EQ(nullptr, channel);
+ ares_library_cleanup();
+}
+
+#ifndef WIN32
+TEST_F(LibraryTest, EnvInit) {
+ ares_channel channel = nullptr;
+ EnvValue v1("LOCALDOMAIN", "this.is.local");
+ EnvValue v2("RES_OPTIONS", "options debug ndots:3 retry:3 rotate retrans:2");
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ ares_destroy(channel);
+}
+
TEST_F(LibraryTest, EnvInitYt) {
ares_channel channel = nullptr;
EnvValue v1("LOCALDOMAIN", "this.is.local");
@@ -268,233 +268,233 @@ TEST_F(LibraryTest, EnvInitYtTimeouts) {
ares_destroy(channel);
}
-TEST_F(LibraryTest, EnvInitAllocFail) {
- ares_channel channel;
- EnvValue v1("LOCALDOMAIN", "this.is.local");
- EnvValue v2("RES_OPTIONS", "options debug ndots:3 retry:3 rotate retrans:2");
- for (int ii = 1; ii <= 10; ii++) {
- ClearFails();
- SetAllocFail(ii);
- channel = nullptr;
- int rc = ares_init(&channel);
- if (rc == ARES_SUCCESS) {
- ares_destroy(channel);
- } else {
- EXPECT_EQ(ARES_ENOMEM, rc);
- }
- }
-}
-#endif
-
-TEST_F(DefaultChannelTest, SetAddresses) {
- ares_set_local_ip4(channel_, 0x01020304);
- byte addr6[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
- 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
- ares_set_local_ip6(channel_, addr6);
- ares_set_local_dev(channel_, "dummy");
-}
-
-TEST_F(DefaultChannelTest, SetSortlistFailures) {
- EXPECT_EQ(ARES_ENODATA, ares_set_sortlist(nullptr, "1.2.3.4"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; lwk"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; 0x123"));
-}
-
-TEST_F(DefaultChannelTest, SetSortlistVariants) {
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "1.2.3.4"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "1.2.3.4 ; 2.3.4.5"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "129.1.1.1"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "192.1.1.1"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "224.1.1.1"));
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "225.1.1.1"));
-}
-
-TEST_F(DefaultChannelTest, SetSortlistAllocFail) {
- for (int ii = 1; ii <= 3; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_set_sortlist(channel_, "12.13.0.0/16 1234::5678/40 1.2.3.4")) << ii;
- }
-}
-
-#ifdef USE_WINSOCK
-TEST(Init, NoLibraryInit) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_ENOTINITIALIZED, ares_init(&channel));
-}
-#endif
-
-#ifdef HAVE_CONTAINER
-// These tests rely on the ability of non-root users to create a chroot
-// using Linux namespaces.
-
-
-// The library uses a variety of information sources to initialize a channel,
-// in particular to determine:
-// - search: the search domains to use
-// - servers: the name servers to use
-// - lookup: whether to check files or DNS or both (e.g. "fb")
-// - options: various resolver options
-// - sortlist: the order of preference for IP addresses
-//
-// The first source from the following list is used:
-// - init_by_options(): explicitly specified values in struct ares_options
-// - init_by_environment(): values from the environment:
-// - LOCALDOMAIN -> search (single value)
-// - RES_OPTIONS -> options
-// - init_by_resolv_conf(): values from various config files:
-// - /etc/resolv.conf -> search, lookup, servers, sortlist, options
-// - /etc/nsswitch.conf -> lookup
-// - /etc/host.conf -> lookup
-// - /etc/svc.conf -> lookup
-// - init_by_defaults(): fallback values:
-// - gethostname(3) -> domain
-// - "fb" -> lookup
-
-NameContentList filelist = {
- {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
- "sortlist 1.2.3.4/16 2.3.4.5\n"
- "search first.com second.com\n"},
- {"/etc/hosts", "3.4.5.6 ahostname.com\n"},
- {"/etc/nsswitch.conf", "hosts: files\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerChannelInit,
- "myhostname", "mydomainname.org", filelist) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- std::vector<std::string> actual = GetNameServers(channel);
- std::vector<std::string> expected = {"1.2.3.4"};
- EXPECT_EQ(expected, actual);
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(2, opts.ndomains);
- EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
- EXPECT_EQ(std::string("second.com"), std::string(opts.domains[1]));
- ares_destroy_options(&opts);
-
- HostResult result;
- ares_gethostbyname(channel, "ahostname.com", AF_INET, HostCallback, &result);
- ProcessWork(channel, NoExtraFDs, nullptr);
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'ahostname.com' aliases=[] addrs=[3.4.5.6]}", ss.str());
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-CONTAINED_TEST_F(LibraryTest, ContainerSortlistOptionInit,
- "myhostname", "mydomainname.org", filelist) {
- ares_channel channel = nullptr;
- struct ares_options opts = {0};
- int optmask = 0;
- optmask |= ARES_OPT_SORTLIST;
- opts.nsort = 0;
- // Explicitly specifying an empty sortlist in the options should override the
- // environment.
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(0, opts.nsort);
- EXPECT_EQ(nullptr, opts.sortlist);
- EXPECT_EQ(ARES_OPT_SORTLIST, (optmask & ARES_OPT_SORTLIST));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList fullresolv = {
- {"/etc/resolv.conf", " nameserver 1.2.3.4 \n"
- "search first.com second.com\n"
- "lookup bind\n"
- "options debug ndots:5\n"
- "sortlist 1.2.3.4/16 2.3.4.5\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerFullResolvInit,
- "myhostname", "mydomainname.org", fullresolv) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(std::string("b"), std::string(opts.lookups));
- EXPECT_EQ(5, opts.ndots);
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-// Allow path for resolv.conf to be configurable
-NameContentList myresolvconf = {
- {"/tmp/myresolv.cnf", " nameserver 1.2.3.4 \n"
- "search first.com second.com\n"
- "lookup bind\n"
- "options debug ndots:5\n"
- "sortlist 1.2.3.4/16 2.3.4.5\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerMyResolvConfInit,
- "myhostname", "mydomain.org", myresolvconf) {
- char filename[] = "/tmp/myresolv.cnf";
- ares_channel channel = nullptr;
- struct ares_options options = {0};
- options.resolvconf_path = strdup(filename);
- int optmask = ARES_OPT_RESOLVCONF;
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &options, optmask));
-
- optmask = 0;
- free(options.resolvconf_path);
- options.resolvconf_path = NULL;
-
- EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel, &options, &optmask));
- EXPECT_EQ(ARES_OPT_RESOLVCONF, (optmask & ARES_OPT_RESOLVCONF));
- EXPECT_EQ(std::string(filename), std::string(options.resolvconf_path));
-
- ares_destroy_options(&options);
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList hostconf = {
- {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
- "sortlist1.2.3.4\n" // malformed line
- "search first.com second.com\n"},
- {"/etc/host.conf", "order bind hosts\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerHostConfInit,
- "myhostname", "mydomainname.org", hostconf) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(std::string("bf"), std::string(opts.lookups));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList svcconf = {
- {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
- "search first.com second.com\n"},
- {"/etc/svc.conf", "hosts= bind\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerSvcConfInit,
- "myhostname", "mydomainname.org", svcconf) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(std::string("b"), std::string(opts.lookups));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
+TEST_F(LibraryTest, EnvInitAllocFail) {
+ ares_channel channel;
+ EnvValue v1("LOCALDOMAIN", "this.is.local");
+ EnvValue v2("RES_OPTIONS", "options debug ndots:3 retry:3 rotate retrans:2");
+ for (int ii = 1; ii <= 10; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ channel = nullptr;
+ int rc = ares_init(&channel);
+ if (rc == ARES_SUCCESS) {
+ ares_destroy(channel);
+ } else {
+ EXPECT_EQ(ARES_ENOMEM, rc);
+ }
+ }
+}
+#endif
+
+TEST_F(DefaultChannelTest, SetAddresses) {
+ ares_set_local_ip4(channel_, 0x01020304);
+ byte addr6[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
+ ares_set_local_ip6(channel_, addr6);
+ ares_set_local_dev(channel_, "dummy");
+}
+
+TEST_F(DefaultChannelTest, SetSortlistFailures) {
+ EXPECT_EQ(ARES_ENODATA, ares_set_sortlist(nullptr, "1.2.3.4"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; lwk"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; 0x123"));
+}
+
+TEST_F(DefaultChannelTest, SetSortlistVariants) {
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "1.2.3.4"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "1.2.3.4 ; 2.3.4.5"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "129.1.1.1"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "192.1.1.1"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "224.1.1.1"));
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "225.1.1.1"));
+}
+
+TEST_F(DefaultChannelTest, SetSortlistAllocFail) {
+ for (int ii = 1; ii <= 3; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_set_sortlist(channel_, "12.13.0.0/16 1234::5678/40 1.2.3.4")) << ii;
+ }
+}
+
+#ifdef USE_WINSOCK
+TEST(Init, NoLibraryInit) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_ENOTINITIALIZED, ares_init(&channel));
+}
+#endif
+
+#ifdef HAVE_CONTAINER
+// These tests rely on the ability of non-root users to create a chroot
+// using Linux namespaces.
+
+
+// The library uses a variety of information sources to initialize a channel,
+// in particular to determine:
+// - search: the search domains to use
+// - servers: the name servers to use
+// - lookup: whether to check files or DNS or both (e.g. "fb")
+// - options: various resolver options
+// - sortlist: the order of preference for IP addresses
+//
+// The first source from the following list is used:
+// - init_by_options(): explicitly specified values in struct ares_options
+// - init_by_environment(): values from the environment:
+// - LOCALDOMAIN -> search (single value)
+// - RES_OPTIONS -> options
+// - init_by_resolv_conf(): values from various config files:
+// - /etc/resolv.conf -> search, lookup, servers, sortlist, options
+// - /etc/nsswitch.conf -> lookup
+// - /etc/host.conf -> lookup
+// - /etc/svc.conf -> lookup
+// - init_by_defaults(): fallback values:
+// - gethostname(3) -> domain
+// - "fb" -> lookup
+
+NameContentList filelist = {
+ {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
+ "sortlist 1.2.3.4/16 2.3.4.5\n"
+ "search first.com second.com\n"},
+ {"/etc/hosts", "3.4.5.6 ahostname.com\n"},
+ {"/etc/nsswitch.conf", "hosts: files\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerChannelInit,
+ "myhostname", "mydomainname.org", filelist) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ std::vector<std::string> actual = GetNameServers(channel);
+ std::vector<std::string> expected = {"1.2.3.4"};
+ EXPECT_EQ(expected, actual);
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(2, opts.ndomains);
+ EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
+ EXPECT_EQ(std::string("second.com"), std::string(opts.domains[1]));
+ ares_destroy_options(&opts);
+
+ HostResult result;
+ ares_gethostbyname(channel, "ahostname.com", AF_INET, HostCallback, &result);
+ ProcessWork(channel, NoExtraFDs, nullptr);
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'ahostname.com' aliases=[] addrs=[3.4.5.6]}", ss.str());
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+CONTAINED_TEST_F(LibraryTest, ContainerSortlistOptionInit,
+ "myhostname", "mydomainname.org", filelist) {
+ ares_channel channel = nullptr;
+ struct ares_options opts = {0};
+ int optmask = 0;
+ optmask |= ARES_OPT_SORTLIST;
+ opts.nsort = 0;
+ // Explicitly specifying an empty sortlist in the options should override the
+ // environment.
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(0, opts.nsort);
+ EXPECT_EQ(nullptr, opts.sortlist);
+ EXPECT_EQ(ARES_OPT_SORTLIST, (optmask & ARES_OPT_SORTLIST));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList fullresolv = {
+ {"/etc/resolv.conf", " nameserver 1.2.3.4 \n"
+ "search first.com second.com\n"
+ "lookup bind\n"
+ "options debug ndots:5\n"
+ "sortlist 1.2.3.4/16 2.3.4.5\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerFullResolvInit,
+ "myhostname", "mydomainname.org", fullresolv) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(std::string("b"), std::string(opts.lookups));
+ EXPECT_EQ(5, opts.ndots);
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+// Allow path for resolv.conf to be configurable
+NameContentList myresolvconf = {
+ {"/tmp/myresolv.cnf", " nameserver 1.2.3.4 \n"
+ "search first.com second.com\n"
+ "lookup bind\n"
+ "options debug ndots:5\n"
+ "sortlist 1.2.3.4/16 2.3.4.5\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerMyResolvConfInit,
+ "myhostname", "mydomain.org", myresolvconf) {
+ char filename[] = "/tmp/myresolv.cnf";
+ ares_channel channel = nullptr;
+ struct ares_options options = {0};
+ options.resolvconf_path = strdup(filename);
+ int optmask = ARES_OPT_RESOLVCONF;
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &options, optmask));
+
+ optmask = 0;
+ free(options.resolvconf_path);
+ options.resolvconf_path = NULL;
+
+ EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel, &options, &optmask));
+ EXPECT_EQ(ARES_OPT_RESOLVCONF, (optmask & ARES_OPT_RESOLVCONF));
+ EXPECT_EQ(std::string(filename), std::string(options.resolvconf_path));
+
+ ares_destroy_options(&options);
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList hostconf = {
+ {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
+ "sortlist1.2.3.4\n" // malformed line
+ "search first.com second.com\n"},
+ {"/etc/host.conf", "order bind hosts\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerHostConfInit,
+ "myhostname", "mydomainname.org", hostconf) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(std::string("bf"), std::string(opts.lookups));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList svcconf = {
+ {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
+ "search first.com second.com\n"},
+ {"/etc/svc.conf", "hosts= bind\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerSvcConfInit,
+ "myhostname", "mydomainname.org", svcconf) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(std::string("b"), std::string(opts.lookups));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
NameContentList malformedresolvconflookup = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"lookup garbage\n"}}; // malformed line
@@ -513,191 +513,191 @@ CONTAINED_TEST_F(LibraryTest, ContainerMalformedResolvConfLookup,
return HasFailure();
}
-// Failures when expected config filenames are inaccessible.
-class MakeUnreadable {
- public:
- explicit MakeUnreadable(const std::string& filename)
- : filename_(filename) {
- chmod(filename_.c_str(), 0000);
- }
- ~MakeUnreadable() { chmod(filename_.c_str(), 0644); }
- private:
- std::string filename_;
-};
-
-CONTAINED_TEST_F(LibraryTest, ContainerResolvConfNotReadable,
- "myhostname", "mydomainname.org", filelist) {
- ares_channel channel = nullptr;
- MakeUnreadable hide("/etc/resolv.conf");
- // Unavailable /etc/resolv.conf falls back to defaults
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- return HasFailure();
-}
-CONTAINED_TEST_F(LibraryTest, ContainerNsswitchConfNotReadable,
- "myhostname", "mydomainname.org", filelist) {
- ares_channel channel = nullptr;
- // Unavailable /etc/nsswitch.conf falls back to defaults.
- MakeUnreadable hide("/etc/nsswitch.conf");
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-CONTAINED_TEST_F(LibraryTest, ContainerHostConfNotReadable,
- "myhostname", "mydomainname.org", hostconf) {
- ares_channel channel = nullptr;
- // Unavailable /etc/host.conf falls back to defaults.
- MakeUnreadable hide("/etc/host.conf");
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- ares_destroy(channel);
- return HasFailure();
-}
-CONTAINED_TEST_F(LibraryTest, ContainerSvcConfNotReadable,
- "myhostname", "mydomainname.org", svcconf) {
- ares_channel channel = nullptr;
- // Unavailable /etc/svc.conf falls back to defaults.
- MakeUnreadable hide("/etc/svc.conf");
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList rotateenv = {
- {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
- "search first.com second.com\n"
- "options rotate\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerRotateInit,
- "myhostname", "mydomainname.org", rotateenv) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(ARES_OPT_ROTATE, (optmask & ARES_OPT_ROTATE));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-CONTAINED_TEST_F(LibraryTest, ContainerRotateOverride,
- "myhostname", "mydomainname.org", rotateenv) {
- ares_channel channel = nullptr;
- struct ares_options opts = {0};
- int optmask = ARES_OPT_NOROTATE;
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
-
- optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(ARES_OPT_NOROTATE, (optmask & ARES_OPT_NOROTATE));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-// Test that blacklisted IPv6 resolves are ignored. They're filtered from any
-// source, so resolv.conf is as good as any.
-NameContentList blacklistedIpv6 = {
- {"/etc/resolv.conf", " nameserver 254.192.1.1\n" // 0xfe.0xc0.0x01.0x01
- " nameserver fec0::dead\n" // Blacklisted
- " nameserver ffc0::c001\n" // Not blacklisted
- " domain first.com\n"},
- {"/etc/nsswitch.conf", "hosts: files\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerBlacklistedIpv6,
- "myhostname", "mydomainname.org", blacklistedIpv6) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- std::vector<std::string> actual = GetNameServers(channel);
- std::vector<std::string> expected = {
- "254.192.1.1",
- "ffc0:0000:0000:0000:0000:0000:0000:c001"
- };
- EXPECT_EQ(expected, actual);
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(1, opts.ndomains);
- EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList multiresolv = {
- {"/etc/resolv.conf", " nameserver 1::2 ; ;;\n"
- " domain first.com\n"},
- {"/etc/nsswitch.conf", "hosts: files\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerMultiResolvInit,
- "myhostname", "mydomainname.org", multiresolv) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- std::vector<std::string> actual = GetNameServers(channel);
- std::vector<std::string> expected = {"0001:0000:0000:0000:0000:0000:0000:0002"};
- EXPECT_EQ(expected, actual);
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(1, opts.ndomains);
- EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList systemdresolv = {
- {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
- "domain first.com\n"},
- {"/etc/nsswitch.conf", "hosts: junk resolve files\n"}};
-CONTAINED_TEST_F(LibraryTest, ContainerSystemdResolvInit,
- "myhostname", "mydomainname.org", systemdresolv) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(std::string("bf"), std::string(opts.lookups));
- ares_destroy_options(&opts);
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-NameContentList empty = {}; // no files
-CONTAINED_TEST_F(LibraryTest, ContainerEmptyInit,
- "host.domain.org", "domain.org", empty) {
- ares_channel channel = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
- std::vector<std::string> actual = GetNameServers(channel);
- std::vector<std::string> expected = {"127.0.0.1"};
- EXPECT_EQ(expected, actual);
-
- struct ares_options opts;
- int optmask = 0;
- ares_save_options(channel, &opts, &optmask);
- EXPECT_EQ(1, opts.ndomains);
- EXPECT_EQ(std::string("domain.org"), std::string(opts.domains[0]));
- EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
- ares_destroy_options(&opts);
-
-
- ares_destroy(channel);
- return HasFailure();
-}
-
-#endif
-
-} // namespace test
-} // namespace ares
+// Failures when expected config filenames are inaccessible.
+class MakeUnreadable {
+ public:
+ explicit MakeUnreadable(const std::string& filename)
+ : filename_(filename) {
+ chmod(filename_.c_str(), 0000);
+ }
+ ~MakeUnreadable() { chmod(filename_.c_str(), 0644); }
+ private:
+ std::string filename_;
+};
+
+CONTAINED_TEST_F(LibraryTest, ContainerResolvConfNotReadable,
+ "myhostname", "mydomainname.org", filelist) {
+ ares_channel channel = nullptr;
+ MakeUnreadable hide("/etc/resolv.conf");
+ // Unavailable /etc/resolv.conf falls back to defaults
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ return HasFailure();
+}
+CONTAINED_TEST_F(LibraryTest, ContainerNsswitchConfNotReadable,
+ "myhostname", "mydomainname.org", filelist) {
+ ares_channel channel = nullptr;
+ // Unavailable /etc/nsswitch.conf falls back to defaults.
+ MakeUnreadable hide("/etc/nsswitch.conf");
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+CONTAINED_TEST_F(LibraryTest, ContainerHostConfNotReadable,
+ "myhostname", "mydomainname.org", hostconf) {
+ ares_channel channel = nullptr;
+ // Unavailable /etc/host.conf falls back to defaults.
+ MakeUnreadable hide("/etc/host.conf");
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ ares_destroy(channel);
+ return HasFailure();
+}
+CONTAINED_TEST_F(LibraryTest, ContainerSvcConfNotReadable,
+ "myhostname", "mydomainname.org", svcconf) {
+ ares_channel channel = nullptr;
+ // Unavailable /etc/svc.conf falls back to defaults.
+ MakeUnreadable hide("/etc/svc.conf");
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList rotateenv = {
+ {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
+ "search first.com second.com\n"
+ "options rotate\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerRotateInit,
+ "myhostname", "mydomainname.org", rotateenv) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(ARES_OPT_ROTATE, (optmask & ARES_OPT_ROTATE));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+CONTAINED_TEST_F(LibraryTest, ContainerRotateOverride,
+ "myhostname", "mydomainname.org", rotateenv) {
+ ares_channel channel = nullptr;
+ struct ares_options opts = {0};
+ int optmask = ARES_OPT_NOROTATE;
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
+
+ optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(ARES_OPT_NOROTATE, (optmask & ARES_OPT_NOROTATE));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+// Test that blacklisted IPv6 resolves are ignored. They're filtered from any
+// source, so resolv.conf is as good as any.
+NameContentList blacklistedIpv6 = {
+ {"/etc/resolv.conf", " nameserver 254.192.1.1\n" // 0xfe.0xc0.0x01.0x01
+ " nameserver fec0::dead\n" // Blacklisted
+ " nameserver ffc0::c001\n" // Not blacklisted
+ " domain first.com\n"},
+ {"/etc/nsswitch.conf", "hosts: files\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerBlacklistedIpv6,
+ "myhostname", "mydomainname.org", blacklistedIpv6) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ std::vector<std::string> actual = GetNameServers(channel);
+ std::vector<std::string> expected = {
+ "254.192.1.1",
+ "ffc0:0000:0000:0000:0000:0000:0000:c001"
+ };
+ EXPECT_EQ(expected, actual);
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(1, opts.ndomains);
+ EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList multiresolv = {
+ {"/etc/resolv.conf", " nameserver 1::2 ; ;;\n"
+ " domain first.com\n"},
+ {"/etc/nsswitch.conf", "hosts: files\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerMultiResolvInit,
+ "myhostname", "mydomainname.org", multiresolv) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ std::vector<std::string> actual = GetNameServers(channel);
+ std::vector<std::string> expected = {"0001:0000:0000:0000:0000:0000:0000:0002"};
+ EXPECT_EQ(expected, actual);
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(1, opts.ndomains);
+ EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList systemdresolv = {
+ {"/etc/resolv.conf", "nameserver 1.2.3.4\n"
+ "domain first.com\n"},
+ {"/etc/nsswitch.conf", "hosts: junk resolve files\n"}};
+CONTAINED_TEST_F(LibraryTest, ContainerSystemdResolvInit,
+ "myhostname", "mydomainname.org", systemdresolv) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(std::string("bf"), std::string(opts.lookups));
+ ares_destroy_options(&opts);
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+NameContentList empty = {}; // no files
+CONTAINED_TEST_F(LibraryTest, ContainerEmptyInit,
+ "host.domain.org", "domain.org", empty) {
+ ares_channel channel = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
+ std::vector<std::string> actual = GetNameServers(channel);
+ std::vector<std::string> expected = {"127.0.0.1"};
+ EXPECT_EQ(expected, actual);
+
+ struct ares_options opts;
+ int optmask = 0;
+ ares_save_options(channel, &opts, &optmask);
+ EXPECT_EQ(1, opts.ndomains);
+ EXPECT_EQ(std::string("domain.org"), std::string(opts.domains[0]));
+ EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
+ ares_destroy_options(&opts);
+
+
+ ares_destroy(channel);
+ return HasFailure();
+}
+
+#endif
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-internal.cc b/contrib/libs/c-ares/test/ares-test-internal.cc
index 96d4edece5..26e91e73e8 100644
--- a/contrib/libs/c-ares/test/ares-test-internal.cc
+++ b/contrib/libs/c-ares/test/ares-test-internal.cc
@@ -1,361 +1,361 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <stdio.h>
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <fcntl.h>
-
-extern "C" {
-// Remove command-line defines of package variables for the test project...
-#undef PACKAGE_NAME
-#undef PACKAGE_BUGREPORT
-#undef PACKAGE_STRING
-#undef PACKAGE_TARNAME
-// ... so we can include the library's config without symbol redefinitions.
-#include "ares_setup.h"
-#include "ares_nowarn.h"
-#include "ares_inet_net_pton.h"
-#include "ares_data.h"
-#include "ares_private.h"
-#include "bitncmp.h"
-
-#ifdef HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-#ifdef HAVE_SYS_UIO_H
-# include <sys/uio.h>
-#endif
-}
-
-#include <string>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-#ifndef CARES_SYMBOL_HIDING
-void CheckPtoN4(int size, unsigned int value, const char *input) {
- struct in_addr a4;
- a4.s_addr = 0;
- uint32_t expected = htonl(value);
- EXPECT_EQ(size, ares_inet_net_pton(AF_INET, input, &a4, sizeof(a4)))
- << " for input " << input;
- EXPECT_EQ(expected, a4.s_addr) << " for input " << input;
-}
-#endif
-
-TEST_F(LibraryTest, InetPtoN) {
- struct in_addr a4;
- struct in6_addr a6;
-
-#ifndef CARES_SYMBOL_HIDING
- uint32_t expected;
-
- CheckPtoN4(4 * 8, 0x01020304, "1.2.3.4");
- CheckPtoN4(4 * 8, 0x81010101, "129.1.1.1");
- CheckPtoN4(4 * 8, 0xC0010101, "192.1.1.1");
- CheckPtoN4(4 * 8, 0xE0010101, "224.1.1.1");
- CheckPtoN4(4 * 8, 0xE1010101, "225.1.1.1");
- CheckPtoN4(4, 0xE0000000, "224");
- CheckPtoN4(4 * 8, 0xFD000000, "253");
- CheckPtoN4(4 * 8, 0xF0010101, "240.1.1.1");
- CheckPtoN4(4 * 8, 0x02030405, "02.3.4.5");
- CheckPtoN4(3 * 8, 0x01020304, "1.2.3.4/24");
- CheckPtoN4(3 * 8, 0x01020300, "1.2.3/24");
- CheckPtoN4(2 * 8, 0xa0000000, "0xa");
- CheckPtoN4(0, 0x02030405, "2.3.4.5/000");
- CheckPtoN4(1 * 8, 0x01020000, "1.2/8");
- CheckPtoN4(2 * 8, 0x01020000, "0x0102/16");
- CheckPtoN4(4 * 8, 0x02030405, "02.3.4.5");
-
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "::", &a6, sizeof(a6)));
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "::1", &a6, sizeof(a6)));
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "1234:5678::", &a6, sizeof(a6)));
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "12:34::ff", &a6, sizeof(a6)));
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4", &a6, sizeof(a6)));
- EXPECT_EQ(23, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4/23", &a6, sizeof(a6)));
- EXPECT_EQ(3 * 8, ares_inet_net_pton(AF_INET6, "12:34::ff/24", &a6, sizeof(a6)));
- EXPECT_EQ(0, ares_inet_net_pton(AF_INET6, "12:34::ff/0", &a6, sizeof(a6)));
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "12:34::ffff:0.2", &a6, sizeof(a6)));
- EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234", &a6, sizeof(a6)));
-
- // Various malformed versions
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, " ", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x ", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "x0", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0xXYZZY", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "xyzzy", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET+AF_INET6, "1.2.3.4", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "257.2.3.4", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "002.3.4.x", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "00.3.4.x", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.x", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5.6", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5.6/12", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4:5", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5/120", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5/1x", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5/x", &a4, sizeof(a4)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/240", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/02", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/2y", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/y", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":x", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ": :1234", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "::12345", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234::2345:3456::0011", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234::", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1.2.3.4", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":1234:1234:1234:1234:1234:1234:1234:1234", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":1234:1234:1234:1234:1234:1234:1234:1234:", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678", &a6, sizeof(a6)));
- // TODO(drysdale): check whether the next two tests should give -1.
- EXPECT_EQ(0, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678:5678", &a6, sizeof(a6)));
- EXPECT_EQ(0, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678:5678:5678", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:257.2.3.4", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:002.2.3.4", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4.5.6", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4.5", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.z", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3001.4", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3..4", &a6, sizeof(a6)));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.", &a6, sizeof(a6)));
-
- // Hex constants are allowed.
- EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x01020304", &a4, sizeof(a4)));
- expected = htonl(0x01020304);
- EXPECT_EQ(expected, a4.s_addr);
- EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x0a0b0c0d", &a4, sizeof(a4)));
- expected = htonl(0x0a0b0c0d);
- EXPECT_EQ(expected, a4.s_addr);
- EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x0A0B0C0D", &a4, sizeof(a4)));
- expected = htonl(0x0a0b0c0d);
- EXPECT_EQ(expected, a4.s_addr);
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x0xyz", &a4, sizeof(a4)));
- EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x1122334", &a4, sizeof(a4)));
- expected = htonl(0x11223340);
- EXPECT_EQ(expected, a4.s_addr); // huh?
-
- // No room, no room.
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "1.2.3.4", &a4, sizeof(a4) - 1));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff", &a6, sizeof(a6) - 1));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x01020304", &a4, 2));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x01020304", &a4, 0));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x0a0b0c0d", &a4, 0));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x0xyz", &a4, 0));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x1122334", &a4, sizeof(a4) - 1));
- EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "253", &a4, sizeof(a4) - 1));
-#endif
-
- EXPECT_EQ(1, ares_inet_pton(AF_INET, "1.2.3.4", &a4));
- EXPECT_EQ(1, ares_inet_pton(AF_INET6, "12:34::ff", &a6));
- EXPECT_EQ(1, ares_inet_pton(AF_INET6, "12:34::ffff:1.2.3.4", &a6));
- EXPECT_EQ(0, ares_inet_pton(AF_INET, "xyzzy", &a4));
- EXPECT_EQ(-1, ares_inet_pton(AF_INET+AF_INET6, "1.2.3.4", &a4));
-}
-
-TEST_F(LibraryTest, FreeCorruptData) {
- // ares_free_data(p) expects that there is a type field and a marker
- // field in the memory before p. Feed it incorrect versions of each.
- struct ares_data *data = (struct ares_data *)malloc(sizeof(struct ares_data));
- void* p = &(data->data);
-
- // Invalid type
- data->type = (ares_datatype)99;
- data->mark = ARES_DATATYPE_MARK;
- ares_free_data(p);
-
- // Invalid marker
- data->type = (ares_datatype)ARES_DATATYPE_MX_REPLY;
- data->mark = ARES_DATATYPE_MARK + 1;
- ares_free_data(p);
-
- // Null pointer
- ares_free_data(nullptr);
-
- free(data);
-}
-
-#ifndef CARES_SYMBOL_HIDING
-TEST_F(LibraryTest, FreeLongChain) {
- struct ares_addr_node *data = nullptr;
- for (int ii = 0; ii < 100000; ii++) {
- struct ares_addr_node *prev = (struct ares_addr_node*)ares_malloc_data(ARES_DATATYPE_ADDR_NODE);
- prev->next = data;
- data = prev;
- }
-
- ares_free_data(data);
-}
-
-TEST(LibraryInit, StrdupFailures) {
- EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
- char* copy = ares_strdup("string");
- EXPECT_NE(nullptr, copy);
- ares_free(copy);
- ares_library_cleanup();
-}
-
-TEST_F(LibraryTest, StrdupFailures) {
- SetAllocFail(1);
- char* copy = ares_strdup("string");
- EXPECT_EQ(nullptr, copy);
-}
-
-TEST_F(LibraryTest, MallocDataFail) {
- EXPECT_EQ(nullptr, ares_malloc_data((ares_datatype)99));
- SetAllocSizeFail(sizeof(struct ares_data));
- EXPECT_EQ(nullptr, ares_malloc_data(ARES_DATATYPE_MX_REPLY));
-}
-
-TEST(Misc, Bitncmp) {
- byte a[4] = {0x80, 0x01, 0x02, 0x03};
- byte b[4] = {0x80, 0x01, 0x02, 0x04};
- byte c[4] = {0x01, 0xFF, 0x80, 0x02};
- EXPECT_GT(0, ares__bitncmp(a, b, sizeof(a)*8));
- EXPECT_LT(0, ares__bitncmp(b, a, sizeof(a)*8));
- EXPECT_EQ(0, ares__bitncmp(a, a, sizeof(a)*8));
-
- for (int ii = 1; ii < (3*8+5); ii++) {
- EXPECT_EQ(0, ares__bitncmp(a, b, ii));
- EXPECT_EQ(0, ares__bitncmp(b, a, ii));
- EXPECT_LT(0, ares__bitncmp(a, c, ii));
- EXPECT_GT(0, ares__bitncmp(c, a, ii));
- }
-
- // Last byte differs at 5th bit
- EXPECT_EQ(0, ares__bitncmp(a, b, 3*8 + 3));
- EXPECT_EQ(0, ares__bitncmp(a, b, 3*8 + 4));
- EXPECT_EQ(0, ares__bitncmp(a, b, 3*8 + 5));
- EXPECT_GT(0, ares__bitncmp(a, b, 3*8 + 6));
- EXPECT_GT(0, ares__bitncmp(a, b, 3*8 + 7));
-}
-
-TEST_F(LibraryTest, Casts) {
- ares_ssize_t ssz = 100;
- unsigned int u = 100;
- int i = 100;
- long l = 100;
-
- unsigned int ru = aresx_sztoui(ssz);
- EXPECT_EQ(u, ru);
- int ri = aresx_sztosi(ssz);
- EXPECT_EQ(i, ri);
-
- ri = aresx_sltosi(l);
- EXPECT_EQ(l, (long)ri);
-}
-
-TEST_F(LibraryTest, ReadLine) {
- TempFile temp("abcde\n0123456789\nXYZ\n012345678901234567890\n\n");
- FILE *fp = fopen(temp.filename(), "r");
- size_t bufsize = 4;
- char *buf = (char *)ares_malloc(bufsize);
-
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("abcde", std::string(buf));
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("0123456789", std::string(buf));
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("XYZ", std::string(buf));
- SetAllocFail(1);
- EXPECT_EQ(ARES_ENOMEM, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ(nullptr, buf);
-
- fclose(fp);
- ares_free(buf);
-}
-
-TEST_F(LibraryTest, ReadLineNoBuf) {
- TempFile temp("abcde\n0123456789\nXYZ\n012345678901234567890");
- FILE *fp = fopen(temp.filename(), "r");
- size_t bufsize = 0;
- char *buf = nullptr;
-
- SetAllocFail(1);
- EXPECT_EQ(ARES_ENOMEM, ares__read_line(fp, &buf, &bufsize));
-
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("abcde", std::string(buf));
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("0123456789", std::string(buf));
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("XYZ", std::string(buf));
- EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
- EXPECT_EQ("012345678901234567890", std::string(buf));
-
- fclose(fp);
- ares_free(buf);
-}
-
-TEST(Misc, GetHostent) {
- TempFile hostsfile("1.2.3.4 example.com \n"
- " 2.3.4.5\tgoogle.com www.google.com\twww2.google.com\n"
- "#comment\n"
- "4.5.6.7\n"
- "1.3.5.7 \n"
- "::1 ipv6.com");
- struct hostent *host = nullptr;
- FILE *fp = fopen(hostsfile.filename(), "r");
- ASSERT_NE(nullptr, fp);
- EXPECT_EQ(ARES_EBADFAMILY, ares__get_hostent(fp, AF_INET+AF_INET6, &host));
- rewind(fp);
-
- EXPECT_EQ(ARES_SUCCESS, ares__get_hostent(fp, AF_INET, &host));
- ASSERT_NE(nullptr, host);
- std::stringstream ss1;
- ss1 << HostEnt(host);
- EXPECT_EQ("{'example.com' aliases=[] addrs=[1.2.3.4]}", ss1.str());
- ares_free_hostent(host);
- host = nullptr;
-
- EXPECT_EQ(ARES_SUCCESS, ares__get_hostent(fp, AF_INET, &host));
- ASSERT_NE(nullptr, host);
- std::stringstream ss2;
- ss2 << HostEnt(host);
- EXPECT_EQ("{'google.com' aliases=[www.google.com, www2.google.com] addrs=[2.3.4.5]}", ss2.str());
- ares_free_hostent(host);
- host = nullptr;
-
- EXPECT_EQ(ARES_EOF, ares__get_hostent(fp, AF_INET, &host));
-
- rewind(fp);
- EXPECT_EQ(ARES_SUCCESS, ares__get_hostent(fp, AF_INET6, &host));
- ASSERT_NE(nullptr, host);
- std::stringstream ss3;
- ss3 << HostEnt(host);
- EXPECT_EQ("{'ipv6.com' aliases=[] addrs=[0000:0000:0000:0000:0000:0000:0000:0001]}", ss3.str());
- ares_free_hostent(host);
- host = nullptr;
- EXPECT_EQ(ARES_EOF, ares__get_hostent(fp, AF_INET6, &host));
- fclose(fp);
-}
-
-TEST_F(LibraryTest, GetHostentAllocFail) {
- TempFile hostsfile("1.2.3.4 example.com alias1 alias2\n");
- struct hostent *host = nullptr;
- FILE *fp = fopen(hostsfile.filename(), "r");
- ASSERT_NE(nullptr, fp);
-
- for (int ii = 1; ii <= 8; ii++) {
- rewind(fp);
- ClearFails();
- SetAllocFail(ii);
- host = nullptr;
- EXPECT_EQ(ARES_ENOMEM, ares__get_hostent(fp, AF_INET, &host)) << ii;
- }
- fclose(fp);
-}
-
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <stdio.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+
+extern "C" {
+// Remove command-line defines of package variables for the test project...
+#undef PACKAGE_NAME
+#undef PACKAGE_BUGREPORT
+#undef PACKAGE_STRING
+#undef PACKAGE_TARNAME
+// ... so we can include the library's config without symbol redefinitions.
+#include "ares_setup.h"
+#include "ares_nowarn.h"
+#include "ares_inet_net_pton.h"
+#include "ares_data.h"
+#include "ares_private.h"
+#include "bitncmp.h"
+
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_SYS_UIO_H
+# include <sys/uio.h>
+#endif
+}
+
+#include <string>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+#ifndef CARES_SYMBOL_HIDING
+void CheckPtoN4(int size, unsigned int value, const char *input) {
+ struct in_addr a4;
+ a4.s_addr = 0;
+ uint32_t expected = htonl(value);
+ EXPECT_EQ(size, ares_inet_net_pton(AF_INET, input, &a4, sizeof(a4)))
+ << " for input " << input;
+ EXPECT_EQ(expected, a4.s_addr) << " for input " << input;
+}
+#endif
+
+TEST_F(LibraryTest, InetPtoN) {
+ struct in_addr a4;
+ struct in6_addr a6;
+
+#ifndef CARES_SYMBOL_HIDING
+ uint32_t expected;
+
+ CheckPtoN4(4 * 8, 0x01020304, "1.2.3.4");
+ CheckPtoN4(4 * 8, 0x81010101, "129.1.1.1");
+ CheckPtoN4(4 * 8, 0xC0010101, "192.1.1.1");
+ CheckPtoN4(4 * 8, 0xE0010101, "224.1.1.1");
+ CheckPtoN4(4 * 8, 0xE1010101, "225.1.1.1");
+ CheckPtoN4(4, 0xE0000000, "224");
+ CheckPtoN4(4 * 8, 0xFD000000, "253");
+ CheckPtoN4(4 * 8, 0xF0010101, "240.1.1.1");
+ CheckPtoN4(4 * 8, 0x02030405, "02.3.4.5");
+ CheckPtoN4(3 * 8, 0x01020304, "1.2.3.4/24");
+ CheckPtoN4(3 * 8, 0x01020300, "1.2.3/24");
+ CheckPtoN4(2 * 8, 0xa0000000, "0xa");
+ CheckPtoN4(0, 0x02030405, "2.3.4.5/000");
+ CheckPtoN4(1 * 8, 0x01020000, "1.2/8");
+ CheckPtoN4(2 * 8, 0x01020000, "0x0102/16");
+ CheckPtoN4(4 * 8, 0x02030405, "02.3.4.5");
+
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "::", &a6, sizeof(a6)));
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "::1", &a6, sizeof(a6)));
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "1234:5678::", &a6, sizeof(a6)));
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "12:34::ff", &a6, sizeof(a6)));
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4", &a6, sizeof(a6)));
+ EXPECT_EQ(23, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4/23", &a6, sizeof(a6)));
+ EXPECT_EQ(3 * 8, ares_inet_net_pton(AF_INET6, "12:34::ff/24", &a6, sizeof(a6)));
+ EXPECT_EQ(0, ares_inet_net_pton(AF_INET6, "12:34::ff/0", &a6, sizeof(a6)));
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "12:34::ffff:0.2", &a6, sizeof(a6)));
+ EXPECT_EQ(16 * 8, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234", &a6, sizeof(a6)));
+
+ // Various malformed versions
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, " ", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x ", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "x0", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0xXYZZY", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "xyzzy", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET+AF_INET6, "1.2.3.4", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "257.2.3.4", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "002.3.4.x", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "00.3.4.x", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.x", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5.6", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5.6/12", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4:5", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5/120", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5/1x", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "2.3.4.5/x", &a4, sizeof(a4)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/240", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/02", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/2y", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/y", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff/", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":x", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ": :1234", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "::12345", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234::2345:3456::0011", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234::", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1.2.3.4", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":1234:1234:1234:1234:1234:1234:1234:1234", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, ":1234:1234:1234:1234:1234:1234:1234:1234:", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678", &a6, sizeof(a6)));
+ // TODO(drysdale): check whether the next two tests should give -1.
+ EXPECT_EQ(0, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678:5678", &a6, sizeof(a6)));
+ EXPECT_EQ(0, ares_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678:5678:5678", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:257.2.3.4", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:002.2.3.4", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4.5.6", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4.5", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.z", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3001.4", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3..4", &a6, sizeof(a6)));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.", &a6, sizeof(a6)));
+
+ // Hex constants are allowed.
+ EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x01020304", &a4, sizeof(a4)));
+ expected = htonl(0x01020304);
+ EXPECT_EQ(expected, a4.s_addr);
+ EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x0a0b0c0d", &a4, sizeof(a4)));
+ expected = htonl(0x0a0b0c0d);
+ EXPECT_EQ(expected, a4.s_addr);
+ EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x0A0B0C0D", &a4, sizeof(a4)));
+ expected = htonl(0x0a0b0c0d);
+ EXPECT_EQ(expected, a4.s_addr);
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x0xyz", &a4, sizeof(a4)));
+ EXPECT_EQ(4 * 8, ares_inet_net_pton(AF_INET, "0x1122334", &a4, sizeof(a4)));
+ expected = htonl(0x11223340);
+ EXPECT_EQ(expected, a4.s_addr); // huh?
+
+ // No room, no room.
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "1.2.3.4", &a4, sizeof(a4) - 1));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET6, "12:34::ff", &a6, sizeof(a6) - 1));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x01020304", &a4, 2));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x01020304", &a4, 0));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x0a0b0c0d", &a4, 0));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x0xyz", &a4, 0));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "0x1122334", &a4, sizeof(a4) - 1));
+ EXPECT_EQ(-1, ares_inet_net_pton(AF_INET, "253", &a4, sizeof(a4) - 1));
+#endif
+
+ EXPECT_EQ(1, ares_inet_pton(AF_INET, "1.2.3.4", &a4));
+ EXPECT_EQ(1, ares_inet_pton(AF_INET6, "12:34::ff", &a6));
+ EXPECT_EQ(1, ares_inet_pton(AF_INET6, "12:34::ffff:1.2.3.4", &a6));
+ EXPECT_EQ(0, ares_inet_pton(AF_INET, "xyzzy", &a4));
+ EXPECT_EQ(-1, ares_inet_pton(AF_INET+AF_INET6, "1.2.3.4", &a4));
+}
+
+TEST_F(LibraryTest, FreeCorruptData) {
+ // ares_free_data(p) expects that there is a type field and a marker
+ // field in the memory before p. Feed it incorrect versions of each.
+ struct ares_data *data = (struct ares_data *)malloc(sizeof(struct ares_data));
+ void* p = &(data->data);
+
+ // Invalid type
+ data->type = (ares_datatype)99;
+ data->mark = ARES_DATATYPE_MARK;
+ ares_free_data(p);
+
+ // Invalid marker
+ data->type = (ares_datatype)ARES_DATATYPE_MX_REPLY;
+ data->mark = ARES_DATATYPE_MARK + 1;
+ ares_free_data(p);
+
+ // Null pointer
+ ares_free_data(nullptr);
+
+ free(data);
+}
+
+#ifndef CARES_SYMBOL_HIDING
+TEST_F(LibraryTest, FreeLongChain) {
+ struct ares_addr_node *data = nullptr;
+ for (int ii = 0; ii < 100000; ii++) {
+ struct ares_addr_node *prev = (struct ares_addr_node*)ares_malloc_data(ARES_DATATYPE_ADDR_NODE);
+ prev->next = data;
+ data = prev;
+ }
+
+ ares_free_data(data);
+}
+
+TEST(LibraryInit, StrdupFailures) {
+ EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
+ char* copy = ares_strdup("string");
+ EXPECT_NE(nullptr, copy);
+ ares_free(copy);
+ ares_library_cleanup();
+}
+
+TEST_F(LibraryTest, StrdupFailures) {
+ SetAllocFail(1);
+ char* copy = ares_strdup("string");
+ EXPECT_EQ(nullptr, copy);
+}
+
+TEST_F(LibraryTest, MallocDataFail) {
+ EXPECT_EQ(nullptr, ares_malloc_data((ares_datatype)99));
+ SetAllocSizeFail(sizeof(struct ares_data));
+ EXPECT_EQ(nullptr, ares_malloc_data(ARES_DATATYPE_MX_REPLY));
+}
+
+TEST(Misc, Bitncmp) {
+ byte a[4] = {0x80, 0x01, 0x02, 0x03};
+ byte b[4] = {0x80, 0x01, 0x02, 0x04};
+ byte c[4] = {0x01, 0xFF, 0x80, 0x02};
+ EXPECT_GT(0, ares__bitncmp(a, b, sizeof(a)*8));
+ EXPECT_LT(0, ares__bitncmp(b, a, sizeof(a)*8));
+ EXPECT_EQ(0, ares__bitncmp(a, a, sizeof(a)*8));
+
+ for (int ii = 1; ii < (3*8+5); ii++) {
+ EXPECT_EQ(0, ares__bitncmp(a, b, ii));
+ EXPECT_EQ(0, ares__bitncmp(b, a, ii));
+ EXPECT_LT(0, ares__bitncmp(a, c, ii));
+ EXPECT_GT(0, ares__bitncmp(c, a, ii));
+ }
+
+ // Last byte differs at 5th bit
+ EXPECT_EQ(0, ares__bitncmp(a, b, 3*8 + 3));
+ EXPECT_EQ(0, ares__bitncmp(a, b, 3*8 + 4));
+ EXPECT_EQ(0, ares__bitncmp(a, b, 3*8 + 5));
+ EXPECT_GT(0, ares__bitncmp(a, b, 3*8 + 6));
+ EXPECT_GT(0, ares__bitncmp(a, b, 3*8 + 7));
+}
+
+TEST_F(LibraryTest, Casts) {
+ ares_ssize_t ssz = 100;
+ unsigned int u = 100;
+ int i = 100;
+ long l = 100;
+
+ unsigned int ru = aresx_sztoui(ssz);
+ EXPECT_EQ(u, ru);
+ int ri = aresx_sztosi(ssz);
+ EXPECT_EQ(i, ri);
+
+ ri = aresx_sltosi(l);
+ EXPECT_EQ(l, (long)ri);
+}
+
+TEST_F(LibraryTest, ReadLine) {
+ TempFile temp("abcde\n0123456789\nXYZ\n012345678901234567890\n\n");
+ FILE *fp = fopen(temp.filename(), "r");
+ size_t bufsize = 4;
+ char *buf = (char *)ares_malloc(bufsize);
+
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("abcde", std::string(buf));
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("0123456789", std::string(buf));
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("XYZ", std::string(buf));
+ SetAllocFail(1);
+ EXPECT_EQ(ARES_ENOMEM, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ(nullptr, buf);
+
+ fclose(fp);
+ ares_free(buf);
+}
+
+TEST_F(LibraryTest, ReadLineNoBuf) {
+ TempFile temp("abcde\n0123456789\nXYZ\n012345678901234567890");
+ FILE *fp = fopen(temp.filename(), "r");
+ size_t bufsize = 0;
+ char *buf = nullptr;
+
+ SetAllocFail(1);
+ EXPECT_EQ(ARES_ENOMEM, ares__read_line(fp, &buf, &bufsize));
+
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("abcde", std::string(buf));
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("0123456789", std::string(buf));
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("XYZ", std::string(buf));
+ EXPECT_EQ(ARES_SUCCESS, ares__read_line(fp, &buf, &bufsize));
+ EXPECT_EQ("012345678901234567890", std::string(buf));
+
+ fclose(fp);
+ ares_free(buf);
+}
+
+TEST(Misc, GetHostent) {
+ TempFile hostsfile("1.2.3.4 example.com \n"
+ " 2.3.4.5\tgoogle.com www.google.com\twww2.google.com\n"
+ "#comment\n"
+ "4.5.6.7\n"
+ "1.3.5.7 \n"
+ "::1 ipv6.com");
+ struct hostent *host = nullptr;
+ FILE *fp = fopen(hostsfile.filename(), "r");
+ ASSERT_NE(nullptr, fp);
+ EXPECT_EQ(ARES_EBADFAMILY, ares__get_hostent(fp, AF_INET+AF_INET6, &host));
+ rewind(fp);
+
+ EXPECT_EQ(ARES_SUCCESS, ares__get_hostent(fp, AF_INET, &host));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss1;
+ ss1 << HostEnt(host);
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[1.2.3.4]}", ss1.str());
+ ares_free_hostent(host);
+ host = nullptr;
+
+ EXPECT_EQ(ARES_SUCCESS, ares__get_hostent(fp, AF_INET, &host));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss2;
+ ss2 << HostEnt(host);
+ EXPECT_EQ("{'google.com' aliases=[www.google.com, www2.google.com] addrs=[2.3.4.5]}", ss2.str());
+ ares_free_hostent(host);
+ host = nullptr;
+
+ EXPECT_EQ(ARES_EOF, ares__get_hostent(fp, AF_INET, &host));
+
+ rewind(fp);
+ EXPECT_EQ(ARES_SUCCESS, ares__get_hostent(fp, AF_INET6, &host));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss3;
+ ss3 << HostEnt(host);
+ EXPECT_EQ("{'ipv6.com' aliases=[] addrs=[0000:0000:0000:0000:0000:0000:0000:0001]}", ss3.str());
+ ares_free_hostent(host);
+ host = nullptr;
+ EXPECT_EQ(ARES_EOF, ares__get_hostent(fp, AF_INET6, &host));
+ fclose(fp);
+}
+
+TEST_F(LibraryTest, GetHostentAllocFail) {
+ TempFile hostsfile("1.2.3.4 example.com alias1 alias2\n");
+ struct hostent *host = nullptr;
+ FILE *fp = fopen(hostsfile.filename(), "r");
+ ASSERT_NE(nullptr, fp);
+
+ for (int ii = 1; ii <= 8; ii++) {
+ rewind(fp);
+ ClearFails();
+ SetAllocFail(ii);
+ host = nullptr;
+ EXPECT_EQ(ARES_ENOMEM, ares__get_hostent(fp, AF_INET, &host)) << ii;
+ }
+ fclose(fp);
+}
+
TEST_F(DefaultChannelTest, GetAddrInfoHostsPositive) {
TempFile hostsfile("1.2.3.4 example.com \n"
" 2.3.4.5\tgoogle.com www.google.com\twww2.google.com\n"
@@ -457,135 +457,135 @@ TEST_F(LibraryTest, GetAddrInfoAllocFail) {
fclose(fp);
}
-TEST(Misc, OnionDomain) {
- EXPECT_EQ(0, ares__is_onion_domain("onion.no"));
- EXPECT_EQ(0, ares__is_onion_domain(".onion.no"));
- EXPECT_EQ(1, ares__is_onion_domain(".onion"));
- EXPECT_EQ(1, ares__is_onion_domain(".onion."));
- EXPECT_EQ(1, ares__is_onion_domain("yes.onion"));
- EXPECT_EQ(1, ares__is_onion_domain("yes.onion."));
- EXPECT_EQ(1, ares__is_onion_domain("YES.ONION"));
- EXPECT_EQ(1, ares__is_onion_domain("YES.ONION."));
-}
-#endif
-
-#ifdef CARES_EXPOSE_STATICS
-// These tests access internal static functions from the library, which
-// are only exposed when CARES_EXPOSE_STATICS has been configured. As such
-// they are tightly couple to the internal library implementation details.
-extern "C" char *ares_striendstr(const char*, const char*);
-TEST_F(LibraryTest, Striendstr) {
- EXPECT_EQ(nullptr, ares_striendstr("abc", "12345"));
- EXPECT_NE(nullptr, ares_striendstr("abc12345", "12345"));
- EXPECT_NE(nullptr, ares_striendstr("abcxyzzy", "XYZZY"));
- EXPECT_NE(nullptr, ares_striendstr("xyzzy", "XYZZY"));
- EXPECT_EQ(nullptr, ares_striendstr("xyxzy", "XYZZY"));
- EXPECT_NE(nullptr, ares_striendstr("", ""));
- const char *str = "plugh";
- EXPECT_NE(nullptr, ares_striendstr(str, str));
-}
+TEST(Misc, OnionDomain) {
+ EXPECT_EQ(0, ares__is_onion_domain("onion.no"));
+ EXPECT_EQ(0, ares__is_onion_domain(".onion.no"));
+ EXPECT_EQ(1, ares__is_onion_domain(".onion"));
+ EXPECT_EQ(1, ares__is_onion_domain(".onion."));
+ EXPECT_EQ(1, ares__is_onion_domain("yes.onion"));
+ EXPECT_EQ(1, ares__is_onion_domain("yes.onion."));
+ EXPECT_EQ(1, ares__is_onion_domain("YES.ONION"));
+ EXPECT_EQ(1, ares__is_onion_domain("YES.ONION."));
+}
+#endif
+
+#ifdef CARES_EXPOSE_STATICS
+// These tests access internal static functions from the library, which
+// are only exposed when CARES_EXPOSE_STATICS has been configured. As such
+// they are tightly couple to the internal library implementation details.
+extern "C" char *ares_striendstr(const char*, const char*);
+TEST_F(LibraryTest, Striendstr) {
+ EXPECT_EQ(nullptr, ares_striendstr("abc", "12345"));
+ EXPECT_NE(nullptr, ares_striendstr("abc12345", "12345"));
+ EXPECT_NE(nullptr, ares_striendstr("abcxyzzy", "XYZZY"));
+ EXPECT_NE(nullptr, ares_striendstr("xyzzy", "XYZZY"));
+ EXPECT_EQ(nullptr, ares_striendstr("xyxzy", "XYZZY"));
+ EXPECT_NE(nullptr, ares_striendstr("", ""));
+ const char *str = "plugh";
+ EXPECT_NE(nullptr, ares_striendstr(str, str));
+}
extern "C" int ares__single_domain(ares_channel, const char*, char**);
-TEST_F(DefaultChannelTest, SingleDomain) {
- TempFile aliases("www www.google.com\n");
- EnvValue with_env("HOSTALIASES", aliases.filename());
-
- SetAllocSizeFail(128);
- char *ptr = nullptr;
+TEST_F(DefaultChannelTest, SingleDomain) {
+ TempFile aliases("www www.google.com\n");
+ EnvValue with_env("HOSTALIASES", aliases.filename());
+
+ SetAllocSizeFail(128);
+ char *ptr = nullptr;
EXPECT_EQ(ARES_ENOMEM, ares__single_domain(channel_, "www", &ptr));
-
- channel_->flags |= ARES_FLAG_NOSEARCH|ARES_FLAG_NOALIASES;
+
+ channel_->flags |= ARES_FLAG_NOSEARCH|ARES_FLAG_NOALIASES;
EXPECT_EQ(ARES_SUCCESS, ares__single_domain(channel_, "www", &ptr));
- EXPECT_EQ("www", std::string(ptr));
- ares_free(ptr);
- ptr = nullptr;
-
- SetAllocFail(1);
+ EXPECT_EQ("www", std::string(ptr));
+ ares_free(ptr);
+ ptr = nullptr;
+
+ SetAllocFail(1);
EXPECT_EQ(ARES_ENOMEM, ares__single_domain(channel_, "www", &ptr));
- EXPECT_EQ(nullptr, ptr);
-}
-#endif
-
-TEST_F(DefaultChannelTest, SaveInvalidChannel) {
- int saved = channel_->nservers;
- channel_->nservers = -1;
- struct ares_options opts;
- int optmask = 0;
- EXPECT_EQ(ARES_ENODATA, ares_save_options(channel_, &opts, &optmask));
- channel_->nservers = saved;
-}
-
-// Need to put this in own function due to nested lambda bug
-// in VS2013. (C2888)
-static int configure_socket(ares_socket_t s) {
- // transposed from ares-process, simplified non-block setter.
-#if defined(USE_BLOCKING_SOCKETS)
- return 0; /* returns success */
-#elif defined(HAVE_FCNTL_O_NONBLOCK)
- /* most recent unix versions */
- int flags;
- flags = fcntl(s, F_GETFL, 0);
- return fcntl(s, F_SETFL, flags | O_NONBLOCK);
-#elif defined(HAVE_IOCTL_FIONBIO)
- /* older unix versions */
- int flags = 1;
- return ioctl(s, FIONBIO, &flags);
-#elif defined(HAVE_IOCTLSOCKET_FIONBIO)
-#ifdef WATT32
- char flags = 1;
-#else
- /* Windows */
- unsigned long flags = 1UL;
-#endif
- return ioctlsocket(s, FIONBIO, &flags);
-#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
- /* Amiga */
- long flags = 1L;
- return IoctlSocket(s, FIONBIO, flags);
-#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
- /* BeOS */
- long b = 1L;
- return setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
-#else
-# error "no non-blocking method was found/used/set"
-#endif
-}
-
-// TODO: This should not really be in this file, but we need ares config
-// flags, and here they are available.
-const struct ares_socket_functions VirtualizeIO::default_functions = {
- [](int af, int type, int protocol, void *) -> ares_socket_t {
- auto s = ::socket(af, type, protocol);
- if (s == ARES_SOCKET_BAD) {
- return s;
- }
- if (configure_socket(s) != 0) {
- sclose(s);
- return ares_socket_t(-1);
- }
- return s;
- },
- [](ares_socket_t s, void * p) {
- return :: sclose(s);
- },
- [](ares_socket_t s, const struct sockaddr * addr, socklen_t len, void *) {
- return ::connect(s, addr, len);
- },
- [](ares_socket_t s, void * dst, size_t len, int flags, struct sockaddr * addr, socklen_t * alen, void *) -> ares_ssize_t {
-#ifdef HAVE_RECVFROM
- return ::recvfrom(s, reinterpret_cast<RECV_TYPE_ARG2>(dst), len, flags, addr, alen);
-#else
- return sread(s, dst, len);
-#endif
- },
- [](ares_socket_t s, const struct iovec * vec, int len, void *) {
+ EXPECT_EQ(nullptr, ptr);
+}
+#endif
+
+TEST_F(DefaultChannelTest, SaveInvalidChannel) {
+ int saved = channel_->nservers;
+ channel_->nservers = -1;
+ struct ares_options opts;
+ int optmask = 0;
+ EXPECT_EQ(ARES_ENODATA, ares_save_options(channel_, &opts, &optmask));
+ channel_->nservers = saved;
+}
+
+// Need to put this in own function due to nested lambda bug
+// in VS2013. (C2888)
+static int configure_socket(ares_socket_t s) {
+ // transposed from ares-process, simplified non-block setter.
+#if defined(USE_BLOCKING_SOCKETS)
+ return 0; /* returns success */
+#elif defined(HAVE_FCNTL_O_NONBLOCK)
+ /* most recent unix versions */
+ int flags;
+ flags = fcntl(s, F_GETFL, 0);
+ return fcntl(s, F_SETFL, flags | O_NONBLOCK);
+#elif defined(HAVE_IOCTL_FIONBIO)
+ /* older unix versions */
+ int flags = 1;
+ return ioctl(s, FIONBIO, &flags);
+#elif defined(HAVE_IOCTLSOCKET_FIONBIO)
+#ifdef WATT32
+ char flags = 1;
+#else
+ /* Windows */
+ unsigned long flags = 1UL;
+#endif
+ return ioctlsocket(s, FIONBIO, &flags);
+#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
+ /* Amiga */
+ long flags = 1L;
+ return IoctlSocket(s, FIONBIO, flags);
+#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
+ /* BeOS */
+ long b = 1L;
+ return setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
+#else
+# error "no non-blocking method was found/used/set"
+#endif
+}
+
+// TODO: This should not really be in this file, but we need ares config
+// flags, and here they are available.
+const struct ares_socket_functions VirtualizeIO::default_functions = {
+ [](int af, int type, int protocol, void *) -> ares_socket_t {
+ auto s = ::socket(af, type, protocol);
+ if (s == ARES_SOCKET_BAD) {
+ return s;
+ }
+ if (configure_socket(s) != 0) {
+ sclose(s);
+ return ares_socket_t(-1);
+ }
+ return s;
+ },
+ [](ares_socket_t s, void * p) {
+ return :: sclose(s);
+ },
+ [](ares_socket_t s, const struct sockaddr * addr, socklen_t len, void *) {
+ return ::connect(s, addr, len);
+ },
+ [](ares_socket_t s, void * dst, size_t len, int flags, struct sockaddr * addr, socklen_t * alen, void *) -> ares_ssize_t {
+#ifdef HAVE_RECVFROM
+ return ::recvfrom(s, reinterpret_cast<RECV_TYPE_ARG2>(dst), len, flags, addr, alen);
+#else
+ return sread(s, dst, len);
+#endif
+ },
+ [](ares_socket_t s, const struct iovec * vec, int len, void *) {
#ifndef HAVE_WRITEV
- return ares_writev(s, vec, len);
-#else
- return :: writev(s, vec, len);
-#endif
- }
-};
-
-
-} // namespace test
-} // namespace ares
+ return ares_writev(s, vec, len);
+#else
+ return :: writev(s, vec, len);
+#endif
+ }
+};
+
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-live.cc b/contrib/libs/c-ares/test/ares-test-live.cc
index 5510163e95..b5de37734e 100644
--- a/contrib/libs/c-ares/test/ares-test-live.cc
+++ b/contrib/libs/c-ares/test/ares-test-live.cc
@@ -1,23 +1,23 @@
-// This file includes tests that attempt to do real lookups
-// of DNS names using the local machine's live infrastructure.
-// As a result, we don't check the results very closely, to allow
-// for varying local configurations.
-
-#include "ares-test.h"
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-
-namespace ares {
-namespace test {
-
-// Use the address of Google's public DNS servers as example addresses that are
-// likely to be accessible everywhere/everywhen.
-unsigned char gdns_addr4[4] = {0x08, 0x08, 0x08, 0x08};
-unsigned char gdns_addr6[16] = {0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88};
-
+// This file includes tests that attempt to do real lookups
+// of DNS names using the local machine's live infrastructure.
+// As a result, we don't check the results very closely, to allow
+// for varying local configurations.
+
+#include "ares-test.h"
+
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+namespace ares {
+namespace test {
+
+// Use the address of Google's public DNS servers as example addresses that are
+// likely to be accessible everywhere/everywhen.
+unsigned char gdns_addr4[4] = {0x08, 0x08, 0x08, 0x08};
+unsigned char gdns_addr6[16] = {0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88};
+
MATCHER_P(IncludesAtLeastNumAddresses, n, "") {
if(!arg)
return false;
@@ -82,620 +82,620 @@ MATCHER_P(IncludesAddrType, addrtype, "") {
//EXPECT_THAT(result.ai_, IncludesAddrType(AF_INET));
//}
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByNameV4) {
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_LT(0, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET, result.host_.addrtype_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByNameV6) {
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_LT(0, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET6, result.host_.addrtype_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByAddrV4) {
- HostResult result;
- ares_gethostbyaddr(channel_, gdns_addr4, sizeof(gdns_addr4), AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_LT(0, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET, result.host_.addrtype_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByAddrV6) {
- HostResult result;
- ares_gethostbyaddr(channel_, gdns_addr6, sizeof(gdns_addr6), AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_LT(0, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET6, result.host_.addrtype_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetHostByNameFile) {
- struct hostent *host = nullptr;
-
- // Still need a channel even to query /etc/hosts.
- EXPECT_EQ(ARES_ENOTFOUND,
- ares_gethostbyname_file(nullptr, "localhost", AF_INET, &host));
-
- int rc = ares_gethostbyname_file(channel_, "bogus.mcname", AF_INET, &host);
- EXPECT_EQ(nullptr, host);
- EXPECT_EQ(ARES_ENOTFOUND, rc);
-
- rc = ares_gethostbyname_file(channel_, "localhost", AF_INET, &host);
- if (rc == ARES_SUCCESS) {
- EXPECT_NE(nullptr, host);
- ares_free_hostent(host);
- }
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameV4) {
- HostResult result;
- ares_gethostbyname(channel_, "localhost", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- if ((result.status_ != ARES_ENOTFOUND) && (result.status_ != ARES_ECONNREFUSED)) {
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ(1, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET, result.host_.addrtype_);
- EXPECT_NE(std::string::npos, result.host_.name_.find("localhost"));
- }
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameV6) {
- HostResult result;
- ares_gethostbyname(channel_, "localhost", AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- if (result.status_ == ARES_SUCCESS) {
- EXPECT_EQ(1, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET6, result.host_.addrtype_);
- std::stringstream ss;
- ss << HostEnt(result.host_);
- EXPECT_NE(std::string::npos, result.host_.name_.find("localhost"));
- }
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameIPV4) {
- HostResult result;
- ares_gethostbyname(channel_, "127.0.0.1", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ(1, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET, result.host_.addrtype_);
- std::stringstream ss;
- ss << HostEnt(result.host_);
- EXPECT_EQ("{'127.0.0.1' aliases=[] addrs=[127.0.0.1]}", ss.str());
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameIPV6) {
- HostResult result;
- ares_gethostbyname(channel_, "::1", AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- if (result.status_ != ARES_ENOTFOUND) {
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ(1, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET6, result.host_.addrtype_);
- std::stringstream ss;
- ss << HostEnt(result.host_);
- EXPECT_EQ("{'::1' aliases=[] addrs=[0000:0000:0000:0000:0000:0000:0000:0001]}", ss.str());
- }
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostFailFamily) {
- HostResult result;
- ares_gethostbyname(channel_, "127.0.0.1", AF_INET+AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTIMP, result.status_);
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostByAddrV4) {
- HostResult result;
- struct in_addr addr;
- addr.s_addr = htonl(INADDR_LOOPBACK);
- ares_gethostbyaddr(channel_, &addr, sizeof(addr), AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- if (result.status_ != ARES_ENOTFOUND) {
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_LT(0, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET, result.host_.addrtype_);
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByNameV4) {
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_LT(0, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET, result.host_.addrtype_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByNameV6) {
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_LT(0, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET6, result.host_.addrtype_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByAddrV4) {
+ HostResult result;
+ ares_gethostbyaddr(channel_, gdns_addr4, sizeof(gdns_addr4), AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_LT(0, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET, result.host_.addrtype_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveGetHostByAddrV6) {
+ HostResult result;
+ ares_gethostbyaddr(channel_, gdns_addr6, sizeof(gdns_addr6), AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_LT(0, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET6, result.host_.addrtype_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetHostByNameFile) {
+ struct hostent *host = nullptr;
+
+ // Still need a channel even to query /etc/hosts.
+ EXPECT_EQ(ARES_ENOTFOUND,
+ ares_gethostbyname_file(nullptr, "localhost", AF_INET, &host));
+
+ int rc = ares_gethostbyname_file(channel_, "bogus.mcname", AF_INET, &host);
+ EXPECT_EQ(nullptr, host);
+ EXPECT_EQ(ARES_ENOTFOUND, rc);
+
+ rc = ares_gethostbyname_file(channel_, "localhost", AF_INET, &host);
+ if (rc == ARES_SUCCESS) {
+ EXPECT_NE(nullptr, host);
+ ares_free_hostent(host);
+ }
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameV4) {
+ HostResult result;
+ ares_gethostbyname(channel_, "localhost", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ if ((result.status_ != ARES_ENOTFOUND) && (result.status_ != ARES_ECONNREFUSED)) {
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ(1, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET, result.host_.addrtype_);
+ EXPECT_NE(std::string::npos, result.host_.name_.find("localhost"));
+ }
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameV6) {
+ HostResult result;
+ ares_gethostbyname(channel_, "localhost", AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ if (result.status_ == ARES_SUCCESS) {
+ EXPECT_EQ(1, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET6, result.host_.addrtype_);
+ std::stringstream ss;
+ ss << HostEnt(result.host_);
+ EXPECT_NE(std::string::npos, result.host_.name_.find("localhost"));
+ }
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameIPV4) {
+ HostResult result;
+ ares_gethostbyname(channel_, "127.0.0.1", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ(1, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET, result.host_.addrtype_);
+ std::stringstream ss;
+ ss << HostEnt(result.host_);
+ EXPECT_EQ("{'127.0.0.1' aliases=[] addrs=[127.0.0.1]}", ss.str());
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostByNameIPV6) {
+ HostResult result;
+ ares_gethostbyname(channel_, "::1", AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ if (result.status_ != ARES_ENOTFOUND) {
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ(1, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET6, result.host_.addrtype_);
+ std::stringstream ss;
+ ss << HostEnt(result.host_);
+ EXPECT_EQ("{'::1' aliases=[] addrs=[0000:0000:0000:0000:0000:0000:0000:0001]}", ss.str());
+ }
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostFailFamily) {
+ HostResult result;
+ ares_gethostbyname(channel_, "127.0.0.1", AF_INET+AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTIMP, result.status_);
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostByAddrV4) {
+ HostResult result;
+ struct in_addr addr;
+ addr.s_addr = htonl(INADDR_LOOPBACK);
+ ares_gethostbyaddr(channel_, &addr, sizeof(addr), AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ if (result.status_ != ARES_ENOTFOUND) {
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_LT(0, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET, result.host_.addrtype_);
// oddly, travis does not resolve to localhost, but a random hostname starting with travis-job
if (result.host_.name_.find("travis-job") == std::string::npos) {
EXPECT_NE(std::string::npos,
result.host_.name_.find("localhost"));
}
- }
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetLocalhostByAddrV6) {
- HostResult result;
- struct in6_addr addr;
- memset(&addr, 0, sizeof(addr));
- addr.s6_addr[15] = 1; // in6addr_loopback
- ares_gethostbyaddr(channel_, &addr, sizeof(addr), AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- if (result.status_ != ARES_ENOTFOUND) {
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_LT(0, (int)result.host_.addrs_.size());
- EXPECT_EQ(AF_INET6, result.host_.addrtype_);
+ }
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetLocalhostByAddrV6) {
+ HostResult result;
+ struct in6_addr addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.s6_addr[15] = 1; // in6addr_loopback
+ ares_gethostbyaddr(channel_, &addr, sizeof(addr), AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ if (result.status_ != ARES_ENOTFOUND) {
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_LT(0, (int)result.host_.addrs_.size());
+ EXPECT_EQ(AF_INET6, result.host_.addrtype_);
const std::string& name = result.host_.name_;
EXPECT_TRUE(std::string::npos != name.find("localhost") ||
std::string::npos != name.find("ip6-loopback"));
- }
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetHostByAddrFailFamily) {
- HostResult result;
- unsigned char addr[4] = {8, 8, 8, 8};
- ares_gethostbyaddr(channel_, addr, sizeof(addr), AF_INET6+AF_INET,
- HostCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTIMP, result.status_);
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetHostByAddrFailAddrSize) {
- HostResult result;
- unsigned char addr[4] = {8, 8, 8, 8};
- ares_gethostbyaddr(channel_, addr, sizeof(addr) - 1, AF_INET,
- HostCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTIMP, result.status_);
-}
-
-TEST_P(DefaultChannelModeTest, LiveGetHostByAddrFailAlloc) {
- HostResult result;
- unsigned char addr[4] = {8, 8, 8, 8};
- SetAllocFail(1);
- ares_gethostbyaddr(channel_, addr, sizeof(addr), AF_INET,
- HostCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOMEM, result.status_);
-}
-
-INSTANTIATE_TEST_CASE_P(Modes, DefaultChannelModeTest,
- ::testing::Values("f", "b", "fb", "bf"));
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchA) {
- SearchResult result;
- ares_search(channel_, "www.youtube.com.", ns_c_in, ns_t_a,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveSearchEmptyA) {
- SearchResult result;
- ares_search(channel_, "", ns_c_in, ns_t_a,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_NE(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchNS) {
- SearchResult result;
- ares_search(channel_, "google.com.", ns_c_in, ns_t_ns,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchMX) {
- SearchResult result;
- ares_search(channel_, "google.com.", ns_c_in, ns_t_mx,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchTXT) {
- SearchResult result;
- ares_search(channel_, "google.com.", ns_c_in, ns_t_txt,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchSOA) {
- SearchResult result;
- ares_search(channel_, "google.com.", ns_c_in, ns_t_soa,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchSRV) {
- SearchResult result;
- ares_search(channel_, "_imap._tcp.gmail.com.", ns_c_in, ns_t_srv,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchANY) {
- SearchResult result;
- ares_search(channel_, "google.com.", ns_c_in, ns_t_any,
- SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(53);
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- if (verbose) std::cerr << "8.8.8.8:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4NoPort) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(0);
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- if (verbose) std::cerr << "8.8.8.8:0 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4UnassignedPort) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(4); // Unassigned at IANA
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- if (verbose) std::cerr << "8.8.8.8:4 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6Both) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6;
- sockaddr.sin6_port = htons(53);
- memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_TCP|ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_NOFQDN,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- if (verbose) std::cerr << "[2001:4860:4860::8888]:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6Neither) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6;
- sockaddr.sin6_port = htons(53);
- memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_TCP|ARES_NI_NOFQDN, // Neither specified => assume lookup host.
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- if (verbose) std::cerr << "[2001:4860:4860::8888]:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4Numeric) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(53);
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_TCP|ARES_NI_NUMERICHOST,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("8.8.8.8", result.node_);
- if (verbose) std::cerr << "8.8.8.8:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6Numeric) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6;
- sockaddr.sin6_port = htons(53);
- memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_DCCP|ARES_NI_NUMERICHOST,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("2001:4860:4860::8888%0", result.node_);
- if (verbose) std::cerr << "[2001:4860:4860::8888]:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6LinkLocal) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6;
- sockaddr.sin6_port = htons(53);
- unsigned char addr6[16] = {0xfe, 0x80, 0x01, 0x02, 0x01, 0x02, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04};
- memcpy(sockaddr.sin6_addr.s6_addr, addr6, 16);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_DCCP|ARES_NI_NUMERICHOST,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("fe80:102:102::304%0", result.node_);
- if (verbose) std::cerr << "[fe80:102:102::304]:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4NotFound) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(4); // Port 4 unassigned at IANA
- // RFC5737 says 192.0.2.0 should not be used publically.
- sockaddr.sin_addr.s_addr = htonl(0xC0000200);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("192.0.2.0", result.node_);
- if (verbose) std::cerr << "192.0.2.0:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4NotFoundFail) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(53);
- // RFC5737 says 192.0.2.0 should not be used publically.
- sockaddr.sin_addr.s_addr = htonl(0xC0000200);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP|ARES_NI_NAMEREQD,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTFOUND, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6NotFound) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6;
- sockaddr.sin6_port = htons(53);
- // 2001:db8::/32 is only supposed to be used in documentation.
- unsigned char addr6[16] = {0x20, 0x01, 0x0d, 0xb8, 0x01, 0x02, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04};
- memcpy(sockaddr.sin6_addr.s6_addr, addr6, 16);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("2001:db8:102::304%0", result.node_);
- if (verbose) std::cerr << "[2001:db8:102::304]:53 => " << result.node_ << "/" << result.service_ << std::endl;
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInvalidFamily) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6 + AF_INET;
- sockaddr.sin6_port = htons(53);
- memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTIMP, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInvalidFlags) {
- NameInfoResult result;
- struct sockaddr_in6 sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin6_family = AF_INET6;
- sockaddr.sin6_port = htons(53);
- memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
- // Ask for both a name-required, and a numeric host.
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP|ARES_NI_NUMERICHOST|ARES_NI_NAMEREQD,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_EBADFLAGS, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetServiceInfo) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(53);
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- // Just look up service info
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPSERVICE|ARES_NI_SCTP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("", result.node_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetServiceInfoNumeric) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(53);
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- // Just look up service info
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPSERVICE|ARES_NI_SCTP|ARES_NI_NUMERICSERV,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- EXPECT_EQ("", result.node_);
- EXPECT_EQ("53", result.service_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoAllocFail) {
- NameInfoResult result;
- struct sockaddr_in sockaddr;
- memset(&sockaddr, 0, sizeof(sockaddr));
- sockaddr.sin_family = AF_INET;
- sockaddr.sin_port = htons(53);
- sockaddr.sin_addr.s_addr = htonl(0x08080808);
- SetAllocFail(1);
- ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
- ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
- NameInfoCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOMEM, result.status_);
-}
-
-VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_GetSock) {
- ares_socket_t socks[3] = {ARES_SOCKET_BAD, ARES_SOCKET_BAD, ARES_SOCKET_BAD};
- int bitmask = ares_getsock(channel_, socks, 3);
- EXPECT_EQ(0, bitmask);
- bitmask = ares_getsock(channel_, nullptr, 0);
- EXPECT_EQ(0, bitmask);
-
- // Ask again with a pending query.
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- bitmask = ares_getsock(channel_, socks, 3);
- EXPECT_NE(0, bitmask);
- bitmask = ares_getsock(channel_, nullptr, 0);
- EXPECT_EQ(0, bitmask);
-
- Process();
-}
-
-TEST_F(LibraryTest, DISABLED_GetTCPSock) {
- ares_channel channel;
- struct ares_options opts = {0};
- opts.tcp_port = 53;
- opts.flags = ARES_FLAG_USEVC;
- int optmask = ARES_OPT_TCP_PORT | ARES_OPT_FLAGS;
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
- EXPECT_NE(nullptr, channel);
-
- ares_socket_t socks[3] = {ARES_SOCKET_BAD, ARES_SOCKET_BAD, ARES_SOCKET_BAD};
- int bitmask = ares_getsock(channel, socks, 3);
- EXPECT_EQ(0, bitmask);
- bitmask = ares_getsock(channel, nullptr, 0);
- EXPECT_EQ(0, bitmask);
-
- // Ask again with a pending query.
- HostResult result;
- ares_gethostbyname(channel, "www.google.com.", AF_INET, HostCallback, &result);
- bitmask = ares_getsock(channel, socks, 3);
- EXPECT_NE(0, bitmask);
- bitmask = ares_getsock(channel, nullptr, 0);
- EXPECT_EQ(0, bitmask);
-
- ProcessWork(channel, NoExtraFDs, nullptr);
-
- ares_destroy(channel);
-}
-
-TEST_F(DefaultChannelTest, VerifySocketFunctionCallback) {
- VirtualizeIO vio(channel_);
-
- auto my_functions = VirtualizeIO::default_functions;
- size_t count = 0;
-
- my_functions.asocket = [](int af, int type, int protocol, void * p) {
- EXPECT_NE(nullptr, p);
- (*reinterpret_cast<size_t *>(p))++;
- return ::socket(af, type, protocol);
- };
-
- ares_set_socket_functions(channel_, &my_functions, &count);
-
- {
- count = 0;
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_NE(0, count);
- }
-
- {
- count = 0;
- ares_channel copy;
- EXPECT_EQ(ARES_SUCCESS, ares_dup(&copy, channel_));
-
- HostResult result;
- ares_gethostbyname(copy, "www.google.com.", AF_INET, HostCallback, &result);
- ProcessWork(copy, NoExtraFDs, nullptr);
- EXPECT_TRUE(result.done_);
- ares_destroy(copy);
- EXPECT_NE(0, count);
- }
-
-}
-
+ }
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetHostByAddrFailFamily) {
+ HostResult result;
+ unsigned char addr[4] = {8, 8, 8, 8};
+ ares_gethostbyaddr(channel_, addr, sizeof(addr), AF_INET6+AF_INET,
+ HostCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTIMP, result.status_);
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetHostByAddrFailAddrSize) {
+ HostResult result;
+ unsigned char addr[4] = {8, 8, 8, 8};
+ ares_gethostbyaddr(channel_, addr, sizeof(addr) - 1, AF_INET,
+ HostCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTIMP, result.status_);
+}
+
+TEST_P(DefaultChannelModeTest, LiveGetHostByAddrFailAlloc) {
+ HostResult result;
+ unsigned char addr[4] = {8, 8, 8, 8};
+ SetAllocFail(1);
+ ares_gethostbyaddr(channel_, addr, sizeof(addr), AF_INET,
+ HostCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOMEM, result.status_);
+}
+
+INSTANTIATE_TEST_CASE_P(Modes, DefaultChannelModeTest,
+ ::testing::Values("f", "b", "fb", "bf"));
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchA) {
+ SearchResult result;
+ ares_search(channel_, "www.youtube.com.", ns_c_in, ns_t_a,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveSearchEmptyA) {
+ SearchResult result;
+ ares_search(channel_, "", ns_c_in, ns_t_a,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_NE(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchNS) {
+ SearchResult result;
+ ares_search(channel_, "google.com.", ns_c_in, ns_t_ns,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchMX) {
+ SearchResult result;
+ ares_search(channel_, "google.com.", ns_c_in, ns_t_mx,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchTXT) {
+ SearchResult result;
+ ares_search(channel_, "google.com.", ns_c_in, ns_t_txt,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchSOA) {
+ SearchResult result;
+ ares_search(channel_, "google.com.", ns_c_in, ns_t_soa,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchSRV) {
+ SearchResult result;
+ ares_search(channel_, "_imap._tcp.gmail.com.", ns_c_in, ns_t_srv,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_LiveSearchANY) {
+ SearchResult result;
+ ares_search(channel_, "google.com.", ns_c_in, ns_t_any,
+ SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(53);
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ if (verbose) std::cerr << "8.8.8.8:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4NoPort) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(0);
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ if (verbose) std::cerr << "8.8.8.8:0 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4UnassignedPort) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(4); // Unassigned at IANA
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ if (verbose) std::cerr << "8.8.8.8:4 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6Both) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6;
+ sockaddr.sin6_port = htons(53);
+ memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_TCP|ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_NOFQDN,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ if (verbose) std::cerr << "[2001:4860:4860::8888]:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6Neither) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6;
+ sockaddr.sin6_port = htons(53);
+ memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_TCP|ARES_NI_NOFQDN, // Neither specified => assume lookup host.
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ if (verbose) std::cerr << "[2001:4860:4860::8888]:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4Numeric) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(53);
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_TCP|ARES_NI_NUMERICHOST,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("8.8.8.8", result.node_);
+ if (verbose) std::cerr << "8.8.8.8:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6Numeric) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6;
+ sockaddr.sin6_port = htons(53);
+ memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_DCCP|ARES_NI_NUMERICHOST,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("2001:4860:4860::8888%0", result.node_);
+ if (verbose) std::cerr << "[2001:4860:4860::8888]:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6LinkLocal) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6;
+ sockaddr.sin6_port = htons(53);
+ unsigned char addr6[16] = {0xfe, 0x80, 0x01, 0x02, 0x01, 0x02, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04};
+ memcpy(sockaddr.sin6_addr.s6_addr, addr6, 16);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_DCCP|ARES_NI_NUMERICHOST,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("fe80:102:102::304%0", result.node_);
+ if (verbose) std::cerr << "[fe80:102:102::304]:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4NotFound) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(4); // Port 4 unassigned at IANA
+ // RFC5737 says 192.0.2.0 should not be used publically.
+ sockaddr.sin_addr.s_addr = htonl(0xC0000200);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("192.0.2.0", result.node_);
+ if (verbose) std::cerr << "192.0.2.0:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV4NotFoundFail) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(53);
+ // RFC5737 says 192.0.2.0 should not be used publically.
+ sockaddr.sin_addr.s_addr = htonl(0xC0000200);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP|ARES_NI_NAMEREQD,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTFOUND, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoV6NotFound) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6;
+ sockaddr.sin6_port = htons(53);
+ // 2001:db8::/32 is only supposed to be used in documentation.
+ unsigned char addr6[16] = {0x20, 0x01, 0x0d, 0xb8, 0x01, 0x02, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04};
+ memcpy(sockaddr.sin6_addr.s6_addr, addr6, 16);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("2001:db8:102::304%0", result.node_);
+ if (verbose) std::cerr << "[2001:db8:102::304]:53 => " << result.node_ << "/" << result.service_ << std::endl;
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInvalidFamily) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6 + AF_INET;
+ sockaddr.sin6_port = htons(53);
+ memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTIMP, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInvalidFlags) {
+ NameInfoResult result;
+ struct sockaddr_in6 sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin6_family = AF_INET6;
+ sockaddr.sin6_port = htons(53);
+ memcpy(sockaddr.sin6_addr.s6_addr, gdns_addr6, 16);
+ // Ask for both a name-required, and a numeric host.
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP|ARES_NI_NUMERICHOST|ARES_NI_NAMEREQD,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_EBADFLAGS, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetServiceInfo) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(53);
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ // Just look up service info
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPSERVICE|ARES_NI_SCTP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("", result.node_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetServiceInfoNumeric) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(53);
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ // Just look up service info
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPSERVICE|ARES_NI_SCTP|ARES_NI_NUMERICSERV,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ EXPECT_EQ("", result.node_);
+ EXPECT_EQ("53", result.service_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, LiveGetNameInfoAllocFail) {
+ NameInfoResult result;
+ struct sockaddr_in sockaddr;
+ memset(&sockaddr, 0, sizeof(sockaddr));
+ sockaddr.sin_family = AF_INET;
+ sockaddr.sin_port = htons(53);
+ sockaddr.sin_addr.s_addr = htonl(0x08080808);
+ SetAllocFail(1);
+ ares_getnameinfo(channel_, (const struct sockaddr*)&sockaddr, sizeof(sockaddr),
+ ARES_NI_LOOKUPHOST|ARES_NI_LOOKUPSERVICE|ARES_NI_UDP,
+ NameInfoCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOMEM, result.status_);
+}
+
+VIRT_NONVIRT_TEST_F(DefaultChannelTest, DISABLED_GetSock) {
+ ares_socket_t socks[3] = {ARES_SOCKET_BAD, ARES_SOCKET_BAD, ARES_SOCKET_BAD};
+ int bitmask = ares_getsock(channel_, socks, 3);
+ EXPECT_EQ(0, bitmask);
+ bitmask = ares_getsock(channel_, nullptr, 0);
+ EXPECT_EQ(0, bitmask);
+
+ // Ask again with a pending query.
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ bitmask = ares_getsock(channel_, socks, 3);
+ EXPECT_NE(0, bitmask);
+ bitmask = ares_getsock(channel_, nullptr, 0);
+ EXPECT_EQ(0, bitmask);
+
+ Process();
+}
+
+TEST_F(LibraryTest, DISABLED_GetTCPSock) {
+ ares_channel channel;
+ struct ares_options opts = {0};
+ opts.tcp_port = 53;
+ opts.flags = ARES_FLAG_USEVC;
+ int optmask = ARES_OPT_TCP_PORT | ARES_OPT_FLAGS;
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
+ EXPECT_NE(nullptr, channel);
+
+ ares_socket_t socks[3] = {ARES_SOCKET_BAD, ARES_SOCKET_BAD, ARES_SOCKET_BAD};
+ int bitmask = ares_getsock(channel, socks, 3);
+ EXPECT_EQ(0, bitmask);
+ bitmask = ares_getsock(channel, nullptr, 0);
+ EXPECT_EQ(0, bitmask);
+
+ // Ask again with a pending query.
+ HostResult result;
+ ares_gethostbyname(channel, "www.google.com.", AF_INET, HostCallback, &result);
+ bitmask = ares_getsock(channel, socks, 3);
+ EXPECT_NE(0, bitmask);
+ bitmask = ares_getsock(channel, nullptr, 0);
+ EXPECT_EQ(0, bitmask);
+
+ ProcessWork(channel, NoExtraFDs, nullptr);
+
+ ares_destroy(channel);
+}
+
+TEST_F(DefaultChannelTest, VerifySocketFunctionCallback) {
+ VirtualizeIO vio(channel_);
+
+ auto my_functions = VirtualizeIO::default_functions;
+ size_t count = 0;
+
+ my_functions.asocket = [](int af, int type, int protocol, void * p) {
+ EXPECT_NE(nullptr, p);
+ (*reinterpret_cast<size_t *>(p))++;
+ return ::socket(af, type, protocol);
+ };
+
+ ares_set_socket_functions(channel_, &my_functions, &count);
+
+ {
+ count = 0;
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_NE(0, count);
+ }
+
+ {
+ count = 0;
+ ares_channel copy;
+ EXPECT_EQ(ARES_SUCCESS, ares_dup(&copy, channel_));
+
+ HostResult result;
+ ares_gethostbyname(copy, "www.google.com.", AF_INET, HostCallback, &result);
+ ProcessWork(copy, NoExtraFDs, nullptr);
+ EXPECT_TRUE(result.done_);
+ ares_destroy(copy);
+ EXPECT_NE(0, count);
+ }
+
+}
+
TEST_F(DefaultChannelTest, LiveSetServers) {
struct ares_addr_node server1;
struct ares_addr_node server2;
@@ -705,7 +705,7 @@ TEST_F(DefaultChannelTest, LiveSetServers) {
server2.next = nullptr;
server2.family = AF_INET;
server2.addr.addr4.s_addr = htonl(0x02030405);
-
+
// Change not allowed while request is pending
HostResult result;
ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
@@ -745,5 +745,5 @@ TEST_F(DefaultChannelTest, LiveSetServersCSV) {
}
-} // namespace test
-} // namespace ares
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-misc.cc b/contrib/libs/c-ares/test/ares-test-misc.cc
index 6fc28a8f97..b42987ef39 100644
--- a/contrib/libs/c-ares/test/ares-test-misc.cc
+++ b/contrib/libs/c-ares/test/ares-test-misc.cc
@@ -1,282 +1,282 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <string>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(DefaultChannelTest, GetServers) {
- std::vector<std::string> servers = GetNameServers(channel_);
- if (verbose) {
- for (const std::string& server : servers) {
- std::cerr << "Nameserver: " << server << std::endl;
- }
- }
-}
-
-TEST_F(DefaultChannelTest, GetServersFailures) {
- EXPECT_EQ(ARES_SUCCESS,
- ares_set_servers_csv(channel_, "1.2.3.4,2.3.4.5"));
- struct ares_addr_node* servers = nullptr;
- SetAllocFail(1);
- EXPECT_EQ(ARES_ENOMEM, ares_get_servers(channel_, &servers));
- SetAllocFail(2);
- EXPECT_EQ(ARES_ENOMEM, ares_get_servers(channel_, &servers));
- EXPECT_EQ(ARES_ENODATA, ares_get_servers(nullptr, &servers));
-}
-
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <string>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(DefaultChannelTest, GetServers) {
+ std::vector<std::string> servers = GetNameServers(channel_);
+ if (verbose) {
+ for (const std::string& server : servers) {
+ std::cerr << "Nameserver: " << server << std::endl;
+ }
+ }
+}
+
+TEST_F(DefaultChannelTest, GetServersFailures) {
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_set_servers_csv(channel_, "1.2.3.4,2.3.4.5"));
+ struct ares_addr_node* servers = nullptr;
+ SetAllocFail(1);
+ EXPECT_EQ(ARES_ENOMEM, ares_get_servers(channel_, &servers));
+ SetAllocFail(2);
+ EXPECT_EQ(ARES_ENOMEM, ares_get_servers(channel_, &servers));
+ EXPECT_EQ(ARES_ENODATA, ares_get_servers(nullptr, &servers));
+}
+
TEST_F(DefaultChannelTest, SetServers) {
- EXPECT_EQ(ARES_SUCCESS, ares_set_servers(channel_, nullptr));
- std::vector<std::string> empty;
- EXPECT_EQ(empty, GetNameServers(channel_));
-
- struct ares_addr_node server1;
- struct ares_addr_node server2;
- server1.next = &server2;
- server1.family = AF_INET;
- server1.addr.addr4.s_addr = htonl(0x01020304);
- server2.next = nullptr;
- server2.family = AF_INET;
- server2.addr.addr4.s_addr = htonl(0x02030405);
- EXPECT_EQ(ARES_ENODATA, ares_set_servers(nullptr, &server1));
-
- EXPECT_EQ(ARES_SUCCESS, ares_set_servers(channel_, &server1));
- std::vector<std::string> expected = {"1.2.3.4", "2.3.4.5"};
- EXPECT_EQ(expected, GetNameServers(channel_));
-}
-
+ EXPECT_EQ(ARES_SUCCESS, ares_set_servers(channel_, nullptr));
+ std::vector<std::string> empty;
+ EXPECT_EQ(empty, GetNameServers(channel_));
+
+ struct ares_addr_node server1;
+ struct ares_addr_node server2;
+ server1.next = &server2;
+ server1.family = AF_INET;
+ server1.addr.addr4.s_addr = htonl(0x01020304);
+ server2.next = nullptr;
+ server2.family = AF_INET;
+ server2.addr.addr4.s_addr = htonl(0x02030405);
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers(nullptr, &server1));
+
+ EXPECT_EQ(ARES_SUCCESS, ares_set_servers(channel_, &server1));
+ std::vector<std::string> expected = {"1.2.3.4", "2.3.4.5"};
+ EXPECT_EQ(expected, GetNameServers(channel_));
+}
+
TEST_F(DefaultChannelTest, SetServersPorts) {
- EXPECT_EQ(ARES_SUCCESS, ares_set_servers_ports(channel_, nullptr));
- std::vector<std::string> empty;
- EXPECT_EQ(empty, GetNameServers(channel_));
-
- struct ares_addr_port_node server1;
- struct ares_addr_port_node server2;
- server1.next = &server2;
- server1.family = AF_INET;
- server1.addr.addr4.s_addr = htonl(0x01020304);
- server1.udp_port = 111;
- server1.tcp_port = 111;
- server2.next = nullptr;
- server2.family = AF_INET;
- server2.addr.addr4.s_addr = htonl(0x02030405);
- server2.udp_port = 0;
- server2.tcp_port = 0;;
- EXPECT_EQ(ARES_ENODATA, ares_set_servers_ports(nullptr, &server1));
-
- EXPECT_EQ(ARES_SUCCESS, ares_set_servers_ports(channel_, &server1));
- std::vector<std::string> expected = {"1.2.3.4:111", "2.3.4.5"};
- EXPECT_EQ(expected, GetNameServers(channel_));
-}
-
+ EXPECT_EQ(ARES_SUCCESS, ares_set_servers_ports(channel_, nullptr));
+ std::vector<std::string> empty;
+ EXPECT_EQ(empty, GetNameServers(channel_));
+
+ struct ares_addr_port_node server1;
+ struct ares_addr_port_node server2;
+ server1.next = &server2;
+ server1.family = AF_INET;
+ server1.addr.addr4.s_addr = htonl(0x01020304);
+ server1.udp_port = 111;
+ server1.tcp_port = 111;
+ server2.next = nullptr;
+ server2.family = AF_INET;
+ server2.addr.addr4.s_addr = htonl(0x02030405);
+ server2.udp_port = 0;
+ server2.tcp_port = 0;;
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers_ports(nullptr, &server1));
+
+ EXPECT_EQ(ARES_SUCCESS, ares_set_servers_ports(channel_, &server1));
+ std::vector<std::string> expected = {"1.2.3.4:111", "2.3.4.5"};
+ EXPECT_EQ(expected, GetNameServers(channel_));
+}
+
TEST_F(DefaultChannelTest, SetServersCSV) {
- EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "1.2.3.4"));
- EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "xyzzy,plugh"));
- EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "256.1.2.3"));
- EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "1.2.3.4.5"));
- EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "1:2:3:4:5"));
-
- EXPECT_EQ(ARES_SUCCESS,
- ares_set_servers_csv(channel_, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
- std::vector<std::string> expected = {"1.2.3.4", "0102:0304:0506:0708:0910:1112:1314:1516", "2.3.4.5"};
- EXPECT_EQ(expected, GetNameServers(channel_));
-
- // Same, with spaces
- EXPECT_EQ(ARES_EBADSTR,
- ares_set_servers_csv(channel_, "1.2.3.4 , 0102:0304:0506:0708:0910:1112:1314:1516, 2.3.4.5"));
-
- // Same, with ports
- EXPECT_EQ(ARES_SUCCESS,
- ares_set_servers_csv(channel_, "1.2.3.4:54,[0102:0304:0506:0708:0910:1112:1314:1516]:80,2.3.4.5:55"));
- EXPECT_EQ(expected, GetNameServers(channel_));
- EXPECT_EQ(ARES_SUCCESS,
- ares_set_servers_ports_csv(channel_, "1.2.3.4:54,[0102:0304:0506:0708:0910:1112:1314:1516]:80,2.3.4.5:55"));
- std::vector<std::string> expected2 = {"1.2.3.4:54", "[0102:0304:0506:0708:0910:1112:1314:1516]:80", "2.3.4.5:55"};
- EXPECT_EQ(expected2, GetNameServers(channel_));
-
- // Should survive duplication
- ares_channel channel2;
- EXPECT_EQ(ARES_SUCCESS, ares_dup(&channel2, channel_));
- EXPECT_EQ(expected2, GetNameServers(channel2));
- ares_destroy(channel2);
-
- // Allocation failure cases
- for (int fail = 1; fail <= 5; fail++) {
- SetAllocFail(fail);
- EXPECT_EQ(ARES_ENOMEM,
- ares_set_servers_csv(channel_, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
- }
-
- // Blank servers
- EXPECT_EQ(ARES_SUCCESS, ares_set_servers_csv(channel_, ""));
- std::vector<std::string> none;
- EXPECT_EQ(none, GetNameServers(channel_));
-
- EXPECT_EQ(ARES_EBADSTR, ares_set_servers_csv(channel_, "2.3.4.5,1.2.3.4:,3.4.5.6"));
- EXPECT_EQ(ARES_EBADSTR, ares_set_servers_csv(channel_, "2.3.4.5,1.2.3.4:Z,3.4.5.6"));
-}
-
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "1.2.3.4"));
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "xyzzy,plugh"));
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "256.1.2.3"));
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "1.2.3.4.5"));
+ EXPECT_EQ(ARES_ENODATA, ares_set_servers_csv(nullptr, "1:2:3:4:5"));
+
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_set_servers_csv(channel_, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
+ std::vector<std::string> expected = {"1.2.3.4", "0102:0304:0506:0708:0910:1112:1314:1516", "2.3.4.5"};
+ EXPECT_EQ(expected, GetNameServers(channel_));
+
+ // Same, with spaces
+ EXPECT_EQ(ARES_EBADSTR,
+ ares_set_servers_csv(channel_, "1.2.3.4 , 0102:0304:0506:0708:0910:1112:1314:1516, 2.3.4.5"));
+
+ // Same, with ports
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_set_servers_csv(channel_, "1.2.3.4:54,[0102:0304:0506:0708:0910:1112:1314:1516]:80,2.3.4.5:55"));
+ EXPECT_EQ(expected, GetNameServers(channel_));
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_set_servers_ports_csv(channel_, "1.2.3.4:54,[0102:0304:0506:0708:0910:1112:1314:1516]:80,2.3.4.5:55"));
+ std::vector<std::string> expected2 = {"1.2.3.4:54", "[0102:0304:0506:0708:0910:1112:1314:1516]:80", "2.3.4.5:55"};
+ EXPECT_EQ(expected2, GetNameServers(channel_));
+
+ // Should survive duplication
+ ares_channel channel2;
+ EXPECT_EQ(ARES_SUCCESS, ares_dup(&channel2, channel_));
+ EXPECT_EQ(expected2, GetNameServers(channel2));
+ ares_destroy(channel2);
+
+ // Allocation failure cases
+ for (int fail = 1; fail <= 5; fail++) {
+ SetAllocFail(fail);
+ EXPECT_EQ(ARES_ENOMEM,
+ ares_set_servers_csv(channel_, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
+ }
+
+ // Blank servers
+ EXPECT_EQ(ARES_SUCCESS, ares_set_servers_csv(channel_, ""));
+ std::vector<std::string> none;
+ EXPECT_EQ(none, GetNameServers(channel_));
+
+ EXPECT_EQ(ARES_EBADSTR, ares_set_servers_csv(channel_, "2.3.4.5,1.2.3.4:,3.4.5.6"));
+ EXPECT_EQ(ARES_EBADSTR, ares_set_servers_csv(channel_, "2.3.4.5,1.2.3.4:Z,3.4.5.6"));
+}
+
TEST_F(DefaultChannelTest, TimeoutValue) {
- struct timeval tinfo;
- tinfo.tv_sec = 0;
- tinfo.tv_usec = 0;
- struct timeval tmax;
- tmax.tv_sec = 0;
- tmax.tv_usec = 10;
- struct timeval* pt;
-
- // No timers => get max back.
- pt = ares_timeout(channel_, &tmax, &tinfo);
- EXPECT_EQ(&tmax, pt);
- EXPECT_EQ(0, pt->tv_sec);
- EXPECT_EQ(10, pt->tv_usec);
-
- pt = ares_timeout(channel_, nullptr, &tinfo);
- EXPECT_EQ(nullptr, pt);
-
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
-
- // Now there's a timer running.
- pt = ares_timeout(channel_, &tmax, &tinfo);
- EXPECT_EQ(&tmax, pt);
- EXPECT_EQ(0, pt->tv_sec);
- EXPECT_EQ(10, pt->tv_usec);
-
- tmax.tv_sec = 100;
- pt = ares_timeout(channel_, &tmax, &tinfo);
- EXPECT_EQ(&tinfo, pt);
-
- pt = ares_timeout(channel_, nullptr, &tinfo);
- EXPECT_EQ(&tinfo, pt);
-
- Process();
-}
-
-TEST_F(LibraryTest, InetNtoP) {
- struct in_addr addr;
- addr.s_addr = htonl(0x01020304);
- char buffer[256];
- EXPECT_EQ(buffer, ares_inet_ntop(AF_INET, &addr, buffer, sizeof(buffer)));
- EXPECT_EQ("1.2.3.4", std::string(buffer));
-}
-
-TEST_F(LibraryTest, Mkquery) {
- byte* p;
- int len;
- ares_mkquery("example.com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len);
- std::vector<byte> data(p, p + len);
- ares_free_string(p);
-
- std::string actual = PacketToString(data);
- DNSPacket pkt;
- pkt.set_qid(0x1234).add_question(new DNSQuestion("example.com", ns_t_a));
- std::string expected = PacketToString(pkt.data());
- EXPECT_EQ(expected, actual);
-}
-
-TEST_F(LibraryTest, CreateQuery) {
- byte* p;
- int len;
- EXPECT_EQ(ARES_SUCCESS,
- ares_create_query("exam\\@le.com", ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
- std::vector<byte> data(p, p + len);
- ares_free_string(p);
-
- std::string actual = PacketToString(data);
- DNSPacket pkt;
- pkt.set_qid(0x1234).add_question(new DNSQuestion("exam@le.com", ns_t_a));
- std::string expected = PacketToString(pkt.data());
- EXPECT_EQ(expected, actual);
-}
-
-TEST_F(LibraryTest, CreateQueryTrailingEscapedDot) {
- byte* p;
- int len;
- EXPECT_EQ(ARES_SUCCESS,
- ares_create_query("example.com\\.", ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
- std::vector<byte> data(p, p + len);
- ares_free_string(p);
-
- std::string actual = PacketToString(data);
- EXPECT_EQ("REQ QRY Q:{'example.com\\.' IN A}", actual);
-}
-
-TEST_F(LibraryTest, CreateQueryNameTooLong) {
- byte* p;
- int len;
- EXPECT_EQ(ARES_EBADNAME,
- ares_create_query(
- "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789."
- "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789."
- "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789."
- "x1234567890123456789.y1234567890123456789.",
- ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0));
-}
-
-TEST_F(LibraryTest, CreateQueryFailures) {
- byte* p;
- int len;
- // RC1035 has a 255 byte limit on names.
- std::string longname;
- for (int ii = 0; ii < 17; ii++) {
- longname += "fedcba9876543210";
- }
- p = nullptr;
- EXPECT_EQ(ARES_EBADNAME,
- ares_create_query(longname.c_str(), ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
- if (p) ares_free_string(p);
-
- SetAllocFail(1);
-
- p = nullptr;
- EXPECT_EQ(ARES_ENOMEM,
- ares_create_query("example.com", ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
- if (p) ares_free_string(p);
-
- // 63-char limit on a single label
- std::string longlabel = "a.a123456789b123456789c123456789d123456789e123456789f123456789g123456789.org";
- p = nullptr;
- EXPECT_EQ(ARES_EBADNAME,
- ares_create_query(longlabel.c_str(), ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
- if (p) ares_free_string(p);
-
- // Empty non-terminal label
- p = nullptr;
- EXPECT_EQ(ARES_EBADNAME,
- ares_create_query("example..com", ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
- if (p) ares_free_string(p);
-}
-
-TEST_F(LibraryTest, CreateQueryOnionDomain) {
- byte* p;
- int len;
- EXPECT_EQ(ARES_ENOTFOUND,
- ares_create_query("dontleak.onion", ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 0));
-}
-
-TEST_F(DefaultChannelTest, HostByNameOnionDomain) {
- HostResult result;
- ares_gethostbyname(channel_, "dontleak.onion", AF_INET, HostCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTFOUND, result.status_);
-}
-
-TEST_F(DefaultChannelTest, HostByNameFileOnionDomain) {
- struct hostent *h;
- EXPECT_EQ(ARES_ENOTFOUND,
- ares_gethostbyname_file(channel_, "dontleak.onion", AF_INET, &h));
-}
-
+ struct timeval tinfo;
+ tinfo.tv_sec = 0;
+ tinfo.tv_usec = 0;
+ struct timeval tmax;
+ tmax.tv_sec = 0;
+ tmax.tv_usec = 10;
+ struct timeval* pt;
+
+ // No timers => get max back.
+ pt = ares_timeout(channel_, &tmax, &tinfo);
+ EXPECT_EQ(&tmax, pt);
+ EXPECT_EQ(0, pt->tv_sec);
+ EXPECT_EQ(10, pt->tv_usec);
+
+ pt = ares_timeout(channel_, nullptr, &tinfo);
+ EXPECT_EQ(nullptr, pt);
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+
+ // Now there's a timer running.
+ pt = ares_timeout(channel_, &tmax, &tinfo);
+ EXPECT_EQ(&tmax, pt);
+ EXPECT_EQ(0, pt->tv_sec);
+ EXPECT_EQ(10, pt->tv_usec);
+
+ tmax.tv_sec = 100;
+ pt = ares_timeout(channel_, &tmax, &tinfo);
+ EXPECT_EQ(&tinfo, pt);
+
+ pt = ares_timeout(channel_, nullptr, &tinfo);
+ EXPECT_EQ(&tinfo, pt);
+
+ Process();
+}
+
+TEST_F(LibraryTest, InetNtoP) {
+ struct in_addr addr;
+ addr.s_addr = htonl(0x01020304);
+ char buffer[256];
+ EXPECT_EQ(buffer, ares_inet_ntop(AF_INET, &addr, buffer, sizeof(buffer)));
+ EXPECT_EQ("1.2.3.4", std::string(buffer));
+}
+
+TEST_F(LibraryTest, Mkquery) {
+ byte* p;
+ int len;
+ ares_mkquery("example.com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len);
+ std::vector<byte> data(p, p + len);
+ ares_free_string(p);
+
+ std::string actual = PacketToString(data);
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).add_question(new DNSQuestion("example.com", ns_t_a));
+ std::string expected = PacketToString(pkt.data());
+ EXPECT_EQ(expected, actual);
+}
+
+TEST_F(LibraryTest, CreateQuery) {
+ byte* p;
+ int len;
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_create_query("exam\\@le.com", ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+ std::vector<byte> data(p, p + len);
+ ares_free_string(p);
+
+ std::string actual = PacketToString(data);
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).add_question(new DNSQuestion("exam@le.com", ns_t_a));
+ std::string expected = PacketToString(pkt.data());
+ EXPECT_EQ(expected, actual);
+}
+
+TEST_F(LibraryTest, CreateQueryTrailingEscapedDot) {
+ byte* p;
+ int len;
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_create_query("example.com\\.", ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+ std::vector<byte> data(p, p + len);
+ ares_free_string(p);
+
+ std::string actual = PacketToString(data);
+ EXPECT_EQ("REQ QRY Q:{'example.com\\.' IN A}", actual);
+}
+
+TEST_F(LibraryTest, CreateQueryNameTooLong) {
+ byte* p;
+ int len;
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_create_query(
+ "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789."
+ "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789."
+ "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789."
+ "x1234567890123456789.y1234567890123456789.",
+ ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0));
+}
+
+TEST_F(LibraryTest, CreateQueryFailures) {
+ byte* p;
+ int len;
+ // RC1035 has a 255 byte limit on names.
+ std::string longname;
+ for (int ii = 0; ii < 17; ii++) {
+ longname += "fedcba9876543210";
+ }
+ p = nullptr;
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_create_query(longname.c_str(), ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+ if (p) ares_free_string(p);
+
+ SetAllocFail(1);
+
+ p = nullptr;
+ EXPECT_EQ(ARES_ENOMEM,
+ ares_create_query("example.com", ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+ if (p) ares_free_string(p);
+
+ // 63-char limit on a single label
+ std::string longlabel = "a.a123456789b123456789c123456789d123456789e123456789f123456789g123456789.org";
+ p = nullptr;
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_create_query(longlabel.c_str(), ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+ if (p) ares_free_string(p);
+
+ // Empty non-terminal label
+ p = nullptr;
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_create_query("example..com", ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+ if (p) ares_free_string(p);
+}
+
+TEST_F(LibraryTest, CreateQueryOnionDomain) {
+ byte* p;
+ int len;
+ EXPECT_EQ(ARES_ENOTFOUND,
+ ares_create_query("dontleak.onion", ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 0));
+}
+
+TEST_F(DefaultChannelTest, HostByNameOnionDomain) {
+ HostResult result;
+ ares_gethostbyname(channel_, "dontleak.onion", AF_INET, HostCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTFOUND, result.status_);
+}
+
+TEST_F(DefaultChannelTest, HostByNameFileOnionDomain) {
+ struct hostent *h;
+ EXPECT_EQ(ARES_ENOTFOUND,
+ ares_gethostbyname_file(channel_, "dontleak.onion", AF_INET, &h));
+}
+
TEST_F(DefaultChannelTest, GetAddrinfoOnionDomain) {
AddrInfoResult result;
struct ares_addrinfo_hints hints = {};
@@ -286,241 +286,241 @@ TEST_F(DefaultChannelTest, GetAddrinfoOnionDomain) {
EXPECT_EQ(ARES_ENOTFOUND, result.status_);
}
-// Interesting question: should tacking on a search domain let the query
-// through? It seems safer to reject it because "supersecret.onion.search"
-// still leaks information about the query to malicious resolvers.
-TEST_F(DefaultChannelTest, SearchOnionDomain) {
- SearchResult result;
- ares_search(channel_, "dontleak.onion", ns_c_in, ns_t_a,
- SearchCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTFOUND, result.status_);
-}
-
-TEST_F(DefaultChannelTest, SendFailure) {
- unsigned char buf[2];
- SearchResult result;
- ares_send(channel_, buf, sizeof(buf), SearchCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_EBADQUERY, result.status_);
-}
-
-std::string ExpandName(const std::vector<byte>& data, int offset,
- long *enclen) {
- char *name = nullptr;
- int rc = ares_expand_name(data.data() + offset, data.data(), data.size(),
- &name, enclen);
- EXPECT_EQ(ARES_SUCCESS, rc);
- std::string result;
- if (rc == ARES_SUCCESS) {
- result = name;
- } else {
- result = "<error>";
- }
- ares_free_string(name);
- return result;
-}
-
-TEST_F(LibraryTest, ExpandName) {
- long enclen;
- std::vector<byte> data1 = {1, 'a', 2, 'b', 'c', 3, 'd', 'e', 'f', 0};
- EXPECT_EQ("a.bc.def", ExpandName(data1, 0, &enclen));
- EXPECT_EQ(data1.size(), enclen);
-
- std::vector<byte> data2 = {0};
- EXPECT_EQ("", ExpandName(data2, 0, &enclen));
- EXPECT_EQ(1, enclen);
-
- // Complete name indirection
- std::vector<byte> data3 = {0x12, 0x23,
- 3, 'd', 'e', 'f', 0,
- 0xC0, 2};
- EXPECT_EQ("def", ExpandName(data3, 2, &enclen));
- EXPECT_EQ(5, enclen);
- EXPECT_EQ("def", ExpandName(data3, 7, &enclen));
- EXPECT_EQ(2, enclen);
-
- // One label then indirection
- std::vector<byte> data4 = {0x12, 0x23,
- 3, 'd', 'e', 'f', 0,
- 1, 'a', 0xC0, 2};
- EXPECT_EQ("def", ExpandName(data4, 2, &enclen));
- EXPECT_EQ(5, enclen);
- EXPECT_EQ("a.def", ExpandName(data4, 7, &enclen));
- EXPECT_EQ(4, enclen);
-
- // Two labels then indirection
- std::vector<byte> data5 = {0x12, 0x23,
- 3, 'd', 'e', 'f', 0,
- 1, 'a', 1, 'b', 0xC0, 2};
- EXPECT_EQ("def", ExpandName(data5, 2, &enclen));
- EXPECT_EQ(5, enclen);
- EXPECT_EQ("a.b.def", ExpandName(data5, 7, &enclen));
- EXPECT_EQ(6, enclen);
-
- // Empty name, indirection to empty name
- std::vector<byte> data6 = {0x12, 0x23,
- 0,
- 0xC0, 2};
- EXPECT_EQ("", ExpandName(data6, 2, &enclen));
- EXPECT_EQ(1, enclen);
- EXPECT_EQ("", ExpandName(data6, 3, &enclen));
- EXPECT_EQ(2, enclen);
-}
-
-TEST_F(LibraryTest, ExpandNameFailure) {
- std::vector<byte> data1 = {0x03, 'c', 'o', 'm', 0x00};
- char *name = nullptr;
- long enclen;
- SetAllocFail(1);
- EXPECT_EQ(ARES_ENOMEM,
- ares_expand_name(data1.data(), data1.data(), data1.size(),
- &name, &enclen));
-
- // Empty packet
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data1.data(), data1.data(), 0, &name, &enclen));
-
- // Start beyond enclosing data
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data1.data() + data1.size(), data1.data(), data1.size(),
- &name, &enclen));
-
- // Length beyond size of enclosing data
- std::vector<byte> data2a = {0x13, 'c', 'o', 'm', 0x00};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data2a.data(), data2a.data(), data2a.size(),
- &name, &enclen));
- std::vector<byte> data2b = {0x1};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data2b.data(), data2b.data(), data2b.size(),
- &name, &enclen));
- std::vector<byte> data2c = {0xC0};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data2c.data(), data2c.data(), data2c.size(),
- &name, &enclen));
-
- // Indirection beyond enclosing data
- std::vector<byte> data3a = {0xC0, 0x02};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data3a.data(), data3a.data(), data3a.size(),
- &name, &enclen));
- std::vector<byte> data3b = {0xC0, 0x0A, 'c', 'o', 'm', 0x00};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data3b.data(), data3b.data(), data3b.size(),
- &name, &enclen));
-
- // Invalid top bits in label length
- std::vector<byte> data4 = {0x03, 'c', 'o', 'm', 0x00, 0x80, 0x00};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data4.data() + 5, data4.data(), data4.size(),
- &name, &enclen));
-
- // Label too long: 64-byte label, with invalid top 2 bits of length (01).
- std::vector<byte> data5 = {0x40,
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
- 0x00};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data5.data(), data5.data(), data5.size(),
- &name, &enclen)) << name;
-
- // Incomplete indirect length
- std::vector<byte> data6 = {0x03, 'c', 'o', 'm', 0x00, 0xC0};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data6.data() + 5, data6.data(), data6.size(),
- &name, &enclen));
-
- // Indirection loops
- std::vector<byte> data7 = {0xC0, 0x02, 0xC0, 0x00};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data7.data(), data7.data(), data7.size(),
- &name, &enclen));
- std::vector<byte> data8 = {3, 'd', 'e', 'f', 0xC0, 0x08, 0x00, 0x00,
- 3, 'a', 'b', 'c', 0xC0, 0x00};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data8.data(), data8.data(), data8.size(),
- &name, &enclen));
- std::vector<byte> data9 = {0x12, 0x23, // start 2 bytes in
- 3, 'd', 'e', 'f', 0xC0, 0x02};
- EXPECT_EQ(ARES_EBADNAME,
- ares_expand_name(data9.data() + 2, data9.data(), data9.size(),
- &name, &enclen));
-}
-
-TEST_F(LibraryTest, CreateEDNSQuery) {
- byte* p;
- int len;
- EXPECT_EQ(ARES_SUCCESS,
- ares_create_query("example.com", ns_c_in, ns_t_a, 0x1234, 0,
- &p, &len, 1280));
- std::vector<byte> data(p, p + len);
- ares_free_string(p);
-
- std::string actual = PacketToString(data);
- DNSPacket pkt;
- pkt.set_qid(0x1234).add_question(new DNSQuestion("example.com", ns_t_a))
- .add_additional(new DNSOptRR(0, 1280));
- std::string expected = PacketToString(pkt.data());
- EXPECT_EQ(expected, actual);
-}
-
-TEST_F(LibraryTest, CreateRootQuery) {
- byte* p;
- int len;
- ares_create_query(".", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0);
- std::vector<byte> data(p, p + len);
- ares_free_string(p);
-
- std::string actual = PacketToString(data);
- DNSPacket pkt;
- pkt.set_qid(0x1234).add_question(new DNSQuestion("", ns_t_a));
- std::string expected = PacketToString(pkt.data());
- EXPECT_EQ(expected, actual);
-}
-
-TEST_F(LibraryTest, Version) {
- // Assume linked to same version
- EXPECT_EQ(std::string(ARES_VERSION_STR),
- std::string(ares_version(nullptr)));
- int version;
- ares_version(&version);
- EXPECT_EQ(ARES_VERSION, version);
-}
-
-TEST_F(LibraryTest, Strerror) {
- EXPECT_EQ("Successful completion",
- std::string(ares_strerror(ARES_SUCCESS)));
- EXPECT_EQ("DNS query cancelled",
- std::string(ares_strerror(ARES_ECANCELLED)));
- EXPECT_EQ("unknown",
- std::string(ares_strerror(99)));
-}
-
-TEST_F(LibraryTest, ExpandString) {
- std::vector<byte> s1 = { 3, 'a', 'b', 'c'};
- char* result = nullptr;
- long len;
- EXPECT_EQ(ARES_SUCCESS,
- ares_expand_string(s1.data(), s1.data(), s1.size(),
- (unsigned char**)&result, &len));
- EXPECT_EQ("abc", std::string(result));
- EXPECT_EQ(1 + 3, len); // amount of data consumed includes 1 byte len
- ares_free_string(result);
- result = nullptr;
- EXPECT_EQ(ARES_EBADSTR,
- ares_expand_string(s1.data() + 1, s1.data(), s1.size(),
- (unsigned char**)&result, &len));
- EXPECT_EQ(ARES_EBADSTR,
- ares_expand_string(s1.data() + 4, s1.data(), s1.size(),
- (unsigned char**)&result, &len));
- SetAllocSizeFail(3 + 1);
- EXPECT_EQ(ARES_ENOMEM,
- ares_expand_string(s1.data(), s1.data(), s1.size(),
- (unsigned char**)&result, &len));
-}
-
-} // namespace test
-} // namespace ares
+// Interesting question: should tacking on a search domain let the query
+// through? It seems safer to reject it because "supersecret.onion.search"
+// still leaks information about the query to malicious resolvers.
+TEST_F(DefaultChannelTest, SearchOnionDomain) {
+ SearchResult result;
+ ares_search(channel_, "dontleak.onion", ns_c_in, ns_t_a,
+ SearchCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTFOUND, result.status_);
+}
+
+TEST_F(DefaultChannelTest, SendFailure) {
+ unsigned char buf[2];
+ SearchResult result;
+ ares_send(channel_, buf, sizeof(buf), SearchCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_EBADQUERY, result.status_);
+}
+
+std::string ExpandName(const std::vector<byte>& data, int offset,
+ long *enclen) {
+ char *name = nullptr;
+ int rc = ares_expand_name(data.data() + offset, data.data(), data.size(),
+ &name, enclen);
+ EXPECT_EQ(ARES_SUCCESS, rc);
+ std::string result;
+ if (rc == ARES_SUCCESS) {
+ result = name;
+ } else {
+ result = "<error>";
+ }
+ ares_free_string(name);
+ return result;
+}
+
+TEST_F(LibraryTest, ExpandName) {
+ long enclen;
+ std::vector<byte> data1 = {1, 'a', 2, 'b', 'c', 3, 'd', 'e', 'f', 0};
+ EXPECT_EQ("a.bc.def", ExpandName(data1, 0, &enclen));
+ EXPECT_EQ(data1.size(), enclen);
+
+ std::vector<byte> data2 = {0};
+ EXPECT_EQ("", ExpandName(data2, 0, &enclen));
+ EXPECT_EQ(1, enclen);
+
+ // Complete name indirection
+ std::vector<byte> data3 = {0x12, 0x23,
+ 3, 'd', 'e', 'f', 0,
+ 0xC0, 2};
+ EXPECT_EQ("def", ExpandName(data3, 2, &enclen));
+ EXPECT_EQ(5, enclen);
+ EXPECT_EQ("def", ExpandName(data3, 7, &enclen));
+ EXPECT_EQ(2, enclen);
+
+ // One label then indirection
+ std::vector<byte> data4 = {0x12, 0x23,
+ 3, 'd', 'e', 'f', 0,
+ 1, 'a', 0xC0, 2};
+ EXPECT_EQ("def", ExpandName(data4, 2, &enclen));
+ EXPECT_EQ(5, enclen);
+ EXPECT_EQ("a.def", ExpandName(data4, 7, &enclen));
+ EXPECT_EQ(4, enclen);
+
+ // Two labels then indirection
+ std::vector<byte> data5 = {0x12, 0x23,
+ 3, 'd', 'e', 'f', 0,
+ 1, 'a', 1, 'b', 0xC0, 2};
+ EXPECT_EQ("def", ExpandName(data5, 2, &enclen));
+ EXPECT_EQ(5, enclen);
+ EXPECT_EQ("a.b.def", ExpandName(data5, 7, &enclen));
+ EXPECT_EQ(6, enclen);
+
+ // Empty name, indirection to empty name
+ std::vector<byte> data6 = {0x12, 0x23,
+ 0,
+ 0xC0, 2};
+ EXPECT_EQ("", ExpandName(data6, 2, &enclen));
+ EXPECT_EQ(1, enclen);
+ EXPECT_EQ("", ExpandName(data6, 3, &enclen));
+ EXPECT_EQ(2, enclen);
+}
+
+TEST_F(LibraryTest, ExpandNameFailure) {
+ std::vector<byte> data1 = {0x03, 'c', 'o', 'm', 0x00};
+ char *name = nullptr;
+ long enclen;
+ SetAllocFail(1);
+ EXPECT_EQ(ARES_ENOMEM,
+ ares_expand_name(data1.data(), data1.data(), data1.size(),
+ &name, &enclen));
+
+ // Empty packet
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data1.data(), data1.data(), 0, &name, &enclen));
+
+ // Start beyond enclosing data
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data1.data() + data1.size(), data1.data(), data1.size(),
+ &name, &enclen));
+
+ // Length beyond size of enclosing data
+ std::vector<byte> data2a = {0x13, 'c', 'o', 'm', 0x00};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data2a.data(), data2a.data(), data2a.size(),
+ &name, &enclen));
+ std::vector<byte> data2b = {0x1};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data2b.data(), data2b.data(), data2b.size(),
+ &name, &enclen));
+ std::vector<byte> data2c = {0xC0};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data2c.data(), data2c.data(), data2c.size(),
+ &name, &enclen));
+
+ // Indirection beyond enclosing data
+ std::vector<byte> data3a = {0xC0, 0x02};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data3a.data(), data3a.data(), data3a.size(),
+ &name, &enclen));
+ std::vector<byte> data3b = {0xC0, 0x0A, 'c', 'o', 'm', 0x00};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data3b.data(), data3b.data(), data3b.size(),
+ &name, &enclen));
+
+ // Invalid top bits in label length
+ std::vector<byte> data4 = {0x03, 'c', 'o', 'm', 0x00, 0x80, 0x00};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data4.data() + 5, data4.data(), data4.size(),
+ &name, &enclen));
+
+ // Label too long: 64-byte label, with invalid top 2 bits of length (01).
+ std::vector<byte> data5 = {0x40,
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
+ 0x00};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data5.data(), data5.data(), data5.size(),
+ &name, &enclen)) << name;
+
+ // Incomplete indirect length
+ std::vector<byte> data6 = {0x03, 'c', 'o', 'm', 0x00, 0xC0};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data6.data() + 5, data6.data(), data6.size(),
+ &name, &enclen));
+
+ // Indirection loops
+ std::vector<byte> data7 = {0xC0, 0x02, 0xC0, 0x00};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data7.data(), data7.data(), data7.size(),
+ &name, &enclen));
+ std::vector<byte> data8 = {3, 'd', 'e', 'f', 0xC0, 0x08, 0x00, 0x00,
+ 3, 'a', 'b', 'c', 0xC0, 0x00};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data8.data(), data8.data(), data8.size(),
+ &name, &enclen));
+ std::vector<byte> data9 = {0x12, 0x23, // start 2 bytes in
+ 3, 'd', 'e', 'f', 0xC0, 0x02};
+ EXPECT_EQ(ARES_EBADNAME,
+ ares_expand_name(data9.data() + 2, data9.data(), data9.size(),
+ &name, &enclen));
+}
+
+TEST_F(LibraryTest, CreateEDNSQuery) {
+ byte* p;
+ int len;
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_create_query("example.com", ns_c_in, ns_t_a, 0x1234, 0,
+ &p, &len, 1280));
+ std::vector<byte> data(p, p + len);
+ ares_free_string(p);
+
+ std::string actual = PacketToString(data);
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).add_question(new DNSQuestion("example.com", ns_t_a))
+ .add_additional(new DNSOptRR(0, 1280));
+ std::string expected = PacketToString(pkt.data());
+ EXPECT_EQ(expected, actual);
+}
+
+TEST_F(LibraryTest, CreateRootQuery) {
+ byte* p;
+ int len;
+ ares_create_query(".", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0);
+ std::vector<byte> data(p, p + len);
+ ares_free_string(p);
+
+ std::string actual = PacketToString(data);
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).add_question(new DNSQuestion("", ns_t_a));
+ std::string expected = PacketToString(pkt.data());
+ EXPECT_EQ(expected, actual);
+}
+
+TEST_F(LibraryTest, Version) {
+ // Assume linked to same version
+ EXPECT_EQ(std::string(ARES_VERSION_STR),
+ std::string(ares_version(nullptr)));
+ int version;
+ ares_version(&version);
+ EXPECT_EQ(ARES_VERSION, version);
+}
+
+TEST_F(LibraryTest, Strerror) {
+ EXPECT_EQ("Successful completion",
+ std::string(ares_strerror(ARES_SUCCESS)));
+ EXPECT_EQ("DNS query cancelled",
+ std::string(ares_strerror(ARES_ECANCELLED)));
+ EXPECT_EQ("unknown",
+ std::string(ares_strerror(99)));
+}
+
+TEST_F(LibraryTest, ExpandString) {
+ std::vector<byte> s1 = { 3, 'a', 'b', 'c'};
+ char* result = nullptr;
+ long len;
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_expand_string(s1.data(), s1.data(), s1.size(),
+ (unsigned char**)&result, &len));
+ EXPECT_EQ("abc", std::string(result));
+ EXPECT_EQ(1 + 3, len); // amount of data consumed includes 1 byte len
+ ares_free_string(result);
+ result = nullptr;
+ EXPECT_EQ(ARES_EBADSTR,
+ ares_expand_string(s1.data() + 1, s1.data(), s1.size(),
+ (unsigned char**)&result, &len));
+ EXPECT_EQ(ARES_EBADSTR,
+ ares_expand_string(s1.data() + 4, s1.data(), s1.size(),
+ (unsigned char**)&result, &len));
+ SetAllocSizeFail(3 + 1);
+ EXPECT_EQ(ARES_ENOMEM,
+ ares_expand_string(s1.data(), s1.data(), s1.size(),
+ (unsigned char**)&result, &len));
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-mock.cc b/contrib/libs/c-ares/test/ares-test-mock.cc
index 80e9fc02b0..fdae07fef6 100644
--- a/contrib/libs/c-ares/test/ares-test-mock.cc
+++ b/contrib/libs/c-ares/test/ares-test-mock.cc
@@ -1,941 +1,941 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-using testing::InvokeWithoutArgs;
-using testing::DoAll;
-
-namespace ares {
-namespace test {
-
-TEST_P(MockChannelTest, Basic) {
- std::vector<byte> reply = {
- 0x00, 0x00, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // 1 question
- 0x00, 0x01, // 1 answer RRs
- 0x00, 0x00, // 0 authority RRs
- 0x00, 0x00, // 0 additional RRs
- // Question
- 0x03, 'w', 'w', 'w',
- 0x06, 'g', 'o', 'o', 'g', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer
- 0x03, 'w', 'w', 'w',
- 0x06, 'g', 'o', 'o', 'g', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- 0x00, 0x00, 0x01, 0x00, // TTL
- 0x00, 0x04, // rdata length
- 0x01, 0x02, 0x03, 0x04
- };
-
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReplyData(&server_, reply));
-
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-// UDP only so mock server doesn't get confused by concatenated requests
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+using testing::InvokeWithoutArgs;
+using testing::DoAll;
+
+namespace ares {
+namespace test {
+
+TEST_P(MockChannelTest, Basic) {
+ std::vector<byte> reply = {
+ 0x00, 0x00, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // 1 question
+ 0x00, 0x01, // 1 answer RRs
+ 0x00, 0x00, // 0 authority RRs
+ 0x00, 0x00, // 0 additional RRs
+ // Question
+ 0x03, 'w', 'w', 'w',
+ 0x06, 'g', 'o', 'o', 'g', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer
+ 0x03, 'w', 'w', 'w',
+ 0x06, 'g', 'o', 'o', 'g', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ 0x00, 0x00, 0x01, 0x00, // TTL
+ 0x00, 0x04, // rdata length
+ 0x01, 0x02, 0x03, 0x04
+ };
+
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReplyData(&server_, reply));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+// UDP only so mock server doesn't get confused by concatenated requests
TEST_P(MockUDPChannelTest, GetHostByNameParallelLookups) {
- DNSPacket rsp1;
- rsp1.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp1));
- DNSPacket rsp2;
- rsp2.set_response().set_aa()
- .add_question(new DNSQuestion("www.example.com", ns_t_a))
- .add_answer(new DNSARR("www.example.com", 100, {1, 2, 3, 4}));
- ON_CALL(server_, OnRequest("www.example.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp2));
-
- HostResult result1;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result1);
- HostResult result2;
- ares_gethostbyname(channel_, "www.example.com.", AF_INET, HostCallback, &result2);
- HostResult result3;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result3);
- Process();
- EXPECT_TRUE(result1.done_);
- EXPECT_TRUE(result2.done_);
- EXPECT_TRUE(result3.done_);
- std::stringstream ss1;
- ss1 << result1.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss1.str());
- std::stringstream ss2;
- ss2 << result2.host_;
- EXPECT_EQ("{'www.example.com' aliases=[] addrs=[1.2.3.4]}", ss2.str());
- std::stringstream ss3;
- ss3 << result3.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss3.str());
-}
-
-// UDP to TCP specific test
-TEST_P(MockUDPChannelTest, TruncationRetry) {
- DNSPacket rsptruncated;
- rsptruncated.set_response().set_aa().set_tc()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- DNSPacket rspok;
- rspok.set_response()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 100, {1, 2, 3, 4}));
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsptruncated))
- .WillOnce(SetReply(&server_, &rspok));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-static int sock_cb_count = 0;
-static int SocketConnectCallback(ares_socket_t fd, int type, void *data) {
- int rc = *(int*)data;
- if (verbose) std::cerr << "SocketConnectCallback(" << fd << ") invoked" << std::endl;
- sock_cb_count++;
- return rc;
-}
-
-TEST_P(MockChannelTest, SockCallback) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
-
- // Get notified of new sockets
- int rc = ARES_SUCCESS;
- ares_set_socket_callback(channel_, SocketConnectCallback, &rc);
-
- HostResult result;
- sock_cb_count = 0;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_EQ(1, sock_cb_count);
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, SockFailCallback) {
- // Notification of new sockets gives an error.
- int rc = -1;
- ares_set_socket_callback(channel_, SocketConnectCallback, &rc);
-
- HostResult result;
- sock_cb_count = 0;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_LT(1, sock_cb_count);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
-}
-
-static int sock_config_cb_count = 0;
-static int SocketConfigureCallback(ares_socket_t fd, int type, void *data) {
- int rc = *(int*)data;
- if (verbose) std::cerr << "SocketConfigureCallback(" << fd << ") invoked" << std::endl;
- sock_config_cb_count++;
- return rc;
-}
-
-TEST_P(MockChannelTest, SockConfigureCallback) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
-
- // Get notified of new sockets
- int rc = ARES_SUCCESS;
- ares_set_socket_configure_callback(channel_, SocketConfigureCallback, &rc);
-
- HostResult result;
- sock_config_cb_count = 0;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_EQ(1, sock_config_cb_count);
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, SockConfigureFailCallback) {
- // Notification of new sockets gives an error.
- int rc = -1;
- ares_set_socket_configure_callback(channel_, SocketConfigureCallback, &rc);
-
- HostResult result;
- sock_config_cb_count = 0;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_LT(1, sock_config_cb_count);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
-}
-
-// TCP only to prevent retries
-TEST_P(MockTCPChannelTest, MalformedResponse) {
- std::vector<byte> one = {0x01};
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReplyData(&server_, one));
-
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ETIMEOUT, result.status_);
-}
-
-TEST_P(MockTCPChannelTest, FormErrResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_formerr);
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_EFORMERR, result.status_);
-}
-
-TEST_P(MockTCPChannelTest, ServFailResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_servfail);
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- // ARES_FLAG_NOCHECKRESP not set, so SERVFAIL consumed
- EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
-}
-
-TEST_P(MockTCPChannelTest, NotImplResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_notimpl);
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- // ARES_FLAG_NOCHECKRESP not set, so NOTIMPL consumed
- EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
-}
-
-TEST_P(MockTCPChannelTest, RefusedResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_refused);
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- // ARES_FLAG_NOCHECKRESP not set, so REFUSED consumed
- EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
-}
-
-TEST_P(MockTCPChannelTest, YXDomainResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_yxdomain);
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENODATA, result.status_);
-}
-
-class MockExtraOptsTest
- : public MockChannelOptsTest,
- public ::testing::WithParamInterface< std::pair<int, bool> > {
- public:
- MockExtraOptsTest()
- : MockChannelOptsTest(1, GetParam().first, GetParam().second,
- FillOptions(&opts_),
- ARES_OPT_SOCK_SNDBUF|ARES_OPT_SOCK_RCVBUF) {}
- static struct ares_options* FillOptions(struct ares_options * opts) {
- memset(opts, 0, sizeof(struct ares_options));
- // Set a few options that affect socket communications
- opts->socket_send_buffer_size = 514;
- opts->socket_receive_buffer_size = 514;
- return opts;
- }
- private:
- struct ares_options opts_;
-};
-
-TEST_P(MockExtraOptsTest, SimpleQuery) {
- ares_set_local_ip4(channel_, 0x7F000001);
- byte addr6[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
- ares_set_local_ip6(channel_, addr6);
- ares_set_local_dev(channel_, "dummy");
-
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp));
-
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-class MockFlagsChannelOptsTest
- : public MockChannelOptsTest,
- public ::testing::WithParamInterface< std::pair<int, bool> > {
- public:
- MockFlagsChannelOptsTest(int flags)
- : MockChannelOptsTest(1, GetParam().first, GetParam().second,
- FillOptions(&opts_, flags), ARES_OPT_FLAGS) {}
- static struct ares_options* FillOptions(struct ares_options * opts, int flags) {
- memset(opts, 0, sizeof(struct ares_options));
- opts->flags = flags;
- return opts;
- }
- private:
- struct ares_options opts_;
-};
-
-class MockNoCheckRespChannelTest : public MockFlagsChannelOptsTest {
- public:
- MockNoCheckRespChannelTest() : MockFlagsChannelOptsTest(ARES_FLAG_NOCHECKRESP) {}
-};
-
-TEST_P(MockNoCheckRespChannelTest, ServFailResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_servfail);
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ESERVFAIL, result.status_);
-}
-
-TEST_P(MockNoCheckRespChannelTest, NotImplResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_notimpl);
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOTIMP, result.status_);
-}
-
-TEST_P(MockNoCheckRespChannelTest, RefusedResponse) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- rsp.set_rcode(ns_r_refused);
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_EREFUSED, result.status_);
-}
-
-class MockEDNSChannelTest : public MockFlagsChannelOptsTest {
- public:
- MockEDNSChannelTest() : MockFlagsChannelOptsTest(ARES_FLAG_EDNS) {}
-};
-
-TEST_P(MockEDNSChannelTest, RetryWithoutEDNS) {
- DNSPacket rspfail;
- rspfail.set_response().set_aa().set_rcode(ns_r_servfail)
- .add_question(new DNSQuestion("www.google.com", ns_t_a));
- DNSPacket rspok;
- rspok.set_response()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 100, {1, 2, 3, 4}));
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReply(&server_, &rspfail))
- .WillOnce(SetReply(&server_, &rspok));
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-TEST_P(MockChannelTest, SearchDomains) {
- DNSPacket nofirst;
- nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillByDefault(SetReply(&server_, &nosecond));
- DNSPacket yesthird;
- yesthird.set_response().set_aa()
- .add_question(new DNSQuestion("www.third.gov", ns_t_a))
- .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesthird));
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-// Relies on retries so is UDP-only
-TEST_P(MockUDPChannelTest, SearchDomainsWithResentReply) {
- DNSPacket nofirst;
- nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- EXPECT_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillOnce(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- EXPECT_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillOnce(SetReply(&server_, &nosecond));
- DNSPacket yesthird;
- yesthird.set_response().set_aa()
- .add_question(new DNSQuestion("www.third.gov", ns_t_a))
- .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
- // Before sending the real answer, resend an earlier reply
- EXPECT_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillOnce(DoAll(SetReply(&server_, &nofirst),
- SetReplyQID(&server_, 123)))
- .WillOnce(DoAll(SetReply(&server_, &yesthird),
- SetReplyQID(&server_, -1)));
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, SearchDomainsBare) {
- DNSPacket nofirst;
- nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillByDefault(SetReply(&server_, &nosecond));
- DNSPacket nothird;
- nothird.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.third.gov", ns_t_a));
- ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillByDefault(SetReply(&server_, &nothird));
- DNSPacket yesbare;
- yesbare.set_response().set_aa()
- .add_question(new DNSQuestion("www", ns_t_a))
- .add_answer(new DNSARR("www", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesbare));
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, SearchNoDataThenSuccess) {
- // First two search domains recognize the name but have no A records.
- DNSPacket nofirst;
- nofirst.set_response().set_aa()
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa()
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillByDefault(SetReply(&server_, &nosecond));
- DNSPacket yesthird;
- yesthird.set_response().set_aa()
- .add_question(new DNSQuestion("www.third.gov", ns_t_a))
- .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesthird));
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, SearchNoDataThenNoDataBare) {
- // First two search domains recognize the name but have no A records.
- DNSPacket nofirst;
- nofirst.set_response().set_aa()
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa()
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillByDefault(SetReply(&server_, &nosecond));
- DNSPacket nothird;
- nothird.set_response().set_aa()
- .add_question(new DNSQuestion("www.third.gov", ns_t_a));
- ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillByDefault(SetReply(&server_, &nothird));
- DNSPacket nobare;
- nobare.set_response().set_aa()
- .add_question(new DNSQuestion("www", ns_t_a));
- ON_CALL(server_, OnRequest("www", ns_t_a))
- .WillByDefault(SetReply(&server_, &nobare));
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENODATA, result.status_);
-}
-
-TEST_P(MockChannelTest, SearchNoDataThenFail) {
- // First two search domains recognize the name but have no A records.
- DNSPacket nofirst;
- nofirst.set_response().set_aa()
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa()
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillByDefault(SetReply(&server_, &nosecond));
- DNSPacket nothird;
- nothird.set_response().set_aa()
- .add_question(new DNSQuestion("www.third.gov", ns_t_a));
- ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillByDefault(SetReply(&server_, &nothird));
- DNSPacket nobare;
- nobare.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www", ns_t_a));
- ON_CALL(server_, OnRequest("www", ns_t_a))
- .WillByDefault(SetReply(&server_, &nobare));
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENODATA, result.status_);
-}
-
-TEST_P(MockChannelTest, SearchAllocFailure) {
- SearchResult result;
- SetAllocFail(1);
- ares_search(channel_, "fully.qualified.", ns_c_in, ns_t_a, SearchCallback, &result);
- /* Already done */
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ENOMEM, result.status_);
-}
-
-TEST_P(MockChannelTest, SearchHighNdots) {
- DNSPacket nobare;
- nobare.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("a.b.c.w.w.w", ns_t_a));
- ON_CALL(server_, OnRequest("a.b.c.w.w.w", ns_t_a))
- .WillByDefault(SetReply(&server_, &nobare));
- DNSPacket yesfirst;
- yesfirst.set_response().set_aa()
- .add_question(new DNSQuestion("a.b.c.w.w.w.first.com", ns_t_a))
- .add_answer(new DNSARR("a.b.c.w.w.w.first.com", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("a.b.c.w.w.w.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesfirst));
-
- SearchResult result;
- ares_search(channel_, "a.b.c.w.w.w", ns_c_in, ns_t_a, SearchCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- std::stringstream ss;
- ss << PacketToString(result.data_);
- EXPECT_EQ("RSP QRY AA NOERROR Q:{'a.b.c.w.w.w.first.com' IN A} "
- "A:{'a.b.c.w.w.w.first.com' IN A TTL=512 2.3.4.5}",
- ss.str());
-}
-
-TEST_P(MockChannelTest, UnspecifiedFamilyV6) {
- DNSPacket rsp6;
- rsp6.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSAaaaRR("example.com", 100,
- {0x21, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03}));
- ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
- .WillByDefault(SetReply(&server_, &rsp6));
-
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- // Default to IPv6 when both are available.
- EXPECT_EQ("{'example.com' aliases=[] addrs=[2121:0000:0000:0000:0000:0000:0000:0303]}", ss.str());
-}
-
-TEST_P(MockChannelTest, UnspecifiedFamilyV4) {
- DNSPacket rsp6;
- rsp6.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa));
- ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
- .WillByDefault(SetReply(&server_, &rsp6));
- DNSPacket rsp4;
- rsp4.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a))
- .add_answer(new DNSARR("example.com", 100, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("example.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp4));
-
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, UnspecifiedFamilyNoData) {
- DNSPacket rsp6;
- rsp6.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSCnameRR("example.com", 100, "elsewhere.com"));
- ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
- .WillByDefault(SetReply(&server_, &rsp6));
- DNSPacket rsp4;
- rsp4.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a));
- ON_CALL(server_, OnRequest("example.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp4));
-
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'' aliases=[] addrs=[]}", ss.str());
-}
-
-TEST_P(MockChannelTest, UnspecifiedFamilyCname6A4) {
- DNSPacket rsp6;
- rsp6.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSCnameRR("example.com", 100, "elsewhere.com"));
- ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
- .WillByDefault(SetReply(&server_, &rsp6));
- DNSPacket rsp4;
- rsp4.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a))
- .add_answer(new DNSARR("example.com", 100, {1, 2, 3, 4}));
- ON_CALL(server_, OnRequest("example.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp4));
-
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'example.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-TEST_P(MockChannelTest, ExplicitIP) {
- HostResult result;
- ares_gethostbyname(channel_, "1.2.3.4", AF_INET, HostCallback, &result);
- EXPECT_TRUE(result.done_); // Immediate return
- EXPECT_EQ(ARES_SUCCESS, result.status_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'1.2.3.4' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-TEST_P(MockChannelTest, ExplicitIPAllocFail) {
- HostResult result;
- SetAllocSizeFail(strlen("1.2.3.4") + 1);
- ares_gethostbyname(channel_, "1.2.3.4", AF_INET, HostCallback, &result);
- EXPECT_TRUE(result.done_); // Immediate return
- EXPECT_EQ(ARES_ENOMEM, result.status_);
-}
-
-TEST_P(MockChannelTest, SortListV4) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a))
- .add_answer(new DNSARR("example.com", 100, {22, 23, 24, 25}))
- .add_answer(new DNSARR("example.com", 100, {12, 13, 14, 15}))
- .add_answer(new DNSARR("example.com", 100, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("example.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &rsp));
-
- {
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "12.13.0.0/255.255.0.0 1234::5678"));
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'example.com' aliases=[] addrs=[12.13.14.15, 22.23.24.25, 2.3.4.5]}", ss.str());
- }
- {
- EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "2.3.0.0/16 130.140.150.160/26"));
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'example.com' aliases=[] addrs=[2.3.4.5, 22.23.24.25, 12.13.14.15]}", ss.str());
- }
- struct ares_options options;
- memset(&options, 0, sizeof(options));
- int optmask = 0;
- EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel_, &options, &optmask));
- EXPECT_TRUE((optmask & ARES_OPT_SORTLIST) == ARES_OPT_SORTLIST);
- ares_destroy_options(&options);
-}
-
-TEST_P(MockChannelTest, SortListV6) {
- DNSPacket rsp;
- rsp.set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSAaaaRR("example.com", 100,
- {0x11, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02}))
- .add_answer(new DNSAaaaRR("example.com", 100,
- {0x21, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03}));
- ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
- .WillByDefault(SetReply(&server_, &rsp));
-
- {
- ares_set_sortlist(channel_, "1111::/16 2.3.0.0/255.255.0.0");
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'example.com' aliases=[] addrs=[1111:0000:0000:0000:0000:0000:0000:0202, "
- "2121:0000:0000:0000:0000:0000:0000:0303]}", ss.str());
- }
- {
- ares_set_sortlist(channel_, "2121::/8");
- HostResult result;
- ares_gethostbyname(channel_, "example.com.", AF_INET6, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'example.com' aliases=[] addrs=[2121:0000:0000:0000:0000:0000:0000:0303, "
- "1111:0000:0000:0000:0000:0000:0000:0202]}", ss.str());
- }
-}
-
-// Relies on retries so is UDP-only
-TEST_P(MockUDPChannelTest, SearchDomainsAllocFail) {
- DNSPacket nofirst;
- nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.first.com", ns_t_a));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &nofirst));
- DNSPacket nosecond;
- nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
- .add_question(new DNSQuestion("www.second.org", ns_t_a));
- ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
- .WillByDefault(SetReply(&server_, &nosecond));
- DNSPacket yesthird;
- yesthird.set_response().set_aa()
- .add_question(new DNSQuestion("www.third.gov", ns_t_a))
- .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesthird));
-
- // Fail a variety of different memory allocations, and confirm
- // that the operation either fails with ENOMEM or succeeds
- // with the expected result.
- const int kCount = 34;
- HostResult results[kCount];
- for (int ii = 1; ii <= kCount; ii++) {
- HostResult* result = &(results[ii - 1]);
- ClearFails();
- SetAllocFail(ii);
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, result);
- Process();
- EXPECT_TRUE(result->done_);
- if (result->status_ == ARES_SUCCESS) {
- std::stringstream ss;
- ss << result->host_;
- EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str()) << " failed alloc #" << ii;
- if (verbose) std::cerr << "Succeeded despite failure of alloc #" << ii << std::endl;
- }
- }
-
- // Explicitly destroy the channel now, so that the HostResult objects
- // are still valid (in case any pending work refers to them).
- ares_destroy(channel_);
- channel_ = nullptr;
-}
-
-// Relies on retries so is UDP-only
-TEST_P(MockUDPChannelTest, Resend) {
- std::vector<byte> nothing;
- DNSPacket reply;
- reply.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 0x0100, {0x01, 0x02, 0x03, 0x04}));
-
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReplyData(&server_, nothing))
- .WillOnce(SetReplyData(&server_, nothing))
- .WillOnce(SetReply(&server_, &reply));
-
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(2, result.timeouts_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-TEST_P(MockChannelTest, CancelImmediate) {
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- ares_cancel(channel_);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ECANCELLED, result.status_);
- EXPECT_EQ(0, result.timeouts_);
-}
-
-TEST_P(MockChannelTest, CancelImmediateGetHostByAddr) {
- HostResult result;
- struct in_addr addr;
- addr.s_addr = htonl(0x08080808);
-
- ares_gethostbyaddr(channel_, &addr, sizeof(addr), AF_INET, HostCallback, &result);
- ares_cancel(channel_);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ECANCELLED, result.status_);
- EXPECT_EQ(0, result.timeouts_);
-}
-
-// Relies on retries so is UDP-only
-TEST_P(MockUDPChannelTest, CancelLater) {
- std::vector<byte> nothing;
-
- // On second request, cancel the channel.
- EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillOnce(SetReplyData(&server_, nothing))
- .WillOnce(CancelChannel(&server_, channel_));
-
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_ECANCELLED, result.status_);
- EXPECT_EQ(0, result.timeouts_);
-}
-
-TEST_P(MockChannelTest, GetHostByNameDestroyAbsolute) {
- HostResult result;
- ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
-
- ares_destroy(channel_);
- channel_ = nullptr;
-
- EXPECT_TRUE(result.done_); // Synchronous
- EXPECT_EQ(ARES_EDESTRUCTION, result.status_);
- EXPECT_EQ(0, result.timeouts_);
-}
-
-TEST_P(MockChannelTest, GetHostByNameDestroyRelative) {
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
-
- ares_destroy(channel_);
- channel_ = nullptr;
-
- EXPECT_TRUE(result.done_); // Synchronous
- EXPECT_EQ(ARES_EDESTRUCTION, result.status_);
- EXPECT_EQ(0, result.timeouts_);
-}
-
+ DNSPacket rsp1;
+ rsp1.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp1));
+ DNSPacket rsp2;
+ rsp2.set_response().set_aa()
+ .add_question(new DNSQuestion("www.example.com", ns_t_a))
+ .add_answer(new DNSARR("www.example.com", 100, {1, 2, 3, 4}));
+ ON_CALL(server_, OnRequest("www.example.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp2));
+
+ HostResult result1;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result1);
+ HostResult result2;
+ ares_gethostbyname(channel_, "www.example.com.", AF_INET, HostCallback, &result2);
+ HostResult result3;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result3);
+ Process();
+ EXPECT_TRUE(result1.done_);
+ EXPECT_TRUE(result2.done_);
+ EXPECT_TRUE(result3.done_);
+ std::stringstream ss1;
+ ss1 << result1.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss1.str());
+ std::stringstream ss2;
+ ss2 << result2.host_;
+ EXPECT_EQ("{'www.example.com' aliases=[] addrs=[1.2.3.4]}", ss2.str());
+ std::stringstream ss3;
+ ss3 << result3.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss3.str());
+}
+
+// UDP to TCP specific test
+TEST_P(MockUDPChannelTest, TruncationRetry) {
+ DNSPacket rsptruncated;
+ rsptruncated.set_response().set_aa().set_tc()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ DNSPacket rspok;
+ rspok.set_response()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 100, {1, 2, 3, 4}));
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsptruncated))
+ .WillOnce(SetReply(&server_, &rspok));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+static int sock_cb_count = 0;
+static int SocketConnectCallback(ares_socket_t fd, int type, void *data) {
+ int rc = *(int*)data;
+ if (verbose) std::cerr << "SocketConnectCallback(" << fd << ") invoked" << std::endl;
+ sock_cb_count++;
+ return rc;
+}
+
+TEST_P(MockChannelTest, SockCallback) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+
+ // Get notified of new sockets
+ int rc = ARES_SUCCESS;
+ ares_set_socket_callback(channel_, SocketConnectCallback, &rc);
+
+ HostResult result;
+ sock_cb_count = 0;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_EQ(1, sock_cb_count);
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, SockFailCallback) {
+ // Notification of new sockets gives an error.
+ int rc = -1;
+ ares_set_socket_callback(channel_, SocketConnectCallback, &rc);
+
+ HostResult result;
+ sock_cb_count = 0;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_LT(1, sock_cb_count);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
+}
+
+static int sock_config_cb_count = 0;
+static int SocketConfigureCallback(ares_socket_t fd, int type, void *data) {
+ int rc = *(int*)data;
+ if (verbose) std::cerr << "SocketConfigureCallback(" << fd << ") invoked" << std::endl;
+ sock_config_cb_count++;
+ return rc;
+}
+
+TEST_P(MockChannelTest, SockConfigureCallback) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+
+ // Get notified of new sockets
+ int rc = ARES_SUCCESS;
+ ares_set_socket_configure_callback(channel_, SocketConfigureCallback, &rc);
+
+ HostResult result;
+ sock_config_cb_count = 0;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_EQ(1, sock_config_cb_count);
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, SockConfigureFailCallback) {
+ // Notification of new sockets gives an error.
+ int rc = -1;
+ ares_set_socket_configure_callback(channel_, SocketConfigureCallback, &rc);
+
+ HostResult result;
+ sock_config_cb_count = 0;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_LT(1, sock_config_cb_count);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
+}
+
+// TCP only to prevent retries
+TEST_P(MockTCPChannelTest, MalformedResponse) {
+ std::vector<byte> one = {0x01};
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReplyData(&server_, one));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ETIMEOUT, result.status_);
+}
+
+TEST_P(MockTCPChannelTest, FormErrResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_formerr);
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_EFORMERR, result.status_);
+}
+
+TEST_P(MockTCPChannelTest, ServFailResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_servfail);
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ // ARES_FLAG_NOCHECKRESP not set, so SERVFAIL consumed
+ EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
+}
+
+TEST_P(MockTCPChannelTest, NotImplResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_notimpl);
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ // ARES_FLAG_NOCHECKRESP not set, so NOTIMPL consumed
+ EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
+}
+
+TEST_P(MockTCPChannelTest, RefusedResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_refused);
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ // ARES_FLAG_NOCHECKRESP not set, so REFUSED consumed
+ EXPECT_EQ(ARES_ECONNREFUSED, result.status_);
+}
+
+TEST_P(MockTCPChannelTest, YXDomainResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_yxdomain);
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENODATA, result.status_);
+}
+
+class MockExtraOptsTest
+ : public MockChannelOptsTest,
+ public ::testing::WithParamInterface< std::pair<int, bool> > {
+ public:
+ MockExtraOptsTest()
+ : MockChannelOptsTest(1, GetParam().first, GetParam().second,
+ FillOptions(&opts_),
+ ARES_OPT_SOCK_SNDBUF|ARES_OPT_SOCK_RCVBUF) {}
+ static struct ares_options* FillOptions(struct ares_options * opts) {
+ memset(opts, 0, sizeof(struct ares_options));
+ // Set a few options that affect socket communications
+ opts->socket_send_buffer_size = 514;
+ opts->socket_receive_buffer_size = 514;
+ return opts;
+ }
+ private:
+ struct ares_options opts_;
+};
+
+TEST_P(MockExtraOptsTest, SimpleQuery) {
+ ares_set_local_ip4(channel_, 0x7F000001);
+ byte addr6[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+ ares_set_local_ip6(channel_, addr6);
+ ares_set_local_dev(channel_, "dummy");
+
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 100, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+class MockFlagsChannelOptsTest
+ : public MockChannelOptsTest,
+ public ::testing::WithParamInterface< std::pair<int, bool> > {
+ public:
+ MockFlagsChannelOptsTest(int flags)
+ : MockChannelOptsTest(1, GetParam().first, GetParam().second,
+ FillOptions(&opts_, flags), ARES_OPT_FLAGS) {}
+ static struct ares_options* FillOptions(struct ares_options * opts, int flags) {
+ memset(opts, 0, sizeof(struct ares_options));
+ opts->flags = flags;
+ return opts;
+ }
+ private:
+ struct ares_options opts_;
+};
+
+class MockNoCheckRespChannelTest : public MockFlagsChannelOptsTest {
+ public:
+ MockNoCheckRespChannelTest() : MockFlagsChannelOptsTest(ARES_FLAG_NOCHECKRESP) {}
+};
+
+TEST_P(MockNoCheckRespChannelTest, ServFailResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_servfail);
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ESERVFAIL, result.status_);
+}
+
+TEST_P(MockNoCheckRespChannelTest, NotImplResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_notimpl);
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOTIMP, result.status_);
+}
+
+TEST_P(MockNoCheckRespChannelTest, RefusedResponse) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ rsp.set_rcode(ns_r_refused);
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_EREFUSED, result.status_);
+}
+
+class MockEDNSChannelTest : public MockFlagsChannelOptsTest {
+ public:
+ MockEDNSChannelTest() : MockFlagsChannelOptsTest(ARES_FLAG_EDNS) {}
+};
+
+TEST_P(MockEDNSChannelTest, RetryWithoutEDNS) {
+ DNSPacket rspfail;
+ rspfail.set_response().set_aa().set_rcode(ns_r_servfail)
+ .add_question(new DNSQuestion("www.google.com", ns_t_a));
+ DNSPacket rspok;
+ rspok.set_response()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 100, {1, 2, 3, 4}));
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &rspfail))
+ .WillOnce(SetReply(&server_, &rspok));
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+TEST_P(MockChannelTest, SearchDomains) {
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nosecond));
+ DNSPacket yesthird;
+ yesthird.set_response().set_aa()
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a))
+ .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesthird));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+// Relies on retries so is UDP-only
+TEST_P(MockUDPChannelTest, SearchDomainsWithResentReply) {
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ EXPECT_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillOnce(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ EXPECT_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillOnce(SetReply(&server_, &nosecond));
+ DNSPacket yesthird;
+ yesthird.set_response().set_aa()
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a))
+ .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
+ // Before sending the real answer, resend an earlier reply
+ EXPECT_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillOnce(DoAll(SetReply(&server_, &nofirst),
+ SetReplyQID(&server_, 123)))
+ .WillOnce(DoAll(SetReply(&server_, &yesthird),
+ SetReplyQID(&server_, -1)));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, SearchDomainsBare) {
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nosecond));
+ DNSPacket nothird;
+ nothird.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a));
+ ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nothird));
+ DNSPacket yesbare;
+ yesbare.set_response().set_aa()
+ .add_question(new DNSQuestion("www", ns_t_a))
+ .add_answer(new DNSARR("www", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesbare));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, SearchNoDataThenSuccess) {
+ // First two search domains recognize the name but have no A records.
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa()
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa()
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nosecond));
+ DNSPacket yesthird;
+ yesthird.set_response().set_aa()
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a))
+ .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesthird));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, SearchNoDataThenNoDataBare) {
+ // First two search domains recognize the name but have no A records.
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa()
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa()
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nosecond));
+ DNSPacket nothird;
+ nothird.set_response().set_aa()
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a));
+ ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nothird));
+ DNSPacket nobare;
+ nobare.set_response().set_aa()
+ .add_question(new DNSQuestion("www", ns_t_a));
+ ON_CALL(server_, OnRequest("www", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nobare));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENODATA, result.status_);
+}
+
+TEST_P(MockChannelTest, SearchNoDataThenFail) {
+ // First two search domains recognize the name but have no A records.
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa()
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa()
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nosecond));
+ DNSPacket nothird;
+ nothird.set_response().set_aa()
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a));
+ ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nothird));
+ DNSPacket nobare;
+ nobare.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www", ns_t_a));
+ ON_CALL(server_, OnRequest("www", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nobare));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENODATA, result.status_);
+}
+
+TEST_P(MockChannelTest, SearchAllocFailure) {
+ SearchResult result;
+ SetAllocFail(1);
+ ares_search(channel_, "fully.qualified.", ns_c_in, ns_t_a, SearchCallback, &result);
+ /* Already done */
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ENOMEM, result.status_);
+}
+
+TEST_P(MockChannelTest, SearchHighNdots) {
+ DNSPacket nobare;
+ nobare.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("a.b.c.w.w.w", ns_t_a));
+ ON_CALL(server_, OnRequest("a.b.c.w.w.w", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nobare));
+ DNSPacket yesfirst;
+ yesfirst.set_response().set_aa()
+ .add_question(new DNSQuestion("a.b.c.w.w.w.first.com", ns_t_a))
+ .add_answer(new DNSARR("a.b.c.w.w.w.first.com", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("a.b.c.w.w.w.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesfirst));
+
+ SearchResult result;
+ ares_search(channel_, "a.b.c.w.w.w", ns_c_in, ns_t_a, SearchCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ std::stringstream ss;
+ ss << PacketToString(result.data_);
+ EXPECT_EQ("RSP QRY AA NOERROR Q:{'a.b.c.w.w.w.first.com' IN A} "
+ "A:{'a.b.c.w.w.w.first.com' IN A TTL=512 2.3.4.5}",
+ ss.str());
+}
+
+TEST_P(MockChannelTest, UnspecifiedFamilyV6) {
+ DNSPacket rsp6;
+ rsp6.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSAaaaRR("example.com", 100,
+ {0x21, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03}));
+ ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
+ .WillByDefault(SetReply(&server_, &rsp6));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ // Default to IPv6 when both are available.
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[2121:0000:0000:0000:0000:0000:0000:0303]}", ss.str());
+}
+
+TEST_P(MockChannelTest, UnspecifiedFamilyV4) {
+ DNSPacket rsp6;
+ rsp6.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa));
+ ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
+ .WillByDefault(SetReply(&server_, &rsp6));
+ DNSPacket rsp4;
+ rsp4.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a))
+ .add_answer(new DNSARR("example.com", 100, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("example.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp4));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, UnspecifiedFamilyNoData) {
+ DNSPacket rsp6;
+ rsp6.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSCnameRR("example.com", 100, "elsewhere.com"));
+ ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
+ .WillByDefault(SetReply(&server_, &rsp6));
+ DNSPacket rsp4;
+ rsp4.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a));
+ ON_CALL(server_, OnRequest("example.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp4));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'' aliases=[] addrs=[]}", ss.str());
+}
+
+TEST_P(MockChannelTest, UnspecifiedFamilyCname6A4) {
+ DNSPacket rsp6;
+ rsp6.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSCnameRR("example.com", 100, "elsewhere.com"));
+ ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
+ .WillByDefault(SetReply(&server_, &rsp6));
+ DNSPacket rsp4;
+ rsp4.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a))
+ .add_answer(new DNSARR("example.com", 100, {1, 2, 3, 4}));
+ ON_CALL(server_, OnRequest("example.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp4));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_UNSPEC, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+TEST_P(MockChannelTest, ExplicitIP) {
+ HostResult result;
+ ares_gethostbyname(channel_, "1.2.3.4", AF_INET, HostCallback, &result);
+ EXPECT_TRUE(result.done_); // Immediate return
+ EXPECT_EQ(ARES_SUCCESS, result.status_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'1.2.3.4' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+TEST_P(MockChannelTest, ExplicitIPAllocFail) {
+ HostResult result;
+ SetAllocSizeFail(strlen("1.2.3.4") + 1);
+ ares_gethostbyname(channel_, "1.2.3.4", AF_INET, HostCallback, &result);
+ EXPECT_TRUE(result.done_); // Immediate return
+ EXPECT_EQ(ARES_ENOMEM, result.status_);
+}
+
+TEST_P(MockChannelTest, SortListV4) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a))
+ .add_answer(new DNSARR("example.com", 100, {22, 23, 24, 25}))
+ .add_answer(new DNSARR("example.com", 100, {12, 13, 14, 15}))
+ .add_answer(new DNSARR("example.com", 100, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("example.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &rsp));
+
+ {
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "12.13.0.0/255.255.0.0 1234::5678"));
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[12.13.14.15, 22.23.24.25, 2.3.4.5]}", ss.str());
+ }
+ {
+ EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "2.3.0.0/16 130.140.150.160/26"));
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[2.3.4.5, 22.23.24.25, 12.13.14.15]}", ss.str());
+ }
+ struct ares_options options;
+ memset(&options, 0, sizeof(options));
+ int optmask = 0;
+ EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel_, &options, &optmask));
+ EXPECT_TRUE((optmask & ARES_OPT_SORTLIST) == ARES_OPT_SORTLIST);
+ ares_destroy_options(&options);
+}
+
+TEST_P(MockChannelTest, SortListV6) {
+ DNSPacket rsp;
+ rsp.set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSAaaaRR("example.com", 100,
+ {0x11, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02}))
+ .add_answer(new DNSAaaaRR("example.com", 100,
+ {0x21, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03}));
+ ON_CALL(server_, OnRequest("example.com", ns_t_aaaa))
+ .WillByDefault(SetReply(&server_, &rsp));
+
+ {
+ ares_set_sortlist(channel_, "1111::/16 2.3.0.0/255.255.0.0");
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[1111:0000:0000:0000:0000:0000:0000:0202, "
+ "2121:0000:0000:0000:0000:0000:0000:0303]}", ss.str());
+ }
+ {
+ ares_set_sortlist(channel_, "2121::/8");
+ HostResult result;
+ ares_gethostbyname(channel_, "example.com.", AF_INET6, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[2121:0000:0000:0000:0000:0000:0000:0303, "
+ "1111:0000:0000:0000:0000:0000:0000:0202]}", ss.str());
+ }
+}
+
+// Relies on retries so is UDP-only
+TEST_P(MockUDPChannelTest, SearchDomainsAllocFail) {
+ DNSPacket nofirst;
+ nofirst.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.first.com", ns_t_a));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nofirst));
+ DNSPacket nosecond;
+ nosecond.set_response().set_aa().set_rcode(ns_r_nxdomain)
+ .add_question(new DNSQuestion("www.second.org", ns_t_a));
+ ON_CALL(server_, OnRequest("www.second.org", ns_t_a))
+ .WillByDefault(SetReply(&server_, &nosecond));
+ DNSPacket yesthird;
+ yesthird.set_response().set_aa()
+ .add_question(new DNSQuestion("www.third.gov", ns_t_a))
+ .add_answer(new DNSARR("www.third.gov", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.third.gov", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesthird));
+
+ // Fail a variety of different memory allocations, and confirm
+ // that the operation either fails with ENOMEM or succeeds
+ // with the expected result.
+ const int kCount = 34;
+ HostResult results[kCount];
+ for (int ii = 1; ii <= kCount; ii++) {
+ HostResult* result = &(results[ii - 1]);
+ ClearFails();
+ SetAllocFail(ii);
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, result);
+ Process();
+ EXPECT_TRUE(result->done_);
+ if (result->status_ == ARES_SUCCESS) {
+ std::stringstream ss;
+ ss << result->host_;
+ EXPECT_EQ("{'www.third.gov' aliases=[] addrs=[2.3.4.5]}", ss.str()) << " failed alloc #" << ii;
+ if (verbose) std::cerr << "Succeeded despite failure of alloc #" << ii << std::endl;
+ }
+ }
+
+ // Explicitly destroy the channel now, so that the HostResult objects
+ // are still valid (in case any pending work refers to them).
+ ares_destroy(channel_);
+ channel_ = nullptr;
+}
+
+// Relies on retries so is UDP-only
+TEST_P(MockUDPChannelTest, Resend) {
+ std::vector<byte> nothing;
+ DNSPacket reply;
+ reply.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 0x0100, {0x01, 0x02, 0x03, 0x04}));
+
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReplyData(&server_, nothing))
+ .WillOnce(SetReplyData(&server_, nothing))
+ .WillOnce(SetReply(&server_, &reply));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(2, result.timeouts_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+TEST_P(MockChannelTest, CancelImmediate) {
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ ares_cancel(channel_);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ECANCELLED, result.status_);
+ EXPECT_EQ(0, result.timeouts_);
+}
+
+TEST_P(MockChannelTest, CancelImmediateGetHostByAddr) {
+ HostResult result;
+ struct in_addr addr;
+ addr.s_addr = htonl(0x08080808);
+
+ ares_gethostbyaddr(channel_, &addr, sizeof(addr), AF_INET, HostCallback, &result);
+ ares_cancel(channel_);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ECANCELLED, result.status_);
+ EXPECT_EQ(0, result.timeouts_);
+}
+
+// Relies on retries so is UDP-only
+TEST_P(MockUDPChannelTest, CancelLater) {
+ std::vector<byte> nothing;
+
+ // On second request, cancel the channel.
+ EXPECT_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillOnce(SetReplyData(&server_, nothing))
+ .WillOnce(CancelChannel(&server_, channel_));
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_ECANCELLED, result.status_);
+ EXPECT_EQ(0, result.timeouts_);
+}
+
+TEST_P(MockChannelTest, GetHostByNameDestroyAbsolute) {
+ HostResult result;
+ ares_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result);
+
+ ares_destroy(channel_);
+ channel_ = nullptr;
+
+ EXPECT_TRUE(result.done_); // Synchronous
+ EXPECT_EQ(ARES_EDESTRUCTION, result.status_);
+ EXPECT_EQ(0, result.timeouts_);
+}
+
+TEST_P(MockChannelTest, GetHostByNameDestroyRelative) {
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+
+ ares_destroy(channel_);
+ channel_ = nullptr;
+
+ EXPECT_TRUE(result.done_); // Synchronous
+ EXPECT_EQ(ARES_EDESTRUCTION, result.status_);
+ EXPECT_EQ(0, result.timeouts_);
+}
+
TEST_P(MockChannelTest, GetHostByNameCNAMENoData) {
DNSPacket response;
response.set_response().set_aa()
@@ -951,223 +951,223 @@ TEST_P(MockChannelTest, GetHostByNameCNAMENoData) {
EXPECT_EQ(ARES_ENODATA, result.status_);
}
-TEST_P(MockChannelTest, GetHostByAddrDestroy) {
- unsigned char gdns_addr4[4] = {0x08, 0x08, 0x08, 0x08};
- HostResult result;
- ares_gethostbyaddr(channel_, gdns_addr4, sizeof(gdns_addr4), AF_INET, HostCallback, &result);
-
- ares_destroy(channel_);
- channel_ = nullptr;
-
- EXPECT_TRUE(result.done_); // Synchronous
- EXPECT_EQ(ARES_EDESTRUCTION, result.status_);
- EXPECT_EQ(0, result.timeouts_);
-}
-
-#ifndef WIN32
-TEST_P(MockChannelTest, HostAlias) {
- DNSPacket reply;
- reply.set_response().set_aa()
- .add_question(new DNSQuestion("www.google.com", ns_t_a))
- .add_answer(new DNSARR("www.google.com", 0x0100, {0x01, 0x02, 0x03, 0x04}));
- ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &reply));
-
- TempFile aliases("\n\n# www commentedout\nwww www.google.com\n");
- EnvValue with_env("HOSTALIASES", aliases.filename());
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
-}
-
-TEST_P(MockChannelTest, HostAliasMissing) {
- DNSPacket yesfirst;
- yesfirst.set_response().set_aa()
- .add_question(new DNSQuestion("www.first.com", ns_t_a))
- .add_answer(new DNSARR("www.first.com", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesfirst));
-
- TempFile aliases("\n\n# www commentedout\nww www.google.com\n");
- EnvValue with_env("HOSTALIASES", aliases.filename());
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.first.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, HostAliasMissingFile) {
- DNSPacket yesfirst;
- yesfirst.set_response().set_aa()
- .add_question(new DNSQuestion("www.first.com", ns_t_a))
- .add_answer(new DNSARR("www.first.com", 0x0200, {2, 3, 4, 5}));
- ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
- .WillByDefault(SetReply(&server_, &yesfirst));
-
- EnvValue with_env("HOSTALIASES", "bogus.mcfile");
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.first.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
-}
-
-TEST_P(MockChannelTest, HostAliasUnreadable) {
- TempFile aliases("www www.google.com\n");
- chmod(aliases.filename(), 0);
- EnvValue with_env("HOSTALIASES", aliases.filename());
-
- HostResult result;
- ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
- EXPECT_TRUE(result.done_);
- EXPECT_EQ(ARES_EFILE, result.status_);
- chmod(aliases.filename(), 0777);
-}
-#endif
-
-class MockMultiServerChannelTest
- : public MockChannelOptsTest,
- public ::testing::WithParamInterface< std::pair<int, bool> > {
- public:
- MockMultiServerChannelTest(bool rotate)
- : MockChannelOptsTest(3, GetParam().first, GetParam().second, nullptr, rotate ? ARES_OPT_ROTATE : ARES_OPT_NOROTATE) {}
- void CheckExample() {
- HostResult result;
- ares_gethostbyname(channel_, "www.example.com.", AF_INET, HostCallback, &result);
- Process();
- EXPECT_TRUE(result.done_);
- std::stringstream ss;
- ss << result.host_;
- EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
- }
-};
-
-class RotateMultiMockTest : public MockMultiServerChannelTest {
- public:
- RotateMultiMockTest() : MockMultiServerChannelTest(true) {}
-};
-
-class NoRotateMultiMockTest : public MockMultiServerChannelTest {
- public:
- NoRotateMultiMockTest() : MockMultiServerChannelTest(false) {}
-};
-
-
-TEST_P(RotateMultiMockTest, ThirdServer) {
- struct ares_options opts = {0};
- int optmask = 0;
- EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel_, &opts, &optmask));
- EXPECT_EQ(0, (optmask & ARES_OPT_NOROTATE));
- ares_destroy_options(&opts);
-
- DNSPacket servfailrsp;
- servfailrsp.set_response().set_aa().set_rcode(ns_r_servfail)
- .add_question(new DNSQuestion("www.example.com", ns_t_a));
- DNSPacket notimplrsp;
- notimplrsp.set_response().set_aa().set_rcode(ns_r_notimpl)
- .add_question(new DNSQuestion("www.example.com", ns_t_a));
- DNSPacket okrsp;
- okrsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.example.com", ns_t_a))
- .add_answer(new DNSARR("www.example.com", 100, {2,3,4,5}));
-
- EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
- EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
- EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[2].get(), &okrsp));
- CheckExample();
-
- // Second time around, starts from server [1].
- EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[1].get(), &servfailrsp));
- EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[2].get(), &notimplrsp));
- EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[0].get(), &okrsp));
- CheckExample();
-
- // Third time around, starts from server [2].
- EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[2].get(), &servfailrsp));
- EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[0].get(), &notimplrsp));
- EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[1].get(), &okrsp));
- CheckExample();
-}
-
-TEST_P(NoRotateMultiMockTest, ThirdServer) {
- struct ares_options opts = {0};
- int optmask = 0;
- EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel_, &opts, &optmask));
- EXPECT_EQ(ARES_OPT_NOROTATE, (optmask & ARES_OPT_NOROTATE));
- ares_destroy_options(&opts);
-
- DNSPacket servfailrsp;
- servfailrsp.set_response().set_aa().set_rcode(ns_r_servfail)
- .add_question(new DNSQuestion("www.example.com", ns_t_a));
- DNSPacket notimplrsp;
- notimplrsp.set_response().set_aa().set_rcode(ns_r_notimpl)
- .add_question(new DNSQuestion("www.example.com", ns_t_a));
- DNSPacket okrsp;
- okrsp.set_response().set_aa()
- .add_question(new DNSQuestion("www.example.com", ns_t_a))
- .add_answer(new DNSARR("www.example.com", 100, {2,3,4,5}));
-
- EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
- EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
- EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[2].get(), &okrsp));
- CheckExample();
-
- // Second time around, still starts from server [0].
- EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
- EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
- EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[2].get(), &okrsp));
- CheckExample();
-
- // Third time around, still starts from server [0].
- EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
- EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
- EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
- .WillOnce(SetReply(servers_[2].get(), &okrsp));
- CheckExample();
-}
-
-INSTANTIATE_TEST_CASE_P(AddressFamilies, MockChannelTest, ::testing::ValuesIn(ares::test::families_modes));
-
-INSTANTIATE_TEST_CASE_P(AddressFamilies, MockUDPChannelTest, ::testing::ValuesIn(ares::test::families));
-
-INSTANTIATE_TEST_CASE_P(AddressFamilies, MockTCPChannelTest, ::testing::ValuesIn(ares::test::families));
-
-INSTANTIATE_TEST_CASE_P(AddressFamilies, MockExtraOptsTest, ::testing::ValuesIn(ares::test::families_modes));
-
-INSTANTIATE_TEST_CASE_P(AddressFamilies, MockNoCheckRespChannelTest, ::testing::ValuesIn(ares::test::families_modes));
-
-INSTANTIATE_TEST_CASE_P(AddressFamilies, MockEDNSChannelTest, ::testing::ValuesIn(ares::test::families_modes));
-
-INSTANTIATE_TEST_CASE_P(TransportModes, RotateMultiMockTest, ::testing::ValuesIn(ares::test::families_modes));
-
-INSTANTIATE_TEST_CASE_P(TransportModes, NoRotateMultiMockTest, ::testing::ValuesIn(ares::test::families_modes));
-
-} // namespace test
-} // namespace ares
+TEST_P(MockChannelTest, GetHostByAddrDestroy) {
+ unsigned char gdns_addr4[4] = {0x08, 0x08, 0x08, 0x08};
+ HostResult result;
+ ares_gethostbyaddr(channel_, gdns_addr4, sizeof(gdns_addr4), AF_INET, HostCallback, &result);
+
+ ares_destroy(channel_);
+ channel_ = nullptr;
+
+ EXPECT_TRUE(result.done_); // Synchronous
+ EXPECT_EQ(ARES_EDESTRUCTION, result.status_);
+ EXPECT_EQ(0, result.timeouts_);
+}
+
+#ifndef WIN32
+TEST_P(MockChannelTest, HostAlias) {
+ DNSPacket reply;
+ reply.set_response().set_aa()
+ .add_question(new DNSQuestion("www.google.com", ns_t_a))
+ .add_answer(new DNSARR("www.google.com", 0x0100, {0x01, 0x02, 0x03, 0x04}));
+ ON_CALL(server_, OnRequest("www.google.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &reply));
+
+ TempFile aliases("\n\n# www commentedout\nwww www.google.com\n");
+ EnvValue with_env("HOSTALIASES", aliases.filename());
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.google.com' aliases=[] addrs=[1.2.3.4]}", ss.str());
+}
+
+TEST_P(MockChannelTest, HostAliasMissing) {
+ DNSPacket yesfirst;
+ yesfirst.set_response().set_aa()
+ .add_question(new DNSQuestion("www.first.com", ns_t_a))
+ .add_answer(new DNSARR("www.first.com", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesfirst));
+
+ TempFile aliases("\n\n# www commentedout\nww www.google.com\n");
+ EnvValue with_env("HOSTALIASES", aliases.filename());
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.first.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, HostAliasMissingFile) {
+ DNSPacket yesfirst;
+ yesfirst.set_response().set_aa()
+ .add_question(new DNSQuestion("www.first.com", ns_t_a))
+ .add_answer(new DNSARR("www.first.com", 0x0200, {2, 3, 4, 5}));
+ ON_CALL(server_, OnRequest("www.first.com", ns_t_a))
+ .WillByDefault(SetReply(&server_, &yesfirst));
+
+ EnvValue with_env("HOSTALIASES", "bogus.mcfile");
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.first.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+}
+
+TEST_P(MockChannelTest, HostAliasUnreadable) {
+ TempFile aliases("www www.google.com\n");
+ chmod(aliases.filename(), 0);
+ EnvValue with_env("HOSTALIASES", aliases.filename());
+
+ HostResult result;
+ ares_gethostbyname(channel_, "www", AF_INET, HostCallback, &result);
+ EXPECT_TRUE(result.done_);
+ EXPECT_EQ(ARES_EFILE, result.status_);
+ chmod(aliases.filename(), 0777);
+}
+#endif
+
+class MockMultiServerChannelTest
+ : public MockChannelOptsTest,
+ public ::testing::WithParamInterface< std::pair<int, bool> > {
+ public:
+ MockMultiServerChannelTest(bool rotate)
+ : MockChannelOptsTest(3, GetParam().first, GetParam().second, nullptr, rotate ? ARES_OPT_ROTATE : ARES_OPT_NOROTATE) {}
+ void CheckExample() {
+ HostResult result;
+ ares_gethostbyname(channel_, "www.example.com.", AF_INET, HostCallback, &result);
+ Process();
+ EXPECT_TRUE(result.done_);
+ std::stringstream ss;
+ ss << result.host_;
+ EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ }
+};
+
+class RotateMultiMockTest : public MockMultiServerChannelTest {
+ public:
+ RotateMultiMockTest() : MockMultiServerChannelTest(true) {}
+};
+
+class NoRotateMultiMockTest : public MockMultiServerChannelTest {
+ public:
+ NoRotateMultiMockTest() : MockMultiServerChannelTest(false) {}
+};
+
+
+TEST_P(RotateMultiMockTest, ThirdServer) {
+ struct ares_options opts = {0};
+ int optmask = 0;
+ EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel_, &opts, &optmask));
+ EXPECT_EQ(0, (optmask & ARES_OPT_NOROTATE));
+ ares_destroy_options(&opts);
+
+ DNSPacket servfailrsp;
+ servfailrsp.set_response().set_aa().set_rcode(ns_r_servfail)
+ .add_question(new DNSQuestion("www.example.com", ns_t_a));
+ DNSPacket notimplrsp;
+ notimplrsp.set_response().set_aa().set_rcode(ns_r_notimpl)
+ .add_question(new DNSQuestion("www.example.com", ns_t_a));
+ DNSPacket okrsp;
+ okrsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.example.com", ns_t_a))
+ .add_answer(new DNSARR("www.example.com", 100, {2,3,4,5}));
+
+ EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
+ EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
+ EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[2].get(), &okrsp));
+ CheckExample();
+
+ // Second time around, starts from server [1].
+ EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[1].get(), &servfailrsp));
+ EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[2].get(), &notimplrsp));
+ EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[0].get(), &okrsp));
+ CheckExample();
+
+ // Third time around, starts from server [2].
+ EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[2].get(), &servfailrsp));
+ EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[0].get(), &notimplrsp));
+ EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[1].get(), &okrsp));
+ CheckExample();
+}
+
+TEST_P(NoRotateMultiMockTest, ThirdServer) {
+ struct ares_options opts = {0};
+ int optmask = 0;
+ EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel_, &opts, &optmask));
+ EXPECT_EQ(ARES_OPT_NOROTATE, (optmask & ARES_OPT_NOROTATE));
+ ares_destroy_options(&opts);
+
+ DNSPacket servfailrsp;
+ servfailrsp.set_response().set_aa().set_rcode(ns_r_servfail)
+ .add_question(new DNSQuestion("www.example.com", ns_t_a));
+ DNSPacket notimplrsp;
+ notimplrsp.set_response().set_aa().set_rcode(ns_r_notimpl)
+ .add_question(new DNSQuestion("www.example.com", ns_t_a));
+ DNSPacket okrsp;
+ okrsp.set_response().set_aa()
+ .add_question(new DNSQuestion("www.example.com", ns_t_a))
+ .add_answer(new DNSARR("www.example.com", 100, {2,3,4,5}));
+
+ EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
+ EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
+ EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[2].get(), &okrsp));
+ CheckExample();
+
+ // Second time around, still starts from server [0].
+ EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
+ EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
+ EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[2].get(), &okrsp));
+ CheckExample();
+
+ // Third time around, still starts from server [0].
+ EXPECT_CALL(*servers_[0], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[0].get(), &servfailrsp));
+ EXPECT_CALL(*servers_[1], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[1].get(), &notimplrsp));
+ EXPECT_CALL(*servers_[2], OnRequest("www.example.com", ns_t_a))
+ .WillOnce(SetReply(servers_[2].get(), &okrsp));
+ CheckExample();
+}
+
+INSTANTIATE_TEST_CASE_P(AddressFamilies, MockChannelTest, ::testing::ValuesIn(ares::test::families_modes));
+
+INSTANTIATE_TEST_CASE_P(AddressFamilies, MockUDPChannelTest, ::testing::ValuesIn(ares::test::families));
+
+INSTANTIATE_TEST_CASE_P(AddressFamilies, MockTCPChannelTest, ::testing::ValuesIn(ares::test::families));
+
+INSTANTIATE_TEST_CASE_P(AddressFamilies, MockExtraOptsTest, ::testing::ValuesIn(ares::test::families_modes));
+
+INSTANTIATE_TEST_CASE_P(AddressFamilies, MockNoCheckRespChannelTest, ::testing::ValuesIn(ares::test::families_modes));
+
+INSTANTIATE_TEST_CASE_P(AddressFamilies, MockEDNSChannelTest, ::testing::ValuesIn(ares::test::families_modes));
+
+INSTANTIATE_TEST_CASE_P(TransportModes, RotateMultiMockTest, ::testing::ValuesIn(ares::test::families_modes));
+
+INSTANTIATE_TEST_CASE_P(TransportModes, NoRotateMultiMockTest, ::testing::ValuesIn(ares::test::families_modes));
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-ns.cc b/contrib/libs/c-ares/test/ares-test-ns.cc
index c3c455214d..77ebdcc2e2 100644
--- a/contrib/libs/c-ares/test/ares-test-ns.cc
+++ b/contrib/libs/c-ares/test/ares-test-ns.cc
@@ -1,199 +1,199 @@
-#include "ares-test.h"
-
-#ifdef HAVE_CONTAINER
-
-#include <sys/mount.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-#include <iostream>
-#include <functional>
-#include <string>
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-namespace {
-
-struct ContainerInfo {
- ContainerFilesystem* fs_;
- std::string hostname_;
- std::string domainname_;
- VoidToIntFn fn_;
-};
-
-int EnterContainer(void *data) {
- ContainerInfo *container = (ContainerInfo*)data;
-
- if (verbose) {
- std::cerr << "Running function in container {chroot='"
- << container->fs_->root() << "', hostname='" << container->hostname_
- << "', domainname='" << container->domainname_ << "'}"
- << std::endl;
- }
-
- // Ensure we are apparently root before continuing.
- int count = 10;
- while (getuid() != 0 && count > 0) {
- usleep(100000);
- count--;
- }
- if (getuid() != 0) {
- std::cerr << "Child in user namespace has uid " << getuid() << std::endl;
- return -1;
- }
- if (!container->fs_->mountpt().empty()) {
- // We want to bind mount this inside the specified directory.
- std::string innerdir = container->fs_->root() + container->fs_->mountpt();
- if (verbose) std::cerr << " mount --bind " << container->fs_->mountpt()
- << " " << innerdir << std::endl;
- int rc = mount(container->fs_->mountpt().c_str(), innerdir.c_str(),
- "none", MS_BIND, 0);
- if (rc != 0) {
- std::cerr << "Warning: failed to bind mount " << container->fs_->mountpt() << " at "
- << innerdir << ", errno=" << errno << std::endl;
- }
- }
-
- // Move into the specified directory.
- if (chdir(container->fs_->root().c_str()) != 0) {
- std::cerr << "Failed to chdir('" << container->fs_->root()
- << "'), errno=" << errno << std::endl;
- return -1;
- }
- // And make it the new root directory;
- char buffer[PATH_MAX + 1];
- if (getcwd(buffer, PATH_MAX) == NULL) {
- std::cerr << "failed to retrieve cwd, errno=" << errno << std::endl;
- return -1;
- }
- buffer[PATH_MAX] = '\0';
- if (chroot(buffer) != 0) {
- std::cerr << "chroot('" << buffer << "') failed, errno=" << errno << std::endl;
- return -1;
- }
-
- // Set host/domainnames if specified
- if (!container->hostname_.empty()) {
- if (sethostname(container->hostname_.c_str(),
- container->hostname_.size()) != 0) {
- std::cerr << "Failed to sethostname('" << container->hostname_
- << "'), errno=" << errno << std::endl;
- return -1;
- }
- }
- if (!container->domainname_.empty()) {
- if (setdomainname(container->domainname_.c_str(),
- container->domainname_.size()) != 0) {
- std::cerr << "Failed to setdomainname('" << container->domainname_
- << "'), errno=" << errno << std::endl;
- return -1;
- }
- }
-
- return container->fn_();
-}
-
-} // namespace
-
-// Run a function while:
-// - chroot()ed into a particular directory
-// - having a specified hostname/domainname
-
-int RunInContainer(ContainerFilesystem* fs, const std::string& hostname,
- const std::string& domainname, VoidToIntFn fn) {
- const int stack_size = 1024 * 1024;
- std::vector<byte> stack(stack_size, 0);
- ContainerInfo container = {fs, hostname, domainname, fn};
-
- // Start a child process in a new user and UTS namespace
- pid_t child = clone(EnterContainer, stack.data() + stack_size,
- CLONE_VM|CLONE_NEWNS|CLONE_NEWUSER|CLONE_NEWUTS|SIGCHLD,
- (void *)&container);
- if (child < 0) {
- std::cerr << "Failed to clone(), errno=" << errno << std::endl;
- return -1;
- }
-
- // Build the UID map that makes us look like root inside the namespace.
- std::stringstream mapfiless;
- mapfiless << "/proc/" << child << "/uid_map";
- std::string mapfile = mapfiless.str();
- int fd = open(mapfile.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0644);
- if (fd < 0) {
- std::cerr << "Failed to create '" << mapfile << "'" << std::endl;
- return -1;
- }
- std::stringstream contentss;
- contentss << "0 " << getuid() << " 1" << std::endl;
- std::string content = contentss.str();
- int rc = write(fd, content.c_str(), content.size());
- if (rc != (int)content.size()) {
- std::cerr << "Failed to write uid map to '" << mapfile << "'" << std::endl;
- }
- close(fd);
-
- // Wait for the child process and retrieve its status.
- int status;
- waitpid(child, &status, 0);
- if (rc <= 0) {
- std::cerr << "Failed to waitpid(" << child << ")" << std::endl;
- return -1;
- }
- if (!WIFEXITED(status)) {
- std::cerr << "Child " << child << " did not exit normally" << std::endl;
- return -1;
- }
- return status;
-}
-
-ContainerFilesystem::ContainerFilesystem(NameContentList files, const std::string& mountpt) {
- rootdir_ = TempNam(nullptr, "ares-chroot");
- mkdir(rootdir_.c_str(), 0755);
- dirs_.push_front(rootdir_);
- for (const auto& nc : files) {
- std::string fullpath = rootdir_ + nc.first;
- int idx = fullpath.rfind('/');
- std::string dir = fullpath.substr(0, idx);
- EnsureDirExists(dir);
- files_.push_back(std::unique_ptr<TransientFile>(
- new TransientFile(fullpath, nc.second)));
- }
- if (!mountpt.empty()) {
- char buffer[PATH_MAX + 1];
- if (realpath(mountpt.c_str(), buffer)) {
- mountpt_ = buffer;
- std::string fullpath = rootdir_ + mountpt_;
- EnsureDirExists(fullpath);
- }
- }
-}
-
-ContainerFilesystem::~ContainerFilesystem() {
- files_.clear();
- for (const std::string& dir : dirs_) {
- rmdir(dir.c_str());
- }
-}
-
-void ContainerFilesystem::EnsureDirExists(const std::string& dir) {
- if (std::find(dirs_.begin(), dirs_.end(), dir) != dirs_.end()) {
- return;
- }
- size_t idx = dir.rfind('/');
- if (idx != std::string::npos) {
- std::string prevdir = dir.substr(0, idx);
- EnsureDirExists(prevdir);
- }
- // Ensure this directory is in the list before its ancestors.
- mkdir(dir.c_str(), 0755);
- dirs_.push_front(dir);
-}
-
-} // namespace test
-} // namespace ares
-
-#endif
+#include "ares-test.h"
+
+#ifdef HAVE_CONTAINER
+
+#include <sys/mount.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#include <iostream>
+#include <functional>
+#include <string>
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+namespace {
+
+struct ContainerInfo {
+ ContainerFilesystem* fs_;
+ std::string hostname_;
+ std::string domainname_;
+ VoidToIntFn fn_;
+};
+
+int EnterContainer(void *data) {
+ ContainerInfo *container = (ContainerInfo*)data;
+
+ if (verbose) {
+ std::cerr << "Running function in container {chroot='"
+ << container->fs_->root() << "', hostname='" << container->hostname_
+ << "', domainname='" << container->domainname_ << "'}"
+ << std::endl;
+ }
+
+ // Ensure we are apparently root before continuing.
+ int count = 10;
+ while (getuid() != 0 && count > 0) {
+ usleep(100000);
+ count--;
+ }
+ if (getuid() != 0) {
+ std::cerr << "Child in user namespace has uid " << getuid() << std::endl;
+ return -1;
+ }
+ if (!container->fs_->mountpt().empty()) {
+ // We want to bind mount this inside the specified directory.
+ std::string innerdir = container->fs_->root() + container->fs_->mountpt();
+ if (verbose) std::cerr << " mount --bind " << container->fs_->mountpt()
+ << " " << innerdir << std::endl;
+ int rc = mount(container->fs_->mountpt().c_str(), innerdir.c_str(),
+ "none", MS_BIND, 0);
+ if (rc != 0) {
+ std::cerr << "Warning: failed to bind mount " << container->fs_->mountpt() << " at "
+ << innerdir << ", errno=" << errno << std::endl;
+ }
+ }
+
+ // Move into the specified directory.
+ if (chdir(container->fs_->root().c_str()) != 0) {
+ std::cerr << "Failed to chdir('" << container->fs_->root()
+ << "'), errno=" << errno << std::endl;
+ return -1;
+ }
+ // And make it the new root directory;
+ char buffer[PATH_MAX + 1];
+ if (getcwd(buffer, PATH_MAX) == NULL) {
+ std::cerr << "failed to retrieve cwd, errno=" << errno << std::endl;
+ return -1;
+ }
+ buffer[PATH_MAX] = '\0';
+ if (chroot(buffer) != 0) {
+ std::cerr << "chroot('" << buffer << "') failed, errno=" << errno << std::endl;
+ return -1;
+ }
+
+ // Set host/domainnames if specified
+ if (!container->hostname_.empty()) {
+ if (sethostname(container->hostname_.c_str(),
+ container->hostname_.size()) != 0) {
+ std::cerr << "Failed to sethostname('" << container->hostname_
+ << "'), errno=" << errno << std::endl;
+ return -1;
+ }
+ }
+ if (!container->domainname_.empty()) {
+ if (setdomainname(container->domainname_.c_str(),
+ container->domainname_.size()) != 0) {
+ std::cerr << "Failed to setdomainname('" << container->domainname_
+ << "'), errno=" << errno << std::endl;
+ return -1;
+ }
+ }
+
+ return container->fn_();
+}
+
+} // namespace
+
+// Run a function while:
+// - chroot()ed into a particular directory
+// - having a specified hostname/domainname
+
+int RunInContainer(ContainerFilesystem* fs, const std::string& hostname,
+ const std::string& domainname, VoidToIntFn fn) {
+ const int stack_size = 1024 * 1024;
+ std::vector<byte> stack(stack_size, 0);
+ ContainerInfo container = {fs, hostname, domainname, fn};
+
+ // Start a child process in a new user and UTS namespace
+ pid_t child = clone(EnterContainer, stack.data() + stack_size,
+ CLONE_VM|CLONE_NEWNS|CLONE_NEWUSER|CLONE_NEWUTS|SIGCHLD,
+ (void *)&container);
+ if (child < 0) {
+ std::cerr << "Failed to clone(), errno=" << errno << std::endl;
+ return -1;
+ }
+
+ // Build the UID map that makes us look like root inside the namespace.
+ std::stringstream mapfiless;
+ mapfiless << "/proc/" << child << "/uid_map";
+ std::string mapfile = mapfiless.str();
+ int fd = open(mapfile.c_str(), O_CREAT|O_WRONLY|O_TRUNC, 0644);
+ if (fd < 0) {
+ std::cerr << "Failed to create '" << mapfile << "'" << std::endl;
+ return -1;
+ }
+ std::stringstream contentss;
+ contentss << "0 " << getuid() << " 1" << std::endl;
+ std::string content = contentss.str();
+ int rc = write(fd, content.c_str(), content.size());
+ if (rc != (int)content.size()) {
+ std::cerr << "Failed to write uid map to '" << mapfile << "'" << std::endl;
+ }
+ close(fd);
+
+ // Wait for the child process and retrieve its status.
+ int status;
+ waitpid(child, &status, 0);
+ if (rc <= 0) {
+ std::cerr << "Failed to waitpid(" << child << ")" << std::endl;
+ return -1;
+ }
+ if (!WIFEXITED(status)) {
+ std::cerr << "Child " << child << " did not exit normally" << std::endl;
+ return -1;
+ }
+ return status;
+}
+
+ContainerFilesystem::ContainerFilesystem(NameContentList files, const std::string& mountpt) {
+ rootdir_ = TempNam(nullptr, "ares-chroot");
+ mkdir(rootdir_.c_str(), 0755);
+ dirs_.push_front(rootdir_);
+ for (const auto& nc : files) {
+ std::string fullpath = rootdir_ + nc.first;
+ int idx = fullpath.rfind('/');
+ std::string dir = fullpath.substr(0, idx);
+ EnsureDirExists(dir);
+ files_.push_back(std::unique_ptr<TransientFile>(
+ new TransientFile(fullpath, nc.second)));
+ }
+ if (!mountpt.empty()) {
+ char buffer[PATH_MAX + 1];
+ if (realpath(mountpt.c_str(), buffer)) {
+ mountpt_ = buffer;
+ std::string fullpath = rootdir_ + mountpt_;
+ EnsureDirExists(fullpath);
+ }
+ }
+}
+
+ContainerFilesystem::~ContainerFilesystem() {
+ files_.clear();
+ for (const std::string& dir : dirs_) {
+ rmdir(dir.c_str());
+ }
+}
+
+void ContainerFilesystem::EnsureDirExists(const std::string& dir) {
+ if (std::find(dirs_.begin(), dirs_.end(), dir) != dirs_.end()) {
+ return;
+ }
+ size_t idx = dir.rfind('/');
+ if (idx != std::string::npos) {
+ std::string prevdir = dir.substr(0, idx);
+ EnsureDirExists(prevdir);
+ }
+ // Ensure this directory is in the list before its ancestors.
+ mkdir(dir.c_str(), 0755);
+ dirs_.push_front(dir);
+}
+
+} // namespace test
+} // namespace ares
+
+#endif
diff --git a/contrib/libs/c-ares/test/ares-test-parse-a.cc b/contrib/libs/c-ares/test/ares-test-parse-a.cc
index 7f6a987c13..65bc822c05 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-a.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-a.cc
@@ -1,41 +1,41 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseAReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a))
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseAReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a))
.add_answer(new DNSARR("example.com", 0x01020304, {2,3,4,5}))
.add_answer(new DNSAaaaRR("example.com", 0x01020304, {0,0,0,0,0,0,0,0,0,0,0,0,2,3,4,5}));
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
0x00, 0x02, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
// Answer 2
0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
0x03, 'c', 'o', 'm',
@@ -45,334 +45,334 @@ TEST_F(LibraryTest, ParseAReplyOK) {
0x01, 0x02, 0x03, 0x04, // TTL
0x00, 0x10, // rdata length
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x04, 0x05,
- };
- EXPECT_EQ(data, pkt.data());
- struct hostent *host = nullptr;
- struct ares_addrttl info[5];
- int count = 5;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ(0x01020304, info[0].ttl);
- unsigned long expected_addr = htonl(0x02030405);
- EXPECT_EQ(expected_addr, info[0].ipaddr.s_addr);
- EXPECT_EQ("2.3.4.5", AddressToString(&(info[0].ipaddr), 4));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
- ares_free_hostent(host);
-
- // Repeat without providing a hostent
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- nullptr, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ(0x01020304, info[0].ttl);
- EXPECT_EQ(expected_addr, info[0].ipaddr.s_addr);
- EXPECT_EQ("2.3.4.5", AddressToString(&(info[0].ipaddr), 4));
-}
-
-TEST_F(LibraryTest, ParseMalformedAReply) {
- std::vector<byte> data = {
- 0x12, 0x34, // [0:2) qid
- 0x84, // [2] response + query + AA + not-TC + not-RD
- 0x00, // [3] not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // [4:6) num questions
+ };
+ EXPECT_EQ(data, pkt.data());
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[5];
+ int count = 5;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ(0x01020304, info[0].ttl);
+ unsigned long expected_addr = htonl(0x02030405);
+ EXPECT_EQ(expected_addr, info[0].ipaddr.s_addr);
+ EXPECT_EQ("2.3.4.5", AddressToString(&(info[0].ipaddr), 4));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ ares_free_hostent(host);
+
+ // Repeat without providing a hostent
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ nullptr, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ(0x01020304, info[0].ttl);
+ EXPECT_EQ(expected_addr, info[0].ipaddr.s_addr);
+ EXPECT_EQ("2.3.4.5", AddressToString(&(info[0].ipaddr), 4));
+}
+
+TEST_F(LibraryTest, ParseMalformedAReply) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // [0:2) qid
+ 0x84, // [2] response + query + AA + not-TC + not-RD
+ 0x00, // [3] not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // [4:6) num questions
0x00, 0x02, // [6:8) num answer RRs
- 0x00, 0x00, // [8:10) num authority RRs
- 0x00, 0x00, // [10:12) num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', // [12:20)
- 0x03, 'c', 'o', 'm', // [20,24)
- 0x00, // [24]
- 0x00, 0x01, // [25:26) type A
- 0x00, 0x01, // [27:29) class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', // [29:37)
- 0x03, 'c', 'o', 'm', // [37:41)
- 0x00, // [41]
- 0x00, 0x01, // [42:44) RR type
- 0x00, 0x01, // [44:46) class IN
- 0x01, 0x02, 0x03, 0x04, // [46:50) TTL
- 0x00, 0x04, // [50:52) rdata length
- 0x02, 0x03, 0x04, 0x05, // [52,56)
- };
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
-
- // Invalid RR-len.
- std::vector<byte> invalid_rrlen(data);
- invalid_rrlen[51] = 180;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(invalid_rrlen.data(), invalid_rrlen.size(),
- &host, info, &count));
-
- // Truncate mid-question.
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), 26,
- &host, info, &count));
-
- // Truncate mid-answer.
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), 42,
- &host, info, &count));
-}
-
-TEST_F(LibraryTest, ParseAReplyNoData) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(0, count);
- EXPECT_EQ(nullptr, host);
-
- // Again but with a CNAME.
- pkt.add_answer(new DNSCnameRR("example.com", 200, "c.example.com"));
+ 0x00, 0x00, // [8:10) num authority RRs
+ 0x00, 0x00, // [10:12) num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', // [12:20)
+ 0x03, 'c', 'o', 'm', // [20,24)
+ 0x00, // [24]
+ 0x00, 0x01, // [25:26) type A
+ 0x00, 0x01, // [27:29) class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', // [29:37)
+ 0x03, 'c', 'o', 'm', // [37:41)
+ 0x00, // [41]
+ 0x00, 0x01, // [42:44) RR type
+ 0x00, 0x01, // [44:46) class IN
+ 0x01, 0x02, 0x03, 0x04, // [46:50) TTL
+ 0x00, 0x04, // [50:52) rdata length
+ 0x02, 0x03, 0x04, 0x05, // [52,56)
+ };
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+
+ // Invalid RR-len.
+ std::vector<byte> invalid_rrlen(data);
+ invalid_rrlen[51] = 180;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(invalid_rrlen.data(), invalid_rrlen.size(),
+ &host, info, &count));
+
+ // Truncate mid-question.
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), 26,
+ &host, info, &count));
+
+ // Truncate mid-answer.
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), 42,
+ &host, info, &count));
+}
+
+TEST_F(LibraryTest, ParseAReplyNoData) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(0, count);
+ EXPECT_EQ(nullptr, host);
+
+ // Again but with a CNAME.
+ pkt.add_answer(new DNSCnameRR("example.com", 200, "c.example.com"));
data = pkt.data();
// Expect success as per https://github.com/c-ares/c-ares/commit/2c63440127feed70ccefb148b8f938a2df6c15f8
EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(0, count);
+ &host, info, &count));
+ EXPECT_EQ(0, count);
EXPECT_NE(nullptr, host);
std::stringstream ss;
ss << HostEnt(host);
EXPECT_EQ("{'c.example.com' aliases=[example.com] addrs=[]}", ss.str());
ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseAReplyVariantA) {
- DNSPacket pkt;
- pkt.set_qid(6366).set_rd().set_ra()
- .add_question(new DNSQuestion("mit.edu", ns_t_a))
- .add_answer(new DNSARR("mit.edu", 52, {18,7,22,69}))
- .add_auth(new DNSNsRR("mit.edu", 292, "W20NS.mit.edu"))
- .add_auth(new DNSNsRR("mit.edu", 292, "BITSY.mit.edu"))
- .add_auth(new DNSNsRR("mit.edu", 292, "STRAWB.mit.edu"))
- .add_additional(new DNSARR("STRAWB.mit.edu", 292, {18,71,0,151}));
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- std::vector<byte> data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ("18.7.22.69", AddressToString(&(info[0].ipaddr), 4));
- EXPECT_EQ(52, info[0].ttl);
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseAReplyJustCname) {
- DNSPacket pkt;
- pkt.set_qid(6366).set_rd().set_ra()
- .add_question(new DNSQuestion("mit.edu", ns_t_a))
- .add_answer(new DNSCnameRR("mit.edu", 52, "other.mit.edu"));
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- std::vector<byte> data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(0, count);
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'other.mit.edu' aliases=[mit.edu] addrs=[]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseAReplyVariantCname) {
- DNSPacket pkt;
- pkt.set_qid(6366).set_rd().set_ra()
- .add_question(new DNSQuestion("query.example.com", ns_t_a))
- .add_answer(new DNSCnameRR("query.example.com", 200, "redirect.query.example.com"))
- .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,22}))
- .add_auth(new DNSNsRR("example.com", 218, "aa.ns1.example.com"))
- .add_auth(new DNSNsRR("example.com", 218, "ns2.example.com"))
- .add_auth(new DNSNsRR("example.com", 218, "ns3.example.com"))
- .add_auth(new DNSNsRR("example.com", 218, "ns4.example.com"))
- .add_additional(new DNSARR("aa.ns1.example.com", 218, {129,97,1,1}))
- .add_additional(new DNSARR("ns2.example.com", 218, {129,97,1,2}))
- .add_additional(new DNSARR("ns3.example.com", 218, {129,97,1,3}))
- .add_additional(new DNSARR("ns4.example.com", 218, {129,97,1,4}));
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- std::vector<byte> data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ("129.97.123.22", AddressToString(&(info[0].ipaddr), 4));
- // TTL is reduced to match CNAME's.
- EXPECT_EQ(200, info[0].ttl);
- ares_free_hostent(host);
-
- // Repeat parsing without places to put the results.
- count = 0;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- nullptr, info, &count));
-}
-
-TEST_F(LibraryTest, ParseAReplyVariantCnameChain) {
- DNSPacket pkt;
- pkt.set_qid(6366).set_rd().set_ra()
- .add_question(new DNSQuestion("c1.localhost", ns_t_a))
- .add_answer(new DNSCnameRR("c1.localhost", 604800, "c2.localhost"))
- .add_answer(new DNSCnameRR("c2.localhost", 604800, "c3.localhost"))
- .add_answer(new DNSCnameRR("c3.localhost", 604800, "c4.localhost"))
- .add_answer(new DNSARR("c4.localhost", 604800, {8,8,8,8}))
- .add_auth(new DNSNsRR("localhost", 604800, "localhost"))
- .add_additional(new DNSARR("localhost", 604800, {127,0,0,1}))
- .add_additional(new DNSAaaaRR("localhost", 604800,
- {0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}));
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- std::vector<byte> data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ("8.8.8.8", AddressToString(&(info[0].ipaddr), 4));
- EXPECT_EQ(604800, info[0].ttl);
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, DISABLED_ParseAReplyVariantCnameLast) {
- DNSPacket pkt;
- pkt.set_qid(6366).set_rd().set_ra()
- .add_question(new DNSQuestion("query.example.com", ns_t_a))
- .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,221}))
- .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,222}))
- .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,223}))
- .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,224}))
- .add_answer(new DNSCnameRR("query.example.com", 60, "redirect.query.example.com"))
- .add_additional(new DNSTxtRR("query.example.com", 60, {"text record"}));
- struct hostent *host = nullptr;
- struct ares_addrttl info[8];
- int count = 8;
- std::vector<byte> data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(4, count);
- EXPECT_EQ("129.97.123.221", AddressToString(&(info[0].ipaddr), 4));
- EXPECT_EQ("129.97.123.222", AddressToString(&(info[1].ipaddr), 4));
- EXPECT_EQ("129.97.123.223", AddressToString(&(info[2].ipaddr), 4));
- EXPECT_EQ("129.97.123.224", AddressToString(&(info[3].ipaddr), 4));
- EXPECT_EQ(300, info[0].ttl);
- EXPECT_EQ(300, info[1].ttl);
- EXPECT_EQ(300, info[2].ttl);
- EXPECT_EQ(300, info[3].ttl);
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseAReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a))
- .add_answer(new DNSARR("example.com", 100, {0x02, 0x03, 0x04, 0x05}));
- std::vector<byte> data;
-
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.add_question(new DNSQuestion("example.com", ns_t_a));
-
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_a));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_a));
-
-#ifdef DISABLED
- // Not a response.
- pkt.set_response(false);
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.set_response(true);
-
- // Bad return code.
- pkt.set_rcode(ns_r_formerr);
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.set_rcode(ns_r_noerror);
-#endif
-
- // Two questions
- pkt.add_question(new DNSQuestion("example.com", ns_t_a));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_a));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.answers_.clear();
- pkt.add_answer(new DNSARR("example.com", 100, {0x02, 0x03, 0x04, 0x05}));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.add_answer(new DNSARR("example.com", 100, {0x02, 0x03, 0x04, 0x05}));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), len,
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), len,
- nullptr, info, &count));
- }
-}
-
-TEST_F(LibraryTest, ParseAReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_a))
- .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
- .add_answer(new DNSARR("c.example.com", 500, {0x02, 0x03, 0x04, 0x05}));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
-
- for (int ii = 1; ii <= 8; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count)) << ii;
- EXPECT_EQ(nullptr, host);
- }
-}
-
-} // namespace test
-} // namespace ares
+}
+
+TEST_F(LibraryTest, ParseAReplyVariantA) {
+ DNSPacket pkt;
+ pkt.set_qid(6366).set_rd().set_ra()
+ .add_question(new DNSQuestion("mit.edu", ns_t_a))
+ .add_answer(new DNSARR("mit.edu", 52, {18,7,22,69}))
+ .add_auth(new DNSNsRR("mit.edu", 292, "W20NS.mit.edu"))
+ .add_auth(new DNSNsRR("mit.edu", 292, "BITSY.mit.edu"))
+ .add_auth(new DNSNsRR("mit.edu", 292, "STRAWB.mit.edu"))
+ .add_additional(new DNSARR("STRAWB.mit.edu", 292, {18,71,0,151}));
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ std::vector<byte> data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ("18.7.22.69", AddressToString(&(info[0].ipaddr), 4));
+ EXPECT_EQ(52, info[0].ttl);
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseAReplyJustCname) {
+ DNSPacket pkt;
+ pkt.set_qid(6366).set_rd().set_ra()
+ .add_question(new DNSQuestion("mit.edu", ns_t_a))
+ .add_answer(new DNSCnameRR("mit.edu", 52, "other.mit.edu"));
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ std::vector<byte> data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(0, count);
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'other.mit.edu' aliases=[mit.edu] addrs=[]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseAReplyVariantCname) {
+ DNSPacket pkt;
+ pkt.set_qid(6366).set_rd().set_ra()
+ .add_question(new DNSQuestion("query.example.com", ns_t_a))
+ .add_answer(new DNSCnameRR("query.example.com", 200, "redirect.query.example.com"))
+ .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,22}))
+ .add_auth(new DNSNsRR("example.com", 218, "aa.ns1.example.com"))
+ .add_auth(new DNSNsRR("example.com", 218, "ns2.example.com"))
+ .add_auth(new DNSNsRR("example.com", 218, "ns3.example.com"))
+ .add_auth(new DNSNsRR("example.com", 218, "ns4.example.com"))
+ .add_additional(new DNSARR("aa.ns1.example.com", 218, {129,97,1,1}))
+ .add_additional(new DNSARR("ns2.example.com", 218, {129,97,1,2}))
+ .add_additional(new DNSARR("ns3.example.com", 218, {129,97,1,3}))
+ .add_additional(new DNSARR("ns4.example.com", 218, {129,97,1,4}));
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ std::vector<byte> data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ("129.97.123.22", AddressToString(&(info[0].ipaddr), 4));
+ // TTL is reduced to match CNAME's.
+ EXPECT_EQ(200, info[0].ttl);
+ ares_free_hostent(host);
+
+ // Repeat parsing without places to put the results.
+ count = 0;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ nullptr, info, &count));
+}
+
+TEST_F(LibraryTest, ParseAReplyVariantCnameChain) {
+ DNSPacket pkt;
+ pkt.set_qid(6366).set_rd().set_ra()
+ .add_question(new DNSQuestion("c1.localhost", ns_t_a))
+ .add_answer(new DNSCnameRR("c1.localhost", 604800, "c2.localhost"))
+ .add_answer(new DNSCnameRR("c2.localhost", 604800, "c3.localhost"))
+ .add_answer(new DNSCnameRR("c3.localhost", 604800, "c4.localhost"))
+ .add_answer(new DNSARR("c4.localhost", 604800, {8,8,8,8}))
+ .add_auth(new DNSNsRR("localhost", 604800, "localhost"))
+ .add_additional(new DNSARR("localhost", 604800, {127,0,0,1}))
+ .add_additional(new DNSAaaaRR("localhost", 604800,
+ {0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}));
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ std::vector<byte> data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ("8.8.8.8", AddressToString(&(info[0].ipaddr), 4));
+ EXPECT_EQ(604800, info[0].ttl);
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, DISABLED_ParseAReplyVariantCnameLast) {
+ DNSPacket pkt;
+ pkt.set_qid(6366).set_rd().set_ra()
+ .add_question(new DNSQuestion("query.example.com", ns_t_a))
+ .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,221}))
+ .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,222}))
+ .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,223}))
+ .add_answer(new DNSARR("redirect.query.example.com", 300, {129,97,123,224}))
+ .add_answer(new DNSCnameRR("query.example.com", 60, "redirect.query.example.com"))
+ .add_additional(new DNSTxtRR("query.example.com", 60, {"text record"}));
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[8];
+ int count = 8;
+ std::vector<byte> data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(4, count);
+ EXPECT_EQ("129.97.123.221", AddressToString(&(info[0].ipaddr), 4));
+ EXPECT_EQ("129.97.123.222", AddressToString(&(info[1].ipaddr), 4));
+ EXPECT_EQ("129.97.123.223", AddressToString(&(info[2].ipaddr), 4));
+ EXPECT_EQ("129.97.123.224", AddressToString(&(info[3].ipaddr), 4));
+ EXPECT_EQ(300, info[0].ttl);
+ EXPECT_EQ(300, info[1].ttl);
+ EXPECT_EQ(300, info[2].ttl);
+ EXPECT_EQ(300, info[3].ttl);
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseAReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a))
+ .add_answer(new DNSARR("example.com", 100, {0x02, 0x03, 0x04, 0x05}));
+ std::vector<byte> data;
+
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.add_question(new DNSQuestion("example.com", ns_t_a));
+
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_a));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_a));
+
+#ifdef DISABLED
+ // Not a response.
+ pkt.set_response(false);
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.set_response(true);
+
+ // Bad return code.
+ pkt.set_rcode(ns_r_formerr);
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.set_rcode(ns_r_noerror);
+#endif
+
+ // Two questions
+ pkt.add_question(new DNSQuestion("example.com", ns_t_a));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_a));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSARR("example.com", 100, {0x02, 0x03, 0x04, 0x05}));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.add_answer(new DNSARR("example.com", 100, {0x02, 0x03, 0x04, 0x05}));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), len,
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_a_reply(data.data(), len,
+ nullptr, info, &count));
+ }
+}
+
+TEST_F(LibraryTest, ParseAReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_a))
+ .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
+ .add_answer(new DNSARR("c.example.com", 500, {0x02, 0x03, 0x04, 0x05}));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+
+ for (int ii = 1; ii <= 8; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count)) << ii;
+ EXPECT_EQ(nullptr, host);
+ }
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-aaaa.cc b/contrib/libs/c-ares/test/ares-test-parse-aaaa.cc
index 1314c837a6..9a12378387 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-aaaa.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-aaaa.cc
@@ -1,192 +1,192 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseAaaaReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSAaaaRR("example.com", 100,
- {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseAaaaReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSAaaaRR("example.com", 100,
+ {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}))
.add_answer(new DNSARR("example.com", 0x01020304, {2,3,4,5}));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
- struct ares_addr6ttl info[5];
- int count = 5;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ(100, info[0].ttl);
- EXPECT_EQ(0x01, info[0].ip6addr._S6_un._S6_u8[0]);
- EXPECT_EQ(0x02, info[0].ip6addr._S6_un._S6_u8[4]);
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'example.com' aliases=[] addrs=[0101:0101:0202:0202:0303:0303:0404:0404]}", ss.str());
- ares_free_hostent(host);
-
- // Repeat without providing places to put the results
- count = 0;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
- nullptr, info, &count));
-}
-
-TEST_F(LibraryTest, ParseAaaaReplyCname) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSCnameRR("example.com", 50, "c.example.com"))
- .add_answer(new DNSAaaaRR("c.example.com", 100,
- {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
- struct ares_addr6ttl info[5];
- int count = 5;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- // CNAME TTL overrides AAAA TTL.
- EXPECT_EQ(50, info[0].ttl);
- EXPECT_EQ(0x01, info[0].ip6addr._S6_un._S6_u8[0]);
- EXPECT_EQ(0x02, info[0].ip6addr._S6_un._S6_u8[4]);
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'c.example.com' aliases=[example.com] addrs=[0101:0101:0202:0202:0303:0303:0404:0404]}", ss.str());
- ares_free_hostent(host);
-
- // Repeat without providing a hostent
- count = 5;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
- nullptr, info, &count));
- EXPECT_EQ(1, count);
- EXPECT_EQ(50, info[0].ttl);
- EXPECT_EQ(0x01, info[0].ip6addr._S6_un._S6_u8[0]);
- EXPECT_EQ(0x02, info[0].ip6addr._S6_un._S6_u8[4]);
-}
-
-TEST_F(LibraryTest, ParseAaaaReplyNoData) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
- struct ares_addr6ttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(0, count);
- EXPECT_EQ(nullptr, host);
-
- // Again but with a CNAME.
- pkt.add_answer(new DNSCnameRR("example.com", 200, "c.example.com"));
- EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(0, count);
- EXPECT_EQ(nullptr, host);
-}
-
-TEST_F(LibraryTest, ParseAaaaReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSAaaaRR("example.com", 100,
- {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
- std::vector<byte> data;
-
- struct hostent *host = nullptr;
- struct ares_addr6ttl info[2];
- int count = 2;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
-
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_aaaa));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
-
- // Two questions.
- pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.answers_.clear();
- pkt.add_answer(new DNSAaaaRR("example.com", 100,
- {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- pkt.add_answer(new DNSAaaaRR("example.com", 100,
- {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), len,
- &host, info, &count));
- EXPECT_EQ(nullptr, host);
- EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), len,
- nullptr, info, &count));
- }
-}
-
-TEST_F(LibraryTest, ParseAaaaReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_aaaa))
- .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
- .add_answer(new DNSAaaaRR("c.example.com", 100,
- {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
- struct ares_addr6ttl info[2];
- int count = 2;
-
- for (int ii = 1; ii <= 8; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_aaaa_reply(data.data(), data.size(),
- &host, info, &count)) << ii;
- EXPECT_EQ(nullptr, host);
- }
-}
-
-} // namespace test
-} // namespace ares
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+ struct ares_addr6ttl info[5];
+ int count = 5;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ(100, info[0].ttl);
+ EXPECT_EQ(0x01, info[0].ip6addr._S6_un._S6_u8[0]);
+ EXPECT_EQ(0x02, info[0].ip6addr._S6_un._S6_u8[4]);
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'example.com' aliases=[] addrs=[0101:0101:0202:0202:0303:0303:0404:0404]}", ss.str());
+ ares_free_hostent(host);
+
+ // Repeat without providing places to put the results
+ count = 0;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
+ nullptr, info, &count));
+}
+
+TEST_F(LibraryTest, ParseAaaaReplyCname) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSCnameRR("example.com", 50, "c.example.com"))
+ .add_answer(new DNSAaaaRR("c.example.com", 100,
+ {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+ struct ares_addr6ttl info[5];
+ int count = 5;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ // CNAME TTL overrides AAAA TTL.
+ EXPECT_EQ(50, info[0].ttl);
+ EXPECT_EQ(0x01, info[0].ip6addr._S6_un._S6_u8[0]);
+ EXPECT_EQ(0x02, info[0].ip6addr._S6_un._S6_u8[4]);
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'c.example.com' aliases=[example.com] addrs=[0101:0101:0202:0202:0303:0303:0404:0404]}", ss.str());
+ ares_free_hostent(host);
+
+ // Repeat without providing a hostent
+ count = 5;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_aaaa_reply(data.data(), data.size(),
+ nullptr, info, &count));
+ EXPECT_EQ(1, count);
+ EXPECT_EQ(50, info[0].ttl);
+ EXPECT_EQ(0x01, info[0].ip6addr._S6_un._S6_u8[0]);
+ EXPECT_EQ(0x02, info[0].ip6addr._S6_un._S6_u8[4]);
+}
+
+TEST_F(LibraryTest, ParseAaaaReplyNoData) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+ struct ares_addr6ttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(0, count);
+ EXPECT_EQ(nullptr, host);
+
+ // Again but with a CNAME.
+ pkt.add_answer(new DNSCnameRR("example.com", 200, "c.example.com"));
+ EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(0, count);
+ EXPECT_EQ(nullptr, host);
+}
+
+TEST_F(LibraryTest, ParseAaaaReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSAaaaRR("example.com", 100,
+ {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
+ std::vector<byte> data;
+
+ struct hostent *host = nullptr;
+ struct ares_addr6ttl info[2];
+ int count = 2;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
+
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_aaaa));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
+
+ // Two questions.
+ pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_aaaa));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSAaaaRR("example.com", 100,
+ {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ pkt.add_answer(new DNSAaaaRR("example.com", 100,
+ {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), len,
+ &host, info, &count));
+ EXPECT_EQ(nullptr, host);
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_aaaa_reply(data.data(), len,
+ nullptr, info, &count));
+ }
+}
+
+TEST_F(LibraryTest, ParseAaaaReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_aaaa))
+ .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
+ .add_answer(new DNSAaaaRR("c.example.com", 100,
+ {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04}));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+ struct ares_addr6ttl info[2];
+ int count = 2;
+
+ for (int ii = 1; ii <= 8; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_aaaa_reply(data.data(), data.size(),
+ &host, info, &count)) << ii;
+ EXPECT_EQ(nullptr, host);
+ }
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-mx.cc b/contrib/libs/c-ares/test/ares-test-parse-mx.cc
index 37324a6d4c..56ce266f6d 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-mx.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-mx.cc
@@ -1,141 +1,141 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseMxReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"))
- .add_answer(new DNSMxRR("example.com", 100, 200, "mx2.example.com"));
- std::vector<byte> data = pkt.data();
-
- struct ares_mx_reply* mx = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_mx_reply(data.data(), data.size(), &mx));
- ASSERT_NE(nullptr, mx);
- EXPECT_EQ("mx1.example.com", std::string(mx->host));
- EXPECT_EQ(100, mx->priority);
-
- struct ares_mx_reply* mx2 = mx->next;
- ASSERT_NE(nullptr, mx2);
- EXPECT_EQ("mx2.example.com", std::string(mx2->host));
- EXPECT_EQ(200, mx2->priority);
- EXPECT_EQ(nullptr, mx2->next);
-
- ares_free_data(mx);
-}
-
-TEST_F(LibraryTest, ParseMxReplyMalformed) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x0F, // type MX
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x0F, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x01, // rdata length -- too short
- 0x02,
- };
-
- struct ares_mx_reply* mx = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
- ASSERT_EQ(nullptr, mx);
-}
-
-
-TEST_F(LibraryTest, ParseMxReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- std::vector<byte> data;
- struct ares_mx_reply* mx = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
- EXPECT_EQ(nullptr, mx);
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
-
-#ifdef DISABLED
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_mx));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
-#endif
-
- // Two questions.
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
- EXPECT_EQ(nullptr, mx);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
-
- // Wrong sort of answer.
- // TODO(drysdale): check if this should be ARES_ENODATA?
- pkt.answers_.clear();
- pkt.add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_mx_reply(data.data(), data.size(), &mx));
- EXPECT_EQ(nullptr, mx);
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_mx_reply(data.data(), data.size(), &mx));
- EXPECT_EQ(nullptr, mx);
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- int rc = ares_parse_mx_reply(data.data(), len, &mx);
- EXPECT_EQ(nullptr, mx);
- EXPECT_TRUE(rc == ARES_EBADRESP || rc == ARES_EBADNAME);
- }
-}
-
-TEST_F(LibraryTest, ParseMxReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
- .add_answer(new DNSMxRR("c.example.com", 100, 100, "mx1.example.com"));
- std::vector<byte> data = pkt.data();
- struct ares_mx_reply* mx = nullptr;
-
- for (int ii = 1; ii <= 5; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_mx_reply(data.data(), data.size(), &mx)) << ii;
- }
-}
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseMxReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"))
+ .add_answer(new DNSMxRR("example.com", 100, 200, "mx2.example.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_mx_reply* mx = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ ASSERT_NE(nullptr, mx);
+ EXPECT_EQ("mx1.example.com", std::string(mx->host));
+ EXPECT_EQ(100, mx->priority);
+
+ struct ares_mx_reply* mx2 = mx->next;
+ ASSERT_NE(nullptr, mx2);
+ EXPECT_EQ("mx2.example.com", std::string(mx2->host));
+ EXPECT_EQ(200, mx2->priority);
+ EXPECT_EQ(nullptr, mx2->next);
+
+ ares_free_data(mx);
+}
+
+TEST_F(LibraryTest, ParseMxReplyMalformed) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x0F, // type MX
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x0F, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x01, // rdata length -- too short
+ 0x02,
+ };
+
+ struct ares_mx_reply* mx = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ ASSERT_EQ(nullptr, mx);
+}
+
+
+TEST_F(LibraryTest, ParseMxReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ std::vector<byte> data;
+ struct ares_mx_reply* mx = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ EXPECT_EQ(nullptr, mx);
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+
+#ifdef DISABLED
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_mx));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+#endif
+
+ // Two questions.
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ EXPECT_EQ(nullptr, mx);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+
+ // Wrong sort of answer.
+ // TODO(drysdale): check if this should be ARES_ENODATA?
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ EXPECT_EQ(nullptr, mx);
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_mx_reply(data.data(), data.size(), &mx));
+ EXPECT_EQ(nullptr, mx);
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ int rc = ares_parse_mx_reply(data.data(), len, &mx);
+ EXPECT_EQ(nullptr, mx);
+ EXPECT_TRUE(rc == ARES_EBADRESP || rc == ARES_EBADNAME);
+ }
+}
+
+TEST_F(LibraryTest, ParseMxReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
+ .add_answer(new DNSMxRR("c.example.com", 100, 100, "mx1.example.com"));
+ std::vector<byte> data = pkt.data();
+ struct ares_mx_reply* mx = nullptr;
+
+ for (int ii = 1; ii <= 5; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_mx_reply(data.data(), data.size(), &mx)) << ii;
+ }
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-naptr.cc b/contrib/libs/c-ares/test/ares-test-parse-naptr.cc
index 3238a1923d..109c2a2604 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-naptr.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-naptr.cc
@@ -1,148 +1,148 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseNaptrReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_naptr))
- .add_answer(new DNSNaptrRR("example.com", 100,
- 10, 20, "SP", "service", "regexp", "replace"))
- .add_answer(new DNSNaptrRR("example.com", 0x0010,
- 11, 21, "SP", "service2", "regexp2", "replace2"));
- std::vector<byte> data = pkt.data();
-
- struct ares_naptr_reply* naptr = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- ASSERT_NE(nullptr, naptr);
- EXPECT_EQ("SP", std::string((char*)naptr->flags));
- EXPECT_EQ("service", std::string((char*)naptr->service));
- EXPECT_EQ("regexp", std::string((char*)naptr->regexp));
- EXPECT_EQ("replace", std::string((char*)naptr->replacement));
- EXPECT_EQ(10, naptr->order);
- EXPECT_EQ(20, naptr->preference);
-
- struct ares_naptr_reply* naptr2 = naptr->next;
- ASSERT_NE(nullptr, naptr2);
- EXPECT_EQ("SP", std::string((char*)naptr2->flags));
- EXPECT_EQ("service2", std::string((char*)naptr2->service));
- EXPECT_EQ("regexp2", std::string((char*)naptr2->regexp));
- EXPECT_EQ("replace2", std::string((char*)naptr2->replacement));
- EXPECT_EQ(11, naptr2->order);
- EXPECT_EQ(21, naptr2->preference);
- EXPECT_EQ(nullptr, naptr2->next);
-
- ares_free_data(naptr);
-}
-
-TEST_F(LibraryTest, ParseNaptrReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_naptr))
- .add_answer(new DNSNaptrRR("example.com", 100,
- 10, 20, "SP", "service", "regexp", "replace"));
- std::vector<byte> data;
- struct ares_naptr_reply* naptr = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
-
-#ifdef DISABLED
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_naptr));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
-#endif
-
- // Two questions
- pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- EXPECT_EQ(nullptr, naptr);
- pkt.answers_.clear();
- pkt.add_answer(new DNSNaptrRR("example.com", 100,
- 10, 20, "SP", "service", "regexp", "replace"));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- pkt.add_answer(new DNSNaptrRR("example.com", 100,
- 10, 20, "SP", "service", "regexp", "replace"));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- int rc = ares_parse_naptr_reply(data.data(), len, &naptr);
- EXPECT_TRUE(rc == ARES_EBADRESP || rc == ARES_EBADNAME);
- }
-}
-
-TEST_F(LibraryTest, ParseNaptrReplyTooShort) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x23, // type NAPTR
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x23, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x01, // rdata length
- 0x00, // Too short: expect 2 x int16 and 3 x name (min 1 byte each)
- };
- struct ares_naptr_reply* naptr = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
-}
-
-TEST_F(LibraryTest, ParseNaptrReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_naptr))
- .add_answer(new DNSNaptrRR("example.com", 100,
- 10, 20, "SP", "service", "regexp", "replace"))
- .add_answer(new DNSNaptrRR("example.com", 0x0010,
- 11, 21, "SP", "service2", "regexp2", "replace2"));
- std::vector<byte> data = pkt.data();
- struct ares_naptr_reply* naptr = nullptr;
-
- for (int ii = 1; ii <= 13; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
- }
-}
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseNaptrReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_naptr))
+ .add_answer(new DNSNaptrRR("example.com", 100,
+ 10, 20, "SP", "service", "regexp", "replace"))
+ .add_answer(new DNSNaptrRR("example.com", 0x0010,
+ 11, 21, "SP", "service2", "regexp2", "replace2"));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_naptr_reply* naptr = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ ASSERT_NE(nullptr, naptr);
+ EXPECT_EQ("SP", std::string((char*)naptr->flags));
+ EXPECT_EQ("service", std::string((char*)naptr->service));
+ EXPECT_EQ("regexp", std::string((char*)naptr->regexp));
+ EXPECT_EQ("replace", std::string((char*)naptr->replacement));
+ EXPECT_EQ(10, naptr->order);
+ EXPECT_EQ(20, naptr->preference);
+
+ struct ares_naptr_reply* naptr2 = naptr->next;
+ ASSERT_NE(nullptr, naptr2);
+ EXPECT_EQ("SP", std::string((char*)naptr2->flags));
+ EXPECT_EQ("service2", std::string((char*)naptr2->service));
+ EXPECT_EQ("regexp2", std::string((char*)naptr2->regexp));
+ EXPECT_EQ("replace2", std::string((char*)naptr2->replacement));
+ EXPECT_EQ(11, naptr2->order);
+ EXPECT_EQ(21, naptr2->preference);
+ EXPECT_EQ(nullptr, naptr2->next);
+
+ ares_free_data(naptr);
+}
+
+TEST_F(LibraryTest, ParseNaptrReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_naptr))
+ .add_answer(new DNSNaptrRR("example.com", 100,
+ 10, 20, "SP", "service", "regexp", "replace"));
+ std::vector<byte> data;
+ struct ares_naptr_reply* naptr = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
+
+#ifdef DISABLED
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_naptr));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
+#endif
+
+ // Two questions
+ pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_naptr));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ EXPECT_EQ(nullptr, naptr);
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSNaptrRR("example.com", 100,
+ 10, 20, "SP", "service", "regexp", "replace"));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ pkt.add_answer(new DNSNaptrRR("example.com", 100,
+ 10, 20, "SP", "service", "regexp", "replace"));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ int rc = ares_parse_naptr_reply(data.data(), len, &naptr);
+ EXPECT_TRUE(rc == ARES_EBADRESP || rc == ARES_EBADNAME);
+ }
+}
+
+TEST_F(LibraryTest, ParseNaptrReplyTooShort) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x23, // type NAPTR
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x23, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x01, // rdata length
+ 0x00, // Too short: expect 2 x int16 and 3 x name (min 1 byte each)
+ };
+ struct ares_naptr_reply* naptr = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+}
+
+TEST_F(LibraryTest, ParseNaptrReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_naptr))
+ .add_answer(new DNSNaptrRR("example.com", 100,
+ 10, 20, "SP", "service", "regexp", "replace"))
+ .add_answer(new DNSNaptrRR("example.com", 0x0010,
+ 11, 21, "SP", "service2", "regexp2", "replace2"));
+ std::vector<byte> data = pkt.data();
+ struct ares_naptr_reply* naptr = nullptr;
+
+ for (int ii = 1; ii <= 13; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_naptr_reply(data.data(), data.size(), &naptr));
+ }
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-ns.cc b/contrib/libs/c-ares/test/ares-test-parse-ns.cc
index cd65318969..55d031857f 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-ns.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-ns.cc
@@ -1,119 +1,119 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseNsReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_ns))
- .add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_ns_reply(data.data(), data.size(), &host));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'example.com' aliases=[ns.example.com] addrs=[]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseNsReplyMultiple) {
- DNSPacket pkt;
- pkt.set_qid(10501).set_response().set_rd().set_ra()
- .add_question(new DNSQuestion("google.com", ns_t_ns))
- .add_answer(new DNSNsRR("google.com", 59, "ns1.google.com"))
- .add_answer(new DNSNsRR("google.com", 59, "ns2.google.com"))
- .add_answer(new DNSNsRR("google.com", 59, "ns3.google.com"))
- .add_answer(new DNSNsRR("google.com", 59, "ns4.google.com"))
- .add_additional(new DNSARR("ns4.google.com", 247, {216,239,38,10}))
- .add_additional(new DNSARR("ns2.google.com", 247, {216,239,34,10}))
- .add_additional(new DNSARR("ns1.google.com", 247, {216,239,32,10}))
- .add_additional(new DNSARR("ns3.google.com", 247, {216,239,36,10}));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_ns_reply(data.data(), data.size(), &host));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'google.com' aliases=[ns1.google.com, ns2.google.com, ns3.google.com, ns4.google.com] addrs=[]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseNsReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_ns))
- .add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
- std::vector<byte> data;
- struct hostent *host = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ns_reply(data.data(), data.size(), &host));
- pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
-
-#ifdef DISABLED
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_ns));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_ns_reply(data.data(), data.size(), &host));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
-#endif
-
- // Two questions.
- pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ns_reply(data.data(), data.size(), &host));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_ns_reply(data.data(), data.size(), &host));
- pkt.answers_.clear();
- pkt.add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_ns_reply(data.data(), data.size(), &host));
- pkt.add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ns_reply(data.data(), len, &host));
- }
-}
-
-TEST_F(LibraryTest, ParseNsReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_ns))
- .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
- .add_answer(new DNSNsRR("c.example.com", 100, "ns.example.com"));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
-
- for (int ii = 1; ii <= 8; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_ns_reply(data.data(), data.size(), &host)) << ii;
- }
-}
-
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseNsReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_ns))
+ .add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_ns_reply(data.data(), data.size(), &host));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'example.com' aliases=[ns.example.com] addrs=[]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseNsReplyMultiple) {
+ DNSPacket pkt;
+ pkt.set_qid(10501).set_response().set_rd().set_ra()
+ .add_question(new DNSQuestion("google.com", ns_t_ns))
+ .add_answer(new DNSNsRR("google.com", 59, "ns1.google.com"))
+ .add_answer(new DNSNsRR("google.com", 59, "ns2.google.com"))
+ .add_answer(new DNSNsRR("google.com", 59, "ns3.google.com"))
+ .add_answer(new DNSNsRR("google.com", 59, "ns4.google.com"))
+ .add_additional(new DNSARR("ns4.google.com", 247, {216,239,38,10}))
+ .add_additional(new DNSARR("ns2.google.com", 247, {216,239,34,10}))
+ .add_additional(new DNSARR("ns1.google.com", 247, {216,239,32,10}))
+ .add_additional(new DNSARR("ns3.google.com", 247, {216,239,36,10}));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_ns_reply(data.data(), data.size(), &host));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'google.com' aliases=[ns1.google.com, ns2.google.com, ns3.google.com, ns4.google.com] addrs=[]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseNsReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_ns))
+ .add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
+ std::vector<byte> data;
+ struct hostent *host = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ns_reply(data.data(), data.size(), &host));
+ pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
+
+#ifdef DISABLED
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_ns));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_ns_reply(data.data(), data.size(), &host));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
+#endif
+
+ // Two questions.
+ pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ns_reply(data.data(), data.size(), &host));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_ns));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_ns_reply(data.data(), data.size(), &host));
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_ns_reply(data.data(), data.size(), &host));
+ pkt.add_answer(new DNSNsRR("example.com", 100, "ns.example.com"));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ns_reply(data.data(), len, &host));
+ }
+}
+
+TEST_F(LibraryTest, ParseNsReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_ns))
+ .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
+ .add_answer(new DNSNsRR("c.example.com", 100, "ns.example.com"));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+
+ for (int ii = 1; ii <= 8; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_ns_reply(data.data(), data.size(), &host)) << ii;
+ }
+}
+
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-ptr.cc b/contrib/libs/c-ares/test/ares-test-parse-ptr.cc
index 75f74c16f7..7b1a86bac0 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-ptr.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-ptr.cc
@@ -1,249 +1,249 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParsePtrReplyOK) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'other.com' aliases=[other.com] addrs=[16.32.48.64]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParsePtrReplyCname) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSCnameRR("64.48.32.16.in-addr.arpa", 50, "64.48.32.8.in-addr.arpa"))
- .add_answer(new DNSPtrRR("64.48.32.8.in-addr.arpa", 100, "other.com"));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'other.com' aliases=[other.com] addrs=[16.32.48.64]}", ss.str());
- ares_free_hostent(host);
-}
-
-
-struct DNSMalformedCnameRR : public DNSCnameRR {
- DNSMalformedCnameRR(const std::string& name, int ttl, const std::string& other)
- : DNSCnameRR(name, ttl, other) {}
- std::vector<byte> data() const {
- std::vector<byte> data = DNSRR::data();
- std::vector<byte> encname = EncodeString(other_);
- encname[0] = encname[0] + 63; // invalid label length
- int len = encname.size();
- PushInt16(&data, len);
- data.insert(data.end(), encname.begin(), encname.end());
- return data;
- }
-};
-
-TEST_F(LibraryTest, ParsePtrReplyMalformedCname) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSMalformedCnameRR("64.48.32.16.in-addr.arpa", 50, "64.48.32.8.in-addr.arpa"))
- .add_answer(new DNSPtrRR("64.48.32.8.in-addr.arpa", 100, "other.com"));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- ASSERT_EQ(nullptr, host);
-}
-
-TEST_F(LibraryTest, ParseManyPtrReply) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "main.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other1.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other2.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other3.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other4.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other5.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other6.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other7.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other8.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other9.com"));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- ASSERT_NE(nullptr, host);
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParsePtrReplyAdditional) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 55, "other.com"))
- .add_auth(new DNSNsRR("16.in-addr.arpa", 234, "ns1.other.com"))
- .add_auth(new DNSNsRR("16.in-addr.arpa", 234, "bb.ns2.other.com"))
- .add_auth(new DNSNsRR("16.in-addr.arpa", 234, "ns3.other.com"))
- .add_additional(new DNSARR("ns1.other.com", 229, {10,20,30,41}))
- .add_additional(new DNSARR("bb.ns2.other.com", 229, {10,20,30,42}))
- .add_additional(new DNSARR("ns3.other.com", 229, {10,20,30,43}));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'other.com' aliases=[other.com] addrs=[16.32.48.64]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParsePtrReplyErrors) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
- std::vector<byte> data;
- struct hostent *host = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
-
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("99.48.32.16.in-addr.arpa", ns_t_ptr));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- EXPECT_EQ(nullptr, host);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
-
- // Two questions.
- pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- EXPECT_EQ(nullptr, host);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- EXPECT_EQ(nullptr, host);
- pkt.answers_.clear();
- pkt.add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- EXPECT_EQ(nullptr, host);
- pkt.add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), len,
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- EXPECT_EQ(nullptr, host);
- }
-
- // Truncated packets with CNAME.
- pkt.add_answer(new DNSCnameRR("64.48.32.16.in-addr.arpa", 50, "64.48.32.8.in-addr.arpa"));
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), len,
- addrv4, sizeof(addrv4), AF_INET, &host, NULL));
- EXPECT_EQ(nullptr, host);
- }
-}
-
-TEST_F(LibraryTest, ParsePtrReplyAllocFailSome) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "main.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other1.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other2.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other3.com"));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
-
- for (int ii = 1; ii <= 18; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL)) << ii;
- }
-}
-
-TEST_F(LibraryTest, ParsePtrReplyAllocFailMany) {
- byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "main.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other1.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other2.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other3.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other4.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other5.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other6.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other7.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other8.com"))
- .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other9.com"));
- std::vector<byte> data = pkt.data();
- struct hostent *host = nullptr;
-
- for (int ii = 1; ii <= 63; ii++) {
- ClearFails();
- SetAllocFail(ii);
- int rc = ares_parse_ptr_reply(data.data(), data.size(),
- addrv4, sizeof(addrv4), AF_INET, &host, NULL);
- if (rc != ARES_ENOMEM) {
- EXPECT_EQ(ARES_SUCCESS, rc);
- ares_free_hostent(host);
- host = nullptr;
- }
- }
-}
-
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParsePtrReplyOK) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'other.com' aliases=[other.com] addrs=[16.32.48.64]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParsePtrReplyCname) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSCnameRR("64.48.32.16.in-addr.arpa", 50, "64.48.32.8.in-addr.arpa"))
+ .add_answer(new DNSPtrRR("64.48.32.8.in-addr.arpa", 100, "other.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'other.com' aliases=[other.com] addrs=[16.32.48.64]}", ss.str());
+ ares_free_hostent(host);
+}
+
+
+struct DNSMalformedCnameRR : public DNSCnameRR {
+ DNSMalformedCnameRR(const std::string& name, int ttl, const std::string& other)
+ : DNSCnameRR(name, ttl, other) {}
+ std::vector<byte> data() const {
+ std::vector<byte> data = DNSRR::data();
+ std::vector<byte> encname = EncodeString(other_);
+ encname[0] = encname[0] + 63; // invalid label length
+ int len = encname.size();
+ PushInt16(&data, len);
+ data.insert(data.end(), encname.begin(), encname.end());
+ return data;
+ }
+};
+
+TEST_F(LibraryTest, ParsePtrReplyMalformedCname) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSMalformedCnameRR("64.48.32.16.in-addr.arpa", 50, "64.48.32.8.in-addr.arpa"))
+ .add_answer(new DNSPtrRR("64.48.32.8.in-addr.arpa", 100, "other.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ ASSERT_EQ(nullptr, host);
+}
+
+TEST_F(LibraryTest, ParseManyPtrReply) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "main.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other1.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other2.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other3.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other4.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other5.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other6.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other7.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other8.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other9.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ ASSERT_NE(nullptr, host);
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParsePtrReplyAdditional) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 55, "other.com"))
+ .add_auth(new DNSNsRR("16.in-addr.arpa", 234, "ns1.other.com"))
+ .add_auth(new DNSNsRR("16.in-addr.arpa", 234, "bb.ns2.other.com"))
+ .add_auth(new DNSNsRR("16.in-addr.arpa", 234, "ns3.other.com"))
+ .add_additional(new DNSARR("ns1.other.com", 229, {10,20,30,41}))
+ .add_additional(new DNSARR("bb.ns2.other.com", 229, {10,20,30,42}))
+ .add_additional(new DNSARR("ns3.other.com", 229, {10,20,30,43}));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'other.com' aliases=[other.com] addrs=[16.32.48.64]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParsePtrReplyErrors) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
+ std::vector<byte> data;
+ struct hostent *host = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
+
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("99.48.32.16.in-addr.arpa", ns_t_ptr));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ EXPECT_EQ(nullptr, host);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
+
+ // Two questions.
+ pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ EXPECT_EQ(nullptr, host);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ EXPECT_EQ(nullptr, host);
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ EXPECT_EQ(nullptr, host);
+ pkt.add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other.com"));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), len,
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ EXPECT_EQ(nullptr, host);
+ }
+
+ // Truncated packets with CNAME.
+ pkt.add_answer(new DNSCnameRR("64.48.32.16.in-addr.arpa", 50, "64.48.32.8.in-addr.arpa"));
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_ptr_reply(data.data(), len,
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL));
+ EXPECT_EQ(nullptr, host);
+ }
+}
+
+TEST_F(LibraryTest, ParsePtrReplyAllocFailSome) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "main.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other1.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other2.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other3.com"));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+
+ for (int ii = 1; ii <= 18; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL)) << ii;
+ }
+}
+
+TEST_F(LibraryTest, ParsePtrReplyAllocFailMany) {
+ byte addrv4[4] = {0x10, 0x20, 0x30, 0x40};
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "main.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other1.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other2.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other3.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other4.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other5.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other6.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other7.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other8.com"))
+ .add_answer(new DNSPtrRR("64.48.32.16.in-addr.arpa", 100, "other9.com"));
+ std::vector<byte> data = pkt.data();
+ struct hostent *host = nullptr;
+
+ for (int ii = 1; ii <= 63; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ int rc = ares_parse_ptr_reply(data.data(), data.size(),
+ addrv4, sizeof(addrv4), AF_INET, &host, NULL);
+ if (rc != ARES_ENOMEM) {
+ EXPECT_EQ(ARES_SUCCESS, rc);
+ ares_free_hostent(host);
+ host = nullptr;
+ }
+ }
+}
+
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-soa.cc b/contrib/libs/c-ares/test/ares-test-parse-soa.cc
index c0ffaaed50..e6f5dcdab7 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-soa.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-soa.cc
@@ -1,108 +1,108 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseSoaReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_soa))
- .add_answer(new DNSSoaRR("example.com", 100,
- "soa1.example.com", "fred.example.com",
- 1, 2, 3, 4, 5));
- std::vector<byte> data = pkt.data();
-
- struct ares_soa_reply* soa = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_soa_reply(data.data(), data.size(), &soa));
- ASSERT_NE(nullptr, soa);
- EXPECT_EQ("soa1.example.com", std::string(soa->nsname));
- EXPECT_EQ("fred.example.com", std::string(soa->hostmaster));
- EXPECT_EQ(1, soa->serial);
- EXPECT_EQ(2, soa->refresh);
- EXPECT_EQ(3, soa->retry);
- EXPECT_EQ(4, soa->expire);
- EXPECT_EQ(5, soa->minttl);
- ares_free_data(soa);
-}
-
-TEST_F(LibraryTest, ParseSoaReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_soa))
- .add_answer(new DNSSoaRR("example.com", 100,
- "soa1.example.com", "fred.example.com",
- 1, 2, 3, 4, 5));
- std::vector<byte> data;
- struct ares_soa_reply* soa = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseSoaReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_soa))
+ .add_answer(new DNSSoaRR("example.com", 100,
+ "soa1.example.com", "fred.example.com",
+ 1, 2, 3, 4, 5));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_soa_reply* soa = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_soa_reply(data.data(), data.size(), &soa));
+ ASSERT_NE(nullptr, soa);
+ EXPECT_EQ("soa1.example.com", std::string(soa->nsname));
+ EXPECT_EQ("fred.example.com", std::string(soa->hostmaster));
+ EXPECT_EQ(1, soa->serial);
+ EXPECT_EQ(2, soa->refresh);
+ EXPECT_EQ(3, soa->retry);
+ EXPECT_EQ(4, soa->expire);
+ EXPECT_EQ(5, soa->minttl);
+ ares_free_data(soa);
+}
+
+TEST_F(LibraryTest, ParseSoaReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_soa))
+ .add_answer(new DNSSoaRR("example.com", 100,
+ "soa1.example.com", "fred.example.com",
+ 1, 2, 3, 4, 5));
+ std::vector<byte> data;
+ struct ares_soa_reply* soa = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
+ pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
+
+#ifdef DISABLED
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_soa));
+ data = pkt.data();
EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
- pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
-
-#ifdef DISABLED
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_soa));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
-#endif
-
- // Two questions
- pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
- pkt.answers_.clear();
- pkt.add_answer(new DNSSoaRR("example.com", 100,
- "soa1.example.com", "fred.example.com",
- 1, 2, 3, 4, 5));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
- pkt.add_answer(new DNSSoaRR("example.com", 100,
- "soa1.example.com", "fred.example.com",
- 1, 2, 3, 4, 5));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), len, &soa));
- }
-}
-
-TEST_F(LibraryTest, ParseSoaReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_soa))
- .add_answer(new DNSSoaRR("example.com", 100,
- "soa1.example.com", "fred.example.com",
- 1, 2, 3, 4, 5));
- std::vector<byte> data = pkt.data();
- struct ares_soa_reply* soa = nullptr;
-
- for (int ii = 1; ii <= 5; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_soa_reply(data.data(), data.size(), &soa)) << ii;
- }
-}
-
-} // namespace test
-} // namespace ares
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
+#endif
+
+ // Two questions
+ pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_soa));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSSoaRR("example.com", 100,
+ "soa1.example.com", "fred.example.com",
+ 1, 2, 3, 4, 5));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), data.size(), &soa));
+ pkt.add_answer(new DNSSoaRR("example.com", 100,
+ "soa1.example.com", "fred.example.com",
+ 1, 2, 3, 4, 5));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_soa_reply(data.data(), len, &soa));
+ }
+}
+
+TEST_F(LibraryTest, ParseSoaReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_soa))
+ .add_answer(new DNSSoaRR("example.com", 100,
+ "soa1.example.com", "fred.example.com",
+ 1, 2, 3, 4, 5));
+ std::vector<byte> data = pkt.data();
+ struct ares_soa_reply* soa = nullptr;
+
+ for (int ii = 1; ii <= 5; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_soa_reply(data.data(), data.size(), &soa)) << ii;
+ }
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-srv.cc b/contrib/libs/c-ares/test/ares-test-parse-srv.cc
index cc651d6d4e..d3e3183d03 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-srv.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-srv.cc
@@ -1,288 +1,288 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseSrvReplyOK) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_srv))
- .add_answer(new DNSSrvRR("example.com", 100, 10, 20, 30, "srv.example.com"))
- .add_answer(new DNSSrvRR("example.com", 100, 11, 21, 31, "srv2.example.com"));
- std::vector<byte> data = pkt.data();
-
- struct ares_srv_reply* srv = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
- ASSERT_NE(nullptr, srv);
-
- EXPECT_EQ("srv.example.com", std::string(srv->host));
- EXPECT_EQ(10, srv->priority);
- EXPECT_EQ(20, srv->weight);
- EXPECT_EQ(30, srv->port);
-
- struct ares_srv_reply* srv2 = srv->next;
- ASSERT_NE(nullptr, srv2);
- EXPECT_EQ("srv2.example.com", std::string(srv2->host));
- EXPECT_EQ(11, srv2->priority);
- EXPECT_EQ(21, srv2->weight);
- EXPECT_EQ(31, srv2->port);
- EXPECT_EQ(nullptr, srv2->next);
-
- ares_free_data(srv);
-}
-
-TEST_F(LibraryTest, ParseSrvReplySingle) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
- .add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else1.where.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else2.where.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else3.where.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else4.where.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else5.where.com"))
- .add_additional(new DNSARR("else2.where.com", 42, {172,19,0,1}))
- .add_additional(new DNSARR("else5.where.com", 42, {172,19,0,2}));
- std::vector<byte> data = pkt.data();
-
- struct ares_srv_reply* srv = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
- ASSERT_NE(nullptr, srv);
-
- EXPECT_EQ("example.abc.def.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(10, srv->weight);
- EXPECT_EQ(8160, srv->port);
- EXPECT_EQ(nullptr, srv->next);
-
- ares_free_data(srv);
-}
-
-TEST_F(LibraryTest, ParseSrvReplyMalformed) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x21, // type SRV
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x21, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length -- too short
- 0x02, 0x03, 0x04, 0x05,
- };
-
- struct ares_srv_reply* srv = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_srv_reply(data.data(), data.size(), &srv));
- ASSERT_EQ(nullptr, srv);
-}
-
-TEST_F(LibraryTest, ParseSrvReplyMultiple) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_ra().set_rd()
- .add_question(new DNSQuestion("srv.example.com", ns_t_srv))
- .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 6789, "a1.srv.example.com"))
- .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 4567, "a2.srv.example.com"))
- .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 5678, "a3.srv.example.com"))
- .add_auth(new DNSNsRR("example.com", 300, "ns1.example.com"))
- .add_auth(new DNSNsRR("example.com", 300, "ns2.example.com"))
- .add_auth(new DNSNsRR("example.com", 300, "ns3.example.com"))
- .add_additional(new DNSARR("a1.srv.example.com", 300, {172,19,1,1}))
- .add_additional(new DNSARR("a2.srv.example.com", 300, {172,19,1,2}))
- .add_additional(new DNSARR("a3.srv.example.com", 300, {172,19,1,3}))
- .add_additional(new DNSARR("n1.example.com", 300, {172,19,0,1}))
- .add_additional(new DNSARR("n2.example.com", 300, {172,19,0,2}))
- .add_additional(new DNSARR("n3.example.com", 300, {172,19,0,3}));
- std::vector<byte> data = pkt.data();
-
- struct ares_srv_reply* srv0 = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv0));
- ASSERT_NE(nullptr, srv0);
- struct ares_srv_reply* srv = srv0;
-
- EXPECT_EQ("a1.srv.example.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(5, srv->weight);
- EXPECT_EQ(6789, srv->port);
- EXPECT_NE(nullptr, srv->next);
- srv = srv->next;
-
- EXPECT_EQ("a2.srv.example.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(5, srv->weight);
- EXPECT_EQ(4567, srv->port);
- EXPECT_NE(nullptr, srv->next);
- srv = srv->next;
-
- EXPECT_EQ("a3.srv.example.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(5, srv->weight);
- EXPECT_EQ(5678, srv->port);
- EXPECT_EQ(nullptr, srv->next);
-
- ares_free_data(srv0);
-}
-
-TEST_F(LibraryTest, ParseSrvReplyCname) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
- .add_answer(new DNSCnameRR("example.abc.def.com", 300, "cname.abc.def.com"))
- .add_answer(new DNSSrvRR("cname.abc.def.com", 300, 0, 10, 1234, "srv.abc.def.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else1.where.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else2.where.com"))
- .add_auth(new DNSNsRR("abc.def.com", 44, "else3.where.com"))
- .add_additional(new DNSARR("example.abc.def.com", 300, {172,19,0,1}))
- .add_additional(new DNSARR("else1.where.com", 42, {172,19,0,1}))
- .add_additional(new DNSARR("else2.where.com", 42, {172,19,0,2}))
- .add_additional(new DNSARR("else3.where.com", 42, {172,19,0,3}));
- std::vector<byte> data = pkt.data();
-
- struct ares_srv_reply* srv = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
- ASSERT_NE(nullptr, srv);
-
- EXPECT_EQ("srv.abc.def.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(10, srv->weight);
- EXPECT_EQ(1234, srv->port);
- EXPECT_EQ(nullptr, srv->next);
-
- ares_free_data(srv);
-}
-
-TEST_F(LibraryTest, ParseSrvReplyCnameMultiple) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_ra().set_rd()
- .add_question(new DNSQuestion("query.example.com", ns_t_srv))
- .add_answer(new DNSCnameRR("query.example.com", 300, "srv.example.com"))
- .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 6789, "a1.srv.example.com"))
- .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 4567, "a2.srv.example.com"))
- .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 5678, "a3.srv.example.com"))
- .add_auth(new DNSNsRR("example.com", 300, "ns1.example.com"))
- .add_auth(new DNSNsRR("example.com", 300, "ns2.example.com"))
- .add_auth(new DNSNsRR("example.com", 300, "ns3.example.com"))
- .add_additional(new DNSARR("a1.srv.example.com", 300, {172,19,1,1}))
- .add_additional(new DNSARR("a2.srv.example.com", 300, {172,19,1,2}))
- .add_additional(new DNSARR("a3.srv.example.com", 300, {172,19,1,3}))
- .add_additional(new DNSARR("n1.example.com", 300, {172,19,0,1}))
- .add_additional(new DNSARR("n2.example.com", 300, {172,19,0,2}))
- .add_additional(new DNSARR("n3.example.com", 300, {172,19,0,3}));
- std::vector<byte> data = pkt.data();
-
- struct ares_srv_reply* srv0 = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv0));
- ASSERT_NE(nullptr, srv0);
- struct ares_srv_reply* srv = srv0;
-
- EXPECT_EQ("a1.srv.example.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(5, srv->weight);
- EXPECT_EQ(6789, srv->port);
- EXPECT_NE(nullptr, srv->next);
- srv = srv->next;
-
- EXPECT_EQ("a2.srv.example.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(5, srv->weight);
- EXPECT_EQ(4567, srv->port);
- EXPECT_NE(nullptr, srv->next);
- srv = srv->next;
-
- EXPECT_EQ("a3.srv.example.com", std::string(srv->host));
- EXPECT_EQ(0, srv->priority);
- EXPECT_EQ(5, srv->weight);
- EXPECT_EQ(5678, srv->port);
- EXPECT_EQ(nullptr, srv->next);
-
- ares_free_data(srv0);
-}
-
-TEST_F(LibraryTest, ParseSrvReplyErrors) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
- .add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
- std::vector<byte> data;
- struct ares_srv_reply* srv = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_srv_reply(data.data(), data.size(), &srv));
- pkt.add_question(new DNSQuestion("example.abc.def.com", ns_t_srv));
-
-#ifdef DISABLED
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_srv));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_srv_reply(data.data(), data.size(), &srv));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_srv));
-#endif
-
- // Two questions.
- pkt.add_question(new DNSQuestion("example.abc.def.com", ns_t_srv));
- data = pkt.data();
- EXPECT_EQ(ARES_EBADRESP, ares_parse_srv_reply(data.data(), data.size(), &srv));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
-
- // Wrong sort of answer.
- pkt.answers_.clear();
- pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
- data = pkt.data();
- EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
- EXPECT_EQ(nullptr, srv);
- pkt.answers_.clear();
- pkt.add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_srv_reply(data.data(), data.size(), &srv));
- pkt.add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
-
- // Truncated packets.
- data = pkt.data();
- for (size_t len = 1; len < data.size(); len++) {
- int rc = ares_parse_srv_reply(data.data(), len, &srv);
- EXPECT_TRUE(rc == ARES_EBADRESP || rc == ARES_EBADNAME);
- }
-}
-
-TEST_F(LibraryTest, ParseSrvReplyAllocFail) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
- .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
- .add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
- std::vector<byte> data = pkt.data();
- struct ares_srv_reply* srv = nullptr;
-
- for (int ii = 1; ii <= 5; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_srv_reply(data.data(), data.size(), &srv)) << ii;
- }
-}
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseSrvReplyOK) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_srv))
+ .add_answer(new DNSSrvRR("example.com", 100, 10, 20, 30, "srv.example.com"))
+ .add_answer(new DNSSrvRR("example.com", 100, 11, 21, 31, "srv2.example.com"));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_srv_reply* srv = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ ASSERT_NE(nullptr, srv);
+
+ EXPECT_EQ("srv.example.com", std::string(srv->host));
+ EXPECT_EQ(10, srv->priority);
+ EXPECT_EQ(20, srv->weight);
+ EXPECT_EQ(30, srv->port);
+
+ struct ares_srv_reply* srv2 = srv->next;
+ ASSERT_NE(nullptr, srv2);
+ EXPECT_EQ("srv2.example.com", std::string(srv2->host));
+ EXPECT_EQ(11, srv2->priority);
+ EXPECT_EQ(21, srv2->weight);
+ EXPECT_EQ(31, srv2->port);
+ EXPECT_EQ(nullptr, srv2->next);
+
+ ares_free_data(srv);
+}
+
+TEST_F(LibraryTest, ParseSrvReplySingle) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
+ .add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else1.where.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else2.where.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else3.where.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else4.where.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else5.where.com"))
+ .add_additional(new DNSARR("else2.where.com", 42, {172,19,0,1}))
+ .add_additional(new DNSARR("else5.where.com", 42, {172,19,0,2}));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_srv_reply* srv = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ ASSERT_NE(nullptr, srv);
+
+ EXPECT_EQ("example.abc.def.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(10, srv->weight);
+ EXPECT_EQ(8160, srv->port);
+ EXPECT_EQ(nullptr, srv->next);
+
+ ares_free_data(srv);
+}
+
+TEST_F(LibraryTest, ParseSrvReplyMalformed) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x21, // type SRV
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x21, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length -- too short
+ 0x02, 0x03, 0x04, 0x05,
+ };
+
+ struct ares_srv_reply* srv = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ ASSERT_EQ(nullptr, srv);
+}
+
+TEST_F(LibraryTest, ParseSrvReplyMultiple) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_ra().set_rd()
+ .add_question(new DNSQuestion("srv.example.com", ns_t_srv))
+ .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 6789, "a1.srv.example.com"))
+ .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 4567, "a2.srv.example.com"))
+ .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 5678, "a3.srv.example.com"))
+ .add_auth(new DNSNsRR("example.com", 300, "ns1.example.com"))
+ .add_auth(new DNSNsRR("example.com", 300, "ns2.example.com"))
+ .add_auth(new DNSNsRR("example.com", 300, "ns3.example.com"))
+ .add_additional(new DNSARR("a1.srv.example.com", 300, {172,19,1,1}))
+ .add_additional(new DNSARR("a2.srv.example.com", 300, {172,19,1,2}))
+ .add_additional(new DNSARR("a3.srv.example.com", 300, {172,19,1,3}))
+ .add_additional(new DNSARR("n1.example.com", 300, {172,19,0,1}))
+ .add_additional(new DNSARR("n2.example.com", 300, {172,19,0,2}))
+ .add_additional(new DNSARR("n3.example.com", 300, {172,19,0,3}));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_srv_reply* srv0 = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv0));
+ ASSERT_NE(nullptr, srv0);
+ struct ares_srv_reply* srv = srv0;
+
+ EXPECT_EQ("a1.srv.example.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(5, srv->weight);
+ EXPECT_EQ(6789, srv->port);
+ EXPECT_NE(nullptr, srv->next);
+ srv = srv->next;
+
+ EXPECT_EQ("a2.srv.example.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(5, srv->weight);
+ EXPECT_EQ(4567, srv->port);
+ EXPECT_NE(nullptr, srv->next);
+ srv = srv->next;
+
+ EXPECT_EQ("a3.srv.example.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(5, srv->weight);
+ EXPECT_EQ(5678, srv->port);
+ EXPECT_EQ(nullptr, srv->next);
+
+ ares_free_data(srv0);
+}
+
+TEST_F(LibraryTest, ParseSrvReplyCname) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
+ .add_answer(new DNSCnameRR("example.abc.def.com", 300, "cname.abc.def.com"))
+ .add_answer(new DNSSrvRR("cname.abc.def.com", 300, 0, 10, 1234, "srv.abc.def.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else1.where.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else2.where.com"))
+ .add_auth(new DNSNsRR("abc.def.com", 44, "else3.where.com"))
+ .add_additional(new DNSARR("example.abc.def.com", 300, {172,19,0,1}))
+ .add_additional(new DNSARR("else1.where.com", 42, {172,19,0,1}))
+ .add_additional(new DNSARR("else2.where.com", 42, {172,19,0,2}))
+ .add_additional(new DNSARR("else3.where.com", 42, {172,19,0,3}));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_srv_reply* srv = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ ASSERT_NE(nullptr, srv);
+
+ EXPECT_EQ("srv.abc.def.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(10, srv->weight);
+ EXPECT_EQ(1234, srv->port);
+ EXPECT_EQ(nullptr, srv->next);
+
+ ares_free_data(srv);
+}
+
+TEST_F(LibraryTest, ParseSrvReplyCnameMultiple) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_ra().set_rd()
+ .add_question(new DNSQuestion("query.example.com", ns_t_srv))
+ .add_answer(new DNSCnameRR("query.example.com", 300, "srv.example.com"))
+ .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 6789, "a1.srv.example.com"))
+ .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 4567, "a2.srv.example.com"))
+ .add_answer(new DNSSrvRR("srv.example.com", 300, 0, 5, 5678, "a3.srv.example.com"))
+ .add_auth(new DNSNsRR("example.com", 300, "ns1.example.com"))
+ .add_auth(new DNSNsRR("example.com", 300, "ns2.example.com"))
+ .add_auth(new DNSNsRR("example.com", 300, "ns3.example.com"))
+ .add_additional(new DNSARR("a1.srv.example.com", 300, {172,19,1,1}))
+ .add_additional(new DNSARR("a2.srv.example.com", 300, {172,19,1,2}))
+ .add_additional(new DNSARR("a3.srv.example.com", 300, {172,19,1,3}))
+ .add_additional(new DNSARR("n1.example.com", 300, {172,19,0,1}))
+ .add_additional(new DNSARR("n2.example.com", 300, {172,19,0,2}))
+ .add_additional(new DNSARR("n3.example.com", 300, {172,19,0,3}));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_srv_reply* srv0 = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv0));
+ ASSERT_NE(nullptr, srv0);
+ struct ares_srv_reply* srv = srv0;
+
+ EXPECT_EQ("a1.srv.example.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(5, srv->weight);
+ EXPECT_EQ(6789, srv->port);
+ EXPECT_NE(nullptr, srv->next);
+ srv = srv->next;
+
+ EXPECT_EQ("a2.srv.example.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(5, srv->weight);
+ EXPECT_EQ(4567, srv->port);
+ EXPECT_NE(nullptr, srv->next);
+ srv = srv->next;
+
+ EXPECT_EQ("a3.srv.example.com", std::string(srv->host));
+ EXPECT_EQ(0, srv->priority);
+ EXPECT_EQ(5, srv->weight);
+ EXPECT_EQ(5678, srv->port);
+ EXPECT_EQ(nullptr, srv->next);
+
+ ares_free_data(srv0);
+}
+
+TEST_F(LibraryTest, ParseSrvReplyErrors) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
+ .add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
+ std::vector<byte> data;
+ struct ares_srv_reply* srv = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ pkt.add_question(new DNSQuestion("example.abc.def.com", ns_t_srv));
+
+#ifdef DISABLED
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_srv));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_srv));
+#endif
+
+ // Two questions.
+ pkt.add_question(new DNSQuestion("example.abc.def.com", ns_t_srv));
+ data = pkt.data();
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("64.48.32.16.in-addr.arpa", ns_t_ptr));
+
+ // Wrong sort of answer.
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSMxRR("example.com", 100, 100, "mx1.example.com"));
+ data = pkt.data();
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ EXPECT_EQ(nullptr, srv);
+ pkt.answers_.clear();
+ pkt.add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_srv_reply(data.data(), data.size(), &srv));
+ pkt.add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
+
+ // Truncated packets.
+ data = pkt.data();
+ for (size_t len = 1; len < data.size(); len++) {
+ int rc = ares_parse_srv_reply(data.data(), len, &srv);
+ EXPECT_TRUE(rc == ARES_EBADRESP || rc == ARES_EBADNAME);
+ }
+}
+
+TEST_F(LibraryTest, ParseSrvReplyAllocFail) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.abc.def.com", ns_t_srv))
+ .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
+ .add_answer(new DNSSrvRR("example.abc.def.com", 180, 0, 10, 8160, "example.abc.def.com"));
+ std::vector<byte> data = pkt.data();
+ struct ares_srv_reply* srv = nullptr;
+
+ for (int ii = 1; ii <= 5; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_srv_reply(data.data(), data.size(), &srv)) << ii;
+ }
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse-txt.cc b/contrib/libs/c-ares/test/ares-test-parse-txt.cc
index 8aaaaa3b47..80a9dad7d1 100644
--- a/contrib/libs/c-ares/test/ares-test-parse-txt.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse-txt.cc
@@ -1,266 +1,266 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseTxtReplyOK) {
- DNSPacket pkt;
- std::string expected1 = "txt1.example.com";
- std::string expected2a = "txt2a";
- std::string expected2b("ABC\0ABC", 7);
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
- .add_answer(new DNSTxtRR("example.com", 100, {expected2a, expected2b}));
- std::vector<byte> data = pkt.data();
-
- struct ares_txt_reply* txt = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_txt_reply(data.data(), data.size(), &txt));
- ASSERT_NE(nullptr, txt);
- EXPECT_EQ(std::vector<byte>(expected1.data(), expected1.data() + expected1.size()),
- std::vector<byte>(txt->txt, txt->txt + txt->length));
-
- struct ares_txt_reply* txt2 = txt->next;
- ASSERT_NE(nullptr, txt2);
- EXPECT_EQ(std::vector<byte>(expected2a.data(), expected2a.data() + expected2a.size()),
- std::vector<byte>(txt2->txt, txt2->txt + txt2->length));
-
- struct ares_txt_reply* txt3 = txt2->next;
- ASSERT_NE(nullptr, txt3);
- EXPECT_EQ(std::vector<byte>(expected2b.data(), expected2b.data() + expected2b.size()),
- std::vector<byte>(txt3->txt, txt3->txt + txt3->length));
- EXPECT_EQ(nullptr, txt3->next);
-
- ares_free_data(txt);
-}
-
-TEST_F(LibraryTest, ParseTxtExtReplyOK) {
- DNSPacket pkt;
- std::string expected1 = "txt1.example.com";
- std::string expected2a = "txt2a";
- std::string expected2b("ABC\0ABC", 7);
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
- .add_answer(new DNSTxtRR("example.com", 100, {expected2a, expected2b}));
- std::vector<byte> data = pkt.data();
-
- struct ares_txt_ext* txt = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_txt_reply_ext(data.data(), data.size(), &txt));
- ASSERT_NE(nullptr, txt);
- EXPECT_EQ(std::vector<byte>(expected1.data(), expected1.data() + expected1.size()),
- std::vector<byte>(txt->txt, txt->txt + txt->length));
- EXPECT_EQ(1, txt->record_start);
-
- struct ares_txt_ext* txt2 = txt->next;
- ASSERT_NE(nullptr, txt2);
- EXPECT_EQ(std::vector<byte>(expected2a.data(), expected2a.data() + expected2a.size()),
- std::vector<byte>(txt2->txt, txt2->txt + txt2->length));
- EXPECT_EQ(1, txt2->record_start);
-
- struct ares_txt_ext* txt3 = txt2->next;
- ASSERT_NE(nullptr, txt3);
- EXPECT_EQ(std::vector<byte>(expected2b.data(), expected2b.data() + expected2b.size()),
- std::vector<byte>(txt3->txt, txt3->txt + txt3->length));
- EXPECT_EQ(nullptr, txt3->next);
- EXPECT_EQ(0, txt3->record_start);
-
- ares_free_data(txt);
-}
-
-TEST_F(LibraryTest, ParseTxtMalformedReply1) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // type TXT
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x03, // rdata length
- 0x12, 'a', 'b', // invalid length
- };
-
- struct ares_txt_reply* txt = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
- ASSERT_EQ(nullptr, txt);
-}
-
-TEST_F(LibraryTest, ParseTxtMalformedReply2) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // type TXT
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // RR type
- // truncated
- };
-
- struct ares_txt_reply* txt = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
- ASSERT_EQ(nullptr, txt);
-}
-
-TEST_F(LibraryTest, ParseTxtMalformedReply3) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // type TXT
- 0x00, 0x01, // class IN
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x13, // rdata length INVALID
- 0x02, 'a', 'b',
- };
-
- struct ares_txt_reply* txt = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
- ASSERT_EQ(nullptr, txt);
-}
-
-TEST_F(LibraryTest, ParseTxtMalformedReply4) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x10, // type TXT
- 0x00, // TRUNCATED
- };
-
- struct ares_txt_reply* txt = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
- ASSERT_EQ(nullptr, txt);
-}
-
-TEST_F(LibraryTest, ParseTxtReplyErrors) {
- DNSPacket pkt;
- std::string expected1 = "txt1.example.com";
- std::string expected2a = "txt2a";
- std::string expected2b = "txt2b";
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
- .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
- .add_answer(new DNSTxtRR("example.com", 100, {expected2a, expected2b}));
- std::vector<byte> data = pkt.data();
- struct ares_txt_reply* txt = nullptr;
-
- // No question.
- pkt.questions_.clear();
- data = pkt.data();
- txt = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
- EXPECT_EQ(nullptr, txt);
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
-
-#ifdef DISABLED
- // Question != answer
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("Axample.com", ns_t_txt));
- data = pkt.data();
- EXPECT_EQ(ARES_ENODATA, ares_parse_txt_reply(data.data(), data.size(), &txt));
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_txt));
-#endif
-
- // Two questions.
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
- data = pkt.data();
- txt = nullptr;
- EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
- EXPECT_EQ(nullptr, txt);
- pkt.questions_.clear();
- pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
-
- // No answer.
- pkt.answers_.clear();
- data = pkt.data();
- txt = nullptr;
- EXPECT_EQ(ARES_ENODATA, ares_parse_txt_reply(data.data(), data.size(), &txt));
- EXPECT_EQ(nullptr, txt);
- pkt.add_answer(new DNSTxtRR("example.com", 100, {expected1}));
-
- // Truncated packets.
- for (size_t len = 1; len < data.size(); len++) {
- txt = nullptr;
- EXPECT_NE(ARES_SUCCESS, ares_parse_txt_reply(data.data(), len, &txt));
- EXPECT_EQ(nullptr, txt);
- }
-}
-
-TEST_F(LibraryTest, ParseTxtReplyAllocFail) {
- DNSPacket pkt;
- std::string expected1 = "txt1.example.com";
- std::string expected2a = "txt2a";
- std::string expected2b = "txt2b";
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com", ns_t_mx))
- .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
- .add_answer(new DNSTxtRR("c.example.com", 100, {expected1}))
- .add_answer(new DNSTxtRR("c.example.com", 100, {expected1}))
- .add_answer(new DNSTxtRR("c.example.com", 100, {expected2a, expected2b}));
- std::vector<byte> data = pkt.data();
- struct ares_txt_reply* txt = nullptr;
-
- for (int ii = 1; ii <= 13; ii++) {
- ClearFails();
- SetAllocFail(ii);
- EXPECT_EQ(ARES_ENOMEM, ares_parse_txt_reply(data.data(), data.size(), &txt)) << ii;
- }
-}
-
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseTxtReplyOK) {
+ DNSPacket pkt;
+ std::string expected1 = "txt1.example.com";
+ std::string expected2a = "txt2a";
+ std::string expected2b("ABC\0ABC", 7);
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected2a, expected2b}));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_txt_reply* txt = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ ASSERT_NE(nullptr, txt);
+ EXPECT_EQ(std::vector<byte>(expected1.data(), expected1.data() + expected1.size()),
+ std::vector<byte>(txt->txt, txt->txt + txt->length));
+
+ struct ares_txt_reply* txt2 = txt->next;
+ ASSERT_NE(nullptr, txt2);
+ EXPECT_EQ(std::vector<byte>(expected2a.data(), expected2a.data() + expected2a.size()),
+ std::vector<byte>(txt2->txt, txt2->txt + txt2->length));
+
+ struct ares_txt_reply* txt3 = txt2->next;
+ ASSERT_NE(nullptr, txt3);
+ EXPECT_EQ(std::vector<byte>(expected2b.data(), expected2b.data() + expected2b.size()),
+ std::vector<byte>(txt3->txt, txt3->txt + txt3->length));
+ EXPECT_EQ(nullptr, txt3->next);
+
+ ares_free_data(txt);
+}
+
+TEST_F(LibraryTest, ParseTxtExtReplyOK) {
+ DNSPacket pkt;
+ std::string expected1 = "txt1.example.com";
+ std::string expected2a = "txt2a";
+ std::string expected2b("ABC\0ABC", 7);
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected2a, expected2b}));
+ std::vector<byte> data = pkt.data();
+
+ struct ares_txt_ext* txt = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_txt_reply_ext(data.data(), data.size(), &txt));
+ ASSERT_NE(nullptr, txt);
+ EXPECT_EQ(std::vector<byte>(expected1.data(), expected1.data() + expected1.size()),
+ std::vector<byte>(txt->txt, txt->txt + txt->length));
+ EXPECT_EQ(1, txt->record_start);
+
+ struct ares_txt_ext* txt2 = txt->next;
+ ASSERT_NE(nullptr, txt2);
+ EXPECT_EQ(std::vector<byte>(expected2a.data(), expected2a.data() + expected2a.size()),
+ std::vector<byte>(txt2->txt, txt2->txt + txt2->length));
+ EXPECT_EQ(1, txt2->record_start);
+
+ struct ares_txt_ext* txt3 = txt2->next;
+ ASSERT_NE(nullptr, txt3);
+ EXPECT_EQ(std::vector<byte>(expected2b.data(), expected2b.data() + expected2b.size()),
+ std::vector<byte>(txt3->txt, txt3->txt + txt3->length));
+ EXPECT_EQ(nullptr, txt3->next);
+ EXPECT_EQ(0, txt3->record_start);
+
+ ares_free_data(txt);
+}
+
+TEST_F(LibraryTest, ParseTxtMalformedReply1) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // type TXT
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x03, // rdata length
+ 0x12, 'a', 'b', // invalid length
+ };
+
+ struct ares_txt_reply* txt = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ ASSERT_EQ(nullptr, txt);
+}
+
+TEST_F(LibraryTest, ParseTxtMalformedReply2) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // type TXT
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // RR type
+ // truncated
+ };
+
+ struct ares_txt_reply* txt = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ ASSERT_EQ(nullptr, txt);
+}
+
+TEST_F(LibraryTest, ParseTxtMalformedReply3) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // type TXT
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x13, // rdata length INVALID
+ 0x02, 'a', 'b',
+ };
+
+ struct ares_txt_reply* txt = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ ASSERT_EQ(nullptr, txt);
+}
+
+TEST_F(LibraryTest, ParseTxtMalformedReply4) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x10, // type TXT
+ 0x00, // TRUNCATED
+ };
+
+ struct ares_txt_reply* txt = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ ASSERT_EQ(nullptr, txt);
+}
+
+TEST_F(LibraryTest, ParseTxtReplyErrors) {
+ DNSPacket pkt;
+ std::string expected1 = "txt1.example.com";
+ std::string expected2a = "txt2a";
+ std::string expected2b = "txt2b";
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected1}))
+ .add_answer(new DNSTxtRR("example.com", 100, {expected2a, expected2b}));
+ std::vector<byte> data = pkt.data();
+ struct ares_txt_reply* txt = nullptr;
+
+ // No question.
+ pkt.questions_.clear();
+ data = pkt.data();
+ txt = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ EXPECT_EQ(nullptr, txt);
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+
+#ifdef DISABLED
+ // Question != answer
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("Axample.com", ns_t_txt));
+ data = pkt.data();
+ EXPECT_EQ(ARES_ENODATA, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_txt));
+#endif
+
+ // Two questions.
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+ data = pkt.data();
+ txt = nullptr;
+ EXPECT_EQ(ARES_EBADRESP, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ EXPECT_EQ(nullptr, txt);
+ pkt.questions_.clear();
+ pkt.add_question(new DNSQuestion("example.com", ns_t_mx));
+
+ // No answer.
+ pkt.answers_.clear();
+ data = pkt.data();
+ txt = nullptr;
+ EXPECT_EQ(ARES_ENODATA, ares_parse_txt_reply(data.data(), data.size(), &txt));
+ EXPECT_EQ(nullptr, txt);
+ pkt.add_answer(new DNSTxtRR("example.com", 100, {expected1}));
+
+ // Truncated packets.
+ for (size_t len = 1; len < data.size(); len++) {
+ txt = nullptr;
+ EXPECT_NE(ARES_SUCCESS, ares_parse_txt_reply(data.data(), len, &txt));
+ EXPECT_EQ(nullptr, txt);
+ }
+}
+
+TEST_F(LibraryTest, ParseTxtReplyAllocFail) {
+ DNSPacket pkt;
+ std::string expected1 = "txt1.example.com";
+ std::string expected2a = "txt2a";
+ std::string expected2b = "txt2b";
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com", ns_t_mx))
+ .add_answer(new DNSCnameRR("example.com", 300, "c.example.com"))
+ .add_answer(new DNSTxtRR("c.example.com", 100, {expected1}))
+ .add_answer(new DNSTxtRR("c.example.com", 100, {expected1}))
+ .add_answer(new DNSTxtRR("c.example.com", 100, {expected2a, expected2b}));
+ std::vector<byte> data = pkt.data();
+ struct ares_txt_reply* txt = nullptr;
+
+ for (int ii = 1; ii <= 13; ii++) {
+ ClearFails();
+ SetAllocFail(ii);
+ EXPECT_EQ(ARES_ENOMEM, ares_parse_txt_reply(data.data(), data.size(), &txt)) << ii;
+ }
+}
+
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test-parse.cc b/contrib/libs/c-ares/test/ares-test-parse.cc
index 4c54fc9902..95744c3eb5 100644
--- a/contrib/libs/c-ares/test/ares-test-parse.cc
+++ b/contrib/libs/c-ares/test/ares-test-parse.cc
@@ -1,219 +1,219 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <sstream>
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST_F(LibraryTest, ParseRootName) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion(".", ns_t_a))
- .add_answer(new DNSARR(".", 100, {0x02, 0x03, 0x04, 0x05}));
- std::vector<byte> data = pkt.data();
-
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'' aliases=[] addrs=[2.3.4.5]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseIndirectRootName) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0xC0, 0x04, // weird: pointer to a random zero earlier in the message
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer 1
- 0xC0, 0x04,
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
- };
-
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'' aliases=[] addrs=[2.3.4.5]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseEscapedName) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x05, 'a', '\\', 'b', '.', 'c',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer 1
- 0x05, 'a', '\\', 'b', '.', 'c',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
- };
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- EXPECT_EQ(1, count);
- HostEnt hent(host);
- std::stringstream ss;
- ss << hent;
- // The printable name is expanded with escapes.
- EXPECT_EQ(11, hent.name_.size());
- EXPECT_EQ('a', hent.name_[0]);
- EXPECT_EQ('\\', hent.name_[1]);
- EXPECT_EQ('\\', hent.name_[2]);
- EXPECT_EQ('b', hent.name_[3]);
- EXPECT_EQ('\\', hent.name_[4]);
- EXPECT_EQ('.', hent.name_[5]);
- EXPECT_EQ('c', hent.name_[6]);
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParsePartialCompressedName) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x03, 'w', 'w', 'w',
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer 1
- 0x03, 'w', 'w', 'w',
- 0xc0, 0x10, // offset 16
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
- };
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseFullyCompressedName) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0x03, 'w', 'w', 'w',
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer 1
- 0xc0, 0x0c, // offset 12
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
- };
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
- ares_free_hostent(host);
-}
-
-TEST_F(LibraryTest, ParseFullyCompressedName2) {
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x01, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question
- 0xC0, 0x12, // pointer to later in message
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Answer 1
- 0x03, 'w', 'w', 'w',
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
- };
- struct hostent *host = nullptr;
- struct ares_addrttl info[2];
- int count = 2;
- EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
- &host, info, &count));
- ASSERT_NE(nullptr, host);
- std::stringstream ss;
- ss << HostEnt(host);
- EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
- ares_free_hostent(host);
-}
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <sstream>
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST_F(LibraryTest, ParseRootName) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion(".", ns_t_a))
+ .add_answer(new DNSARR(".", 100, {0x02, 0x03, 0x04, 0x05}));
+ std::vector<byte> data = pkt.data();
+
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseIndirectRootName) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0xC0, 0x04, // weird: pointer to a random zero earlier in the message
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0xC0, 0x04,
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
+ };
+
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseEscapedName) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x05, 'a', '\\', 'b', '.', 'c',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x05, 'a', '\\', 'b', '.', 'c',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
+ };
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ EXPECT_EQ(1, count);
+ HostEnt hent(host);
+ std::stringstream ss;
+ ss << hent;
+ // The printable name is expanded with escapes.
+ EXPECT_EQ(11, hent.name_.size());
+ EXPECT_EQ('a', hent.name_[0]);
+ EXPECT_EQ('\\', hent.name_[1]);
+ EXPECT_EQ('\\', hent.name_[2]);
+ EXPECT_EQ('b', hent.name_[3]);
+ EXPECT_EQ('\\', hent.name_[4]);
+ EXPECT_EQ('.', hent.name_[5]);
+ EXPECT_EQ('c', hent.name_[6]);
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParsePartialCompressedName) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x03, 'w', 'w', 'w',
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x03, 'w', 'w', 'w',
+ 0xc0, 0x10, // offset 16
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
+ };
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseFullyCompressedName) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0x03, 'w', 'w', 'w',
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0xc0, 0x0c, // offset 12
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
+ };
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ ares_free_hostent(host);
+}
+
+TEST_F(LibraryTest, ParseFullyCompressedName2) {
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x01, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question
+ 0xC0, 0x12, // pointer to later in message
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Answer 1
+ 0x03, 'w', 'w', 'w',
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
+ };
+ struct hostent *host = nullptr;
+ struct ares_addrttl info[2];
+ int count = 2;
+ EXPECT_EQ(ARES_SUCCESS, ares_parse_a_reply(data.data(), data.size(),
+ &host, info, &count));
+ ASSERT_NE(nullptr, host);
+ std::stringstream ss;
+ ss << HostEnt(host);
+ EXPECT_EQ("{'www.example.com' aliases=[] addrs=[2.3.4.5]}", ss.str());
+ ares_free_hostent(host);
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test.cc b/contrib/libs/c-ares/test/ares-test.cc
index ec4b460549..90d05013f0 100644
--- a/contrib/libs/c-ares/test/ares-test.cc
+++ b/contrib/libs/c-ares/test/ares-test.cc
@@ -1,570 +1,570 @@
-#include "ares-test.h"
+#include "ares-test.h"
#include "ares-test-ai.h"
-#include "dns-proto.h"
-
-// Include ares internal files for DNS protocol details
-#include "nameser.h"
-#include "ares_dns.h"
-
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#ifdef HAVE_NETINET_TCP_H
-#include <netinet/tcp.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <functional>
-#include <sstream>
-
-#ifdef WIN32
-#define BYTE_CAST (char *)
-#define mkdir_(d, p) mkdir(d)
-#else
-#define BYTE_CAST
-#define mkdir_(d, p) mkdir(d, p)
-#endif
-
-namespace ares {
-namespace test {
-
-bool verbose = false;
-int mock_port = 5300;
-
-const std::vector<int> both_families = {AF_INET, AF_INET6};
-const std::vector<int> ipv4_family = {AF_INET};
-const std::vector<int> ipv6_family = {AF_INET6};
-
-const std::vector<std::pair<int, bool>> both_families_both_modes = {
- std::make_pair<int, bool>(AF_INET, false),
- std::make_pair<int, bool>(AF_INET, true),
- std::make_pair<int, bool>(AF_INET6, false),
- std::make_pair<int, bool>(AF_INET6, true)
-};
-const std::vector<std::pair<int, bool>> ipv4_family_both_modes = {
- std::make_pair<int, bool>(AF_INET, false),
- std::make_pair<int, bool>(AF_INET, true)
-};
-const std::vector<std::pair<int, bool>> ipv6_family_both_modes = {
- std::make_pair<int, bool>(AF_INET6, false),
- std::make_pair<int, bool>(AF_INET6, true)
-};
-
-// Which parameters to use in tests
-std::vector<int> families = both_families;
-std::vector<std::pair<int, bool>> families_modes = both_families_both_modes;
-
-unsigned long long LibraryTest::fails_ = 0;
-std::map<size_t, int> LibraryTest::size_fails_;
-
-void ProcessWork(ares_channel channel,
- std::function<std::set<int>()> get_extrafds,
- std::function<void(int)> process_extra) {
- int nfds, count;
- fd_set readers, writers;
- struct timeval tv;
- while (true) {
- // Retrieve the set of file descriptors that the library wants us to monitor.
- FD_ZERO(&readers);
- FD_ZERO(&writers);
- nfds = ares_fds(channel, &readers, &writers);
- if (nfds == 0) // no work left to do in the library
- return;
-
- // Add in the extra FDs if present.
- std::set<int> extrafds = get_extrafds();
- for (int extrafd : extrafds) {
- FD_SET(extrafd, &readers);
- if (extrafd >= nfds) {
- nfds = extrafd + 1;
- }
- }
-
- // Wait for activity or timeout.
- tv.tv_sec = 0;
- tv.tv_usec = 100000; // 100ms
- count = select(nfds, &readers, &writers, nullptr, &tv);
- if (count < 0) {
- fprintf(stderr, "select() failed, errno %d\n", errno);
- return;
- }
-
- // Let the library process any activity.
- ares_process(channel, &readers, &writers);
-
- // Let the provided callback process any activity on the extra FD.
- for (int extrafd : extrafds) {
- if (FD_ISSET(extrafd, &readers)) {
- process_extra(extrafd);
- }
- }
- }
-}
-
-// static
-void LibraryTest::SetAllocFail(int nth) {
- assert(nth > 0);
- assert(nth <= (int)(8 * sizeof(fails_)));
- fails_ |= (1LL << (nth - 1));
-}
-
-// static
-void LibraryTest::SetAllocSizeFail(size_t size) {
- size_fails_[size]++;
-}
-
-// static
-void LibraryTest::ClearFails() {
- fails_ = 0;
- size_fails_.clear();
-}
-
-
-// static
-bool LibraryTest::ShouldAllocFail(size_t size) {
- bool fail = (fails_ & 0x01);
- fails_ >>= 1;
- if (size_fails_[size] > 0) {
- size_fails_[size]--;
- fail = true;
- }
- return fail;
-}
-
-// static
-void* LibraryTest::amalloc(size_t size) {
- if (ShouldAllocFail(size)) {
- if (verbose) std::cerr << "Failing malloc(" << size << ") request" << std::endl;
- return nullptr;
- } else {
- return malloc(size);
- }
-}
-
-// static
-void* LibraryTest::arealloc(void *ptr, size_t size) {
- if (ShouldAllocFail(size)) {
- if (verbose) std::cerr << "Failing realloc(" << ptr << ", " << size << ") request" << std::endl;
- return nullptr;
- } else {
- return realloc(ptr, size);
- }
-}
-
-// static
-void LibraryTest::afree(void *ptr) {
- free(ptr);
-}
-
-std::set<int> NoExtraFDs() {
- return std::set<int>();
-}
-
-void DefaultChannelTest::Process() {
- ProcessWork(channel_, NoExtraFDs, nullptr);
-}
-
-void DefaultChannelModeTest::Process() {
- ProcessWork(channel_, NoExtraFDs, nullptr);
-}
-
-MockServer::MockServer(int family, int port, int tcpport)
- : udpport_(port), tcpport_(tcpport ? tcpport : udpport_), qid_(-1) {
- // Create a TCP socket to receive data on.
- tcpfd_ = socket(family, SOCK_STREAM, 0);
- EXPECT_NE(-1, tcpfd_);
- int optval = 1;
- setsockopt(tcpfd_, SOL_SOCKET, SO_REUSEADDR,
- BYTE_CAST &optval , sizeof(int));
- // Send TCP data right away.
- setsockopt(tcpfd_, IPPROTO_TCP, TCP_NODELAY,
- BYTE_CAST &optval , sizeof(int));
-
- // Create a UDP socket to receive data on.
- udpfd_ = socket(family, SOCK_DGRAM, 0);
- EXPECT_NE(-1, udpfd_);
-
- // Bind the sockets to the given port.
- if (family == AF_INET) {
- struct sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = htonl(INADDR_ANY);
- addr.sin_port = htons(tcpport_);
- int tcprc = bind(tcpfd_, (struct sockaddr*)&addr, sizeof(addr));
- EXPECT_EQ(0, tcprc) << "Failed to bind AF_INET to TCP port " << tcpport_;
- addr.sin_port = htons(udpport_);
- int udprc = bind(udpfd_, (struct sockaddr*)&addr, sizeof(addr));
- EXPECT_EQ(0, udprc) << "Failed to bind AF_INET to UDP port " << udpport_;
- } else {
- EXPECT_EQ(AF_INET6, family);
- struct sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
- memset(&addr.sin6_addr, 0, sizeof(addr.sin6_addr)); // in6addr_any
- addr.sin6_port = htons(tcpport_);
- int tcprc = bind(tcpfd_, (struct sockaddr*)&addr, sizeof(addr));
- EXPECT_EQ(0, tcprc) << "Failed to bind AF_INET6 to TCP port " << tcpport_;
- addr.sin6_port = htons(udpport_);
- int udprc = bind(udpfd_, (struct sockaddr*)&addr, sizeof(addr));
- EXPECT_EQ(0, udprc) << "Failed to bind AF_INET6 to UDP port " << udpport_;
- }
- if (verbose) std::cerr << "Configured "
- << (family == AF_INET ? "IPv4" : "IPv6")
- << " mock server with TCP socket " << tcpfd_
- << " on port " << tcpport_
- << " and UDP socket " << udpfd_
- << " on port " << udpport_ << std::endl;
-
- // For TCP, also need to listen for connections.
- EXPECT_EQ(0, listen(tcpfd_, 5)) << "Failed to listen for TCP connections";
-}
-
-MockServer::~MockServer() {
- for (int fd : connfds_) {
- sclose(fd);
- }
- sclose(tcpfd_);
- sclose(udpfd_);
-}
-
-void MockServer::ProcessFD(int fd) {
- if (fd != tcpfd_ && fd != udpfd_ && connfds_.find(fd) == connfds_.end()) {
- // Not one of our FDs.
- return;
- }
- if (fd == tcpfd_) {
- int connfd = accept(tcpfd_, NULL, NULL);
- if (connfd < 0) {
- std::cerr << "Error accepting connection on fd " << fd << std::endl;
- } else {
- connfds_.insert(connfd);
- }
- return;
- }
-
- // Activity on a data-bearing file descriptor.
- struct sockaddr_storage addr;
- socklen_t addrlen = sizeof(addr);
- byte buffer[2048];
- int len = recvfrom(fd, BYTE_CAST buffer, sizeof(buffer), 0,
- (struct sockaddr *)&addr, &addrlen);
- byte* data = buffer;
- if (fd != udpfd_) {
- if (len == 0) {
- connfds_.erase(std::find(connfds_.begin(), connfds_.end(), fd));
- sclose(fd);
- return;
- }
- if (len < 2) {
- std::cerr << "Packet too short (" << len << ")" << std::endl;
- return;
- }
- int tcplen = (data[0] << 8) + data[1];
- data += 2;
- len -= 2;
- if (tcplen != len) {
- std::cerr << "Warning: TCP length " << tcplen
- << " doesn't match remaining data length " << len << std::endl;
- }
- }
-
- // Assume the packet is a well-formed DNS request and extract the request
- // details.
- if (len < NS_HFIXEDSZ) {
- std::cerr << "Packet too short (" << len << ")" << std::endl;
- return;
- }
- int qid = DNS_HEADER_QID(data);
- if (DNS_HEADER_QR(data) != 0) {
- std::cerr << "Not a request" << std::endl;
- return;
- }
- if (DNS_HEADER_OPCODE(data) != ns_o_query) {
- std::cerr << "Not a query (opcode " << DNS_HEADER_OPCODE(data)
- << ")" << std::endl;
- return;
- }
- if (DNS_HEADER_QDCOUNT(data) != 1) {
- std::cerr << "Unexpected question count (" << DNS_HEADER_QDCOUNT(data)
- << ")" << std::endl;
- return;
- }
- byte* question = data + 12;
- int qlen = len - 12;
-
- char *name = nullptr;
- long enclen;
- ares_expand_name(question, data, len, &name, &enclen);
- if (!name) {
- std::cerr << "Failed to retrieve name" << std::endl;
- return;
- }
- qlen -= enclen;
- question += enclen;
- std::string namestr(name);
- ares_free_string(name);
-
- if (qlen < 4) {
- std::cerr << "Unexpected question size (" << qlen
- << " bytes after name)" << std::endl;
- return;
- }
- if (DNS_QUESTION_CLASS(question) != ns_c_in) {
- std::cerr << "Unexpected question class (" << DNS_QUESTION_CLASS(question)
- << ")" << std::endl;
- return;
- }
- int rrtype = DNS_QUESTION_TYPE(question);
-
- if (verbose) {
- std::vector<byte> req(data, data + len);
- std::cerr << "received " << (fd == udpfd_ ? "UDP" : "TCP") << " request " << PacketToString(req)
- << " on port " << (fd == udpfd_ ? udpport_ : tcpport_) << std::endl;
- std::cerr << "ProcessRequest(" << qid << ", '" << namestr
- << "', " << RRTypeToString(rrtype) << ")" << std::endl;
- }
- ProcessRequest(fd, &addr, addrlen, qid, namestr, rrtype);
-}
-
-std::set<int> MockServer::fds() const {
- std::set<int> result = connfds_;
- result.insert(tcpfd_);
- result.insert(udpfd_);
- return result;
-}
-
-void MockServer::ProcessRequest(int fd, struct sockaddr_storage* addr, int addrlen,
- int qid, const std::string& name, int rrtype) {
- // Before processing, let gMock know the request is happening.
- OnRequest(name, rrtype);
-
- if (reply_.size() == 0) {
- return;
- }
-
- // Make a local copy of the current pending reply.
- std::vector<byte> reply = reply_;
-
- if (qid_ >= 0) {
- // Use the explicitly specified query ID.
- qid = qid_;
- }
- if (reply.size() >= 2) {
- // Overwrite the query ID if space to do so.
- reply[0] = (byte)((qid >> 8) & 0xff);
- reply[1] = (byte)(qid & 0xff);
- }
- if (verbose) std::cerr << "sending reply " << PacketToString(reply)
- << " on port " << ((fd == udpfd_) ? udpport_ : tcpport_) << std::endl;
-
- // Prefix with 2-byte length if TCP.
- if (fd != udpfd_) {
- int len = reply.size();
- std::vector<byte> vlen = {(byte)((len & 0xFF00) >> 8), (byte)(len & 0xFF)};
- reply.insert(reply.begin(), vlen.begin(), vlen.end());
- // Also, don't bother with the destination address.
- addr = nullptr;
- addrlen = 0;
- }
-
- int rc = sendto(fd, BYTE_CAST reply.data(), reply.size(), 0,
- (struct sockaddr *)addr, addrlen);
- if (rc < static_cast<int>(reply.size())) {
- std::cerr << "Failed to send full reply, rc=" << rc << std::endl;
- }
-}
-
-// static
-MockChannelOptsTest::NiceMockServers MockChannelOptsTest::BuildServers(int count, int family, int base_port) {
- NiceMockServers servers;
- assert(count > 0);
- for (int ii = 0; ii < count; ii++) {
- std::unique_ptr<NiceMockServer> server(new NiceMockServer(family, base_port + ii));
- servers.push_back(std::move(server));
- }
- return servers;
-}
-
-MockChannelOptsTest::MockChannelOptsTest(int count,
- int family,
- bool force_tcp,
- struct ares_options* givenopts,
- int optmask)
- : servers_(BuildServers(count, family, mock_port)),
- server_(*servers_[0].get()), channel_(nullptr) {
- // Set up channel options.
- struct ares_options opts;
- if (givenopts) {
- memcpy(&opts, givenopts, sizeof(opts));
- } else {
- memset(&opts, 0, sizeof(opts));
- }
-
- // Point the library at the first mock server by default (overridden below).
- opts.udp_port = mock_port;
- optmask |= ARES_OPT_UDP_PORT;
- opts.tcp_port = mock_port;
- optmask |= ARES_OPT_TCP_PORT;
-
- // If not already overridden, set short-ish timeouts.
- if (!(optmask & (ARES_OPT_TIMEOUTMS|ARES_OPT_TIMEOUT))) {
- opts.timeout = 1500;
- optmask |= ARES_OPT_TIMEOUTMS;
- }
- // If not already overridden, set 3 retries.
- if (!(optmask & ARES_OPT_TRIES)) {
- opts.tries = 3;
- optmask |= ARES_OPT_TRIES;
- }
- // If not already overridden, set search domains.
- const char *domains[3] = {"first.com", "second.org", "third.gov"};
- if (!(optmask & ARES_OPT_DOMAINS)) {
- opts.ndomains = 3;
- opts.domains = (char**)domains;
- optmask |= ARES_OPT_DOMAINS;
- }
- if (force_tcp) {
- opts.flags |= ARES_FLAG_USEVC;
- optmask |= ARES_OPT_FLAGS;
- }
-
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel_, &opts, optmask));
- EXPECT_NE(nullptr, channel_);
-
- // Set up servers after construction so we can set individual ports
- struct ares_addr_port_node* prev = nullptr;
- struct ares_addr_port_node* first = nullptr;
- for (const auto& server : servers_) {
- struct ares_addr_port_node* node = (struct ares_addr_port_node*)malloc(sizeof(*node));
- if (prev) {
- prev->next = node;
- } else {
- first = node;
- }
- node->next = nullptr;
- node->family = family;
- node->udp_port = server->udpport();
- node->tcp_port = server->tcpport();
- if (family == AF_INET) {
- node->addr.addr4.s_addr = htonl(0x7F000001);
- } else {
- memset(&node->addr.addr6, 0, sizeof(node->addr.addr6));
- node->addr.addr6._S6_un._S6_u8[15] = 1;
- }
- prev = node;
- }
- EXPECT_EQ(ARES_SUCCESS, ares_set_servers_ports(channel_, first));
-
- while (first) {
- prev = first;
- first = first->next;
- free(prev);
- }
- if (verbose) {
- std::cerr << "Configured library with servers:";
- std::vector<std::string> servers = GetNameServers(channel_);
- for (const auto& server : servers) {
- std::cerr << " " << server;
- }
- std::cerr << std::endl;
- }
-}
-
-MockChannelOptsTest::~MockChannelOptsTest() {
- if (channel_) {
- ares_destroy(channel_);
- }
- channel_ = nullptr;
-}
-
-std::set<int> MockChannelOptsTest::fds() const {
- std::set<int> fds;
- for (const auto& server : servers_) {
- std::set<int> serverfds = server->fds();
- fds.insert(serverfds.begin(), serverfds.end());
- }
- return fds;
-}
-
-void MockChannelOptsTest::ProcessFD(int fd) {
- for (auto& server : servers_) {
- server->ProcessFD(fd);
- }
-}
-
-void MockChannelOptsTest::Process() {
- using namespace std::placeholders;
- ProcessWork(channel_,
- std::bind(&MockChannelOptsTest::fds, this),
- std::bind(&MockChannelOptsTest::ProcessFD, this, _1));
-}
-
-std::ostream& operator<<(std::ostream& os, const HostResult& result) {
- os << '{';
- if (result.done_) {
- os << StatusToString(result.status_) << " " << result.host_;
- } else {
- os << "(incomplete)";
- }
- os << '}';
- return os;
-}
-
-HostEnt::HostEnt(const struct hostent *hostent) : addrtype_(-1) {
- if (!hostent)
- return;
- if (hostent->h_name)
- name_ = hostent->h_name;
- if (hostent->h_aliases) {
- char** palias = hostent->h_aliases;
- while (*palias != nullptr) {
- aliases_.push_back(*palias);
- palias++;
- }
- }
- addrtype_ = hostent->h_addrtype;
- if (hostent->h_addr_list) {
- char** paddr = hostent->h_addr_list;
- while (*paddr != nullptr) {
- std::string addr = AddressToString(*paddr, hostent->h_length);
- addrs_.push_back(addr);
- paddr++;
- }
- }
-}
-
-std::ostream& operator<<(std::ostream& os, const HostEnt& host) {
- os << '{';
- os << "'" << host.name_ << "' "
- << "aliases=[";
- for (size_t ii = 0; ii < host.aliases_.size(); ii++) {
- if (ii > 0) os << ", ";
- os << host.aliases_[ii];
- }
- os << "] ";
- os << "addrs=[";
- for (size_t ii = 0; ii < host.addrs_.size(); ii++) {
- if (ii > 0) os << ", ";
- os << host.addrs_[ii];
- }
- os << "]";
- os << '}';
- return os;
-}
-
-void HostCallback(void *data, int status, int timeouts,
- struct hostent *hostent) {
- EXPECT_NE(nullptr, data);
- HostResult* result = reinterpret_cast<HostResult*>(data);
- result->done_ = true;
- result->status_ = status;
- result->timeouts_ = timeouts;
- result->host_ = HostEnt(hostent);
- if (verbose) std::cerr << "HostCallback(" << *result << ")" << std::endl;
-}
-
+#include "dns-proto.h"
+
+// Include ares internal files for DNS protocol details
+#include "nameser.h"
+#include "ares_dns.h"
+
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_NETINET_TCP_H
+#include <netinet/tcp.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <functional>
+#include <sstream>
+
+#ifdef WIN32
+#define BYTE_CAST (char *)
+#define mkdir_(d, p) mkdir(d)
+#else
+#define BYTE_CAST
+#define mkdir_(d, p) mkdir(d, p)
+#endif
+
+namespace ares {
+namespace test {
+
+bool verbose = false;
+int mock_port = 5300;
+
+const std::vector<int> both_families = {AF_INET, AF_INET6};
+const std::vector<int> ipv4_family = {AF_INET};
+const std::vector<int> ipv6_family = {AF_INET6};
+
+const std::vector<std::pair<int, bool>> both_families_both_modes = {
+ std::make_pair<int, bool>(AF_INET, false),
+ std::make_pair<int, bool>(AF_INET, true),
+ std::make_pair<int, bool>(AF_INET6, false),
+ std::make_pair<int, bool>(AF_INET6, true)
+};
+const std::vector<std::pair<int, bool>> ipv4_family_both_modes = {
+ std::make_pair<int, bool>(AF_INET, false),
+ std::make_pair<int, bool>(AF_INET, true)
+};
+const std::vector<std::pair<int, bool>> ipv6_family_both_modes = {
+ std::make_pair<int, bool>(AF_INET6, false),
+ std::make_pair<int, bool>(AF_INET6, true)
+};
+
+// Which parameters to use in tests
+std::vector<int> families = both_families;
+std::vector<std::pair<int, bool>> families_modes = both_families_both_modes;
+
+unsigned long long LibraryTest::fails_ = 0;
+std::map<size_t, int> LibraryTest::size_fails_;
+
+void ProcessWork(ares_channel channel,
+ std::function<std::set<int>()> get_extrafds,
+ std::function<void(int)> process_extra) {
+ int nfds, count;
+ fd_set readers, writers;
+ struct timeval tv;
+ while (true) {
+ // Retrieve the set of file descriptors that the library wants us to monitor.
+ FD_ZERO(&readers);
+ FD_ZERO(&writers);
+ nfds = ares_fds(channel, &readers, &writers);
+ if (nfds == 0) // no work left to do in the library
+ return;
+
+ // Add in the extra FDs if present.
+ std::set<int> extrafds = get_extrafds();
+ for (int extrafd : extrafds) {
+ FD_SET(extrafd, &readers);
+ if (extrafd >= nfds) {
+ nfds = extrafd + 1;
+ }
+ }
+
+ // Wait for activity or timeout.
+ tv.tv_sec = 0;
+ tv.tv_usec = 100000; // 100ms
+ count = select(nfds, &readers, &writers, nullptr, &tv);
+ if (count < 0) {
+ fprintf(stderr, "select() failed, errno %d\n", errno);
+ return;
+ }
+
+ // Let the library process any activity.
+ ares_process(channel, &readers, &writers);
+
+ // Let the provided callback process any activity on the extra FD.
+ for (int extrafd : extrafds) {
+ if (FD_ISSET(extrafd, &readers)) {
+ process_extra(extrafd);
+ }
+ }
+ }
+}
+
+// static
+void LibraryTest::SetAllocFail(int nth) {
+ assert(nth > 0);
+ assert(nth <= (int)(8 * sizeof(fails_)));
+ fails_ |= (1LL << (nth - 1));
+}
+
+// static
+void LibraryTest::SetAllocSizeFail(size_t size) {
+ size_fails_[size]++;
+}
+
+// static
+void LibraryTest::ClearFails() {
+ fails_ = 0;
+ size_fails_.clear();
+}
+
+
+// static
+bool LibraryTest::ShouldAllocFail(size_t size) {
+ bool fail = (fails_ & 0x01);
+ fails_ >>= 1;
+ if (size_fails_[size] > 0) {
+ size_fails_[size]--;
+ fail = true;
+ }
+ return fail;
+}
+
+// static
+void* LibraryTest::amalloc(size_t size) {
+ if (ShouldAllocFail(size)) {
+ if (verbose) std::cerr << "Failing malloc(" << size << ") request" << std::endl;
+ return nullptr;
+ } else {
+ return malloc(size);
+ }
+}
+
+// static
+void* LibraryTest::arealloc(void *ptr, size_t size) {
+ if (ShouldAllocFail(size)) {
+ if (verbose) std::cerr << "Failing realloc(" << ptr << ", " << size << ") request" << std::endl;
+ return nullptr;
+ } else {
+ return realloc(ptr, size);
+ }
+}
+
+// static
+void LibraryTest::afree(void *ptr) {
+ free(ptr);
+}
+
+std::set<int> NoExtraFDs() {
+ return std::set<int>();
+}
+
+void DefaultChannelTest::Process() {
+ ProcessWork(channel_, NoExtraFDs, nullptr);
+}
+
+void DefaultChannelModeTest::Process() {
+ ProcessWork(channel_, NoExtraFDs, nullptr);
+}
+
+MockServer::MockServer(int family, int port, int tcpport)
+ : udpport_(port), tcpport_(tcpport ? tcpport : udpport_), qid_(-1) {
+ // Create a TCP socket to receive data on.
+ tcpfd_ = socket(family, SOCK_STREAM, 0);
+ EXPECT_NE(-1, tcpfd_);
+ int optval = 1;
+ setsockopt(tcpfd_, SOL_SOCKET, SO_REUSEADDR,
+ BYTE_CAST &optval , sizeof(int));
+ // Send TCP data right away.
+ setsockopt(tcpfd_, IPPROTO_TCP, TCP_NODELAY,
+ BYTE_CAST &optval , sizeof(int));
+
+ // Create a UDP socket to receive data on.
+ udpfd_ = socket(family, SOCK_DGRAM, 0);
+ EXPECT_NE(-1, udpfd_);
+
+ // Bind the sockets to the given port.
+ if (family == AF_INET) {
+ struct sockaddr_in addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl(INADDR_ANY);
+ addr.sin_port = htons(tcpport_);
+ int tcprc = bind(tcpfd_, (struct sockaddr*)&addr, sizeof(addr));
+ EXPECT_EQ(0, tcprc) << "Failed to bind AF_INET to TCP port " << tcpport_;
+ addr.sin_port = htons(udpport_);
+ int udprc = bind(udpfd_, (struct sockaddr*)&addr, sizeof(addr));
+ EXPECT_EQ(0, udprc) << "Failed to bind AF_INET to UDP port " << udpport_;
+ } else {
+ EXPECT_EQ(AF_INET6, family);
+ struct sockaddr_in6 addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sin6_family = AF_INET6;
+ memset(&addr.sin6_addr, 0, sizeof(addr.sin6_addr)); // in6addr_any
+ addr.sin6_port = htons(tcpport_);
+ int tcprc = bind(tcpfd_, (struct sockaddr*)&addr, sizeof(addr));
+ EXPECT_EQ(0, tcprc) << "Failed to bind AF_INET6 to TCP port " << tcpport_;
+ addr.sin6_port = htons(udpport_);
+ int udprc = bind(udpfd_, (struct sockaddr*)&addr, sizeof(addr));
+ EXPECT_EQ(0, udprc) << "Failed to bind AF_INET6 to UDP port " << udpport_;
+ }
+ if (verbose) std::cerr << "Configured "
+ << (family == AF_INET ? "IPv4" : "IPv6")
+ << " mock server with TCP socket " << tcpfd_
+ << " on port " << tcpport_
+ << " and UDP socket " << udpfd_
+ << " on port " << udpport_ << std::endl;
+
+ // For TCP, also need to listen for connections.
+ EXPECT_EQ(0, listen(tcpfd_, 5)) << "Failed to listen for TCP connections";
+}
+
+MockServer::~MockServer() {
+ for (int fd : connfds_) {
+ sclose(fd);
+ }
+ sclose(tcpfd_);
+ sclose(udpfd_);
+}
+
+void MockServer::ProcessFD(int fd) {
+ if (fd != tcpfd_ && fd != udpfd_ && connfds_.find(fd) == connfds_.end()) {
+ // Not one of our FDs.
+ return;
+ }
+ if (fd == tcpfd_) {
+ int connfd = accept(tcpfd_, NULL, NULL);
+ if (connfd < 0) {
+ std::cerr << "Error accepting connection on fd " << fd << std::endl;
+ } else {
+ connfds_.insert(connfd);
+ }
+ return;
+ }
+
+ // Activity on a data-bearing file descriptor.
+ struct sockaddr_storage addr;
+ socklen_t addrlen = sizeof(addr);
+ byte buffer[2048];
+ int len = recvfrom(fd, BYTE_CAST buffer, sizeof(buffer), 0,
+ (struct sockaddr *)&addr, &addrlen);
+ byte* data = buffer;
+ if (fd != udpfd_) {
+ if (len == 0) {
+ connfds_.erase(std::find(connfds_.begin(), connfds_.end(), fd));
+ sclose(fd);
+ return;
+ }
+ if (len < 2) {
+ std::cerr << "Packet too short (" << len << ")" << std::endl;
+ return;
+ }
+ int tcplen = (data[0] << 8) + data[1];
+ data += 2;
+ len -= 2;
+ if (tcplen != len) {
+ std::cerr << "Warning: TCP length " << tcplen
+ << " doesn't match remaining data length " << len << std::endl;
+ }
+ }
+
+ // Assume the packet is a well-formed DNS request and extract the request
+ // details.
+ if (len < NS_HFIXEDSZ) {
+ std::cerr << "Packet too short (" << len << ")" << std::endl;
+ return;
+ }
+ int qid = DNS_HEADER_QID(data);
+ if (DNS_HEADER_QR(data) != 0) {
+ std::cerr << "Not a request" << std::endl;
+ return;
+ }
+ if (DNS_HEADER_OPCODE(data) != ns_o_query) {
+ std::cerr << "Not a query (opcode " << DNS_HEADER_OPCODE(data)
+ << ")" << std::endl;
+ return;
+ }
+ if (DNS_HEADER_QDCOUNT(data) != 1) {
+ std::cerr << "Unexpected question count (" << DNS_HEADER_QDCOUNT(data)
+ << ")" << std::endl;
+ return;
+ }
+ byte* question = data + 12;
+ int qlen = len - 12;
+
+ char *name = nullptr;
+ long enclen;
+ ares_expand_name(question, data, len, &name, &enclen);
+ if (!name) {
+ std::cerr << "Failed to retrieve name" << std::endl;
+ return;
+ }
+ qlen -= enclen;
+ question += enclen;
+ std::string namestr(name);
+ ares_free_string(name);
+
+ if (qlen < 4) {
+ std::cerr << "Unexpected question size (" << qlen
+ << " bytes after name)" << std::endl;
+ return;
+ }
+ if (DNS_QUESTION_CLASS(question) != ns_c_in) {
+ std::cerr << "Unexpected question class (" << DNS_QUESTION_CLASS(question)
+ << ")" << std::endl;
+ return;
+ }
+ int rrtype = DNS_QUESTION_TYPE(question);
+
+ if (verbose) {
+ std::vector<byte> req(data, data + len);
+ std::cerr << "received " << (fd == udpfd_ ? "UDP" : "TCP") << " request " << PacketToString(req)
+ << " on port " << (fd == udpfd_ ? udpport_ : tcpport_) << std::endl;
+ std::cerr << "ProcessRequest(" << qid << ", '" << namestr
+ << "', " << RRTypeToString(rrtype) << ")" << std::endl;
+ }
+ ProcessRequest(fd, &addr, addrlen, qid, namestr, rrtype);
+}
+
+std::set<int> MockServer::fds() const {
+ std::set<int> result = connfds_;
+ result.insert(tcpfd_);
+ result.insert(udpfd_);
+ return result;
+}
+
+void MockServer::ProcessRequest(int fd, struct sockaddr_storage* addr, int addrlen,
+ int qid, const std::string& name, int rrtype) {
+ // Before processing, let gMock know the request is happening.
+ OnRequest(name, rrtype);
+
+ if (reply_.size() == 0) {
+ return;
+ }
+
+ // Make a local copy of the current pending reply.
+ std::vector<byte> reply = reply_;
+
+ if (qid_ >= 0) {
+ // Use the explicitly specified query ID.
+ qid = qid_;
+ }
+ if (reply.size() >= 2) {
+ // Overwrite the query ID if space to do so.
+ reply[0] = (byte)((qid >> 8) & 0xff);
+ reply[1] = (byte)(qid & 0xff);
+ }
+ if (verbose) std::cerr << "sending reply " << PacketToString(reply)
+ << " on port " << ((fd == udpfd_) ? udpport_ : tcpport_) << std::endl;
+
+ // Prefix with 2-byte length if TCP.
+ if (fd != udpfd_) {
+ int len = reply.size();
+ std::vector<byte> vlen = {(byte)((len & 0xFF00) >> 8), (byte)(len & 0xFF)};
+ reply.insert(reply.begin(), vlen.begin(), vlen.end());
+ // Also, don't bother with the destination address.
+ addr = nullptr;
+ addrlen = 0;
+ }
+
+ int rc = sendto(fd, BYTE_CAST reply.data(), reply.size(), 0,
+ (struct sockaddr *)addr, addrlen);
+ if (rc < static_cast<int>(reply.size())) {
+ std::cerr << "Failed to send full reply, rc=" << rc << std::endl;
+ }
+}
+
+// static
+MockChannelOptsTest::NiceMockServers MockChannelOptsTest::BuildServers(int count, int family, int base_port) {
+ NiceMockServers servers;
+ assert(count > 0);
+ for (int ii = 0; ii < count; ii++) {
+ std::unique_ptr<NiceMockServer> server(new NiceMockServer(family, base_port + ii));
+ servers.push_back(std::move(server));
+ }
+ return servers;
+}
+
+MockChannelOptsTest::MockChannelOptsTest(int count,
+ int family,
+ bool force_tcp,
+ struct ares_options* givenopts,
+ int optmask)
+ : servers_(BuildServers(count, family, mock_port)),
+ server_(*servers_[0].get()), channel_(nullptr) {
+ // Set up channel options.
+ struct ares_options opts;
+ if (givenopts) {
+ memcpy(&opts, givenopts, sizeof(opts));
+ } else {
+ memset(&opts, 0, sizeof(opts));
+ }
+
+ // Point the library at the first mock server by default (overridden below).
+ opts.udp_port = mock_port;
+ optmask |= ARES_OPT_UDP_PORT;
+ opts.tcp_port = mock_port;
+ optmask |= ARES_OPT_TCP_PORT;
+
+ // If not already overridden, set short-ish timeouts.
+ if (!(optmask & (ARES_OPT_TIMEOUTMS|ARES_OPT_TIMEOUT))) {
+ opts.timeout = 1500;
+ optmask |= ARES_OPT_TIMEOUTMS;
+ }
+ // If not already overridden, set 3 retries.
+ if (!(optmask & ARES_OPT_TRIES)) {
+ opts.tries = 3;
+ optmask |= ARES_OPT_TRIES;
+ }
+ // If not already overridden, set search domains.
+ const char *domains[3] = {"first.com", "second.org", "third.gov"};
+ if (!(optmask & ARES_OPT_DOMAINS)) {
+ opts.ndomains = 3;
+ opts.domains = (char**)domains;
+ optmask |= ARES_OPT_DOMAINS;
+ }
+ if (force_tcp) {
+ opts.flags |= ARES_FLAG_USEVC;
+ optmask |= ARES_OPT_FLAGS;
+ }
+
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel_, &opts, optmask));
+ EXPECT_NE(nullptr, channel_);
+
+ // Set up servers after construction so we can set individual ports
+ struct ares_addr_port_node* prev = nullptr;
+ struct ares_addr_port_node* first = nullptr;
+ for (const auto& server : servers_) {
+ struct ares_addr_port_node* node = (struct ares_addr_port_node*)malloc(sizeof(*node));
+ if (prev) {
+ prev->next = node;
+ } else {
+ first = node;
+ }
+ node->next = nullptr;
+ node->family = family;
+ node->udp_port = server->udpport();
+ node->tcp_port = server->tcpport();
+ if (family == AF_INET) {
+ node->addr.addr4.s_addr = htonl(0x7F000001);
+ } else {
+ memset(&node->addr.addr6, 0, sizeof(node->addr.addr6));
+ node->addr.addr6._S6_un._S6_u8[15] = 1;
+ }
+ prev = node;
+ }
+ EXPECT_EQ(ARES_SUCCESS, ares_set_servers_ports(channel_, first));
+
+ while (first) {
+ prev = first;
+ first = first->next;
+ free(prev);
+ }
+ if (verbose) {
+ std::cerr << "Configured library with servers:";
+ std::vector<std::string> servers = GetNameServers(channel_);
+ for (const auto& server : servers) {
+ std::cerr << " " << server;
+ }
+ std::cerr << std::endl;
+ }
+}
+
+MockChannelOptsTest::~MockChannelOptsTest() {
+ if (channel_) {
+ ares_destroy(channel_);
+ }
+ channel_ = nullptr;
+}
+
+std::set<int> MockChannelOptsTest::fds() const {
+ std::set<int> fds;
+ for (const auto& server : servers_) {
+ std::set<int> serverfds = server->fds();
+ fds.insert(serverfds.begin(), serverfds.end());
+ }
+ return fds;
+}
+
+void MockChannelOptsTest::ProcessFD(int fd) {
+ for (auto& server : servers_) {
+ server->ProcessFD(fd);
+ }
+}
+
+void MockChannelOptsTest::Process() {
+ using namespace std::placeholders;
+ ProcessWork(channel_,
+ std::bind(&MockChannelOptsTest::fds, this),
+ std::bind(&MockChannelOptsTest::ProcessFD, this, _1));
+}
+
+std::ostream& operator<<(std::ostream& os, const HostResult& result) {
+ os << '{';
+ if (result.done_) {
+ os << StatusToString(result.status_) << " " << result.host_;
+ } else {
+ os << "(incomplete)";
+ }
+ os << '}';
+ return os;
+}
+
+HostEnt::HostEnt(const struct hostent *hostent) : addrtype_(-1) {
+ if (!hostent)
+ return;
+ if (hostent->h_name)
+ name_ = hostent->h_name;
+ if (hostent->h_aliases) {
+ char** palias = hostent->h_aliases;
+ while (*palias != nullptr) {
+ aliases_.push_back(*palias);
+ palias++;
+ }
+ }
+ addrtype_ = hostent->h_addrtype;
+ if (hostent->h_addr_list) {
+ char** paddr = hostent->h_addr_list;
+ while (*paddr != nullptr) {
+ std::string addr = AddressToString(*paddr, hostent->h_length);
+ addrs_.push_back(addr);
+ paddr++;
+ }
+ }
+}
+
+std::ostream& operator<<(std::ostream& os, const HostEnt& host) {
+ os << '{';
+ os << "'" << host.name_ << "' "
+ << "aliases=[";
+ for (size_t ii = 0; ii < host.aliases_.size(); ii++) {
+ if (ii > 0) os << ", ";
+ os << host.aliases_[ii];
+ }
+ os << "] ";
+ os << "addrs=[";
+ for (size_t ii = 0; ii < host.addrs_.size(); ii++) {
+ if (ii > 0) os << ", ";
+ os << host.addrs_[ii];
+ }
+ os << "]";
+ os << '}';
+ return os;
+}
+
+void HostCallback(void *data, int status, int timeouts,
+ struct hostent *hostent) {
+ EXPECT_NE(nullptr, data);
+ HostResult* result = reinterpret_cast<HostResult*>(data);
+ result->done_ = true;
+ result->status_ = status;
+ result->timeouts_ = timeouts;
+ result->host_ = HostEnt(hostent);
+ if (verbose) std::cerr << "HostCallback(" << *result << ")" << std::endl;
+}
+
std::ostream& operator<<(std::ostream& os, const AddrInfoResult& result) {
os << '{';
if (result.done_ && result.ai_) {
@@ -638,135 +638,135 @@ void AddrInfoCallback(void *data, int status, int timeouts,
if (verbose) std::cerr << "AddrInfoCallback(" << *result << ")" << std::endl;
}
-std::ostream& operator<<(std::ostream& os, const SearchResult& result) {
- os << '{';
- if (result.done_) {
- os << StatusToString(result.status_) << " " << PacketToString(result.data_);
- } else {
- os << "(incomplete)";
- }
- os << '}';
- return os;
-}
-
-void SearchCallback(void *data, int status, int timeouts,
- unsigned char *abuf, int alen) {
- EXPECT_NE(nullptr, data);
- SearchResult* result = reinterpret_cast<SearchResult*>(data);
- result->done_ = true;
- result->status_ = status;
- result->timeouts_ = timeouts;
- result->data_.assign(abuf, abuf + alen);
- if (verbose) std::cerr << "SearchCallback(" << *result << ")" << std::endl;
-}
-
-std::ostream& operator<<(std::ostream& os, const NameInfoResult& result) {
- os << '{';
- if (result.done_) {
- os << StatusToString(result.status_) << " " << result.node_ << " " << result.service_;
- } else {
- os << "(incomplete)";
- }
- os << '}';
- return os;
-}
-
-void NameInfoCallback(void *data, int status, int timeouts,
- char *node, char *service) {
- EXPECT_NE(nullptr, data);
- NameInfoResult* result = reinterpret_cast<NameInfoResult*>(data);
- result->done_ = true;
- result->status_ = status;
- result->timeouts_ = timeouts;
- result->node_ = std::string(node ? node : "");
- result->service_ = std::string(service ? service : "");
- if (verbose) std::cerr << "NameInfoCallback(" << *result << ")" << std::endl;
-}
-
-std::vector<std::string> GetNameServers(ares_channel channel) {
- struct ares_addr_port_node* servers = nullptr;
- EXPECT_EQ(ARES_SUCCESS, ares_get_servers_ports(channel, &servers));
- struct ares_addr_port_node* server = servers;
- std::vector<std::string> results;
- while (server) {
- std::stringstream ss;
- switch (server->family) {
- case AF_INET:
- ss << AddressToString((char*)&server->addr.addr4, 4);
- break;
- case AF_INET6:
- if (server->udp_port != 0) {
- ss << '[';
- }
- ss << AddressToString((char*)&server->addr.addr6, 16);
- if (server->udp_port != 0) {
- ss << ']';
- }
- break;
- default:
- results.push_back("<unknown family>");
- break;
- }
- if (server->udp_port != 0) {
- ss << ":" << server->udp_port;
- }
- results.push_back(ss.str());
- server = server->next;
- }
- if (servers) ares_free_data(servers);
- return results;
-}
-
-TransientDir::TransientDir(const std::string& dirname) : dirname_(dirname) {
- if (mkdir_(dirname_.c_str(), 0755) != 0) {
- std::cerr << "Failed to create subdirectory '" << dirname_ << "'" << std::endl;
- }
-}
-
-TransientDir::~TransientDir() {
- rmdir(dirname_.c_str());
-}
-
-TransientFile::TransientFile(const std::string& filename,
- const std::string& contents)
- : filename_(filename) {
- FILE *f = fopen(filename.c_str(), "w");
- if (f == nullptr) {
- std::cerr << "Error: failed to create '" << filename << "'" << std::endl;
- return;
- }
- int rc = fwrite(contents.data(), 1, contents.size(), f);
- if (rc != (int)contents.size()) {
- std::cerr << "Error: failed to write contents of '" << filename << "'" << std::endl;
- }
- fclose(f);
-}
-
-TransientFile::~TransientFile() {
- unlink(filename_.c_str());
-}
-
-std::string TempNam(const char *dir, const char *prefix) {
- char *p = tempnam(dir, prefix);
- std::string result(p);
- free(p);
- return result;
-}
-
-TempFile::TempFile(const std::string& contents)
- : TransientFile(TempNam(nullptr, "ares"), contents) {
-
-}
-
-VirtualizeIO::VirtualizeIO(ares_channel c)
- : channel_(c)
-{
- ares_set_socket_functions(channel_, &default_functions, 0);
-}
-
-VirtualizeIO::~VirtualizeIO() {
- ares_set_socket_functions(channel_, 0, 0);
-}
-
-} // namespace test
-} // namespace ares
+std::ostream& operator<<(std::ostream& os, const SearchResult& result) {
+ os << '{';
+ if (result.done_) {
+ os << StatusToString(result.status_) << " " << PacketToString(result.data_);
+ } else {
+ os << "(incomplete)";
+ }
+ os << '}';
+ return os;
+}
+
+void SearchCallback(void *data, int status, int timeouts,
+ unsigned char *abuf, int alen) {
+ EXPECT_NE(nullptr, data);
+ SearchResult* result = reinterpret_cast<SearchResult*>(data);
+ result->done_ = true;
+ result->status_ = status;
+ result->timeouts_ = timeouts;
+ result->data_.assign(abuf, abuf + alen);
+ if (verbose) std::cerr << "SearchCallback(" << *result << ")" << std::endl;
+}
+
+std::ostream& operator<<(std::ostream& os, const NameInfoResult& result) {
+ os << '{';
+ if (result.done_) {
+ os << StatusToString(result.status_) << " " << result.node_ << " " << result.service_;
+ } else {
+ os << "(incomplete)";
+ }
+ os << '}';
+ return os;
+}
+
+void NameInfoCallback(void *data, int status, int timeouts,
+ char *node, char *service) {
+ EXPECT_NE(nullptr, data);
+ NameInfoResult* result = reinterpret_cast<NameInfoResult*>(data);
+ result->done_ = true;
+ result->status_ = status;
+ result->timeouts_ = timeouts;
+ result->node_ = std::string(node ? node : "");
+ result->service_ = std::string(service ? service : "");
+ if (verbose) std::cerr << "NameInfoCallback(" << *result << ")" << std::endl;
+}
+
+std::vector<std::string> GetNameServers(ares_channel channel) {
+ struct ares_addr_port_node* servers = nullptr;
+ EXPECT_EQ(ARES_SUCCESS, ares_get_servers_ports(channel, &servers));
+ struct ares_addr_port_node* server = servers;
+ std::vector<std::string> results;
+ while (server) {
+ std::stringstream ss;
+ switch (server->family) {
+ case AF_INET:
+ ss << AddressToString((char*)&server->addr.addr4, 4);
+ break;
+ case AF_INET6:
+ if (server->udp_port != 0) {
+ ss << '[';
+ }
+ ss << AddressToString((char*)&server->addr.addr6, 16);
+ if (server->udp_port != 0) {
+ ss << ']';
+ }
+ break;
+ default:
+ results.push_back("<unknown family>");
+ break;
+ }
+ if (server->udp_port != 0) {
+ ss << ":" << server->udp_port;
+ }
+ results.push_back(ss.str());
+ server = server->next;
+ }
+ if (servers) ares_free_data(servers);
+ return results;
+}
+
+TransientDir::TransientDir(const std::string& dirname) : dirname_(dirname) {
+ if (mkdir_(dirname_.c_str(), 0755) != 0) {
+ std::cerr << "Failed to create subdirectory '" << dirname_ << "'" << std::endl;
+ }
+}
+
+TransientDir::~TransientDir() {
+ rmdir(dirname_.c_str());
+}
+
+TransientFile::TransientFile(const std::string& filename,
+ const std::string& contents)
+ : filename_(filename) {
+ FILE *f = fopen(filename.c_str(), "w");
+ if (f == nullptr) {
+ std::cerr << "Error: failed to create '" << filename << "'" << std::endl;
+ return;
+ }
+ int rc = fwrite(contents.data(), 1, contents.size(), f);
+ if (rc != (int)contents.size()) {
+ std::cerr << "Error: failed to write contents of '" << filename << "'" << std::endl;
+ }
+ fclose(f);
+}
+
+TransientFile::~TransientFile() {
+ unlink(filename_.c_str());
+}
+
+std::string TempNam(const char *dir, const char *prefix) {
+ char *p = tempnam(dir, prefix);
+ std::string result(p);
+ free(p);
+ return result;
+}
+
+TempFile::TempFile(const std::string& contents)
+ : TransientFile(TempNam(nullptr, "ares"), contents) {
+
+}
+
+VirtualizeIO::VirtualizeIO(ares_channel c)
+ : channel_(c)
+{
+ ares_set_socket_functions(channel_, &default_functions, 0);
+}
+
+VirtualizeIO::~VirtualizeIO() {
+ ares_set_socket_functions(channel_, 0, 0);
+}
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/ares-test.h b/contrib/libs/c-ares/test/ares-test.h
index fd3bc31c27..a905702aef 100644
--- a/contrib/libs/c-ares/test/ares-test.h
+++ b/contrib/libs/c-ares/test/ares-test.h
@@ -1,281 +1,281 @@
-// -*- mode: c++ -*-
-#ifndef ARES_TEST_H
-#define ARES_TEST_H
-
-#include "dns-proto.h"
-// Include ares internal file for DNS protocol constants
-#include "nameser.h"
-
-#include "ares_setup.h"
-#include "ares.h"
-
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-
-#if defined(HAVE_USER_NAMESPACE) && defined(HAVE_UTS_NAMESPACE)
-#define HAVE_CONTAINER
-#endif
-
-#include <functional>
-#include <list>
-#include <map>
-#include <memory>
-#include <set>
-#include <string>
-#include <utility>
-#include <vector>
-
-namespace ares {
-
-typedef unsigned char byte;
-
-namespace test {
-
-extern bool verbose;
-extern int mock_port;
-extern const std::vector<int> both_families;
-extern const std::vector<int> ipv4_family;
-extern const std::vector<int> ipv6_family;
-
-extern const std::vector<std::pair<int, bool>> both_families_both_modes;
-extern const std::vector<std::pair<int, bool>> ipv4_family_both_modes;
-extern const std::vector<std::pair<int, bool>> ipv6_family_both_modes;
-
-// Which parameters to use in tests
-extern std::vector<int> families;
-extern std::vector<std::pair<int, bool>> families_modes;
-
-// Process all pending work on ares-owned file descriptors, plus
-// optionally the given set-of-FDs + work function.
-void ProcessWork(ares_channel channel,
- std::function<std::set<int>()> get_extrafds,
- std::function<void(int)> process_extra);
-std::set<int> NoExtraFDs();
-
-// Test fixture that ensures library initialization, and allows
-// memory allocations to be failed.
-class LibraryTest : public ::testing::Test {
- public:
- LibraryTest() {
- EXPECT_EQ(ARES_SUCCESS,
- ares_library_init_mem(ARES_LIB_INIT_ALL,
- &LibraryTest::amalloc,
- &LibraryTest::afree,
- &LibraryTest::arealloc));
- }
- ~LibraryTest() {
- ares_library_cleanup();
- ClearFails();
- }
- // Set the n-th malloc call (of any size) from the library to fail.
- // (nth == 1 means the next call)
- static void SetAllocFail(int nth);
- // Set the next malloc call for the given size to fail.
- static void SetAllocSizeFail(size_t size);
- // Remove any pending alloc failures.
- static void ClearFails();
-
- static void *amalloc(size_t size);
- static void* arealloc(void *ptr, size_t size);
- static void afree(void *ptr);
- private:
- static bool ShouldAllocFail(size_t size);
- static unsigned long long fails_;
- static std::map<size_t, int> size_fails_;
-};
-
-// Test fixture that uses a default channel.
-class DefaultChannelTest : public LibraryTest {
- public:
- DefaultChannelTest() : channel_(nullptr) {
- EXPECT_EQ(ARES_SUCCESS, ares_init(&channel_));
- EXPECT_NE(nullptr, channel_);
- }
-
- ~DefaultChannelTest() {
- ares_destroy(channel_);
- channel_ = nullptr;
- }
-
- // Process all pending work on ares-owned file descriptors.
- void Process();
-
- protected:
- ares_channel channel_;
-};
-
-// Test fixture that uses a default channel with the specified lookup mode.
-class DefaultChannelModeTest
- : public LibraryTest,
- public ::testing::WithParamInterface<std::string> {
- public:
- DefaultChannelModeTest() : channel_(nullptr) {
- struct ares_options opts = {0};
- opts.lookups = strdup(GetParam().c_str());
- int optmask = ARES_OPT_LOOKUPS;
- EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel_, &opts, optmask));
- EXPECT_NE(nullptr, channel_);
- free(opts.lookups);
- }
-
- ~DefaultChannelModeTest() {
- ares_destroy(channel_);
- channel_ = nullptr;
- }
-
- // Process all pending work on ares-owned file descriptors.
- void Process();
-
- protected:
- ares_channel channel_;
-};
-
-// Mock DNS server to allow responses to be scripted by tests.
-class MockServer {
- public:
- MockServer(int family, int port, int tcpport = 0);
- ~MockServer();
-
- // Mock method indicating the processing of a particular <name, RRtype>
- // request.
- MOCK_METHOD2(OnRequest, void(const std::string& name, int rrtype));
-
- // Set the reply to be sent next; the query ID field will be overwritten
- // with the value from the request.
- void SetReplyData(const std::vector<byte>& reply) { reply_ = reply; }
- void SetReply(const DNSPacket* reply) { SetReplyData(reply->data()); }
- void SetReplyQID(int qid) { qid_ = qid; }
-
- // The set of file descriptors that the server handles.
- std::set<int> fds() const;
-
- // Process activity on a file descriptor.
- void ProcessFD(int fd);
-
- // Ports the server is responding to
- int udpport() const { return udpport_; }
- int tcpport() const { return tcpport_; }
-
- private:
- void ProcessRequest(int fd, struct sockaddr_storage* addr, int addrlen,
- int qid, const std::string& name, int rrtype);
-
- int udpport_;
- int tcpport_;
- int udpfd_;
- int tcpfd_;
- std::set<int> connfds_;
- std::vector<byte> reply_;
- int qid_;
-};
-
-// Test fixture that uses a mock DNS server.
-class MockChannelOptsTest : public LibraryTest {
- public:
- MockChannelOptsTest(int count, int family, bool force_tcp, struct ares_options* givenopts, int optmask);
- ~MockChannelOptsTest();
-
- // Process all pending work on ares-owned and mock-server-owned file descriptors.
- void Process();
-
- protected:
- // NiceMockServer doesn't complain about uninteresting calls.
- typedef testing::NiceMock<MockServer> NiceMockServer;
- typedef std::vector< std::unique_ptr<NiceMockServer> > NiceMockServers;
-
- std::set<int> fds() const;
- void ProcessFD(int fd);
-
- static NiceMockServers BuildServers(int count, int family, int base_port);
-
- NiceMockServers servers_;
- // Convenience reference to first server.
- NiceMockServer& server_;
- ares_channel channel_;
-};
-
-class MockChannelTest
- : public MockChannelOptsTest,
- public ::testing::WithParamInterface< std::pair<int, bool> > {
- public:
- MockChannelTest() : MockChannelOptsTest(1, GetParam().first, GetParam().second, nullptr, 0) {}
-};
-
-class MockUDPChannelTest
- : public MockChannelOptsTest,
- public ::testing::WithParamInterface<int> {
- public:
- MockUDPChannelTest() : MockChannelOptsTest(1, GetParam(), false, nullptr, 0) {}
-};
-
-class MockTCPChannelTest
- : public MockChannelOptsTest,
- public ::testing::WithParamInterface<int> {
- public:
- MockTCPChannelTest() : MockChannelOptsTest(1, GetParam(), true, nullptr, 0) {}
-};
-
-// gMock action to set the reply for a mock server.
-ACTION_P2(SetReplyData, mockserver, data) {
- mockserver->SetReplyData(data);
-}
-ACTION_P2(SetReply, mockserver, reply) {
- mockserver->SetReply(reply);
-}
-ACTION_P2(SetReplyQID, mockserver, qid) {
- mockserver->SetReplyQID(qid);
-}
-// gMock action to cancel a channel.
-ACTION_P2(CancelChannel, mockserver, channel) {
- ares_cancel(channel);
-}
-
-// C++ wrapper for struct hostent.
-struct HostEnt {
- HostEnt() : addrtype_(-1) {}
- HostEnt(const struct hostent* hostent);
- std::string name_;
- std::vector<std::string> aliases_;
- int addrtype_; // AF_INET or AF_INET6
- std::vector<std::string> addrs_;
-};
-std::ostream& operator<<(std::ostream& os, const HostEnt& result);
-
-// Structure that describes the result of an ares_host_callback invocation.
-struct HostResult {
- // Whether the callback has been invoked.
- bool done_;
- // Explicitly provided result information.
- int status_;
- int timeouts_;
- // Contents of the hostent structure, if provided.
- HostEnt host_;
-};
-std::ostream& operator<<(std::ostream& os, const HostResult& result);
-
-// Structure that describes the result of an ares_callback invocation.
-struct SearchResult {
- // Whether the callback has been invoked.
- bool done_;
- // Explicitly provided result information.
- int status_;
- int timeouts_;
- std::vector<byte> data_;
-};
-std::ostream& operator<<(std::ostream& os, const SearchResult& result);
-
-// Structure that describes the result of an ares_nameinfo_callback invocation.
-struct NameInfoResult {
- // Whether the callback has been invoked.
- bool done_;
- // Explicitly provided result information.
- int status_;
- int timeouts_;
- std::string node_;
- std::string service_;
-};
-std::ostream& operator<<(std::ostream& os, const NameInfoResult& result);
-
+// -*- mode: c++ -*-
+#ifndef ARES_TEST_H
+#define ARES_TEST_H
+
+#include "dns-proto.h"
+// Include ares internal file for DNS protocol constants
+#include "nameser.h"
+
+#include "ares_setup.h"
+#include "ares.h"
+
+#include "gtest/gtest.h"
+#include "gmock/gmock.h"
+
+#if defined(HAVE_USER_NAMESPACE) && defined(HAVE_UTS_NAMESPACE)
+#define HAVE_CONTAINER
+#endif
+
+#include <functional>
+#include <list>
+#include <map>
+#include <memory>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace ares {
+
+typedef unsigned char byte;
+
+namespace test {
+
+extern bool verbose;
+extern int mock_port;
+extern const std::vector<int> both_families;
+extern const std::vector<int> ipv4_family;
+extern const std::vector<int> ipv6_family;
+
+extern const std::vector<std::pair<int, bool>> both_families_both_modes;
+extern const std::vector<std::pair<int, bool>> ipv4_family_both_modes;
+extern const std::vector<std::pair<int, bool>> ipv6_family_both_modes;
+
+// Which parameters to use in tests
+extern std::vector<int> families;
+extern std::vector<std::pair<int, bool>> families_modes;
+
+// Process all pending work on ares-owned file descriptors, plus
+// optionally the given set-of-FDs + work function.
+void ProcessWork(ares_channel channel,
+ std::function<std::set<int>()> get_extrafds,
+ std::function<void(int)> process_extra);
+std::set<int> NoExtraFDs();
+
+// Test fixture that ensures library initialization, and allows
+// memory allocations to be failed.
+class LibraryTest : public ::testing::Test {
+ public:
+ LibraryTest() {
+ EXPECT_EQ(ARES_SUCCESS,
+ ares_library_init_mem(ARES_LIB_INIT_ALL,
+ &LibraryTest::amalloc,
+ &LibraryTest::afree,
+ &LibraryTest::arealloc));
+ }
+ ~LibraryTest() {
+ ares_library_cleanup();
+ ClearFails();
+ }
+ // Set the n-th malloc call (of any size) from the library to fail.
+ // (nth == 1 means the next call)
+ static void SetAllocFail(int nth);
+ // Set the next malloc call for the given size to fail.
+ static void SetAllocSizeFail(size_t size);
+ // Remove any pending alloc failures.
+ static void ClearFails();
+
+ static void *amalloc(size_t size);
+ static void* arealloc(void *ptr, size_t size);
+ static void afree(void *ptr);
+ private:
+ static bool ShouldAllocFail(size_t size);
+ static unsigned long long fails_;
+ static std::map<size_t, int> size_fails_;
+};
+
+// Test fixture that uses a default channel.
+class DefaultChannelTest : public LibraryTest {
+ public:
+ DefaultChannelTest() : channel_(nullptr) {
+ EXPECT_EQ(ARES_SUCCESS, ares_init(&channel_));
+ EXPECT_NE(nullptr, channel_);
+ }
+
+ ~DefaultChannelTest() {
+ ares_destroy(channel_);
+ channel_ = nullptr;
+ }
+
+ // Process all pending work on ares-owned file descriptors.
+ void Process();
+
+ protected:
+ ares_channel channel_;
+};
+
+// Test fixture that uses a default channel with the specified lookup mode.
+class DefaultChannelModeTest
+ : public LibraryTest,
+ public ::testing::WithParamInterface<std::string> {
+ public:
+ DefaultChannelModeTest() : channel_(nullptr) {
+ struct ares_options opts = {0};
+ opts.lookups = strdup(GetParam().c_str());
+ int optmask = ARES_OPT_LOOKUPS;
+ EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel_, &opts, optmask));
+ EXPECT_NE(nullptr, channel_);
+ free(opts.lookups);
+ }
+
+ ~DefaultChannelModeTest() {
+ ares_destroy(channel_);
+ channel_ = nullptr;
+ }
+
+ // Process all pending work on ares-owned file descriptors.
+ void Process();
+
+ protected:
+ ares_channel channel_;
+};
+
+// Mock DNS server to allow responses to be scripted by tests.
+class MockServer {
+ public:
+ MockServer(int family, int port, int tcpport = 0);
+ ~MockServer();
+
+ // Mock method indicating the processing of a particular <name, RRtype>
+ // request.
+ MOCK_METHOD2(OnRequest, void(const std::string& name, int rrtype));
+
+ // Set the reply to be sent next; the query ID field will be overwritten
+ // with the value from the request.
+ void SetReplyData(const std::vector<byte>& reply) { reply_ = reply; }
+ void SetReply(const DNSPacket* reply) { SetReplyData(reply->data()); }
+ void SetReplyQID(int qid) { qid_ = qid; }
+
+ // The set of file descriptors that the server handles.
+ std::set<int> fds() const;
+
+ // Process activity on a file descriptor.
+ void ProcessFD(int fd);
+
+ // Ports the server is responding to
+ int udpport() const { return udpport_; }
+ int tcpport() const { return tcpport_; }
+
+ private:
+ void ProcessRequest(int fd, struct sockaddr_storage* addr, int addrlen,
+ int qid, const std::string& name, int rrtype);
+
+ int udpport_;
+ int tcpport_;
+ int udpfd_;
+ int tcpfd_;
+ std::set<int> connfds_;
+ std::vector<byte> reply_;
+ int qid_;
+};
+
+// Test fixture that uses a mock DNS server.
+class MockChannelOptsTest : public LibraryTest {
+ public:
+ MockChannelOptsTest(int count, int family, bool force_tcp, struct ares_options* givenopts, int optmask);
+ ~MockChannelOptsTest();
+
+ // Process all pending work on ares-owned and mock-server-owned file descriptors.
+ void Process();
+
+ protected:
+ // NiceMockServer doesn't complain about uninteresting calls.
+ typedef testing::NiceMock<MockServer> NiceMockServer;
+ typedef std::vector< std::unique_ptr<NiceMockServer> > NiceMockServers;
+
+ std::set<int> fds() const;
+ void ProcessFD(int fd);
+
+ static NiceMockServers BuildServers(int count, int family, int base_port);
+
+ NiceMockServers servers_;
+ // Convenience reference to first server.
+ NiceMockServer& server_;
+ ares_channel channel_;
+};
+
+class MockChannelTest
+ : public MockChannelOptsTest,
+ public ::testing::WithParamInterface< std::pair<int, bool> > {
+ public:
+ MockChannelTest() : MockChannelOptsTest(1, GetParam().first, GetParam().second, nullptr, 0) {}
+};
+
+class MockUDPChannelTest
+ : public MockChannelOptsTest,
+ public ::testing::WithParamInterface<int> {
+ public:
+ MockUDPChannelTest() : MockChannelOptsTest(1, GetParam(), false, nullptr, 0) {}
+};
+
+class MockTCPChannelTest
+ : public MockChannelOptsTest,
+ public ::testing::WithParamInterface<int> {
+ public:
+ MockTCPChannelTest() : MockChannelOptsTest(1, GetParam(), true, nullptr, 0) {}
+};
+
+// gMock action to set the reply for a mock server.
+ACTION_P2(SetReplyData, mockserver, data) {
+ mockserver->SetReplyData(data);
+}
+ACTION_P2(SetReply, mockserver, reply) {
+ mockserver->SetReply(reply);
+}
+ACTION_P2(SetReplyQID, mockserver, qid) {
+ mockserver->SetReplyQID(qid);
+}
+// gMock action to cancel a channel.
+ACTION_P2(CancelChannel, mockserver, channel) {
+ ares_cancel(channel);
+}
+
+// C++ wrapper for struct hostent.
+struct HostEnt {
+ HostEnt() : addrtype_(-1) {}
+ HostEnt(const struct hostent* hostent);
+ std::string name_;
+ std::vector<std::string> aliases_;
+ int addrtype_; // AF_INET or AF_INET6
+ std::vector<std::string> addrs_;
+};
+std::ostream& operator<<(std::ostream& os, const HostEnt& result);
+
+// Structure that describes the result of an ares_host_callback invocation.
+struct HostResult {
+ // Whether the callback has been invoked.
+ bool done_;
+ // Explicitly provided result information.
+ int status_;
+ int timeouts_;
+ // Contents of the hostent structure, if provided.
+ HostEnt host_;
+};
+std::ostream& operator<<(std::ostream& os, const HostResult& result);
+
+// Structure that describes the result of an ares_callback invocation.
+struct SearchResult {
+ // Whether the callback has been invoked.
+ bool done_;
+ // Explicitly provided result information.
+ int status_;
+ int timeouts_;
+ std::vector<byte> data_;
+};
+std::ostream& operator<<(std::ostream& os, const SearchResult& result);
+
+// Structure that describes the result of an ares_nameinfo_callback invocation.
+struct NameInfoResult {
+ // Whether the callback has been invoked.
+ bool done_;
+ // Explicitly provided result information.
+ int status_;
+ int timeouts_;
+ std::string node_;
+ std::string service_;
+};
+std::ostream& operator<<(std::ostream& os, const NameInfoResult& result);
+
struct AddrInfoDeleter {
void operator() (ares_addrinfo *ptr) {
if (ptr) ares_freeaddrinfo(ptr);
@@ -300,51 +300,51 @@ struct AddrInfoResult {
};
std::ostream& operator<<(std::ostream& os, const AddrInfoResult& result);
-// Standard implementation of ares callbacks that fill out the corresponding
-// structures.
-void HostCallback(void *data, int status, int timeouts,
- struct hostent *hostent);
-void SearchCallback(void *data, int status, int timeouts,
- unsigned char *abuf, int alen);
-void NameInfoCallback(void *data, int status, int timeouts,
- char *node, char *service);
+// Standard implementation of ares callbacks that fill out the corresponding
+// structures.
+void HostCallback(void *data, int status, int timeouts,
+ struct hostent *hostent);
+void SearchCallback(void *data, int status, int timeouts,
+ unsigned char *abuf, int alen);
+void NameInfoCallback(void *data, int status, int timeouts,
+ char *node, char *service);
void AddrInfoCallback(void *data, int status, int timeouts,
struct ares_addrinfo *res);
-
-// Retrieve the name servers used by a channel.
-std::vector<std::string> GetNameServers(ares_channel channel);
-
-
-// RAII class to temporarily create a directory of a given name.
-class TransientDir {
- public:
- TransientDir(const std::string& dirname);
- ~TransientDir();
-
- private:
- std::string dirname_;
-};
-
-// C++ wrapper around tempnam()
-std::string TempNam(const char *dir, const char *prefix);
-
-// RAII class to temporarily create file of a given name and contents.
-class TransientFile {
- public:
- TransientFile(const std::string &filename, const std::string &contents);
- ~TransientFile();
-
- protected:
- std::string filename_;
-};
-
-// RAII class for a temporary file with the given contents.
-class TempFile : public TransientFile {
- public:
- TempFile(const std::string& contents);
- const char* filename() const { return filename_.c_str(); }
-};
-
+
+// Retrieve the name servers used by a channel.
+std::vector<std::string> GetNameServers(ares_channel channel);
+
+
+// RAII class to temporarily create a directory of a given name.
+class TransientDir {
+ public:
+ TransientDir(const std::string& dirname);
+ ~TransientDir();
+
+ private:
+ std::string dirname_;
+};
+
+// C++ wrapper around tempnam()
+std::string TempNam(const char *dir, const char *prefix);
+
+// RAII class to temporarily create file of a given name and contents.
+class TransientFile {
+ public:
+ TransientFile(const std::string &filename, const std::string &contents);
+ ~TransientFile();
+
+ protected:
+ std::string filename_;
+};
+
+// RAII class for a temporary file with the given contents.
+class TempFile : public TransientFile {
+ public:
+ TempFile(const std::string& contents);
+ const char* filename() const { return filename_.c_str(); }
+};
+
#ifdef _WIN32
extern "C" {
@@ -379,111 +379,111 @@ static int unsetenv(const char *name)
} /* extern "C" */
#endif
-// RAII class for a temporary environment variable value.
-class EnvValue {
- public:
- EnvValue(const char *name, const char *value) : name_(name), restore_(false) {
- char *original = getenv(name);
- if (original) {
- restore_ = true;
- original_ = original;
- }
- setenv(name_.c_str(), value, 1);
- }
- ~EnvValue() {
- if (restore_) {
- setenv(name_.c_str(), original_.c_str(), 1);
- } else {
- unsetenv(name_.c_str());
- }
- }
- private:
- std::string name_;
- bool restore_;
- std::string original_;
-};
-
-
-#ifdef HAVE_CONTAINER
-// Linux-specific functionality for running code in a container, implemented
-// in ares-test-ns.cc
-typedef std::function<int(void)> VoidToIntFn;
-typedef std::vector<std::pair<std::string, std::string>> NameContentList;
-
-class ContainerFilesystem {
- public:
- ContainerFilesystem(NameContentList files, const std::string& mountpt);
- ~ContainerFilesystem();
- std::string root() const { return rootdir_; };
- std::string mountpt() const { return mountpt_; };
- private:
- void EnsureDirExists(const std::string& dir);
- std::string rootdir_;
- std::string mountpt_;
- std::list<std::string> dirs_;
- std::vector<std::unique_ptr<TransientFile>> files_;
-};
-
-int RunInContainer(ContainerFilesystem* fs, const std::string& hostname,
- const std::string& domainname, VoidToIntFn fn);
-
-#define ICLASS_NAME(casename, testname) Contained##casename##_##testname
-#define CONTAINED_TEST_F(casename, testname, hostname, domainname, files) \
- class ICLASS_NAME(casename, testname) : public casename { \
- public: \
- ICLASS_NAME(casename, testname)() {} \
- static int InnerTestBody(); \
- }; \
- TEST_F(ICLASS_NAME(casename, testname), _) { \
- ContainerFilesystem chroot(files, ".."); \
- VoidToIntFn fn(ICLASS_NAME(casename, testname)::InnerTestBody); \
- EXPECT_EQ(0, RunInContainer(&chroot, hostname, domainname, fn)); \
- } \
- int ICLASS_NAME(casename, testname)::InnerTestBody()
-
-#endif
-
-/* Assigns virtual IO functions to a channel. These functions simply call
- * the actual system functions.
- */
-class VirtualizeIO {
-public:
- VirtualizeIO(ares_channel);
- ~VirtualizeIO();
-
- static const ares_socket_functions default_functions;
-private:
- ares_channel channel_;
-};
-
-/*
- * Slightly white-box macro to generate two runs for a given test case:
- * One with no modifications, and one with all IO functions set to use
- * the virtual io structure.
- * Since no magic socket setup or anything is done in the latter case
- * this should probably only be used for test with very vanilla IO
- * requirements.
- */
-#define VCLASS_NAME(casename, testname) Virt##casename##_##testname
-#define VIRT_NONVIRT_TEST_F(casename, testname) \
- class VCLASS_NAME(casename, testname) : public casename { \
- public: \
- VCLASS_NAME(casename, testname)() {} \
- void InnerTestBody(); \
- }; \
- GTEST_TEST_(casename, testname, VCLASS_NAME(casename, testname), \
- ::testing::internal::GetTypeId<casename>()) { \
- InnerTestBody(); \
- } \
- GTEST_TEST_(casename, testname##_virtualized, \
- VCLASS_NAME(casename, testname), \
- ::testing::internal::GetTypeId<casename>()) { \
- VirtualizeIO vio(channel_); \
- InnerTestBody(); \
- } \
- void VCLASS_NAME(casename, testname)::InnerTestBody()
-
-} // namespace test
-} // namespace ares
-
-#endif
+// RAII class for a temporary environment variable value.
+class EnvValue {
+ public:
+ EnvValue(const char *name, const char *value) : name_(name), restore_(false) {
+ char *original = getenv(name);
+ if (original) {
+ restore_ = true;
+ original_ = original;
+ }
+ setenv(name_.c_str(), value, 1);
+ }
+ ~EnvValue() {
+ if (restore_) {
+ setenv(name_.c_str(), original_.c_str(), 1);
+ } else {
+ unsetenv(name_.c_str());
+ }
+ }
+ private:
+ std::string name_;
+ bool restore_;
+ std::string original_;
+};
+
+
+#ifdef HAVE_CONTAINER
+// Linux-specific functionality for running code in a container, implemented
+// in ares-test-ns.cc
+typedef std::function<int(void)> VoidToIntFn;
+typedef std::vector<std::pair<std::string, std::string>> NameContentList;
+
+class ContainerFilesystem {
+ public:
+ ContainerFilesystem(NameContentList files, const std::string& mountpt);
+ ~ContainerFilesystem();
+ std::string root() const { return rootdir_; };
+ std::string mountpt() const { return mountpt_; };
+ private:
+ void EnsureDirExists(const std::string& dir);
+ std::string rootdir_;
+ std::string mountpt_;
+ std::list<std::string> dirs_;
+ std::vector<std::unique_ptr<TransientFile>> files_;
+};
+
+int RunInContainer(ContainerFilesystem* fs, const std::string& hostname,
+ const std::string& domainname, VoidToIntFn fn);
+
+#define ICLASS_NAME(casename, testname) Contained##casename##_##testname
+#define CONTAINED_TEST_F(casename, testname, hostname, domainname, files) \
+ class ICLASS_NAME(casename, testname) : public casename { \
+ public: \
+ ICLASS_NAME(casename, testname)() {} \
+ static int InnerTestBody(); \
+ }; \
+ TEST_F(ICLASS_NAME(casename, testname), _) { \
+ ContainerFilesystem chroot(files, ".."); \
+ VoidToIntFn fn(ICLASS_NAME(casename, testname)::InnerTestBody); \
+ EXPECT_EQ(0, RunInContainer(&chroot, hostname, domainname, fn)); \
+ } \
+ int ICLASS_NAME(casename, testname)::InnerTestBody()
+
+#endif
+
+/* Assigns virtual IO functions to a channel. These functions simply call
+ * the actual system functions.
+ */
+class VirtualizeIO {
+public:
+ VirtualizeIO(ares_channel);
+ ~VirtualizeIO();
+
+ static const ares_socket_functions default_functions;
+private:
+ ares_channel channel_;
+};
+
+/*
+ * Slightly white-box macro to generate two runs for a given test case:
+ * One with no modifications, and one with all IO functions set to use
+ * the virtual io structure.
+ * Since no magic socket setup or anything is done in the latter case
+ * this should probably only be used for test with very vanilla IO
+ * requirements.
+ */
+#define VCLASS_NAME(casename, testname) Virt##casename##_##testname
+#define VIRT_NONVIRT_TEST_F(casename, testname) \
+ class VCLASS_NAME(casename, testname) : public casename { \
+ public: \
+ VCLASS_NAME(casename, testname)() {} \
+ void InnerTestBody(); \
+ }; \
+ GTEST_TEST_(casename, testname, VCLASS_NAME(casename, testname), \
+ ::testing::internal::GetTypeId<casename>()) { \
+ InnerTestBody(); \
+ } \
+ GTEST_TEST_(casename, testname##_virtualized, \
+ VCLASS_NAME(casename, testname), \
+ ::testing::internal::GetTypeId<casename>()) { \
+ VirtualizeIO vio(channel_); \
+ InnerTestBody(); \
+ } \
+ void VCLASS_NAME(casename, testname)::InnerTestBody()
+
+} // namespace test
+} // namespace ares
+
+#endif
diff --git a/contrib/libs/c-ares/test/config.h b/contrib/libs/c-ares/test/config.h
index 787575c8e0..ce02fa3963 100644
--- a/contrib/libs/c-ares/test/config.h
+++ b/contrib/libs/c-ares/test/config.h
@@ -1,81 +1,81 @@
-/* config.h. Generated from config.h.in by configure. */
-/* config.h.in. Generated from configure.ac by autoheader. */
-
-/* define if the compiler supports basic C++11 syntax */
-/* #undef HAVE_CXX11 */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
-/* Define to 1 if you have the <netinet/tcp.h> header file. */
-#define HAVE_NETINET_TCP_H 1
-
-/* Define if you have POSIX threads libraries and header files. */
-#define HAVE_PTHREAD 1
-
-/* Have PTHREAD_PRIO_INHERIT. */
-#define HAVE_PTHREAD_PRIO_INHERIT 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Whether user namespaces are available */
-#define HAVE_USER_NAMESPACE 1
-
-/* Whether UTS namespaces are available */
-#define HAVE_UTS_NAMESPACE 1
-
-/* Define to the sub-directory where libtool stores uninstalled libraries. */
-#define LT_OBJDIR ".libs/"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "-"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "c-ares-test"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "c-ares-test -"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "c-ares-test"
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "-"
-
-/* Define to necessary symbol if this constant uses a non-standard name on
- your system. */
-/* #undef PTHREAD_CREATE_JOINABLE */
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
+/* config.h. Generated from config.h.in by configure. */
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* define if the compiler supports basic C++11 syntax */
+/* #undef HAVE_CXX11 */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define HAVE_NETINET_TCP_H 1
+
+/* Define if you have POSIX threads libraries and header files. */
+#define HAVE_PTHREAD 1
+
+/* Have PTHREAD_PRIO_INHERIT. */
+#define HAVE_PTHREAD_PRIO_INHERIT 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Whether user namespaces are available */
+#define HAVE_USER_NAMESPACE 1
+
+/* Whether UTS namespaces are available */
+#define HAVE_UTS_NAMESPACE 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define LT_OBJDIR ".libs/"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "-"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "c-ares-test"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "c-ares-test -"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "c-ares-test"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "-"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef PTHREAD_CREATE_JOINABLE */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
diff --git a/contrib/libs/c-ares/test/dns-proto-test.cc b/contrib/libs/c-ares/test/dns-proto-test.cc
index 0c36a0c922..2d9a9ec34d 100644
--- a/contrib/libs/c-ares/test/dns-proto-test.cc
+++ b/contrib/libs/c-ares/test/dns-proto-test.cc
@@ -1,131 +1,131 @@
-#include "ares-test.h"
-#include "dns-proto.h"
-
-#include <vector>
-
-namespace ares {
-namespace test {
-
-TEST(DNSProto, EncodeQuestions) {
- DNSPacket pkt;
- pkt.set_qid(0x1234).set_response().set_aa()
- .add_question(new DNSQuestion("example.com.", ns_t_a))
- .add_question(new DNSQuestion("www.example.com", ns_t_aaaa, ns_c_chaos));
-
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x02, // num questions
- 0x00, 0x00, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Question 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // type A
- 0x00, 0x01, // class IN
- // Question 2
- 0x03, 'w', 'w', 'w',
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x1C, // type AAAA = 28
- 0x00, 0x03, // class CHAOS = 3
- };
- EXPECT_EQ(data, pkt.data());
-}
-
-TEST(DNSProto, EncodeSingleNameAnswers) {
- DNSPacket pkt;
- pkt.qid_ = 0x1234;
- pkt.response_ = true;
- pkt.aa_ = true;
- pkt.opcode_ = ns_o_query;
- pkt.add_answer(new DNSCnameRR("example.com", 0x01020304, "other.com."));
- pkt.add_auth(new DNSPtrRR("www.example.com", 0x01020304, "www.other.com"));
-
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x00, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x01, // num authority RRs
- 0x00, 0x00, // num additional RRs
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x05, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x0B, // rdata length
- 0x05, 'o', 't', 'h', 'e', 'r',
- 0x03, 'c', 'o', 'm',
- 0x00,
- // Authority 1
- 0x03, 'w', 'w', 'w',
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x0c, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x0F, // rdata length
- 0x03, 'w', 'w', 'w',
- 0x05, 'o', 't', 'h', 'e', 'r',
- 0x03, 'c', 'o', 'm',
- 0x00,
- };
- EXPECT_EQ(data, pkt.data());
-}
-
-TEST(DNSProto, EncodeAddressAnswers) {
- DNSPacket pkt;
- pkt.qid_ = 0x1234;
- pkt.response_ = true;
- pkt.aa_ = true;
- pkt.opcode_ = ns_o_query;
- std::vector<byte> addrv4 = {0x02, 0x03, 0x04, 0x05};
- pkt.add_answer(new DNSARR("example.com", 0x01020304, addrv4));
- byte addrv6[16] = {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04};
- pkt.add_additional(new DNSAaaaRR("www.example.com", 0x01020304, addrv6, 16));
-
- std::vector<byte> data = {
- 0x12, 0x34, // qid
- 0x84, // response + query + AA + not-TC + not-RD
- 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
- 0x00, 0x00, // num questions
- 0x00, 0x01, // num answer RRs
- 0x00, 0x00, // num authority RRs
- 0x00, 0x01, // num additional RRs
- // Answer 1
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x01, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x04, // rdata length
- 0x02, 0x03, 0x04, 0x05,
- // Additional 1
- 0x03, 'w', 'w', 'w',
- 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
- 0x03, 'c', 'o', 'm',
- 0x00,
- 0x00, 0x1c, // RR type
- 0x00, 0x01, // class IN
- 0x01, 0x02, 0x03, 0x04, // TTL
- 0x00, 0x10, // rdata length
- 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
- 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04
- };
- EXPECT_EQ(data, pkt.data());
-}
-
-
-} // namespace test
-} // namespace ares
+#include "ares-test.h"
+#include "dns-proto.h"
+
+#include <vector>
+
+namespace ares {
+namespace test {
+
+TEST(DNSProto, EncodeQuestions) {
+ DNSPacket pkt;
+ pkt.set_qid(0x1234).set_response().set_aa()
+ .add_question(new DNSQuestion("example.com.", ns_t_a))
+ .add_question(new DNSQuestion("www.example.com", ns_t_aaaa, ns_c_chaos));
+
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x02, // num questions
+ 0x00, 0x00, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Question 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // type A
+ 0x00, 0x01, // class IN
+ // Question 2
+ 0x03, 'w', 'w', 'w',
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x1C, // type AAAA = 28
+ 0x00, 0x03, // class CHAOS = 3
+ };
+ EXPECT_EQ(data, pkt.data());
+}
+
+TEST(DNSProto, EncodeSingleNameAnswers) {
+ DNSPacket pkt;
+ pkt.qid_ = 0x1234;
+ pkt.response_ = true;
+ pkt.aa_ = true;
+ pkt.opcode_ = ns_o_query;
+ pkt.add_answer(new DNSCnameRR("example.com", 0x01020304, "other.com."));
+ pkt.add_auth(new DNSPtrRR("www.example.com", 0x01020304, "www.other.com"));
+
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x00, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x01, // num authority RRs
+ 0x00, 0x00, // num additional RRs
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x05, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x0B, // rdata length
+ 0x05, 'o', 't', 'h', 'e', 'r',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ // Authority 1
+ 0x03, 'w', 'w', 'w',
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x0c, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x0F, // rdata length
+ 0x03, 'w', 'w', 'w',
+ 0x05, 'o', 't', 'h', 'e', 'r',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ };
+ EXPECT_EQ(data, pkt.data());
+}
+
+TEST(DNSProto, EncodeAddressAnswers) {
+ DNSPacket pkt;
+ pkt.qid_ = 0x1234;
+ pkt.response_ = true;
+ pkt.aa_ = true;
+ pkt.opcode_ = ns_o_query;
+ std::vector<byte> addrv4 = {0x02, 0x03, 0x04, 0x05};
+ pkt.add_answer(new DNSARR("example.com", 0x01020304, addrv4));
+ byte addrv6[16] = {0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04};
+ pkt.add_additional(new DNSAaaaRR("www.example.com", 0x01020304, addrv6, 16));
+
+ std::vector<byte> data = {
+ 0x12, 0x34, // qid
+ 0x84, // response + query + AA + not-TC + not-RD
+ 0x00, // not-RA + not-Z + not-AD + not-CD + rc=NoError
+ 0x00, 0x00, // num questions
+ 0x00, 0x01, // num answer RRs
+ 0x00, 0x00, // num authority RRs
+ 0x00, 0x01, // num additional RRs
+ // Answer 1
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x01, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x04, // rdata length
+ 0x02, 0x03, 0x04, 0x05,
+ // Additional 1
+ 0x03, 'w', 'w', 'w',
+ 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e',
+ 0x03, 'c', 'o', 'm',
+ 0x00,
+ 0x00, 0x1c, // RR type
+ 0x00, 0x01, // class IN
+ 0x01, 0x02, 0x03, 0x04, // TTL
+ 0x00, 0x10, // rdata length
+ 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02,
+ 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04
+ };
+ EXPECT_EQ(data, pkt.data());
+}
+
+
+} // namespace test
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/dns-proto.cc b/contrib/libs/c-ares/test/dns-proto.cc
index d2fa8b15be..7f50be3534 100644
--- a/contrib/libs/c-ares/test/dns-proto.cc
+++ b/contrib/libs/c-ares/test/dns-proto.cc
@@ -1,638 +1,638 @@
-#include "dns-proto.h"
-
-// Include ares internal file for DNS protocol details
-#include "ares_setup.h"
-#include "ares.h"
-#include "ares_dns.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <sstream>
-
-namespace ares {
-
-std::string HexDump(std::vector<byte> data) {
- std::stringstream ss;
- for (size_t ii = 0; ii < data.size(); ii++) {
- char buffer[2 + 1];
- sprintf(buffer, "%02x", data[ii]);
- ss << buffer;
- }
- return ss.str();
-}
-
-std::string HexDump(const byte *data, int len) {
- return HexDump(std::vector<byte>(data, data + len));
-}
-
-std::string HexDump(const char *data, int len) {
- return HexDump(reinterpret_cast<const byte*>(data), len);
-}
-
-std::string StatusToString(int status) {
- switch (status) {
- case ARES_SUCCESS: return "ARES_SUCCESS";
- case ARES_ENODATA: return "ARES_ENODATA";
- case ARES_EFORMERR: return "ARES_EFORMERR";
- case ARES_ESERVFAIL: return "ARES_ESERVFAIL";
- case ARES_ENOTFOUND: return "ARES_ENOTFOUND";
- case ARES_ENOTIMP: return "ARES_ENOTIMP";
- case ARES_EREFUSED: return "ARES_EREFUSED";
- case ARES_EBADQUERY: return "ARES_EBADQUERY";
- case ARES_EBADNAME: return "ARES_EBADNAME";
- case ARES_EBADFAMILY: return "ARES_EBADFAMILY";
- case ARES_EBADRESP: return "ARES_EBADRESP";
- case ARES_ECONNREFUSED: return "ARES_ECONNREFUSED";
- case ARES_ETIMEOUT: return "ARES_ETIMEOUT";
- case ARES_EOF: return "ARES_EOF";
- case ARES_EFILE: return "ARES_EFILE";
- case ARES_ENOMEM: return "ARES_ENOMEM";
- case ARES_EDESTRUCTION: return "ARES_EDESTRUCTION";
- case ARES_EBADSTR: return "ARES_EBADSTR";
- case ARES_EBADFLAGS: return "ARES_EBADFLAGS";
- case ARES_ENONAME: return "ARES_ENONAME";
- case ARES_EBADHINTS: return "ARES_EBADHINTS";
- case ARES_ENOTINITIALIZED: return "ARES_ENOTINITIALIZED";
- case ARES_ELOADIPHLPAPI: return "ARES_ELOADIPHLPAPI";
- case ARES_EADDRGETNETWORKPARAMS: return "ARES_EADDRGETNETWORKPARAMS";
- case ARES_ECANCELLED: return "ARES_ECANCELLED";
- default: return "UNKNOWN";
- }
-}
-
-std::string RcodeToString(int rcode) {
- switch (rcode) {
- case ns_r_noerror: return "NOERROR";
- case ns_r_formerr: return "FORMERR";
- case ns_r_servfail: return "SERVFAIL";
- case ns_r_nxdomain: return "NXDOMAIN";
- case ns_r_notimpl: return "NOTIMPL";
- case ns_r_refused: return "REFUSED";
- case ns_r_yxdomain: return "YXDOMAIN";
- case ns_r_yxrrset: return "YXRRSET";
- case ns_r_nxrrset: return "NXRRSET";
- case ns_r_notauth: return "NOTAUTH";
- case ns_r_notzone: return "NOTZONE";
- case ns_r_badsig: return "BADSIG";
- case ns_r_badkey: return "BADKEY";
- case ns_r_badtime: return "BADTIME";
- default: return "UNKNOWN";
- }
-}
-
-std::string RRTypeToString(int rrtype) {
- switch (rrtype) {
- case ns_t_a: return "A";
- case ns_t_ns: return "NS";
- case ns_t_md: return "MD";
- case ns_t_mf: return "MF";
- case ns_t_cname: return "CNAME";
- case ns_t_soa: return "SOA";
- case ns_t_mb: return "MB";
- case ns_t_mg: return "MG";
- case ns_t_mr: return "MR";
- case ns_t_null: return "NULL";
- case ns_t_wks: return "WKS";
- case ns_t_ptr: return "PTR";
- case ns_t_hinfo: return "HINFO";
- case ns_t_minfo: return "MINFO";
- case ns_t_mx: return "MX";
- case ns_t_txt: return "TXT";
- case ns_t_rp: return "RP";
- case ns_t_afsdb: return "AFSDB";
- case ns_t_x25: return "X25";
- case ns_t_isdn: return "ISDN";
- case ns_t_rt: return "RT";
- case ns_t_nsap: return "NSAP";
- case ns_t_nsap_ptr: return "NSAP_PTR";
- case ns_t_sig: return "SIG";
- case ns_t_key: return "KEY";
- case ns_t_px: return "PX";
- case ns_t_gpos: return "GPOS";
- case ns_t_aaaa: return "AAAA";
- case ns_t_loc: return "LOC";
- case ns_t_nxt: return "NXT";
- case ns_t_eid: return "EID";
- case ns_t_nimloc: return "NIMLOC";
- case ns_t_srv: return "SRV";
- case ns_t_atma: return "ATMA";
- case ns_t_naptr: return "NAPTR";
- case ns_t_kx: return "KX";
- case ns_t_cert: return "CERT";
- case ns_t_a6: return "A6";
- case ns_t_dname: return "DNAME";
- case ns_t_sink: return "SINK";
- case ns_t_opt: return "OPT";
- case ns_t_apl: return "APL";
- case ns_t_ds: return "DS";
- case ns_t_sshfp: return "SSHFP";
- case ns_t_rrsig: return "RRSIG";
- case ns_t_nsec: return "NSEC";
- case ns_t_dnskey: return "DNSKEY";
- case ns_t_tkey: return "TKEY";
- case ns_t_tsig: return "TSIG";
- case ns_t_ixfr: return "IXFR";
- case ns_t_axfr: return "AXFR";
- case ns_t_mailb: return "MAILB";
- case ns_t_maila: return "MAILA";
- case ns_t_any: return "ANY";
- case ns_t_zxfr: return "ZXFR";
- case ns_t_max: return "MAX";
- default: return "UNKNOWN";
- }
-}
-
-std::string ClassToString(int qclass) {
- switch (qclass) {
- case ns_c_in: return "IN";
- case ns_c_chaos: return "CHAOS";
- case ns_c_hs: return "HESIOD";
- case ns_c_none: return "NONE";
- case ns_c_any: return "ANY";
- default: return "UNKNOWN";
- }
-}
-
-std::string AddressToString(const void* vaddr, int len) {
- const byte* addr = reinterpret_cast<const byte*>(vaddr);
- std::stringstream ss;
- if (len == 4) {
- char buffer[4*4 + 3 + 1];
- sprintf(buffer, "%u.%u.%u.%u",
- (unsigned char)addr[0],
- (unsigned char)addr[1],
- (unsigned char)addr[2],
- (unsigned char)addr[3]);
- ss << buffer;
- } else if (len == 16) {
- for (int ii = 0; ii < 16; ii+=2) {
- if (ii > 0) ss << ':';
- char buffer[4 + 1];
- sprintf(buffer, "%02x%02x", (unsigned char)addr[ii], (unsigned char)addr[ii+1]);
- ss << buffer;
- }
- } else {
- ss << "!" << HexDump(addr, len) << "!";
- }
- return ss.str();
-}
-
-std::string PacketToString(const std::vector<byte>& packet) {
- const byte* data = packet.data();
- int len = packet.size();
- std::stringstream ss;
- if (len < NS_HFIXEDSZ) {
- ss << "(too short, len " << len << ")";
- return ss.str();
- }
- ss << ((DNS_HEADER_QR(data) == 0) ? "REQ " : "RSP ");
- switch (DNS_HEADER_OPCODE(data)) {
- case ns_o_query: ss << "QRY "; break;
- case ns_o_iquery: ss << "IQRY "; break;
- case ns_o_status: ss << "STATUS "; break;
- case ns_o_notify: ss << "NOTIFY "; break;
- case ns_o_update: ss << "UPDATE "; break;
- default: ss << "UNKNOWN(" << DNS_HEADER_OPCODE(data) << ") "; break;
- }
- if (DNS_HEADER_AA(data)) ss << "AA ";
- if (DNS_HEADER_TC(data)) ss << "TC ";
- if (DNS_HEADER_RD(data)) ss << "RD ";
- if (DNS_HEADER_RA(data)) ss << "RA ";
- if (DNS_HEADER_Z(data)) ss << "Z ";
- if (DNS_HEADER_QR(data) == 1) ss << RcodeToString(DNS_HEADER_RCODE(data));
-
- int nquestions = DNS_HEADER_QDCOUNT(data);
- int nanswers = DNS_HEADER_ANCOUNT(data);
- int nauths = DNS_HEADER_NSCOUNT(data);
- int nadds = DNS_HEADER_ARCOUNT(data);
-
- const byte* pq = data + NS_HFIXEDSZ;
- len -= NS_HFIXEDSZ;
- for (int ii = 0; ii < nquestions; ii++) {
- ss << " Q:" << QuestionToString(packet, &pq, &len);
- }
- const byte* prr = pq;
- for (int ii = 0; ii < nanswers; ii++) {
- ss << " A:" << RRToString(packet, &prr, &len);
- }
- for (int ii = 0; ii < nauths; ii++) {
- ss << " AUTH:" << RRToString(packet, &prr, &len);
- }
- for (int ii = 0; ii < nadds; ii++) {
- ss << " ADD:" << RRToString(packet, &prr, &len);
- }
- return ss.str();
-}
-
-std::string QuestionToString(const std::vector<byte>& packet,
- const byte** data, int* len) {
- std::stringstream ss;
- ss << "{";
- if (*len < NS_QFIXEDSZ) {
- ss << "(too short, len " << *len << ")";
- return ss.str();
- }
-
- char *name = nullptr;
- long enclen;
- int rc = ares_expand_name(*data, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- return ss.str();
- }
- if (enclen > *len) {
- ss << "(error, encoded name len " << enclen << "bigger than remaining data " << *len << " bytes)";
- return ss.str();
- }
- *len -= enclen;
- *data += enclen;
- ss << "'" << name << "' ";
- ares_free_string(name);
- if (*len < NS_QFIXEDSZ) {
- ss << "(too short, len left " << *len << ")";
- return ss.str();
- }
- ss << ClassToString(DNS_QUESTION_CLASS(*data)) << " ";
- ss << RRTypeToString(DNS_QUESTION_TYPE(*data));
- *data += NS_QFIXEDSZ;
- *len -= NS_QFIXEDSZ;
- ss << "}";
- return ss.str();
-}
-
-std::string RRToString(const std::vector<byte>& packet,
- const byte** data, int* len) {
- std::stringstream ss;
- ss << "{";
- if (*len < NS_RRFIXEDSZ) {
- ss << "too short, len " << *len << ")";
- return ss.str();
- }
-
- char *name = nullptr;
- long enclen;
- int rc = ares_expand_name(*data, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- return ss.str();
- }
- if (enclen > *len) {
- ss << "(error, encoded name len " << enclen << "bigger than remaining data " << *len << " bytes)";
- return ss.str();
- }
- *len -= enclen;
- *data += enclen;
- ss << "'" << name << "' ";
- ares_free_string(name);
- name = nullptr;
-
- if (*len < NS_RRFIXEDSZ) {
- ss << "(too short, len left " << *len << ")";
- return ss.str();
- }
- int rrtype = DNS_RR_TYPE(*data);
- if (rrtype == ns_t_opt) {
- ss << "MAXUDP=" << DNS_RR_CLASS(*data) << " ";
- ss << RRTypeToString(rrtype) << " ";
- ss << "RCODE2=" << DNS_RR_TTL(*data);
- } else {
- ss << ClassToString(DNS_RR_CLASS(*data)) << " ";
- ss << RRTypeToString(rrtype) << " ";
- ss << "TTL=" << DNS_RR_TTL(*data);
- }
- int rdatalen = DNS_RR_LEN(*data);
-
- *data += NS_RRFIXEDSZ;
- *len -= NS_RRFIXEDSZ;
- if (*len < rdatalen) {
- ss << "(RR too long at " << rdatalen << ", len left " << *len << ")";
- } else {
- switch (rrtype) {
- case ns_t_a:
- case ns_t_aaaa:
- ss << " " << AddressToString(*data, rdatalen);
- break;
- case ns_t_txt: {
- const byte* p = *data;
- while (p < (*data + rdatalen)) {
- int len = *p++;
- if ((p + len) <= (*data + rdatalen)) {
- std::string txt(p, p + len);
- ss << " " << len << ":'" << txt << "'";
- } else {
- ss << "(string too long)";
- }
- p += len;
- }
- break;
- }
- case ns_t_cname:
- case ns_t_ns:
- case ns_t_ptr: {
- int rc = ares_expand_name(*data, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- break;
- }
- ss << " '" << name << "'";
- ares_free_string(name);
- break;
- }
- case ns_t_mx:
- if (rdatalen > 2) {
- int rc = ares_expand_name(*data + 2, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- break;
- }
- ss << " " << DNS__16BIT(*data) << " '" << name << "'";
- ares_free_string(name);
- } else {
- ss << "(RR too short)";
- }
- break;
- case ns_t_srv: {
- if (rdatalen > 6) {
- const byte* p = *data;
- unsigned long prio = DNS__16BIT(p);
- unsigned long weight = DNS__16BIT(p + 2);
- unsigned long port = DNS__16BIT(p + 4);
- p += 6;
- int rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- break;
- }
- ss << prio << " " << weight << " " << port << " '" << name << "'";
- ares_free_string(name);
- } else {
- ss << "(RR too short)";
- }
- break;
- }
- case ns_t_soa: {
- const byte* p = *data;
- int rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- break;
- }
- ss << " '" << name << "'";
- ares_free_string(name);
- p += enclen;
- rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- break;
- }
- ss << " '" << name << "'";
- ares_free_string(name);
- p += enclen;
- if ((p + 20) <= (*data + rdatalen)) {
- unsigned long serial = DNS__32BIT(p);
- unsigned long refresh = DNS__32BIT(p + 4);
- unsigned long retry = DNS__32BIT(p + 8);
- unsigned long expire = DNS__32BIT(p + 12);
- unsigned long minimum = DNS__32BIT(p + 16);
- ss << " " << serial << " " << refresh << " " << retry << " " << expire << " " << minimum;
- } else {
- ss << "(RR too short)";
- }
- break;
- }
- case ns_t_naptr: {
- if (rdatalen > 7) {
- const byte* p = *data;
- unsigned long order = DNS__16BIT(p);
- unsigned long pref = DNS__16BIT(p + 2);
- p += 4;
- ss << order << " " << pref;
-
- int len = *p++;
- std::string flags(p, p + len);
- ss << " " << flags;
- p += len;
-
- len = *p++;
- std::string service(p, p + len);
- ss << " '" << service << "'";
- p += len;
-
- len = *p++;
- std::string regexp(p, p + len);
- ss << " '" << regexp << "'";
- p += len;
-
- int rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
- if (rc != ARES_SUCCESS) {
- ss << "(error from ares_expand_name)";
- break;
- }
- ss << " '" << name << "'";
- ares_free_string(name);
- } else {
- ss << "(RR too short)";
- }
- break;
- }
- default:
- ss << " " << HexDump(*data, rdatalen);
- break;
- }
- }
- *data += rdatalen;
- *len -= rdatalen;
-
- ss << "}";
- return ss.str();
-}
-
-void PushInt32(std::vector<byte>* data, int value) {
- data->push_back((value & 0xff000000) >> 24);
- data->push_back((value & 0x00ff0000) >> 16);
- data->push_back((value & 0x0000ff00) >> 8);
- data->push_back(value & 0x000000ff);
-}
-
-void PushInt16(std::vector<byte>* data, int value) {
- data->push_back((value & 0xff00) >> 8);
- data->push_back(value & 0x00ff);
-}
-
-std::vector<byte> EncodeString(const std::string& name) {
- std::vector<byte> data;
- std::stringstream ss(name);
- std::string label;
- // TODO: cope with escapes
- while (std::getline(ss, label, '.')) {
- data.push_back(label.length());
- data.insert(data.end(), label.begin(), label.end());
- }
- data.push_back(0);
- return data;
-}
-
-std::vector<byte> DNSQuestion::data() const {
- std::vector<byte> data;
- std::vector<byte> encname = EncodeString(name_);
- data.insert(data.end(), encname.begin(), encname.end());
- PushInt16(&data, rrtype_);
- PushInt16(&data, qclass_);
- return data;
-}
-
-std::vector<byte> DNSRR::data() const {
- std::vector<byte> data = DNSQuestion::data();
- PushInt32(&data, ttl_);
- return data;
-}
-
-std::vector<byte> DNSSingleNameRR::data() const {
- std::vector<byte> data = DNSRR::data();
- std::vector<byte> encname = EncodeString(other_);
- int len = encname.size();
- PushInt16(&data, len);
- data.insert(data.end(), encname.begin(), encname.end());
- return data;
-}
-
-std::vector<byte> DNSTxtRR::data() const {
- std::vector<byte> data = DNSRR::data();
- int len = 0;
- for (const std::string& txt : txt_) {
- len += (1 + txt.size());
- }
- PushInt16(&data, len);
- for (const std::string& txt : txt_) {
- data.push_back(txt.size());
- data.insert(data.end(), txt.begin(), txt.end());
- }
- return data;
-}
-
-std::vector<byte> DNSMxRR::data() const {
- std::vector<byte> data = DNSRR::data();
- std::vector<byte> encname = EncodeString(other_);
- int len = 2 + encname.size();
- PushInt16(&data, len);
- PushInt16(&data, pref_);
- data.insert(data.end(), encname.begin(), encname.end());
- return data;
-}
-
-std::vector<byte> DNSSrvRR::data() const {
- std::vector<byte> data = DNSRR::data();
- std::vector<byte> encname = EncodeString(target_);
- int len = 6 + encname.size();
- PushInt16(&data, len);
- PushInt16(&data, prio_);
- PushInt16(&data, weight_);
- PushInt16(&data, port_);
- data.insert(data.end(), encname.begin(), encname.end());
- return data;
-}
-
-std::vector<byte> DNSAddressRR::data() const {
- std::vector<byte> data = DNSRR::data();
- int len = addr_.size();
- PushInt16(&data, len);
- data.insert(data.end(), addr_.begin(), addr_.end());
- return data;
-}
-
-std::vector<byte> DNSSoaRR::data() const {
- std::vector<byte> data = DNSRR::data();
- std::vector<byte> encname1 = EncodeString(nsname_);
- std::vector<byte> encname2 = EncodeString(rname_);
- int len = encname1.size() + encname2.size() + 5*4;
- PushInt16(&data, len);
- data.insert(data.end(), encname1.begin(), encname1.end());
- data.insert(data.end(), encname2.begin(), encname2.end());
- PushInt32(&data, serial_);
- PushInt32(&data, refresh_);
- PushInt32(&data, retry_);
- PushInt32(&data, expire_);
- PushInt32(&data, minimum_);
- return data;
-}
-
-std::vector<byte> DNSOptRR::data() const {
- std::vector<byte> data = DNSRR::data();
- int len = 0;
- for (const DNSOption& opt : opts_) {
- len += (4 + opt.data_.size());
- }
- PushInt16(&data, len);
- for (const DNSOption& opt : opts_) {
- PushInt16(&data, opt.code_);
- PushInt16(&data, opt.data_.size());
- data.insert(data.end(), opt.data_.begin(), opt.data_.end());
- }
- return data;
-}
-
-std::vector<byte> DNSNaptrRR::data() const {
- std::vector<byte> data = DNSRR::data();
- std::vector<byte> encname = EncodeString(replacement_);
- int len = (4 + 1 + flags_.size() + 1 + service_.size() + 1 + regexp_.size() + encname.size());
- PushInt16(&data, len);
- PushInt16(&data, order_);
- PushInt16(&data, pref_);
- data.push_back(flags_.size());
- data.insert(data.end(), flags_.begin(), flags_.end());
- data.push_back(service_.size());
- data.insert(data.end(), service_.begin(), service_.end());
- data.push_back(regexp_.size());
- data.insert(data.end(), regexp_.begin(), regexp_.end());
- data.insert(data.end(), encname.begin(), encname.end());
- return data;
-}
-
-std::vector<byte> DNSPacket::data() const {
- std::vector<byte> data;
- PushInt16(&data, qid_);
- byte b = 0x00;
- if (response_) b |= 0x80;
- b |= ((opcode_ & 0x0f) << 3);
- if (aa_) b |= 0x04;
- if (tc_) b |= 0x02;
- if (rd_) b |= 0x01;
- data.push_back(b);
- b = 0x00;
- if (ra_) b |= 0x80;
- if (z_) b |= 0x40;
- if (ad_) b |= 0x20;
- if (cd_) b |= 0x10;
- b |= (rcode_ & 0x0f);
- data.push_back(b);
-
- int count = questions_.size();
- PushInt16(&data, count);
- count = answers_.size();
- PushInt16(&data, count);
- count = auths_.size();
- PushInt16(&data, count);
- count = adds_.size();
- PushInt16(&data, count);
-
- for (const std::unique_ptr<DNSQuestion>& question : questions_) {
- std::vector<byte> qdata = question->data();
- data.insert(data.end(), qdata.begin(), qdata.end());
- }
- for (const std::unique_ptr<DNSRR>& rr : answers_) {
- std::vector<byte> rrdata = rr->data();
- data.insert(data.end(), rrdata.begin(), rrdata.end());
- }
- for (const std::unique_ptr<DNSRR>& rr : auths_) {
- std::vector<byte> rrdata = rr->data();
- data.insert(data.end(), rrdata.begin(), rrdata.end());
- }
- for (const std::unique_ptr<DNSRR>& rr : adds_) {
- std::vector<byte> rrdata = rr->data();
- data.insert(data.end(), rrdata.begin(), rrdata.end());
- }
- return data;
-}
-
-} // namespace ares
+#include "dns-proto.h"
+
+// Include ares internal file for DNS protocol details
+#include "ares_setup.h"
+#include "ares.h"
+#include "ares_dns.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <sstream>
+
+namespace ares {
+
+std::string HexDump(std::vector<byte> data) {
+ std::stringstream ss;
+ for (size_t ii = 0; ii < data.size(); ii++) {
+ char buffer[2 + 1];
+ sprintf(buffer, "%02x", data[ii]);
+ ss << buffer;
+ }
+ return ss.str();
+}
+
+std::string HexDump(const byte *data, int len) {
+ return HexDump(std::vector<byte>(data, data + len));
+}
+
+std::string HexDump(const char *data, int len) {
+ return HexDump(reinterpret_cast<const byte*>(data), len);
+}
+
+std::string StatusToString(int status) {
+ switch (status) {
+ case ARES_SUCCESS: return "ARES_SUCCESS";
+ case ARES_ENODATA: return "ARES_ENODATA";
+ case ARES_EFORMERR: return "ARES_EFORMERR";
+ case ARES_ESERVFAIL: return "ARES_ESERVFAIL";
+ case ARES_ENOTFOUND: return "ARES_ENOTFOUND";
+ case ARES_ENOTIMP: return "ARES_ENOTIMP";
+ case ARES_EREFUSED: return "ARES_EREFUSED";
+ case ARES_EBADQUERY: return "ARES_EBADQUERY";
+ case ARES_EBADNAME: return "ARES_EBADNAME";
+ case ARES_EBADFAMILY: return "ARES_EBADFAMILY";
+ case ARES_EBADRESP: return "ARES_EBADRESP";
+ case ARES_ECONNREFUSED: return "ARES_ECONNREFUSED";
+ case ARES_ETIMEOUT: return "ARES_ETIMEOUT";
+ case ARES_EOF: return "ARES_EOF";
+ case ARES_EFILE: return "ARES_EFILE";
+ case ARES_ENOMEM: return "ARES_ENOMEM";
+ case ARES_EDESTRUCTION: return "ARES_EDESTRUCTION";
+ case ARES_EBADSTR: return "ARES_EBADSTR";
+ case ARES_EBADFLAGS: return "ARES_EBADFLAGS";
+ case ARES_ENONAME: return "ARES_ENONAME";
+ case ARES_EBADHINTS: return "ARES_EBADHINTS";
+ case ARES_ENOTINITIALIZED: return "ARES_ENOTINITIALIZED";
+ case ARES_ELOADIPHLPAPI: return "ARES_ELOADIPHLPAPI";
+ case ARES_EADDRGETNETWORKPARAMS: return "ARES_EADDRGETNETWORKPARAMS";
+ case ARES_ECANCELLED: return "ARES_ECANCELLED";
+ default: return "UNKNOWN";
+ }
+}
+
+std::string RcodeToString(int rcode) {
+ switch (rcode) {
+ case ns_r_noerror: return "NOERROR";
+ case ns_r_formerr: return "FORMERR";
+ case ns_r_servfail: return "SERVFAIL";
+ case ns_r_nxdomain: return "NXDOMAIN";
+ case ns_r_notimpl: return "NOTIMPL";
+ case ns_r_refused: return "REFUSED";
+ case ns_r_yxdomain: return "YXDOMAIN";
+ case ns_r_yxrrset: return "YXRRSET";
+ case ns_r_nxrrset: return "NXRRSET";
+ case ns_r_notauth: return "NOTAUTH";
+ case ns_r_notzone: return "NOTZONE";
+ case ns_r_badsig: return "BADSIG";
+ case ns_r_badkey: return "BADKEY";
+ case ns_r_badtime: return "BADTIME";
+ default: return "UNKNOWN";
+ }
+}
+
+std::string RRTypeToString(int rrtype) {
+ switch (rrtype) {
+ case ns_t_a: return "A";
+ case ns_t_ns: return "NS";
+ case ns_t_md: return "MD";
+ case ns_t_mf: return "MF";
+ case ns_t_cname: return "CNAME";
+ case ns_t_soa: return "SOA";
+ case ns_t_mb: return "MB";
+ case ns_t_mg: return "MG";
+ case ns_t_mr: return "MR";
+ case ns_t_null: return "NULL";
+ case ns_t_wks: return "WKS";
+ case ns_t_ptr: return "PTR";
+ case ns_t_hinfo: return "HINFO";
+ case ns_t_minfo: return "MINFO";
+ case ns_t_mx: return "MX";
+ case ns_t_txt: return "TXT";
+ case ns_t_rp: return "RP";
+ case ns_t_afsdb: return "AFSDB";
+ case ns_t_x25: return "X25";
+ case ns_t_isdn: return "ISDN";
+ case ns_t_rt: return "RT";
+ case ns_t_nsap: return "NSAP";
+ case ns_t_nsap_ptr: return "NSAP_PTR";
+ case ns_t_sig: return "SIG";
+ case ns_t_key: return "KEY";
+ case ns_t_px: return "PX";
+ case ns_t_gpos: return "GPOS";
+ case ns_t_aaaa: return "AAAA";
+ case ns_t_loc: return "LOC";
+ case ns_t_nxt: return "NXT";
+ case ns_t_eid: return "EID";
+ case ns_t_nimloc: return "NIMLOC";
+ case ns_t_srv: return "SRV";
+ case ns_t_atma: return "ATMA";
+ case ns_t_naptr: return "NAPTR";
+ case ns_t_kx: return "KX";
+ case ns_t_cert: return "CERT";
+ case ns_t_a6: return "A6";
+ case ns_t_dname: return "DNAME";
+ case ns_t_sink: return "SINK";
+ case ns_t_opt: return "OPT";
+ case ns_t_apl: return "APL";
+ case ns_t_ds: return "DS";
+ case ns_t_sshfp: return "SSHFP";
+ case ns_t_rrsig: return "RRSIG";
+ case ns_t_nsec: return "NSEC";
+ case ns_t_dnskey: return "DNSKEY";
+ case ns_t_tkey: return "TKEY";
+ case ns_t_tsig: return "TSIG";
+ case ns_t_ixfr: return "IXFR";
+ case ns_t_axfr: return "AXFR";
+ case ns_t_mailb: return "MAILB";
+ case ns_t_maila: return "MAILA";
+ case ns_t_any: return "ANY";
+ case ns_t_zxfr: return "ZXFR";
+ case ns_t_max: return "MAX";
+ default: return "UNKNOWN";
+ }
+}
+
+std::string ClassToString(int qclass) {
+ switch (qclass) {
+ case ns_c_in: return "IN";
+ case ns_c_chaos: return "CHAOS";
+ case ns_c_hs: return "HESIOD";
+ case ns_c_none: return "NONE";
+ case ns_c_any: return "ANY";
+ default: return "UNKNOWN";
+ }
+}
+
+std::string AddressToString(const void* vaddr, int len) {
+ const byte* addr = reinterpret_cast<const byte*>(vaddr);
+ std::stringstream ss;
+ if (len == 4) {
+ char buffer[4*4 + 3 + 1];
+ sprintf(buffer, "%u.%u.%u.%u",
+ (unsigned char)addr[0],
+ (unsigned char)addr[1],
+ (unsigned char)addr[2],
+ (unsigned char)addr[3]);
+ ss << buffer;
+ } else if (len == 16) {
+ for (int ii = 0; ii < 16; ii+=2) {
+ if (ii > 0) ss << ':';
+ char buffer[4 + 1];
+ sprintf(buffer, "%02x%02x", (unsigned char)addr[ii], (unsigned char)addr[ii+1]);
+ ss << buffer;
+ }
+ } else {
+ ss << "!" << HexDump(addr, len) << "!";
+ }
+ return ss.str();
+}
+
+std::string PacketToString(const std::vector<byte>& packet) {
+ const byte* data = packet.data();
+ int len = packet.size();
+ std::stringstream ss;
+ if (len < NS_HFIXEDSZ) {
+ ss << "(too short, len " << len << ")";
+ return ss.str();
+ }
+ ss << ((DNS_HEADER_QR(data) == 0) ? "REQ " : "RSP ");
+ switch (DNS_HEADER_OPCODE(data)) {
+ case ns_o_query: ss << "QRY "; break;
+ case ns_o_iquery: ss << "IQRY "; break;
+ case ns_o_status: ss << "STATUS "; break;
+ case ns_o_notify: ss << "NOTIFY "; break;
+ case ns_o_update: ss << "UPDATE "; break;
+ default: ss << "UNKNOWN(" << DNS_HEADER_OPCODE(data) << ") "; break;
+ }
+ if (DNS_HEADER_AA(data)) ss << "AA ";
+ if (DNS_HEADER_TC(data)) ss << "TC ";
+ if (DNS_HEADER_RD(data)) ss << "RD ";
+ if (DNS_HEADER_RA(data)) ss << "RA ";
+ if (DNS_HEADER_Z(data)) ss << "Z ";
+ if (DNS_HEADER_QR(data) == 1) ss << RcodeToString(DNS_HEADER_RCODE(data));
+
+ int nquestions = DNS_HEADER_QDCOUNT(data);
+ int nanswers = DNS_HEADER_ANCOUNT(data);
+ int nauths = DNS_HEADER_NSCOUNT(data);
+ int nadds = DNS_HEADER_ARCOUNT(data);
+
+ const byte* pq = data + NS_HFIXEDSZ;
+ len -= NS_HFIXEDSZ;
+ for (int ii = 0; ii < nquestions; ii++) {
+ ss << " Q:" << QuestionToString(packet, &pq, &len);
+ }
+ const byte* prr = pq;
+ for (int ii = 0; ii < nanswers; ii++) {
+ ss << " A:" << RRToString(packet, &prr, &len);
+ }
+ for (int ii = 0; ii < nauths; ii++) {
+ ss << " AUTH:" << RRToString(packet, &prr, &len);
+ }
+ for (int ii = 0; ii < nadds; ii++) {
+ ss << " ADD:" << RRToString(packet, &prr, &len);
+ }
+ return ss.str();
+}
+
+std::string QuestionToString(const std::vector<byte>& packet,
+ const byte** data, int* len) {
+ std::stringstream ss;
+ ss << "{";
+ if (*len < NS_QFIXEDSZ) {
+ ss << "(too short, len " << *len << ")";
+ return ss.str();
+ }
+
+ char *name = nullptr;
+ long enclen;
+ int rc = ares_expand_name(*data, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ return ss.str();
+ }
+ if (enclen > *len) {
+ ss << "(error, encoded name len " << enclen << "bigger than remaining data " << *len << " bytes)";
+ return ss.str();
+ }
+ *len -= enclen;
+ *data += enclen;
+ ss << "'" << name << "' ";
+ ares_free_string(name);
+ if (*len < NS_QFIXEDSZ) {
+ ss << "(too short, len left " << *len << ")";
+ return ss.str();
+ }
+ ss << ClassToString(DNS_QUESTION_CLASS(*data)) << " ";
+ ss << RRTypeToString(DNS_QUESTION_TYPE(*data));
+ *data += NS_QFIXEDSZ;
+ *len -= NS_QFIXEDSZ;
+ ss << "}";
+ return ss.str();
+}
+
+std::string RRToString(const std::vector<byte>& packet,
+ const byte** data, int* len) {
+ std::stringstream ss;
+ ss << "{";
+ if (*len < NS_RRFIXEDSZ) {
+ ss << "too short, len " << *len << ")";
+ return ss.str();
+ }
+
+ char *name = nullptr;
+ long enclen;
+ int rc = ares_expand_name(*data, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ return ss.str();
+ }
+ if (enclen > *len) {
+ ss << "(error, encoded name len " << enclen << "bigger than remaining data " << *len << " bytes)";
+ return ss.str();
+ }
+ *len -= enclen;
+ *data += enclen;
+ ss << "'" << name << "' ";
+ ares_free_string(name);
+ name = nullptr;
+
+ if (*len < NS_RRFIXEDSZ) {
+ ss << "(too short, len left " << *len << ")";
+ return ss.str();
+ }
+ int rrtype = DNS_RR_TYPE(*data);
+ if (rrtype == ns_t_opt) {
+ ss << "MAXUDP=" << DNS_RR_CLASS(*data) << " ";
+ ss << RRTypeToString(rrtype) << " ";
+ ss << "RCODE2=" << DNS_RR_TTL(*data);
+ } else {
+ ss << ClassToString(DNS_RR_CLASS(*data)) << " ";
+ ss << RRTypeToString(rrtype) << " ";
+ ss << "TTL=" << DNS_RR_TTL(*data);
+ }
+ int rdatalen = DNS_RR_LEN(*data);
+
+ *data += NS_RRFIXEDSZ;
+ *len -= NS_RRFIXEDSZ;
+ if (*len < rdatalen) {
+ ss << "(RR too long at " << rdatalen << ", len left " << *len << ")";
+ } else {
+ switch (rrtype) {
+ case ns_t_a:
+ case ns_t_aaaa:
+ ss << " " << AddressToString(*data, rdatalen);
+ break;
+ case ns_t_txt: {
+ const byte* p = *data;
+ while (p < (*data + rdatalen)) {
+ int len = *p++;
+ if ((p + len) <= (*data + rdatalen)) {
+ std::string txt(p, p + len);
+ ss << " " << len << ":'" << txt << "'";
+ } else {
+ ss << "(string too long)";
+ }
+ p += len;
+ }
+ break;
+ }
+ case ns_t_cname:
+ case ns_t_ns:
+ case ns_t_ptr: {
+ int rc = ares_expand_name(*data, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ break;
+ }
+ ss << " '" << name << "'";
+ ares_free_string(name);
+ break;
+ }
+ case ns_t_mx:
+ if (rdatalen > 2) {
+ int rc = ares_expand_name(*data + 2, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ break;
+ }
+ ss << " " << DNS__16BIT(*data) << " '" << name << "'";
+ ares_free_string(name);
+ } else {
+ ss << "(RR too short)";
+ }
+ break;
+ case ns_t_srv: {
+ if (rdatalen > 6) {
+ const byte* p = *data;
+ unsigned long prio = DNS__16BIT(p);
+ unsigned long weight = DNS__16BIT(p + 2);
+ unsigned long port = DNS__16BIT(p + 4);
+ p += 6;
+ int rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ break;
+ }
+ ss << prio << " " << weight << " " << port << " '" << name << "'";
+ ares_free_string(name);
+ } else {
+ ss << "(RR too short)";
+ }
+ break;
+ }
+ case ns_t_soa: {
+ const byte* p = *data;
+ int rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ break;
+ }
+ ss << " '" << name << "'";
+ ares_free_string(name);
+ p += enclen;
+ rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ break;
+ }
+ ss << " '" << name << "'";
+ ares_free_string(name);
+ p += enclen;
+ if ((p + 20) <= (*data + rdatalen)) {
+ unsigned long serial = DNS__32BIT(p);
+ unsigned long refresh = DNS__32BIT(p + 4);
+ unsigned long retry = DNS__32BIT(p + 8);
+ unsigned long expire = DNS__32BIT(p + 12);
+ unsigned long minimum = DNS__32BIT(p + 16);
+ ss << " " << serial << " " << refresh << " " << retry << " " << expire << " " << minimum;
+ } else {
+ ss << "(RR too short)";
+ }
+ break;
+ }
+ case ns_t_naptr: {
+ if (rdatalen > 7) {
+ const byte* p = *data;
+ unsigned long order = DNS__16BIT(p);
+ unsigned long pref = DNS__16BIT(p + 2);
+ p += 4;
+ ss << order << " " << pref;
+
+ int len = *p++;
+ std::string flags(p, p + len);
+ ss << " " << flags;
+ p += len;
+
+ len = *p++;
+ std::string service(p, p + len);
+ ss << " '" << service << "'";
+ p += len;
+
+ len = *p++;
+ std::string regexp(p, p + len);
+ ss << " '" << regexp << "'";
+ p += len;
+
+ int rc = ares_expand_name(p, packet.data(), packet.size(), &name, &enclen);
+ if (rc != ARES_SUCCESS) {
+ ss << "(error from ares_expand_name)";
+ break;
+ }
+ ss << " '" << name << "'";
+ ares_free_string(name);
+ } else {
+ ss << "(RR too short)";
+ }
+ break;
+ }
+ default:
+ ss << " " << HexDump(*data, rdatalen);
+ break;
+ }
+ }
+ *data += rdatalen;
+ *len -= rdatalen;
+
+ ss << "}";
+ return ss.str();
+}
+
+void PushInt32(std::vector<byte>* data, int value) {
+ data->push_back((value & 0xff000000) >> 24);
+ data->push_back((value & 0x00ff0000) >> 16);
+ data->push_back((value & 0x0000ff00) >> 8);
+ data->push_back(value & 0x000000ff);
+}
+
+void PushInt16(std::vector<byte>* data, int value) {
+ data->push_back((value & 0xff00) >> 8);
+ data->push_back(value & 0x00ff);
+}
+
+std::vector<byte> EncodeString(const std::string& name) {
+ std::vector<byte> data;
+ std::stringstream ss(name);
+ std::string label;
+ // TODO: cope with escapes
+ while (std::getline(ss, label, '.')) {
+ data.push_back(label.length());
+ data.insert(data.end(), label.begin(), label.end());
+ }
+ data.push_back(0);
+ return data;
+}
+
+std::vector<byte> DNSQuestion::data() const {
+ std::vector<byte> data;
+ std::vector<byte> encname = EncodeString(name_);
+ data.insert(data.end(), encname.begin(), encname.end());
+ PushInt16(&data, rrtype_);
+ PushInt16(&data, qclass_);
+ return data;
+}
+
+std::vector<byte> DNSRR::data() const {
+ std::vector<byte> data = DNSQuestion::data();
+ PushInt32(&data, ttl_);
+ return data;
+}
+
+std::vector<byte> DNSSingleNameRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ std::vector<byte> encname = EncodeString(other_);
+ int len = encname.size();
+ PushInt16(&data, len);
+ data.insert(data.end(), encname.begin(), encname.end());
+ return data;
+}
+
+std::vector<byte> DNSTxtRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ int len = 0;
+ for (const std::string& txt : txt_) {
+ len += (1 + txt.size());
+ }
+ PushInt16(&data, len);
+ for (const std::string& txt : txt_) {
+ data.push_back(txt.size());
+ data.insert(data.end(), txt.begin(), txt.end());
+ }
+ return data;
+}
+
+std::vector<byte> DNSMxRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ std::vector<byte> encname = EncodeString(other_);
+ int len = 2 + encname.size();
+ PushInt16(&data, len);
+ PushInt16(&data, pref_);
+ data.insert(data.end(), encname.begin(), encname.end());
+ return data;
+}
+
+std::vector<byte> DNSSrvRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ std::vector<byte> encname = EncodeString(target_);
+ int len = 6 + encname.size();
+ PushInt16(&data, len);
+ PushInt16(&data, prio_);
+ PushInt16(&data, weight_);
+ PushInt16(&data, port_);
+ data.insert(data.end(), encname.begin(), encname.end());
+ return data;
+}
+
+std::vector<byte> DNSAddressRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ int len = addr_.size();
+ PushInt16(&data, len);
+ data.insert(data.end(), addr_.begin(), addr_.end());
+ return data;
+}
+
+std::vector<byte> DNSSoaRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ std::vector<byte> encname1 = EncodeString(nsname_);
+ std::vector<byte> encname2 = EncodeString(rname_);
+ int len = encname1.size() + encname2.size() + 5*4;
+ PushInt16(&data, len);
+ data.insert(data.end(), encname1.begin(), encname1.end());
+ data.insert(data.end(), encname2.begin(), encname2.end());
+ PushInt32(&data, serial_);
+ PushInt32(&data, refresh_);
+ PushInt32(&data, retry_);
+ PushInt32(&data, expire_);
+ PushInt32(&data, minimum_);
+ return data;
+}
+
+std::vector<byte> DNSOptRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ int len = 0;
+ for (const DNSOption& opt : opts_) {
+ len += (4 + opt.data_.size());
+ }
+ PushInt16(&data, len);
+ for (const DNSOption& opt : opts_) {
+ PushInt16(&data, opt.code_);
+ PushInt16(&data, opt.data_.size());
+ data.insert(data.end(), opt.data_.begin(), opt.data_.end());
+ }
+ return data;
+}
+
+std::vector<byte> DNSNaptrRR::data() const {
+ std::vector<byte> data = DNSRR::data();
+ std::vector<byte> encname = EncodeString(replacement_);
+ int len = (4 + 1 + flags_.size() + 1 + service_.size() + 1 + regexp_.size() + encname.size());
+ PushInt16(&data, len);
+ PushInt16(&data, order_);
+ PushInt16(&data, pref_);
+ data.push_back(flags_.size());
+ data.insert(data.end(), flags_.begin(), flags_.end());
+ data.push_back(service_.size());
+ data.insert(data.end(), service_.begin(), service_.end());
+ data.push_back(regexp_.size());
+ data.insert(data.end(), regexp_.begin(), regexp_.end());
+ data.insert(data.end(), encname.begin(), encname.end());
+ return data;
+}
+
+std::vector<byte> DNSPacket::data() const {
+ std::vector<byte> data;
+ PushInt16(&data, qid_);
+ byte b = 0x00;
+ if (response_) b |= 0x80;
+ b |= ((opcode_ & 0x0f) << 3);
+ if (aa_) b |= 0x04;
+ if (tc_) b |= 0x02;
+ if (rd_) b |= 0x01;
+ data.push_back(b);
+ b = 0x00;
+ if (ra_) b |= 0x80;
+ if (z_) b |= 0x40;
+ if (ad_) b |= 0x20;
+ if (cd_) b |= 0x10;
+ b |= (rcode_ & 0x0f);
+ data.push_back(b);
+
+ int count = questions_.size();
+ PushInt16(&data, count);
+ count = answers_.size();
+ PushInt16(&data, count);
+ count = auths_.size();
+ PushInt16(&data, count);
+ count = adds_.size();
+ PushInt16(&data, count);
+
+ for (const std::unique_ptr<DNSQuestion>& question : questions_) {
+ std::vector<byte> qdata = question->data();
+ data.insert(data.end(), qdata.begin(), qdata.end());
+ }
+ for (const std::unique_ptr<DNSRR>& rr : answers_) {
+ std::vector<byte> rrdata = rr->data();
+ data.insert(data.end(), rrdata.begin(), rrdata.end());
+ }
+ for (const std::unique_ptr<DNSRR>& rr : auths_) {
+ std::vector<byte> rrdata = rr->data();
+ data.insert(data.end(), rrdata.begin(), rrdata.end());
+ }
+ for (const std::unique_ptr<DNSRR>& rr : adds_) {
+ std::vector<byte> rrdata = rr->data();
+ data.insert(data.end(), rrdata.begin(), rrdata.end());
+ }
+ return data;
+}
+
+} // namespace ares
diff --git a/contrib/libs/c-ares/test/dns-proto.h b/contrib/libs/c-ares/test/dns-proto.h
index 346711dfe9..9fcb850153 100644
--- a/contrib/libs/c-ares/test/dns-proto.h
+++ b/contrib/libs/c-ares/test/dns-proto.h
@@ -1,242 +1,242 @@
-// -*- mode: c++ -*-
-#ifndef DNS_PROTO_H
-#define DNS_PROTO_H
-// Utilities for processing DNS packet contents
-
-// Include ares internal file for DNS protocol constants
-#include "nameser.h"
-
-#include <memory>
-#include <string>
-#include <vector>
-
-namespace ares {
-
-typedef unsigned char byte;
-
-std::string HexDump(std::vector<byte> data);
-std::string HexDump(const byte *data, int len);
-std::string HexDump(const char *data, int len);
-
-std::string StatusToString(int status);
-std::string RcodeToString(int rcode);
-std::string RRTypeToString(int rrtype);
-std::string ClassToString(int qclass);
-std::string AddressToString(const void* addr, int len);
-
-// Convert DNS protocol data to strings.
-// Note that these functions are not defensive; they assume
-// a validly formatted input, and so should not be used on
-// externally-determined inputs.
-std::string PacketToString(const std::vector<byte>& packet);
-std::string QuestionToString(const std::vector<byte>& packet,
- const byte** data, int* len);
-std::string RRToString(const std::vector<byte>& packet,
- const byte** data, int* len);
-
-
-// Manipulate DNS protocol data.
-void PushInt32(std::vector<byte>* data, int value);
-void PushInt16(std::vector<byte>* data, int value);
-std::vector<byte> EncodeString(const std::string& name);
-
-struct DNSQuestion {
- DNSQuestion(const std::string& name, ns_type rrtype, ns_class qclass)
- : name_(name), rrtype_(rrtype), qclass_(qclass) {}
- DNSQuestion(const std::string& name, ns_type rrtype)
- : name_(name), rrtype_(rrtype), qclass_(ns_c_in) {}
- virtual ~DNSQuestion() {}
- virtual std::vector<byte> data() const;
- std::string name_;
- ns_type rrtype_;
- ns_class qclass_;
-};
-
-struct DNSRR : public DNSQuestion {
- DNSRR(const std::string& name, ns_type rrtype, ns_class qclass, int ttl)
- : DNSQuestion(name, rrtype, qclass), ttl_(ttl) {}
- DNSRR(const std::string& name, ns_type rrtype, int ttl)
- : DNSQuestion(name, rrtype), ttl_(ttl) {}
- virtual ~DNSRR() {}
- virtual std::vector<byte> data() const = 0;
- int ttl_;
-};
-
-struct DNSAddressRR : public DNSRR {
- DNSAddressRR(const std::string& name, ns_type rrtype, int ttl,
- const byte* addr, int addrlen)
- : DNSRR(name, rrtype, ttl), addr_(addr, addr + addrlen) {}
- DNSAddressRR(const std::string& name, ns_type rrtype, int ttl,
- const std::vector<byte>& addr)
- : DNSRR(name, rrtype, ttl), addr_(addr) {}
- virtual std::vector<byte> data() const;
- std::vector<byte> addr_;
-};
-
-struct DNSARR : public DNSAddressRR {
- DNSARR(const std::string& name, int ttl, const byte* addr, int addrlen)
- : DNSAddressRR(name, ns_t_a, ttl, addr, addrlen) {}
- DNSARR(const std::string& name, int ttl, const std::vector<byte>& addr)
- : DNSAddressRR(name, ns_t_a, ttl, addr) {}
-};
-
-struct DNSAaaaRR : public DNSAddressRR {
- DNSAaaaRR(const std::string& name, int ttl, const byte* addr, int addrlen)
- : DNSAddressRR(name, ns_t_aaaa, ttl, addr, addrlen) {}
- DNSAaaaRR(const std::string& name, int ttl, const std::vector<byte>& addr)
- : DNSAddressRR(name, ns_t_aaaa, ttl, addr) {}
-};
-
-struct DNSSingleNameRR : public DNSRR {
- DNSSingleNameRR(const std::string& name, ns_type rrtype, int ttl,
- const std::string& other)
- : DNSRR(name, rrtype, ttl), other_(other) {}
- virtual std::vector<byte> data() const;
- std::string other_;
-};
-
-struct DNSCnameRR : public DNSSingleNameRR {
- DNSCnameRR(const std::string& name, int ttl, const std::string& other)
- : DNSSingleNameRR(name, ns_t_cname, ttl, other) {}
-};
-
-struct DNSNsRR : public DNSSingleNameRR {
- DNSNsRR(const std::string& name, int ttl, const std::string& other)
- : DNSSingleNameRR(name, ns_t_ns, ttl, other) {}
-};
-
-struct DNSPtrRR : public DNSSingleNameRR {
- DNSPtrRR(const std::string& name, int ttl, const std::string& other)
- : DNSSingleNameRR(name, ns_t_ptr, ttl, other) {}
-};
-
-struct DNSTxtRR : public DNSRR {
- DNSTxtRR(const std::string& name, int ttl, const std::vector<std::string>& txt)
- : DNSRR(name, ns_t_txt, ttl), txt_(txt) {}
- virtual std::vector<byte> data() const;
- std::vector<std::string> txt_;
-};
-
-struct DNSMxRR : public DNSRR {
- DNSMxRR(const std::string& name, int ttl, int pref, const std::string& other)
- : DNSRR(name, ns_t_mx, ttl), pref_(pref), other_(other) {}
- virtual std::vector<byte> data() const;
- int pref_;
- std::string other_;
-};
-
-struct DNSSrvRR : public DNSRR {
- DNSSrvRR(const std::string& name, int ttl,
- int prio, int weight, int port, const std::string& target)
- : DNSRR(name, ns_t_srv, ttl), prio_(prio), weight_(weight), port_(port), target_(target) {}
- virtual std::vector<byte> data() const;
- int prio_;
- int weight_;
- int port_;
- std::string target_;
-};
-
-struct DNSSoaRR : public DNSRR {
- DNSSoaRR(const std::string& name, int ttl,
- const std::string& nsname, const std::string& rname,
- int serial, int refresh, int retry, int expire, int minimum)
- : DNSRR(name, ns_t_soa, ttl), nsname_(nsname), rname_(rname),
- serial_(serial), refresh_(refresh), retry_(retry),
- expire_(expire), minimum_(minimum) {}
- virtual std::vector<byte> data() const;
- std::string nsname_;
- std::string rname_;
- int serial_;
- int refresh_;
- int retry_;
- int expire_;
- int minimum_;
-};
-
-struct DNSNaptrRR : public DNSRR {
- DNSNaptrRR(const std::string& name, int ttl,
- int order, int pref,
- const std::string& flags,
- const std::string& service,
- const std::string& regexp,
- const std::string& replacement)
- : DNSRR(name, ns_t_naptr, ttl), order_(order), pref_(pref),
- flags_(flags), service_(service), regexp_(regexp), replacement_(replacement) {}
- virtual std::vector<byte> data() const;
- int order_;
- int pref_;
- std::string flags_;
- std::string service_;
- std::string regexp_;
- std::string replacement_;
-};
-
-struct DNSOption {
- int code_;
- std::vector<byte> data_;
-};
-
-struct DNSOptRR : public DNSRR {
- DNSOptRR(int extrcode, int udpsize)
- : DNSRR("", ns_t_opt, static_cast<ns_class>(udpsize), extrcode) {}
- virtual std::vector<byte> data() const;
- std::vector<DNSOption> opts_;
-};
-
-struct DNSPacket {
- DNSPacket()
- : qid_(0), response_(false), opcode_(ns_o_query),
- aa_(false), tc_(false), rd_(false), ra_(false),
- z_(false), ad_(false), cd_(false), rcode_(ns_r_noerror) {}
- // Convenience functions that take ownership of given pointers.
- DNSPacket& add_question(DNSQuestion *q) {
- questions_.push_back(std::unique_ptr<DNSQuestion>(q));
- return *this;
- }
- DNSPacket& add_answer(DNSRR *q) {
- answers_.push_back(std::unique_ptr<DNSRR>(q));
- return *this;
- }
- DNSPacket& add_auth(DNSRR *q) {
- auths_.push_back(std::unique_ptr<DNSRR>(q));
- return *this;
- }
- DNSPacket& add_additional(DNSRR *q) {
- adds_.push_back(std::unique_ptr<DNSRR>(q));
- return *this;
- }
- // Chainable setters.
- DNSPacket& set_qid(int qid) { qid_ = qid; return *this; }
- DNSPacket& set_response(bool v = true) { response_ = v; return *this; }
- DNSPacket& set_aa(bool v = true) { aa_ = v; return *this; }
- DNSPacket& set_tc(bool v = true) { tc_ = v; return *this; }
- DNSPacket& set_rd(bool v = true) { rd_ = v; return *this; }
- DNSPacket& set_ra(bool v = true) { ra_ = v; return *this; }
- DNSPacket& set_z(bool v = true) { z_ = v; return *this; }
- DNSPacket& set_ad(bool v = true) { ad_ = v; return *this; }
- DNSPacket& set_cd(bool v = true) { cd_ = v; return *this; }
- DNSPacket& set_rcode(ns_rcode rcode) { rcode_ = rcode; return *this; }
-
- // Return the encoded packet.
- std::vector<byte> data() const;
-
- int qid_;
- bool response_;
- ns_opcode opcode_;
- bool aa_;
- bool tc_;
- bool rd_;
- bool ra_;
- bool z_;
- bool ad_;
- bool cd_;
- ns_rcode rcode_;
- std::vector<std::unique_ptr<DNSQuestion>> questions_;
- std::vector<std::unique_ptr<DNSRR>> answers_;
- std::vector<std::unique_ptr<DNSRR>> auths_;
- std::vector<std::unique_ptr<DNSRR>> adds_;
-};
-
-} // namespace ares
-
-#endif
+// -*- mode: c++ -*-
+#ifndef DNS_PROTO_H
+#define DNS_PROTO_H
+// Utilities for processing DNS packet contents
+
+// Include ares internal file for DNS protocol constants
+#include "nameser.h"
+
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace ares {
+
+typedef unsigned char byte;
+
+std::string HexDump(std::vector<byte> data);
+std::string HexDump(const byte *data, int len);
+std::string HexDump(const char *data, int len);
+
+std::string StatusToString(int status);
+std::string RcodeToString(int rcode);
+std::string RRTypeToString(int rrtype);
+std::string ClassToString(int qclass);
+std::string AddressToString(const void* addr, int len);
+
+// Convert DNS protocol data to strings.
+// Note that these functions are not defensive; they assume
+// a validly formatted input, and so should not be used on
+// externally-determined inputs.
+std::string PacketToString(const std::vector<byte>& packet);
+std::string QuestionToString(const std::vector<byte>& packet,
+ const byte** data, int* len);
+std::string RRToString(const std::vector<byte>& packet,
+ const byte** data, int* len);
+
+
+// Manipulate DNS protocol data.
+void PushInt32(std::vector<byte>* data, int value);
+void PushInt16(std::vector<byte>* data, int value);
+std::vector<byte> EncodeString(const std::string& name);
+
+struct DNSQuestion {
+ DNSQuestion(const std::string& name, ns_type rrtype, ns_class qclass)
+ : name_(name), rrtype_(rrtype), qclass_(qclass) {}
+ DNSQuestion(const std::string& name, ns_type rrtype)
+ : name_(name), rrtype_(rrtype), qclass_(ns_c_in) {}
+ virtual ~DNSQuestion() {}
+ virtual std::vector<byte> data() const;
+ std::string name_;
+ ns_type rrtype_;
+ ns_class qclass_;
+};
+
+struct DNSRR : public DNSQuestion {
+ DNSRR(const std::string& name, ns_type rrtype, ns_class qclass, int ttl)
+ : DNSQuestion(name, rrtype, qclass), ttl_(ttl) {}
+ DNSRR(const std::string& name, ns_type rrtype, int ttl)
+ : DNSQuestion(name, rrtype), ttl_(ttl) {}
+ virtual ~DNSRR() {}
+ virtual std::vector<byte> data() const = 0;
+ int ttl_;
+};
+
+struct DNSAddressRR : public DNSRR {
+ DNSAddressRR(const std::string& name, ns_type rrtype, int ttl,
+ const byte* addr, int addrlen)
+ : DNSRR(name, rrtype, ttl), addr_(addr, addr + addrlen) {}
+ DNSAddressRR(const std::string& name, ns_type rrtype, int ttl,
+ const std::vector<byte>& addr)
+ : DNSRR(name, rrtype, ttl), addr_(addr) {}
+ virtual std::vector<byte> data() const;
+ std::vector<byte> addr_;
+};
+
+struct DNSARR : public DNSAddressRR {
+ DNSARR(const std::string& name, int ttl, const byte* addr, int addrlen)
+ : DNSAddressRR(name, ns_t_a, ttl, addr, addrlen) {}
+ DNSARR(const std::string& name, int ttl, const std::vector<byte>& addr)
+ : DNSAddressRR(name, ns_t_a, ttl, addr) {}
+};
+
+struct DNSAaaaRR : public DNSAddressRR {
+ DNSAaaaRR(const std::string& name, int ttl, const byte* addr, int addrlen)
+ : DNSAddressRR(name, ns_t_aaaa, ttl, addr, addrlen) {}
+ DNSAaaaRR(const std::string& name, int ttl, const std::vector<byte>& addr)
+ : DNSAddressRR(name, ns_t_aaaa, ttl, addr) {}
+};
+
+struct DNSSingleNameRR : public DNSRR {
+ DNSSingleNameRR(const std::string& name, ns_type rrtype, int ttl,
+ const std::string& other)
+ : DNSRR(name, rrtype, ttl), other_(other) {}
+ virtual std::vector<byte> data() const;
+ std::string other_;
+};
+
+struct DNSCnameRR : public DNSSingleNameRR {
+ DNSCnameRR(const std::string& name, int ttl, const std::string& other)
+ : DNSSingleNameRR(name, ns_t_cname, ttl, other) {}
+};
+
+struct DNSNsRR : public DNSSingleNameRR {
+ DNSNsRR(const std::string& name, int ttl, const std::string& other)
+ : DNSSingleNameRR(name, ns_t_ns, ttl, other) {}
+};
+
+struct DNSPtrRR : public DNSSingleNameRR {
+ DNSPtrRR(const std::string& name, int ttl, const std::string& other)
+ : DNSSingleNameRR(name, ns_t_ptr, ttl, other) {}
+};
+
+struct DNSTxtRR : public DNSRR {
+ DNSTxtRR(const std::string& name, int ttl, const std::vector<std::string>& txt)
+ : DNSRR(name, ns_t_txt, ttl), txt_(txt) {}
+ virtual std::vector<byte> data() const;
+ std::vector<std::string> txt_;
+};
+
+struct DNSMxRR : public DNSRR {
+ DNSMxRR(const std::string& name, int ttl, int pref, const std::string& other)
+ : DNSRR(name, ns_t_mx, ttl), pref_(pref), other_(other) {}
+ virtual std::vector<byte> data() const;
+ int pref_;
+ std::string other_;
+};
+
+struct DNSSrvRR : public DNSRR {
+ DNSSrvRR(const std::string& name, int ttl,
+ int prio, int weight, int port, const std::string& target)
+ : DNSRR(name, ns_t_srv, ttl), prio_(prio), weight_(weight), port_(port), target_(target) {}
+ virtual std::vector<byte> data() const;
+ int prio_;
+ int weight_;
+ int port_;
+ std::string target_;
+};
+
+struct DNSSoaRR : public DNSRR {
+ DNSSoaRR(const std::string& name, int ttl,
+ const std::string& nsname, const std::string& rname,
+ int serial, int refresh, int retry, int expire, int minimum)
+ : DNSRR(name, ns_t_soa, ttl), nsname_(nsname), rname_(rname),
+ serial_(serial), refresh_(refresh), retry_(retry),
+ expire_(expire), minimum_(minimum) {}
+ virtual std::vector<byte> data() const;
+ std::string nsname_;
+ std::string rname_;
+ int serial_;
+ int refresh_;
+ int retry_;
+ int expire_;
+ int minimum_;
+};
+
+struct DNSNaptrRR : public DNSRR {
+ DNSNaptrRR(const std::string& name, int ttl,
+ int order, int pref,
+ const std::string& flags,
+ const std::string& service,
+ const std::string& regexp,
+ const std::string& replacement)
+ : DNSRR(name, ns_t_naptr, ttl), order_(order), pref_(pref),
+ flags_(flags), service_(service), regexp_(regexp), replacement_(replacement) {}
+ virtual std::vector<byte> data() const;
+ int order_;
+ int pref_;
+ std::string flags_;
+ std::string service_;
+ std::string regexp_;
+ std::string replacement_;
+};
+
+struct DNSOption {
+ int code_;
+ std::vector<byte> data_;
+};
+
+struct DNSOptRR : public DNSRR {
+ DNSOptRR(int extrcode, int udpsize)
+ : DNSRR("", ns_t_opt, static_cast<ns_class>(udpsize), extrcode) {}
+ virtual std::vector<byte> data() const;
+ std::vector<DNSOption> opts_;
+};
+
+struct DNSPacket {
+ DNSPacket()
+ : qid_(0), response_(false), opcode_(ns_o_query),
+ aa_(false), tc_(false), rd_(false), ra_(false),
+ z_(false), ad_(false), cd_(false), rcode_(ns_r_noerror) {}
+ // Convenience functions that take ownership of given pointers.
+ DNSPacket& add_question(DNSQuestion *q) {
+ questions_.push_back(std::unique_ptr<DNSQuestion>(q));
+ return *this;
+ }
+ DNSPacket& add_answer(DNSRR *q) {
+ answers_.push_back(std::unique_ptr<DNSRR>(q));
+ return *this;
+ }
+ DNSPacket& add_auth(DNSRR *q) {
+ auths_.push_back(std::unique_ptr<DNSRR>(q));
+ return *this;
+ }
+ DNSPacket& add_additional(DNSRR *q) {
+ adds_.push_back(std::unique_ptr<DNSRR>(q));
+ return *this;
+ }
+ // Chainable setters.
+ DNSPacket& set_qid(int qid) { qid_ = qid; return *this; }
+ DNSPacket& set_response(bool v = true) { response_ = v; return *this; }
+ DNSPacket& set_aa(bool v = true) { aa_ = v; return *this; }
+ DNSPacket& set_tc(bool v = true) { tc_ = v; return *this; }
+ DNSPacket& set_rd(bool v = true) { rd_ = v; return *this; }
+ DNSPacket& set_ra(bool v = true) { ra_ = v; return *this; }
+ DNSPacket& set_z(bool v = true) { z_ = v; return *this; }
+ DNSPacket& set_ad(bool v = true) { ad_ = v; return *this; }
+ DNSPacket& set_cd(bool v = true) { cd_ = v; return *this; }
+ DNSPacket& set_rcode(ns_rcode rcode) { rcode_ = rcode; return *this; }
+
+ // Return the encoded packet.
+ std::vector<byte> data() const;
+
+ int qid_;
+ bool response_;
+ ns_opcode opcode_;
+ bool aa_;
+ bool tc_;
+ bool rd_;
+ bool ra_;
+ bool z_;
+ bool ad_;
+ bool cd_;
+ ns_rcode rcode_;
+ std::vector<std::unique_ptr<DNSQuestion>> questions_;
+ std::vector<std::unique_ptr<DNSRR>> answers_;
+ std::vector<std::unique_ptr<DNSRR>> auths_;
+ std::vector<std::unique_ptr<DNSRR>> adds_;
+};
+
+} // namespace ares
+
+#endif
diff --git a/contrib/libs/c-ares/test/ya.make b/contrib/libs/c-ares/test/ya.make
index ef42eab230..fb81afa54e 100644
--- a/contrib/libs/c-ares/test/ya.make
+++ b/contrib/libs/c-ares/test/ya.make
@@ -1,60 +1,60 @@
-# Generated by devtools/yamaker.
-
+# Generated by devtools/yamaker.
+
GTEST(arestest)
-
+
OWNER(max42 g:cpp-contrib)
-
-LICENSE(MIT)
-
-SIZE(MEDIUM)
-
-TAG(ya:external)
-
-REQUIREMENTS(network:full)
-
-PEERDIR(
- contrib/libs/c-ares
-)
-
-ADDINCL(
- contrib/libs/c-ares
- contrib/libs/c-ares/test
-)
-
-NO_COMPILER_WARNINGS()
-
+
+LICENSE(MIT)
+
+SIZE(MEDIUM)
+
+TAG(ya:external)
+
+REQUIREMENTS(network:full)
+
+PEERDIR(
+ contrib/libs/c-ares
+)
+
+ADDINCL(
+ contrib/libs/c-ares
+ contrib/libs/c-ares/test
+)
+
+NO_COMPILER_WARNINGS()
+
CFLAGS(
-DHAVE_CONFIG_H
)
-IF (NOT DLL_FOR)
- CFLAGS(
- -DCARES_STATICLIB
- )
-ENDIF()
-
-SRCS(
- ares-test-init.cc
- ares-test-internal.cc
- ares-test-live.cc
- ares-test-misc.cc
+IF (NOT DLL_FOR)
+ CFLAGS(
+ -DCARES_STATICLIB
+ )
+ENDIF()
+
+SRCS(
+ ares-test-init.cc
+ ares-test-internal.cc
+ ares-test-live.cc
+ ares-test-misc.cc
ares-test-mock-ai.cc
- ares-test-mock.cc
- ares-test-ns.cc
- ares-test-parse-a.cc
- ares-test-parse-aaaa.cc
- ares-test-parse-mx.cc
- ares-test-parse-naptr.cc
- ares-test-parse-ns.cc
- ares-test-parse-ptr.cc
+ ares-test-mock.cc
+ ares-test-ns.cc
+ ares-test-parse-a.cc
+ ares-test-parse-aaaa.cc
+ ares-test-parse-mx.cc
+ ares-test-parse-naptr.cc
+ ares-test-parse-ns.cc
+ ares-test-parse-ptr.cc
ares-test-parse-soa-any.cc
- ares-test-parse-soa.cc
- ares-test-parse-srv.cc
- ares-test-parse-txt.cc
- ares-test-parse.cc
- ares-test.cc
- dns-proto-test.cc
- dns-proto.cc
-)
-
-END()
+ ares-test-parse-soa.cc
+ ares-test-parse-srv.cc
+ ares-test-parse-txt.cc
+ ares-test-parse.cc
+ ares-test.cc
+ dns-proto-test.cc
+ dns-proto.cc
+)
+
+END()
diff --git a/contrib/libs/c-ares/ya.make b/contrib/libs/c-ares/ya.make
index bd35762e44..29d591935e 100644
--- a/contrib/libs/c-ares/ya.make
+++ b/contrib/libs/c-ares/ya.make
@@ -1,5 +1,5 @@
# Generated by devtools/yamaker from nixpkgs e392df43c9f302d4a0892caaadcad3cd693edf9e.
-
+
LIBRARY()
OWNER(
@@ -8,7 +8,7 @@ OWNER(
)
VERSION(1.16.1)
-
+
ORIGINAL_SOURCE(https://c-ares.haxx.se/download/c-ares-1.16.1.tar.gz)
LICENSE(
@@ -30,12 +30,12 @@ ADDINCL(
NO_COMPILER_WARNINGS()
-CFLAGS(
- -DCARES_BUILDING_LIBRARY
- -DCARES_SYMBOL_HIDING
+CFLAGS(
+ -DCARES_BUILDING_LIBRARY
+ -DCARES_SYMBOL_HIDING
-DHAVE_CONFIG_H
-)
-
+)
+
IF (NOT DLL_FOR)
CFLAGS(
-DCARES_STATICLIB
@@ -97,7 +97,7 @@ SRCS(
ares_strcasecmp.c
ares_strdup.c
ares_strerror.c
- ares_strsplit.c
+ ares_strsplit.c
ares_timeout.c
ares_version.c
ares_writev.c
@@ -111,10 +111,10 @@ SRCS(
CHECK_CONFIG_H(ares_setup.h)
END()
-
-RECURSE(
- acountry
- adig
- ahost
- test
-)
+
+RECURSE(
+ acountry
+ adig
+ ahost
+ test
+)
diff --git a/contrib/libs/grpc/AUTHORS b/contrib/libs/grpc/AUTHORS
index 0c5fee8c73..1214d56b28 100644
--- a/contrib/libs/grpc/AUTHORS
+++ b/contrib/libs/grpc/AUTHORS
@@ -1,4 +1,4 @@
-Dropbox, Inc.
-Google Inc.
-Skyscanner Ltd.
-WeWork Companies Inc.
+Dropbox, Inc.
+Google Inc.
+Skyscanner Ltd.
+WeWork Companies Inc.
diff --git a/contrib/libs/grpc/BUILD.gn b/contrib/libs/grpc/BUILD.gn
index 4d69b1d336..9c6d3a5b84 100644
--- a/contrib/libs/grpc/BUILD.gn
+++ b/contrib/libs/grpc/BUILD.gn
@@ -1,392 +1,392 @@
-# GRPC Fuchsia GN build file
-
-# This file has been automatically generated from a template file.
-# Please look at the templates directory instead.
-# This file can be regenerated from the template by running
-# tools/buildgen/generate_projects.sh
-
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-config("grpc_config") {
- include_dirs = [
- ".",
- "include/",
- ]
- defines = [
- "GRPC_USE_PROTO_LITE",
- "GPR_SUPPORT_CHANNELS_FROM_FD",
- "PB_FIELD_16BIT",
- ]
-}
-
-
-
- source_set("address_sorting") {
- sources = [
- "third_party/address_sorting/address_sorting.c",
- "third_party/address_sorting/address_sorting_internal.h",
- "third_party/address_sorting/address_sorting_posix.c",
- "third_party/address_sorting/address_sorting_windows.c",
- "third_party/address_sorting/include/address_sorting/address_sorting.h",
- ]
- deps = [
- ]
-
- public_configs = [
- ":grpc_config",
- ]
- include_dirs = [
- "third_party/address_sorting/include",
- ]
- }
-
-
-
- source_set("gpr") {
- sources = [
- "include/grpc/impl/codegen/atm.h",
- "include/grpc/impl/codegen/atm_gcc_atomic.h",
- "include/grpc/impl/codegen/atm_gcc_sync.h",
- "include/grpc/impl/codegen/atm_windows.h",
+# GRPC Fuchsia GN build file
+
+# This file has been automatically generated from a template file.
+# Please look at the templates directory instead.
+# This file can be regenerated from the template by running
+# tools/buildgen/generate_projects.sh
+
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+config("grpc_config") {
+ include_dirs = [
+ ".",
+ "include/",
+ ]
+ defines = [
+ "GRPC_USE_PROTO_LITE",
+ "GPR_SUPPORT_CHANNELS_FROM_FD",
+ "PB_FIELD_16BIT",
+ ]
+}
+
+
+
+ source_set("address_sorting") {
+ sources = [
+ "third_party/address_sorting/address_sorting.c",
+ "third_party/address_sorting/address_sorting_internal.h",
+ "third_party/address_sorting/address_sorting_posix.c",
+ "third_party/address_sorting/address_sorting_windows.c",
+ "third_party/address_sorting/include/address_sorting/address_sorting.h",
+ ]
+ deps = [
+ ]
+
+ public_configs = [
+ ":grpc_config",
+ ]
+ include_dirs = [
+ "third_party/address_sorting/include",
+ ]
+ }
+
+
+
+ source_set("gpr") {
+ sources = [
+ "include/grpc/impl/codegen/atm.h",
+ "include/grpc/impl/codegen/atm_gcc_atomic.h",
+ "include/grpc/impl/codegen/atm_gcc_sync.h",
+ "include/grpc/impl/codegen/atm_windows.h",
"include/grpc/impl/codegen/byte_buffer.h",
"include/grpc/impl/codegen/byte_buffer_reader.h",
"include/grpc/impl/codegen/compression_types.h",
"include/grpc/impl/codegen/connectivity_state.h",
- "include/grpc/impl/codegen/fork.h",
- "include/grpc/impl/codegen/gpr_slice.h",
- "include/grpc/impl/codegen/gpr_types.h",
+ "include/grpc/impl/codegen/fork.h",
+ "include/grpc/impl/codegen/gpr_slice.h",
+ "include/grpc/impl/codegen/gpr_types.h",
"include/grpc/impl/codegen/grpc_types.h",
- "include/grpc/impl/codegen/log.h",
- "include/grpc/impl/codegen/port_platform.h",
+ "include/grpc/impl/codegen/log.h",
+ "include/grpc/impl/codegen/port_platform.h",
"include/grpc/impl/codegen/propagation_bits.h",
"include/grpc/impl/codegen/slice.h",
"include/grpc/impl/codegen/status.h",
- "include/grpc/impl/codegen/sync.h",
+ "include/grpc/impl/codegen/sync.h",
"include/grpc/impl/codegen/sync_abseil.h",
- "include/grpc/impl/codegen/sync_custom.h",
- "include/grpc/impl/codegen/sync_generic.h",
- "include/grpc/impl/codegen/sync_posix.h",
- "include/grpc/impl/codegen/sync_windows.h",
- "include/grpc/support/alloc.h",
- "include/grpc/support/atm.h",
- "include/grpc/support/atm_gcc_atomic.h",
- "include/grpc/support/atm_gcc_sync.h",
- "include/grpc/support/atm_windows.h",
- "include/grpc/support/cpu.h",
- "include/grpc/support/log.h",
- "include/grpc/support/log_windows.h",
- "include/grpc/support/port_platform.h",
- "include/grpc/support/string_util.h",
- "include/grpc/support/sync.h",
+ "include/grpc/impl/codegen/sync_custom.h",
+ "include/grpc/impl/codegen/sync_generic.h",
+ "include/grpc/impl/codegen/sync_posix.h",
+ "include/grpc/impl/codegen/sync_windows.h",
+ "include/grpc/support/alloc.h",
+ "include/grpc/support/atm.h",
+ "include/grpc/support/atm_gcc_atomic.h",
+ "include/grpc/support/atm_gcc_sync.h",
+ "include/grpc/support/atm_windows.h",
+ "include/grpc/support/cpu.h",
+ "include/grpc/support/log.h",
+ "include/grpc/support/log_windows.h",
+ "include/grpc/support/port_platform.h",
+ "include/grpc/support/string_util.h",
+ "include/grpc/support/sync.h",
"include/grpc/support/sync_abseil.h",
- "include/grpc/support/sync_custom.h",
- "include/grpc/support/sync_generic.h",
- "include/grpc/support/sync_posix.h",
- "include/grpc/support/sync_windows.h",
- "include/grpc/support/thd_id.h",
- "include/grpc/support/time.h",
- "src/core/lib/gpr/alloc.cc",
- "src/core/lib/gpr/alloc.h",
- "src/core/lib/gpr/arena.h",
- "src/core/lib/gpr/atm.cc",
- "src/core/lib/gpr/cpu_iphone.cc",
- "src/core/lib/gpr/cpu_linux.cc",
- "src/core/lib/gpr/cpu_posix.cc",
- "src/core/lib/gpr/cpu_windows.cc",
- "src/core/lib/gpr/env.h",
- "src/core/lib/gpr/env_linux.cc",
- "src/core/lib/gpr/env_posix.cc",
- "src/core/lib/gpr/env_windows.cc",
- "src/core/lib/gpr/log.cc",
- "src/core/lib/gpr/log_android.cc",
- "src/core/lib/gpr/log_linux.cc",
- "src/core/lib/gpr/log_posix.cc",
- "src/core/lib/gpr/log_windows.cc",
- "src/core/lib/gpr/murmur_hash.cc",
- "src/core/lib/gpr/murmur_hash.h",
- "src/core/lib/gpr/spinlock.h",
- "src/core/lib/gpr/string.cc",
- "src/core/lib/gpr/string.h",
- "src/core/lib/gpr/string_posix.cc",
- "src/core/lib/gpr/string_util_windows.cc",
- "src/core/lib/gpr/string_windows.cc",
- "src/core/lib/gpr/string_windows.h",
- "src/core/lib/gpr/sync.cc",
+ "include/grpc/support/sync_custom.h",
+ "include/grpc/support/sync_generic.h",
+ "include/grpc/support/sync_posix.h",
+ "include/grpc/support/sync_windows.h",
+ "include/grpc/support/thd_id.h",
+ "include/grpc/support/time.h",
+ "src/core/lib/gpr/alloc.cc",
+ "src/core/lib/gpr/alloc.h",
+ "src/core/lib/gpr/arena.h",
+ "src/core/lib/gpr/atm.cc",
+ "src/core/lib/gpr/cpu_iphone.cc",
+ "src/core/lib/gpr/cpu_linux.cc",
+ "src/core/lib/gpr/cpu_posix.cc",
+ "src/core/lib/gpr/cpu_windows.cc",
+ "src/core/lib/gpr/env.h",
+ "src/core/lib/gpr/env_linux.cc",
+ "src/core/lib/gpr/env_posix.cc",
+ "src/core/lib/gpr/env_windows.cc",
+ "src/core/lib/gpr/log.cc",
+ "src/core/lib/gpr/log_android.cc",
+ "src/core/lib/gpr/log_linux.cc",
+ "src/core/lib/gpr/log_posix.cc",
+ "src/core/lib/gpr/log_windows.cc",
+ "src/core/lib/gpr/murmur_hash.cc",
+ "src/core/lib/gpr/murmur_hash.h",
+ "src/core/lib/gpr/spinlock.h",
+ "src/core/lib/gpr/string.cc",
+ "src/core/lib/gpr/string.h",
+ "src/core/lib/gpr/string_posix.cc",
+ "src/core/lib/gpr/string_util_windows.cc",
+ "src/core/lib/gpr/string_windows.cc",
+ "src/core/lib/gpr/string_windows.h",
+ "src/core/lib/gpr/sync.cc",
"src/core/lib/gpr/sync_abseil.cc",
- "src/core/lib/gpr/sync_posix.cc",
- "src/core/lib/gpr/sync_windows.cc",
- "src/core/lib/gpr/time.cc",
- "src/core/lib/gpr/time_posix.cc",
- "src/core/lib/gpr/time_precise.cc",
- "src/core/lib/gpr/time_precise.h",
- "src/core/lib/gpr/time_windows.cc",
- "src/core/lib/gpr/tls.h",
- "src/core/lib/gpr/tls_gcc.h",
- "src/core/lib/gpr/tls_msvc.h",
- "src/core/lib/gpr/tls_pthread.cc",
- "src/core/lib/gpr/tls_pthread.h",
- "src/core/lib/gpr/tmpfile.h",
- "src/core/lib/gpr/tmpfile_msys.cc",
- "src/core/lib/gpr/tmpfile_posix.cc",
- "src/core/lib/gpr/tmpfile_windows.cc",
- "src/core/lib/gpr/useful.h",
- "src/core/lib/gpr/wrap_memcpy.cc",
- "src/core/lib/gprpp/arena.cc",
- "src/core/lib/gprpp/arena.h",
- "src/core/lib/gprpp/atomic.h",
- "src/core/lib/gprpp/fork.cc",
- "src/core/lib/gprpp/fork.h",
- "src/core/lib/gprpp/global_config.h",
- "src/core/lib/gprpp/global_config_custom.h",
- "src/core/lib/gprpp/global_config_env.cc",
- "src/core/lib/gprpp/global_config_env.h",
- "src/core/lib/gprpp/global_config_generic.h",
- "src/core/lib/gprpp/host_port.cc",
- "src/core/lib/gprpp/host_port.h",
- "src/core/lib/gprpp/manual_constructor.h",
- "src/core/lib/gprpp/map.h",
- "src/core/lib/gprpp/memory.h",
- "src/core/lib/gprpp/mpscq.cc",
- "src/core/lib/gprpp/mpscq.h",
- "src/core/lib/gprpp/sync.h",
- "src/core/lib/gprpp/thd.h",
- "src/core/lib/gprpp/thd_posix.cc",
- "src/core/lib/gprpp/thd_windows.cc",
- "src/core/lib/profiling/basic_timers.cc",
- "src/core/lib/profiling/stap_timers.cc",
- "src/core/lib/profiling/timers.h",
- ]
- deps = [
+ "src/core/lib/gpr/sync_posix.cc",
+ "src/core/lib/gpr/sync_windows.cc",
+ "src/core/lib/gpr/time.cc",
+ "src/core/lib/gpr/time_posix.cc",
+ "src/core/lib/gpr/time_precise.cc",
+ "src/core/lib/gpr/time_precise.h",
+ "src/core/lib/gpr/time_windows.cc",
+ "src/core/lib/gpr/tls.h",
+ "src/core/lib/gpr/tls_gcc.h",
+ "src/core/lib/gpr/tls_msvc.h",
+ "src/core/lib/gpr/tls_pthread.cc",
+ "src/core/lib/gpr/tls_pthread.h",
+ "src/core/lib/gpr/tmpfile.h",
+ "src/core/lib/gpr/tmpfile_msys.cc",
+ "src/core/lib/gpr/tmpfile_posix.cc",
+ "src/core/lib/gpr/tmpfile_windows.cc",
+ "src/core/lib/gpr/useful.h",
+ "src/core/lib/gpr/wrap_memcpy.cc",
+ "src/core/lib/gprpp/arena.cc",
+ "src/core/lib/gprpp/arena.h",
+ "src/core/lib/gprpp/atomic.h",
+ "src/core/lib/gprpp/fork.cc",
+ "src/core/lib/gprpp/fork.h",
+ "src/core/lib/gprpp/global_config.h",
+ "src/core/lib/gprpp/global_config_custom.h",
+ "src/core/lib/gprpp/global_config_env.cc",
+ "src/core/lib/gprpp/global_config_env.h",
+ "src/core/lib/gprpp/global_config_generic.h",
+ "src/core/lib/gprpp/host_port.cc",
+ "src/core/lib/gprpp/host_port.h",
+ "src/core/lib/gprpp/manual_constructor.h",
+ "src/core/lib/gprpp/map.h",
+ "src/core/lib/gprpp/memory.h",
+ "src/core/lib/gprpp/mpscq.cc",
+ "src/core/lib/gprpp/mpscq.h",
+ "src/core/lib/gprpp/sync.h",
+ "src/core/lib/gprpp/thd.h",
+ "src/core/lib/gprpp/thd_posix.cc",
+ "src/core/lib/gprpp/thd_windows.cc",
+ "src/core/lib/profiling/basic_timers.cc",
+ "src/core/lib/profiling/stap_timers.cc",
+ "src/core/lib/profiling/timers.h",
+ ]
+ deps = [
":y_absl/time:time",
":y_absl/synchronization:synchronization",
":y_absl/strings:strings",
":y_absl/strings:str_format",
":y_absl/memory:memory",
":y_absl/base:base",
- ]
-
- public_configs = [
- ":grpc_config",
- ]
- }
-
-
-
- source_set("grpc") {
- sources = [
- "include/grpc/byte_buffer.h",
- "include/grpc/byte_buffer_reader.h",
- "include/grpc/census.h",
- "include/grpc/compression.h",
- "include/grpc/fork.h",
- "include/grpc/grpc.h",
- "include/grpc/grpc_posix.h",
- "include/grpc/grpc_security.h",
- "include/grpc/grpc_security_constants.h",
- "include/grpc/load_reporting.h",
- "include/grpc/slice.h",
- "include/grpc/slice_buffer.h",
- "include/grpc/status.h",
- "include/grpc/support/workaround_list.h",
- "src/core/ext/filters/census/grpc_context.cc",
- "src/core/ext/filters/client_channel/backend_metric.cc",
- "src/core/ext/filters/client_channel/backend_metric.h",
- "src/core/ext/filters/client_channel/backup_poller.cc",
- "src/core/ext/filters/client_channel/backup_poller.h",
- "src/core/ext/filters/client_channel/channel_connectivity.cc",
- "src/core/ext/filters/client_channel/client_channel.cc",
- "src/core/ext/filters/client_channel/client_channel.h",
- "src/core/ext/filters/client_channel/client_channel_channelz.cc",
- "src/core/ext/filters/client_channel/client_channel_channelz.h",
- "src/core/ext/filters/client_channel/client_channel_factory.cc",
- "src/core/ext/filters/client_channel/client_channel_factory.h",
- "src/core/ext/filters/client_channel/client_channel_plugin.cc",
+ ]
+
+ public_configs = [
+ ":grpc_config",
+ ]
+ }
+
+
+
+ source_set("grpc") {
+ sources = [
+ "include/grpc/byte_buffer.h",
+ "include/grpc/byte_buffer_reader.h",
+ "include/grpc/census.h",
+ "include/grpc/compression.h",
+ "include/grpc/fork.h",
+ "include/grpc/grpc.h",
+ "include/grpc/grpc_posix.h",
+ "include/grpc/grpc_security.h",
+ "include/grpc/grpc_security_constants.h",
+ "include/grpc/load_reporting.h",
+ "include/grpc/slice.h",
+ "include/grpc/slice_buffer.h",
+ "include/grpc/status.h",
+ "include/grpc/support/workaround_list.h",
+ "src/core/ext/filters/census/grpc_context.cc",
+ "src/core/ext/filters/client_channel/backend_metric.cc",
+ "src/core/ext/filters/client_channel/backend_metric.h",
+ "src/core/ext/filters/client_channel/backup_poller.cc",
+ "src/core/ext/filters/client_channel/backup_poller.h",
+ "src/core/ext/filters/client_channel/channel_connectivity.cc",
+ "src/core/ext/filters/client_channel/client_channel.cc",
+ "src/core/ext/filters/client_channel/client_channel.h",
+ "src/core/ext/filters/client_channel/client_channel_channelz.cc",
+ "src/core/ext/filters/client_channel/client_channel_channelz.h",
+ "src/core/ext/filters/client_channel/client_channel_factory.cc",
+ "src/core/ext/filters/client_channel/client_channel_factory.h",
+ "src/core/ext/filters/client_channel/client_channel_plugin.cc",
"src/core/ext/filters/client_channel/config_selector.cc",
"src/core/ext/filters/client_channel/config_selector.h",
- "src/core/ext/filters/client_channel/connector.h",
- "src/core/ext/filters/client_channel/global_subchannel_pool.cc",
- "src/core/ext/filters/client_channel/global_subchannel_pool.h",
- "src/core/ext/filters/client_channel/health/health_check_client.cc",
- "src/core/ext/filters/client_channel/health/health_check_client.h",
- "src/core/ext/filters/client_channel/http_connect_handshaker.cc",
- "src/core/ext/filters/client_channel/http_connect_handshaker.h",
- "src/core/ext/filters/client_channel/http_proxy.cc",
- "src/core/ext/filters/client_channel/http_proxy.h",
- "src/core/ext/filters/client_channel/lb_policy.cc",
- "src/core/ext/filters/client_channel/lb_policy.h",
+ "src/core/ext/filters/client_channel/connector.h",
+ "src/core/ext/filters/client_channel/global_subchannel_pool.cc",
+ "src/core/ext/filters/client_channel/global_subchannel_pool.h",
+ "src/core/ext/filters/client_channel/health/health_check_client.cc",
+ "src/core/ext/filters/client_channel/health/health_check_client.h",
+ "src/core/ext/filters/client_channel/http_connect_handshaker.cc",
+ "src/core/ext/filters/client_channel/http_connect_handshaker.h",
+ "src/core/ext/filters/client_channel/http_proxy.cc",
+ "src/core/ext/filters/client_channel/http_proxy.h",
+ "src/core/ext/filters/client_channel/lb_policy.cc",
+ "src/core/ext/filters/client_channel/lb_policy.h",
"src/core/ext/filters/client_channel/lb_policy/address_filtering.cc",
"src/core/ext/filters/client_channel/lb_policy/address_filtering.h",
"src/core/ext/filters/client_channel/lb_policy/child_policy_handler.cc",
"src/core/ext/filters/client_channel/lb_policy/child_policy_handler.h",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h",
"src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.cc",
"src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc",
- "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h",
- "src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc",
+ "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h",
+ "src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc",
"src/core/ext/filters/client_channel/lb_policy/priority/priority.cc",
- "src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc",
- "src/core/ext/filters/client_channel/lb_policy/subchannel_list.h",
+ "src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc",
+ "src/core/ext/filters/client_channel/lb_policy/subchannel_list.h",
"src/core/ext/filters/client_channel/lb_policy/weighted_target/weighted_target.cc",
- "src/core/ext/filters/client_channel/lb_policy/xds/cds.cc",
+ "src/core/ext/filters/client_channel/lb_policy/xds/cds.cc",
"src/core/ext/filters/client_channel/lb_policy/xds/eds.cc",
"src/core/ext/filters/client_channel/lb_policy/xds/eds_drop.cc",
- "src/core/ext/filters/client_channel/lb_policy/xds/xds.h",
+ "src/core/ext/filters/client_channel/lb_policy/xds/xds.h",
"src/core/ext/filters/client_channel/lb_policy/xds/xds_cluster_manager.cc",
- "src/core/ext/filters/client_channel/lb_policy_factory.h",
- "src/core/ext/filters/client_channel/lb_policy_registry.cc",
- "src/core/ext/filters/client_channel/lb_policy_registry.h",
- "src/core/ext/filters/client_channel/local_subchannel_pool.cc",
- "src/core/ext/filters/client_channel/local_subchannel_pool.h",
- "src/core/ext/filters/client_channel/proxy_mapper.h",
- "src/core/ext/filters/client_channel/proxy_mapper_registry.cc",
- "src/core/ext/filters/client_channel/proxy_mapper_registry.h",
- "src/core/ext/filters/client_channel/resolver.cc",
- "src/core/ext/filters/client_channel/resolver.h",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc",
- "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc",
- "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc",
- "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h",
- "src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc",
- "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc",
- "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h",
- "src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc",
- "src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc",
+ "src/core/ext/filters/client_channel/lb_policy_factory.h",
+ "src/core/ext/filters/client_channel/lb_policy_registry.cc",
+ "src/core/ext/filters/client_channel/lb_policy_registry.h",
+ "src/core/ext/filters/client_channel/local_subchannel_pool.cc",
+ "src/core/ext/filters/client_channel/local_subchannel_pool.h",
+ "src/core/ext/filters/client_channel/proxy_mapper.h",
+ "src/core/ext/filters/client_channel/proxy_mapper_registry.cc",
+ "src/core/ext/filters/client_channel/proxy_mapper_registry.h",
+ "src/core/ext/filters/client_channel/resolver.cc",
+ "src/core/ext/filters/client_channel/resolver.h",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc",
+ "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h",
+ "src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc",
+ "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc",
+ "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h",
+ "src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc",
+ "src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc",
"src/core/ext/filters/client_channel/resolver/xds/xds_resolver.h",
- "src/core/ext/filters/client_channel/resolver_factory.h",
- "src/core/ext/filters/client_channel/resolver_registry.cc",
- "src/core/ext/filters/client_channel/resolver_registry.h",
- "src/core/ext/filters/client_channel/resolver_result_parsing.cc",
- "src/core/ext/filters/client_channel/resolver_result_parsing.h",
- "src/core/ext/filters/client_channel/resolving_lb_policy.cc",
- "src/core/ext/filters/client_channel/resolving_lb_policy.h",
- "src/core/ext/filters/client_channel/retry_throttle.cc",
- "src/core/ext/filters/client_channel/retry_throttle.h",
- "src/core/ext/filters/client_channel/server_address.cc",
- "src/core/ext/filters/client_channel/server_address.h",
- "src/core/ext/filters/client_channel/service_config.cc",
- "src/core/ext/filters/client_channel/service_config.h",
+ "src/core/ext/filters/client_channel/resolver_factory.h",
+ "src/core/ext/filters/client_channel/resolver_registry.cc",
+ "src/core/ext/filters/client_channel/resolver_registry.h",
+ "src/core/ext/filters/client_channel/resolver_result_parsing.cc",
+ "src/core/ext/filters/client_channel/resolver_result_parsing.h",
+ "src/core/ext/filters/client_channel/resolving_lb_policy.cc",
+ "src/core/ext/filters/client_channel/resolving_lb_policy.h",
+ "src/core/ext/filters/client_channel/retry_throttle.cc",
+ "src/core/ext/filters/client_channel/retry_throttle.h",
+ "src/core/ext/filters/client_channel/server_address.cc",
+ "src/core/ext/filters/client_channel/server_address.h",
+ "src/core/ext/filters/client_channel/service_config.cc",
+ "src/core/ext/filters/client_channel/service_config.h",
"src/core/ext/filters/client_channel/service_config_call_data.h",
"src/core/ext/filters/client_channel/service_config_channel_arg_filter.cc",
"src/core/ext/filters/client_channel/service_config_parser.cc",
"src/core/ext/filters/client_channel/service_config_parser.h",
- "src/core/ext/filters/client_channel/subchannel.cc",
- "src/core/ext/filters/client_channel/subchannel.h",
- "src/core/ext/filters/client_channel/subchannel_interface.h",
- "src/core/ext/filters/client_channel/subchannel_pool_interface.cc",
- "src/core/ext/filters/client_channel/subchannel_pool_interface.h",
- "src/core/ext/filters/client_idle/client_idle_filter.cc",
- "src/core/ext/filters/deadline/deadline_filter.cc",
- "src/core/ext/filters/deadline/deadline_filter.h",
- "src/core/ext/filters/http/client/http_client_filter.cc",
- "src/core/ext/filters/http/client/http_client_filter.h",
- "src/core/ext/filters/http/client_authority_filter.cc",
- "src/core/ext/filters/http/client_authority_filter.h",
- "src/core/ext/filters/http/http_filters_plugin.cc",
- "src/core/ext/filters/http/message_compress/message_compress_filter.cc",
- "src/core/ext/filters/http/message_compress/message_compress_filter.h",
+ "src/core/ext/filters/client_channel/subchannel.cc",
+ "src/core/ext/filters/client_channel/subchannel.h",
+ "src/core/ext/filters/client_channel/subchannel_interface.h",
+ "src/core/ext/filters/client_channel/subchannel_pool_interface.cc",
+ "src/core/ext/filters/client_channel/subchannel_pool_interface.h",
+ "src/core/ext/filters/client_idle/client_idle_filter.cc",
+ "src/core/ext/filters/deadline/deadline_filter.cc",
+ "src/core/ext/filters/deadline/deadline_filter.h",
+ "src/core/ext/filters/http/client/http_client_filter.cc",
+ "src/core/ext/filters/http/client/http_client_filter.h",
+ "src/core/ext/filters/http/client_authority_filter.cc",
+ "src/core/ext/filters/http/client_authority_filter.h",
+ "src/core/ext/filters/http/http_filters_plugin.cc",
+ "src/core/ext/filters/http/message_compress/message_compress_filter.cc",
+ "src/core/ext/filters/http/message_compress/message_compress_filter.h",
"src/core/ext/filters/http/message_compress/message_decompress_filter.cc",
"src/core/ext/filters/http/message_compress/message_decompress_filter.h",
- "src/core/ext/filters/http/server/http_server_filter.cc",
- "src/core/ext/filters/http/server/http_server_filter.h",
- "src/core/ext/filters/max_age/max_age_filter.cc",
- "src/core/ext/filters/max_age/max_age_filter.h",
- "src/core/ext/filters/message_size/message_size_filter.cc",
- "src/core/ext/filters/message_size/message_size_filter.h",
- "src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc",
- "src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h",
- "src/core/ext/filters/workarounds/workaround_utils.cc",
- "src/core/ext/filters/workarounds/workaround_utils.h",
- "src/core/ext/transport/chttp2/alpn/alpn.cc",
- "src/core/ext/transport/chttp2/alpn/alpn.h",
- "src/core/ext/transport/chttp2/client/authority.cc",
- "src/core/ext/transport/chttp2/client/authority.h",
- "src/core/ext/transport/chttp2/client/chttp2_connector.cc",
- "src/core/ext/transport/chttp2/client/chttp2_connector.h",
- "src/core/ext/transport/chttp2/client/insecure/channel_create.cc",
- "src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc",
- "src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc",
- "src/core/ext/transport/chttp2/server/chttp2_server.cc",
- "src/core/ext/transport/chttp2/server/chttp2_server.h",
- "src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc",
- "src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc",
- "src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc",
- "src/core/ext/transport/chttp2/transport/bin_decoder.cc",
- "src/core/ext/transport/chttp2/transport/bin_decoder.h",
- "src/core/ext/transport/chttp2/transport/bin_encoder.cc",
- "src/core/ext/transport/chttp2/transport/bin_encoder.h",
- "src/core/ext/transport/chttp2/transport/chttp2_plugin.cc",
- "src/core/ext/transport/chttp2/transport/chttp2_transport.cc",
- "src/core/ext/transport/chttp2/transport/chttp2_transport.h",
- "src/core/ext/transport/chttp2/transport/context_list.cc",
- "src/core/ext/transport/chttp2/transport/context_list.h",
- "src/core/ext/transport/chttp2/transport/flow_control.cc",
- "src/core/ext/transport/chttp2/transport/flow_control.h",
- "src/core/ext/transport/chttp2/transport/frame.h",
- "src/core/ext/transport/chttp2/transport/frame_data.cc",
- "src/core/ext/transport/chttp2/transport/frame_data.h",
- "src/core/ext/transport/chttp2/transport/frame_goaway.cc",
- "src/core/ext/transport/chttp2/transport/frame_goaway.h",
- "src/core/ext/transport/chttp2/transport/frame_ping.cc",
- "src/core/ext/transport/chttp2/transport/frame_ping.h",
- "src/core/ext/transport/chttp2/transport/frame_rst_stream.cc",
- "src/core/ext/transport/chttp2/transport/frame_rst_stream.h",
- "src/core/ext/transport/chttp2/transport/frame_settings.cc",
- "src/core/ext/transport/chttp2/transport/frame_settings.h",
- "src/core/ext/transport/chttp2/transport/frame_window_update.cc",
- "src/core/ext/transport/chttp2/transport/frame_window_update.h",
- "src/core/ext/transport/chttp2/transport/hpack_encoder.cc",
- "src/core/ext/transport/chttp2/transport/hpack_encoder.h",
- "src/core/ext/transport/chttp2/transport/hpack_parser.cc",
- "src/core/ext/transport/chttp2/transport/hpack_parser.h",
- "src/core/ext/transport/chttp2/transport/hpack_table.cc",
- "src/core/ext/transport/chttp2/transport/hpack_table.h",
- "src/core/ext/transport/chttp2/transport/http2_settings.cc",
- "src/core/ext/transport/chttp2/transport/http2_settings.h",
- "src/core/ext/transport/chttp2/transport/huffsyms.cc",
- "src/core/ext/transport/chttp2/transport/huffsyms.h",
- "src/core/ext/transport/chttp2/transport/incoming_metadata.cc",
- "src/core/ext/transport/chttp2/transport/incoming_metadata.h",
- "src/core/ext/transport/chttp2/transport/internal.h",
- "src/core/ext/transport/chttp2/transport/parsing.cc",
- "src/core/ext/transport/chttp2/transport/stream_lists.cc",
- "src/core/ext/transport/chttp2/transport/stream_map.cc",
- "src/core/ext/transport/chttp2/transport/stream_map.h",
- "src/core/ext/transport/chttp2/transport/varint.cc",
- "src/core/ext/transport/chttp2/transport/varint.h",
- "src/core/ext/transport/chttp2/transport/writing.cc",
- "src/core/ext/transport/inproc/inproc_plugin.cc",
- "src/core/ext/transport/inproc/inproc_transport.cc",
- "src/core/ext/transport/inproc/inproc_transport.h",
+ "src/core/ext/filters/http/server/http_server_filter.cc",
+ "src/core/ext/filters/http/server/http_server_filter.h",
+ "src/core/ext/filters/max_age/max_age_filter.cc",
+ "src/core/ext/filters/max_age/max_age_filter.h",
+ "src/core/ext/filters/message_size/message_size_filter.cc",
+ "src/core/ext/filters/message_size/message_size_filter.h",
+ "src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc",
+ "src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h",
+ "src/core/ext/filters/workarounds/workaround_utils.cc",
+ "src/core/ext/filters/workarounds/workaround_utils.h",
+ "src/core/ext/transport/chttp2/alpn/alpn.cc",
+ "src/core/ext/transport/chttp2/alpn/alpn.h",
+ "src/core/ext/transport/chttp2/client/authority.cc",
+ "src/core/ext/transport/chttp2/client/authority.h",
+ "src/core/ext/transport/chttp2/client/chttp2_connector.cc",
+ "src/core/ext/transport/chttp2/client/chttp2_connector.h",
+ "src/core/ext/transport/chttp2/client/insecure/channel_create.cc",
+ "src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc",
+ "src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc",
+ "src/core/ext/transport/chttp2/server/chttp2_server.cc",
+ "src/core/ext/transport/chttp2/server/chttp2_server.h",
+ "src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc",
+ "src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc",
+ "src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc",
+ "src/core/ext/transport/chttp2/transport/bin_decoder.cc",
+ "src/core/ext/transport/chttp2/transport/bin_decoder.h",
+ "src/core/ext/transport/chttp2/transport/bin_encoder.cc",
+ "src/core/ext/transport/chttp2/transport/bin_encoder.h",
+ "src/core/ext/transport/chttp2/transport/chttp2_plugin.cc",
+ "src/core/ext/transport/chttp2/transport/chttp2_transport.cc",
+ "src/core/ext/transport/chttp2/transport/chttp2_transport.h",
+ "src/core/ext/transport/chttp2/transport/context_list.cc",
+ "src/core/ext/transport/chttp2/transport/context_list.h",
+ "src/core/ext/transport/chttp2/transport/flow_control.cc",
+ "src/core/ext/transport/chttp2/transport/flow_control.h",
+ "src/core/ext/transport/chttp2/transport/frame.h",
+ "src/core/ext/transport/chttp2/transport/frame_data.cc",
+ "src/core/ext/transport/chttp2/transport/frame_data.h",
+ "src/core/ext/transport/chttp2/transport/frame_goaway.cc",
+ "src/core/ext/transport/chttp2/transport/frame_goaway.h",
+ "src/core/ext/transport/chttp2/transport/frame_ping.cc",
+ "src/core/ext/transport/chttp2/transport/frame_ping.h",
+ "src/core/ext/transport/chttp2/transport/frame_rst_stream.cc",
+ "src/core/ext/transport/chttp2/transport/frame_rst_stream.h",
+ "src/core/ext/transport/chttp2/transport/frame_settings.cc",
+ "src/core/ext/transport/chttp2/transport/frame_settings.h",
+ "src/core/ext/transport/chttp2/transport/frame_window_update.cc",
+ "src/core/ext/transport/chttp2/transport/frame_window_update.h",
+ "src/core/ext/transport/chttp2/transport/hpack_encoder.cc",
+ "src/core/ext/transport/chttp2/transport/hpack_encoder.h",
+ "src/core/ext/transport/chttp2/transport/hpack_parser.cc",
+ "src/core/ext/transport/chttp2/transport/hpack_parser.h",
+ "src/core/ext/transport/chttp2/transport/hpack_table.cc",
+ "src/core/ext/transport/chttp2/transport/hpack_table.h",
+ "src/core/ext/transport/chttp2/transport/http2_settings.cc",
+ "src/core/ext/transport/chttp2/transport/http2_settings.h",
+ "src/core/ext/transport/chttp2/transport/huffsyms.cc",
+ "src/core/ext/transport/chttp2/transport/huffsyms.h",
+ "src/core/ext/transport/chttp2/transport/incoming_metadata.cc",
+ "src/core/ext/transport/chttp2/transport/incoming_metadata.h",
+ "src/core/ext/transport/chttp2/transport/internal.h",
+ "src/core/ext/transport/chttp2/transport/parsing.cc",
+ "src/core/ext/transport/chttp2/transport/stream_lists.cc",
+ "src/core/ext/transport/chttp2/transport/stream_map.cc",
+ "src/core/ext/transport/chttp2/transport/stream_map.h",
+ "src/core/ext/transport/chttp2/transport/varint.cc",
+ "src/core/ext/transport/chttp2/transport/varint.h",
+ "src/core/ext/transport/chttp2/transport/writing.cc",
+ "src/core/ext/transport/inproc/inproc_plugin.cc",
+ "src/core/ext/transport/inproc/inproc_transport.cc",
+ "src/core/ext/transport/inproc/inproc_transport.h",
"src/core/ext/upb-generated/envoy/annotations/deprecation.upb.c",
"src/core/ext/upb-generated/envoy/annotations/deprecation.upb.h",
"src/core/ext/upb-generated/envoy/annotations/resource.upb.c",
@@ -501,40 +501,40 @@ config("grpc_config") {
"src/core/ext/upb-generated/envoy/type/v3/range.upb.h",
"src/core/ext/upb-generated/envoy/type/v3/semantic_version.upb.c",
"src/core/ext/upb-generated/envoy/type/v3/semantic_version.upb.h",
- "src/core/ext/upb-generated/google/api/annotations.upb.c",
- "src/core/ext/upb-generated/google/api/annotations.upb.h",
+ "src/core/ext/upb-generated/google/api/annotations.upb.c",
+ "src/core/ext/upb-generated/google/api/annotations.upb.h",
"src/core/ext/upb-generated/google/api/expr/v1alpha1/checked.upb.c",
"src/core/ext/upb-generated/google/api/expr/v1alpha1/checked.upb.h",
"src/core/ext/upb-generated/google/api/expr/v1alpha1/syntax.upb.c",
"src/core/ext/upb-generated/google/api/expr/v1alpha1/syntax.upb.h",
- "src/core/ext/upb-generated/google/api/http.upb.c",
- "src/core/ext/upb-generated/google/api/http.upb.h",
- "src/core/ext/upb-generated/google/protobuf/any.upb.c",
- "src/core/ext/upb-generated/google/protobuf/any.upb.h",
- "src/core/ext/upb-generated/google/protobuf/descriptor.upb.c",
- "src/core/ext/upb-generated/google/protobuf/descriptor.upb.h",
- "src/core/ext/upb-generated/google/protobuf/duration.upb.c",
- "src/core/ext/upb-generated/google/protobuf/duration.upb.h",
- "src/core/ext/upb-generated/google/protobuf/empty.upb.c",
- "src/core/ext/upb-generated/google/protobuf/empty.upb.h",
- "src/core/ext/upb-generated/google/protobuf/struct.upb.c",
- "src/core/ext/upb-generated/google/protobuf/struct.upb.h",
- "src/core/ext/upb-generated/google/protobuf/timestamp.upb.c",
- "src/core/ext/upb-generated/google/protobuf/timestamp.upb.h",
- "src/core/ext/upb-generated/google/protobuf/wrappers.upb.c",
- "src/core/ext/upb-generated/google/protobuf/wrappers.upb.h",
- "src/core/ext/upb-generated/google/rpc/status.upb.c",
- "src/core/ext/upb-generated/google/rpc/status.upb.h",
- "src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c",
- "src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h",
- "src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c",
- "src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h",
- "src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c",
- "src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h",
- "src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c",
- "src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h",
- "src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c",
- "src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h",
+ "src/core/ext/upb-generated/google/api/http.upb.c",
+ "src/core/ext/upb-generated/google/api/http.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/any.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/any.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/descriptor.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/descriptor.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/duration.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/duration.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/empty.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/empty.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/struct.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/struct.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/timestamp.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/timestamp.upb.h",
+ "src/core/ext/upb-generated/google/protobuf/wrappers.upb.c",
+ "src/core/ext/upb-generated/google/protobuf/wrappers.upb.h",
+ "src/core/ext/upb-generated/google/rpc/status.upb.c",
+ "src/core/ext/upb-generated/google/rpc/status.upb.h",
+ "src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c",
+ "src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h",
+ "src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c",
+ "src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h",
+ "src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c",
+ "src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h",
+ "src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c",
+ "src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h",
+ "src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c",
+ "src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h",
"src/core/ext/upb-generated/udpa/annotations/migrate.upb.c",
"src/core/ext/upb-generated/udpa/annotations/migrate.upb.h",
"src/core/ext/upb-generated/udpa/annotations/security.upb.c",
@@ -557,10 +557,10 @@ config("grpc_config") {
"src/core/ext/upb-generated/udpa/core/v1/resource_locator.upb.h",
"src/core/ext/upb-generated/udpa/core/v1/resource_name.upb.c",
"src/core/ext/upb-generated/udpa/core/v1/resource_name.upb.h",
- "src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c",
- "src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h",
- "src/core/ext/upb-generated/validate/validate.upb.c",
- "src/core/ext/upb-generated/validate/validate.upb.h",
+ "src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c",
+ "src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h",
+ "src/core/ext/upb-generated/validate/validate.upb.c",
+ "src/core/ext/upb-generated/validate/validate.upb.h",
"src/core/ext/xds/certificate_provider_factory.h",
"src/core/ext/xds/certificate_provider_registry.cc",
"src/core/ext/xds/certificate_provider_registry.h",
@@ -576,244 +576,244 @@ config("grpc_config") {
"src/core/ext/xds/xds_client.h",
"src/core/ext/xds/xds_client_stats.cc",
"src/core/ext/xds/xds_client_stats.h",
- "src/core/lib/avl/avl.cc",
- "src/core/lib/avl/avl.h",
- "src/core/lib/backoff/backoff.cc",
- "src/core/lib/backoff/backoff.h",
- "src/core/lib/channel/channel_args.cc",
- "src/core/lib/channel/channel_args.h",
- "src/core/lib/channel/channel_stack.cc",
- "src/core/lib/channel/channel_stack.h",
- "src/core/lib/channel/channel_stack_builder.cc",
- "src/core/lib/channel/channel_stack_builder.h",
- "src/core/lib/channel/channel_trace.cc",
- "src/core/lib/channel/channel_trace.h",
- "src/core/lib/channel/channelz.cc",
- "src/core/lib/channel/channelz.h",
- "src/core/lib/channel/channelz_registry.cc",
- "src/core/lib/channel/channelz_registry.h",
- "src/core/lib/channel/connected_channel.cc",
- "src/core/lib/channel/connected_channel.h",
- "src/core/lib/channel/context.h",
- "src/core/lib/channel/handshaker.cc",
- "src/core/lib/channel/handshaker.h",
- "src/core/lib/channel/handshaker_factory.h",
- "src/core/lib/channel/handshaker_registry.cc",
- "src/core/lib/channel/handshaker_registry.h",
- "src/core/lib/channel/status_util.cc",
- "src/core/lib/channel/status_util.h",
- "src/core/lib/compression/algorithm_metadata.h",
- "src/core/lib/compression/compression.cc",
- "src/core/lib/compression/compression_args.cc",
- "src/core/lib/compression/compression_args.h",
- "src/core/lib/compression/compression_internal.cc",
- "src/core/lib/compression/compression_internal.h",
- "src/core/lib/compression/message_compress.cc",
- "src/core/lib/compression/message_compress.h",
- "src/core/lib/compression/stream_compression.cc",
- "src/core/lib/compression/stream_compression.h",
- "src/core/lib/compression/stream_compression_gzip.cc",
- "src/core/lib/compression/stream_compression_gzip.h",
- "src/core/lib/compression/stream_compression_identity.cc",
- "src/core/lib/compression/stream_compression_identity.h",
- "src/core/lib/debug/stats.cc",
- "src/core/lib/debug/stats.h",
- "src/core/lib/debug/stats_data.cc",
- "src/core/lib/debug/stats_data.h",
- "src/core/lib/debug/trace.cc",
- "src/core/lib/debug/trace.h",
+ "src/core/lib/avl/avl.cc",
+ "src/core/lib/avl/avl.h",
+ "src/core/lib/backoff/backoff.cc",
+ "src/core/lib/backoff/backoff.h",
+ "src/core/lib/channel/channel_args.cc",
+ "src/core/lib/channel/channel_args.h",
+ "src/core/lib/channel/channel_stack.cc",
+ "src/core/lib/channel/channel_stack.h",
+ "src/core/lib/channel/channel_stack_builder.cc",
+ "src/core/lib/channel/channel_stack_builder.h",
+ "src/core/lib/channel/channel_trace.cc",
+ "src/core/lib/channel/channel_trace.h",
+ "src/core/lib/channel/channelz.cc",
+ "src/core/lib/channel/channelz.h",
+ "src/core/lib/channel/channelz_registry.cc",
+ "src/core/lib/channel/channelz_registry.h",
+ "src/core/lib/channel/connected_channel.cc",
+ "src/core/lib/channel/connected_channel.h",
+ "src/core/lib/channel/context.h",
+ "src/core/lib/channel/handshaker.cc",
+ "src/core/lib/channel/handshaker.h",
+ "src/core/lib/channel/handshaker_factory.h",
+ "src/core/lib/channel/handshaker_registry.cc",
+ "src/core/lib/channel/handshaker_registry.h",
+ "src/core/lib/channel/status_util.cc",
+ "src/core/lib/channel/status_util.h",
+ "src/core/lib/compression/algorithm_metadata.h",
+ "src/core/lib/compression/compression.cc",
+ "src/core/lib/compression/compression_args.cc",
+ "src/core/lib/compression/compression_args.h",
+ "src/core/lib/compression/compression_internal.cc",
+ "src/core/lib/compression/compression_internal.h",
+ "src/core/lib/compression/message_compress.cc",
+ "src/core/lib/compression/message_compress.h",
+ "src/core/lib/compression/stream_compression.cc",
+ "src/core/lib/compression/stream_compression.h",
+ "src/core/lib/compression/stream_compression_gzip.cc",
+ "src/core/lib/compression/stream_compression_gzip.h",
+ "src/core/lib/compression/stream_compression_identity.cc",
+ "src/core/lib/compression/stream_compression_identity.h",
+ "src/core/lib/debug/stats.cc",
+ "src/core/lib/debug/stats.h",
+ "src/core/lib/debug/stats_data.cc",
+ "src/core/lib/debug/stats_data.h",
+ "src/core/lib/debug/trace.cc",
+ "src/core/lib/debug/trace.h",
"src/core/lib/gprpp/atomic.h",
- "src/core/lib/gprpp/debug_location.h",
+ "src/core/lib/gprpp/debug_location.h",
"src/core/lib/gprpp/dual_ref_counted.h",
- "src/core/lib/gprpp/orphanable.h",
- "src/core/lib/gprpp/ref_counted.h",
- "src/core/lib/gprpp/ref_counted_ptr.h",
- "src/core/lib/http/format_request.cc",
- "src/core/lib/http/format_request.h",
- "src/core/lib/http/httpcli.cc",
- "src/core/lib/http/httpcli.h",
- "src/core/lib/http/httpcli_security_connector.cc",
- "src/core/lib/http/parser.cc",
- "src/core/lib/http/parser.h",
- "src/core/lib/iomgr/block_annotate.h",
- "src/core/lib/iomgr/buffer_list.cc",
- "src/core/lib/iomgr/buffer_list.h",
- "src/core/lib/iomgr/call_combiner.cc",
- "src/core/lib/iomgr/call_combiner.h",
- "src/core/lib/iomgr/cfstream_handle.cc",
- "src/core/lib/iomgr/cfstream_handle.h",
- "src/core/lib/iomgr/closure.h",
- "src/core/lib/iomgr/combiner.cc",
- "src/core/lib/iomgr/combiner.h",
+ "src/core/lib/gprpp/orphanable.h",
+ "src/core/lib/gprpp/ref_counted.h",
+ "src/core/lib/gprpp/ref_counted_ptr.h",
+ "src/core/lib/http/format_request.cc",
+ "src/core/lib/http/format_request.h",
+ "src/core/lib/http/httpcli.cc",
+ "src/core/lib/http/httpcli.h",
+ "src/core/lib/http/httpcli_security_connector.cc",
+ "src/core/lib/http/parser.cc",
+ "src/core/lib/http/parser.h",
+ "src/core/lib/iomgr/block_annotate.h",
+ "src/core/lib/iomgr/buffer_list.cc",
+ "src/core/lib/iomgr/buffer_list.h",
+ "src/core/lib/iomgr/call_combiner.cc",
+ "src/core/lib/iomgr/call_combiner.h",
+ "src/core/lib/iomgr/cfstream_handle.cc",
+ "src/core/lib/iomgr/cfstream_handle.h",
+ "src/core/lib/iomgr/closure.h",
+ "src/core/lib/iomgr/combiner.cc",
+ "src/core/lib/iomgr/combiner.h",
"src/core/lib/iomgr/dualstack_socket_posix.cc",
- "src/core/lib/iomgr/dynamic_annotations.h",
- "src/core/lib/iomgr/endpoint.cc",
- "src/core/lib/iomgr/endpoint.h",
- "src/core/lib/iomgr/endpoint_cfstream.cc",
- "src/core/lib/iomgr/endpoint_cfstream.h",
- "src/core/lib/iomgr/endpoint_pair.h",
- "src/core/lib/iomgr/endpoint_pair_posix.cc",
- "src/core/lib/iomgr/endpoint_pair_uv.cc",
- "src/core/lib/iomgr/endpoint_pair_windows.cc",
- "src/core/lib/iomgr/error.cc",
- "src/core/lib/iomgr/error.h",
- "src/core/lib/iomgr/error_cfstream.cc",
- "src/core/lib/iomgr/error_cfstream.h",
- "src/core/lib/iomgr/error_internal.h",
+ "src/core/lib/iomgr/dynamic_annotations.h",
+ "src/core/lib/iomgr/endpoint.cc",
+ "src/core/lib/iomgr/endpoint.h",
+ "src/core/lib/iomgr/endpoint_cfstream.cc",
+ "src/core/lib/iomgr/endpoint_cfstream.h",
+ "src/core/lib/iomgr/endpoint_pair.h",
+ "src/core/lib/iomgr/endpoint_pair_posix.cc",
+ "src/core/lib/iomgr/endpoint_pair_uv.cc",
+ "src/core/lib/iomgr/endpoint_pair_windows.cc",
+ "src/core/lib/iomgr/error.cc",
+ "src/core/lib/iomgr/error.h",
+ "src/core/lib/iomgr/error_cfstream.cc",
+ "src/core/lib/iomgr/error_cfstream.h",
+ "src/core/lib/iomgr/error_internal.h",
"src/core/lib/iomgr/ev_apple.cc",
"src/core/lib/iomgr/ev_apple.h",
- "src/core/lib/iomgr/ev_epoll1_linux.cc",
- "src/core/lib/iomgr/ev_epoll1_linux.h",
- "src/core/lib/iomgr/ev_epollex_linux.cc",
- "src/core/lib/iomgr/ev_epollex_linux.h",
- "src/core/lib/iomgr/ev_poll_posix.cc",
- "src/core/lib/iomgr/ev_poll_posix.h",
- "src/core/lib/iomgr/ev_posix.cc",
- "src/core/lib/iomgr/ev_posix.h",
- "src/core/lib/iomgr/ev_windows.cc",
- "src/core/lib/iomgr/exec_ctx.cc",
- "src/core/lib/iomgr/exec_ctx.h",
- "src/core/lib/iomgr/executor.cc",
- "src/core/lib/iomgr/executor.h",
- "src/core/lib/iomgr/executor/mpmcqueue.cc",
- "src/core/lib/iomgr/executor/mpmcqueue.h",
- "src/core/lib/iomgr/executor/threadpool.cc",
- "src/core/lib/iomgr/executor/threadpool.h",
- "src/core/lib/iomgr/fork_posix.cc",
- "src/core/lib/iomgr/fork_windows.cc",
- "src/core/lib/iomgr/gethostname.h",
- "src/core/lib/iomgr/gethostname_fallback.cc",
- "src/core/lib/iomgr/gethostname_host_name_max.cc",
- "src/core/lib/iomgr/gethostname_sysconf.cc",
- "src/core/lib/iomgr/grpc_if_nametoindex.h",
- "src/core/lib/iomgr/grpc_if_nametoindex_posix.cc",
- "src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc",
- "src/core/lib/iomgr/internal_errqueue.cc",
- "src/core/lib/iomgr/internal_errqueue.h",
- "src/core/lib/iomgr/iocp_windows.cc",
- "src/core/lib/iomgr/iocp_windows.h",
- "src/core/lib/iomgr/iomgr.cc",
- "src/core/lib/iomgr/iomgr.h",
- "src/core/lib/iomgr/iomgr_custom.cc",
- "src/core/lib/iomgr/iomgr_custom.h",
- "src/core/lib/iomgr/iomgr_internal.cc",
- "src/core/lib/iomgr/iomgr_internal.h",
- "src/core/lib/iomgr/iomgr_posix.cc",
- "src/core/lib/iomgr/iomgr_posix.h",
- "src/core/lib/iomgr/iomgr_posix_cfstream.cc",
- "src/core/lib/iomgr/iomgr_uv.cc",
- "src/core/lib/iomgr/iomgr_windows.cc",
- "src/core/lib/iomgr/is_epollexclusive_available.cc",
- "src/core/lib/iomgr/is_epollexclusive_available.h",
- "src/core/lib/iomgr/load_file.cc",
- "src/core/lib/iomgr/load_file.h",
- "src/core/lib/iomgr/lockfree_event.cc",
- "src/core/lib/iomgr/lockfree_event.h",
- "src/core/lib/iomgr/nameser.h",
+ "src/core/lib/iomgr/ev_epoll1_linux.cc",
+ "src/core/lib/iomgr/ev_epoll1_linux.h",
+ "src/core/lib/iomgr/ev_epollex_linux.cc",
+ "src/core/lib/iomgr/ev_epollex_linux.h",
+ "src/core/lib/iomgr/ev_poll_posix.cc",
+ "src/core/lib/iomgr/ev_poll_posix.h",
+ "src/core/lib/iomgr/ev_posix.cc",
+ "src/core/lib/iomgr/ev_posix.h",
+ "src/core/lib/iomgr/ev_windows.cc",
+ "src/core/lib/iomgr/exec_ctx.cc",
+ "src/core/lib/iomgr/exec_ctx.h",
+ "src/core/lib/iomgr/executor.cc",
+ "src/core/lib/iomgr/executor.h",
+ "src/core/lib/iomgr/executor/mpmcqueue.cc",
+ "src/core/lib/iomgr/executor/mpmcqueue.h",
+ "src/core/lib/iomgr/executor/threadpool.cc",
+ "src/core/lib/iomgr/executor/threadpool.h",
+ "src/core/lib/iomgr/fork_posix.cc",
+ "src/core/lib/iomgr/fork_windows.cc",
+ "src/core/lib/iomgr/gethostname.h",
+ "src/core/lib/iomgr/gethostname_fallback.cc",
+ "src/core/lib/iomgr/gethostname_host_name_max.cc",
+ "src/core/lib/iomgr/gethostname_sysconf.cc",
+ "src/core/lib/iomgr/grpc_if_nametoindex.h",
+ "src/core/lib/iomgr/grpc_if_nametoindex_posix.cc",
+ "src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc",
+ "src/core/lib/iomgr/internal_errqueue.cc",
+ "src/core/lib/iomgr/internal_errqueue.h",
+ "src/core/lib/iomgr/iocp_windows.cc",
+ "src/core/lib/iomgr/iocp_windows.h",
+ "src/core/lib/iomgr/iomgr.cc",
+ "src/core/lib/iomgr/iomgr.h",
+ "src/core/lib/iomgr/iomgr_custom.cc",
+ "src/core/lib/iomgr/iomgr_custom.h",
+ "src/core/lib/iomgr/iomgr_internal.cc",
+ "src/core/lib/iomgr/iomgr_internal.h",
+ "src/core/lib/iomgr/iomgr_posix.cc",
+ "src/core/lib/iomgr/iomgr_posix.h",
+ "src/core/lib/iomgr/iomgr_posix_cfstream.cc",
+ "src/core/lib/iomgr/iomgr_uv.cc",
+ "src/core/lib/iomgr/iomgr_windows.cc",
+ "src/core/lib/iomgr/is_epollexclusive_available.cc",
+ "src/core/lib/iomgr/is_epollexclusive_available.h",
+ "src/core/lib/iomgr/load_file.cc",
+ "src/core/lib/iomgr/load_file.h",
+ "src/core/lib/iomgr/lockfree_event.cc",
+ "src/core/lib/iomgr/lockfree_event.h",
+ "src/core/lib/iomgr/nameser.h",
"src/core/lib/iomgr/parse_address.cc",
"src/core/lib/iomgr/parse_address.h",
"src/core/lib/iomgr/poller/eventmanager_libuv.cc",
"src/core/lib/iomgr/poller/eventmanager_libuv.h",
- "src/core/lib/iomgr/polling_entity.cc",
- "src/core/lib/iomgr/polling_entity.h",
- "src/core/lib/iomgr/pollset.cc",
- "src/core/lib/iomgr/pollset.h",
- "src/core/lib/iomgr/pollset_custom.cc",
- "src/core/lib/iomgr/pollset_custom.h",
- "src/core/lib/iomgr/pollset_set.cc",
- "src/core/lib/iomgr/pollset_set.h",
- "src/core/lib/iomgr/pollset_set_custom.cc",
- "src/core/lib/iomgr/pollset_set_custom.h",
- "src/core/lib/iomgr/pollset_set_windows.cc",
- "src/core/lib/iomgr/pollset_set_windows.h",
- "src/core/lib/iomgr/pollset_uv.cc",
+ "src/core/lib/iomgr/polling_entity.cc",
+ "src/core/lib/iomgr/polling_entity.h",
+ "src/core/lib/iomgr/pollset.cc",
+ "src/core/lib/iomgr/pollset.h",
+ "src/core/lib/iomgr/pollset_custom.cc",
+ "src/core/lib/iomgr/pollset_custom.h",
+ "src/core/lib/iomgr/pollset_set.cc",
+ "src/core/lib/iomgr/pollset_set.h",
+ "src/core/lib/iomgr/pollset_set_custom.cc",
+ "src/core/lib/iomgr/pollset_set_custom.h",
+ "src/core/lib/iomgr/pollset_set_windows.cc",
+ "src/core/lib/iomgr/pollset_set_windows.h",
+ "src/core/lib/iomgr/pollset_uv.cc",
"src/core/lib/iomgr/pollset_uv.h",
- "src/core/lib/iomgr/pollset_windows.cc",
- "src/core/lib/iomgr/pollset_windows.h",
- "src/core/lib/iomgr/port.h",
+ "src/core/lib/iomgr/pollset_windows.cc",
+ "src/core/lib/iomgr/pollset_windows.h",
+ "src/core/lib/iomgr/port.h",
"src/core/lib/iomgr/python_util.h",
- "src/core/lib/iomgr/resolve_address.cc",
- "src/core/lib/iomgr/resolve_address.h",
- "src/core/lib/iomgr/resolve_address_custom.cc",
- "src/core/lib/iomgr/resolve_address_custom.h",
- "src/core/lib/iomgr/resolve_address_posix.cc",
- "src/core/lib/iomgr/resolve_address_windows.cc",
- "src/core/lib/iomgr/resource_quota.cc",
- "src/core/lib/iomgr/resource_quota.h",
- "src/core/lib/iomgr/sockaddr.h",
- "src/core/lib/iomgr/sockaddr_custom.h",
- "src/core/lib/iomgr/sockaddr_posix.h",
- "src/core/lib/iomgr/sockaddr_utils.cc",
- "src/core/lib/iomgr/sockaddr_utils.h",
- "src/core/lib/iomgr/sockaddr_windows.h",
- "src/core/lib/iomgr/socket_factory_posix.cc",
- "src/core/lib/iomgr/socket_factory_posix.h",
- "src/core/lib/iomgr/socket_mutator.cc",
- "src/core/lib/iomgr/socket_mutator.h",
- "src/core/lib/iomgr/socket_utils.h",
- "src/core/lib/iomgr/socket_utils_common_posix.cc",
- "src/core/lib/iomgr/socket_utils_linux.cc",
- "src/core/lib/iomgr/socket_utils_posix.cc",
- "src/core/lib/iomgr/socket_utils_posix.h",
- "src/core/lib/iomgr/socket_utils_uv.cc",
- "src/core/lib/iomgr/socket_utils_windows.cc",
- "src/core/lib/iomgr/socket_windows.cc",
- "src/core/lib/iomgr/socket_windows.h",
- "src/core/lib/iomgr/sys_epoll_wrapper.h",
- "src/core/lib/iomgr/tcp_client.cc",
- "src/core/lib/iomgr/tcp_client.h",
- "src/core/lib/iomgr/tcp_client_cfstream.cc",
- "src/core/lib/iomgr/tcp_client_custom.cc",
- "src/core/lib/iomgr/tcp_client_posix.cc",
- "src/core/lib/iomgr/tcp_client_posix.h",
- "src/core/lib/iomgr/tcp_client_windows.cc",
- "src/core/lib/iomgr/tcp_custom.cc",
- "src/core/lib/iomgr/tcp_custom.h",
- "src/core/lib/iomgr/tcp_posix.cc",
- "src/core/lib/iomgr/tcp_posix.h",
- "src/core/lib/iomgr/tcp_server.cc",
- "src/core/lib/iomgr/tcp_server.h",
- "src/core/lib/iomgr/tcp_server_custom.cc",
- "src/core/lib/iomgr/tcp_server_posix.cc",
- "src/core/lib/iomgr/tcp_server_utils_posix.h",
- "src/core/lib/iomgr/tcp_server_utils_posix_common.cc",
- "src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc",
- "src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc",
- "src/core/lib/iomgr/tcp_server_windows.cc",
- "src/core/lib/iomgr/tcp_uv.cc",
- "src/core/lib/iomgr/tcp_windows.cc",
- "src/core/lib/iomgr/tcp_windows.h",
- "src/core/lib/iomgr/time_averaged_stats.cc",
- "src/core/lib/iomgr/time_averaged_stats.h",
- "src/core/lib/iomgr/timer.cc",
- "src/core/lib/iomgr/timer.h",
- "src/core/lib/iomgr/timer_custom.cc",
- "src/core/lib/iomgr/timer_custom.h",
- "src/core/lib/iomgr/timer_generic.cc",
+ "src/core/lib/iomgr/resolve_address.cc",
+ "src/core/lib/iomgr/resolve_address.h",
+ "src/core/lib/iomgr/resolve_address_custom.cc",
+ "src/core/lib/iomgr/resolve_address_custom.h",
+ "src/core/lib/iomgr/resolve_address_posix.cc",
+ "src/core/lib/iomgr/resolve_address_windows.cc",
+ "src/core/lib/iomgr/resource_quota.cc",
+ "src/core/lib/iomgr/resource_quota.h",
+ "src/core/lib/iomgr/sockaddr.h",
+ "src/core/lib/iomgr/sockaddr_custom.h",
+ "src/core/lib/iomgr/sockaddr_posix.h",
+ "src/core/lib/iomgr/sockaddr_utils.cc",
+ "src/core/lib/iomgr/sockaddr_utils.h",
+ "src/core/lib/iomgr/sockaddr_windows.h",
+ "src/core/lib/iomgr/socket_factory_posix.cc",
+ "src/core/lib/iomgr/socket_factory_posix.h",
+ "src/core/lib/iomgr/socket_mutator.cc",
+ "src/core/lib/iomgr/socket_mutator.h",
+ "src/core/lib/iomgr/socket_utils.h",
+ "src/core/lib/iomgr/socket_utils_common_posix.cc",
+ "src/core/lib/iomgr/socket_utils_linux.cc",
+ "src/core/lib/iomgr/socket_utils_posix.cc",
+ "src/core/lib/iomgr/socket_utils_posix.h",
+ "src/core/lib/iomgr/socket_utils_uv.cc",
+ "src/core/lib/iomgr/socket_utils_windows.cc",
+ "src/core/lib/iomgr/socket_windows.cc",
+ "src/core/lib/iomgr/socket_windows.h",
+ "src/core/lib/iomgr/sys_epoll_wrapper.h",
+ "src/core/lib/iomgr/tcp_client.cc",
+ "src/core/lib/iomgr/tcp_client.h",
+ "src/core/lib/iomgr/tcp_client_cfstream.cc",
+ "src/core/lib/iomgr/tcp_client_custom.cc",
+ "src/core/lib/iomgr/tcp_client_posix.cc",
+ "src/core/lib/iomgr/tcp_client_posix.h",
+ "src/core/lib/iomgr/tcp_client_windows.cc",
+ "src/core/lib/iomgr/tcp_custom.cc",
+ "src/core/lib/iomgr/tcp_custom.h",
+ "src/core/lib/iomgr/tcp_posix.cc",
+ "src/core/lib/iomgr/tcp_posix.h",
+ "src/core/lib/iomgr/tcp_server.cc",
+ "src/core/lib/iomgr/tcp_server.h",
+ "src/core/lib/iomgr/tcp_server_custom.cc",
+ "src/core/lib/iomgr/tcp_server_posix.cc",
+ "src/core/lib/iomgr/tcp_server_utils_posix.h",
+ "src/core/lib/iomgr/tcp_server_utils_posix_common.cc",
+ "src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc",
+ "src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc",
+ "src/core/lib/iomgr/tcp_server_windows.cc",
+ "src/core/lib/iomgr/tcp_uv.cc",
+ "src/core/lib/iomgr/tcp_windows.cc",
+ "src/core/lib/iomgr/tcp_windows.h",
+ "src/core/lib/iomgr/time_averaged_stats.cc",
+ "src/core/lib/iomgr/time_averaged_stats.h",
+ "src/core/lib/iomgr/timer.cc",
+ "src/core/lib/iomgr/timer.h",
+ "src/core/lib/iomgr/timer_custom.cc",
+ "src/core/lib/iomgr/timer_custom.h",
+ "src/core/lib/iomgr/timer_generic.cc",
"src/core/lib/iomgr/timer_generic.h",
- "src/core/lib/iomgr/timer_heap.cc",
- "src/core/lib/iomgr/timer_heap.h",
- "src/core/lib/iomgr/timer_manager.cc",
- "src/core/lib/iomgr/timer_manager.h",
- "src/core/lib/iomgr/timer_uv.cc",
- "src/core/lib/iomgr/udp_server.cc",
- "src/core/lib/iomgr/udp_server.h",
- "src/core/lib/iomgr/unix_sockets_posix.cc",
- "src/core/lib/iomgr/unix_sockets_posix.h",
- "src/core/lib/iomgr/unix_sockets_posix_noop.cc",
- "src/core/lib/iomgr/wakeup_fd_eventfd.cc",
- "src/core/lib/iomgr/wakeup_fd_nospecial.cc",
- "src/core/lib/iomgr/wakeup_fd_pipe.cc",
- "src/core/lib/iomgr/wakeup_fd_pipe.h",
- "src/core/lib/iomgr/wakeup_fd_posix.cc",
- "src/core/lib/iomgr/wakeup_fd_posix.h",
+ "src/core/lib/iomgr/timer_heap.cc",
+ "src/core/lib/iomgr/timer_heap.h",
+ "src/core/lib/iomgr/timer_manager.cc",
+ "src/core/lib/iomgr/timer_manager.h",
+ "src/core/lib/iomgr/timer_uv.cc",
+ "src/core/lib/iomgr/udp_server.cc",
+ "src/core/lib/iomgr/udp_server.h",
+ "src/core/lib/iomgr/unix_sockets_posix.cc",
+ "src/core/lib/iomgr/unix_sockets_posix.h",
+ "src/core/lib/iomgr/unix_sockets_posix_noop.cc",
+ "src/core/lib/iomgr/wakeup_fd_eventfd.cc",
+ "src/core/lib/iomgr/wakeup_fd_nospecial.cc",
+ "src/core/lib/iomgr/wakeup_fd_pipe.cc",
+ "src/core/lib/iomgr/wakeup_fd_pipe.h",
+ "src/core/lib/iomgr/wakeup_fd_posix.cc",
+ "src/core/lib/iomgr/wakeup_fd_posix.h",
"src/core/lib/iomgr/work_serializer.cc",
"src/core/lib/iomgr/work_serializer.h",
- "src/core/lib/json/json.h",
- "src/core/lib/json/json_reader.cc",
+ "src/core/lib/json/json.h",
+ "src/core/lib/json/json_reader.cc",
"src/core/lib/json/json_util.cc",
"src/core/lib/json/json_util.h",
- "src/core/lib/json/json_writer.cc",
+ "src/core/lib/json/json_writer.cc",
"src/core/lib/security/authorization/authorization_engine.cc",
"src/core/lib/security/authorization/authorization_engine.h",
"src/core/lib/security/authorization/evaluate_args.cc",
@@ -826,559 +826,559 @@ config("grpc_config") {
"src/core/lib/security/authorization/mock_cel/flat_expr_builder.h",
"src/core/lib/security/authorization/mock_cel/statusor.h",
"src/core/lib/security/certificate_provider.h",
- "src/core/lib/security/context/security_context.cc",
- "src/core/lib/security/context/security_context.h",
- "src/core/lib/security/credentials/alts/alts_credentials.cc",
- "src/core/lib/security/credentials/alts/alts_credentials.h",
- "src/core/lib/security/credentials/alts/check_gcp_environment.cc",
- "src/core/lib/security/credentials/alts/check_gcp_environment.h",
- "src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc",
- "src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc",
- "src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc",
- "src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc",
- "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc",
- "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h",
- "src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc",
- "src/core/lib/security/credentials/composite/composite_credentials.cc",
- "src/core/lib/security/credentials/composite/composite_credentials.h",
- "src/core/lib/security/credentials/credentials.cc",
- "src/core/lib/security/credentials/credentials.h",
- "src/core/lib/security/credentials/credentials_metadata.cc",
- "src/core/lib/security/credentials/fake/fake_credentials.cc",
- "src/core/lib/security/credentials/fake/fake_credentials.h",
- "src/core/lib/security/credentials/google_default/credentials_generic.cc",
- "src/core/lib/security/credentials/google_default/google_default_credentials.cc",
- "src/core/lib/security/credentials/google_default/google_default_credentials.h",
- "src/core/lib/security/credentials/iam/iam_credentials.cc",
- "src/core/lib/security/credentials/iam/iam_credentials.h",
- "src/core/lib/security/credentials/jwt/json_token.cc",
- "src/core/lib/security/credentials/jwt/json_token.h",
- "src/core/lib/security/credentials/jwt/jwt_credentials.cc",
- "src/core/lib/security/credentials/jwt/jwt_credentials.h",
- "src/core/lib/security/credentials/jwt/jwt_verifier.cc",
- "src/core/lib/security/credentials/jwt/jwt_verifier.h",
- "src/core/lib/security/credentials/local/local_credentials.cc",
- "src/core/lib/security/credentials/local/local_credentials.h",
- "src/core/lib/security/credentials/oauth2/oauth2_credentials.cc",
- "src/core/lib/security/credentials/oauth2/oauth2_credentials.h",
- "src/core/lib/security/credentials/plugin/plugin_credentials.cc",
- "src/core/lib/security/credentials/plugin/plugin_credentials.h",
- "src/core/lib/security/credentials/ssl/ssl_credentials.cc",
- "src/core/lib/security/credentials/ssl/ssl_credentials.h",
+ "src/core/lib/security/context/security_context.cc",
+ "src/core/lib/security/context/security_context.h",
+ "src/core/lib/security/credentials/alts/alts_credentials.cc",
+ "src/core/lib/security/credentials/alts/alts_credentials.h",
+ "src/core/lib/security/credentials/alts/check_gcp_environment.cc",
+ "src/core/lib/security/credentials/alts/check_gcp_environment.h",
+ "src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc",
+ "src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc",
+ "src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc",
+ "src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc",
+ "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc",
+ "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h",
+ "src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc",
+ "src/core/lib/security/credentials/composite/composite_credentials.cc",
+ "src/core/lib/security/credentials/composite/composite_credentials.h",
+ "src/core/lib/security/credentials/credentials.cc",
+ "src/core/lib/security/credentials/credentials.h",
+ "src/core/lib/security/credentials/credentials_metadata.cc",
+ "src/core/lib/security/credentials/fake/fake_credentials.cc",
+ "src/core/lib/security/credentials/fake/fake_credentials.h",
+ "src/core/lib/security/credentials/google_default/credentials_generic.cc",
+ "src/core/lib/security/credentials/google_default/google_default_credentials.cc",
+ "src/core/lib/security/credentials/google_default/google_default_credentials.h",
+ "src/core/lib/security/credentials/iam/iam_credentials.cc",
+ "src/core/lib/security/credentials/iam/iam_credentials.h",
+ "src/core/lib/security/credentials/jwt/json_token.cc",
+ "src/core/lib/security/credentials/jwt/json_token.h",
+ "src/core/lib/security/credentials/jwt/jwt_credentials.cc",
+ "src/core/lib/security/credentials/jwt/jwt_credentials.h",
+ "src/core/lib/security/credentials/jwt/jwt_verifier.cc",
+ "src/core/lib/security/credentials/jwt/jwt_verifier.h",
+ "src/core/lib/security/credentials/local/local_credentials.cc",
+ "src/core/lib/security/credentials/local/local_credentials.h",
+ "src/core/lib/security/credentials/oauth2/oauth2_credentials.cc",
+ "src/core/lib/security/credentials/oauth2/oauth2_credentials.h",
+ "src/core/lib/security/credentials/plugin/plugin_credentials.cc",
+ "src/core/lib/security/credentials/plugin/plugin_credentials.h",
+ "src/core/lib/security/credentials/ssl/ssl_credentials.cc",
+ "src/core/lib/security/credentials/ssl/ssl_credentials.h",
"src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc",
"src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.h",
- "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc",
- "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h",
+ "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc",
+ "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h",
"src/core/lib/security/credentials/tls/tls_credentials.cc",
"src/core/lib/security/credentials/tls/tls_credentials.h",
"src/core/lib/security/credentials/xds/xds_credentials.cc",
"src/core/lib/security/credentials/xds/xds_credentials.h",
- "src/core/lib/security/security_connector/alts/alts_security_connector.cc",
- "src/core/lib/security/security_connector/alts/alts_security_connector.h",
- "src/core/lib/security/security_connector/fake/fake_security_connector.cc",
- "src/core/lib/security/security_connector/fake/fake_security_connector.h",
- "src/core/lib/security/security_connector/load_system_roots.h",
- "src/core/lib/security/security_connector/load_system_roots_fallback.cc",
- "src/core/lib/security/security_connector/load_system_roots_linux.cc",
- "src/core/lib/security/security_connector/load_system_roots_linux.h",
- "src/core/lib/security/security_connector/local/local_security_connector.cc",
- "src/core/lib/security/security_connector/local/local_security_connector.h",
- "src/core/lib/security/security_connector/security_connector.cc",
- "src/core/lib/security/security_connector/security_connector.h",
- "src/core/lib/security/security_connector/ssl/ssl_security_connector.cc",
- "src/core/lib/security/security_connector/ssl/ssl_security_connector.h",
- "src/core/lib/security/security_connector/ssl_utils.cc",
- "src/core/lib/security/security_connector/ssl_utils.h",
- "src/core/lib/security/security_connector/ssl_utils_config.cc",
- "src/core/lib/security/security_connector/ssl_utils_config.h",
+ "src/core/lib/security/security_connector/alts/alts_security_connector.cc",
+ "src/core/lib/security/security_connector/alts/alts_security_connector.h",
+ "src/core/lib/security/security_connector/fake/fake_security_connector.cc",
+ "src/core/lib/security/security_connector/fake/fake_security_connector.h",
+ "src/core/lib/security/security_connector/load_system_roots.h",
+ "src/core/lib/security/security_connector/load_system_roots_fallback.cc",
+ "src/core/lib/security/security_connector/load_system_roots_linux.cc",
+ "src/core/lib/security/security_connector/load_system_roots_linux.h",
+ "src/core/lib/security/security_connector/local/local_security_connector.cc",
+ "src/core/lib/security/security_connector/local/local_security_connector.h",
+ "src/core/lib/security/security_connector/security_connector.cc",
+ "src/core/lib/security/security_connector/security_connector.h",
+ "src/core/lib/security/security_connector/ssl/ssl_security_connector.cc",
+ "src/core/lib/security/security_connector/ssl/ssl_security_connector.h",
+ "src/core/lib/security/security_connector/ssl_utils.cc",
+ "src/core/lib/security/security_connector/ssl_utils.h",
+ "src/core/lib/security/security_connector/ssl_utils_config.cc",
+ "src/core/lib/security/security_connector/ssl_utils_config.h",
"src/core/lib/security/security_connector/tls/tls_security_connector.cc",
"src/core/lib/security/security_connector/tls/tls_security_connector.h",
- "src/core/lib/security/transport/auth_filters.h",
- "src/core/lib/security/transport/client_auth_filter.cc",
- "src/core/lib/security/transport/secure_endpoint.cc",
- "src/core/lib/security/transport/secure_endpoint.h",
- "src/core/lib/security/transport/security_handshaker.cc",
- "src/core/lib/security/transport/security_handshaker.h",
- "src/core/lib/security/transport/server_auth_filter.cc",
- "src/core/lib/security/transport/tsi_error.cc",
- "src/core/lib/security/transport/tsi_error.h",
- "src/core/lib/security/util/json_util.cc",
- "src/core/lib/security/util/json_util.h",
- "src/core/lib/slice/b64.cc",
- "src/core/lib/slice/b64.h",
- "src/core/lib/slice/percent_encoding.cc",
- "src/core/lib/slice/percent_encoding.h",
- "src/core/lib/slice/slice.cc",
- "src/core/lib/slice/slice_buffer.cc",
- "src/core/lib/slice/slice_intern.cc",
- "src/core/lib/slice/slice_internal.h",
- "src/core/lib/slice/slice_string_helpers.cc",
- "src/core/lib/slice/slice_string_helpers.h",
- "src/core/lib/slice/slice_utils.h",
- "src/core/lib/surface/api_trace.cc",
- "src/core/lib/surface/api_trace.h",
- "src/core/lib/surface/byte_buffer.cc",
- "src/core/lib/surface/byte_buffer_reader.cc",
- "src/core/lib/surface/call.cc",
- "src/core/lib/surface/call.h",
- "src/core/lib/surface/call_details.cc",
- "src/core/lib/surface/call_log_batch.cc",
- "src/core/lib/surface/call_test_only.h",
- "src/core/lib/surface/channel.cc",
- "src/core/lib/surface/channel.h",
- "src/core/lib/surface/channel_init.cc",
- "src/core/lib/surface/channel_init.h",
- "src/core/lib/surface/channel_ping.cc",
- "src/core/lib/surface/channel_stack_type.cc",
- "src/core/lib/surface/channel_stack_type.h",
- "src/core/lib/surface/completion_queue.cc",
- "src/core/lib/surface/completion_queue.h",
- "src/core/lib/surface/completion_queue_factory.cc",
- "src/core/lib/surface/completion_queue_factory.h",
- "src/core/lib/surface/event_string.cc",
- "src/core/lib/surface/event_string.h",
- "src/core/lib/surface/init.cc",
- "src/core/lib/surface/init.h",
- "src/core/lib/surface/init_secure.cc",
- "src/core/lib/surface/lame_client.cc",
- "src/core/lib/surface/lame_client.h",
- "src/core/lib/surface/metadata_array.cc",
- "src/core/lib/surface/server.cc",
- "src/core/lib/surface/server.h",
- "src/core/lib/surface/validate_metadata.cc",
- "src/core/lib/surface/validate_metadata.h",
- "src/core/lib/surface/version.cc",
+ "src/core/lib/security/transport/auth_filters.h",
+ "src/core/lib/security/transport/client_auth_filter.cc",
+ "src/core/lib/security/transport/secure_endpoint.cc",
+ "src/core/lib/security/transport/secure_endpoint.h",
+ "src/core/lib/security/transport/security_handshaker.cc",
+ "src/core/lib/security/transport/security_handshaker.h",
+ "src/core/lib/security/transport/server_auth_filter.cc",
+ "src/core/lib/security/transport/tsi_error.cc",
+ "src/core/lib/security/transport/tsi_error.h",
+ "src/core/lib/security/util/json_util.cc",
+ "src/core/lib/security/util/json_util.h",
+ "src/core/lib/slice/b64.cc",
+ "src/core/lib/slice/b64.h",
+ "src/core/lib/slice/percent_encoding.cc",
+ "src/core/lib/slice/percent_encoding.h",
+ "src/core/lib/slice/slice.cc",
+ "src/core/lib/slice/slice_buffer.cc",
+ "src/core/lib/slice/slice_intern.cc",
+ "src/core/lib/slice/slice_internal.h",
+ "src/core/lib/slice/slice_string_helpers.cc",
+ "src/core/lib/slice/slice_string_helpers.h",
+ "src/core/lib/slice/slice_utils.h",
+ "src/core/lib/surface/api_trace.cc",
+ "src/core/lib/surface/api_trace.h",
+ "src/core/lib/surface/byte_buffer.cc",
+ "src/core/lib/surface/byte_buffer_reader.cc",
+ "src/core/lib/surface/call.cc",
+ "src/core/lib/surface/call.h",
+ "src/core/lib/surface/call_details.cc",
+ "src/core/lib/surface/call_log_batch.cc",
+ "src/core/lib/surface/call_test_only.h",
+ "src/core/lib/surface/channel.cc",
+ "src/core/lib/surface/channel.h",
+ "src/core/lib/surface/channel_init.cc",
+ "src/core/lib/surface/channel_init.h",
+ "src/core/lib/surface/channel_ping.cc",
+ "src/core/lib/surface/channel_stack_type.cc",
+ "src/core/lib/surface/channel_stack_type.h",
+ "src/core/lib/surface/completion_queue.cc",
+ "src/core/lib/surface/completion_queue.h",
+ "src/core/lib/surface/completion_queue_factory.cc",
+ "src/core/lib/surface/completion_queue_factory.h",
+ "src/core/lib/surface/event_string.cc",
+ "src/core/lib/surface/event_string.h",
+ "src/core/lib/surface/init.cc",
+ "src/core/lib/surface/init.h",
+ "src/core/lib/surface/init_secure.cc",
+ "src/core/lib/surface/lame_client.cc",
+ "src/core/lib/surface/lame_client.h",
+ "src/core/lib/surface/metadata_array.cc",
+ "src/core/lib/surface/server.cc",
+ "src/core/lib/surface/server.h",
+ "src/core/lib/surface/validate_metadata.cc",
+ "src/core/lib/surface/validate_metadata.h",
+ "src/core/lib/surface/version.cc",
"src/core/lib/transport/authority_override.cc",
"src/core/lib/transport/authority_override.h",
- "src/core/lib/transport/bdp_estimator.cc",
- "src/core/lib/transport/bdp_estimator.h",
- "src/core/lib/transport/byte_stream.cc",
- "src/core/lib/transport/byte_stream.h",
- "src/core/lib/transport/connectivity_state.cc",
- "src/core/lib/transport/connectivity_state.h",
- "src/core/lib/transport/error_utils.cc",
- "src/core/lib/transport/error_utils.h",
- "src/core/lib/transport/http2_errors.h",
- "src/core/lib/transport/metadata.cc",
- "src/core/lib/transport/metadata.h",
- "src/core/lib/transport/metadata_batch.cc",
- "src/core/lib/transport/metadata_batch.h",
- "src/core/lib/transport/pid_controller.cc",
- "src/core/lib/transport/pid_controller.h",
- "src/core/lib/transport/static_metadata.cc",
- "src/core/lib/transport/static_metadata.h",
- "src/core/lib/transport/status_conversion.cc",
- "src/core/lib/transport/status_conversion.h",
- "src/core/lib/transport/status_metadata.cc",
- "src/core/lib/transport/status_metadata.h",
- "src/core/lib/transport/timeout_encoding.cc",
- "src/core/lib/transport/timeout_encoding.h",
- "src/core/lib/transport/transport.cc",
- "src/core/lib/transport/transport.h",
- "src/core/lib/transport/transport_impl.h",
- "src/core/lib/transport/transport_op_string.cc",
- "src/core/lib/uri/uri_parser.cc",
- "src/core/lib/uri/uri_parser.h",
- "src/core/plugin_registry/grpc_plugin_registry.cc",
- "src/core/tsi/alts/crypt/aes_gcm.cc",
- "src/core/tsi/alts/crypt/gsec.cc",
- "src/core/tsi/alts/crypt/gsec.h",
- "src/core/tsi/alts/frame_protector/alts_counter.cc",
- "src/core/tsi/alts/frame_protector/alts_counter.h",
- "src/core/tsi/alts/frame_protector/alts_crypter.cc",
- "src/core/tsi/alts/frame_protector/alts_crypter.h",
- "src/core/tsi/alts/frame_protector/alts_frame_protector.cc",
- "src/core/tsi/alts/frame_protector/alts_frame_protector.h",
- "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc",
- "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h",
- "src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc",
- "src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc",
- "src/core/tsi/alts/frame_protector/frame_handler.cc",
- "src/core/tsi/alts/frame_protector/frame_handler.h",
- "src/core/tsi/alts/handshaker/alts_handshaker_client.cc",
- "src/core/tsi/alts/handshaker/alts_handshaker_client.h",
- "src/core/tsi/alts/handshaker/alts_shared_resource.cc",
- "src/core/tsi/alts/handshaker/alts_shared_resource.h",
- "src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc",
- "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h",
- "src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h",
- "src/core/tsi/alts/handshaker/alts_tsi_utils.cc",
- "src/core/tsi/alts/handshaker/alts_tsi_utils.h",
- "src/core/tsi/alts/handshaker/transport_security_common_api.cc",
- "src/core/tsi/alts/handshaker/transport_security_common_api.h",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc",
- "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h",
- "src/core/tsi/fake_transport_security.cc",
- "src/core/tsi/fake_transport_security.h",
- "src/core/tsi/local_transport_security.cc",
- "src/core/tsi/local_transport_security.h",
- "src/core/tsi/ssl/session_cache/ssl_session.h",
- "src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc",
- "src/core/tsi/ssl/session_cache/ssl_session_cache.cc",
- "src/core/tsi/ssl/session_cache/ssl_session_cache.h",
- "src/core/tsi/ssl/session_cache/ssl_session_openssl.cc",
- "src/core/tsi/ssl_transport_security.cc",
- "src/core/tsi/ssl_transport_security.h",
- "src/core/tsi/ssl_types.h",
- "src/core/tsi/transport_security.cc",
- "src/core/tsi/transport_security.h",
- "src/core/tsi/transport_security_grpc.cc",
- "src/core/tsi/transport_security_grpc.h",
- "src/core/tsi/transport_security_interface.h",
- ]
- deps = [
- "//third_party/boringssl",
- "//third_party/zlib",
- ":gpr",
+ "src/core/lib/transport/bdp_estimator.cc",
+ "src/core/lib/transport/bdp_estimator.h",
+ "src/core/lib/transport/byte_stream.cc",
+ "src/core/lib/transport/byte_stream.h",
+ "src/core/lib/transport/connectivity_state.cc",
+ "src/core/lib/transport/connectivity_state.h",
+ "src/core/lib/transport/error_utils.cc",
+ "src/core/lib/transport/error_utils.h",
+ "src/core/lib/transport/http2_errors.h",
+ "src/core/lib/transport/metadata.cc",
+ "src/core/lib/transport/metadata.h",
+ "src/core/lib/transport/metadata_batch.cc",
+ "src/core/lib/transport/metadata_batch.h",
+ "src/core/lib/transport/pid_controller.cc",
+ "src/core/lib/transport/pid_controller.h",
+ "src/core/lib/transport/static_metadata.cc",
+ "src/core/lib/transport/static_metadata.h",
+ "src/core/lib/transport/status_conversion.cc",
+ "src/core/lib/transport/status_conversion.h",
+ "src/core/lib/transport/status_metadata.cc",
+ "src/core/lib/transport/status_metadata.h",
+ "src/core/lib/transport/timeout_encoding.cc",
+ "src/core/lib/transport/timeout_encoding.h",
+ "src/core/lib/transport/transport.cc",
+ "src/core/lib/transport/transport.h",
+ "src/core/lib/transport/transport_impl.h",
+ "src/core/lib/transport/transport_op_string.cc",
+ "src/core/lib/uri/uri_parser.cc",
+ "src/core/lib/uri/uri_parser.h",
+ "src/core/plugin_registry/grpc_plugin_registry.cc",
+ "src/core/tsi/alts/crypt/aes_gcm.cc",
+ "src/core/tsi/alts/crypt/gsec.cc",
+ "src/core/tsi/alts/crypt/gsec.h",
+ "src/core/tsi/alts/frame_protector/alts_counter.cc",
+ "src/core/tsi/alts/frame_protector/alts_counter.h",
+ "src/core/tsi/alts/frame_protector/alts_crypter.cc",
+ "src/core/tsi/alts/frame_protector/alts_crypter.h",
+ "src/core/tsi/alts/frame_protector/alts_frame_protector.cc",
+ "src/core/tsi/alts/frame_protector/alts_frame_protector.h",
+ "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc",
+ "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h",
+ "src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc",
+ "src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc",
+ "src/core/tsi/alts/frame_protector/frame_handler.cc",
+ "src/core/tsi/alts/frame_protector/frame_handler.h",
+ "src/core/tsi/alts/handshaker/alts_handshaker_client.cc",
+ "src/core/tsi/alts/handshaker/alts_handshaker_client.h",
+ "src/core/tsi/alts/handshaker/alts_shared_resource.cc",
+ "src/core/tsi/alts/handshaker/alts_shared_resource.h",
+ "src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc",
+ "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h",
+ "src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h",
+ "src/core/tsi/alts/handshaker/alts_tsi_utils.cc",
+ "src/core/tsi/alts/handshaker/alts_tsi_utils.h",
+ "src/core/tsi/alts/handshaker/transport_security_common_api.cc",
+ "src/core/tsi/alts/handshaker/transport_security_common_api.h",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc",
+ "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h",
+ "src/core/tsi/fake_transport_security.cc",
+ "src/core/tsi/fake_transport_security.h",
+ "src/core/tsi/local_transport_security.cc",
+ "src/core/tsi/local_transport_security.h",
+ "src/core/tsi/ssl/session_cache/ssl_session.h",
+ "src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc",
+ "src/core/tsi/ssl/session_cache/ssl_session_cache.cc",
+ "src/core/tsi/ssl/session_cache/ssl_session_cache.h",
+ "src/core/tsi/ssl/session_cache/ssl_session_openssl.cc",
+ "src/core/tsi/ssl_transport_security.cc",
+ "src/core/tsi/ssl_transport_security.h",
+ "src/core/tsi/ssl_types.h",
+ "src/core/tsi/transport_security.cc",
+ "src/core/tsi/transport_security.h",
+ "src/core/tsi/transport_security_grpc.cc",
+ "src/core/tsi/transport_security_grpc.h",
+ "src/core/tsi/transport_security_interface.h",
+ ]
+ deps = [
+ "//third_party/boringssl",
+ "//third_party/zlib",
+ ":gpr",
":address_sorting",
- ":upb",
+ ":upb",
":y_absl/types:optional",
":y_absl/strings:strings",
":y_absl/status:status",
":y_absl/container:inlined_vector",
":y_absl/container:flat_hash_set",
- "//third_party/cares",
- ":address_sorting",
- ]
-
- public_configs = [
- ":grpc_config",
- ]
- include_dirs = [
- "third_party/cares",
- "third_party/address_sorting/include",
- ]
- }
-
-
-
- source_set("grpc++") {
- sources = [
- "include/grpc++/alarm.h",
- "include/grpc++/channel.h",
- "include/grpc++/client_context.h",
- "include/grpc++/completion_queue.h",
- "include/grpc++/create_channel.h",
- "include/grpc++/create_channel_posix.h",
- "include/grpc++/ext/health_check_service_server_builder_option.h",
- "include/grpc++/generic/async_generic_service.h",
- "include/grpc++/generic/generic_stub.h",
- "include/grpc++/grpc++.h",
- "include/grpc++/health_check_service_interface.h",
- "include/grpc++/impl/call.h",
- "include/grpc++/impl/channel_argument_option.h",
- "include/grpc++/impl/client_unary_call.h",
- "include/grpc++/impl/codegen/async_stream.h",
- "include/grpc++/impl/codegen/async_unary_call.h",
- "include/grpc++/impl/codegen/byte_buffer.h",
- "include/grpc++/impl/codegen/call.h",
- "include/grpc++/impl/codegen/call_hook.h",
- "include/grpc++/impl/codegen/channel_interface.h",
- "include/grpc++/impl/codegen/client_context.h",
- "include/grpc++/impl/codegen/client_unary_call.h",
- "include/grpc++/impl/codegen/completion_queue.h",
- "include/grpc++/impl/codegen/completion_queue_tag.h",
- "include/grpc++/impl/codegen/config.h",
- "include/grpc++/impl/codegen/config_protobuf.h",
- "include/grpc++/impl/codegen/core_codegen.h",
- "include/grpc++/impl/codegen/core_codegen_interface.h",
- "include/grpc++/impl/codegen/create_auth_context.h",
- "include/grpc++/impl/codegen/grpc_library.h",
- "include/grpc++/impl/codegen/metadata_map.h",
- "include/grpc++/impl/codegen/method_handler_impl.h",
- "include/grpc++/impl/codegen/proto_utils.h",
- "include/grpc++/impl/codegen/rpc_method.h",
- "include/grpc++/impl/codegen/rpc_service_method.h",
- "include/grpc++/impl/codegen/security/auth_context.h",
- "include/grpc++/impl/codegen/serialization_traits.h",
- "include/grpc++/impl/codegen/server_context.h",
- "include/grpc++/impl/codegen/server_interface.h",
- "include/grpc++/impl/codegen/service_type.h",
- "include/grpc++/impl/codegen/slice.h",
- "include/grpc++/impl/codegen/status.h",
- "include/grpc++/impl/codegen/status_code_enum.h",
- "include/grpc++/impl/codegen/string_ref.h",
- "include/grpc++/impl/codegen/stub_options.h",
- "include/grpc++/impl/codegen/sync_stream.h",
- "include/grpc++/impl/codegen/time.h",
- "include/grpc++/impl/grpc_library.h",
- "include/grpc++/impl/method_handler_impl.h",
- "include/grpc++/impl/rpc_method.h",
- "include/grpc++/impl/rpc_service_method.h",
- "include/grpc++/impl/serialization_traits.h",
- "include/grpc++/impl/server_builder_option.h",
- "include/grpc++/impl/server_builder_plugin.h",
- "include/grpc++/impl/server_initializer.h",
- "include/grpc++/impl/service_type.h",
- "include/grpc++/resource_quota.h",
- "include/grpc++/security/auth_context.h",
- "include/grpc++/security/auth_metadata_processor.h",
- "include/grpc++/security/credentials.h",
- "include/grpc++/security/server_credentials.h",
- "include/grpc++/server.h",
- "include/grpc++/server_builder.h",
- "include/grpc++/server_context.h",
- "include/grpc++/server_posix.h",
- "include/grpc++/support/async_stream.h",
- "include/grpc++/support/async_unary_call.h",
- "include/grpc++/support/byte_buffer.h",
- "include/grpc++/support/channel_arguments.h",
- "include/grpc++/support/config.h",
- "include/grpc++/support/slice.h",
- "include/grpc++/support/status.h",
- "include/grpc++/support/status_code_enum.h",
- "include/grpc++/support/string_ref.h",
- "include/grpc++/support/stub_options.h",
- "include/grpc++/support/sync_stream.h",
- "include/grpc++/support/time.h",
- "include/grpcpp/alarm.h",
- "include/grpcpp/channel.h",
- "include/grpcpp/client_context.h",
- "include/grpcpp/completion_queue.h",
- "include/grpcpp/create_channel.h",
- "include/grpcpp/create_channel_posix.h",
- "include/grpcpp/ext/health_check_service_server_builder_option.h",
- "include/grpcpp/generic/async_generic_service.h",
- "include/grpcpp/generic/generic_stub.h",
- "include/grpcpp/grpcpp.h",
- "include/grpcpp/health_check_service_interface.h",
- "include/grpcpp/impl/call.h",
- "include/grpcpp/impl/channel_argument_option.h",
- "include/grpcpp/impl/client_unary_call.h",
- "include/grpcpp/impl/codegen/async_generic_service.h",
- "include/grpcpp/impl/codegen/async_stream.h",
- "include/grpcpp/impl/codegen/async_unary_call.h",
- "include/grpcpp/impl/codegen/byte_buffer.h",
- "include/grpcpp/impl/codegen/call.h",
- "include/grpcpp/impl/codegen/call_hook.h",
- "include/grpcpp/impl/codegen/call_op_set.h",
- "include/grpcpp/impl/codegen/call_op_set_interface.h",
- "include/grpcpp/impl/codegen/callback_common.h",
- "include/grpcpp/impl/codegen/channel_interface.h",
- "include/grpcpp/impl/codegen/client_callback.h",
- "include/grpcpp/impl/codegen/client_context.h",
- "include/grpcpp/impl/codegen/client_interceptor.h",
- "include/grpcpp/impl/codegen/client_unary_call.h",
- "include/grpcpp/impl/codegen/completion_queue.h",
- "include/grpcpp/impl/codegen/completion_queue_tag.h",
- "include/grpcpp/impl/codegen/config.h",
- "include/grpcpp/impl/codegen/config_protobuf.h",
- "include/grpcpp/impl/codegen/core_codegen.h",
- "include/grpcpp/impl/codegen/core_codegen_interface.h",
- "include/grpcpp/impl/codegen/create_auth_context.h",
- "include/grpcpp/impl/codegen/delegating_channel.h",
- "include/grpcpp/impl/codegen/grpc_library.h",
- "include/grpcpp/impl/codegen/intercepted_channel.h",
- "include/grpcpp/impl/codegen/interceptor.h",
- "include/grpcpp/impl/codegen/interceptor_common.h",
- "include/grpcpp/impl/codegen/message_allocator.h",
- "include/grpcpp/impl/codegen/metadata_map.h",
- "include/grpcpp/impl/codegen/method_handler.h",
- "include/grpcpp/impl/codegen/proto_buffer_reader.h",
- "include/grpcpp/impl/codegen/proto_buffer_writer.h",
- "include/grpcpp/impl/codegen/proto_utils.h",
- "include/grpcpp/impl/codegen/rpc_method.h",
- "include/grpcpp/impl/codegen/rpc_service_method.h",
- "include/grpcpp/impl/codegen/security/auth_context.h",
- "include/grpcpp/impl/codegen/serialization_traits.h",
- "include/grpcpp/impl/codegen/server_callback.h",
- "include/grpcpp/impl/codegen/server_callback_handlers.h",
- "include/grpcpp/impl/codegen/server_context.h",
- "include/grpcpp/impl/codegen/server_interceptor.h",
- "include/grpcpp/impl/codegen/server_interface.h",
- "include/grpcpp/impl/codegen/service_type.h",
- "include/grpcpp/impl/codegen/slice.h",
- "include/grpcpp/impl/codegen/status.h",
- "include/grpcpp/impl/codegen/status_code_enum.h",
- "include/grpcpp/impl/codegen/string_ref.h",
- "include/grpcpp/impl/codegen/stub_options.h",
- "include/grpcpp/impl/codegen/sync.h",
- "include/grpcpp/impl/codegen/sync_stream.h",
- "include/grpcpp/impl/codegen/time.h",
- "include/grpcpp/impl/grpc_library.h",
- "include/grpcpp/impl/method_handler_impl.h",
- "include/grpcpp/impl/rpc_method.h",
- "include/grpcpp/impl/rpc_service_method.h",
- "include/grpcpp/impl/serialization_traits.h",
- "include/grpcpp/impl/server_builder_option.h",
- "include/grpcpp/impl/server_builder_plugin.h",
- "include/grpcpp/impl/server_initializer.h",
- "include/grpcpp/impl/service_type.h",
- "include/grpcpp/resource_quota.h",
- "include/grpcpp/security/auth_context.h",
- "include/grpcpp/security/auth_metadata_processor.h",
- "include/grpcpp/security/credentials.h",
- "include/grpcpp/security/server_credentials.h",
- "include/grpcpp/security/tls_credentials_options.h",
- "include/grpcpp/server.h",
- "include/grpcpp/server_builder.h",
- "include/grpcpp/server_context.h",
- "include/grpcpp/server_posix.h",
- "include/grpcpp/support/async_stream.h",
- "include/grpcpp/support/async_unary_call.h",
- "include/grpcpp/support/byte_buffer.h",
- "include/grpcpp/support/channel_arguments.h",
- "include/grpcpp/support/client_callback.h",
- "include/grpcpp/support/client_interceptor.h",
- "include/grpcpp/support/config.h",
- "include/grpcpp/support/interceptor.h",
- "include/grpcpp/support/message_allocator.h",
+ "//third_party/cares",
+ ":address_sorting",
+ ]
+
+ public_configs = [
+ ":grpc_config",
+ ]
+ include_dirs = [
+ "third_party/cares",
+ "third_party/address_sorting/include",
+ ]
+ }
+
+
+
+ source_set("grpc++") {
+ sources = [
+ "include/grpc++/alarm.h",
+ "include/grpc++/channel.h",
+ "include/grpc++/client_context.h",
+ "include/grpc++/completion_queue.h",
+ "include/grpc++/create_channel.h",
+ "include/grpc++/create_channel_posix.h",
+ "include/grpc++/ext/health_check_service_server_builder_option.h",
+ "include/grpc++/generic/async_generic_service.h",
+ "include/grpc++/generic/generic_stub.h",
+ "include/grpc++/grpc++.h",
+ "include/grpc++/health_check_service_interface.h",
+ "include/grpc++/impl/call.h",
+ "include/grpc++/impl/channel_argument_option.h",
+ "include/grpc++/impl/client_unary_call.h",
+ "include/grpc++/impl/codegen/async_stream.h",
+ "include/grpc++/impl/codegen/async_unary_call.h",
+ "include/grpc++/impl/codegen/byte_buffer.h",
+ "include/grpc++/impl/codegen/call.h",
+ "include/grpc++/impl/codegen/call_hook.h",
+ "include/grpc++/impl/codegen/channel_interface.h",
+ "include/grpc++/impl/codegen/client_context.h",
+ "include/grpc++/impl/codegen/client_unary_call.h",
+ "include/grpc++/impl/codegen/completion_queue.h",
+ "include/grpc++/impl/codegen/completion_queue_tag.h",
+ "include/grpc++/impl/codegen/config.h",
+ "include/grpc++/impl/codegen/config_protobuf.h",
+ "include/grpc++/impl/codegen/core_codegen.h",
+ "include/grpc++/impl/codegen/core_codegen_interface.h",
+ "include/grpc++/impl/codegen/create_auth_context.h",
+ "include/grpc++/impl/codegen/grpc_library.h",
+ "include/grpc++/impl/codegen/metadata_map.h",
+ "include/grpc++/impl/codegen/method_handler_impl.h",
+ "include/grpc++/impl/codegen/proto_utils.h",
+ "include/grpc++/impl/codegen/rpc_method.h",
+ "include/grpc++/impl/codegen/rpc_service_method.h",
+ "include/grpc++/impl/codegen/security/auth_context.h",
+ "include/grpc++/impl/codegen/serialization_traits.h",
+ "include/grpc++/impl/codegen/server_context.h",
+ "include/grpc++/impl/codegen/server_interface.h",
+ "include/grpc++/impl/codegen/service_type.h",
+ "include/grpc++/impl/codegen/slice.h",
+ "include/grpc++/impl/codegen/status.h",
+ "include/grpc++/impl/codegen/status_code_enum.h",
+ "include/grpc++/impl/codegen/string_ref.h",
+ "include/grpc++/impl/codegen/stub_options.h",
+ "include/grpc++/impl/codegen/sync_stream.h",
+ "include/grpc++/impl/codegen/time.h",
+ "include/grpc++/impl/grpc_library.h",
+ "include/grpc++/impl/method_handler_impl.h",
+ "include/grpc++/impl/rpc_method.h",
+ "include/grpc++/impl/rpc_service_method.h",
+ "include/grpc++/impl/serialization_traits.h",
+ "include/grpc++/impl/server_builder_option.h",
+ "include/grpc++/impl/server_builder_plugin.h",
+ "include/grpc++/impl/server_initializer.h",
+ "include/grpc++/impl/service_type.h",
+ "include/grpc++/resource_quota.h",
+ "include/grpc++/security/auth_context.h",
+ "include/grpc++/security/auth_metadata_processor.h",
+ "include/grpc++/security/credentials.h",
+ "include/grpc++/security/server_credentials.h",
+ "include/grpc++/server.h",
+ "include/grpc++/server_builder.h",
+ "include/grpc++/server_context.h",
+ "include/grpc++/server_posix.h",
+ "include/grpc++/support/async_stream.h",
+ "include/grpc++/support/async_unary_call.h",
+ "include/grpc++/support/byte_buffer.h",
+ "include/grpc++/support/channel_arguments.h",
+ "include/grpc++/support/config.h",
+ "include/grpc++/support/slice.h",
+ "include/grpc++/support/status.h",
+ "include/grpc++/support/status_code_enum.h",
+ "include/grpc++/support/string_ref.h",
+ "include/grpc++/support/stub_options.h",
+ "include/grpc++/support/sync_stream.h",
+ "include/grpc++/support/time.h",
+ "include/grpcpp/alarm.h",
+ "include/grpcpp/channel.h",
+ "include/grpcpp/client_context.h",
+ "include/grpcpp/completion_queue.h",
+ "include/grpcpp/create_channel.h",
+ "include/grpcpp/create_channel_posix.h",
+ "include/grpcpp/ext/health_check_service_server_builder_option.h",
+ "include/grpcpp/generic/async_generic_service.h",
+ "include/grpcpp/generic/generic_stub.h",
+ "include/grpcpp/grpcpp.h",
+ "include/grpcpp/health_check_service_interface.h",
+ "include/grpcpp/impl/call.h",
+ "include/grpcpp/impl/channel_argument_option.h",
+ "include/grpcpp/impl/client_unary_call.h",
+ "include/grpcpp/impl/codegen/async_generic_service.h",
+ "include/grpcpp/impl/codegen/async_stream.h",
+ "include/grpcpp/impl/codegen/async_unary_call.h",
+ "include/grpcpp/impl/codegen/byte_buffer.h",
+ "include/grpcpp/impl/codegen/call.h",
+ "include/grpcpp/impl/codegen/call_hook.h",
+ "include/grpcpp/impl/codegen/call_op_set.h",
+ "include/grpcpp/impl/codegen/call_op_set_interface.h",
+ "include/grpcpp/impl/codegen/callback_common.h",
+ "include/grpcpp/impl/codegen/channel_interface.h",
+ "include/grpcpp/impl/codegen/client_callback.h",
+ "include/grpcpp/impl/codegen/client_context.h",
+ "include/grpcpp/impl/codegen/client_interceptor.h",
+ "include/grpcpp/impl/codegen/client_unary_call.h",
+ "include/grpcpp/impl/codegen/completion_queue.h",
+ "include/grpcpp/impl/codegen/completion_queue_tag.h",
+ "include/grpcpp/impl/codegen/config.h",
+ "include/grpcpp/impl/codegen/config_protobuf.h",
+ "include/grpcpp/impl/codegen/core_codegen.h",
+ "include/grpcpp/impl/codegen/core_codegen_interface.h",
+ "include/grpcpp/impl/codegen/create_auth_context.h",
+ "include/grpcpp/impl/codegen/delegating_channel.h",
+ "include/grpcpp/impl/codegen/grpc_library.h",
+ "include/grpcpp/impl/codegen/intercepted_channel.h",
+ "include/grpcpp/impl/codegen/interceptor.h",
+ "include/grpcpp/impl/codegen/interceptor_common.h",
+ "include/grpcpp/impl/codegen/message_allocator.h",
+ "include/grpcpp/impl/codegen/metadata_map.h",
+ "include/grpcpp/impl/codegen/method_handler.h",
+ "include/grpcpp/impl/codegen/proto_buffer_reader.h",
+ "include/grpcpp/impl/codegen/proto_buffer_writer.h",
+ "include/grpcpp/impl/codegen/proto_utils.h",
+ "include/grpcpp/impl/codegen/rpc_method.h",
+ "include/grpcpp/impl/codegen/rpc_service_method.h",
+ "include/grpcpp/impl/codegen/security/auth_context.h",
+ "include/grpcpp/impl/codegen/serialization_traits.h",
+ "include/grpcpp/impl/codegen/server_callback.h",
+ "include/grpcpp/impl/codegen/server_callback_handlers.h",
+ "include/grpcpp/impl/codegen/server_context.h",
+ "include/grpcpp/impl/codegen/server_interceptor.h",
+ "include/grpcpp/impl/codegen/server_interface.h",
+ "include/grpcpp/impl/codegen/service_type.h",
+ "include/grpcpp/impl/codegen/slice.h",
+ "include/grpcpp/impl/codegen/status.h",
+ "include/grpcpp/impl/codegen/status_code_enum.h",
+ "include/grpcpp/impl/codegen/string_ref.h",
+ "include/grpcpp/impl/codegen/stub_options.h",
+ "include/grpcpp/impl/codegen/sync.h",
+ "include/grpcpp/impl/codegen/sync_stream.h",
+ "include/grpcpp/impl/codegen/time.h",
+ "include/grpcpp/impl/grpc_library.h",
+ "include/grpcpp/impl/method_handler_impl.h",
+ "include/grpcpp/impl/rpc_method.h",
+ "include/grpcpp/impl/rpc_service_method.h",
+ "include/grpcpp/impl/serialization_traits.h",
+ "include/grpcpp/impl/server_builder_option.h",
+ "include/grpcpp/impl/server_builder_plugin.h",
+ "include/grpcpp/impl/server_initializer.h",
+ "include/grpcpp/impl/service_type.h",
+ "include/grpcpp/resource_quota.h",
+ "include/grpcpp/security/auth_context.h",
+ "include/grpcpp/security/auth_metadata_processor.h",
+ "include/grpcpp/security/credentials.h",
+ "include/grpcpp/security/server_credentials.h",
+ "include/grpcpp/security/tls_credentials_options.h",
+ "include/grpcpp/server.h",
+ "include/grpcpp/server_builder.h",
+ "include/grpcpp/server_context.h",
+ "include/grpcpp/server_posix.h",
+ "include/grpcpp/support/async_stream.h",
+ "include/grpcpp/support/async_unary_call.h",
+ "include/grpcpp/support/byte_buffer.h",
+ "include/grpcpp/support/channel_arguments.h",
+ "include/grpcpp/support/client_callback.h",
+ "include/grpcpp/support/client_interceptor.h",
+ "include/grpcpp/support/config.h",
+ "include/grpcpp/support/interceptor.h",
+ "include/grpcpp/support/message_allocator.h",
"include/grpcpp/support/method_handler.h",
- "include/grpcpp/support/proto_buffer_reader.h",
- "include/grpcpp/support/proto_buffer_writer.h",
- "include/grpcpp/support/server_callback.h",
- "include/grpcpp/support/server_interceptor.h",
- "include/grpcpp/support/slice.h",
- "include/grpcpp/support/status.h",
- "include/grpcpp/support/status_code_enum.h",
- "include/grpcpp/support/string_ref.h",
- "include/grpcpp/support/stub_options.h",
- "include/grpcpp/support/sync_stream.h",
- "include/grpcpp/support/time.h",
- "include/grpcpp/support/validate_service_config.h",
- "src/cpp/client/channel_cc.cc",
+ "include/grpcpp/support/proto_buffer_reader.h",
+ "include/grpcpp/support/proto_buffer_writer.h",
+ "include/grpcpp/support/server_callback.h",
+ "include/grpcpp/support/server_interceptor.h",
+ "include/grpcpp/support/slice.h",
+ "include/grpcpp/support/status.h",
+ "include/grpcpp/support/status_code_enum.h",
+ "include/grpcpp/support/string_ref.h",
+ "include/grpcpp/support/stub_options.h",
+ "include/grpcpp/support/sync_stream.h",
+ "include/grpcpp/support/time.h",
+ "include/grpcpp/support/validate_service_config.h",
+ "src/cpp/client/channel_cc.cc",
"src/cpp/client/client_callback.cc",
- "src/cpp/client/client_context.cc",
- "src/cpp/client/client_interceptor.cc",
- "src/cpp/client/create_channel.cc",
- "src/cpp/client/create_channel_internal.cc",
- "src/cpp/client/create_channel_internal.h",
- "src/cpp/client/create_channel_posix.cc",
- "src/cpp/client/credentials_cc.cc",
- "src/cpp/client/insecure_credentials.cc",
- "src/cpp/client/secure_credentials.cc",
- "src/cpp/client/secure_credentials.h",
- "src/cpp/codegen/codegen_init.cc",
- "src/cpp/common/alarm.cc",
- "src/cpp/common/auth_property_iterator.cc",
- "src/cpp/common/channel_arguments.cc",
- "src/cpp/common/channel_filter.cc",
- "src/cpp/common/channel_filter.h",
- "src/cpp/common/completion_queue_cc.cc",
- "src/cpp/common/core_codegen.cc",
- "src/cpp/common/resource_quota_cc.cc",
- "src/cpp/common/rpc_method.cc",
- "src/cpp/common/secure_auth_context.cc",
- "src/cpp/common/secure_auth_context.h",
- "src/cpp/common/secure_channel_arguments.cc",
- "src/cpp/common/secure_create_auth_context.cc",
- "src/cpp/common/tls_credentials_options.cc",
- "src/cpp/common/tls_credentials_options_util.cc",
- "src/cpp/common/tls_credentials_options_util.h",
- "src/cpp/common/validate_service_config.cc",
- "src/cpp/common/version_cc.cc",
- "src/cpp/server/async_generic_service.cc",
- "src/cpp/server/channel_argument_option.cc",
- "src/cpp/server/create_default_thread_pool.cc",
- "src/cpp/server/dynamic_thread_pool.cc",
- "src/cpp/server/dynamic_thread_pool.h",
- "src/cpp/server/external_connection_acceptor_impl.cc",
- "src/cpp/server/external_connection_acceptor_impl.h",
- "src/cpp/server/health/default_health_check_service.cc",
- "src/cpp/server/health/default_health_check_service.h",
- "src/cpp/server/health/health_check_service.cc",
- "src/cpp/server/health/health_check_service_server_builder_option.cc",
- "src/cpp/server/insecure_server_credentials.cc",
- "src/cpp/server/secure_server_credentials.cc",
- "src/cpp/server/secure_server_credentials.h",
- "src/cpp/server/server_builder.cc",
- "src/cpp/server/server_callback.cc",
- "src/cpp/server/server_cc.cc",
- "src/cpp/server/server_context.cc",
- "src/cpp/server/server_credentials.cc",
- "src/cpp/server/server_posix.cc",
- "src/cpp/server/thread_pool_interface.h",
- "src/cpp/thread_manager/thread_manager.cc",
- "src/cpp/thread_manager/thread_manager.h",
- "src/cpp/util/byte_buffer_cc.cc",
- "src/cpp/util/status.cc",
- "src/cpp/util/string_ref.cc",
- "src/cpp/util/time_cc.cc",
- ]
- deps = [
- "//third_party/protobuf:protobuf_lite",
- ":grpc",
- ":gpr",
+ "src/cpp/client/client_context.cc",
+ "src/cpp/client/client_interceptor.cc",
+ "src/cpp/client/create_channel.cc",
+ "src/cpp/client/create_channel_internal.cc",
+ "src/cpp/client/create_channel_internal.h",
+ "src/cpp/client/create_channel_posix.cc",
+ "src/cpp/client/credentials_cc.cc",
+ "src/cpp/client/insecure_credentials.cc",
+ "src/cpp/client/secure_credentials.cc",
+ "src/cpp/client/secure_credentials.h",
+ "src/cpp/codegen/codegen_init.cc",
+ "src/cpp/common/alarm.cc",
+ "src/cpp/common/auth_property_iterator.cc",
+ "src/cpp/common/channel_arguments.cc",
+ "src/cpp/common/channel_filter.cc",
+ "src/cpp/common/channel_filter.h",
+ "src/cpp/common/completion_queue_cc.cc",
+ "src/cpp/common/core_codegen.cc",
+ "src/cpp/common/resource_quota_cc.cc",
+ "src/cpp/common/rpc_method.cc",
+ "src/cpp/common/secure_auth_context.cc",
+ "src/cpp/common/secure_auth_context.h",
+ "src/cpp/common/secure_channel_arguments.cc",
+ "src/cpp/common/secure_create_auth_context.cc",
+ "src/cpp/common/tls_credentials_options.cc",
+ "src/cpp/common/tls_credentials_options_util.cc",
+ "src/cpp/common/tls_credentials_options_util.h",
+ "src/cpp/common/validate_service_config.cc",
+ "src/cpp/common/version_cc.cc",
+ "src/cpp/server/async_generic_service.cc",
+ "src/cpp/server/channel_argument_option.cc",
+ "src/cpp/server/create_default_thread_pool.cc",
+ "src/cpp/server/dynamic_thread_pool.cc",
+ "src/cpp/server/dynamic_thread_pool.h",
+ "src/cpp/server/external_connection_acceptor_impl.cc",
+ "src/cpp/server/external_connection_acceptor_impl.h",
+ "src/cpp/server/health/default_health_check_service.cc",
+ "src/cpp/server/health/default_health_check_service.h",
+ "src/cpp/server/health/health_check_service.cc",
+ "src/cpp/server/health/health_check_service_server_builder_option.cc",
+ "src/cpp/server/insecure_server_credentials.cc",
+ "src/cpp/server/secure_server_credentials.cc",
+ "src/cpp/server/secure_server_credentials.h",
+ "src/cpp/server/server_builder.cc",
+ "src/cpp/server/server_callback.cc",
+ "src/cpp/server/server_cc.cc",
+ "src/cpp/server/server_context.cc",
+ "src/cpp/server/server_credentials.cc",
+ "src/cpp/server/server_posix.cc",
+ "src/cpp/server/thread_pool_interface.h",
+ "src/cpp/thread_manager/thread_manager.cc",
+ "src/cpp/thread_manager/thread_manager.h",
+ "src/cpp/util/byte_buffer_cc.cc",
+ "src/cpp/util/status.cc",
+ "src/cpp/util/string_ref.cc",
+ "src/cpp/util/time_cc.cc",
+ ]
+ deps = [
+ "//third_party/protobuf:protobuf_lite",
+ ":grpc",
+ ":gpr",
":address_sorting",
- ":upb",
- ]
-
- public_configs = [
- ":grpc_config",
- ]
- }
-
- # Only compile the plugin for the host architecture.
- if (current_toolchain == host_toolchain) {
-
-
- source_set("grpc_plugin_support") {
- sources = [
- "include/grpc++/impl/codegen/config_protobuf.h",
- "include/grpcpp/impl/codegen/config_protobuf.h",
- "src/compiler/config.h",
- "src/compiler/config_protobuf.h",
- "src/compiler/cpp_generator.cc",
- "src/compiler/cpp_generator.h",
- "src/compiler/cpp_generator_helpers.h",
+ ":upb",
+ ]
+
+ public_configs = [
+ ":grpc_config",
+ ]
+ }
+
+ # Only compile the plugin for the host architecture.
+ if (current_toolchain == host_toolchain) {
+
+
+ source_set("grpc_plugin_support") {
+ sources = [
+ "include/grpc++/impl/codegen/config_protobuf.h",
+ "include/grpcpp/impl/codegen/config_protobuf.h",
+ "src/compiler/config.h",
+ "src/compiler/config_protobuf.h",
+ "src/compiler/cpp_generator.cc",
+ "src/compiler/cpp_generator.h",
+ "src/compiler/cpp_generator_helpers.h",
"src/compiler/cpp_plugin.h",
- "src/compiler/csharp_generator.cc",
- "src/compiler/csharp_generator.h",
- "src/compiler/csharp_generator_helpers.h",
- "src/compiler/generator_helpers.h",
- "src/compiler/node_generator.cc",
- "src/compiler/node_generator.h",
- "src/compiler/node_generator_helpers.h",
- "src/compiler/objective_c_generator.cc",
- "src/compiler/objective_c_generator.h",
- "src/compiler/objective_c_generator_helpers.h",
- "src/compiler/php_generator.cc",
- "src/compiler/php_generator.h",
- "src/compiler/php_generator_helpers.h",
- "src/compiler/protobuf_plugin.h",
- "src/compiler/python_generator.cc",
- "src/compiler/python_generator.h",
- "src/compiler/python_generator_helpers.h",
- "src/compiler/python_private_generator.h",
- "src/compiler/schema_interface.h",
- ]
- deps = [
- "//third_party/protobuf:protoc_lib",
- ]
-
- public_configs = [
- ":grpc_config",
- ]
- }
-
- }
- # Only compile the plugin for the host architecture.
- if (current_toolchain == host_toolchain) {
-
- executable("grpc_cpp_plugin") {
- sources = [
- "src/compiler/cpp_plugin.cc",
- ]
- deps = [
- "//third_party/protobuf:protoc_lib",
- ":grpc_plugin_support",
- ]
-
- configs += [
- "//third_party/protobuf:protobuf_config",
- ]
- public_configs = [ ":grpc_config" ]
- }
-
- }
-
-
+ "src/compiler/csharp_generator.cc",
+ "src/compiler/csharp_generator.h",
+ "src/compiler/csharp_generator_helpers.h",
+ "src/compiler/generator_helpers.h",
+ "src/compiler/node_generator.cc",
+ "src/compiler/node_generator.h",
+ "src/compiler/node_generator_helpers.h",
+ "src/compiler/objective_c_generator.cc",
+ "src/compiler/objective_c_generator.h",
+ "src/compiler/objective_c_generator_helpers.h",
+ "src/compiler/php_generator.cc",
+ "src/compiler/php_generator.h",
+ "src/compiler/php_generator_helpers.h",
+ "src/compiler/protobuf_plugin.h",
+ "src/compiler/python_generator.cc",
+ "src/compiler/python_generator.h",
+ "src/compiler/python_generator_helpers.h",
+ "src/compiler/python_private_generator.h",
+ "src/compiler/schema_interface.h",
+ ]
+ deps = [
+ "//third_party/protobuf:protoc_lib",
+ ]
+
+ public_configs = [
+ ":grpc_config",
+ ]
+ }
+
+ }
+ # Only compile the plugin for the host architecture.
+ if (current_toolchain == host_toolchain) {
+
+ executable("grpc_cpp_plugin") {
+ sources = [
+ "src/compiler/cpp_plugin.cc",
+ ]
+ deps = [
+ "//third_party/protobuf:protoc_lib",
+ ":grpc_plugin_support",
+ ]
+
+ configs += [
+ "//third_party/protobuf:protobuf_config",
+ ]
+ public_configs = [ ":grpc_config" ]
+ }
+
+ }
+
+
diff --git a/contrib/libs/grpc/BUILDING.md b/contrib/libs/grpc/BUILDING.md
index e9f0823c4d..9215983809 100644
--- a/contrib/libs/grpc/BUILDING.md
+++ b/contrib/libs/grpc/BUILDING.md
@@ -1,19 +1,19 @@
-gRPC C++ - Building from source
-===========================
-
+gRPC C++ - Building from source
+===========================
+
This document has detailed instructions on how to build gRPC C++ from source. Note that it only covers the build of gRPC itself and is mostly meant for gRPC C++ contributors and/or power users.
Other should follow the user instructions. See the [How to use](https://github.com/grpc/grpc/tree/master/src/cpp#to-start-using-grpc-c) instructions for guidance on how to add gRPC as a dependency to a C++ application (there are several ways and system wide installation is often not the best choice).
-# Pre-requisites
-
-## Linux
-
-```sh
- $ [sudo] apt-get install build-essential autoconf libtool pkg-config
-```
-
+# Pre-requisites
+
+## Linux
+
+```sh
+ $ [sudo] apt-get install build-essential autoconf libtool pkg-config
+```
+
If you plan to build using CMake
-```sh
+```sh
$ [sudo] apt-get install cmake
```
@@ -22,151 +22,151 @@ If you are a contributor and plan to build and run tests, install the following
$ # libgflags-dev is only required if building with make (deprecated)
$ [sudo] apt-get install libgflags-dev
$ # clang and LLVM C++ lib is only required for sanitizer builds
- $ [sudo] apt-get install clang-5.0 libc++-dev
-```
-
-## MacOS
-
-On a Mac, you will first need to
-install Xcode or
-[Command Line Tools for Xcode](https://developer.apple.com/download/more/)
-and then run the following command from a terminal:
-
-```sh
- $ [sudo] xcode-select --install
-```
-
-To build gRPC from source, you may need to install the following
-packages from [Homebrew](https://brew.sh):
-
-```sh
- $ brew install autoconf automake libtool shtool
-```
-
+ $ [sudo] apt-get install clang-5.0 libc++-dev
+```
+
+## MacOS
+
+On a Mac, you will first need to
+install Xcode or
+[Command Line Tools for Xcode](https://developer.apple.com/download/more/)
+and then run the following command from a terminal:
+
+```sh
+ $ [sudo] xcode-select --install
+```
+
+To build gRPC from source, you may need to install the following
+packages from [Homebrew](https://brew.sh):
+
+```sh
+ $ brew install autoconf automake libtool shtool
+```
+
If you plan to build using CMake, follow the instructions from https://cmake.org/download/
If you are a contributor and plan to build and run tests, install the following as well:
-```sh
+```sh
$ # gflags is only required if building with make (deprecated)
- $ brew install gflags
-```
-
+ $ brew install gflags
+```
+
*Tip*: when building,
-you *may* want to explicitly set the `LIBTOOL` and `LIBTOOLIZE`
-environment variables when running `make` to ensure the version
-installed by `brew` is being used:
-
-```sh
- $ LIBTOOL=glibtool LIBTOOLIZE=glibtoolize make
-```
-
-## Windows
-
-To prepare for cmake + Microsoft Visual C++ compiler build
-- Install Visual Studio 2015 or 2017 (Visual C++ compiler will be used).
-- Install [Git](https://git-scm.com/).
-- Install [CMake](https://cmake.org/download/).
+you *may* want to explicitly set the `LIBTOOL` and `LIBTOOLIZE`
+environment variables when running `make` to ensure the version
+installed by `brew` is being used:
+
+```sh
+ $ LIBTOOL=glibtool LIBTOOLIZE=glibtoolize make
+```
+
+## Windows
+
+To prepare for cmake + Microsoft Visual C++ compiler build
+- Install Visual Studio 2015 or 2017 (Visual C++ compiler will be used).
+- Install [Git](https://git-scm.com/).
+- Install [CMake](https://cmake.org/download/).
- Install [nasm](https://www.nasm.us/) and add it to `PATH` (`choco install nasm`) - *required by boringssl*
-- (Optional) Install [Ninja](https://ninja-build.org/) (`choco install ninja`)
-
-# Clone the repository (including submodules)
-
+- (Optional) Install [Ninja](https://ninja-build.org/) (`choco install ninja`)
+
+# Clone the repository (including submodules)
+
Before building, you need to clone the gRPC github repository and download submodules containing source code
for gRPC's dependencies (that's done by the `submodule` command or `--recursive` flag). Use following commands
to clone the gRPC repository at the [latest stable release tag](https://github.com/grpc/grpc/releases)
-
-## Unix
-
-```sh
+
+## Unix
+
+```sh
$ git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc
- $ cd grpc
- $ git submodule update --init
- ```
-
-## Windows
-
-```
+ $ cd grpc
+ $ git submodule update --init
+ ```
+
+## Windows
+
+```
> git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc
-> cd grpc
+> cd grpc
> git submodule update --init
-```
-
+```
+
NOTE: The `bazel` build tool uses a different model for dependencies. You only need to worry about downloading submodules if you're building
with something else than `bazel` (e.g. `cmake`).
-# Build from source
-
-In the C++ world, there's no "standard" build system that would work for in all supported use cases and on all supported platforms.
+# Build from source
+
+In the C++ world, there's no "standard" build system that would work for in all supported use cases and on all supported platforms.
Therefore, gRPC supports several major build systems, which should satisfy most users. Depending on your needs
we recommend building using `bazel` or `cmake`.
-
+
## Building with bazel (recommended)
-
+
Bazel is the primary build system for gRPC C++ and if you're comfortable with using bazel, we can certainly recommend it.
Using bazel will give you the best developer experience as well as faster and cleaner builds.
-
+
You'll need `bazel` version `1.0.0` or higher to build gRPC.
See [Installing Bazel](https://docs.bazel.build/versions/master/install.html) for instructions how to install bazel on your system.
We support building with `bazel` on Linux, MacOS and Windows.
-From the grpc repository root
-```
+From the grpc repository root
+```
# Build gRPC C++
$ bazel build :all
-```
-
+```
+
```
# Run all the C/C++ tests
$ bazel test --config=dbg //test/...
```
-
+
NOTE: If you are gRPC maintainer and you have access to our test cluster, you should use the our [gRPC's Remote Execution environment](tools/remote_build/README.md)
to get significant improvement to the build and test speed (and a bunch of other very useful features).
-
+
## Building with CMake
### Linux/Unix, Using Make
Run from grpc directory after cloning the repo with --recursive or updating submodules.
-```
+```
$ mkdir -p cmake/build
$ cd cmake/build
$ cmake ../..
$ make
-```
-
+```
+
If you want to build shared libraries (`.so` files), run `cmake` with `-DBUILD_SHARED_LIBS=ON`.
### Windows, Using Visual Studio 2015 or 2017
-When using the "Visual Studio" generator,
+When using the "Visual Studio" generator,
cmake will generate a solution (`grpc.sln`) that contains a VS project for
-every target defined in `CMakeLists.txt` (+ few extra convenience projects
+every target defined in `CMakeLists.txt` (+ few extra convenience projects
added automatically by cmake). After opening the solution with Visual Studio
-you will be able to browse and build the code.
-```
-> @rem Run from grpc directory after cloning the repo with --recursive or updating submodules.
-> md .build
-> cd .build
-> cmake .. -G "Visual Studio 14 2015"
-> cmake --build . --config Release
-```
-
+you will be able to browse and build the code.
+```
+> @rem Run from grpc directory after cloning the repo with --recursive or updating submodules.
+> md .build
+> cd .build
+> cmake .. -G "Visual Studio 14 2015"
+> cmake --build . --config Release
+```
+
If you want to build DLLs, run `cmake` with `-DBUILD_SHARED_LIBS=ON`.
### Windows, Using Ninja (faster build).
-Please note that when using Ninja, you will still need Visual C++ (part of Visual Studio)
-installed to be able to compile the C/C++ sources.
-```
-> @rem Run from grpc directory after cloning the repo with --recursive or updating submodules.
+Please note that when using Ninja, you will still need Visual C++ (part of Visual Studio)
+installed to be able to compile the C/C++ sources.
+```
+> @rem Run from grpc directory after cloning the repo with --recursive or updating submodules.
> cd cmake
> md build
> cd build
-> call "%VS140COMNTOOLS%..\..\VC\vcvarsall.bat" x64
+> call "%VS140COMNTOOLS%..\..\VC\vcvarsall.bat" x64
> cmake ..\.. -GNinja -DCMAKE_BUILD_TYPE=Release
-> cmake --build .
-```
+> cmake --build .
+```
If you want to build DLLs, run `cmake` with `-DBUILD_SHARED_LIBS=ON`.
diff --git a/contrib/libs/grpc/CODE-OF-CONDUCT.md b/contrib/libs/grpc/CODE-OF-CONDUCT.md
index 9d4213ebca..055e2badce 100644
--- a/contrib/libs/grpc/CODE-OF-CONDUCT.md
+++ b/contrib/libs/grpc/CODE-OF-CONDUCT.md
@@ -1,3 +1,3 @@
-## Community Code of Conduct
-
-gRPC follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).
+## Community Code of Conduct
+
+gRPC follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).
diff --git a/contrib/libs/grpc/CONCEPTS.md b/contrib/libs/grpc/CONCEPTS.md
index 034d58e427..dcb0ad1ce5 100644
--- a/contrib/libs/grpc/CONCEPTS.md
+++ b/contrib/libs/grpc/CONCEPTS.md
@@ -1,63 +1,63 @@
-# gRPC Concepts Overview
-
-Remote Procedure Calls (RPCs) provide a useful abstraction for building
-distributed applications and services. The libraries in this repository
-provide a concrete implementation of the gRPC protocol, layered over HTTP/2.
-These libraries enable communication between clients and servers using any
-combination of the supported languages.
-
-
-## Interface
-
-Developers using gRPC start with a language agnostic description of an RPC service (a collection
-of methods). From this description, gRPC will generate client and server side interfaces
-in any of the supported languages. The server implements
-the service interface, which can be remotely invoked by the client interface.
-
-By default, gRPC uses [Protocol Buffers](https://github.com/google/protobuf) as the
-Interface Definition Language (IDL) for describing both the service interface
-and the structure of the payload messages. It is possible to use other
-alternatives if desired.
-
-### Invoking & handling remote calls
-Starting from an interface definition in a .proto file, gRPC provides
-Protocol Compiler plugins that generate Client- and Server-side APIs.
-gRPC users call into these APIs on the Client side and implement
-the corresponding API on the server side.
-
-#### Synchronous vs. asynchronous
-Synchronous RPC calls, that block until a response arrives from the server, are
-the closest approximation to the abstraction of a procedure call that RPC
-aspires to.
-
-On the other hand, networks are inherently asynchronous and in many scenarios,
-it is desirable to have the ability to start RPCs without blocking the current
-thread.
-
-The gRPC programming surface in most languages comes in both synchronous and
-asynchronous flavors.
-
-
-## Streaming
-
-gRPC supports streaming semantics, where either the client or the server (or both)
-send a stream of messages on a single RPC call. The most general case is
-Bidirectional Streaming where a single gRPC call establishes a stream in which both
-the client and the server can send a stream of messages to each other. The streamed
-messages are delivered in the order they were sent.
-
-
-# Protocol
-
-The [gRPC protocol](doc/PROTOCOL-HTTP2.md) specifies the abstract requirements for communication between
-clients and servers. A concrete embedding over HTTP/2 completes the picture by
-fleshing out the details of each of the required operations.
-
-## Abstract gRPC protocol
-A gRPC call comprises of a bidirectional stream of messages, initiated by the client. In the client-to-server direction, this stream begins with a mandatory `Call Header`, followed by optional `Initial-Metadata`, followed by zero or more `Payload Messages`. The server-to-client direction contains an optional `Initial-Metadata`, followed by zero or more `Payload Messages` terminated with a mandatory `Status` and optional `Status-Metadata` (a.k.a.,`Trailing-Metadata`).
-
-## Implementation over HTTP/2
-The abstract protocol defined above is implemented over [HTTP/2](https://http2.github.io/). gRPC bidirectional streams are mapped to HTTP/2 streams. The contents of `Call Header` and `Initial Metadata` are sent as HTTP/2 headers and subject to HPACK compression. `Payload Messages` are serialized into a byte stream of length prefixed gRPC frames which are then fragmented into HTTP/2 frames at the sender and reassembled at the receiver. `Status` and `Trailing-Metadata` are sent as HTTP/2 trailing headers (a.k.a., trailers).
-
-## Flow Control
-gRPC uses the flow control mechanism in HTTP/2. This enables fine-grained control of memory used for buffering in-flight messages.
+# gRPC Concepts Overview
+
+Remote Procedure Calls (RPCs) provide a useful abstraction for building
+distributed applications and services. The libraries in this repository
+provide a concrete implementation of the gRPC protocol, layered over HTTP/2.
+These libraries enable communication between clients and servers using any
+combination of the supported languages.
+
+
+## Interface
+
+Developers using gRPC start with a language agnostic description of an RPC service (a collection
+of methods). From this description, gRPC will generate client and server side interfaces
+in any of the supported languages. The server implements
+the service interface, which can be remotely invoked by the client interface.
+
+By default, gRPC uses [Protocol Buffers](https://github.com/google/protobuf) as the
+Interface Definition Language (IDL) for describing both the service interface
+and the structure of the payload messages. It is possible to use other
+alternatives if desired.
+
+### Invoking & handling remote calls
+Starting from an interface definition in a .proto file, gRPC provides
+Protocol Compiler plugins that generate Client- and Server-side APIs.
+gRPC users call into these APIs on the Client side and implement
+the corresponding API on the server side.
+
+#### Synchronous vs. asynchronous
+Synchronous RPC calls, that block until a response arrives from the server, are
+the closest approximation to the abstraction of a procedure call that RPC
+aspires to.
+
+On the other hand, networks are inherently asynchronous and in many scenarios,
+it is desirable to have the ability to start RPCs without blocking the current
+thread.
+
+The gRPC programming surface in most languages comes in both synchronous and
+asynchronous flavors.
+
+
+## Streaming
+
+gRPC supports streaming semantics, where either the client or the server (or both)
+send a stream of messages on a single RPC call. The most general case is
+Bidirectional Streaming where a single gRPC call establishes a stream in which both
+the client and the server can send a stream of messages to each other. The streamed
+messages are delivered in the order they were sent.
+
+
+# Protocol
+
+The [gRPC protocol](doc/PROTOCOL-HTTP2.md) specifies the abstract requirements for communication between
+clients and servers. A concrete embedding over HTTP/2 completes the picture by
+fleshing out the details of each of the required operations.
+
+## Abstract gRPC protocol
+A gRPC call comprises of a bidirectional stream of messages, initiated by the client. In the client-to-server direction, this stream begins with a mandatory `Call Header`, followed by optional `Initial-Metadata`, followed by zero or more `Payload Messages`. The server-to-client direction contains an optional `Initial-Metadata`, followed by zero or more `Payload Messages` terminated with a mandatory `Status` and optional `Status-Metadata` (a.k.a.,`Trailing-Metadata`).
+
+## Implementation over HTTP/2
+The abstract protocol defined above is implemented over [HTTP/2](https://http2.github.io/). gRPC bidirectional streams are mapped to HTTP/2 streams. The contents of `Call Header` and `Initial Metadata` are sent as HTTP/2 headers and subject to HPACK compression. `Payload Messages` are serialized into a byte stream of length prefixed gRPC frames which are then fragmented into HTTP/2 frames at the sender and reassembled at the receiver. `Status` and `Trailing-Metadata` are sent as HTTP/2 trailing headers (a.k.a., trailers).
+
+## Flow Control
+gRPC uses the flow control mechanism in HTTP/2. This enables fine-grained control of memory used for buffering in-flight messages.
diff --git a/contrib/libs/grpc/CONTRIBUTING.md b/contrib/libs/grpc/CONTRIBUTING.md
index 1d074d8dce..32d2d6b056 100644
--- a/contrib/libs/grpc/CONTRIBUTING.md
+++ b/contrib/libs/grpc/CONTRIBUTING.md
@@ -1,134 +1,134 @@
-# How to contribute
-
-We definitely welcome your patches and contributions to gRPC! Please read the gRPC
-organization's [governance rules](https://github.com/grpc/grpc-community/blob/master/governance.md)
-and [contribution guidelines](https://github.com/grpc/grpc-community/blob/master/CONTRIBUTING.md) before proceeding.
-
-If you are new to github, please start by reading [Pull Request
-howto](https://help.github.com/articles/about-pull-requests/)
-
+# How to contribute
+
+We definitely welcome your patches and contributions to gRPC! Please read the gRPC
+organization's [governance rules](https://github.com/grpc/grpc-community/blob/master/governance.md)
+and [contribution guidelines](https://github.com/grpc/grpc-community/blob/master/CONTRIBUTING.md) before proceeding.
+
+If you are new to github, please start by reading [Pull Request
+howto](https://help.github.com/articles/about-pull-requests/)
+
If you are looking for features to work on, please filter the issues list with the label ["disposition/help wanted"](https://github.com/grpc/grpc/issues?q=label%3A%22disposition%2Fhelp+wanted%22).
Please note that some of these feature requests might have been closed in the past as a result of them being marked as stale due to there being no activity, but these are still valid feature requests.
-## Legal requirements
-
-In order to protect both you and ourselves, you will need to sign the
-[Contributor License
-Agreement](https://identity.linuxfoundation.org/projects/cncf).
-
-## Cloning the repository
-
-Before starting any development work you will need a local copy of the gRPC repository.
-Please follow the instructions in [Building gRPC C++: Clone the repository](BUILDING.md#clone-the-repository-including-submodules).
-
-## Building & Running tests
-
-Different languages use different build systems. To hide the complexity
-of needing to build with many different build systems, a portable python
-script that unifies the experience of building and testing gRPC in different
-languages and on different platforms is provided.
-
-To build gRPC in the language of choice (e.g. `c++`, `csharp`, `php`, `python`, `ruby`, ...)
-- Prepare your development environment based on language-specific instructions in `src/YOUR-LANGUAGE` directory.
-- The language-specific instructions might involve installing C/C++ prerequisites listed in
- [Building gRPC C++: Prerequisites](BUILDING.md#pre-requisites). This is because gRPC implementations
- in this repository are using the native gRPC "core" library internally.
-- Run
- ```
- python tools/run_tests/run_tests.py -l YOUR_LANGUAGE --build_only
- ```
-- To also run all the unit tests after building
- ```
- python tools/run_tests/run_tests.py -l YOUR_LANGUAGE
- ```
-
-You can also run `python tools/run_tests/run_tests.py --help` to discover useful command line flags supported. For more details,
-see [tools/run_tests](tools/run_tests) where you will also find guidance on how to run various other test suites (e.g. interop tests, benchmarks).
-
-## Generated project files
-
-To ease maintenance of language- and platform- specific build systems, many
-projects files are generated using templates and should not be edited by hand.
-Run `tools/buildgen/generate_projects.sh` to regenerate. See
-[templates](templates) for details.
-
-As a rule of thumb, if you see the "sanity tests" failing you've most likely
-edited generated files or you didn't regenerate the projects properly (or your
-code formatting doesn't match our code style).
-
-## Guidelines for Pull Requests
-How to get your contributions merged smoothly and quickly.
+## Legal requirements
-- Create **small PRs** that are narrowly focused on **addressing a single
- concern**. We often times receive PRs that are trying to fix several things
- at a time, but only one fix is considered acceptable, nothing gets merged and
- both author's & review's time is wasted. Create more PRs to address different
- concerns and everyone will be happy.
+In order to protect both you and ourselves, you will need to sign the
+[Contributor License
+Agreement](https://identity.linuxfoundation.org/projects/cncf).
-- For speculative changes, consider opening an issue and discussing it first.
- If you are suggesting a behavioral or API change, consider starting with a
- [gRFC proposal](https://github.com/grpc/proposal).
+## Cloning the repository
-- Provide a good **PR description** as a record of **what** change is being made
- and **why** it was made. Link to a GitHub issue if it exists.
+Before starting any development work you will need a local copy of the gRPC repository.
+Please follow the instructions in [Building gRPC C++: Clone the repository](BUILDING.md#clone-the-repository-including-submodules).
+
+## Building & Running tests
+
+Different languages use different build systems. To hide the complexity
+of needing to build with many different build systems, a portable python
+script that unifies the experience of building and testing gRPC in different
+languages and on different platforms is provided.
+
+To build gRPC in the language of choice (e.g. `c++`, `csharp`, `php`, `python`, `ruby`, ...)
+- Prepare your development environment based on language-specific instructions in `src/YOUR-LANGUAGE` directory.
+- The language-specific instructions might involve installing C/C++ prerequisites listed in
+ [Building gRPC C++: Prerequisites](BUILDING.md#pre-requisites). This is because gRPC implementations
+ in this repository are using the native gRPC "core" library internally.
+- Run
+ ```
+ python tools/run_tests/run_tests.py -l YOUR_LANGUAGE --build_only
+ ```
+- To also run all the unit tests after building
+ ```
+ python tools/run_tests/run_tests.py -l YOUR_LANGUAGE
+ ```
+
+You can also run `python tools/run_tests/run_tests.py --help` to discover useful command line flags supported. For more details,
+see [tools/run_tests](tools/run_tests) where you will also find guidance on how to run various other test suites (e.g. interop tests, benchmarks).
+
+## Generated project files
+
+To ease maintenance of language- and platform- specific build systems, many
+projects files are generated using templates and should not be edited by hand.
+Run `tools/buildgen/generate_projects.sh` to regenerate. See
+[templates](templates) for details.
+
+As a rule of thumb, if you see the "sanity tests" failing you've most likely
+edited generated files or you didn't regenerate the projects properly (or your
+code formatting doesn't match our code style).
+
+## Guidelines for Pull Requests
+How to get your contributions merged smoothly and quickly.
+
+- Create **small PRs** that are narrowly focused on **addressing a single
+ concern**. We often times receive PRs that are trying to fix several things
+ at a time, but only one fix is considered acceptable, nothing gets merged and
+ both author's & review's time is wasted. Create more PRs to address different
+ concerns and everyone will be happy.
+
+- For speculative changes, consider opening an issue and discussing it first.
+ If you are suggesting a behavioral or API change, consider starting with a
+ [gRFC proposal](https://github.com/grpc/proposal).
+
+- Provide a good **PR description** as a record of **what** change is being made
+ and **why** it was made. Link to a GitHub issue if it exists.
+
+- Don't fix code style and formatting unless you are already changing that line
+ to address an issue. PRs with irrelevant changes won't be merged. If you do
+ want to fix formatting or style, do that in a separate PR.
+
+- If you are adding a new file, make sure it has the copyright message template
+ at the top as a comment. You can copy over the message from an existing file
+ and update the year.
+
+- Unless your PR is trivial, you should expect there will be reviewer comments
+ that you'll need to address before merging. We expect you to be reasonably
+ responsive to those comments, otherwise the PR will be closed after 2-3 weeks
+ of inactivity.
+
+- If you have non-trivial contributions, please consider adding an entry to [the
+ AUTHORS file](https://github.com/grpc/grpc/blob/master/AUTHORS) listing the
+ copyright holder for the contribution (yourself, if you are signing the
+ individual CLA, or your company, for corporate CLAs) in the same PR as your
+ contribution. This needs to be done only once, for each company, or
+ individual. Please keep this file in alphabetical order.
+
+- Maintain **clean commit history** and use **meaningful commit messages**.
+ PRs with messy commit history are difficult to review and won't be merged.
+ Use `rebase -i upstream/master` to curate your commit history and/or to
+ bring in latest changes from master (but avoid rebasing in the middle of
+ a code review).
+
+- Keep your PR up to date with upstream/master (if there are merge conflicts,
+ we can't really merge your change).
+
+- If you are regenerating the projects using
+ `tools/buildgen/generate_projects.sh`, make changes to generated files a
+ separate commit with commit message `regenerate projects`. Mixing changes
+ to generated and hand-written files make your PR difficult to review.
+ Note that running this script requires the installation of Python packages
+ `pyyaml` and `mako` (typically installed using `pip`) as well as a recent
+ version of [`go`](https://golang.org/doc/install#install).
+
+- **All tests need to be passing** before your change can be merged.
+ We recommend you **run tests locally** before creating your PR to catch
+ breakages early on (see [tools/run_tests](tools/run_tests). Ultimately, the
+ green signal will be provided by our testing infrastructure. The reviewer
+ will help you if there are test failures that seem not related to the change
+ you are making.
+
+- Exceptions to the rules can be made if there's a compelling reason for doing
+ so.
+
+## Obtaining Commit Access
+We grant Commit Access to contributors based on the following criteria:
+* Sustained contribution to the gRPC project.
+* Deep understanding of the areas contributed to, and good consideration of various reliability, usability and performance tradeoffs.
+* Contributions demonstrate that obtaining Commit Access will significantly reduce friction for the contributors or others.
+
+In addition to submitting PRs, a Contributor with Commit Access can:
+* Review PRs and merge once other checks and criteria pass.
+* Triage bugs and PRs and assign appropriate labels and reviewers.
+
+### Obtaining Commit Access without Code Contributions
+The [gRPC organization](https://github.com/grpc) is comprised of multiple repositories and commit access is usually restricted to one or more of these repositories. Some repositories such as the [grpc.github.io](https://github.com/grpc/grpc.github.io/) do not have code, but the same principle of sustained, high quality contributions, with a good understanding of the fundamentals, apply.
-- Don't fix code style and formatting unless you are already changing that line
- to address an issue. PRs with irrelevant changes won't be merged. If you do
- want to fix formatting or style, do that in a separate PR.
-
-- If you are adding a new file, make sure it has the copyright message template
- at the top as a comment. You can copy over the message from an existing file
- and update the year.
-
-- Unless your PR is trivial, you should expect there will be reviewer comments
- that you'll need to address before merging. We expect you to be reasonably
- responsive to those comments, otherwise the PR will be closed after 2-3 weeks
- of inactivity.
-
-- If you have non-trivial contributions, please consider adding an entry to [the
- AUTHORS file](https://github.com/grpc/grpc/blob/master/AUTHORS) listing the
- copyright holder for the contribution (yourself, if you are signing the
- individual CLA, or your company, for corporate CLAs) in the same PR as your
- contribution. This needs to be done only once, for each company, or
- individual. Please keep this file in alphabetical order.
-
-- Maintain **clean commit history** and use **meaningful commit messages**.
- PRs with messy commit history are difficult to review and won't be merged.
- Use `rebase -i upstream/master` to curate your commit history and/or to
- bring in latest changes from master (but avoid rebasing in the middle of
- a code review).
-
-- Keep your PR up to date with upstream/master (if there are merge conflicts,
- we can't really merge your change).
-
-- If you are regenerating the projects using
- `tools/buildgen/generate_projects.sh`, make changes to generated files a
- separate commit with commit message `regenerate projects`. Mixing changes
- to generated and hand-written files make your PR difficult to review.
- Note that running this script requires the installation of Python packages
- `pyyaml` and `mako` (typically installed using `pip`) as well as a recent
- version of [`go`](https://golang.org/doc/install#install).
-
-- **All tests need to be passing** before your change can be merged.
- We recommend you **run tests locally** before creating your PR to catch
- breakages early on (see [tools/run_tests](tools/run_tests). Ultimately, the
- green signal will be provided by our testing infrastructure. The reviewer
- will help you if there are test failures that seem not related to the change
- you are making.
-
-- Exceptions to the rules can be made if there's a compelling reason for doing
- so.
-
-## Obtaining Commit Access
-We grant Commit Access to contributors based on the following criteria:
-* Sustained contribution to the gRPC project.
-* Deep understanding of the areas contributed to, and good consideration of various reliability, usability and performance tradeoffs.
-* Contributions demonstrate that obtaining Commit Access will significantly reduce friction for the contributors or others.
-
-In addition to submitting PRs, a Contributor with Commit Access can:
-* Review PRs and merge once other checks and criteria pass.
-* Triage bugs and PRs and assign appropriate labels and reviewers.
-
-### Obtaining Commit Access without Code Contributions
-The [gRPC organization](https://github.com/grpc) is comprised of multiple repositories and commit access is usually restricted to one or more of these repositories. Some repositories such as the [grpc.github.io](https://github.com/grpc/grpc.github.io/) do not have code, but the same principle of sustained, high quality contributions, with a good understanding of the fundamentals, apply.
-
diff --git a/contrib/libs/grpc/GOVERNANCE.md b/contrib/libs/grpc/GOVERNANCE.md
index d6ff267471..ee50698224 100644
--- a/contrib/libs/grpc/GOVERNANCE.md
+++ b/contrib/libs/grpc/GOVERNANCE.md
@@ -1 +1 @@
-This repository is governed by the gRPC organization's [governance rules](https://github.com/grpc/grpc-community/blob/master/governance.md).
+This repository is governed by the gRPC organization's [governance rules](https://github.com/grpc/grpc-community/blob/master/governance.md).
diff --git a/contrib/libs/grpc/MAINTAINERS.md b/contrib/libs/grpc/MAINTAINERS.md
index f338c6b193..f8c05a6238 100644
--- a/contrib/libs/grpc/MAINTAINERS.md
+++ b/contrib/libs/grpc/MAINTAINERS.md
@@ -1,84 +1,84 @@
-This page lists all active maintainers of this repository. If you were a
-maintainer and would like to add your name to the Emeritus list, please send us a
-PR.
-
-See [GOVERNANCE.md](https://github.com/grpc/grpc-community/blob/master/governance.md)
-for governance guidelines and how to become a maintainer.
-See [CONTRIBUTING.md](https://github.com/grpc/grpc-community/blob/master/CONTRIBUTING.md)
-for general contribution guidelines.
-
-## Maintainers (in alphabetical order)
-- [a11r](https://github.com/a11r), Google LLC
-- [apolcyn](https://github.com/apolcyn), Google LLC
-- [arjunroy](https://github.com/arjunroy), Google LLC
-- [AspirinSJL](https://github.com/AspirinSJL), Google LLC
-- [bogdandrutu](https://github.com/bogdandrutu), Google LLC
-- [daniel-j-born](https://github.com/daniel-j-born), Google LLC
-- [dapengzhang0](https://github.com/dapengzhang0), Google LLC
-- [dfawley](https://github.com/dfawley), Google LLC
-- [dklempner](https://github.com/dklempner), Google LLC
-- [ejona86](https://github.com/ejona86), Google LLC
-- [ericgribkoff](https://github.com/ericgribkoff), Google LLC
-- [gnossen](https://github.com/gnossen), Google LLC
-- [guantaol](https://github.com/guantaol), Google LLC
-- [hcaseyal](https://github.com/hcaseyal), Google LLC
-- [jboeuf](https://github.com/jboeuf), Google LLC
-- [jiangtaoli2016](https://github.com/jiangtaoli2016), Google LLC
-- [jkolhe](https://github.com/jkolhe), Google LLC
-- [jtattermusch](https://github.com/jtattermusch), Google LLC
-- [karthikravis](https://github.com/karthikravis), Google LLC
-- [kumaralokgithub](https://github.com/kumaralokgithub), Google LLC
-- [lidizheng](https://github.com/lidizheng), Google LLC
-- [markdroth](https://github.com/markdroth), Google LLC
-- [matthewstevenson88](https://github.com/matthewstevenson88), Google LLC
-- [mehrdada](https://github.com/mehrdada), Dropbox, Inc.
-- [mhaidrygoog](https://github.com/mhaidrygoog), Google LLC
-- [murgatroid99](https://github.com/murgatroid99), Google LLC
-- [muxi](https://github.com/muxi), Google LLC
-- [nanahpang](https://github.com/nanahpang), Google LLC
-- [nathanielmanistaatgoogle](https://github.com/nathanielmanistaatgoogle), Google LLC
-- [nicolasnoble](https://github.com/nicolasnoble), Google LLC
-- [pfreixes](https://github.com/pfreixes), Skyscanner Ltd
-- [qixuanl1](https://github.com/qixuanl1), Google LLC
-- [ran-su](https://github.com/ran-su), Google LLC
-- [rmstar](https://github.com/rmstar), Google LLC
-- [sanjaypujare](https://github.com/sanjaypujare), Google LLC
-- [sheenaqotj](https://github.com/sheenaqotj), Google LLC
-- [soheilhy](https://github.com/soheilhy), Google LLC
-- [sreecha](https://github.com/sreecha), LinkedIn
-- [srini100](https://github.com/srini100), Google LLC
-- [stanley-cheung](https://github.com/stanley-cheung), Google LLC
-- [veblush](https://github.com/veblush), Google LLC
-- [vishalpowar](https://github.com/vishalpowar), Google LLC
-- [Vizerai](https://github.com/Vizerai), Google LLC
-- [vjpai](https://github.com/vjpai), Google LLC
-- [wcevans](https://github.com/wcevans), Google LLC
-- [wenbozhu](https://github.com/wenbozhu), Google LLC
-- [yang-g](https://github.com/yang-g), Google LLC
-- [yashykt](https://github.com/yashykt), Google LLC
-- [yihuazhang](https://github.com/yihuazhang), Google LLC
+This page lists all active maintainers of this repository. If you were a
+maintainer and would like to add your name to the Emeritus list, please send us a
+PR.
+
+See [GOVERNANCE.md](https://github.com/grpc/grpc-community/blob/master/governance.md)
+for governance guidelines and how to become a maintainer.
+See [CONTRIBUTING.md](https://github.com/grpc/grpc-community/blob/master/CONTRIBUTING.md)
+for general contribution guidelines.
+
+## Maintainers (in alphabetical order)
+- [a11r](https://github.com/a11r), Google LLC
+- [apolcyn](https://github.com/apolcyn), Google LLC
+- [arjunroy](https://github.com/arjunroy), Google LLC
+- [AspirinSJL](https://github.com/AspirinSJL), Google LLC
+- [bogdandrutu](https://github.com/bogdandrutu), Google LLC
+- [daniel-j-born](https://github.com/daniel-j-born), Google LLC
+- [dapengzhang0](https://github.com/dapengzhang0), Google LLC
+- [dfawley](https://github.com/dfawley), Google LLC
+- [dklempner](https://github.com/dklempner), Google LLC
+- [ejona86](https://github.com/ejona86), Google LLC
+- [ericgribkoff](https://github.com/ericgribkoff), Google LLC
+- [gnossen](https://github.com/gnossen), Google LLC
+- [guantaol](https://github.com/guantaol), Google LLC
+- [hcaseyal](https://github.com/hcaseyal), Google LLC
+- [jboeuf](https://github.com/jboeuf), Google LLC
+- [jiangtaoli2016](https://github.com/jiangtaoli2016), Google LLC
+- [jkolhe](https://github.com/jkolhe), Google LLC
+- [jtattermusch](https://github.com/jtattermusch), Google LLC
+- [karthikravis](https://github.com/karthikravis), Google LLC
+- [kumaralokgithub](https://github.com/kumaralokgithub), Google LLC
+- [lidizheng](https://github.com/lidizheng), Google LLC
+- [markdroth](https://github.com/markdroth), Google LLC
+- [matthewstevenson88](https://github.com/matthewstevenson88), Google LLC
+- [mehrdada](https://github.com/mehrdada), Dropbox, Inc.
+- [mhaidrygoog](https://github.com/mhaidrygoog), Google LLC
+- [murgatroid99](https://github.com/murgatroid99), Google LLC
+- [muxi](https://github.com/muxi), Google LLC
+- [nanahpang](https://github.com/nanahpang), Google LLC
+- [nathanielmanistaatgoogle](https://github.com/nathanielmanistaatgoogle), Google LLC
+- [nicolasnoble](https://github.com/nicolasnoble), Google LLC
+- [pfreixes](https://github.com/pfreixes), Skyscanner Ltd
+- [qixuanl1](https://github.com/qixuanl1), Google LLC
+- [ran-su](https://github.com/ran-su), Google LLC
+- [rmstar](https://github.com/rmstar), Google LLC
+- [sanjaypujare](https://github.com/sanjaypujare), Google LLC
+- [sheenaqotj](https://github.com/sheenaqotj), Google LLC
+- [soheilhy](https://github.com/soheilhy), Google LLC
+- [sreecha](https://github.com/sreecha), LinkedIn
+- [srini100](https://github.com/srini100), Google LLC
+- [stanley-cheung](https://github.com/stanley-cheung), Google LLC
+- [veblush](https://github.com/veblush), Google LLC
+- [vishalpowar](https://github.com/vishalpowar), Google LLC
+- [Vizerai](https://github.com/Vizerai), Google LLC
+- [vjpai](https://github.com/vjpai), Google LLC
+- [wcevans](https://github.com/wcevans), Google LLC
+- [wenbozhu](https://github.com/wenbozhu), Google LLC
+- [yang-g](https://github.com/yang-g), Google LLC
+- [yashykt](https://github.com/yashykt), Google LLC
+- [yihuazhang](https://github.com/yihuazhang), Google LLC
- [ZhenLian](https://github.com/ZhenLian), Google LLC
-- [ZhouyihaiDing](https://github.com/ZhouyihaiDing), Google LLC
-
-
-## Emeritus Maintainers (in alphabetical order)
-- [adelez](https://github.com/adelez), Google LLC
-- [billfeng327](https://github.com/billfeng327), Google LLC
-- [ctiller](https://github.com/ctiller), Google LLC
-- [dgquintas](https://github.com/dgquintas), Google LLC
-- [fengli79](https://github.com/fengli79), Google LLC
-- [jcanizales](https://github.com/jcanizales), Google LLC
-- [jpalmerLinuxFoundation](https://github.com/jpalmerLinuxFoundation), Linux Foundation
-- [justinburke](https://github.com/justinburke), Google LLC
-- [kpayson64](https://github.com/kpayson64), Google LLC
-- [lyuxuan](https://github.com/lyuxuan), Google LLC
-- [matt-kwong](https://github.com/matt-kwong), Google LLC
-- [mit-mit](https://github.com/mit-mit), Google LLC
-- [mpwarres](https://github.com/mpwarres), Google LLC
-- [ncteisen](https://github.com/ncteisen), Google LLC
-- [pmarks-net](https://github.com/pmarks-net), Google LLC
-- [slash-lib](https://github.com/slash-lib), Google LLC
-- [soltanmm](https://github.com/soltanmm), Google LLC
-- [summerxyt](https://github.com/summerxyt), Google LLC
-- [y-zeng](https://github.com/y-zeng), Google LLC
-- [zpencer](https://github.com/zpencer), Google LLC
+- [ZhouyihaiDing](https://github.com/ZhouyihaiDing), Google LLC
+
+
+## Emeritus Maintainers (in alphabetical order)
+- [adelez](https://github.com/adelez), Google LLC
+- [billfeng327](https://github.com/billfeng327), Google LLC
+- [ctiller](https://github.com/ctiller), Google LLC
+- [dgquintas](https://github.com/dgquintas), Google LLC
+- [fengli79](https://github.com/fengli79), Google LLC
+- [jcanizales](https://github.com/jcanizales), Google LLC
+- [jpalmerLinuxFoundation](https://github.com/jpalmerLinuxFoundation), Linux Foundation
+- [justinburke](https://github.com/justinburke), Google LLC
+- [kpayson64](https://github.com/kpayson64), Google LLC
+- [lyuxuan](https://github.com/lyuxuan), Google LLC
+- [matt-kwong](https://github.com/matt-kwong), Google LLC
+- [mit-mit](https://github.com/mit-mit), Google LLC
+- [mpwarres](https://github.com/mpwarres), Google LLC
+- [ncteisen](https://github.com/ncteisen), Google LLC
+- [pmarks-net](https://github.com/pmarks-net), Google LLC
+- [slash-lib](https://github.com/slash-lib), Google LLC
+- [soltanmm](https://github.com/soltanmm), Google LLC
+- [summerxyt](https://github.com/summerxyt), Google LLC
+- [y-zeng](https://github.com/y-zeng), Google LLC
+- [zpencer](https://github.com/zpencer), Google LLC
diff --git a/contrib/libs/grpc/MANIFEST.md b/contrib/libs/grpc/MANIFEST.md
index 9581e1c993..198156f1fc 100644
--- a/contrib/libs/grpc/MANIFEST.md
+++ b/contrib/libs/grpc/MANIFEST.md
@@ -1,23 +1,23 @@
-# Top-level Items by language
-
-## Bazel
-* [grpc.bzl](grpc.bzl)
-
-## Objective-C
-* [gRPC.podspec](gRPC.podspec)
-
-## PHP
-* [composer.json](composer.json)
-* [config.m4](config.m4)
-* [package.xml](package.xml)
-
-## Python
-* [requirements.txt](requirements.txt)
-* [setup.cfg](setup.cfg)
-* [setup.py](setup.py)
-* [PYTHON-MANIFEST.in](PYTHON-MANIFEST.in)
-
-## Ruby
-* [Gemfile](Gemfile)
-* [grpc.gemspec](grpc.gemspec)
-* [Rakefile](Rakefile)
+# Top-level Items by language
+
+## Bazel
+* [grpc.bzl](grpc.bzl)
+
+## Objective-C
+* [gRPC.podspec](gRPC.podspec)
+
+## PHP
+* [composer.json](composer.json)
+* [config.m4](config.m4)
+* [package.xml](package.xml)
+
+## Python
+* [requirements.txt](requirements.txt)
+* [setup.cfg](setup.cfg)
+* [setup.py](setup.py)
+* [PYTHON-MANIFEST.in](PYTHON-MANIFEST.in)
+
+## Ruby
+* [Gemfile](Gemfile)
+* [grpc.gemspec](grpc.gemspec)
+* [Rakefile](Rakefile)
diff --git a/contrib/libs/grpc/NOTICE.txt b/contrib/libs/grpc/NOTICE.txt
index 530197749e..21a5b8b3e9 100644
--- a/contrib/libs/grpc/NOTICE.txt
+++ b/contrib/libs/grpc/NOTICE.txt
@@ -1,13 +1,13 @@
-Copyright 2014 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.
+Copyright 2014 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.
diff --git a/contrib/libs/grpc/README.md b/contrib/libs/grpc/README.md
index a392de0e7e..f628dd5905 100644
--- a/contrib/libs/grpc/README.md
+++ b/contrib/libs/grpc/README.md
@@ -1,87 +1,87 @@
-gRPC - An RPC library and framework
-===================================
-
-gRPC is a modern, open source, high-performance remote procedure call (RPC) framework that can run anywhere. gRPC enables client and server applications to communicate transparently, and simplifies the building of connected systems.
-
-<table>
- <tr>
- <td><b>Homepage:</b></td>
- <td><a href="https://grpc.io/">grpc.io</a></td>
- </tr>
- <tr>
- <td><b>Mailing List:</b></td>
- <td><a href="https://groups.google.com/forum/#!forum/grpc-io">grpc-io@googlegroups.com</a></td>
- </tr>
-</table>
-
-[![Join the chat at https://gitter.im/grpc/grpc](https://badges.gitter.im/grpc/grpc.svg)](https://gitter.im/grpc/grpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-
-# To start using gRPC
-
-To maximize usability, gRPC supports the standard method for adding dependencies to a user's chosen language (if there is one).
-In most languages, the gRPC runtime comes as a package available in a user's language package manager.
-
-For instructions on how to use the language-specific gRPC runtime for a project, please refer to these documents
-
- * [C++](src/cpp): follow the instructions under the `src/cpp` directory
- * [C#](src/csharp): NuGet package `Grpc`
- * [Dart](https://github.com/grpc/grpc-dart): pub package `grpc`
- * [Go](https://github.com/grpc/grpc-go): `go get google.golang.org/grpc`
- * [Java](https://github.com/grpc/grpc-java): Use JARs from Maven Central Repository
+gRPC - An RPC library and framework
+===================================
+
+gRPC is a modern, open source, high-performance remote procedure call (RPC) framework that can run anywhere. gRPC enables client and server applications to communicate transparently, and simplifies the building of connected systems.
+
+<table>
+ <tr>
+ <td><b>Homepage:</b></td>
+ <td><a href="https://grpc.io/">grpc.io</a></td>
+ </tr>
+ <tr>
+ <td><b>Mailing List:</b></td>
+ <td><a href="https://groups.google.com/forum/#!forum/grpc-io">grpc-io@googlegroups.com</a></td>
+ </tr>
+</table>
+
+[![Join the chat at https://gitter.im/grpc/grpc](https://badges.gitter.im/grpc/grpc.svg)](https://gitter.im/grpc/grpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+# To start using gRPC
+
+To maximize usability, gRPC supports the standard method for adding dependencies to a user's chosen language (if there is one).
+In most languages, the gRPC runtime comes as a package available in a user's language package manager.
+
+For instructions on how to use the language-specific gRPC runtime for a project, please refer to these documents
+
+ * [C++](src/cpp): follow the instructions under the `src/cpp` directory
+ * [C#](src/csharp): NuGet package `Grpc`
+ * [Dart](https://github.com/grpc/grpc-dart): pub package `grpc`
+ * [Go](https://github.com/grpc/grpc-go): `go get google.golang.org/grpc`
+ * [Java](https://github.com/grpc/grpc-java): Use JARs from Maven Central Repository
* [Kotlin](https://github.com/grpc/grpc-kotlin): Use JARs from Maven Central Repository
- * [Node](https://github.com/grpc/grpc-node): `npm install grpc`
- * [Objective-C](src/objective-c): Add `gRPC-ProtoRPC` dependency to podspec
- * [PHP](src/php): `pecl install grpc`
- * [Python](src/python/grpcio): `pip install grpcio`
- * [Ruby](src/ruby): `gem install grpc`
- * [WebJS](https://github.com/grpc/grpc-web): follow the grpc-web instructions
-
-Per-language quickstart guides and tutorials can be found in the [documentation section on the grpc.io website](https://grpc.io/docs/). Code examples are available in the [examples](examples) directory.
-
-Precompiled bleeding-edge package builds of gRPC `master` branch's `HEAD` are uploaded daily to [packages.grpc.io](https://packages.grpc.io).
-
-# To start developing gRPC
-
-Contributions are welcome!
-
-Please read [How to contribute](CONTRIBUTING.md) which will guide you through the entire workflow of how to build the source code, how to run the tests, and how to contribute changes to
-the gRPC codebase.
-The "How to contribute" document also contains info on how the contribution process works and contains best practices for creating contributions.
-
-# Troubleshooting
-
-Sometimes things go wrong. Please check out the [Troubleshooting guide](TROUBLESHOOTING.md) if you are experiencing issues with gRPC.
-
-# Performance
-
+ * [Node](https://github.com/grpc/grpc-node): `npm install grpc`
+ * [Objective-C](src/objective-c): Add `gRPC-ProtoRPC` dependency to podspec
+ * [PHP](src/php): `pecl install grpc`
+ * [Python](src/python/grpcio): `pip install grpcio`
+ * [Ruby](src/ruby): `gem install grpc`
+ * [WebJS](https://github.com/grpc/grpc-web): follow the grpc-web instructions
+
+Per-language quickstart guides and tutorials can be found in the [documentation section on the grpc.io website](https://grpc.io/docs/). Code examples are available in the [examples](examples) directory.
+
+Precompiled bleeding-edge package builds of gRPC `master` branch's `HEAD` are uploaded daily to [packages.grpc.io](https://packages.grpc.io).
+
+# To start developing gRPC
+
+Contributions are welcome!
+
+Please read [How to contribute](CONTRIBUTING.md) which will guide you through the entire workflow of how to build the source code, how to run the tests, and how to contribute changes to
+the gRPC codebase.
+The "How to contribute" document also contains info on how the contribution process works and contains best practices for creating contributions.
+
+# Troubleshooting
+
+Sometimes things go wrong. Please check out the [Troubleshooting guide](TROUBLESHOOTING.md) if you are experiencing issues with gRPC.
+
+# Performance
+
See the [Performance dashboard](https://performance-dot-grpc-testing.appspot.com/explore?dashboard=5652536396611584) for performance numbers of master branch daily builds.
-
-# Concepts
-
-See [gRPC Concepts](CONCEPTS.md)
-
-# About This Repository
-
-This repository contains source code for gRPC libraries implemented in multiple languages written on top of a shared C core library [src/core](src/core).
-
-Libraries in different languages may be in various states of development. We are seeking contributions for all of these libraries:
-
-| Language | Source |
-|-------------------------|-------------------------------------|
-| Shared C [core library] | [src/core](src/core) |
-| C++ | [src/cpp](src/cpp) |
-| Ruby | [src/ruby](src/ruby) |
-| Python | [src/python](src/python) |
-| PHP | [src/php](src/php) |
-| C# (core library based) | [src/csharp](src/csharp) |
-| Objective-C | [src/objective-c](src/objective-c) |
-
-| Language | Source repo |
-|-------------------------|------------------------------------------------------|
+
+# Concepts
+
+See [gRPC Concepts](CONCEPTS.md)
+
+# About This Repository
+
+This repository contains source code for gRPC libraries implemented in multiple languages written on top of a shared C core library [src/core](src/core).
+
+Libraries in different languages may be in various states of development. We are seeking contributions for all of these libraries:
+
+| Language | Source |
+|-------------------------|-------------------------------------|
+| Shared C [core library] | [src/core](src/core) |
+| C++ | [src/cpp](src/cpp) |
+| Ruby | [src/ruby](src/ruby) |
+| Python | [src/python](src/python) |
+| PHP | [src/php](src/php) |
+| C# (core library based) | [src/csharp](src/csharp) |
+| Objective-C | [src/objective-c](src/objective-c) |
+
+| Language | Source repo |
+|-------------------------|------------------------------------------------------|
| Java | [grpc-java](https://github.com/grpc/grpc-java) |
| Kotlin | [grpc-kotlin](https://github.com/grpc/grpc-kotlin) |
| Go | [grpc-go](https://github.com/grpc/grpc-go) |
-| NodeJS | [grpc-node](https://github.com/grpc/grpc-node) |
-| WebJS | [grpc-web](https://github.com/grpc/grpc-web) |
-| Dart | [grpc-dart](https://github.com/grpc/grpc-dart) |
-| .NET (pure C# impl.) | [grpc-dotnet](https://github.com/grpc/grpc-dotnet) |
+| NodeJS | [grpc-node](https://github.com/grpc/grpc-node) |
+| WebJS | [grpc-web](https://github.com/grpc/grpc-web) |
+| Dart | [grpc-dart](https://github.com/grpc/grpc-dart) |
+| .NET (pure C# impl.) | [grpc-dotnet](https://github.com/grpc/grpc-dotnet) |
diff --git a/contrib/libs/grpc/TROUBLESHOOTING.md b/contrib/libs/grpc/TROUBLESHOOTING.md
index 035213b9e1..68aed92175 100644
--- a/contrib/libs/grpc/TROUBLESHOOTING.md
+++ b/contrib/libs/grpc/TROUBLESHOOTING.md
@@ -1,43 +1,43 @@
-# Troubleshooting gRPC
-
-This guide is for troubleshooting gRPC implementations based on C core library (sources for most of them are living in the `grpc/grpc` repository).
-
-## Enabling extra logging and tracing
-
-Extra logging can be very useful for diagnosing problems. All gRPC implementations based on C core library support
-the `GRPC_VERBOSITY` and `GRPC_TRACE` environment variables that can be used to increase the amount of information
-that gets printed to stderr.
-
-## GRPC_VERBOSITY
-
-`GRPC_VERBOSITY` is used to set the minimum level of log messages printed by gRPC (supported values are `DEBUG`, `INFO` and `ERROR`). If this environment variable is unset, only `ERROR` logs will be printed.
-
-## GRPC_TRACE
-
-`GRPC_TRACE` can be used to enable extra logging for some internal gRPC components. Enabling the right traces can be invaluable
-for diagnosing for what is going wrong when things aren't working as intended. Possible values for `GRPC_TRACE` are listed in [Environment Variables Overview](doc/environment_variables.md).
+# Troubleshooting gRPC
+
+This guide is for troubleshooting gRPC implementations based on C core library (sources for most of them are living in the `grpc/grpc` repository).
+
+## Enabling extra logging and tracing
+
+Extra logging can be very useful for diagnosing problems. All gRPC implementations based on C core library support
+the `GRPC_VERBOSITY` and `GRPC_TRACE` environment variables that can be used to increase the amount of information
+that gets printed to stderr.
+
+## GRPC_VERBOSITY
+
+`GRPC_VERBOSITY` is used to set the minimum level of log messages printed by gRPC (supported values are `DEBUG`, `INFO` and `ERROR`). If this environment variable is unset, only `ERROR` logs will be printed.
+
+## GRPC_TRACE
+
+`GRPC_TRACE` can be used to enable extra logging for some internal gRPC components. Enabling the right traces can be invaluable
+for diagnosing for what is going wrong when things aren't working as intended. Possible values for `GRPC_TRACE` are listed in [Environment Variables Overview](doc/environment_variables.md).
Multiple traces can be enabled at once (use comma as separator).
-
-```
-# Enable debug logs for an application
-GRPC_VERBOSITY=debug ./helloworld_application_using_grpc
-```
-
-```
-# Print information about invocations of low-level C core API.
-# Note that trace logs of log level DEBUG won't be displayed.
-# Also note that most tracers user log level INFO, so without setting
-# GPRC_VERBOSITY accordingly, no traces will be printed.
-GRPC_VERBOSITY=info GRPC_TRACE=api ./helloworld_application_using_grpc
-```
-
-```
-# Print info from 3 different tracers, including tracing logs with log level DEBUG
-GRPC_VERBOSITY=debug GRPC_TRACE=tcp,http,api ./helloworld_application_using_grpc
-```
-
-Known limitations: `GPRC_TRACE=tcp` is currently not implemented for Windows (you won't see any tcp traces).
-
-Please note that the `GRPC_TRACE` environment variable has nothing to do with gRPC's "tracing" feature (= tracing RPCs in
-microservice environment to gain insight about how requests are processed by deployment), it is merely used to enable printing
-of extra logs.
+
+```
+# Enable debug logs for an application
+GRPC_VERBOSITY=debug ./helloworld_application_using_grpc
+```
+
+```
+# Print information about invocations of low-level C core API.
+# Note that trace logs of log level DEBUG won't be displayed.
+# Also note that most tracers user log level INFO, so without setting
+# GPRC_VERBOSITY accordingly, no traces will be printed.
+GRPC_VERBOSITY=info GRPC_TRACE=api ./helloworld_application_using_grpc
+```
+
+```
+# Print info from 3 different tracers, including tracing logs with log level DEBUG
+GRPC_VERBOSITY=debug GRPC_TRACE=tcp,http,api ./helloworld_application_using_grpc
+```
+
+Known limitations: `GPRC_TRACE=tcp` is currently not implemented for Windows (you won't see any tcp traces).
+
+Please note that the `GRPC_TRACE` environment variable has nothing to do with gRPC's "tracing" feature (= tracing RPCs in
+microservice environment to gain insight about how requests are processed by deployment), it is merely used to enable printing
+of extra logs.
diff --git a/contrib/libs/grpc/grpc++/ya.make b/contrib/libs/grpc/grpc++/ya.make
index 788da4ce7e..46927dd644 100644
--- a/contrib/libs/grpc/grpc++/ya.make
+++ b/contrib/libs/grpc/grpc++/ya.make
@@ -1,41 +1,41 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/third_party/address_sorting
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
contrib/libs/openssl
contrib/restricted/abseil-cpp-tstring/y_absl/strings
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/src/core/ext/upb-generated
- contrib/libs/grpc/third_party/upb
-)
-
-NO_COMPILER_WARNINGS()
-
+ contrib/libs/grpc
+ contrib/libs/grpc/src/core/ext/upb-generated
+ contrib/libs/grpc/third_party/upb
+)
+
+NO_COMPILER_WARNINGS()
+
SRCDIR(contrib/libs/grpc/src/cpp)
-
-IF (OS_LINUX OR OS_DARWIN)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
+ENDIF()
+
+SRCS(
client/channel_cc.cc
client/client_callback.cc
client/client_context.cc
@@ -89,6 +89,6 @@ SRCS(
util/status.cc
util/string_ref.cc
util/time_cc.cc
-)
-
-END()
+)
+
+END()
diff --git a/contrib/libs/grpc/grpc++_error_details/ya.make b/contrib/libs/grpc/grpc++_error_details/ya.make
index c1b3fad26f..26c74192dd 100644
--- a/contrib/libs/grpc/grpc++_error_details/ya.make
+++ b/contrib/libs/grpc/grpc++_error_details/ya.make
@@ -1,41 +1,41 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/grpc++
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/src/proto/grpc/status
- contrib/libs/grpc/third_party/address_sorting
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/grpc++
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/src/proto/grpc/status
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
contrib/libs/protobuf
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- cpp/util/error_details.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ cpp/util/error_details.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/grpc++_reflection/ya.make b/contrib/libs/grpc/grpc++_reflection/ya.make
index 3068b78f9a..8e61b125c5 100644
--- a/contrib/libs/grpc/grpc++_reflection/ya.make
+++ b/contrib/libs/grpc/grpc++_reflection/ya.make
@@ -1,42 +1,42 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/grpc++
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
- contrib/libs/grpc/third_party/address_sorting
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/grpc++
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
contrib/libs/protobuf
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
+ENDIF()
+
+SRCS(
GLOBAL cpp/ext/proto_server_reflection_plugin.cc
- cpp/ext/proto_server_reflection.cc
-)
-
-END()
+ cpp/ext/proto_server_reflection.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/grpc++_unsecure/ya.make b/contrib/libs/grpc/grpc++_unsecure/ya.make
index 4810d9a037..9321f1cad3 100644
--- a/contrib/libs/grpc/grpc++_unsecure/ya.make
+++ b/contrib/libs/grpc/grpc++_unsecure/ya.make
@@ -1,42 +1,42 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/grpc++
- contrib/libs/grpc/grpc_unsecure
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/third_party/address_sorting
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/grpc++
+ contrib/libs/grpc/grpc_unsecure
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/src/core/ext/upb-generated
- contrib/libs/grpc/third_party/upb
-)
-
-NO_COMPILER_WARNINGS()
-
+ contrib/libs/grpc
+ contrib/libs/grpc/src/core/ext/upb-generated
+ contrib/libs/grpc/third_party/upb
+)
+
+NO_COMPILER_WARNINGS()
+
SRCDIR(contrib/libs/grpc/src/cpp)
-
-IF (OS_LINUX OR OS_DARWIN)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
+ENDIF()
+
+SRCS(
common/insecure_create_auth_context.cc
-)
-
-END()
+)
+
+END()
diff --git a/contrib/libs/grpc/grpc/ya.make b/contrib/libs/grpc/grpc/ya.make
index c29c11c0c4..f43aa75485 100644
--- a/contrib/libs/grpc/grpc/ya.make
+++ b/contrib/libs/grpc/grpc/ya.make
@@ -1,14 +1,14 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
+PEERDIR(
certs
contrib/libs/c-ares
contrib/libs/grpc/src/core/lib
@@ -25,8 +25,8 @@ PEERDIR(
contrib/restricted/abseil-cpp-tstring/y_absl/strings/internal/str_format
contrib/restricted/abseil-cpp-tstring/y_absl/time
library/cpp/resource
-)
-
+)
+
ADDINCL(
GLOBAL contrib/libs/grpc/include
contrib/libs/c-ares
@@ -490,4 +490,4 @@ SRCS(
tsi/transport_security_grpc.cc
)
-END()
+END()
diff --git a/contrib/libs/grpc/grpc_unsecure/ya.make b/contrib/libs/grpc/grpc_unsecure/ya.make
index 38ef63eb18..9f5151da90 100644
--- a/contrib/libs/grpc/grpc_unsecure/ya.make
+++ b/contrib/libs/grpc/grpc_unsecure/ya.make
@@ -1,50 +1,50 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
- contrib/libs/c-ares
- contrib/libs/grpc/grpc
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/third_party/address_sorting
+PEERDIR(
+ contrib/libs/c-ares
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
- contrib/libs/zlib
+ contrib/libs/zlib
contrib/restricted/abseil-cpp-tstring/y_absl/status
contrib/restricted/abseil-cpp-tstring/y_absl/strings
contrib/restricted/abseil-cpp-tstring/y_absl/strings/cord
contrib/restricted/abseil-cpp-tstring/y_absl/strings/internal/str_format
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
- contrib/libs/c-ares
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
+ contrib/libs/c-ares
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/src/core/ext/upb-generated
- contrib/libs/grpc/third_party/address_sorting/include
- contrib/libs/grpc/third_party/upb
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src/core)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+ contrib/libs/grpc/src/core/ext/upb-generated
+ contrib/libs/grpc/third_party/address_sorting/include
+ contrib/libs/grpc/third_party/upb
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src/core)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc
- lib/surface/init_unsecure.cc
- plugin_registry/grpc_unsecure_plugin_registry.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc
+ lib/surface/init_unsecure.cc
+ plugin_registry/grpc_unsecure_plugin_registry.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/grpcpp_channelz/ya.make b/contrib/libs/grpc/grpcpp_channelz/ya.make
index 31761e3d47..eab98dc73a 100644
--- a/contrib/libs/grpc/grpcpp_channelz/ya.make
+++ b/contrib/libs/grpc/grpcpp_channelz/ya.make
@@ -1,42 +1,42 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/grpc++
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/src/proto/grpc/channelz
- contrib/libs/grpc/third_party/address_sorting
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/grpc++
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/src/proto/grpc/channelz
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
contrib/libs/protobuf
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- cpp/server/channelz/channelz_service.cc
- cpp/server/channelz/channelz_service_plugin.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ cpp/server/channelz/channelz_service.cc
+ cpp/server/channelz/channelz_service_plugin.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/include/grpc/grpc.h b/contrib/libs/grpc/include/grpc/grpc.h
index 6001117521..847cc6fceb 100644
--- a/contrib/libs/grpc/include/grpc/grpc.h
+++ b/contrib/libs/grpc/include/grpc/grpc.h
@@ -76,11 +76,11 @@ GRPCAPI void grpc_init(void);
Before it's called, there should haven been a matching invocation to
grpc_init().
- The last call to grpc_shutdown will initiate cleaning up of grpc library
- internals, which can happen in another thread. Once the clean-up is done,
- no memory is used by grpc, nor are any instructions executing within the
- grpc library. Prior to calling, all application owned grpc objects must
- have been destroyed. */
+ The last call to grpc_shutdown will initiate cleaning up of grpc library
+ internals, which can happen in another thread. Once the clean-up is done,
+ no memory is used by grpc, nor are any instructions executing within the
+ grpc library. Prior to calling, all application owned grpc objects must
+ have been destroyed. */
GRPCAPI void grpc_shutdown(void);
/** EXPERIMENTAL. Returns 1 if the grpc library has been initialized.
@@ -89,10 +89,10 @@ GRPCAPI void grpc_shutdown(void);
https://github.com/grpc/grpc/issues/15334 */
GRPCAPI int grpc_is_initialized(void);
-/** EXPERIMENTAL. Blocking shut down grpc library.
- This is only for wrapped language to use now. */
-GRPCAPI void grpc_shutdown_blocking(void);
-
+/** EXPERIMENTAL. Blocking shut down grpc library.
+ This is only for wrapped language to use now. */
+GRPCAPI void grpc_shutdown_blocking(void);
+
/** Return a string representing the current version of grpc */
GRPCAPI const char* grpc_version_string(void);
@@ -222,7 +222,7 @@ GRPCAPI grpc_call* grpc_channel_create_call(
grpc_completion_queue* completion_queue, grpc_slice method,
const grpc_slice* host, gpr_timespec deadline, void* reserved);
-/** Pre-register a method/host pair on a channel.
+/** Pre-register a method/host pair on a channel.
method and host are not owned and must remain alive while the channel is
alive. */
GRPCAPI void* grpc_channel_register_call(grpc_channel* channel,
@@ -323,14 +323,14 @@ GRPCAPI void grpc_channel_destroy(grpc_channel* channel);
If a grpc_call fails, it's guaranteed that no change to the call state
has been made. */
-/** Cancel an RPC.
+/** Cancel an RPC.
Can be called multiple times, from any thread.
THREAD-SAFETY grpc_call_cancel and grpc_call_cancel_with_status
are thread-safe, and can be called at any point before grpc_call_unref
is called.*/
GRPCAPI grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved);
-/** Cancel an RPC.
+/** Cancel an RPC.
Can be called multiple times, from any thread.
If a status has not been received for the call, set it to the status code
and description passed in.
diff --git a/contrib/libs/grpc/include/grpc/grpc_security.h b/contrib/libs/grpc/include/grpc/grpc_security.h
index 1810681b76..3e79c1a33a 100644
--- a/contrib/libs/grpc/include/grpc/grpc_security.h
+++ b/contrib/libs/grpc/include/grpc/grpc_security.h
@@ -191,28 +191,28 @@ typedef struct {
const char* cert_chain;
} grpc_ssl_pem_key_cert_pair;
-/** Deprecated in favor of grpc_ssl_verify_peer_options. It will be removed
- after all of its call sites are migrated to grpc_ssl_verify_peer_options.
- Object that holds additional peer-verification options on a secure
- channel. */
-typedef struct {
- /** If non-NULL this callback will be invoked with the expected
- target_name, the peer's certificate (in PEM format), and whatever
- userdata pointer is set below. If a non-zero value is returned by this
- callback then it is treated as a verification failure. Invocation of
- the callback is blocking, so any implementation should be light-weight.
- */
- int (*verify_peer_callback)(const char* target_name, const char* peer_pem,
- void* userdata);
- /** Arbitrary userdata that will be passed as the last argument to
- verify_peer_callback. */
- void* verify_peer_callback_userdata;
- /** A destruct callback that will be invoked when the channel is being
- cleaned up. The userdata argument will be passed to it. The intent is
- to perform any cleanup associated with that userdata. */
- void (*verify_peer_destruct)(void* userdata);
-} verify_peer_options;
-
+/** Deprecated in favor of grpc_ssl_verify_peer_options. It will be removed
+ after all of its call sites are migrated to grpc_ssl_verify_peer_options.
+ Object that holds additional peer-verification options on a secure
+ channel. */
+typedef struct {
+ /** If non-NULL this callback will be invoked with the expected
+ target_name, the peer's certificate (in PEM format), and whatever
+ userdata pointer is set below. If a non-zero value is returned by this
+ callback then it is treated as a verification failure. Invocation of
+ the callback is blocking, so any implementation should be light-weight.
+ */
+ int (*verify_peer_callback)(const char* target_name, const char* peer_pem,
+ void* userdata);
+ /** Arbitrary userdata that will be passed as the last argument to
+ verify_peer_callback. */
+ void* verify_peer_callback_userdata;
+ /** A destruct callback that will be invoked when the channel is being
+ cleaned up. The userdata argument will be passed to it. The intent is
+ to perform any cleanup associated with that userdata. */
+ void (*verify_peer_destruct)(void* userdata);
+} verify_peer_options;
+
/** Object that holds additional peer-verification options on a secure
channel. */
typedef struct {
@@ -231,11 +231,11 @@ typedef struct {
cleaned up. The userdata argument will be passed to it. The intent is
to perform any cleanup associated with that userdata. */
void (*verify_peer_destruct)(void* userdata);
-} grpc_ssl_verify_peer_options;
+} grpc_ssl_verify_peer_options;
-/** Deprecated in favor of grpc_ssl_server_credentials_create_ex. It will be
- removed after all of its call sites are migrated to
- grpc_ssl_server_credentials_create_ex. Creates an SSL credentials object.
+/** Deprecated in favor of grpc_ssl_server_credentials_create_ex. It will be
+ removed after all of its call sites are migrated to
+ grpc_ssl_server_credentials_create_ex. Creates an SSL credentials object.
The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY.
- pem_root_certs is the NULL-terminated string containing the PEM encoding
of the server root certificates. If this parameter is NULL, the
@@ -244,15 +244,15 @@ typedef struct {
try to get the roots set by grpc_override_ssl_default_roots. Eventually,
if all these fail, it will try to get the roots from a well-known place on
disk (in the grpc install directory).
-
- gRPC has implemented root cache if the underlying OpenSSL library supports
- it. The gRPC root certificates cache is only applicable on the default
- root certificates, which is used when this parameter is nullptr. If user
- provides their own pem_root_certs, when creating an SSL credential object,
- gRPC would not be able to cache it, and each subchannel will generate a
- copy of the root store. So it is recommended to avoid providing large room
- pem with pem_root_certs parameter to avoid excessive memory consumption,
- particularly on mobile platforms such as iOS.
+
+ gRPC has implemented root cache if the underlying OpenSSL library supports
+ it. The gRPC root certificates cache is only applicable on the default
+ root certificates, which is used when this parameter is nullptr. If user
+ provides their own pem_root_certs, when creating an SSL credential object,
+ gRPC would not be able to cache it, and each subchannel will generate a
+ copy of the root store. So it is recommended to avoid providing large room
+ pem with pem_root_certs parameter to avoid excessive memory consumption,
+ particularly on mobile platforms such as iOS.
- pem_key_cert_pair is a pointer on the object containing client's private
key and certificate chain. This parameter can be NULL if the client does
not have such a key/cert pair.
@@ -267,38 +267,38 @@ GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create(
const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
const verify_peer_options* verify_options, void* reserved);
-/* Creates an SSL credentials object.
+/* Creates an SSL credentials object.
The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY.
- - pem_root_certs is the NULL-terminated string containing the PEM encoding
- of the server root certificates. If this parameter is NULL, the
- implementation will first try to dereference the file pointed by the
- GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable, and if that fails,
- try to get the roots set by grpc_override_ssl_default_roots. Eventually,
- if all these fail, it will try to get the roots from a well-known place on
- disk (in the grpc install directory).
-
- gRPC has implemented root cache if the underlying OpenSSL library supports
- it. The gRPC root certificates cache is only applicable on the default
- root certificates, which is used when this parameter is nullptr. If user
- provides their own pem_root_certs, when creating an SSL credential object,
- gRPC would not be able to cache it, and each subchannel will generate a
- copy of the root store. So it is recommended to avoid providing large room
- pem with pem_root_certs parameter to avoid excessive memory consumption,
- particularly on mobile platforms such as iOS.
- - pem_key_cert_pair is a pointer on the object containing client's private
- key and certificate chain. This parameter can be NULL if the client does
- not have such a key/cert pair.
- - verify_options is an optional verify_peer_options object which holds
- additional options controlling how peer certificates are verified. For
- example, you can supply a callback which receives the peer's certificate
- with which you can do additional verification. Can be NULL, in which
- case verification will retain default behavior. Any settings in
- verify_options are copied during this call, so the verify_options
- object can be released afterwards. */
-GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create_ex(
- const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const grpc_ssl_verify_peer_options* verify_options, void* reserved);
-
+ - pem_root_certs is the NULL-terminated string containing the PEM encoding
+ of the server root certificates. If this parameter is NULL, the
+ implementation will first try to dereference the file pointed by the
+ GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable, and if that fails,
+ try to get the roots set by grpc_override_ssl_default_roots. Eventually,
+ if all these fail, it will try to get the roots from a well-known place on
+ disk (in the grpc install directory).
+
+ gRPC has implemented root cache if the underlying OpenSSL library supports
+ it. The gRPC root certificates cache is only applicable on the default
+ root certificates, which is used when this parameter is nullptr. If user
+ provides their own pem_root_certs, when creating an SSL credential object,
+ gRPC would not be able to cache it, and each subchannel will generate a
+ copy of the root store. So it is recommended to avoid providing large room
+ pem with pem_root_certs parameter to avoid excessive memory consumption,
+ particularly on mobile platforms such as iOS.
+ - pem_key_cert_pair is a pointer on the object containing client's private
+ key and certificate chain. This parameter can be NULL if the client does
+ not have such a key/cert pair.
+ - verify_options is an optional verify_peer_options object which holds
+ additional options controlling how peer certificates are verified. For
+ example, you can supply a callback which receives the peer's certificate
+ with which you can do additional verification. Can be NULL, in which
+ case verification will retain default behavior. Any settings in
+ verify_options are copied during this call, so the verify_options
+ object can be released afterwards. */
+GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create_ex(
+ const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
+ const grpc_ssl_verify_peer_options* verify_options, void* reserved);
+
/** Creates a composite channel credentials object. The security level of
* resulting connection is determined by channel_creds. */
GRPCAPI grpc_channel_credentials* grpc_composite_channel_credentials_create(
@@ -340,7 +340,7 @@ GRPCAPI grpc_call_credentials* grpc_google_refresh_token_credentials_create(
const char* json_refresh_token, void* reserved);
/** Creates an Oauth2 Access Token credentials with an access token that was
- acquired by an out of band mechanism. */
+ acquired by an out of band mechanism. */
GRPCAPI grpc_call_credentials* grpc_access_token_credentials_create(
const char* access_token, void* reserved);
@@ -349,31 +349,31 @@ GRPCAPI grpc_call_credentials* grpc_google_iam_credentials_create(
const char* authorization_token, const char* authority_selector,
void* reserved);
-/** Options for creating STS Oauth Token Exchange credentials following the IETF
- draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
- Optional fields may be set to NULL or empty string. It is the responsibility
- of the caller to ensure that the subject and actor tokens are refreshed on
- disk at the specified paths. This API is used for experimental purposes for
- now and may change in the future. */
-typedef struct {
- const char* token_exchange_service_uri; /* Required. */
- const char* resource; /* Optional. */
- const char* audience; /* Optional. */
- const char* scope; /* Optional. */
- const char* requested_token_type; /* Optional. */
- const char* subject_token_path; /* Required. */
- const char* subject_token_type; /* Required. */
- const char* actor_token_path; /* Optional. */
- const char* actor_token_type; /* Optional. */
-} grpc_sts_credentials_options;
-
-/** Creates an STS credentials following the STS Token Exchanged specifed in the
- IETF draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
- This API is used for experimental purposes for now and may change in the
- future. */
-GRPCAPI grpc_call_credentials* grpc_sts_credentials_create(
- const grpc_sts_credentials_options* options, void* reserved);
-
+/** Options for creating STS Oauth Token Exchange credentials following the IETF
+ draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
+ Optional fields may be set to NULL or empty string. It is the responsibility
+ of the caller to ensure that the subject and actor tokens are refreshed on
+ disk at the specified paths. This API is used for experimental purposes for
+ now and may change in the future. */
+typedef struct {
+ const char* token_exchange_service_uri; /* Required. */
+ const char* resource; /* Optional. */
+ const char* audience; /* Optional. */
+ const char* scope; /* Optional. */
+ const char* requested_token_type; /* Optional. */
+ const char* subject_token_path; /* Required. */
+ const char* subject_token_type; /* Required. */
+ const char* actor_token_path; /* Optional. */
+ const char* actor_token_type; /* Optional. */
+} grpc_sts_credentials_options;
+
+/** Creates an STS credentials following the STS Token Exchanged specifed in the
+ IETF draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
+ This API is used for experimental purposes for now and may change in the
+ future. */
+GRPCAPI grpc_call_credentials* grpc_sts_credentials_create(
+ const grpc_sts_credentials_options* options, void* reserved);
+
/** Callback function to be called by the metadata credentials plugin
implementation when the metadata is ready.
- user_data is the opaque pointer that was passed in the get_metadata method
@@ -550,7 +550,7 @@ GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create(
/** Deprecated in favor of grpc_ssl_server_credentials_create_with_options.
Same as grpc_ssl_server_credentials_create method except uses
grpc_ssl_client_certificate_request_type enum to support more ways to
- authenticate client certificates.*/
+ authenticate client certificates.*/
GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create_ex(
const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
size_t num_key_cert_pairs,
@@ -763,7 +763,7 @@ typedef struct grpc_tls_credentials_options grpc_tls_credentials_options;
/** Create an empty TLS credentials options. It is used for
* experimental purpose for now and subject to change. */
-GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_create(void);
+GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_create(void);
/** Set grpc_ssl_client_certificate_request_type field in credentials options
with the provided type. options should not be NULL.
@@ -818,8 +818,8 @@ GRPCAPI int grpc_tls_credentials_options_set_server_authorization_check_config(
/** Create an empty grpc_tls_key_materials_config instance.
* It is used for experimental purpose for now and subject to change. */
-GRPCAPI grpc_tls_key_materials_config* grpc_tls_key_materials_config_create(
- void);
+GRPCAPI grpc_tls_key_materials_config* grpc_tls_key_materials_config_create(
+ void);
/** Set grpc_tls_key_materials_config instance with provided a TLS certificate.
It's valid for the caller to provide nullptr pem_root_certs, in which case
@@ -835,21 +835,21 @@ GRPCAPI int grpc_tls_key_materials_config_set_key_materials(
const grpc_ssl_pem_key_cert_pair** pem_key_cert_pairs,
size_t num_key_cert_pairs);
-/** Set grpc_tls_key_materials_config instance with a provided version number,
- which is used to keep track of the version of key materials.
- It returns 1 on success and 0 on failure. It is used for
- experimental purpose for now and subject to change.
- */
-GRPCAPI int grpc_tls_key_materials_config_set_version(
- grpc_tls_key_materials_config* config, int version);
-
-/** Get the version number of a grpc_tls_key_materials_config instance.
- It returns the version number on success and -1 on failure.
- It is used for experimental purpose for now and subject to change.
- */
-GRPCAPI int grpc_tls_key_materials_config_get_version(
- grpc_tls_key_materials_config* config);
-
+/** Set grpc_tls_key_materials_config instance with a provided version number,
+ which is used to keep track of the version of key materials.
+ It returns 1 on success and 0 on failure. It is used for
+ experimental purpose for now and subject to change.
+ */
+GRPCAPI int grpc_tls_key_materials_config_set_version(
+ grpc_tls_key_materials_config* config, int version);
+
+/** Get the version number of a grpc_tls_key_materials_config instance.
+ It returns the version number on success and -1 on failure.
+ It is used for experimental purpose for now and subject to change.
+ */
+GRPCAPI int grpc_tls_key_materials_config_get_version(
+ grpc_tls_key_materials_config* config);
+
/** --- TLS credential reload config. ---
It is used for experimental purpose for now and subject to change.*/
@@ -862,34 +862,34 @@ typedef struct grpc_tls_credential_reload_arg grpc_tls_credential_reload_arg;
typedef void (*grpc_tls_on_credential_reload_done_cb)(
grpc_tls_credential_reload_arg* arg);
-/** A struct containing all information necessary to schedule/cancel a
- credential reload request.
- - cb and cb_user_data represent a gRPC-provided
- callback and an argument passed to it.
- - key_materials_config is an in/output parameter containing currently
+/** A struct containing all information necessary to schedule/cancel a
+ credential reload request.
+ - cb and cb_user_data represent a gRPC-provided
+ callback and an argument passed to it.
+ - key_materials_config is an in/output parameter containing currently
used/newly reloaded credentials. If credential reload does not result in
a new credential, key_materials_config should not be modified. The same
key_materials_config object can be updated if new key materials is
available.
- - status and error_details are used to hold information about
- errors occurred when a credential reload request is scheduled/cancelled.
- - config is a pointer to the unique grpc_tls_credential_reload_config
- instance that this argument corresponds to.
- - context is a pointer to a wrapped language implementation of this
- grpc_tls_credential_reload_arg instance.
- - destroy_context is a pointer to a caller-provided method that cleans
- up any data associated with the context pointer.
- It is used for experimental purposes for now and subject to change.
-*/
+ - status and error_details are used to hold information about
+ errors occurred when a credential reload request is scheduled/cancelled.
+ - config is a pointer to the unique grpc_tls_credential_reload_config
+ instance that this argument corresponds to.
+ - context is a pointer to a wrapped language implementation of this
+ grpc_tls_credential_reload_arg instance.
+ - destroy_context is a pointer to a caller-provided method that cleans
+ up any data associated with the context pointer.
+ It is used for experimental purposes for now and subject to change.
+*/
struct grpc_tls_credential_reload_arg {
grpc_tls_on_credential_reload_done_cb cb;
void* cb_user_data;
grpc_tls_key_materials_config* key_materials_config;
- grpc_ssl_certificate_config_reload_status status;
+ grpc_ssl_certificate_config_reload_status status;
grpc_tls_error_details* error_details;
- grpc_tls_credential_reload_config* config;
- void* context;
- void (*destroy_context)(void* ctx);
+ grpc_tls_credential_reload_config* config;
+ void* context;
+ void (*destroy_context)(void* ctx);
};
/** Create a grpc_tls_credential_reload_config instance.
@@ -935,39 +935,39 @@ typedef void (*grpc_tls_on_server_authorization_check_done_cb)(
grpc_tls_server_authorization_check_arg* arg);
/** A struct containing all information necessary to schedule/cancel a server
- authorization check request.
- - cb and cb_user_data represent a gRPC-provided callback and an argument
- passed to it.
- - success will store the result of server authorization check. That is,
- if success returns a non-zero value, it means the authorization check
- passes and if returning zero, it means the check fails.
- - target_name is the name of an endpoint the channel is connecting to.
- - peer_cert represents a complete certificate chain including both
- signing and leaf certificates.
- - status and error_details contain information
- about errors occurred when a server authorization check request is
- scheduled/cancelled.
- - config is a pointer to the unique
- grpc_tls_server_authorization_check_config instance that this argument
- corresponds to.
- - context is a pointer to a wrapped language implementation of this
- grpc_tls_server_authorization_check_arg instance.
- - destroy_context is a pointer to a caller-provided method that cleans
- up any data associated with the context pointer.
- It is used for experimental purpose for now and subject to change.
-*/
+ authorization check request.
+ - cb and cb_user_data represent a gRPC-provided callback and an argument
+ passed to it.
+ - success will store the result of server authorization check. That is,
+ if success returns a non-zero value, it means the authorization check
+ passes and if returning zero, it means the check fails.
+ - target_name is the name of an endpoint the channel is connecting to.
+ - peer_cert represents a complete certificate chain including both
+ signing and leaf certificates.
+ - status and error_details contain information
+ about errors occurred when a server authorization check request is
+ scheduled/cancelled.
+ - config is a pointer to the unique
+ grpc_tls_server_authorization_check_config instance that this argument
+ corresponds to.
+ - context is a pointer to a wrapped language implementation of this
+ grpc_tls_server_authorization_check_arg instance.
+ - destroy_context is a pointer to a caller-provided method that cleans
+ up any data associated with the context pointer.
+ It is used for experimental purpose for now and subject to change.
+*/
struct grpc_tls_server_authorization_check_arg {
grpc_tls_on_server_authorization_check_done_cb cb;
void* cb_user_data;
- int success;
+ int success;
const char* target_name;
const char* peer_cert;
const char* peer_cert_full_chain;
grpc_status_code status;
grpc_tls_error_details* error_details;
- grpc_tls_server_authorization_check_config* config;
- void* context;
- void (*destroy_context)(void* ctx);
+ grpc_tls_server_authorization_check_config* config;
+ void* context;
+ void (*destroy_context)(void* ctx);
};
/** Create a grpc_tls_server_authorization_check_config instance.
@@ -999,36 +999,36 @@ grpc_tls_server_authorization_check_config_create(
grpc_tls_server_authorization_check_arg* arg),
void (*destruct)(void* config_user_data));
-/**
+/**
* This method creates a TLS channel credential object.
* It takes ownership of the options parameter. The security level
* of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY.
- *
- * - options: grpc TLS credentials options instance.
- *
- * It returns the created credential object.
- *
- * It is used for experimental purpose for now and subject
- * to change.
- */
-
+ *
+ * - options: grpc TLS credentials options instance.
+ *
+ * It returns the created credential object.
+ *
+ * It is used for experimental purpose for now and subject
+ * to change.
+ */
+
grpc_channel_credentials* grpc_tls_credentials_create(
- grpc_tls_credentials_options* options);
-
-/**
- * This method creates a TLS server credential object.
- * It takes ownership of the options parameter.
- *
- * - options: grpc TLS credentials options instance.
- *
- * It returns the created credential object.
- *
- * It is used for experimental purpose for now and subject
- * to change.
- */
+ grpc_tls_credentials_options* options);
+
+/**
+ * This method creates a TLS server credential object.
+ * It takes ownership of the options parameter.
+ *
+ * - options: grpc TLS credentials options instance.
+ *
+ * It returns the created credential object.
+ *
+ * It is used for experimental purpose for now and subject
+ * to change.
+ */
grpc_server_credentials* grpc_tls_server_credentials_create(
- grpc_tls_credentials_options* options);
-
+ grpc_tls_credentials_options* options);
+
/**
* EXPERIMENTAL API - Subject to change
*
diff --git a/contrib/libs/grpc/include/grpc/grpc_security_constants.h b/contrib/libs/grpc/include/grpc/grpc_security_constants.h
index a62f76753b..47619ca4da 100644
--- a/contrib/libs/grpc/include/grpc/grpc_security_constants.h
+++ b/contrib/libs/grpc/include/grpc/grpc_security_constants.h
@@ -99,7 +99,7 @@ typedef enum {
/** Server requests client certificate and enforces that the client presents a
certificate.
- The certificate presented by the client is verified by the gRPC framework.
+ The certificate presented by the client is verified by the gRPC framework.
(For a successful connection the client needs to present a certificate that
can be verified against the root certificate configured by the server)
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/byte_buffer.h b/contrib/libs/grpc/include/grpc/impl/codegen/byte_buffer.h
index 1247906815..540243d478 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/byte_buffer.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/byte_buffer.h
@@ -73,19 +73,19 @@ GRPCAPI void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader* reader);
GRPCAPI int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader,
grpc_slice* slice);
-/** EXPERIMENTAL API - This function may be removed and changed, in the future.
- *
- * Updates \a slice with the next piece of data from from \a reader and returns
- * 1. Returns 0 at the end of the stream. Caller is responsible for making sure
- * the slice pointer remains valid when accessed.
- *
- * NOTE: Do not use this function unless the caller can guarantee that the
- * underlying grpc_byte_buffer outlasts the use of the slice. This is only
- * safe when the underlying grpc_byte_buffer remains immutable while slice
- * is being accessed. */
-GRPCAPI int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
- grpc_slice** slice);
-
+/** EXPERIMENTAL API - This function may be removed and changed, in the future.
+ *
+ * Updates \a slice with the next piece of data from from \a reader and returns
+ * 1. Returns 0 at the end of the stream. Caller is responsible for making sure
+ * the slice pointer remains valid when accessed.
+ *
+ * NOTE: Do not use this function unless the caller can guarantee that the
+ * underlying grpc_byte_buffer outlasts the use of the slice. This is only
+ * safe when the underlying grpc_byte_buffer remains immutable while slice
+ * is being accessed. */
+GRPCAPI int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
+ grpc_slice** slice);
+
/** Merge all data from \a reader into single slice */
GRPCAPI grpc_slice
grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader* reader);
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/gpr_types.h b/contrib/libs/grpc/include/grpc/impl/codegen/gpr_types.h
index 6daf339861..87ace73eb0 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/gpr_types.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/gpr_types.h
@@ -48,7 +48,7 @@ typedef struct gpr_timespec {
int64_t tv_sec;
int32_t tv_nsec;
/** Against which clock was this time measured? (or GPR_TIMESPAN if
- this is a relative time measure) */
+ this is a relative time measure) */
gpr_clock_type clock_type;
} gpr_timespec;
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h b/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h
index 07066f0e1d..e3ca197c5d 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h
@@ -157,9 +157,9 @@ typedef struct {
/** Maximum message length that the channel can send. Int valued, bytes.
-1 means unlimited. */
#define GRPC_ARG_MAX_SEND_MESSAGE_LENGTH "grpc.max_send_message_length"
-/** Maximum time that a channel may have no outstanding rpcs, after which the
- * server will close the connection. Int valued, milliseconds. INT_MAX means
- * unlimited. */
+/** Maximum time that a channel may have no outstanding rpcs, after which the
+ * server will close the connection. Int valued, milliseconds. INT_MAX means
+ * unlimited. */
#define GRPC_ARG_MAX_CONNECTION_IDLE_MS "grpc.max_connection_idle_ms"
/** Maximum time that a channel may exist. Int valued, milliseconds.
* INT_MAX means unlimited. */
@@ -167,10 +167,10 @@ typedef struct {
/** Grace period after the channel reaches its max age. Int valued,
milliseconds. INT_MAX means unlimited. */
#define GRPC_ARG_MAX_CONNECTION_AGE_GRACE_MS "grpc.max_connection_age_grace_ms"
-/** Timeout after the last RPC finishes on the client channel at which the
- * channel goes back into IDLE state. Int valued, milliseconds. INT_MAX means
- * unlimited. The default value is 30 minutes and the min value is 1 second. */
-#define GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS "grpc.client_idle_timeout_ms"
+/** Timeout after the last RPC finishes on the client channel at which the
+ * channel goes back into IDLE state. Int valued, milliseconds. INT_MAX means
+ * unlimited. The default value is 30 minutes and the min value is 1 second. */
+#define GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS "grpc.client_idle_timeout_ms"
/** Enable/disable support for per-message compression. Defaults to 1, unless
GRPC_ARG_MINIMAL_STACK is enabled, in which case it defaults to 0. */
#define GRPC_ARG_ENABLE_PER_MESSAGE_COMPRESSION "grpc.per_message_compression"
@@ -273,14 +273,14 @@ typedef struct {
grpc_ssl_session_cache*). (use grpc_ssl_session_cache_arg_vtable() to fetch
an appropriate pointer arg vtable) */
#define GRPC_SSL_SESSION_CACHE_ARG "grpc.ssl_session_cache"
-/** If non-zero, it will determine the maximum frame size used by TSI's frame
- * protector.
- *
- * NOTE: Be aware that using a large "max_frame_size" is memory inefficient
- * for non-zerocopy protectors. Also, increasing this value above 1MiB
- * can break old binaries that don't support larger than 1MiB frame
- * size. */
-#define GRPC_ARG_TSI_MAX_FRAME_SIZE "grpc.tsi.max_frame_size"
+/** If non-zero, it will determine the maximum frame size used by TSI's frame
+ * protector.
+ *
+ * NOTE: Be aware that using a large "max_frame_size" is memory inefficient
+ * for non-zerocopy protectors. Also, increasing this value above 1MiB
+ * can break old binaries that don't support larger than 1MiB frame
+ * size. */
+#define GRPC_ARG_TSI_MAX_FRAME_SIZE "grpc.tsi.max_frame_size"
/** Maximum metadata size, in bytes. Note this limit applies to the max sum of
all metadata key-value entries in a batch of headers. */
#define GRPC_ARG_MAX_METADATA_SIZE "grpc.max_metadata_size"
@@ -348,7 +348,7 @@ typedef struct {
#define GRPC_ARG_GRPCLB_CALL_TIMEOUT_MS "grpc.grpclb_call_timeout_ms"
/* Timeout in milliseconds to wait for the serverlist from the grpclb load
balancer before using fallback backend addresses from the resolver.
- If 0, enter fallback mode immediately. Default value is 10000. */
+ If 0, enter fallback mode immediately. Default value is 10000. */
#define GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS "grpc.grpclb_fallback_timeout_ms"
/* Timeout in milliseconds to wait for the child of a specific priority to
complete its initial connection attempt before the priority LB policy fails
@@ -396,12 +396,12 @@ typedef struct {
* load balancing policy. Note that this only works with the "ares"
* DNS resolver, and isn't supported by the "native" DNS resolver. */
#define GRPC_ARG_DNS_ENABLE_SRV_QUERIES "grpc.dns_enable_srv_queries"
-/** If set, determines an upper bound on the number of milliseconds that the
- * c-ares based DNS resolver will wait on queries before cancelling them.
- * The default value is 120,000. Setting this to "0" will disable the
- * overall timeout entirely. Note that this doesn't include internal c-ares
- * timeouts/backoff/retry logic, and so the actual DNS resolution may time out
- * sooner than the value specified here. */
+/** If set, determines an upper bound on the number of milliseconds that the
+ * c-ares based DNS resolver will wait on queries before cancelling them.
+ * The default value is 120,000. Setting this to "0" will disable the
+ * overall timeout entirely. Note that this doesn't include internal c-ares
+ * timeouts/backoff/retry logic, and so the actual DNS resolution may time out
+ * sooner than the value specified here. */
#define GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS "grpc.dns_ares_query_timeout"
/** If set, uses a local subchannel pool within the channel. Otherwise, uses the
* global subchannel pool. */
@@ -533,8 +533,8 @@ typedef struct grpc_event {
field is guaranteed to be 0 */
int success;
/** The tag passed to grpc_call_start_batch etc to start this operation.
- *Only* GRPC_OP_COMPLETE has a tag. For all other grpc_completion_type
- values, tag is uninitialized. */
+ *Only* GRPC_OP_COMPLETE has a tag. For all other grpc_completion_type
+ values, tag is uninitialized. */
void* tag;
} grpc_event;
@@ -740,10 +740,10 @@ typedef struct grpc_experimental_completion_queue_functor {
operation succeeded (non-zero) or failed (zero) */
void (*functor_run)(struct grpc_experimental_completion_queue_functor*, int);
- /** The inlineable member specifies whether this functor can be run inline.
- This should only be used for trivial internally-defined functors. */
- int inlineable;
-
+ /** The inlineable member specifies whether this functor can be run inline.
+ This should only be used for trivial internally-defined functors. */
+ int inlineable;
+
/** The following fields are not API. They are meant for internal use. */
int internal_success;
struct grpc_experimental_completion_queue_functor* internal_next;
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h b/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h
index 35419f017b..bc9246307a 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h
@@ -27,7 +27,7 @@
* - some syscalls to be made directly
*/
-/*
+/*
* Defines GPR_ABSEIL_SYNC to use synchronization features from Abseil
*/
#ifndef GPR_ABSEIL_SYNC
@@ -132,7 +132,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#define GPR_SUPPORT_CHANNELS_FROM_FD 1
#elif defined(__linux__)
@@ -159,7 +159,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
@@ -173,26 +173,26 @@
#else /* musl libc */
#define GPR_MUSL_LIBC_COMPAT 1
#endif
-#elif defined(__ASYLO__)
-#define GPR_ARCH_64 1
-#define GPR_CPU_POSIX 1
-#define GPR_GCC_TLS 1
-#define GPR_PLATFORM_STRING "asylo"
-#define GPR_GCC_SYNC 1
-#define GPR_POSIX_SYNC 1
-#define GPR_POSIX_STRING 1
-#define GPR_POSIX_LOG 1
-#define GPR_POSIX_TIME 1
-#define GPR_POSIX_ENV 1
-#define GPR_ASYLO 1
-#define GRPC_POSIX_SOCKET 1
-#define GRPC_POSIX_SOCKETADDR
-#define GRPC_POSIX_SOCKETUTILS 1
-#define GRPC_TIMER_USE_GENERIC 1
-#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
-#define GRPC_POSIX_WAKEUP_FD 1
-#define GRPC_ARES 0
-#define GPR_NO_AUTODETECT_PLATFORM 1
+#elif defined(__ASYLO__)
+#define GPR_ARCH_64 1
+#define GPR_CPU_POSIX 1
+#define GPR_GCC_TLS 1
+#define GPR_PLATFORM_STRING "asylo"
+#define GPR_GCC_SYNC 1
+#define GPR_POSIX_SYNC 1
+#define GPR_POSIX_STRING 1
+#define GPR_POSIX_LOG 1
+#define GPR_POSIX_TIME 1
+#define GPR_POSIX_ENV 1
+#define GPR_ASYLO 1
+#define GRPC_POSIX_SOCKET 1
+#define GRPC_POSIX_SOCKETADDR
+#define GRPC_POSIX_SOCKETUTILS 1
+#define GRPC_TIMER_USE_GENERIC 1
+#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
+#define GRPC_POSIX_WAKEUP_FD 1
+#define GRPC_ARES 0
+#define GPR_NO_AUTODETECT_PLATFORM 1
#elif defined(__APPLE__)
#include <Availability.h>
#include <TargetConditionals.h>
@@ -203,8 +203,8 @@
#define GPR_PLATFORM_STRING "ios"
#define GPR_CPU_IPHONE 1
#define GPR_PTHREAD_TLS 1
-#define GRPC_CFSTREAM 1
-/* the c-ares resolver isn't safe to enable on iOS */
+#define GRPC_CFSTREAM 1
+/* the c-ares resolver isn't safe to enable on iOS */
#define GRPC_ARES 0
#else /* TARGET_OS_IPHONE */
#define GPR_PLATFORM_STRING "osx"
@@ -245,7 +245,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifndef GRPC_CFSTREAM
#define GPR_SUPPORT_CHANNELS_FROM_FD 1
@@ -271,7 +271,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#define GPR_SUPPORT_CHANNELS_FROM_FD 1
#ifdef _LP64
@@ -295,7 +295,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#define GPR_SUPPORT_CHANNELS_FROM_FD 1
#ifdef _LP64
@@ -316,7 +316,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
@@ -339,7 +339,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
@@ -368,52 +368,52 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
+#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
#else /* _LP64 */
#define GPR_ARCH_32 1
#endif /* _LP64 */
-#elif defined(__Fuchsia__)
-#define GPR_FUCHSIA 1
-#define GPR_ARCH_64 1
-#define GPR_PLATFORM_STRING "fuchsia"
-#include <features.h>
-// Specifying musl libc affects wrap_memcpy.c. It causes memmove() to be
-// invoked.
-#define GPR_MUSL_LIBC_COMPAT 1
-#define GPR_CPU_POSIX 1
-#define GPR_GCC_ATOMIC 1
-#define GPR_PTHREAD_TLS 1
-#define GPR_POSIX_LOG 1
-#define GPR_POSIX_SYNC 1
-#define GPR_POSIX_ENV 1
-#define GPR_POSIX_TMPFILE 1
-#define GPR_POSIX_SUBPROCESS 1
-#define GPR_POSIX_SYNC 1
-#define GPR_POSIX_STRING 1
-#define GPR_POSIX_TIME 1
-#define GPR_HAS_PTHREAD_H 1
-#define GPR_GETPID_IN_UNISTD_H 1
+#elif defined(__Fuchsia__)
+#define GPR_FUCHSIA 1
+#define GPR_ARCH_64 1
+#define GPR_PLATFORM_STRING "fuchsia"
+#include <features.h>
+// Specifying musl libc affects wrap_memcpy.c. It causes memmove() to be
+// invoked.
+#define GPR_MUSL_LIBC_COMPAT 1
+#define GPR_CPU_POSIX 1
+#define GPR_GCC_ATOMIC 1
+#define GPR_PTHREAD_TLS 1
+#define GPR_POSIX_LOG 1
+#define GPR_POSIX_SYNC 1
+#define GPR_POSIX_ENV 1
+#define GPR_POSIX_TMPFILE 1
+#define GPR_POSIX_SUBPROCESS 1
+#define GPR_POSIX_SYNC 1
+#define GPR_POSIX_STRING 1
+#define GPR_POSIX_TIME 1
+#define GPR_HAS_PTHREAD_H 1
+#define GPR_GETPID_IN_UNISTD_H 1
#else
#error "Could not auto-detect platform"
#endif
#endif /* GPR_NO_AUTODETECT_PLATFORM */
-#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
-/*
- * For backward compatibility mode, reset _FORTIFY_SOURCE to prevent
- * a library from having non-standard symbols such as __asprintf_chk.
- * This helps non-glibc systems such as alpine using musl to find symbols.
- */
-#if defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0
-#undef _FORTIFY_SOURCE
-#define _FORTIFY_SOURCE 0
-#endif
-#endif
-
+#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
/*
+ * For backward compatibility mode, reset _FORTIFY_SOURCE to prevent
+ * a library from having non-standard symbols such as __asprintf_chk.
+ * This helps non-glibc systems such as alpine using musl to find symbols.
+ */
+#if defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0
+#undef _FORTIFY_SOURCE
+#define _FORTIFY_SOURCE 0
+#endif
+#endif
+
+/*
* There are platforms for which TLS should not be used even though the
* compiler makes it seem like it's supported (Android NDK < r12b for example).
* This is primarily because of linker problems and toolchain misconfiguration:
@@ -470,23 +470,23 @@ typedef unsigned __int64 uint64_t;
#include <stdint.h>
#endif /* _MSC_VER */
-/* Type of cycle clock implementation */
-#ifdef GPR_LINUX
-/* Disable cycle clock by default.
- TODO(soheil): enable when we support fallback for unstable cycle clocks.
-#if defined(__i386__)
-#define GPR_CYCLE_COUNTER_RDTSC_32 1
-#elif defined(__x86_64__) || defined(__amd64__)
-#define GPR_CYCLE_COUNTER_RDTSC_64 1
-#else
-#define GPR_CYCLE_COUNTER_FALLBACK 1
-#endif
-*/
-#define GPR_CYCLE_COUNTER_FALLBACK 1
-#else
-#define GPR_CYCLE_COUNTER_FALLBACK 1
-#endif /* GPR_LINUX */
-
+/* Type of cycle clock implementation */
+#ifdef GPR_LINUX
+/* Disable cycle clock by default.
+ TODO(soheil): enable when we support fallback for unstable cycle clocks.
+#if defined(__i386__)
+#define GPR_CYCLE_COUNTER_RDTSC_32 1
+#elif defined(__x86_64__) || defined(__amd64__)
+#define GPR_CYCLE_COUNTER_RDTSC_64 1
+#else
+#define GPR_CYCLE_COUNTER_FALLBACK 1
+#endif
+*/
+#define GPR_CYCLE_COUNTER_FALLBACK 1
+#else
+#define GPR_CYCLE_COUNTER_FALLBACK 1
+#endif /* GPR_LINUX */
+
/* Cache line alignment */
#ifndef GPR_CACHELINE_SIZE_LOG
#if defined(__i386__) || defined(__x86_64__)
@@ -600,14 +600,14 @@ typedef unsigned __int64 uint64_t;
#endif
#endif /* GPR_HAS_ATTRIBUTE */
-#ifndef GPR_HAS_FEATURE
-#ifdef __has_feature
-#define GPR_HAS_FEATURE(a) __has_feature(a)
-#else
-#define GPR_HAS_FEATURE(a) 0
-#endif
-#endif /* GPR_HAS_FEATURE */
-
+#ifndef GPR_HAS_FEATURE
+#ifdef __has_feature
+#define GPR_HAS_FEATURE(a) __has_feature(a)
+#else
+#define GPR_HAS_FEATURE(a) 0
+#endif
+#endif /* GPR_HAS_FEATURE */
+
#ifndef GPR_ATTRIBUTE_NOINLINE
#if GPR_HAS_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__))
#define GPR_ATTRIBUTE_NOINLINE __attribute__((noinline))
@@ -630,9 +630,9 @@ typedef unsigned __int64 uint64_t;
#endif /* GPR_ATTRIBUTE_WEAK */
#ifndef GPR_ATTRIBUTE_NO_TSAN /* (1) */
-#if GPR_HAS_FEATURE(thread_sanitizer)
+#if GPR_HAS_FEATURE(thread_sanitizer)
#define GPR_ATTRIBUTE_NO_TSAN __attribute__((no_sanitize("thread")))
-#endif /* GPR_HAS_FEATURE */
+#endif /* GPR_HAS_FEATURE */
#ifndef GPR_ATTRIBUTE_NO_TSAN /* (2) */
#define GPR_ATTRIBUTE_NO_TSAN
#endif /* GPR_ATTRIBUTE_NO_TSAN (2) */
@@ -642,30 +642,30 @@ typedef unsigned __int64 uint64_t;
#ifndef GRPC_TSAN_SUPPRESSED
#if defined(__SANITIZE_THREAD__)
#define GRPC_TSAN_ENABLED
-#elif GPR_HAS_FEATURE(thread_sanitizer)
+#elif GPR_HAS_FEATURE(thread_sanitizer)
#define GRPC_TSAN_ENABLED
#endif
#endif
-
-/* GRPC_ASAN_ENABLED will be defined, when compiled with address sanitizer. */
+
+/* GRPC_ASAN_ENABLED will be defined, when compiled with address sanitizer. */
#ifndef GRPC_ASAN_SUPPRESSED
-#if defined(__SANITIZE_ADDRESS__)
-#define GRPC_ASAN_ENABLED
-#elif GPR_HAS_FEATURE(address_sanitizer)
-#define GRPC_ASAN_ENABLED
+#if defined(__SANITIZE_ADDRESS__)
+#define GRPC_ASAN_ENABLED
+#elif GPR_HAS_FEATURE(address_sanitizer)
+#define GRPC_ASAN_ENABLED
#endif
#endif
/* GRPC_ALLOW_EXCEPTIONS should be 0 or 1 if exceptions are allowed or not */
#ifndef GRPC_ALLOW_EXCEPTIONS
#ifdef GPR_WINDOWS
-#if defined(_MSC_VER) && defined(_CPPUNWIND)
-#define GRPC_ALLOW_EXCEPTIONS 1
-#elif defined(__EXCEPTIONS)
+#if defined(_MSC_VER) && defined(_CPPUNWIND)
#define GRPC_ALLOW_EXCEPTIONS 1
-#else
-#define GRPC_ALLOW_EXCEPTIONS 0
-#endif
+#elif defined(__EXCEPTIONS)
+#define GRPC_ALLOW_EXCEPTIONS 1
+#else
+#define GRPC_ALLOW_EXCEPTIONS 0
+#endif
#else /* GPR_WINDOWS */
#ifdef __EXCEPTIONS
#define GRPC_ALLOW_EXCEPTIONS 1
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/slice.h b/contrib/libs/grpc/include/grpc/impl/codegen/slice.h
index 3567b1e88b..8c6d29ef1d 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/slice.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/slice.h
@@ -47,7 +47,7 @@ typedef struct grpc_slice grpc_slice;
#define GRPC_SLICE_INLINED_SIZE \
(sizeof(size_t) + sizeof(uint8_t*) - 1 + GRPC_SLICE_INLINE_EXTRA_SIZE)
-struct grpc_slice_refcount;
+struct grpc_slice_refcount;
/** A grpc_slice s, if initialized, represents the byte range
s.bytes[0..s.length-1].
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/status.h b/contrib/libs/grpc/include/grpc/impl/codegen/status.h
index dec3b8f340..15c8f8271e 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/status.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/status.h
@@ -128,8 +128,8 @@ typedef enum {
/** The service is currently unavailable. This is a most likely a
transient condition and may be corrected by retrying with
- a backoff. Note that it is not always safe to retry non-idempotent
- operations.
+ a backoff. Note that it is not always safe to retry non-idempotent
+ operations.
WARNING: Although data MIGHT not have been transmitted when this
status occurs, there is NOT A GUARANTEE that the server has not seen
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/sync_generic.h b/contrib/libs/grpc/include/grpc/impl/codegen/sync_generic.h
index eabdc513f4..3970bb0fe9 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/sync_generic.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/sync_generic.h
@@ -18,7 +18,7 @@
#ifndef GRPC_IMPL_CODEGEN_SYNC_GENERIC_H
#define GRPC_IMPL_CODEGEN_SYNC_GENERIC_H
-/* Generic type definitions for gpr_sync. */
+/* Generic type definitions for gpr_sync. */
#include <grpc/impl/codegen/port_platform.h>
diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/sync_posix.h b/contrib/libs/grpc/include/grpc/impl/codegen/sync_posix.h
index 2aec3a3f8d..8436855d0b 100644
--- a/contrib/libs/grpc/include/grpc/impl/codegen/sync_posix.h
+++ b/contrib/libs/grpc/include/grpc/impl/codegen/sync_posix.h
@@ -25,26 +25,26 @@
#include <pthread.h>
-#ifdef GRPC_ASAN_ENABLED
-/* The member |leak_checker| is used to check whether there is a memory leak
- * caused by upper layer logic that's missing the |gpr_xx_destroy| call
- * to the object before freeing it.
- * This issue was reported at https://github.com/grpc/grpc/issues/17563
- * and discussed at https://github.com/grpc/grpc/pull/17586
- */
-typedef struct {
- pthread_mutex_t mutex;
- int* leak_checker;
-} gpr_mu;
-
-typedef struct {
- pthread_cond_t cond_var;
- int* leak_checker;
-} gpr_cv;
-#else
+#ifdef GRPC_ASAN_ENABLED
+/* The member |leak_checker| is used to check whether there is a memory leak
+ * caused by upper layer logic that's missing the |gpr_xx_destroy| call
+ * to the object before freeing it.
+ * This issue was reported at https://github.com/grpc/grpc/issues/17563
+ * and discussed at https://github.com/grpc/grpc/pull/17586
+ */
+typedef struct {
+ pthread_mutex_t mutex;
+ int* leak_checker;
+} gpr_mu;
+
+typedef struct {
+ pthread_cond_t cond_var;
+ int* leak_checker;
+} gpr_cv;
+#else
typedef pthread_mutex_t gpr_mu;
typedef pthread_cond_t gpr_cv;
-#endif
+#endif
typedef pthread_once_t gpr_once;
#define GPR_ONCE_INIT PTHREAD_ONCE_INIT
diff --git a/contrib/libs/grpc/include/grpc/slice.h b/contrib/libs/grpc/include/grpc/slice.h
index 51fc62b44d..1c6283dba6 100644
--- a/contrib/libs/grpc/include/grpc/slice.h
+++ b/contrib/libs/grpc/include/grpc/slice.h
@@ -107,7 +107,7 @@ GPRAPI grpc_slice grpc_slice_sub_no_ref(grpc_slice s, size_t begin, size_t end);
/** Splits s into two: modifies s to be s[0:split], and returns a new slice,
sharing a refcount with s, that contains s[split:s.length].
- Requires s initialized, split <= s.length */
+ Requires s initialized, split <= s.length */
GPRAPI grpc_slice grpc_slice_split_tail(grpc_slice* s, size_t split);
typedef enum {
@@ -124,7 +124,7 @@ GPRAPI grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* s, size_t split,
/** Splits s into two: modifies s to be s[split:s.length], and returns a new
slice, sharing a refcount with s, that contains s[0:split].
- Requires s initialized, split <= s.length */
+ Requires s initialized, split <= s.length */
GPRAPI grpc_slice grpc_slice_split_head(grpc_slice* s, size_t split);
GPRAPI grpc_slice grpc_empty_slice(void);
@@ -147,7 +147,7 @@ GPRAPI int grpc_slice_buf_start_eq(grpc_slice a, const void* b, size_t blen);
GPRAPI int grpc_slice_rchr(grpc_slice s, char c);
GPRAPI int grpc_slice_chr(grpc_slice s, char c);
-/** return the index of the first occurrence of \a needle in \a haystack, or -1
+/** return the index of the first occurrence of \a needle in \a haystack, or -1
if it's not found */
GPRAPI int grpc_slice_slice(grpc_slice haystack, grpc_slice needle);
diff --git a/contrib/libs/grpc/include/grpcpp/channel.h b/contrib/libs/grpc/include/grpcpp/channel.h
index 6a31ff7aa9..6b1ca6f8b5 100644
--- a/contrib/libs/grpc/include/grpcpp/channel.h
+++ b/contrib/libs/grpc/include/grpcpp/channel.h
@@ -32,7 +32,7 @@
struct grpc_channel;
-namespace grpc {
+namespace grpc {
namespace testing {
class ChannelTestPeer;
} // namespace testing
diff --git a/contrib/libs/grpc/include/grpcpp/create_channel_posix.h b/contrib/libs/grpc/include/grpcpp/create_channel_posix.h
index c6755b0aa6..23747d34a8 100644
--- a/contrib/libs/grpc/include/grpcpp/create_channel_posix.h
+++ b/contrib/libs/grpc/include/grpcpp/create_channel_posix.h
@@ -55,7 +55,7 @@ namespace experimental {
/// \param args Options for channel creation.
/// \param interceptor_creators Vector of interceptor factory objects.
std::shared_ptr<grpc::Channel>
-CreateCustomInsecureChannelWithInterceptorsFromFd(
+CreateCustomInsecureChannelWithInterceptorsFromFd(
const TString& target, int fd, const grpc::ChannelArguments& args,
std::unique_ptr<std::vector<
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>>
diff --git a/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h b/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h
index 95cb93e321..05e5a78004 100644
--- a/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h
+++ b/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h
@@ -19,15 +19,15 @@
#ifndef GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H
#define GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H
-#include <grpcpp/ext/channelz_service_plugin_impl.h>
+#include <grpcpp/ext/channelz_service_plugin_impl.h>
namespace grpc {
namespace channelz {
namespace experimental {
-static inline void InitChannelzService() {
- ::grpc_impl::channelz::experimental::InitChannelzService();
-}
+static inline void InitChannelzService() {
+ ::grpc_impl::channelz::experimental::InitChannelzService();
+}
} // namespace experimental
} // namespace channelz
diff --git a/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin_impl.h b/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin_impl.h
index 3a5f3c4b99..e0fe7b79ae 100644
--- a/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin_impl.h
+++ b/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin_impl.h
@@ -1,41 +1,41 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
-#define GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpcpp/impl/server_builder_plugin.h>
-#include <grpcpp/impl/server_initializer.h>
-#include <grpcpp/support/config.h>
-
-namespace grpc_impl {
-namespace channelz {
-namespace experimental {
-
-/// Add channelz server plugin to \a ServerBuilder. This function should
-/// be called at static initialization time. This service is experimental
-/// for now. Track progress in https://github.com/grpc/grpc/issues/15988.
-void InitChannelzService();
-
-} // namespace experimental
-} // namespace channelz
-} // namespace grpc_impl
-
-#endif // GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
+/*
+ *
+ * Copyright 2018 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
+#define GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpcpp/impl/server_builder_plugin.h>
+#include <grpcpp/impl/server_initializer.h>
+#include <grpcpp/support/config.h>
+
+namespace grpc_impl {
+namespace channelz {
+namespace experimental {
+
+/// Add channelz server plugin to \a ServerBuilder. This function should
+/// be called at static initialization time. This service is experimental
+/// for now. Track progress in https://github.com/grpc/grpc/issues/15988.
+void InitChannelzService();
+
+} // namespace experimental
+} // namespace channelz
+} // namespace grpc_impl
+
+#endif // GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h
index a812b086a2..48f3eea31d 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h
@@ -24,7 +24,7 @@
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/byte_buffer.h>
#include <grpcpp/impl/codegen/server_callback.h>
-#include <grpcpp/impl/codegen/server_callback_handlers.h>
+#include <grpcpp/impl/codegen/server_callback_handlers.h>
struct grpc_server;
@@ -80,62 +80,62 @@ class AsyncGenericService final {
};
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
-namespace experimental {
+namespace experimental {
#endif
-
-/// \a ServerGenericBidiReactor is the reactor class for bidi streaming RPCs
-/// invoked on a CallbackGenericService. It is just a ServerBidi reactor with
-/// ByteBuffer arguments.
+
+/// \a ServerGenericBidiReactor is the reactor class for bidi streaming RPCs
+/// invoked on a CallbackGenericService. It is just a ServerBidi reactor with
+/// ByteBuffer arguments.
using ServerGenericBidiReactor = ServerBidiReactor<ByteBuffer, ByteBuffer>;
-
+
class GenericCallbackServerContext final : public grpc::CallbackServerContext {
- public:
+ public:
const TString& method() const { return method_; }
const TString& host() const { return host_; }
-
- private:
+
+ private:
friend class ::grpc::Server;
-
+
TString method_;
TString host_;
-};
-
-/// \a CallbackGenericService is the base class for generic services implemented
-/// using the callback API and registered through the ServerBuilder using
-/// RegisterCallbackGenericService.
-class CallbackGenericService {
- public:
- CallbackGenericService() {}
- virtual ~CallbackGenericService() {}
-
- /// The "method handler" for the generic API. This function should be
- /// overridden to provide a ServerGenericBidiReactor that implements the
- /// application-level interface for this RPC. Unimplemented by default.
- virtual ServerGenericBidiReactor* CreateReactor(
- GenericCallbackServerContext* /*ctx*/) {
- class Reactor : public ServerGenericBidiReactor {
- public:
- Reactor() { this->Finish(Status(StatusCode::UNIMPLEMENTED, "")); }
- void OnDone() override { delete this; }
- };
- return new Reactor;
- }
-
- private:
+};
+
+/// \a CallbackGenericService is the base class for generic services implemented
+/// using the callback API and registered through the ServerBuilder using
+/// RegisterCallbackGenericService.
+class CallbackGenericService {
+ public:
+ CallbackGenericService() {}
+ virtual ~CallbackGenericService() {}
+
+ /// The "method handler" for the generic API. This function should be
+ /// overridden to provide a ServerGenericBidiReactor that implements the
+ /// application-level interface for this RPC. Unimplemented by default.
+ virtual ServerGenericBidiReactor* CreateReactor(
+ GenericCallbackServerContext* /*ctx*/) {
+ class Reactor : public ServerGenericBidiReactor {
+ public:
+ Reactor() { this->Finish(Status(StatusCode::UNIMPLEMENTED, "")); }
+ void OnDone() override { delete this; }
+ };
+ return new Reactor;
+ }
+
+ private:
friend class grpc::Server;
-
+
internal::CallbackBidiHandler<ByteBuffer, ByteBuffer>* Handler() {
return new internal::CallbackBidiHandler<ByteBuffer, ByteBuffer>(
[this](::grpc::CallbackServerContext* ctx) {
- return CreateReactor(static_cast<GenericCallbackServerContext*>(ctx));
- });
- }
-
+ return CreateReactor(static_cast<GenericCallbackServerContext*>(ctx));
+ });
+ }
+
grpc::Server* server_{nullptr};
-};
+};
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
-} // namespace experimental
+} // namespace experimental
#endif
} // namespace grpc
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/async_unary_call.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/async_unary_call.h
index 3deeda8c7f..abbd645b06 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/async_unary_call.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/async_unary_call.h
@@ -30,7 +30,7 @@ namespace grpc {
/// An interface relevant for async client side unary RPCs (which send
/// one request message to a server and receive one response message).
-template <class R>
+template <class R>
class ClientAsyncResponseReaderInterface {
public:
virtual ~ClientAsyncResponseReaderInterface() {}
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h
index 6e64ec9981..d8b63e33af 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h
@@ -35,22 +35,22 @@ class ServerInterface;
class ByteBuffer;
class ServerInterface;
-namespace internal {
-template <class RequestType, class ResponseType>
-class CallbackUnaryHandler;
-template <class RequestType, class ResponseType>
-class CallbackServerStreamingHandler;
-template <class ServiceType, class RequestType, class ResponseType>
-class RpcMethodHandler;
-template <class ServiceType, class RequestType, class ResponseType>
-class ServerStreamingHandler;
-template <::grpc::StatusCode code>
-class ErrorMethodHandler;
+namespace internal {
+template <class RequestType, class ResponseType>
+class CallbackUnaryHandler;
+template <class RequestType, class ResponseType>
+class CallbackServerStreamingHandler;
+template <class ServiceType, class RequestType, class ResponseType>
+class RpcMethodHandler;
+template <class ServiceType, class RequestType, class ResponseType>
+class ServerStreamingHandler;
+template <::grpc::StatusCode code>
+class ErrorMethodHandler;
class CallOpSendMessage;
template <class R>
class CallOpRecvMessage;
class CallOpGenericRecvMessage;
-class ExternalConnectionAcceptorImpl;
+class ExternalConnectionAcceptorImpl;
template <class R>
class DeserializeFuncType;
class GrpcByteBufferPeer;
@@ -92,7 +92,7 @@ class ByteBuffer final {
/// \a buf. Wrapper of core function grpc_byte_buffer_copy . This is not
/// a deep copy; it is just a referencing. As a result, its performance is
/// size-independent.
- ByteBuffer(const ByteBuffer& buf) : buffer_(nullptr) { operator=(buf); }
+ ByteBuffer(const ByteBuffer& buf) : buffer_(nullptr) { operator=(buf); }
~ByteBuffer() {
if (buffer_) {
@@ -103,16 +103,16 @@ class ByteBuffer final {
/// Wrapper of core function grpc_byte_buffer_copy . This is not
/// a deep copy; it is just a referencing. As a result, its performance is
/// size-independent.
- ByteBuffer& operator=(const ByteBuffer& buf) {
- if (this != &buf) {
- Clear(); // first remove existing data
- }
- if (buf.buffer_) {
- // then copy
- buffer_ = g_core_codegen_interface->grpc_byte_buffer_copy(buf.buffer_);
- }
- return *this;
- }
+ ByteBuffer& operator=(const ByteBuffer& buf) {
+ if (this != &buf) {
+ Clear(); // first remove existing data
+ }
+ if (buf.buffer_) {
+ // then copy
+ buffer_ = g_core_codegen_interface->grpc_byte_buffer_copy(buf.buffer_);
+ }
+ return *this;
+ }
/// Dump (read) the buffer contents into \a slices.
Status Dump(std::vector<Slice>* slices) const;
@@ -177,7 +177,7 @@ class ByteBuffer final {
friend class ProtoBufferReader;
friend class ProtoBufferWriter;
friend class internal::GrpcByteBufferPeer;
- friend class internal::ExternalConnectionAcceptorImpl;
+ friend class internal::ExternalConnectionAcceptorImpl;
grpc_byte_buffer* buffer_;
@@ -217,7 +217,7 @@ class SerializationTraits<ByteBuffer, void> {
bool* own_buffer) {
*buffer = source;
*own_buffer = true;
- return g_core_codegen_interface->ok();
+ return g_core_codegen_interface->ok();
}
};
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h
index 379333164a..f47b20eab4 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h
@@ -27,8 +27,8 @@
#include <map>
#include <memory>
-#include <grpc/impl/codegen/compression_types.h>
-#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/impl/codegen/compression_types.h>
+#include <grpc/impl/codegen/grpc_types.h>
#include <grpcpp/impl/codegen/byte_buffer.h>
#include <grpcpp/impl/codegen/call.h>
#include <grpcpp/impl/codegen/call_hook.h>
@@ -86,9 +86,9 @@ class WriteOptions {
WriteOptions(const WriteOptions& other)
: flags_(other.flags_), last_message_(other.last_message_) {}
- /// Default assignment operator
- WriteOptions& operator=(const WriteOptions& other) = default;
-
+ /// Default assignment operator
+ WriteOptions& operator=(const WriteOptions& other) = default;
+
/// Clear all flags.
inline void Clear() { flags_ = 0; }
@@ -208,14 +208,14 @@ namespace internal {
template <int Unused>
class CallNoOp {
protected:
- void AddOp(grpc_op* /*ops*/, size_t* /*nops*/) {}
- void FinishOp(bool* /*status*/) {}
+ void AddOp(grpc_op* /*ops*/, size_t* /*nops*/) {}
+ void FinishOp(bool* /*status*/) {}
void SetInterceptionHookPoint(
- InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
+ InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
void SetFinishInterceptionHookPoint(
- InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
- void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
- }
+ InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
+ void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
+ }
};
class CallOpSendInitialMetadata {
@@ -255,7 +255,7 @@ class CallOpSendInitialMetadata {
maybe_compression_level_.level;
}
}
- void FinishOp(bool* /*status*/) {
+ void FinishOp(bool* /*status*/) {
if (!send_ || hijacked_) return;
g_core_codegen_interface->gpr_free(initial_metadata_);
send_ = false;
@@ -270,9 +270,9 @@ class CallOpSendInitialMetadata {
}
void SetFinishInterceptionHookPoint(
- InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
+ InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
- void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
+ void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
@@ -366,7 +366,7 @@ class CallOpSendMessage {
nullptr);
}
- void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
+ void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
@@ -592,7 +592,7 @@ class CallOpGenericRecvMessage {
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr);
- deserialize_.reset();
+ deserialize_.reset();
}
void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
hijacked_ = true;
@@ -633,7 +633,7 @@ class CallOpClientSendClose {
op->flags = 0;
op->reserved = NULL;
}
- void FinishOp(bool* /*status*/) { send_ = false; }
+ void FinishOp(bool* /*status*/) { send_ = false; }
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
@@ -643,9 +643,9 @@ class CallOpClientSendClose {
}
void SetFinishInterceptionHookPoint(
- InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
+ InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
- void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
+ void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
@@ -686,7 +686,7 @@ class CallOpServerSendStatus {
op->reserved = NULL;
}
- void FinishOp(bool* /*status*/) {
+ void FinishOp(bool* /*status*/) {
if (!send_status_available_ || hijacked_) return;
g_core_codegen_interface->gpr_free(trailing_metadata_);
send_status_available_ = false;
@@ -703,9 +703,9 @@ class CallOpServerSendStatus {
}
void SetFinishInterceptionHookPoint(
- InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
+ InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
- void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
+ void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
@@ -740,7 +740,7 @@ class CallOpRecvInitialMetadata {
op->reserved = NULL;
}
- void FinishOp(bool* /*status*/) {
+ void FinishOp(bool* /*status*/) {
if (metadata_map_ == nullptr || hijacked_) return;
}
@@ -794,26 +794,26 @@ class CallOpClientRecvStatus {
op->reserved = NULL;
}
- void FinishOp(bool* /*status*/) {
+ void FinishOp(bool* /*status*/) {
if (recv_status_ == nullptr || hijacked_) return;
- if (static_cast<StatusCode>(status_code_) == StatusCode::OK) {
- *recv_status_ = Status();
- GPR_CODEGEN_DEBUG_ASSERT(debug_error_string_ == nullptr);
- } else {
- *recv_status_ =
- Status(static_cast<StatusCode>(status_code_),
- GRPC_SLICE_IS_EMPTY(error_message_)
+ if (static_cast<StatusCode>(status_code_) == StatusCode::OK) {
+ *recv_status_ = Status();
+ GPR_CODEGEN_DEBUG_ASSERT(debug_error_string_ == nullptr);
+ } else {
+ *recv_status_ =
+ Status(static_cast<StatusCode>(status_code_),
+ GRPC_SLICE_IS_EMPTY(error_message_)
? TString()
: TString(reinterpret_cast<const char*>GRPC_SLICE_START_PTR(error_message_),
reinterpret_cast<const char*>GRPC_SLICE_END_PTR(error_message_)),
- metadata_map_->GetBinaryErrorDetails());
- if (debug_error_string_ != nullptr) {
- client_context_->set_debug_error_string(debug_error_string_);
- g_core_codegen_interface->gpr_free((void*)debug_error_string_);
- }
- }
- // TODO(soheil): Find callers that set debug string even for status OK,
- // and fix them.
+ metadata_map_->GetBinaryErrorDetails());
+ if (debug_error_string_ != nullptr) {
+ client_context_->set_debug_error_string(debug_error_string_);
+ g_core_codegen_interface->gpr_free((void*)debug_error_string_);
+ }
+ }
+ // TODO(soheil): Find callers that set debug string even for status OK,
+ // and fix them.
g_core_codegen_interface->grpc_slice_unref(error_message_);
}
@@ -964,29 +964,29 @@ class CallOpSet : public CallOpSetInterface,
this->Op4::AddOp(ops, &nops);
this->Op5::AddOp(ops, &nops);
this->Op6::AddOp(ops, &nops);
-
- grpc_call_error err = g_core_codegen_interface->grpc_call_start_batch(
- call_.call(), ops, nops, core_cq_tag(), nullptr);
-
- if (err != GRPC_CALL_OK) {
- // A failure here indicates an API misuse; for example, doing a Write
- // while another Write is already pending on the same RPC or invoking
- // WritesDone multiple times
- // gpr_log(GPR_ERROR, "API misuse of type %s observed",
- // g_core_codegen_interface->grpc_call_error_to_string(err));
- GPR_CODEGEN_ASSERT(false);
- }
+
+ grpc_call_error err = g_core_codegen_interface->grpc_call_start_batch(
+ call_.call(), ops, nops, core_cq_tag(), nullptr);
+
+ if (err != GRPC_CALL_OK) {
+ // A failure here indicates an API misuse; for example, doing a Write
+ // while another Write is already pending on the same RPC or invoking
+ // WritesDone multiple times
+ // gpr_log(GPR_ERROR, "API misuse of type %s observed",
+ // g_core_codegen_interface->grpc_call_error_to_string(err));
+ GPR_CODEGEN_ASSERT(false);
+ }
}
// Should be called after interceptors are done running on the finalize result
// path
void ContinueFinalizeResultAfterInterception() override {
done_intercepting_ = true;
- // The following call_start_batch is internally-generated so no need for an
- // explanatory log on failure.
- GPR_CODEGEN_ASSERT(g_core_codegen_interface->grpc_call_start_batch(
- call_.call(), nullptr, 0, core_cq_tag(), nullptr) ==
- GRPC_CALL_OK);
+ // The following call_start_batch is internally-generated so no need for an
+ // explanatory log on failure.
+ GPR_CODEGEN_ASSERT(g_core_codegen_interface->grpc_call_start_batch(
+ call_.call(), nullptr, 0, core_cq_tag(), nullptr) ==
+ GRPC_CALL_OK);
}
private:
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h
index 3c3bfd7e76..6253e48b20 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h
@@ -51,8 +51,8 @@ void CatchingCallback(Func&& func, Args&&... args) {
#endif // GRPC_ALLOW_EXCEPTIONS
}
-template <class Reactor, class Func, class... Args>
-Reactor* CatchingReactorGetter(Func&& func, Args&&... args) {
+template <class Reactor, class Func, class... Args>
+Reactor* CatchingReactorGetter(Func&& func, Args&&... args) {
#if GRPC_ALLOW_EXCEPTIONS
try {
return func(std::forward<Args>(args)...);
@@ -73,8 +73,8 @@ class CallbackWithStatusTag
: public grpc_experimental_completion_queue_functor {
public:
// always allocated against a call arena, no memory free required
- static void operator delete(void* /*ptr*/, std::size_t size) {
- GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithStatusTag));
+ static void operator delete(void* /*ptr*/, std::size_t size) {
+ GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithStatusTag));
}
// This operator should never be called as the memory should be freed as part
@@ -82,17 +82,17 @@ class CallbackWithStatusTag
// delete to the operator new so that some compilers will not complain (see
// https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
// there are no tests catching the compiler warning.
- static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
+ static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
CallbackWithStatusTag(grpc_call* call, std::function<void(Status)> f,
CompletionQueueTag* ops)
: call_(call), func_(std::move(f)), ops_(ops) {
g_core_codegen_interface->grpc_call_ref(call);
functor_run = &CallbackWithStatusTag::StaticRun;
- // A client-side callback should never be run inline since they will always
- // have work to do from the user application. So, set the parent's
- // inlineable field to false
- inlineable = false;
+ // A client-side callback should never be run inline since they will always
+ // have work to do from the user application. So, set the parent's
+ // inlineable field to false
+ inlineable = false;
}
~CallbackWithStatusTag() {}
Status* status_ptr() { return &status_; }
@@ -141,8 +141,8 @@ class CallbackWithSuccessTag
: public grpc_experimental_completion_queue_functor {
public:
// always allocated against a call arena, no memory free required
- static void operator delete(void* /*ptr*/, std::size_t size) {
- GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithSuccessTag));
+ static void operator delete(void* /*ptr*/, std::size_t size) {
+ GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithSuccessTag));
}
// This operator should never be called as the memory should be freed as part
@@ -150,7 +150,7 @@ class CallbackWithSuccessTag
// delete to the operator new so that some compilers will not complain (see
// https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
// there are no tests catching the compiler warning.
- static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
+ static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
CallbackWithSuccessTag() : call_(nullptr) {}
@@ -162,18 +162,18 @@ class CallbackWithSuccessTag
// Set can only be called on a default-constructed or Clear'ed tag.
// It should never be called on a tag that was constructed with arguments
// or on a tag that has been Set before unless the tag has been cleared.
- // can_inline indicates that this particular callback can be executed inline
- // (without needing a thread hop) and is only used for library-provided server
- // callbacks.
+ // can_inline indicates that this particular callback can be executed inline
+ // (without needing a thread hop) and is only used for library-provided server
+ // callbacks.
void Set(grpc_call* call, std::function<void(bool)> f,
- CompletionQueueTag* ops, bool can_inline) {
+ CompletionQueueTag* ops, bool can_inline) {
GPR_CODEGEN_ASSERT(call_ == nullptr);
g_core_codegen_interface->grpc_call_ref(call);
call_ = call;
func_ = std::move(f);
ops_ = ops;
functor_run = &CallbackWithSuccessTag::StaticRun;
- inlineable = can_inline;
+ inlineable = can_inline;
}
void Clear() {
@@ -208,11 +208,11 @@ class CallbackWithSuccessTag
void* ignored = ops_;
// Allow a "false" return value from FinalizeResult to silence the
// callback, just as it silences a CQ tag in the async cases
-#ifndef NDEBUG
+#ifndef NDEBUG
auto* ops = ops_;
-#endif
+#endif
bool do_callback = ops_->FinalizeResult(&ignored, &ok);
- GPR_CODEGEN_DEBUG_ASSERT(ignored == ops);
+ GPR_CODEGEN_DEBUG_ASSERT(ignored == ops);
if (do_callback) {
CatchingCallback(func_, ok);
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h
index ea0752d90e..4ac1270989 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h
@@ -52,24 +52,24 @@ template <class R>
class ClientCallbackReaderFactory;
template <class W>
class ClientCallbackWriterFactory;
-class ClientCallbackUnaryFactory;
-} // namespace internal
-
-class ChannelInterface;
+class ClientCallbackUnaryFactory;
+} // namespace internal
+
+class ChannelInterface;
class ClientContext;
class CompletionQueue;
-
-namespace experimental {
-class DelegatingChannel;
-}
-
-namespace internal {
-class Call;
-class CallOpSetInterface;
-class RpcMethod;
+
+namespace experimental {
+class DelegatingChannel;
+}
+
+namespace internal {
+class Call;
+class CallOpSetInterface;
+class RpcMethod;
class InterceptedChannel;
-template <class InputMessage, class OutputMessage>
-class BlockingUnaryCallImpl;
+template <class InputMessage, class OutputMessage>
+class BlockingUnaryCallImpl;
} // namespace internal
/// Codegen interface for \a grpc::Channel.
@@ -134,7 +134,7 @@ class ChannelInterface {
template <class InputMessage, class OutputMessage>
friend class ::grpc::internal::CallbackUnaryCallImpl;
friend class ::grpc::internal::RpcMethod;
- friend class ::grpc::experimental::DelegatingChannel;
+ friend class ::grpc::experimental::DelegatingChannel;
friend class ::grpc::internal::InterceptedChannel;
virtual internal::Call CreateCall(const internal::RpcMethod& method,
::grpc::ClientContext* context,
@@ -145,7 +145,7 @@ class ChannelInterface {
virtual void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
::grpc::CompletionQueue* cq,
- void* tag) = 0;
+ void* tag) = 0;
virtual bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) = 0;
@@ -156,7 +156,7 @@ class ChannelInterface {
// Returns an empty Call object (rather than being pure) since this is a new
// method and adding a new pure method to an interface would be a breaking
// change (even though this is private and non-API)
- virtual internal::Call CreateCallInternal(
+ virtual internal::Call CreateCallInternal(
const internal::RpcMethod& /*method*/, ::grpc::ClientContext* /*context*/,
::grpc::CompletionQueue* /*cq*/, size_t /*interceptor_pos*/) {
return internal::Call();
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h
index 90c817ceaa..dbb90a5b06 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h
@@ -1194,12 +1194,12 @@ namespace experimental {
template <class Response>
using ClientCallbackReader = ::grpc::ClientCallbackReader<Response>;
-
+
template <class Request>
using ClientCallbackWriter = ::grpc::ClientCallbackWriter<Request>;
template <class Request, class Response>
-using ClientCallbackReaderWriter =
+using ClientCallbackReaderWriter =
::grpc::ClientCallbackReaderWriter<Request, Response>;
template <class Response>
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h
index 78be1f7597..ed995a8ce4 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h
@@ -28,7 +28,7 @@
namespace grpc {
-class Channel;
+class Channel;
class ClientContext;
namespace internal {
@@ -76,7 +76,7 @@ class ClientRpcInfo {
UNKNOWN // UNKNOWN is not API and will be removed later
};
- ~ClientRpcInfo() {}
+ ~ClientRpcInfo() {}
// Delete copy constructor but allow default move constructor
ClientRpcInfo(const ClientRpcInfo&) = delete;
@@ -141,8 +141,8 @@ class ClientRpcInfo {
// No interceptors to register
return;
}
- // NOTE: The following is not a range-based for loop because it will only
- // iterate over a portion of the creators vector.
+ // NOTE: The following is not a range-based for loop because it will only
+ // iterate over a portion of the creators vector.
for (auto it = creators.begin() + interceptor_pos; it != creators.end();
++it) {
auto* interceptor = (*it)->CreateClientInterceptor(this);
@@ -174,16 +174,16 @@ class ClientRpcInfo {
// PLEASE DO NOT USE THIS. ALWAYS PREFER PER CHANNEL INTERCEPTORS OVER A GLOBAL
// INTERCEPTOR. IF USAGE IS ABSOLUTELY NECESSARY, PLEASE READ THE SAFETY NOTES.
// Registers a global client interceptor factory object, which is used for all
-// RPCs made in this process. The application is responsible for maintaining the
-// life of the object while gRPC operations are in progress. The global
-// interceptor factory should only be registered once at the start of the
-// process before any gRPC operations have begun.
+// RPCs made in this process. The application is responsible for maintaining the
+// life of the object while gRPC operations are in progress. The global
+// interceptor factory should only be registered once at the start of the
+// process before any gRPC operations have begun.
void RegisterGlobalClientInterceptorFactory(
ClientInterceptorFactoryInterface* factory);
-// For testing purposes only
-void TestOnlyResetGlobalClientInterceptorFactory();
-
+// For testing purposes only
+void TestOnlyResetGlobalClientInterceptorFactory();
+
} // namespace experimental
} // namespace grpc
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h
index 098bb50ee2..3baba87ab3 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h
@@ -34,7 +34,7 @@ class RpcMethod;
template <class InputMessage, class OutputMessage>
Status BlockingUnaryCall(ChannelInterface* channel, const RpcMethod& method,
grpc::ClientContext* context,
- const InputMessage& request, OutputMessage* result) {
+ const InputMessage& request, OutputMessage* result) {
return BlockingUnaryCallImpl<InputMessage, OutputMessage>(
channel, method, context, request, result)
.status();
@@ -45,11 +45,11 @@ class BlockingUnaryCallImpl {
public:
BlockingUnaryCallImpl(ChannelInterface* channel, const RpcMethod& method,
grpc::ClientContext* context,
- const InputMessage& request, OutputMessage* result) {
+ const InputMessage& request, OutputMessage* result) {
::grpc::CompletionQueue cq(grpc_completion_queue_attributes{
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
nullptr}); // Pluckable completion queue
- ::grpc::internal::Call call(channel->CreateCall(method, context, &cq));
+ ::grpc::internal::Call call(channel->CreateCall(method, context, &cq));
CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage,
CallOpRecvInitialMetadata, CallOpRecvMessage<OutputMessage>,
CallOpClientSendClose, CallOpClientRecvStatus>
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h
index c4012fb00c..e0d87704f7 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h
@@ -25,11 +25,11 @@
#ifdef GRPC_USE_PROTO_LITE
#include <google/protobuf/message_lite.h>
#define GRPC_CUSTOM_MESSAGE ::google::protobuf::MessageLite
-#define GRPC_CUSTOM_MESSAGELITE ::google::protobuf::MessageLite
+#define GRPC_CUSTOM_MESSAGELITE ::google::protobuf::MessageLite
#else
#include <google/protobuf/message.h>
#define GRPC_CUSTOM_MESSAGE ::google::protobuf::Message
-#define GRPC_CUSTOM_MESSAGELITE ::google::protobuf::MessageLite
+#define GRPC_CUSTOM_MESSAGELITE ::google::protobuf::MessageLite
#endif
#endif
@@ -73,7 +73,7 @@ namespace grpc {
namespace protobuf {
typedef GRPC_CUSTOM_MESSAGE Message;
-typedef GRPC_CUSTOM_MESSAGELITE MessageLite;
+typedef GRPC_CUSTOM_MESSAGELITE MessageLite;
typedef GRPC_CUSTOM_DESCRIPTOR Descriptor;
typedef GRPC_CUSTOM_DESCRIPTORPOOL DescriptorPool;
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h
index 50c8da4ffe..f7ac555f76 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h
@@ -73,8 +73,8 @@ class CoreCodegen final : public CoreCodegenInterface {
void* reserved) override;
void grpc_call_ref(grpc_call* call) override;
void grpc_call_unref(grpc_call* call) override;
- void* grpc_call_arena_alloc(grpc_call* call, size_t length) override;
- const char* grpc_call_error_to_string(grpc_call_error error) override;
+ void* grpc_call_arena_alloc(grpc_call* call, size_t length) override;
+ const char* grpc_call_error_to_string(grpc_call_error error) override;
grpc_byte_buffer* grpc_byte_buffer_copy(grpc_byte_buffer* bb) override;
void grpc_byte_buffer_destroy(grpc_byte_buffer* bb) override;
@@ -86,8 +86,8 @@ class CoreCodegen final : public CoreCodegenInterface {
grpc_byte_buffer_reader* reader) override;
int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader,
grpc_slice* slice) override;
- int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
- grpc_slice** slice) override;
+ int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
+ grpc_slice** slice) override;
grpc_byte_buffer* grpc_raw_byte_buffer_create(grpc_slice* slice,
size_t nslices) override;
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h
index c08cf6c683..637ef69874 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h
@@ -19,7 +19,7 @@
#ifndef GRPCPP_IMPL_CODEGEN_CORE_CODEGEN_INTERFACE_H
#define GRPCPP_IMPL_CODEGEN_CORE_CODEGEN_INTERFACE_H
-#include <grpc/impl/codegen/byte_buffer.h>
+#include <grpc/impl/codegen/byte_buffer.h>
#include <grpc/impl/codegen/byte_buffer_reader.h>
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/impl/codegen/sync.h>
@@ -93,8 +93,8 @@ class CoreCodegenInterface {
grpc_byte_buffer_reader* reader) = 0;
virtual int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader,
grpc_slice* slice) = 0;
- virtual int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
- grpc_slice** slice) = 0;
+ virtual int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
+ grpc_slice** slice) = 0;
virtual grpc_byte_buffer* grpc_raw_byte_buffer_create(grpc_slice* slice,
size_t nslices) = 0;
@@ -114,7 +114,7 @@ class CoreCodegenInterface {
virtual void grpc_call_ref(grpc_call* call) = 0;
virtual void grpc_call_unref(grpc_call* call) = 0;
virtual void* grpc_call_arena_alloc(grpc_call* call, size_t length) = 0;
- virtual const char* grpc_call_error_to_string(grpc_call_error error) = 0;
+ virtual const char* grpc_call_error_to_string(grpc_call_error error) = 0;
virtual grpc_slice grpc_empty_slice() = 0;
virtual grpc_slice grpc_slice_malloc(size_t length) = 0;
virtual void grpc_slice_unref(grpc_slice slice) = 0;
@@ -145,7 +145,7 @@ extern CoreCodegenInterface* g_core_codegen_interface;
/// Codegen specific version of \a GPR_ASSERT.
#define GPR_CODEGEN_ASSERT(x) \
do { \
- if (GPR_UNLIKELY(!(x))) { \
+ if (GPR_UNLIKELY(!(x))) { \
grpc::g_core_codegen_interface->assert_fail(#x, __FILE__, __LINE__); \
} \
} while (0)
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/delegating_channel.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/delegating_channel.h
index 1a3bbd3349..52e10e36e3 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/delegating_channel.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/delegating_channel.h
@@ -1,87 +1,87 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
-#define GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
-
-namespace grpc {
-namespace experimental {
-
-class DelegatingChannel : public ::grpc::ChannelInterface {
- public:
- virtual ~DelegatingChannel() {}
-
- DelegatingChannel(std::shared_ptr<::grpc::ChannelInterface> delegate_channel)
- : delegate_channel_(delegate_channel) {}
-
- grpc_connectivity_state GetState(bool try_to_connect) override {
- return delegate_channel()->GetState(try_to_connect);
- }
-
- std::shared_ptr<::grpc::ChannelInterface> delegate_channel() {
- return delegate_channel_;
- }
-
- private:
- internal::Call CreateCall(const internal::RpcMethod& method,
- ClientContext* context,
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
+#define GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
+
+namespace grpc {
+namespace experimental {
+
+class DelegatingChannel : public ::grpc::ChannelInterface {
+ public:
+ virtual ~DelegatingChannel() {}
+
+ DelegatingChannel(std::shared_ptr<::grpc::ChannelInterface> delegate_channel)
+ : delegate_channel_(delegate_channel) {}
+
+ grpc_connectivity_state GetState(bool try_to_connect) override {
+ return delegate_channel()->GetState(try_to_connect);
+ }
+
+ std::shared_ptr<::grpc::ChannelInterface> delegate_channel() {
+ return delegate_channel_;
+ }
+
+ private:
+ internal::Call CreateCall(const internal::RpcMethod& method,
+ ClientContext* context,
::grpc::CompletionQueue* cq) final {
- return delegate_channel()->CreateCall(method, context, cq);
- }
-
- void PerformOpsOnCall(internal::CallOpSetInterface* ops,
- internal::Call* call) final {
- delegate_channel()->PerformOpsOnCall(ops, call);
- }
-
- void* RegisterMethod(const char* method) final {
- return delegate_channel()->RegisterMethod(method);
- }
-
- void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
- gpr_timespec deadline,
+ return delegate_channel()->CreateCall(method, context, cq);
+ }
+
+ void PerformOpsOnCall(internal::CallOpSetInterface* ops,
+ internal::Call* call) final {
+ delegate_channel()->PerformOpsOnCall(ops, call);
+ }
+
+ void* RegisterMethod(const char* method) final {
+ return delegate_channel()->RegisterMethod(method);
+ }
+
+ void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
+ gpr_timespec deadline,
::grpc::CompletionQueue* cq,
- void* tag) override {
- delegate_channel()->NotifyOnStateChangeImpl(last_observed, deadline, cq,
- tag);
- }
-
- bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
- gpr_timespec deadline) override {
- return delegate_channel()->WaitForStateChangeImpl(last_observed, deadline);
- }
-
- internal::Call CreateCallInternal(const internal::RpcMethod& method,
- ClientContext* context,
+ void* tag) override {
+ delegate_channel()->NotifyOnStateChangeImpl(last_observed, deadline, cq,
+ tag);
+ }
+
+ bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
+ gpr_timespec deadline) override {
+ return delegate_channel()->WaitForStateChangeImpl(last_observed, deadline);
+ }
+
+ internal::Call CreateCallInternal(const internal::RpcMethod& method,
+ ClientContext* context,
::grpc::CompletionQueue* cq,
- size_t interceptor_pos) final {
- return delegate_channel()->CreateCallInternal(method, context, cq,
- interceptor_pos);
- }
-
+ size_t interceptor_pos) final {
+ return delegate_channel()->CreateCallInternal(method, context, cq,
+ interceptor_pos);
+ }
+
::grpc::CompletionQueue* CallbackCQ() final {
- return delegate_channel()->CallbackCQ();
- }
-
- std::shared_ptr<::grpc::ChannelInterface> delegate_channel_;
-};
-
-} // namespace experimental
-} // namespace grpc
-
-#endif // GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
+ return delegate_channel()->CallbackCQ();
+ }
+
+ std::shared_ptr<::grpc::ChannelInterface> delegate_channel_;
+};
+
+} // namespace experimental
+} // namespace grpc
+
+#endif // GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h
index c729970ca8..edb5c2c87f 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h
@@ -22,8 +22,8 @@
#include <grpcpp/impl/codegen/channel_interface.h>
namespace grpc {
-class CompletionQueue;
-
+class CompletionQueue;
+
namespace internal {
class InterceptorBatchMethodsImpl;
@@ -59,7 +59,7 @@ class InterceptedChannel : public ChannelInterface {
}
void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
- gpr_timespec deadline,
+ gpr_timespec deadline,
::grpc::CompletionQueue* cq,
void* tag) override {
return channel_->NotifyOnStateChangeImpl(last_observed, deadline, cq, tag);
@@ -70,8 +70,8 @@ class InterceptedChannel : public ChannelInterface {
}
::grpc::CompletionQueue* CallbackCQ() override {
- return channel_->CallbackCQ();
- }
+ return channel_->CallbackCQ();
+ }
ChannelInterface* channel_;
size_t interceptor_pos_;
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h
index d0afa03a17..83223dad94 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h
@@ -92,7 +92,7 @@ enum class InterceptionHookPoints {
/// 5. Set some fields of an RPC at each interception point, when possible
class InterceptorBatchMethods {
public:
- virtual ~InterceptorBatchMethods() {}
+ virtual ~InterceptorBatchMethods() {}
/// Determine whether the current batch has an interception hook point
/// of type \a type
virtual bool QueryInterceptionHookPoint(InterceptionHookPoints type) = 0;
@@ -175,22 +175,22 @@ class InterceptorBatchMethods {
/// Returns a pointer to the modifiable received message. Note that the
/// message is already deserialized but the type is not set; the interceptor
/// should static_cast to the appropriate type before using it. This is valid
- /// for PRE_RECV_MESSAGE and POST_RECV_MESSAGE interceptions; nullptr for not
- /// valid
+ /// for PRE_RECV_MESSAGE and POST_RECV_MESSAGE interceptions; nullptr for not
+ /// valid
virtual void* GetRecvMessage() = 0;
/// Returns a modifiable multimap of the received initial metadata.
- /// Valid for PRE_RECV_INITIAL_METADATA and POST_RECV_INITIAL_METADATA
- /// interceptions; nullptr if not valid
+ /// Valid for PRE_RECV_INITIAL_METADATA and POST_RECV_INITIAL_METADATA
+ /// interceptions; nullptr if not valid
virtual std::multimap<grpc::string_ref, grpc::string_ref>*
GetRecvInitialMetadata() = 0;
- /// Returns a modifiable view of the received status on PRE_RECV_STATUS and
- /// POST_RECV_STATUS interceptions; nullptr if not valid.
+ /// Returns a modifiable view of the received status on PRE_RECV_STATUS and
+ /// POST_RECV_STATUS interceptions; nullptr if not valid.
virtual Status* GetRecvStatus() = 0;
/// Returns a modifiable multimap of the received trailing metadata on
- /// PRE_RECV_STATUS and POST_RECV_STATUS interceptions; nullptr if not valid
+ /// PRE_RECV_STATUS and POST_RECV_STATUS interceptions; nullptr if not valid
virtual std::multimap<grpc::string_ref, grpc::string_ref>*
GetRecvTrailingMetadata() = 0;
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h
index 714351f543..49d63aee1b 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h
@@ -468,7 +468,7 @@ class CancelInterceptorBatchMethods
return nullptr;
}
- void ModifySendMessage(const void* /*message*/) override {
+ void ModifySendMessage(const void* /*message*/) override {
GPR_CODEGEN_ASSERT(
false &&
"It is illegal to call ModifySendMessage on a method which "
@@ -489,7 +489,7 @@ class CancelInterceptorBatchMethods
return Status();
}
- void ModifySendStatus(const Status& /*status*/) override {
+ void ModifySendStatus(const Status& /*status*/) override {
GPR_CODEGEN_ASSERT(false &&
"It is illegal to call ModifySendStatus on a method "
"which has a Cancel notification");
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/message_allocator.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/message_allocator.h
index 4048ea1197..8e4513c223 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/message_allocator.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/message_allocator.h
@@ -1,76 +1,76 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
-#define GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
-
-namespace grpc {
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
+#define GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
+
+namespace grpc {
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
-namespace experimental {
+namespace experimental {
#endif
-
-// NOTE: This is an API for advanced users who need custom allocators.
-// Per rpc struct for the allocator. This is the interface to return to user.
-class RpcAllocatorState {
- public:
- virtual ~RpcAllocatorState() = default;
- // Optionally deallocate request early to reduce the size of working set.
- // A custom MessageAllocator needs to be registered to make use of this.
- // This is not abstract because implementing it is optional.
- virtual void FreeRequest() {}
-};
-
-// This is the interface returned by the allocator.
-// grpc library will call the methods to get request/response pointers and to
-// release the object when it is done.
-template <typename RequestT, typename ResponseT>
-class MessageHolder : public RpcAllocatorState {
- public:
- // Release this object. For example, if the custom allocator's
- // AllocateMessasge creates an instance of a subclass with new, the Release()
- // should do a "delete this;".
- virtual void Release() = 0;
- RequestT* request() { return request_; }
- ResponseT* response() { return response_; }
-
- protected:
- void set_request(RequestT* request) { request_ = request; }
- void set_response(ResponseT* response) { response_ = response; }
-
- private:
- // NOTE: subclasses should set these pointers.
- RequestT* request_;
- ResponseT* response_;
-};
-
-// A custom allocator can be set via the generated code to a callback unary
-// method, such as SetMessageAllocatorFor_Echo(custom_allocator). The allocator
-// needs to be alive for the lifetime of the server.
-// Implementations need to be thread-safe.
-template <typename RequestT, typename ResponseT>
-class MessageAllocator {
- public:
- virtual ~MessageAllocator() = default;
- virtual MessageHolder<RequestT, ResponseT>* AllocateMessages() = 0;
-};
-
+
+// NOTE: This is an API for advanced users who need custom allocators.
+// Per rpc struct for the allocator. This is the interface to return to user.
+class RpcAllocatorState {
+ public:
+ virtual ~RpcAllocatorState() = default;
+ // Optionally deallocate request early to reduce the size of working set.
+ // A custom MessageAllocator needs to be registered to make use of this.
+ // This is not abstract because implementing it is optional.
+ virtual void FreeRequest() {}
+};
+
+// This is the interface returned by the allocator.
+// grpc library will call the methods to get request/response pointers and to
+// release the object when it is done.
+template <typename RequestT, typename ResponseT>
+class MessageHolder : public RpcAllocatorState {
+ public:
+ // Release this object. For example, if the custom allocator's
+ // AllocateMessasge creates an instance of a subclass with new, the Release()
+ // should do a "delete this;".
+ virtual void Release() = 0;
+ RequestT* request() { return request_; }
+ ResponseT* response() { return response_; }
+
+ protected:
+ void set_request(RequestT* request) { request_ = request; }
+ void set_response(ResponseT* response) { response_ = response; }
+
+ private:
+ // NOTE: subclasses should set these pointers.
+ RequestT* request_;
+ ResponseT* response_;
+};
+
+// A custom allocator can be set via the generated code to a callback unary
+// method, such as SetMessageAllocatorFor_Echo(custom_allocator). The allocator
+// needs to be alive for the lifetime of the server.
+// Implementations need to be thread-safe.
+template <typename RequestT, typename ResponseT>
+class MessageAllocator {
+ public:
+ virtual ~MessageAllocator() = default;
+ virtual MessageHolder<RequestT, ResponseT>* AllocateMessages() = 0;
+};
+
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
-} // namespace experimental
+} // namespace experimental
#endif
// TODO(vjpai): Remove namespace experimental when de-experimentalized fully.
@@ -88,6 +88,6 @@ using MessageAllocator = ::grpc::MessageAllocator<RequestT, ResponseT>;
} // namespace experimental
#endif
-} // namespace grpc
-
-#endif // GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
+} // namespace grpc
+
+#endif // GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/method_handler.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/method_handler.h
index 0033936b04..c4fe9c3aee 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/method_handler.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/method_handler.h
@@ -1,33 +1,33 @@
-/*
- *
+/*
+ *
* Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
-#define GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
-
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
+#define GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
+
#include <grpcpp/impl/codegen/byte_buffer.h>
#include <grpcpp/impl/codegen/core_codegen_interface.h>
#include <grpcpp/impl/codegen/rpc_service_method.h>
#include <grpcpp/impl/codegen/sync_stream.h>
-
-namespace grpc {
-
-namespace internal {
-
+
+namespace grpc {
+
+namespace internal {
+
// Invoke the method handler, fill in the status, and
// return whether or not we finished safely (without an exception).
// Note that exception handling is 0-cost in most compiler/library
@@ -48,9 +48,9 @@ template <class Callable>
return handler();
#endif // GRPC_ALLOW_EXCEPTIONS
}
-
+
/// A wrapper class of an application provided rpc method handler.
-template <class ServiceType, class RequestType, class ResponseType>
+template <class ServiceType, class RequestType, class ResponseType>
class RpcMethodHandler : public ::grpc::internal::MethodHandler {
public:
RpcMethodHandler(
@@ -59,7 +59,7 @@ class RpcMethodHandler : public ::grpc::internal::MethodHandler {
func,
ServiceType* service)
: func_(func), service_(service) {}
-
+
void RunHandler(const HandlerParameter& param) final {
ResponseType rsp;
::grpc::Status status = param.status;
@@ -117,7 +117,7 @@ class RpcMethodHandler : public ::grpc::internal::MethodHandler {
};
/// A wrapper class of an application provided client streaming handler.
-template <class ServiceType, class RequestType, class ResponseType>
+template <class ServiceType, class RequestType, class ResponseType>
class ClientStreamingHandler : public ::grpc::internal::MethodHandler {
public:
ClientStreamingHandler(
@@ -126,7 +126,7 @@ class ClientStreamingHandler : public ::grpc::internal::MethodHandler {
func,
ServiceType* service)
: func_(func), service_(service) {}
-
+
void RunHandler(const HandlerParameter& param) final {
ServerReader<RequestType> reader(
param.call, static_cast<::grpc::ServerContext*>(param.server_context));
@@ -165,7 +165,7 @@ class ClientStreamingHandler : public ::grpc::internal::MethodHandler {
};
/// A wrapper class of an application provided server streaming handler.
-template <class ServiceType, class RequestType, class ResponseType>
+template <class ServiceType, class RequestType, class ResponseType>
class ServerStreamingHandler : public ::grpc::internal::MethodHandler {
public:
ServerStreamingHandler(std::function<::grpc::Status(
@@ -174,7 +174,7 @@ class ServerStreamingHandler : public ::grpc::internal::MethodHandler {
func,
ServiceType* service)
: func_(func), service_(service) {}
-
+
void RunHandler(const HandlerParameter& param) final {
::grpc::Status status = param.status;
if (status.ok()) {
@@ -238,13 +238,13 @@ class ServerStreamingHandler : public ::grpc::internal::MethodHandler {
/// Since this is used by more than 1 class, the service is not passed in.
/// Instead, it is expected to be an implicitly-captured argument of func
/// (through bind or something along those lines)
-template <class Streamer, bool WriteNeeded>
+template <class Streamer, bool WriteNeeded>
class TemplatedBidiStreamingHandler : public ::grpc::internal::MethodHandler {
public:
TemplatedBidiStreamingHandler(
std::function<::grpc::Status(::grpc::ServerContext*, Streamer*)> func)
: func_(func), write_needed_(WriteNeeded) {}
-
+
void RunHandler(const HandlerParameter& param) final {
Streamer stream(param.call,
static_cast<::grpc::ServerContext*>(param.server_context));
@@ -302,7 +302,7 @@ class BidiStreamingHandler
}) {}
};
-template <class RequestType, class ResponseType>
+template <class RequestType, class ResponseType>
class StreamedUnaryHandler
: public TemplatedBidiStreamingHandler<
ServerUnaryStreamer<RequestType, ResponseType>, true> {
@@ -316,8 +316,8 @@ class StreamedUnaryHandler
ServerUnaryStreamer<RequestType, ResponseType>, true>(
std::move(func)) {}
};
-
-template <class RequestType, class ResponseType>
+
+template <class RequestType, class ResponseType>
class SplitServerStreamingHandler
: public TemplatedBidiStreamingHandler<
ServerSplitStreamer<RequestType, ResponseType>, false> {
@@ -331,7 +331,7 @@ class SplitServerStreamingHandler
ServerSplitStreamer<RequestType, ResponseType>, false>(
std::move(func)) {}
};
-
+
/// General method handler class for errors that prevent real method use
/// e.g., handle unknown method by returning UNIMPLEMENTED error.
template <::grpc::StatusCode code>
@@ -350,7 +350,7 @@ class ErrorMethodHandler : public ::grpc::internal::MethodHandler {
}
ops->ServerSendStatus(&context->trailing_metadata_, status);
}
-
+
void RunHandler(const HandlerParameter& param) final {
::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
::grpc::internal::CallOpServerSendStatus>
@@ -359,7 +359,7 @@ class ErrorMethodHandler : public ::grpc::internal::MethodHandler {
param.call->PerformOps(&ops);
param.call->cq()->Pluck(&ops);
}
-
+
void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req,
::grpc::Status* /*status*/, void** /*handler_data*/) final {
// We have to destroy any request payload
@@ -369,13 +369,13 @@ class ErrorMethodHandler : public ::grpc::internal::MethodHandler {
return nullptr;
}
};
-
+
typedef ErrorMethodHandler<::grpc::StatusCode::UNIMPLEMENTED>
UnknownMethodHandler;
typedef ErrorMethodHandler<::grpc::StatusCode::RESOURCE_EXHAUSTED>
ResourceExhaustedHandler;
-} // namespace internal
-} // namespace grpc
-
-#endif // GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
+} // namespace internal
+} // namespace grpc
+
+#endif // GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_reader.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_reader.h
index 487471290d..c43ebd0aa5 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_reader.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_reader.h
@@ -73,7 +73,7 @@ class ProtoBufferReader : public ::grpc::protobuf::io::ZeroCopyInputStream {
}
/// If we have backed up previously, we need to return the backed-up slice
if (backup_count_ > 0) {
- *data = GRPC_SLICE_START_PTR(*slice_) + GRPC_SLICE_LENGTH(*slice_) -
+ *data = GRPC_SLICE_START_PTR(*slice_) + GRPC_SLICE_LENGTH(*slice_) -
backup_count_;
GPR_CODEGEN_ASSERT(backup_count_ <= INT_MAX);
*size = (int)backup_count_;
@@ -81,14 +81,14 @@ class ProtoBufferReader : public ::grpc::protobuf::io::ZeroCopyInputStream {
return true;
}
/// Otherwise get the next slice from the byte buffer reader
- if (!g_core_codegen_interface->grpc_byte_buffer_reader_peek(&reader_,
+ if (!g_core_codegen_interface->grpc_byte_buffer_reader_peek(&reader_,
&slice_)) {
return false;
}
- *data = GRPC_SLICE_START_PTR(*slice_);
+ *data = GRPC_SLICE_START_PTR(*slice_);
// On win x64, int is only 32bit
- GPR_CODEGEN_ASSERT(GRPC_SLICE_LENGTH(*slice_) <= INT_MAX);
- byte_count_ += * size = (int)GRPC_SLICE_LENGTH(*slice_);
+ GPR_CODEGEN_ASSERT(GRPC_SLICE_LENGTH(*slice_) <= INT_MAX);
+ byte_count_ += * size = (int)GRPC_SLICE_LENGTH(*slice_);
return true;
}
@@ -99,7 +99,7 @@ class ProtoBufferReader : public ::grpc::protobuf::io::ZeroCopyInputStream {
/// bytes that have already been returned by the last call of Next.
/// So do the backup and have that ready for a later Next.
void BackUp(int count) override {
- GPR_CODEGEN_ASSERT(count <= static_cast<int>(GRPC_SLICE_LENGTH(*slice_)));
+ GPR_CODEGEN_ASSERT(count <= static_cast<int>(GRPC_SLICE_LENGTH(*slice_)));
backup_count_ = count;
}
@@ -132,15 +132,15 @@ class ProtoBufferReader : public ::grpc::protobuf::io::ZeroCopyInputStream {
int64_t backup_count() { return backup_count_; }
void set_backup_count(int64_t backup_count) { backup_count_ = backup_count; }
grpc_byte_buffer_reader* reader() { return &reader_; }
- grpc_slice* slice() { return slice_; }
- grpc_slice** mutable_slice_ptr() { return &slice_; }
+ grpc_slice* slice() { return slice_; }
+ grpc_slice** mutable_slice_ptr() { return &slice_; }
private:
int64_t byte_count_; ///< total bytes read since object creation
int64_t backup_count_; ///< how far backed up in the stream we are
grpc_byte_buffer_reader reader_; ///< internal object to read \a grpc_slice
///< from the \a grpc_byte_buffer
- grpc_slice* slice_; ///< current slice passed back to the caller
+ grpc_slice* slice_; ///< current slice passed back to the caller
Status status_; ///< status of the entire object
};
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_writer.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_writer.h
index 0af4616e50..a8cc302f2d 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_writer.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_buffer_writer.h
@@ -86,7 +86,7 @@ class ProtoBufferWriter : public ::grpc::protobuf::io::ZeroCopyOutputStream {
// or our maximum allocation size
// 3. Provide the slice start and size available
// 4. Add the slice being returned to the slice buffer
- size_t remain = static_cast<size_t>(total_size_ - byte_count_);
+ size_t remain = static_cast<size_t>(total_size_ - byte_count_);
if (have_backup_) {
/// If we have a backup slice, we should use it first
slice_ = backup_slice_;
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_utils.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_utils.h
index 2e102135a3..b1ac427453 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_utils.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/proto_utils.h
@@ -42,7 +42,7 @@ extern CoreCodegenInterface* g_core_codegen_interface;
// ProtoBufferWriter must be a subclass of ::protobuf::io::ZeroCopyOutputStream.
template <class ProtoBufferWriter, class T>
-Status GenericSerialize(const grpc::protobuf::MessageLite& msg, ByteBuffer* bb,
+Status GenericSerialize(const grpc::protobuf::MessageLite& msg, ByteBuffer* bb,
bool* own_buffer) {
static_assert(std::is_base_of<protobuf::io::ZeroCopyOutputStream,
ProtoBufferWriter>::value,
@@ -68,8 +68,8 @@ Status GenericSerialize(const grpc::protobuf::MessageLite& msg, ByteBuffer* bb,
// BufferReader must be a subclass of ::protobuf::io::ZeroCopyInputStream.
template <class ProtoBufferReader, class T>
-Status GenericDeserialize(ByteBuffer* buffer,
- grpc::protobuf::MessageLite* msg) {
+Status GenericDeserialize(ByteBuffer* buffer,
+ grpc::protobuf::MessageLite* msg) {
static_assert(std::is_base_of<protobuf::io::ZeroCopyInputStream,
ProtoBufferReader>::value,
"ProtoBufferReader must be a subclass of "
@@ -83,7 +83,7 @@ Status GenericDeserialize(ByteBuffer* buffer,
if (!reader.status().ok()) {
return reader.status();
}
- if (!msg->ParseFromZeroCopyStream(&reader)) {
+ if (!msg->ParseFromZeroCopyStream(&reader)) {
result = Status(StatusCode::INTERNAL, msg->InitializationErrorString());
}
}
@@ -98,17 +98,17 @@ Status GenericDeserialize(ByteBuffer* buffer,
// objects and grpc_byte_buffers. More information about SerializationTraits can
// be found in include/grpcpp/impl/codegen/serialization_traits.h.
template <class T>
-class SerializationTraits<
- T, typename std::enable_if<
- std::is_base_of<grpc::protobuf::MessageLite, T>::value>::type> {
+class SerializationTraits<
+ T, typename std::enable_if<
+ std::is_base_of<grpc::protobuf::MessageLite, T>::value>::type> {
public:
- static Status Serialize(const grpc::protobuf::MessageLite& msg,
- ByteBuffer* bb, bool* own_buffer) {
+ static Status Serialize(const grpc::protobuf::MessageLite& msg,
+ ByteBuffer* bb, bool* own_buffer) {
return GenericSerialize<ProtoBufferWriter, T>(msg, bb, own_buffer);
}
- static Status Deserialize(ByteBuffer* buffer,
- grpc::protobuf::MessageLite* msg) {
+ static Status Deserialize(ByteBuffer* buffer,
+ grpc::protobuf::MessageLite* msg) {
return GenericDeserialize<ProtoBufferReader, T>(buffer, msg);
}
};
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h
index 4fcc211243..f86def7fa7 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h
@@ -32,7 +32,7 @@
#include <grpcpp/impl/codegen/status.h>
namespace grpc {
-class ServerContextBase;
+class ServerContextBase;
namespace internal {
/// Base class for running an RPC handler.
class MethodHandler {
@@ -45,26 +45,26 @@ class MethodHandler {
/// \param context : the ServerContext structure for this server call
/// \param req : the request payload, if appropriate for this RPC
/// \param req_status : the request status after any interceptors have run
- /// \param handler_data: internal data for the handler.
- /// \param requester : used only by the callback API. It is a function
+ /// \param handler_data: internal data for the handler.
+ /// \param requester : used only by the callback API. It is a function
/// called by the RPC Controller to request another RPC (and also
/// to set up the state required to make that request possible)
HandlerParameter(Call* c, ::grpc::ServerContextBase* context, void* req,
Status req_status, void* handler_data,
- std::function<void()> requester)
+ std::function<void()> requester)
: call(c),
server_context(context),
request(req),
status(req_status),
- internal_data(handler_data),
+ internal_data(handler_data),
call_requester(std::move(requester)) {}
~HandlerParameter() {}
- Call* const call;
+ Call* const call;
::grpc::ServerContextBase* const server_context;
- void* const request;
- const Status status;
- void* const internal_data;
- const std::function<void()> call_requester;
+ void* const request;
+ const Status status;
+ void* const internal_data;
+ const std::function<void()> call_requester;
};
virtual void RunHandler(const HandlerParameter& param) = 0;
@@ -73,8 +73,8 @@ class MethodHandler {
a HandlerParameter and passed to RunHandler. It is illegal to access the
pointer after calling RunHandler. Ownership of the deserialized request is
retained by the handler. Returns nullptr if deserialization failed. */
- virtual void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req,
- Status* /*status*/, void** /*handler_data*/) {
+ virtual void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req,
+ Status* /*status*/, void** /*handler_data*/) {
GPR_CODEGEN_ASSERT(req == nullptr);
return nullptr;
}
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/security/auth_context.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/security/auth_context.h
index 220b78f2eb..ad137001ed 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/security/auth_context.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/security/auth_context.h
@@ -32,7 +32,7 @@ struct grpc_auth_property_iterator;
namespace grpc {
class SecureAuthContext;
-typedef std::pair<string_ref, string_ref> AuthProperty;
+typedef std::pair<string_ref, string_ref> AuthProperty;
class AuthPropertyIterator
: public std::iterator<std::input_iterator_tag, const AuthProperty> {
@@ -86,7 +86,7 @@ class AuthContext {
/// Mutation functions: should only be used by an AuthMetadataProcessor.
virtual void AddProperty(const TString& key, const string_ref& value) = 0;
- virtual bool SetPeerIdentityPropertyName(const string& name) = 0;
+ virtual bool SetPeerIdentityPropertyName(const string& name) = 0;
};
} // namespace grpc
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback_handlers.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback_handlers.h
index 8120fcaf85..9aa12fcc81 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback_handlers.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback_handlers.h
@@ -1,209 +1,209 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
-#define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
-
-#include <grpcpp/impl/codegen/message_allocator.h>
-#include <grpcpp/impl/codegen/rpc_service_method.h>
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
+#define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
+
+#include <grpcpp/impl/codegen/message_allocator.h>
+#include <grpcpp/impl/codegen/rpc_service_method.h>
#include <grpcpp/impl/codegen/server_callback.h>
#include <grpcpp/impl/codegen/server_context.h>
-#include <grpcpp/impl/codegen/status.h>
-
+#include <grpcpp/impl/codegen/status.h>
+
namespace grpc {
-namespace internal {
-
-template <class RequestType, class ResponseType>
-class CallbackUnaryHandler : public ::grpc::internal::MethodHandler {
- public:
- explicit CallbackUnaryHandler(
+namespace internal {
+
+template <class RequestType, class ResponseType>
+class CallbackUnaryHandler : public ::grpc::internal::MethodHandler {
+ public:
+ explicit CallbackUnaryHandler(
std::function<ServerUnaryReactor*(::grpc::CallbackServerContext*,
- const RequestType*, ResponseType*)>
- get_reactor)
- : get_reactor_(std::move(get_reactor)) {}
-
- void SetMessageAllocator(
- ::grpc::experimental::MessageAllocator<RequestType, ResponseType>*
- allocator) {
- allocator_ = allocator;
- }
-
- void RunHandler(const HandlerParameter& param) final {
- // Arena allocate a controller structure (that includes request/response)
- ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
- auto* allocator_state = static_cast<
- ::grpc::experimental::MessageHolder<RequestType, ResponseType>*>(
- param.internal_data);
-
- auto* call = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(ServerCallbackUnaryImpl)))
- ServerCallbackUnaryImpl(
+ const RequestType*, ResponseType*)>
+ get_reactor)
+ : get_reactor_(std::move(get_reactor)) {}
+
+ void SetMessageAllocator(
+ ::grpc::experimental::MessageAllocator<RequestType, ResponseType>*
+ allocator) {
+ allocator_ = allocator;
+ }
+
+ void RunHandler(const HandlerParameter& param) final {
+ // Arena allocate a controller structure (that includes request/response)
+ ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
+ auto* allocator_state = static_cast<
+ ::grpc::experimental::MessageHolder<RequestType, ResponseType>*>(
+ param.internal_data);
+
+ auto* call = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(ServerCallbackUnaryImpl)))
+ ServerCallbackUnaryImpl(
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- param.call, allocator_state, std::move(param.call_requester));
- param.server_context->BeginCompletionOp(
- param.call, [call](bool) { call->MaybeDone(); }, call);
-
- ServerUnaryReactor* reactor = nullptr;
- if (param.status.ok()) {
- reactor = ::grpc::internal::CatchingReactorGetter<ServerUnaryReactor>(
- get_reactor_,
+ param.call, allocator_state, std::move(param.call_requester));
+ param.server_context->BeginCompletionOp(
+ param.call, [call](bool) { call->MaybeDone(); }, call);
+
+ ServerUnaryReactor* reactor = nullptr;
+ if (param.status.ok()) {
+ reactor = ::grpc::internal::CatchingReactorGetter<ServerUnaryReactor>(
+ get_reactor_,
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- call->request(), call->response());
- }
-
- if (reactor == nullptr) {
- // if deserialization or reactor creator failed, we need to fail the call
- reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(UnimplementedUnaryReactor)))
- UnimplementedUnaryReactor(
- ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
- }
-
- /// Invoke SetupReactor as the last part of the handler
- call->SetupReactor(reactor);
- }
-
- void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
- ::grpc::Status* status, void** handler_data) final {
- ::grpc::ByteBuffer buf;
- buf.set_buffer(req);
- RequestType* request = nullptr;
- ::grpc::experimental::MessageHolder<RequestType, ResponseType>*
- allocator_state = nullptr;
- if (allocator_ != nullptr) {
- allocator_state = allocator_->AllocateMessages();
- } else {
- allocator_state =
- new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- call, sizeof(DefaultMessageHolder<RequestType, ResponseType>)))
- DefaultMessageHolder<RequestType, ResponseType>();
- }
- *handler_data = allocator_state;
- request = allocator_state->request();
- *status =
- ::grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
- buf.Release();
- if (status->ok()) {
- return request;
- }
- // Clean up on deserialization failure.
- allocator_state->Release();
- return nullptr;
- }
-
- private:
+ call->request(), call->response());
+ }
+
+ if (reactor == nullptr) {
+ // if deserialization or reactor creator failed, we need to fail the call
+ reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(UnimplementedUnaryReactor)))
+ UnimplementedUnaryReactor(
+ ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
+ }
+
+ /// Invoke SetupReactor as the last part of the handler
+ call->SetupReactor(reactor);
+ }
+
+ void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
+ ::grpc::Status* status, void** handler_data) final {
+ ::grpc::ByteBuffer buf;
+ buf.set_buffer(req);
+ RequestType* request = nullptr;
+ ::grpc::experimental::MessageHolder<RequestType, ResponseType>*
+ allocator_state = nullptr;
+ if (allocator_ != nullptr) {
+ allocator_state = allocator_->AllocateMessages();
+ } else {
+ allocator_state =
+ new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ call, sizeof(DefaultMessageHolder<RequestType, ResponseType>)))
+ DefaultMessageHolder<RequestType, ResponseType>();
+ }
+ *handler_data = allocator_state;
+ request = allocator_state->request();
+ *status =
+ ::grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
+ buf.Release();
+ if (status->ok()) {
+ return request;
+ }
+ // Clean up on deserialization failure.
+ allocator_state->Release();
+ return nullptr;
+ }
+
+ private:
std::function<ServerUnaryReactor*(::grpc::CallbackServerContext*,
- const RequestType*, ResponseType*)>
- get_reactor_;
- ::grpc::experimental::MessageAllocator<RequestType, ResponseType>*
- allocator_ = nullptr;
-
- class ServerCallbackUnaryImpl : public ServerCallbackUnary {
- public:
- void Finish(::grpc::Status s) override {
+ const RequestType*, ResponseType*)>
+ get_reactor_;
+ ::grpc::experimental::MessageAllocator<RequestType, ResponseType>*
+ allocator_ = nullptr;
+
+ class ServerCallbackUnaryImpl : public ServerCallbackUnary {
+ public:
+ void Finish(::grpc::Status s) override {
// A callback that only contains a call to MaybeDone can be run as an
// inline callback regardless of whether or not OnDone is inlineable
// because if the actual OnDone callback needs to be scheduled, MaybeDone
// is responsible for dispatching to an executor thread if needed. Thus,
// when setting up the finish_tag_, we can set its own callback to
// inlineable.
- finish_tag_.Set(
+ finish_tag_.Set(
call_.call(),
[this](bool) {
this->MaybeDone(
reactor_.load(std::memory_order_relaxed)->InternalInlineable());
},
&finish_ops_, /*can_inline=*/true);
- finish_ops_.set_core_cq_tag(&finish_tag_);
-
- if (!ctx_->sent_initial_metadata_) {
- finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- finish_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- }
- // The response is dropped if the status is not OK.
- if (s.ok()) {
- finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
- finish_ops_.SendMessagePtr(response()));
- } else {
- finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
- }
- finish_ops_.set_core_cq_tag(&finish_tag_);
- call_.PerformOps(&finish_ops_);
- }
-
- void SendInitialMetadata() override {
- GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
- this->Ref();
+ finish_ops_.set_core_cq_tag(&finish_tag_);
+
+ if (!ctx_->sent_initial_metadata_) {
+ finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ finish_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ }
+ // The response is dropped if the status is not OK.
+ if (s.ok()) {
+ finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
+ finish_ops_.SendMessagePtr(response()));
+ } else {
+ finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
+ }
+ finish_ops_.set_core_cq_tag(&finish_tag_);
+ call_.PerformOps(&finish_ops_);
+ }
+
+ void SendInitialMetadata() override {
+ GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
+ this->Ref();
// The callback for this function should not be marked inline because it
// is directly invoking a user-controlled reaction
// (OnSendInitialMetadataDone). Thus it must be dispatched to an executor
// thread. However, any OnDone needed after that can be inlined because it
// is already running on an executor thread.
- meta_tag_.Set(call_.call(),
- [this](bool ok) {
+ meta_tag_.Set(call_.call(),
+ [this](bool ok) {
ServerUnaryReactor* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
- },
+ },
&meta_ops_, /*can_inline=*/false);
- meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- meta_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- meta_ops_.set_core_cq_tag(&meta_tag_);
- call_.PerformOps(&meta_ops_);
- }
-
- private:
- friend class CallbackUnaryHandler<RequestType, ResponseType>;
-
- ServerCallbackUnaryImpl(
+ meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ meta_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ meta_ops_.set_core_cq_tag(&meta_tag_);
+ call_.PerformOps(&meta_ops_);
+ }
+
+ private:
+ friend class CallbackUnaryHandler<RequestType, ResponseType>;
+
+ ServerCallbackUnaryImpl(
::grpc::CallbackServerContext* ctx, ::grpc::internal::Call* call,
- ::grpc::experimental::MessageHolder<RequestType, ResponseType>*
- allocator_state,
- std::function<void()> call_requester)
- : ctx_(ctx),
- call_(*call),
- allocator_state_(allocator_state),
- call_requester_(std::move(call_requester)) {
- ctx_->set_message_allocator_state(allocator_state);
- }
-
- /// SetupReactor binds the reactor (which also releases any queued
- /// operations), maybe calls OnCancel if possible/needed, and maybe marks
- /// the completion of the RPC. This should be the last component of the
- /// handler.
- void SetupReactor(ServerUnaryReactor* reactor) {
- reactor_.store(reactor, std::memory_order_relaxed);
- this->BindReactor(reactor);
- this->MaybeCallOnCancel(reactor);
+ ::grpc::experimental::MessageHolder<RequestType, ResponseType>*
+ allocator_state,
+ std::function<void()> call_requester)
+ : ctx_(ctx),
+ call_(*call),
+ allocator_state_(allocator_state),
+ call_requester_(std::move(call_requester)) {
+ ctx_->set_message_allocator_state(allocator_state);
+ }
+
+ /// SetupReactor binds the reactor (which also releases any queued
+ /// operations), maybe calls OnCancel if possible/needed, and maybe marks
+ /// the completion of the RPC. This should be the last component of the
+ /// handler.
+ void SetupReactor(ServerUnaryReactor* reactor) {
+ reactor_.store(reactor, std::memory_order_relaxed);
+ this->BindReactor(reactor);
+ this->MaybeCallOnCancel(reactor);
this->MaybeDone(reactor->InternalInlineable());
- }
-
- const RequestType* request() { return allocator_state_->request(); }
- ResponseType* response() { return allocator_state_->response(); }
-
+ }
+
+ const RequestType* request() { return allocator_state_->request(); }
+ ResponseType* response() { return allocator_state_->response(); }
+
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
@@ -212,96 +212,96 @@ class CallbackUnaryHandler : public ::grpc::internal::MethodHandler {
this->~ServerCallbackUnaryImpl(); // explicitly call destructor
::grpc::g_core_codegen_interface->grpc_call_unref(call);
call_requester();
- }
-
- ServerReactor* reactor() override {
- return reactor_.load(std::memory_order_relaxed);
- }
-
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
- meta_ops_;
- ::grpc::internal::CallbackWithSuccessTag meta_tag_;
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
- ::grpc::internal::CallOpSendMessage,
- ::grpc::internal::CallOpServerSendStatus>
- finish_ops_;
- ::grpc::internal::CallbackWithSuccessTag finish_tag_;
-
+ }
+
+ ServerReactor* reactor() override {
+ return reactor_.load(std::memory_order_relaxed);
+ }
+
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
+ meta_ops_;
+ ::grpc::internal::CallbackWithSuccessTag meta_tag_;
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
+ ::grpc::internal::CallOpSendMessage,
+ ::grpc::internal::CallOpServerSendStatus>
+ finish_ops_;
+ ::grpc::internal::CallbackWithSuccessTag finish_tag_;
+
::grpc::CallbackServerContext* const ctx_;
- ::grpc::internal::Call call_;
- ::grpc::experimental::MessageHolder<RequestType, ResponseType>* const
- allocator_state_;
- std::function<void()> call_requester_;
- // reactor_ can always be loaded/stored with relaxed memory ordering because
- // its value is only set once, independently of other data in the object,
- // and the loads that use it will always actually come provably later even
- // though they are from different threads since they are triggered by
- // actions initiated only by the setting up of the reactor_ variable. In
- // a sense, it's a delayed "const": it gets its value from the SetupReactor
- // method (not the constructor, so it's not a true const), but it doesn't
- // change after that and it only gets used by actions caused, directly or
- // indirectly, by that setup. This comment also applies to the reactor_
- // variables of the other streaming objects in this file.
- std::atomic<ServerUnaryReactor*> reactor_;
- // callbacks_outstanding_ follows a refcount pattern
- std::atomic<intptr_t> callbacks_outstanding_{
- 3}; // reserve for start, Finish, and CompletionOp
- };
-};
-
-template <class RequestType, class ResponseType>
-class CallbackClientStreamingHandler : public ::grpc::internal::MethodHandler {
- public:
- explicit CallbackClientStreamingHandler(
- std::function<ServerReadReactor<RequestType>*(
+ ::grpc::internal::Call call_;
+ ::grpc::experimental::MessageHolder<RequestType, ResponseType>* const
+ allocator_state_;
+ std::function<void()> call_requester_;
+ // reactor_ can always be loaded/stored with relaxed memory ordering because
+ // its value is only set once, independently of other data in the object,
+ // and the loads that use it will always actually come provably later even
+ // though they are from different threads since they are triggered by
+ // actions initiated only by the setting up of the reactor_ variable. In
+ // a sense, it's a delayed "const": it gets its value from the SetupReactor
+ // method (not the constructor, so it's not a true const), but it doesn't
+ // change after that and it only gets used by actions caused, directly or
+ // indirectly, by that setup. This comment also applies to the reactor_
+ // variables of the other streaming objects in this file.
+ std::atomic<ServerUnaryReactor*> reactor_;
+ // callbacks_outstanding_ follows a refcount pattern
+ std::atomic<intptr_t> callbacks_outstanding_{
+ 3}; // reserve for start, Finish, and CompletionOp
+ };
+};
+
+template <class RequestType, class ResponseType>
+class CallbackClientStreamingHandler : public ::grpc::internal::MethodHandler {
+ public:
+ explicit CallbackClientStreamingHandler(
+ std::function<ServerReadReactor<RequestType>*(
::grpc::CallbackServerContext*, ResponseType*)>
- get_reactor)
- : get_reactor_(std::move(get_reactor)) {}
- void RunHandler(const HandlerParameter& param) final {
- // Arena allocate a reader structure (that includes response)
- ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
-
- auto* reader = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(ServerCallbackReaderImpl)))
- ServerCallbackReaderImpl(
+ get_reactor)
+ : get_reactor_(std::move(get_reactor)) {}
+ void RunHandler(const HandlerParameter& param) final {
+ // Arena allocate a reader structure (that includes response)
+ ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
+
+ auto* reader = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(ServerCallbackReaderImpl)))
+ ServerCallbackReaderImpl(
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- param.call, std::move(param.call_requester));
+ param.call, std::move(param.call_requester));
// Inlineable OnDone can be false in the CompletionOp callback because there
// is no read reactor that has an inlineable OnDone; this only applies to
// the DefaultReactor (which is unary).
- param.server_context->BeginCompletionOp(
+ param.server_context->BeginCompletionOp(
param.call,
[reader](bool) { reader->MaybeDone(/*inlineable_ondone=*/false); },
reader);
-
- ServerReadReactor<RequestType>* reactor = nullptr;
- if (param.status.ok()) {
- reactor = ::grpc::internal::CatchingReactorGetter<
- ServerReadReactor<RequestType>>(
- get_reactor_,
+
+ ServerReadReactor<RequestType>* reactor = nullptr;
+ if (param.status.ok()) {
+ reactor = ::grpc::internal::CatchingReactorGetter<
+ ServerReadReactor<RequestType>>(
+ get_reactor_,
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- reader->response());
- }
-
- if (reactor == nullptr) {
- // if deserialization or reactor creator failed, we need to fail the call
- reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(UnimplementedReadReactor<RequestType>)))
- UnimplementedReadReactor<RequestType>(
- ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
- }
-
- reader->SetupReactor(reactor);
- }
-
- private:
+ reader->response());
+ }
+
+ if (reactor == nullptr) {
+ // if deserialization or reactor creator failed, we need to fail the call
+ reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(UnimplementedReadReactor<RequestType>)))
+ UnimplementedReadReactor<RequestType>(
+ ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
+ }
+
+ reader->SetupReactor(reactor);
+ }
+
+ private:
std::function<ServerReadReactor<RequestType>*(::grpc::CallbackServerContext*,
ResponseType*)>
- get_reactor_;
-
- class ServerCallbackReaderImpl : public ServerCallbackReader<RequestType> {
- public:
- void Finish(::grpc::Status s) override {
+ get_reactor_;
+
+ class ServerCallbackReaderImpl : public ServerCallbackReader<RequestType> {
+ public:
+ void Finish(::grpc::Status s) override {
// A finish tag with only MaybeDone can have its callback inlined
// regardless even if OnDone is not inlineable because this callback just
// checks a ref and then decides whether or not to dispatch OnDone.
@@ -313,87 +313,87 @@ class CallbackClientStreamingHandler : public ::grpc::internal::MethodHandler {
this->MaybeDone(/*inlineable_ondone=*/false);
},
&finish_ops_, /*can_inline=*/true);
- if (!ctx_->sent_initial_metadata_) {
- finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- finish_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- }
- // The response is dropped if the status is not OK.
- if (s.ok()) {
- finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
- finish_ops_.SendMessagePtr(&resp_));
- } else {
- finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
- }
- finish_ops_.set_core_cq_tag(&finish_tag_);
- call_.PerformOps(&finish_ops_);
- }
-
- void SendInitialMetadata() override {
- GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
- this->Ref();
+ if (!ctx_->sent_initial_metadata_) {
+ finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ finish_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ }
+ // The response is dropped if the status is not OK.
+ if (s.ok()) {
+ finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
+ finish_ops_.SendMessagePtr(&resp_));
+ } else {
+ finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
+ }
+ finish_ops_.set_core_cq_tag(&finish_tag_);
+ call_.PerformOps(&finish_ops_);
+ }
+
+ void SendInitialMetadata() override {
+ GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
+ this->Ref();
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
- meta_tag_.Set(call_.call(),
- [this](bool ok) {
+ meta_tag_.Set(call_.call(),
+ [this](bool ok) {
ServerReadReactor<RequestType>* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
- },
+ },
&meta_ops_, /*can_inline=*/false);
- meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- meta_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- meta_ops_.set_core_cq_tag(&meta_tag_);
- call_.PerformOps(&meta_ops_);
- }
-
- void Read(RequestType* req) override {
- this->Ref();
- read_ops_.RecvMessage(req);
- call_.PerformOps(&read_ops_);
- }
-
- private:
- friend class CallbackClientStreamingHandler<RequestType, ResponseType>;
-
+ meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ meta_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ meta_ops_.set_core_cq_tag(&meta_tag_);
+ call_.PerformOps(&meta_ops_);
+ }
+
+ void Read(RequestType* req) override {
+ this->Ref();
+ read_ops_.RecvMessage(req);
+ call_.PerformOps(&read_ops_);
+ }
+
+ private:
+ friend class CallbackClientStreamingHandler<RequestType, ResponseType>;
+
ServerCallbackReaderImpl(::grpc::CallbackServerContext* ctx,
- ::grpc::internal::Call* call,
- std::function<void()> call_requester)
- : ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
-
- void SetupReactor(ServerReadReactor<RequestType>* reactor) {
- reactor_.store(reactor, std::memory_order_relaxed);
+ ::grpc::internal::Call* call,
+ std::function<void()> call_requester)
+ : ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
+
+ void SetupReactor(ServerReadReactor<RequestType>* reactor) {
+ reactor_.store(reactor, std::memory_order_relaxed);
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
- read_tag_.Set(call_.call(),
+ read_tag_.Set(call_.call(),
[this, reactor](bool ok) {
reactor->OnReadDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
- },
+ },
&read_ops_, /*can_inline=*/false);
- read_ops_.set_core_cq_tag(&read_tag_);
- this->BindReactor(reactor);
- this->MaybeCallOnCancel(reactor);
+ read_ops_.set_core_cq_tag(&read_tag_);
+ this->BindReactor(reactor);
+ this->MaybeCallOnCancel(reactor);
// Inlineable OnDone can be false here because there is no read
// reactor that has an inlineable OnDone; this only applies to the
// DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
- }
-
- ~ServerCallbackReaderImpl() {}
-
- ResponseType* response() { return &resp_; }
-
+ }
+
+ ~ServerCallbackReaderImpl() {}
+
+ ResponseType* response() { return &resp_; }
+
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
@@ -401,107 +401,107 @@ class CallbackClientStreamingHandler : public ::grpc::internal::MethodHandler {
this->~ServerCallbackReaderImpl(); // explicitly call destructor
::grpc::g_core_codegen_interface->grpc_call_unref(call);
call_requester();
- }
-
- ServerReactor* reactor() override {
- return reactor_.load(std::memory_order_relaxed);
- }
-
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
- meta_ops_;
- ::grpc::internal::CallbackWithSuccessTag meta_tag_;
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
- ::grpc::internal::CallOpSendMessage,
- ::grpc::internal::CallOpServerSendStatus>
- finish_ops_;
- ::grpc::internal::CallbackWithSuccessTag finish_tag_;
- ::grpc::internal::CallOpSet<
- ::grpc::internal::CallOpRecvMessage<RequestType>>
- read_ops_;
- ::grpc::internal::CallbackWithSuccessTag read_tag_;
-
+ }
+
+ ServerReactor* reactor() override {
+ return reactor_.load(std::memory_order_relaxed);
+ }
+
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
+ meta_ops_;
+ ::grpc::internal::CallbackWithSuccessTag meta_tag_;
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
+ ::grpc::internal::CallOpSendMessage,
+ ::grpc::internal::CallOpServerSendStatus>
+ finish_ops_;
+ ::grpc::internal::CallbackWithSuccessTag finish_tag_;
+ ::grpc::internal::CallOpSet<
+ ::grpc::internal::CallOpRecvMessage<RequestType>>
+ read_ops_;
+ ::grpc::internal::CallbackWithSuccessTag read_tag_;
+
::grpc::CallbackServerContext* const ctx_;
- ::grpc::internal::Call call_;
- ResponseType resp_;
- std::function<void()> call_requester_;
- // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
- std::atomic<ServerReadReactor<RequestType>*> reactor_;
- // callbacks_outstanding_ follows a refcount pattern
- std::atomic<intptr_t> callbacks_outstanding_{
- 3}; // reserve for OnStarted, Finish, and CompletionOp
- };
-};
-
-template <class RequestType, class ResponseType>
-class CallbackServerStreamingHandler : public ::grpc::internal::MethodHandler {
- public:
- explicit CallbackServerStreamingHandler(
- std::function<ServerWriteReactor<ResponseType>*(
+ ::grpc::internal::Call call_;
+ ResponseType resp_;
+ std::function<void()> call_requester_;
+ // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
+ std::atomic<ServerReadReactor<RequestType>*> reactor_;
+ // callbacks_outstanding_ follows a refcount pattern
+ std::atomic<intptr_t> callbacks_outstanding_{
+ 3}; // reserve for OnStarted, Finish, and CompletionOp
+ };
+};
+
+template <class RequestType, class ResponseType>
+class CallbackServerStreamingHandler : public ::grpc::internal::MethodHandler {
+ public:
+ explicit CallbackServerStreamingHandler(
+ std::function<ServerWriteReactor<ResponseType>*(
::grpc::CallbackServerContext*, const RequestType*)>
- get_reactor)
- : get_reactor_(std::move(get_reactor)) {}
- void RunHandler(const HandlerParameter& param) final {
- // Arena allocate a writer structure
- ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
-
- auto* writer = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(ServerCallbackWriterImpl)))
- ServerCallbackWriterImpl(
+ get_reactor)
+ : get_reactor_(std::move(get_reactor)) {}
+ void RunHandler(const HandlerParameter& param) final {
+ // Arena allocate a writer structure
+ ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
+
+ auto* writer = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(ServerCallbackWriterImpl)))
+ ServerCallbackWriterImpl(
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- param.call, static_cast<RequestType*>(param.request),
- std::move(param.call_requester));
+ param.call, static_cast<RequestType*>(param.request),
+ std::move(param.call_requester));
// Inlineable OnDone can be false in the CompletionOp callback because there
// is no write reactor that has an inlineable OnDone; this only applies to
// the DefaultReactor (which is unary).
- param.server_context->BeginCompletionOp(
+ param.server_context->BeginCompletionOp(
param.call,
[writer](bool) { writer->MaybeDone(/*inlineable_ondone=*/false); },
writer);
-
- ServerWriteReactor<ResponseType>* reactor = nullptr;
- if (param.status.ok()) {
- reactor = ::grpc::internal::CatchingReactorGetter<
- ServerWriteReactor<ResponseType>>(
- get_reactor_,
+
+ ServerWriteReactor<ResponseType>* reactor = nullptr;
+ if (param.status.ok()) {
+ reactor = ::grpc::internal::CatchingReactorGetter<
+ ServerWriteReactor<ResponseType>>(
+ get_reactor_,
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- writer->request());
- }
- if (reactor == nullptr) {
- // if deserialization or reactor creator failed, we need to fail the call
- reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(UnimplementedWriteReactor<ResponseType>)))
- UnimplementedWriteReactor<ResponseType>(
- ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
- }
-
- writer->SetupReactor(reactor);
- }
-
- void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
- ::grpc::Status* status, void** /*handler_data*/) final {
- ::grpc::ByteBuffer buf;
- buf.set_buffer(req);
- auto* request =
- new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- call, sizeof(RequestType))) RequestType();
- *status =
- ::grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
- buf.Release();
- if (status->ok()) {
- return request;
- }
- request->~RequestType();
- return nullptr;
- }
-
- private:
- std::function<ServerWriteReactor<ResponseType>*(
+ writer->request());
+ }
+ if (reactor == nullptr) {
+ // if deserialization or reactor creator failed, we need to fail the call
+ reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(UnimplementedWriteReactor<ResponseType>)))
+ UnimplementedWriteReactor<ResponseType>(
+ ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
+ }
+
+ writer->SetupReactor(reactor);
+ }
+
+ void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
+ ::grpc::Status* status, void** /*handler_data*/) final {
+ ::grpc::ByteBuffer buf;
+ buf.set_buffer(req);
+ auto* request =
+ new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ call, sizeof(RequestType))) RequestType();
+ *status =
+ ::grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
+ buf.Release();
+ if (status->ok()) {
+ return request;
+ }
+ request->~RequestType();
+ return nullptr;
+ }
+
+ private:
+ std::function<ServerWriteReactor<ResponseType>*(
::grpc::CallbackServerContext*, const RequestType*)>
- get_reactor_;
-
- class ServerCallbackWriterImpl : public ServerCallbackWriter<ResponseType> {
- public:
- void Finish(::grpc::Status s) override {
+ get_reactor_;
+
+ class ServerCallbackWriterImpl : public ServerCallbackWriter<ResponseType> {
+ public:
+ void Finish(::grpc::Status s) override {
// A finish tag with only MaybeDone can have its callback inlined
// regardless even if OnDone is not inlineable because this callback just
// checks a ref and then decides whether or not to dispatch OnDone.
@@ -513,85 +513,85 @@ class CallbackServerStreamingHandler : public ::grpc::internal::MethodHandler {
this->MaybeDone(/*inlineable_ondone=*/false);
},
&finish_ops_, /*can_inline=*/true);
- finish_ops_.set_core_cq_tag(&finish_tag_);
-
- if (!ctx_->sent_initial_metadata_) {
- finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- finish_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- }
- finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
- call_.PerformOps(&finish_ops_);
- }
-
- void SendInitialMetadata() override {
- GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
- this->Ref();
+ finish_ops_.set_core_cq_tag(&finish_tag_);
+
+ if (!ctx_->sent_initial_metadata_) {
+ finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ finish_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ }
+ finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
+ call_.PerformOps(&finish_ops_);
+ }
+
+ void SendInitialMetadata() override {
+ GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
+ this->Ref();
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
- meta_tag_.Set(call_.call(),
- [this](bool ok) {
+ meta_tag_.Set(call_.call(),
+ [this](bool ok) {
ServerWriteReactor<ResponseType>* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
- },
+ },
&meta_ops_, /*can_inline=*/false);
- meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- meta_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- meta_ops_.set_core_cq_tag(&meta_tag_);
- call_.PerformOps(&meta_ops_);
- }
-
- void Write(const ResponseType* resp,
- ::grpc::WriteOptions options) override {
- this->Ref();
- if (options.is_last_message()) {
- options.set_buffer_hint();
- }
- if (!ctx_->sent_initial_metadata_) {
- write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- write_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- }
- // TODO(vjpai): don't assert
- GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
- call_.PerformOps(&write_ops_);
- }
-
- void WriteAndFinish(const ResponseType* resp, ::grpc::WriteOptions options,
- ::grpc::Status s) override {
- // This combines the write into the finish callback
+ meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ meta_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ meta_ops_.set_core_cq_tag(&meta_tag_);
+ call_.PerformOps(&meta_ops_);
+ }
+
+ void Write(const ResponseType* resp,
+ ::grpc::WriteOptions options) override {
+ this->Ref();
+ if (options.is_last_message()) {
+ options.set_buffer_hint();
+ }
+ if (!ctx_->sent_initial_metadata_) {
+ write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ write_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ }
+ // TODO(vjpai): don't assert
+ GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
+ call_.PerformOps(&write_ops_);
+ }
+
+ void WriteAndFinish(const ResponseType* resp, ::grpc::WriteOptions options,
+ ::grpc::Status s) override {
+ // This combines the write into the finish callback
// TODO(vjpai): don't assert
GPR_CODEGEN_ASSERT(finish_ops_.SendMessagePtr(resp, options).ok());
- Finish(std::move(s));
- }
-
- private:
- friend class CallbackServerStreamingHandler<RequestType, ResponseType>;
-
+ Finish(std::move(s));
+ }
+
+ private:
+ friend class CallbackServerStreamingHandler<RequestType, ResponseType>;
+
ServerCallbackWriterImpl(::grpc::CallbackServerContext* ctx,
- ::grpc::internal::Call* call,
- const RequestType* req,
- std::function<void()> call_requester)
- : ctx_(ctx),
- call_(*call),
- req_(req),
- call_requester_(std::move(call_requester)) {}
-
- void SetupReactor(ServerWriteReactor<ResponseType>* reactor) {
- reactor_.store(reactor, std::memory_order_relaxed);
+ ::grpc::internal::Call* call,
+ const RequestType* req,
+ std::function<void()> call_requester)
+ : ctx_(ctx),
+ call_(*call),
+ req_(req),
+ call_requester_(std::move(call_requester)) {}
+
+ void SetupReactor(ServerWriteReactor<ResponseType>* reactor) {
+ reactor_.store(reactor, std::memory_order_relaxed);
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
@@ -601,18 +601,18 @@ class CallbackServerStreamingHandler : public ::grpc::internal::MethodHandler {
this->MaybeDone(/*inlineable_ondone=*/true);
},
&write_ops_, /*can_inline=*/false);
- write_ops_.set_core_cq_tag(&write_tag_);
- this->BindReactor(reactor);
- this->MaybeCallOnCancel(reactor);
+ write_ops_.set_core_cq_tag(&write_tag_);
+ this->BindReactor(reactor);
+ this->MaybeCallOnCancel(reactor);
// Inlineable OnDone can be false here because there is no write
// reactor that has an inlineable OnDone; this only applies to the
// DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
- }
- ~ServerCallbackWriterImpl() { req_->~RequestType(); }
-
- const RequestType* request() { return req_; }
-
+ }
+ ~ServerCallbackWriterImpl() { req_->~RequestType(); }
+
+ const RequestType* request() { return req_; }
+
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
@@ -620,90 +620,90 @@ class CallbackServerStreamingHandler : public ::grpc::internal::MethodHandler {
this->~ServerCallbackWriterImpl(); // explicitly call destructor
::grpc::g_core_codegen_interface->grpc_call_unref(call);
call_requester();
- }
-
- ServerReactor* reactor() override {
- return reactor_.load(std::memory_order_relaxed);
- }
-
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
- meta_ops_;
- ::grpc::internal::CallbackWithSuccessTag meta_tag_;
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
- ::grpc::internal::CallOpSendMessage,
- ::grpc::internal::CallOpServerSendStatus>
- finish_ops_;
- ::grpc::internal::CallbackWithSuccessTag finish_tag_;
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
- ::grpc::internal::CallOpSendMessage>
- write_ops_;
- ::grpc::internal::CallbackWithSuccessTag write_tag_;
-
+ }
+
+ ServerReactor* reactor() override {
+ return reactor_.load(std::memory_order_relaxed);
+ }
+
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
+ meta_ops_;
+ ::grpc::internal::CallbackWithSuccessTag meta_tag_;
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
+ ::grpc::internal::CallOpSendMessage,
+ ::grpc::internal::CallOpServerSendStatus>
+ finish_ops_;
+ ::grpc::internal::CallbackWithSuccessTag finish_tag_;
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
+ ::grpc::internal::CallOpSendMessage>
+ write_ops_;
+ ::grpc::internal::CallbackWithSuccessTag write_tag_;
+
::grpc::CallbackServerContext* const ctx_;
- ::grpc::internal::Call call_;
- const RequestType* req_;
- std::function<void()> call_requester_;
- // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
- std::atomic<ServerWriteReactor<ResponseType>*> reactor_;
- // callbacks_outstanding_ follows a refcount pattern
- std::atomic<intptr_t> callbacks_outstanding_{
- 3}; // reserve for OnStarted, Finish, and CompletionOp
- };
-};
-
-template <class RequestType, class ResponseType>
-class CallbackBidiHandler : public ::grpc::internal::MethodHandler {
- public:
- explicit CallbackBidiHandler(
- std::function<ServerBidiReactor<RequestType, ResponseType>*(
+ ::grpc::internal::Call call_;
+ const RequestType* req_;
+ std::function<void()> call_requester_;
+ // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
+ std::atomic<ServerWriteReactor<ResponseType>*> reactor_;
+ // callbacks_outstanding_ follows a refcount pattern
+ std::atomic<intptr_t> callbacks_outstanding_{
+ 3}; // reserve for OnStarted, Finish, and CompletionOp
+ };
+};
+
+template <class RequestType, class ResponseType>
+class CallbackBidiHandler : public ::grpc::internal::MethodHandler {
+ public:
+ explicit CallbackBidiHandler(
+ std::function<ServerBidiReactor<RequestType, ResponseType>*(
::grpc::CallbackServerContext*)>
- get_reactor)
- : get_reactor_(std::move(get_reactor)) {}
- void RunHandler(const HandlerParameter& param) final {
- ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
-
- auto* stream = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(), sizeof(ServerCallbackReaderWriterImpl)))
- ServerCallbackReaderWriterImpl(
+ get_reactor)
+ : get_reactor_(std::move(get_reactor)) {}
+ void RunHandler(const HandlerParameter& param) final {
+ ::grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
+
+ auto* stream = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(), sizeof(ServerCallbackReaderWriterImpl)))
+ ServerCallbackReaderWriterImpl(
static_cast<::grpc::CallbackServerContext*>(param.server_context),
- param.call, std::move(param.call_requester));
+ param.call, std::move(param.call_requester));
// Inlineable OnDone can be false in the CompletionOp callback because there
// is no bidi reactor that has an inlineable OnDone; this only applies to
// the DefaultReactor (which is unary).
- param.server_context->BeginCompletionOp(
+ param.server_context->BeginCompletionOp(
param.call,
[stream](bool) { stream->MaybeDone(/*inlineable_ondone=*/false); },
stream);
-
- ServerBidiReactor<RequestType, ResponseType>* reactor = nullptr;
- if (param.status.ok()) {
- reactor = ::grpc::internal::CatchingReactorGetter<
- ServerBidiReactor<RequestType, ResponseType>>(
+
+ ServerBidiReactor<RequestType, ResponseType>* reactor = nullptr;
+ if (param.status.ok()) {
+ reactor = ::grpc::internal::CatchingReactorGetter<
+ ServerBidiReactor<RequestType, ResponseType>>(
get_reactor_,
static_cast<::grpc::CallbackServerContext*>(param.server_context));
- }
-
- if (reactor == nullptr) {
- // if deserialization or reactor creator failed, we need to fail the call
- reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
- param.call->call(),
- sizeof(UnimplementedBidiReactor<RequestType, ResponseType>)))
- UnimplementedBidiReactor<RequestType, ResponseType>(
- ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
- }
-
- stream->SetupReactor(reactor);
- }
-
- private:
- std::function<ServerBidiReactor<RequestType, ResponseType>*(
+ }
+
+ if (reactor == nullptr) {
+ // if deserialization or reactor creator failed, we need to fail the call
+ reactor = new (::grpc::g_core_codegen_interface->grpc_call_arena_alloc(
+ param.call->call(),
+ sizeof(UnimplementedBidiReactor<RequestType, ResponseType>)))
+ UnimplementedBidiReactor<RequestType, ResponseType>(
+ ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""));
+ }
+
+ stream->SetupReactor(reactor);
+ }
+
+ private:
+ std::function<ServerBidiReactor<RequestType, ResponseType>*(
::grpc::CallbackServerContext*)>
- get_reactor_;
-
- class ServerCallbackReaderWriterImpl
- : public ServerCallbackReaderWriter<RequestType, ResponseType> {
- public:
- void Finish(::grpc::Status s) override {
+ get_reactor_;
+
+ class ServerCallbackReaderWriterImpl
+ : public ServerCallbackReaderWriter<RequestType, ResponseType> {
+ public:
+ void Finish(::grpc::Status s) override {
// A finish tag with only MaybeDone can have its callback inlined
// regardless even if OnDone is not inlineable because this callback just
// checks a ref and then decides whether or not to dispatch OnDone.
@@ -715,86 +715,86 @@ class CallbackBidiHandler : public ::grpc::internal::MethodHandler {
this->MaybeDone(/*inlineable_ondone=*/false);
},
&finish_ops_, /*can_inline=*/true);
- finish_ops_.set_core_cq_tag(&finish_tag_);
-
- if (!ctx_->sent_initial_metadata_) {
- finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- finish_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- }
- finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
- call_.PerformOps(&finish_ops_);
- }
-
- void SendInitialMetadata() override {
- GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
- this->Ref();
+ finish_ops_.set_core_cq_tag(&finish_tag_);
+
+ if (!ctx_->sent_initial_metadata_) {
+ finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ finish_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ }
+ finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
+ call_.PerformOps(&finish_ops_);
+ }
+
+ void SendInitialMetadata() override {
+ GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
+ this->Ref();
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
- meta_tag_.Set(call_.call(),
- [this](bool ok) {
+ meta_tag_.Set(call_.call(),
+ [this](bool ok) {
ServerBidiReactor<RequestType, ResponseType>* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
- },
+ },
&meta_ops_, /*can_inline=*/false);
- meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- meta_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- meta_ops_.set_core_cq_tag(&meta_tag_);
- call_.PerformOps(&meta_ops_);
- }
-
- void Write(const ResponseType* resp,
- ::grpc::WriteOptions options) override {
- this->Ref();
- if (options.is_last_message()) {
- options.set_buffer_hint();
- }
- if (!ctx_->sent_initial_metadata_) {
- write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
- ctx_->initial_metadata_flags());
- if (ctx_->compression_level_set()) {
- write_ops_.set_compression_level(ctx_->compression_level());
- }
- ctx_->sent_initial_metadata_ = true;
- }
- // TODO(vjpai): don't assert
- GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
- call_.PerformOps(&write_ops_);
- }
-
- void WriteAndFinish(const ResponseType* resp, ::grpc::WriteOptions options,
- ::grpc::Status s) override {
+ meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ meta_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ meta_ops_.set_core_cq_tag(&meta_tag_);
+ call_.PerformOps(&meta_ops_);
+ }
+
+ void Write(const ResponseType* resp,
+ ::grpc::WriteOptions options) override {
+ this->Ref();
+ if (options.is_last_message()) {
+ options.set_buffer_hint();
+ }
+ if (!ctx_->sent_initial_metadata_) {
+ write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
+ ctx_->initial_metadata_flags());
+ if (ctx_->compression_level_set()) {
+ write_ops_.set_compression_level(ctx_->compression_level());
+ }
+ ctx_->sent_initial_metadata_ = true;
+ }
+ // TODO(vjpai): don't assert
+ GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
+ call_.PerformOps(&write_ops_);
+ }
+
+ void WriteAndFinish(const ResponseType* resp, ::grpc::WriteOptions options,
+ ::grpc::Status s) override {
// TODO(vjpai): don't assert
GPR_CODEGEN_ASSERT(finish_ops_.SendMessagePtr(resp, options).ok());
- Finish(std::move(s));
- }
-
- void Read(RequestType* req) override {
- this->Ref();
- read_ops_.RecvMessage(req);
- call_.PerformOps(&read_ops_);
- }
-
- private:
- friend class CallbackBidiHandler<RequestType, ResponseType>;
-
+ Finish(std::move(s));
+ }
+
+ void Read(RequestType* req) override {
+ this->Ref();
+ read_ops_.RecvMessage(req);
+ call_.PerformOps(&read_ops_);
+ }
+
+ private:
+ friend class CallbackBidiHandler<RequestType, ResponseType>;
+
ServerCallbackReaderWriterImpl(::grpc::CallbackServerContext* ctx,
- ::grpc::internal::Call* call,
- std::function<void()> call_requester)
- : ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
-
- void SetupReactor(ServerBidiReactor<RequestType, ResponseType>* reactor) {
- reactor_.store(reactor, std::memory_order_relaxed);
+ ::grpc::internal::Call* call,
+ std::function<void()> call_requester)
+ : ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
+
+ void SetupReactor(ServerBidiReactor<RequestType, ResponseType>* reactor) {
+ reactor_.store(reactor, std::memory_order_relaxed);
// The callbacks for these functions should not be inlined because they
// invoke user-controlled reactions, but any resulting OnDones can be
// inlined in the executor to which a callback is dispatched.
@@ -804,22 +804,22 @@ class CallbackBidiHandler : public ::grpc::internal::MethodHandler {
this->MaybeDone(/*inlineable_ondone=*/true);
},
&write_ops_, /*can_inline=*/false);
- write_ops_.set_core_cq_tag(&write_tag_);
- read_tag_.Set(call_.call(),
+ write_ops_.set_core_cq_tag(&write_tag_);
+ read_tag_.Set(call_.call(),
[this, reactor](bool ok) {
reactor->OnReadDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
- },
+ },
&read_ops_, /*can_inline=*/false);
- read_ops_.set_core_cq_tag(&read_tag_);
- this->BindReactor(reactor);
- this->MaybeCallOnCancel(reactor);
+ read_ops_.set_core_cq_tag(&read_tag_);
+ this->BindReactor(reactor);
+ this->MaybeCallOnCancel(reactor);
// Inlineable OnDone can be false here because there is no bidi
// reactor that has an inlineable OnDone; this only applies to the
// DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
- }
-
+ }
+
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
@@ -827,41 +827,41 @@ class CallbackBidiHandler : public ::grpc::internal::MethodHandler {
this->~ServerCallbackReaderWriterImpl(); // explicitly call destructor
::grpc::g_core_codegen_interface->grpc_call_unref(call);
call_requester();
- }
-
- ServerReactor* reactor() override {
- return reactor_.load(std::memory_order_relaxed);
- }
-
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
- meta_ops_;
- ::grpc::internal::CallbackWithSuccessTag meta_tag_;
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
- ::grpc::internal::CallOpSendMessage,
- ::grpc::internal::CallOpServerSendStatus>
- finish_ops_;
- ::grpc::internal::CallbackWithSuccessTag finish_tag_;
- ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
- ::grpc::internal::CallOpSendMessage>
- write_ops_;
- ::grpc::internal::CallbackWithSuccessTag write_tag_;
- ::grpc::internal::CallOpSet<
- ::grpc::internal::CallOpRecvMessage<RequestType>>
- read_ops_;
- ::grpc::internal::CallbackWithSuccessTag read_tag_;
-
+ }
+
+ ServerReactor* reactor() override {
+ return reactor_.load(std::memory_order_relaxed);
+ }
+
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
+ meta_ops_;
+ ::grpc::internal::CallbackWithSuccessTag meta_tag_;
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
+ ::grpc::internal::CallOpSendMessage,
+ ::grpc::internal::CallOpServerSendStatus>
+ finish_ops_;
+ ::grpc::internal::CallbackWithSuccessTag finish_tag_;
+ ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
+ ::grpc::internal::CallOpSendMessage>
+ write_ops_;
+ ::grpc::internal::CallbackWithSuccessTag write_tag_;
+ ::grpc::internal::CallOpSet<
+ ::grpc::internal::CallOpRecvMessage<RequestType>>
+ read_ops_;
+ ::grpc::internal::CallbackWithSuccessTag read_tag_;
+
::grpc::CallbackServerContext* const ctx_;
- ::grpc::internal::Call call_;
- std::function<void()> call_requester_;
- // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
- std::atomic<ServerBidiReactor<RequestType, ResponseType>*> reactor_;
- // callbacks_outstanding_ follows a refcount pattern
- std::atomic<intptr_t> callbacks_outstanding_{
- 3}; // reserve for OnStarted, Finish, and CompletionOp
- };
-};
-
-} // namespace internal
+ ::grpc::internal::Call call_;
+ std::function<void()> call_requester_;
+ // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
+ std::atomic<ServerBidiReactor<RequestType, ResponseType>*> reactor_;
+ // callbacks_outstanding_ follows a refcount pattern
+ std::atomic<intptr_t> callbacks_outstanding_{
+ 3}; // reserve for OnStarted, Finish, and CompletionOp
+ };
+};
+
+} // namespace internal
} // namespace grpc
-
-#endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
+
+#endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_context.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_context.h
index 685f006cda..4a6963c382 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_context.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_context.h
@@ -97,12 +97,12 @@ class Server;
class ServerInterface;
// TODO(vjpai): Remove namespace experimental when de-experimentalized fully.
-namespace experimental {
+namespace experimental {
typedef ::grpc::ServerContextBase ServerContextBase;
typedef ::grpc::CallbackServerContext CallbackServerContext;
-} // namespace experimental
+} // namespace experimental
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
namespace experimental {
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h
index 7598e72a40..6acfa57648 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h
@@ -27,7 +27,7 @@
#include <grpcpp/impl/codegen/string_ref.h>
namespace grpc {
-class ServerContextBase;
+class ServerContextBase;
namespace internal {
class InterceptorBatchMethodsImpl;
}
@@ -58,7 +58,7 @@ class ServerRpcInfo {
/// Type categorizes RPCs by unary or streaming type
enum class Type { UNARY, CLIENT_STREAMING, SERVER_STREAMING, BIDI_STREAMING };
- ~ServerRpcInfo() {}
+ ~ServerRpcInfo() {}
// Delete all copy and move constructors and assignments
ServerRpcInfo(const ServerRpcInfo&) = delete;
@@ -94,7 +94,7 @@ class ServerRpcInfo {
ServerRpcInfo(ServerContextBase* ctx, const char* method,
internal::RpcMethod::RpcType type)
- : ctx_(ctx), method_(method), type_(static_cast<Type>(type)) {}
+ : ctx_(ctx), method_(method), type_(static_cast<Type>(type)) {}
// Runs interceptor at pos \a pos.
void RunInterceptor(
@@ -116,9 +116,9 @@ class ServerRpcInfo {
}
}
- void Ref() { ref_.fetch_add(1, std::memory_order_relaxed); }
+ void Ref() { ref_.fetch_add(1, std::memory_order_relaxed); }
void Unref() {
- if (GPR_UNLIKELY(ref_.fetch_sub(1, std::memory_order_acq_rel) == 1)) {
+ if (GPR_UNLIKELY(ref_.fetch_sub(1, std::memory_order_acq_rel) == 1)) {
delete this;
}
}
@@ -126,7 +126,7 @@ class ServerRpcInfo {
ServerContextBase* ctx_ = nullptr;
const char* method_ = nullptr;
const Type type_;
- std::atomic<intptr_t> ref_{1};
+ std::atomic<intptr_t> ref_{1};
std::vector<std::unique_ptr<experimental::Interceptor>> interceptors_;
friend class internal::InterceptorBatchMethodsImpl;
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h
index d97b725025..41151a67f1 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h
@@ -27,18 +27,18 @@
#include <grpcpp/impl/codegen/call_hook.h>
#include <grpcpp/impl/codegen/completion_queue_tag.h>
#include <grpcpp/impl/codegen/core_codegen_interface.h>
-#include <grpcpp/impl/codegen/interceptor_common.h>
+#include <grpcpp/impl/codegen/interceptor_common.h>
#include <grpcpp/impl/codegen/rpc_service_method.h>
#include <grpcpp/impl/codegen/server_context.h>
namespace grpc {
-
+
class AsyncGenericService;
-class Channel;
-class CompletionQueue;
+class Channel;
+class CompletionQueue;
class GenericServerContext;
-class ServerCompletionQueue;
-class ServerCredentials;
+class ServerCompletionQueue;
+class ServerCredentials;
class Service;
extern CoreCodegenInterface* g_core_codegen_interface;
@@ -51,17 +51,17 @@ class ServerAsyncStreamingInterface;
} // namespace internal
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
-namespace experimental {
+namespace experimental {
#endif
-class CallbackGenericService;
+class CallbackGenericService;
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
} // namespace experimental
#endif
namespace experimental {
-class ServerInterceptorFactoryInterface;
-} // namespace experimental
-
+class ServerInterceptorFactoryInterface;
+} // namespace experimental
+
class ServerInterface : public internal::CallHook {
public:
virtual ~ServerInterface() {}
@@ -138,26 +138,26 @@ class ServerInterface : public internal::CallHook {
virtual void RegisterCallbackGenericService(CallbackGenericService*
/*service*/) {}
#else
- /// NOTE: class experimental_registration_interface is not part of the public
- /// API of this class
- /// TODO(vjpai): Move these contents to public API when no longer experimental
- class experimental_registration_interface {
- public:
- virtual ~experimental_registration_interface() {}
- /// May not be abstract since this is a post-1.0 API addition
- virtual void RegisterCallbackGenericService(
- experimental::CallbackGenericService* /*service*/) {}
- };
-
- /// NOTE: The function experimental_registration() is not stable public API.
- /// It is a view to the experimental components of this class. It may be
- /// changed or removed at any time. May not be abstract since this is a
- /// post-1.0 API addition
- virtual experimental_registration_interface* experimental_registration() {
- return nullptr;
- }
+ /// NOTE: class experimental_registration_interface is not part of the public
+ /// API of this class
+ /// TODO(vjpai): Move these contents to public API when no longer experimental
+ class experimental_registration_interface {
+ public:
+ virtual ~experimental_registration_interface() {}
+ /// May not be abstract since this is a post-1.0 API addition
+ virtual void RegisterCallbackGenericService(
+ experimental::CallbackGenericService* /*service*/) {}
+ };
+
+ /// NOTE: The function experimental_registration() is not stable public API.
+ /// It is a view to the experimental components of this class. It may be
+ /// changed or removed at any time. May not be abstract since this is a
+ /// post-1.0 API addition
+ virtual experimental_registration_interface* experimental_registration() {
+ return nullptr;
+ }
#endif
-
+
/// Tries to bind \a server to the given \a addr.
///
/// It can be invoked multiple times.
@@ -166,7 +166,7 @@ class ServerInterface : public internal::CallHook {
/// 192.168.1.1:31416, [::1]:27182, etc.).
/// \params creds The credentials associated with the server.
///
- /// \return bound port number on success, 0 on failure.
+ /// \return bound port number on success, 0 on failure.
///
/// \warning It's an error to call this method on an already started server.
virtual int AddListeningPort(const TString& addr,
@@ -220,20 +220,20 @@ class ServerInterface : public internal::CallHook {
/// RegisteredAsyncRequest is not part of the C++ API
class RegisteredAsyncRequest : public BaseAsyncRequest {
public:
- RegisteredAsyncRequest(ServerInterface* server,
+ RegisteredAsyncRequest(ServerInterface* server,
::grpc::ServerContext* context,
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag, const char* name,
- internal::RpcMethod::RpcType type);
+ void* tag, const char* name,
+ internal::RpcMethod::RpcType type);
virtual bool FinalizeResult(void** tag, bool* status) override {
/* If we are done intercepting, then there is nothing more for us to do */
if (done_intercepting_) {
return BaseAsyncRequest::FinalizeResult(tag, status);
}
- call_wrapper_ = ::grpc::internal::Call(
+ call_wrapper_ = ::grpc::internal::Call(
call_, server_, call_cq_, server_->max_receive_message_size(),
context_->set_server_rpc_info(name_, type_,
*server_->interceptor_creators()));
@@ -250,12 +250,12 @@ class ServerInterface : public internal::CallHook {
class NoPayloadAsyncRequest final : public RegisteredAsyncRequest {
public:
NoPayloadAsyncRequest(internal::RpcServiceMethod* registered_method,
- ServerInterface* server,
+ ServerInterface* server,
::grpc::ServerContext* context,
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag)
+ void* tag)
: RegisteredAsyncRequest(
server, context, stream, call_cq, notification_cq, tag,
registered_method->name(), registered_method->method_type()) {
@@ -273,7 +273,7 @@ class ServerInterface : public internal::CallHook {
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag, Message* request)
+ void* tag, Message* request)
: RegisteredAsyncRequest(
server, context, stream, call_cq, notification_cq, tag,
registered_method->name(), registered_method->method_type()),
@@ -329,7 +329,7 @@ class ServerInterface : public internal::CallHook {
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag, bool delete_on_finalize);
+ void* tag, bool delete_on_finalize);
bool FinalizeResult(void** tag, bool* status) override;
@@ -343,7 +343,7 @@ class ServerInterface : public internal::CallHook {
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag, Message* message) {
+ void* tag, Message* message) {
GPR_CODEGEN_ASSERT(method);
new PayloadAsyncRequest<Message>(method, this, context, stream, call_cq,
notification_cq, tag, message);
@@ -354,7 +354,7 @@ class ServerInterface : public internal::CallHook {
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag) {
+ void* tag) {
GPR_CODEGEN_ASSERT(method);
new NoPayloadAsyncRequest(method, this, context, stream, call_cq,
notification_cq, tag);
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h
index 30be904a3c..266d093ea6 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h
@@ -30,8 +30,8 @@ namespace grpc {
class CompletionQueue;
class ServerContext;
-class ServerInterface;
-
+class ServerInterface;
+
namespace internal {
class Call;
class ServerAsyncStreamingInterface {
@@ -59,8 +59,8 @@ class Service {
virtual ~Service() {}
bool has_async_methods() const {
- for (const auto& method : methods_) {
- if (method && method->handler() == nullptr) {
+ for (const auto& method : methods_) {
+ if (method && method->handler() == nullptr) {
return true;
}
}
@@ -68,9 +68,9 @@ class Service {
}
bool has_synchronous_methods() const {
- for (const auto& method : methods_) {
- if (method &&
- method->api_type() == internal::RpcServiceMethod::ApiType::SYNC) {
+ for (const auto& method : methods_) {
+ if (method &&
+ method->api_type() == internal::RpcServiceMethod::ApiType::SYNC) {
return true;
}
}
@@ -78,11 +78,11 @@ class Service {
}
bool has_callback_methods() const {
- for (const auto& method : methods_) {
- if (method && (method->api_type() ==
- internal::RpcServiceMethod::ApiType::CALL_BACK ||
- method->api_type() ==
- internal::RpcServiceMethod::ApiType::RAW_CALL_BACK)) {
+ for (const auto& method : methods_) {
+ if (method && (method->api_type() ==
+ internal::RpcServiceMethod::ApiType::CALL_BACK ||
+ method->api_type() ==
+ internal::RpcServiceMethod::ApiType::RAW_CALL_BACK)) {
return true;
}
}
@@ -90,8 +90,8 @@ class Service {
}
bool has_generic_methods() const {
- for (const auto& method : methods_) {
- if (method.get() == nullptr) {
+ for (const auto& method : methods_) {
+ if (method.get() == nullptr) {
return true;
}
}
@@ -112,10 +112,10 @@ class Service {
service_->MarkMethodRawCallbackInternal(index, handler);
}
- internal::MethodHandler* GetHandler(int index) {
+ internal::MethodHandler* GetHandler(int index) {
return service_->GetHandlerInternal(index);
- }
-
+ }
+
private:
Service* service_;
};
@@ -124,11 +124,11 @@ class Service {
template <class Message>
void RequestAsyncUnary(int index, ::grpc::ServerContext* context,
- Message* request,
+ Message* request,
internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq,
- void* tag) {
+ void* tag) {
// Typecast the index to size_t for indexing into a vector
// while preserving the API that existed before a compiler
// warning was first seen (grpc/grpc#11664)
@@ -138,7 +138,7 @@ class Service {
}
void RequestAsyncClientStreaming(
int index, ::grpc::ServerContext* context,
- internal::ServerAsyncStreamingInterface* stream,
+ internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq, void* tag) {
size_t idx = static_cast<size_t>(index);
@@ -148,7 +148,7 @@ class Service {
template <class Message>
void RequestAsyncServerStreaming(
int index, ::grpc::ServerContext* context, Message* request,
- internal::ServerAsyncStreamingInterface* stream,
+ internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq, void* tag) {
size_t idx = static_cast<size_t>(index);
@@ -157,7 +157,7 @@ class Service {
}
void RequestAsyncBidiStreaming(
int index, ::grpc::ServerContext* context,
- internal::ServerAsyncStreamingInterface* stream,
+ internal::ServerAsyncStreamingInterface* stream,
::grpc::CompletionQueue* call_cq,
::grpc::ServerCompletionQueue* notification_cq, void* tag) {
size_t idx = static_cast<size_t>(index);
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/status_code_enum.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/status_code_enum.h
index bdd7ead6ad..f47ee068ed 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/status_code_enum.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/status_code_enum.h
@@ -119,8 +119,8 @@ enum StatusCode {
INTERNAL = 13,
/// The service is currently unavailable. This is a most likely a transient
- /// condition and may be corrected by retrying with a backoff. Note that it is
- /// not always safe to retry non-idempotent operations.
+ /// condition and may be corrected by retrying with a backoff. Note that it is
+ /// not always safe to retry non-idempotent operations.
///
/// \warning Although data MIGHT not have been transmitted when this
/// status occurs, there is NOT A GUARANTEE that the server has not seen
diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/sync.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/sync.h
index 146f182e57..0d058c091f 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/codegen/sync.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/sync.h
@@ -1,151 +1,151 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_IMPL_CODEGEN_SYNC_H
-#define GRPCPP_IMPL_CODEGEN_SYNC_H
-
-#include <grpc/impl/codegen/port_platform.h>
-
-#ifdef GPR_HAS_PTHREAD_H
-#include <pthread.h>
-#endif
-
-#include <mutex>
-
-#include <grpc/impl/codegen/log.h>
-#include <grpc/impl/codegen/sync.h>
-
-#include <grpcpp/impl/codegen/core_codegen_interface.h>
-
-// The core library is not accessible in C++ codegen headers, and vice versa.
-// Thus, we need to have duplicate headers with similar functionality.
-// Make sure any change to this file is also reflected in
-// src/core/lib/gprpp/sync.h too.
-//
-// Whenever possible, prefer "src/core/lib/gprpp/sync.h" over this file,
-// since in core we do not rely on g_core_codegen_interface and hence do not
-// pay the costs of virtual function calls.
-
-namespace grpc {
-namespace internal {
-
-class Mutex {
- public:
- Mutex() { g_core_codegen_interface->gpr_mu_init(&mu_); }
- ~Mutex() { g_core_codegen_interface->gpr_mu_destroy(&mu_); }
-
- Mutex(const Mutex&) = delete;
- Mutex& operator=(const Mutex&) = delete;
-
- gpr_mu* get() { return &mu_; }
- const gpr_mu* get() const { return &mu_; }
-
- private:
- union {
- gpr_mu mu_;
- std::mutex do_not_use_sth_;
-#ifdef GPR_HAS_PTHREAD_H
- pthread_mutex_t do_not_use_pth_;
-#endif
- };
-};
-
-// MutexLock is a std::
-class MutexLock {
- public:
- explicit MutexLock(Mutex* mu) : mu_(mu->get()) {
- g_core_codegen_interface->gpr_mu_lock(mu_);
- }
- explicit MutexLock(gpr_mu* mu) : mu_(mu) {
- g_core_codegen_interface->gpr_mu_lock(mu_);
- }
- ~MutexLock() { g_core_codegen_interface->gpr_mu_unlock(mu_); }
-
- MutexLock(const MutexLock&) = delete;
- MutexLock& operator=(const MutexLock&) = delete;
-
- private:
- gpr_mu* const mu_;
-};
-
-class ReleasableMutexLock {
- public:
- explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) {
- g_core_codegen_interface->gpr_mu_lock(mu_);
- }
- explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) {
- g_core_codegen_interface->gpr_mu_lock(mu_);
- }
- ~ReleasableMutexLock() {
- if (!released_) g_core_codegen_interface->gpr_mu_unlock(mu_);
- }
-
- ReleasableMutexLock(const ReleasableMutexLock&) = delete;
- ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
-
- void Lock() {
- GPR_DEBUG_ASSERT(released_);
- g_core_codegen_interface->gpr_mu_lock(mu_);
- released_ = false;
- }
-
- void Unlock() {
- GPR_DEBUG_ASSERT(!released_);
- released_ = true;
- g_core_codegen_interface->gpr_mu_unlock(mu_);
- }
-
- private:
- gpr_mu* const mu_;
- bool released_ = false;
-};
-
-class CondVar {
- public:
- CondVar() { g_core_codegen_interface->gpr_cv_init(&cv_); }
- ~CondVar() { g_core_codegen_interface->gpr_cv_destroy(&cv_); }
-
- CondVar(const CondVar&) = delete;
- CondVar& operator=(const CondVar&) = delete;
-
- void Signal() { g_core_codegen_interface->gpr_cv_signal(&cv_); }
- void Broadcast() { g_core_codegen_interface->gpr_cv_broadcast(&cv_); }
-
- int Wait(Mutex* mu) {
- return Wait(mu,
- g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME));
- }
- int Wait(Mutex* mu, const gpr_timespec& deadline) {
- return g_core_codegen_interface->gpr_cv_wait(&cv_, mu->get(), deadline);
- }
-
- template <typename Predicate>
- void WaitUntil(Mutex* mu, Predicate pred) {
- while (!pred()) {
- Wait(mu, g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME));
- }
- }
-
- private:
- gpr_cv cv_;
-};
-
-} // namespace internal
-} // namespace grpc
-
-#endif // GRPCPP_IMPL_CODEGEN_SYNC_H
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_IMPL_CODEGEN_SYNC_H
+#define GRPCPP_IMPL_CODEGEN_SYNC_H
+
+#include <grpc/impl/codegen/port_platform.h>
+
+#ifdef GPR_HAS_PTHREAD_H
+#include <pthread.h>
+#endif
+
+#include <mutex>
+
+#include <grpc/impl/codegen/log.h>
+#include <grpc/impl/codegen/sync.h>
+
+#include <grpcpp/impl/codegen/core_codegen_interface.h>
+
+// The core library is not accessible in C++ codegen headers, and vice versa.
+// Thus, we need to have duplicate headers with similar functionality.
+// Make sure any change to this file is also reflected in
+// src/core/lib/gprpp/sync.h too.
+//
+// Whenever possible, prefer "src/core/lib/gprpp/sync.h" over this file,
+// since in core we do not rely on g_core_codegen_interface and hence do not
+// pay the costs of virtual function calls.
+
+namespace grpc {
+namespace internal {
+
+class Mutex {
+ public:
+ Mutex() { g_core_codegen_interface->gpr_mu_init(&mu_); }
+ ~Mutex() { g_core_codegen_interface->gpr_mu_destroy(&mu_); }
+
+ Mutex(const Mutex&) = delete;
+ Mutex& operator=(const Mutex&) = delete;
+
+ gpr_mu* get() { return &mu_; }
+ const gpr_mu* get() const { return &mu_; }
+
+ private:
+ union {
+ gpr_mu mu_;
+ std::mutex do_not_use_sth_;
+#ifdef GPR_HAS_PTHREAD_H
+ pthread_mutex_t do_not_use_pth_;
+#endif
+ };
+};
+
+// MutexLock is a std::
+class MutexLock {
+ public:
+ explicit MutexLock(Mutex* mu) : mu_(mu->get()) {
+ g_core_codegen_interface->gpr_mu_lock(mu_);
+ }
+ explicit MutexLock(gpr_mu* mu) : mu_(mu) {
+ g_core_codegen_interface->gpr_mu_lock(mu_);
+ }
+ ~MutexLock() { g_core_codegen_interface->gpr_mu_unlock(mu_); }
+
+ MutexLock(const MutexLock&) = delete;
+ MutexLock& operator=(const MutexLock&) = delete;
+
+ private:
+ gpr_mu* const mu_;
+};
+
+class ReleasableMutexLock {
+ public:
+ explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) {
+ g_core_codegen_interface->gpr_mu_lock(mu_);
+ }
+ explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) {
+ g_core_codegen_interface->gpr_mu_lock(mu_);
+ }
+ ~ReleasableMutexLock() {
+ if (!released_) g_core_codegen_interface->gpr_mu_unlock(mu_);
+ }
+
+ ReleasableMutexLock(const ReleasableMutexLock&) = delete;
+ ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
+
+ void Lock() {
+ GPR_DEBUG_ASSERT(released_);
+ g_core_codegen_interface->gpr_mu_lock(mu_);
+ released_ = false;
+ }
+
+ void Unlock() {
+ GPR_DEBUG_ASSERT(!released_);
+ released_ = true;
+ g_core_codegen_interface->gpr_mu_unlock(mu_);
+ }
+
+ private:
+ gpr_mu* const mu_;
+ bool released_ = false;
+};
+
+class CondVar {
+ public:
+ CondVar() { g_core_codegen_interface->gpr_cv_init(&cv_); }
+ ~CondVar() { g_core_codegen_interface->gpr_cv_destroy(&cv_); }
+
+ CondVar(const CondVar&) = delete;
+ CondVar& operator=(const CondVar&) = delete;
+
+ void Signal() { g_core_codegen_interface->gpr_cv_signal(&cv_); }
+ void Broadcast() { g_core_codegen_interface->gpr_cv_broadcast(&cv_); }
+
+ int Wait(Mutex* mu) {
+ return Wait(mu,
+ g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME));
+ }
+ int Wait(Mutex* mu, const gpr_timespec& deadline) {
+ return g_core_codegen_interface->gpr_cv_wait(&cv_, mu->get(), deadline);
+ }
+
+ template <typename Predicate>
+ void WaitUntil(Mutex* mu, Predicate pred) {
+ while (!pred()) {
+ Wait(mu, g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME));
+ }
+ }
+
+ private:
+ gpr_cv cv_;
+};
+
+} // namespace internal
+} // namespace grpc
+
+#endif // GRPCPP_IMPL_CODEGEN_SYNC_H
diff --git a/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h b/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h
index 8fedca2b14..fbb178f21e 100644
--- a/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h
+++ b/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h
@@ -25,7 +25,7 @@
#include <memory>
-#include <grpcpp/support/channel_arguments.h>
+#include <grpcpp/support/channel_arguments.h>
#include <grpcpp/support/config.h>
namespace grpc {
@@ -59,7 +59,7 @@ class ServerBuilderPlugin {
/// UpdateChannelArguments will be called in ServerBuilder::BuildAndStart(),
/// before the Server instance is created.
- virtual void UpdateChannelArguments(ChannelArguments* /*args*/) {}
+ virtual void UpdateChannelArguments(ChannelArguments* /*args*/) {}
virtual bool has_sync_methods() const { return false; }
virtual bool has_async_methods() const { return false; }
diff --git a/contrib/libs/grpc/include/grpcpp/security/credentials.h b/contrib/libs/grpc/include/grpcpp/security/credentials.h
index 339e9d4c27..090886f283 100644
--- a/contrib/libs/grpc/include/grpcpp/security/credentials.h
+++ b/contrib/libs/grpc/include/grpcpp/security/credentials.h
@@ -58,7 +58,7 @@ std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors(
std::vector<
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
-}
+}
/// A channel credentials object encapsulates all the state needed by a client
/// to authenticate with a server for a given channel.
@@ -265,7 +265,7 @@ class MetadataCredentialsPlugin {
std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
std::unique_ptr<MetadataCredentialsPlugin> plugin);
-namespace experimental {
+namespace experimental {
/// Options for creating STS Oauth Token Exchange credentials following the IETF
/// draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
@@ -314,7 +314,7 @@ std::shared_ptr<ChannelCredentials> AltsCredentials(
/// Builds Local Credentials.
std::shared_ptr<ChannelCredentials> LocalCredentials(
grpc_local_connect_type type);
-
+
/// Builds TLS Credentials given TLS options.
std::shared_ptr<ChannelCredentials> TlsCredentials(
const TlsCredentialsOptions& options);
diff --git a/contrib/libs/grpc/include/grpcpp/security/cronet_credentials.h b/contrib/libs/grpc/include/grpcpp/security/cronet_credentials.h
index 7874debae8..09f9e5ea29 100644
--- a/contrib/libs/grpc/include/grpcpp/security/cronet_credentials.h
+++ b/contrib/libs/grpc/include/grpcpp/security/cronet_credentials.h
@@ -1,33 +1,33 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SECURITY_CRONET_CREDENTIALS_H
-#define GRPCPP_SECURITY_CRONET_CREDENTIALS_H
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_SECURITY_CRONET_CREDENTIALS_H
+#define GRPCPP_SECURITY_CRONET_CREDENTIALS_H
+
#include <memory>
-
-namespace grpc {
-
+
+namespace grpc {
+
class ChannelCredentials;
-
+
/// Credentials for a channel using Cronet.
std::shared_ptr<ChannelCredentials> CronetChannelCredentials(void* engine);
-} // namespace grpc
-
-#endif // GRPCPP_SECURITY_CRONET_CREDENTIALS_H
+} // namespace grpc
+
+#endif // GRPCPP_SECURITY_CRONET_CREDENTIALS_H
diff --git a/contrib/libs/grpc/include/grpcpp/security/server_credentials.h b/contrib/libs/grpc/include/grpcpp/security/server_credentials.h
index d0a532360a..4b41d492b1 100644
--- a/contrib/libs/grpc/include/grpcpp/security/server_credentials.h
+++ b/contrib/libs/grpc/include/grpcpp/security/server_credentials.h
@@ -103,10 +103,10 @@ std::shared_ptr<ServerCredentials> AltsServerCredentials(
std::shared_ptr<ServerCredentials> LocalServerCredentials(
grpc_local_connect_type type);
-/// Builds TLS ServerCredentials given TLS options.
+/// Builds TLS ServerCredentials given TLS options.
std::shared_ptr<ServerCredentials> TlsServerCredentials(
const experimental::TlsCredentialsOptions& options);
-
+
} // namespace experimental
} // namespace grpc
diff --git a/contrib/libs/grpc/include/grpcpp/security/tls_credentials_options.h b/contrib/libs/grpc/include/grpcpp/security/tls_credentials_options.h
index f704cf6129..20c3d7ba05 100644
--- a/contrib/libs/grpc/include/grpcpp/security/tls_credentials_options.h
+++ b/contrib/libs/grpc/include/grpcpp/security/tls_credentials_options.h
@@ -1,283 +1,283 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
-#define GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
-
-#include <grpc/grpc_security_constants.h>
-#include <grpc/status.h>
-#include <grpc/support/log.h>
-#include <grpcpp/support/config.h>
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
+#define GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
+
+#include <grpc/grpc_security_constants.h>
+#include <grpc/status.h>
+#include <grpc/support/log.h>
+#include <grpcpp/support/config.h>
+
#include <memory>
#include <vector>
-typedef struct grpc_tls_credential_reload_arg grpc_tls_credential_reload_arg;
-typedef struct grpc_tls_credential_reload_config
- grpc_tls_credential_reload_config;
-typedef struct grpc_tls_server_authorization_check_arg
- grpc_tls_server_authorization_check_arg;
-typedef struct grpc_tls_server_authorization_check_config
- grpc_tls_server_authorization_check_config;
-typedef struct grpc_tls_credentials_options grpc_tls_credentials_options;
-
+typedef struct grpc_tls_credential_reload_arg grpc_tls_credential_reload_arg;
+typedef struct grpc_tls_credential_reload_config
+ grpc_tls_credential_reload_config;
+typedef struct grpc_tls_server_authorization_check_arg
+ grpc_tls_server_authorization_check_arg;
+typedef struct grpc_tls_server_authorization_check_config
+ grpc_tls_server_authorization_check_config;
+typedef struct grpc_tls_credentials_options grpc_tls_credentials_options;
+
namespace grpc {
-namespace experimental {
-
-/** TLS key materials config, wrapper for grpc_tls_key_materials_config. It is
- * used for experimental purposes for now and subject to change. **/
-class TlsKeyMaterialsConfig {
- public:
- struct PemKeyCertPair {
+namespace experimental {
+
+/** TLS key materials config, wrapper for grpc_tls_key_materials_config. It is
+ * used for experimental purposes for now and subject to change. **/
+class TlsKeyMaterialsConfig {
+ public:
+ struct PemKeyCertPair {
TString private_key;
TString cert_chain;
- };
-
- /** Getters for member fields. **/
+ };
+
+ /** Getters for member fields. **/
const TString pem_root_certs() const { return pem_root_certs_; }
- const std::vector<PemKeyCertPair>& pem_key_cert_pair_list() const {
- return pem_key_cert_pair_list_;
- }
- int version() const { return version_; }
-
+ const std::vector<PemKeyCertPair>& pem_key_cert_pair_list() const {
+ return pem_key_cert_pair_list_;
+ }
+ int version() const { return version_; }
+
/** Setter for key materials that will be called by the user. Ownership of the
* arguments will not be transferred. **/
void set_pem_root_certs(const TString& pem_root_certs);
- void add_pem_key_cert_pair(const PemKeyCertPair& pem_key_cert_pair);
+ void add_pem_key_cert_pair(const PemKeyCertPair& pem_key_cert_pair);
void set_key_materials(
const TString& pem_root_certs,
const std::vector<PemKeyCertPair>& pem_key_cert_pair_list);
- void set_version(int version) { version_ = version; };
-
- private:
- int version_ = 0;
- std::vector<PemKeyCertPair> pem_key_cert_pair_list_;
+ void set_version(int version) { version_ = version; };
+
+ private:
+ int version_ = 0;
+ std::vector<PemKeyCertPair> pem_key_cert_pair_list_;
TString pem_root_certs_;
-};
-
-/** TLS credential reload arguments, wraps grpc_tls_credential_reload_arg. It is
+};
+
+/** TLS credential reload arguments, wraps grpc_tls_credential_reload_arg. It is
* used for experimental purposes for now and it is subject to change.
- *
+ *
* The credential reload arg contains all the info necessary to schedule/cancel
* a credential reload request. The callback function must be called after
* finishing the schedule operation. See the description of the
* grpc_tls_credential_reload_arg struct in grpc_security.h for more details.
- * **/
-class TlsCredentialReloadArg {
- public:
- /** TlsCredentialReloadArg does not take ownership of the C arg that is passed
+ * **/
+class TlsCredentialReloadArg {
+ public:
+ /** TlsCredentialReloadArg does not take ownership of the C arg that is passed
* to the constructor. One must remember to free any memory allocated to the
* C arg after using the setter functions below. **/
- TlsCredentialReloadArg(grpc_tls_credential_reload_arg* arg);
- ~TlsCredentialReloadArg();
-
+ TlsCredentialReloadArg(grpc_tls_credential_reload_arg* arg);
+ ~TlsCredentialReloadArg();
+
/** Getters for member fields. **/
- void* cb_user_data() const;
- bool is_pem_key_cert_pair_list_empty() const;
- grpc_ssl_certificate_config_reload_status status() const;
+ void* cb_user_data() const;
+ bool is_pem_key_cert_pair_list_empty() const;
+ grpc_ssl_certificate_config_reload_status status() const;
TString error_details() const;
-
+
/** Setters for member fields. Ownership of the arguments will not be
* transferred. **/
- void set_cb_user_data(void* cb_user_data);
+ void set_cb_user_data(void* cb_user_data);
void set_pem_root_certs(const TString& pem_root_certs);
- void add_pem_key_cert_pair(
+ void add_pem_key_cert_pair(
const TlsKeyMaterialsConfig::PemKeyCertPair& pem_key_cert_pair);
void set_key_materials(const TString& pem_root_certs,
std::vector<TlsKeyMaterialsConfig::PemKeyCertPair>
pem_key_cert_pair_list);
- void set_key_materials_config(
- const std::shared_ptr<TlsKeyMaterialsConfig>& key_materials_config);
- void set_status(grpc_ssl_certificate_config_reload_status status);
+ void set_key_materials_config(
+ const std::shared_ptr<TlsKeyMaterialsConfig>& key_materials_config);
+ void set_status(grpc_ssl_certificate_config_reload_status status);
void set_error_details(const TString& error_details);
-
- /** Calls the C arg's callback function. **/
- void OnCredentialReloadDoneCallback();
-
- private:
- grpc_tls_credential_reload_arg* c_arg_;
-};
-
-/** An interface that the application derives and uses to instantiate a
- * TlsCredentialReloadConfig instance. Refer to the definition of the
- * grpc_tls_credential_reload_config in grpc_tls_credentials_options.h for more
- * details on the expectations of the member functions of the interface. **/
-struct TlsCredentialReloadInterface {
- virtual ~TlsCredentialReloadInterface() = default;
- /** A callback that invokes the credential reload. **/
- virtual int Schedule(TlsCredentialReloadArg* arg) = 0;
- /** A callback that cancels a credential reload request. **/
- virtual void Cancel(TlsCredentialReloadArg* /* arg */) {}
-};
-
-/** TLS credential reloag config, wraps grpc_tls_credential_reload_config. It is
- * used for experimental purposes for now and it is subject to change. **/
-class TlsCredentialReloadConfig {
- public:
- TlsCredentialReloadConfig(std::shared_ptr<TlsCredentialReloadInterface>
- credential_reload_interface);
- ~TlsCredentialReloadConfig();
-
- int Schedule(TlsCredentialReloadArg* arg) const {
- if (credential_reload_interface_ == nullptr) {
- gpr_log(GPR_ERROR, "credential reload interface is nullptr");
- if (arg != nullptr) {
- arg->set_status(GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL);
- arg->set_error_details(
- "the interface of the credential reload config is nullptr");
- }
- return 1;
- }
- return credential_reload_interface_->Schedule(arg);
- }
-
- void Cancel(TlsCredentialReloadArg* arg) const {
- if (credential_reload_interface_ == nullptr) {
- gpr_log(GPR_ERROR, "credential reload interface is nullptr");
- if (arg != nullptr) {
- arg->set_status(GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL);
- arg->set_error_details(
- "the interface of the credential reload config is nullptr");
- }
- return;
- }
- credential_reload_interface_->Cancel(arg);
- }
-
- /** Returns a C struct for the credential reload config. **/
- grpc_tls_credential_reload_config* c_config() const { return c_config_; }
-
- private:
- grpc_tls_credential_reload_config* c_config_;
- std::shared_ptr<TlsCredentialReloadInterface> credential_reload_interface_;
-};
-
-/** TLS server authorization check arguments, wraps
- * grpc_tls_server_authorization_check_arg. It is used for experimental
- * purposes for now and it is subject to change.
- *
- * The server authorization check arg contains all the info necessary to
- * schedule/cancel a server authorization check request. The callback function
- * must be called after finishing the schedule operation. See the description
- * of the grpc_tls_server_authorization_check_arg struct in grpc_security.h for
- * more details. **/
-class TlsServerAuthorizationCheckArg {
- public:
- /** TlsServerAuthorizationCheckArg does not take ownership of the C arg passed
- * to the constructor. One must remember to free any memory allocated to the
- * C arg after using the setter functions below. **/
- TlsServerAuthorizationCheckArg(grpc_tls_server_authorization_check_arg* arg);
- ~TlsServerAuthorizationCheckArg();
-
+
+ /** Calls the C arg's callback function. **/
+ void OnCredentialReloadDoneCallback();
+
+ private:
+ grpc_tls_credential_reload_arg* c_arg_;
+};
+
+/** An interface that the application derives and uses to instantiate a
+ * TlsCredentialReloadConfig instance. Refer to the definition of the
+ * grpc_tls_credential_reload_config in grpc_tls_credentials_options.h for more
+ * details on the expectations of the member functions of the interface. **/
+struct TlsCredentialReloadInterface {
+ virtual ~TlsCredentialReloadInterface() = default;
+ /** A callback that invokes the credential reload. **/
+ virtual int Schedule(TlsCredentialReloadArg* arg) = 0;
+ /** A callback that cancels a credential reload request. **/
+ virtual void Cancel(TlsCredentialReloadArg* /* arg */) {}
+};
+
+/** TLS credential reloag config, wraps grpc_tls_credential_reload_config. It is
+ * used for experimental purposes for now and it is subject to change. **/
+class TlsCredentialReloadConfig {
+ public:
+ TlsCredentialReloadConfig(std::shared_ptr<TlsCredentialReloadInterface>
+ credential_reload_interface);
+ ~TlsCredentialReloadConfig();
+
+ int Schedule(TlsCredentialReloadArg* arg) const {
+ if (credential_reload_interface_ == nullptr) {
+ gpr_log(GPR_ERROR, "credential reload interface is nullptr");
+ if (arg != nullptr) {
+ arg->set_status(GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL);
+ arg->set_error_details(
+ "the interface of the credential reload config is nullptr");
+ }
+ return 1;
+ }
+ return credential_reload_interface_->Schedule(arg);
+ }
+
+ void Cancel(TlsCredentialReloadArg* arg) const {
+ if (credential_reload_interface_ == nullptr) {
+ gpr_log(GPR_ERROR, "credential reload interface is nullptr");
+ if (arg != nullptr) {
+ arg->set_status(GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL);
+ arg->set_error_details(
+ "the interface of the credential reload config is nullptr");
+ }
+ return;
+ }
+ credential_reload_interface_->Cancel(arg);
+ }
+
+ /** Returns a C struct for the credential reload config. **/
+ grpc_tls_credential_reload_config* c_config() const { return c_config_; }
+
+ private:
+ grpc_tls_credential_reload_config* c_config_;
+ std::shared_ptr<TlsCredentialReloadInterface> credential_reload_interface_;
+};
+
+/** TLS server authorization check arguments, wraps
+ * grpc_tls_server_authorization_check_arg. It is used for experimental
+ * purposes for now and it is subject to change.
+ *
+ * The server authorization check arg contains all the info necessary to
+ * schedule/cancel a server authorization check request. The callback function
+ * must be called after finishing the schedule operation. See the description
+ * of the grpc_tls_server_authorization_check_arg struct in grpc_security.h for
+ * more details. **/
+class TlsServerAuthorizationCheckArg {
+ public:
+ /** TlsServerAuthorizationCheckArg does not take ownership of the C arg passed
+ * to the constructor. One must remember to free any memory allocated to the
+ * C arg after using the setter functions below. **/
+ TlsServerAuthorizationCheckArg(grpc_tls_server_authorization_check_arg* arg);
+ ~TlsServerAuthorizationCheckArg();
+
/** Getters for member fields. **/
- void* cb_user_data() const;
- int success() const;
+ void* cb_user_data() const;
+ int success() const;
TString target_name() const;
TString peer_cert() const;
TString peer_cert_full_chain() const;
- grpc_status_code status() const;
+ grpc_status_code status() const;
TString error_details() const;
-
+
/** Setters for member fields. **/
- void set_cb_user_data(void* cb_user_data);
- void set_success(int success);
+ void set_cb_user_data(void* cb_user_data);
+ void set_success(int success);
void set_target_name(const TString& target_name);
void set_peer_cert(const TString& peer_cert);
void set_peer_cert_full_chain(const TString& peer_cert_full_chain);
- void set_status(grpc_status_code status);
+ void set_status(grpc_status_code status);
void set_error_details(const TString& error_details);
-
- /** Calls the C arg's callback function. **/
- void OnServerAuthorizationCheckDoneCallback();
-
- private:
- grpc_tls_server_authorization_check_arg* c_arg_;
-};
-
-/** An interface that the application derives and uses to instantiate a
- * TlsServerAuthorizationCheckConfig instance. Refer to the definition of the
- * grpc_tls_server_authorization_check_config in grpc_tls_credentials_options.h
- * for more details on the expectations of the member functions of the
- * interface.
- * **/
-struct TlsServerAuthorizationCheckInterface {
- virtual ~TlsServerAuthorizationCheckInterface() = default;
- /** A callback that invokes the server authorization check. **/
- virtual int Schedule(TlsServerAuthorizationCheckArg* arg) = 0;
- /** A callback that cancels a server authorization check request. **/
- virtual void Cancel(TlsServerAuthorizationCheckArg* /* arg */) {}
-};
-
-/** TLS server authorization check config, wraps
- * grps_tls_server_authorization_check_config. It is used for experimental
- * purposes for now and it is subject to change. **/
-class TlsServerAuthorizationCheckConfig {
- public:
- TlsServerAuthorizationCheckConfig(
- std::shared_ptr<TlsServerAuthorizationCheckInterface>
- server_authorization_check_interface);
- ~TlsServerAuthorizationCheckConfig();
-
- int Schedule(TlsServerAuthorizationCheckArg* arg) const {
- if (server_authorization_check_interface_ == nullptr) {
- gpr_log(GPR_ERROR, "server authorization check interface is nullptr");
- if (arg != nullptr) {
- arg->set_status(GRPC_STATUS_NOT_FOUND);
- arg->set_error_details(
- "the interface of the server authorization check config is "
- "nullptr");
- }
- return 1;
- }
- return server_authorization_check_interface_->Schedule(arg);
- }
-
- void Cancel(TlsServerAuthorizationCheckArg* arg) const {
- if (server_authorization_check_interface_ == nullptr) {
- gpr_log(GPR_ERROR, "server authorization check interface is nullptr");
- if (arg != nullptr) {
- arg->set_status(GRPC_STATUS_NOT_FOUND);
- arg->set_error_details(
- "the interface of the server authorization check config is "
- "nullptr");
- }
- return;
- }
- server_authorization_check_interface_->Cancel(arg);
- }
-
- /** Returns C struct for the server authorization check config. **/
- grpc_tls_server_authorization_check_config* c_config() const {
- return c_config_;
- }
-
- private:
- grpc_tls_server_authorization_check_config* c_config_;
- std::shared_ptr<TlsServerAuthorizationCheckInterface>
- server_authorization_check_interface_;
-};
-
-/** TLS credentials options, wrapper for grpc_tls_credentials_options. It is
- * used for experimental purposes for now and it is subject to change. See the
- * description of the grpc_tls_credentials_options struct in grpc_security.h for
- * more details. **/
-class TlsCredentialsOptions {
- public:
+
+ /** Calls the C arg's callback function. **/
+ void OnServerAuthorizationCheckDoneCallback();
+
+ private:
+ grpc_tls_server_authorization_check_arg* c_arg_;
+};
+
+/** An interface that the application derives and uses to instantiate a
+ * TlsServerAuthorizationCheckConfig instance. Refer to the definition of the
+ * grpc_tls_server_authorization_check_config in grpc_tls_credentials_options.h
+ * for more details on the expectations of the member functions of the
+ * interface.
+ * **/
+struct TlsServerAuthorizationCheckInterface {
+ virtual ~TlsServerAuthorizationCheckInterface() = default;
+ /** A callback that invokes the server authorization check. **/
+ virtual int Schedule(TlsServerAuthorizationCheckArg* arg) = 0;
+ /** A callback that cancels a server authorization check request. **/
+ virtual void Cancel(TlsServerAuthorizationCheckArg* /* arg */) {}
+};
+
+/** TLS server authorization check config, wraps
+ * grps_tls_server_authorization_check_config. It is used for experimental
+ * purposes for now and it is subject to change. **/
+class TlsServerAuthorizationCheckConfig {
+ public:
+ TlsServerAuthorizationCheckConfig(
+ std::shared_ptr<TlsServerAuthorizationCheckInterface>
+ server_authorization_check_interface);
+ ~TlsServerAuthorizationCheckConfig();
+
+ int Schedule(TlsServerAuthorizationCheckArg* arg) const {
+ if (server_authorization_check_interface_ == nullptr) {
+ gpr_log(GPR_ERROR, "server authorization check interface is nullptr");
+ if (arg != nullptr) {
+ arg->set_status(GRPC_STATUS_NOT_FOUND);
+ arg->set_error_details(
+ "the interface of the server authorization check config is "
+ "nullptr");
+ }
+ return 1;
+ }
+ return server_authorization_check_interface_->Schedule(arg);
+ }
+
+ void Cancel(TlsServerAuthorizationCheckArg* arg) const {
+ if (server_authorization_check_interface_ == nullptr) {
+ gpr_log(GPR_ERROR, "server authorization check interface is nullptr");
+ if (arg != nullptr) {
+ arg->set_status(GRPC_STATUS_NOT_FOUND);
+ arg->set_error_details(
+ "the interface of the server authorization check config is "
+ "nullptr");
+ }
+ return;
+ }
+ server_authorization_check_interface_->Cancel(arg);
+ }
+
+ /** Returns C struct for the server authorization check config. **/
+ grpc_tls_server_authorization_check_config* c_config() const {
+ return c_config_;
+ }
+
+ private:
+ grpc_tls_server_authorization_check_config* c_config_;
+ std::shared_ptr<TlsServerAuthorizationCheckInterface>
+ server_authorization_check_interface_;
+};
+
+/** TLS credentials options, wrapper for grpc_tls_credentials_options. It is
+ * used for experimental purposes for now and it is subject to change. See the
+ * description of the grpc_tls_credentials_options struct in grpc_security.h for
+ * more details. **/
+class TlsCredentialsOptions {
+ public:
// Constructor for client.
explicit TlsCredentialsOptions(
grpc_tls_server_verification_option server_verification_option,
@@ -293,53 +293,53 @@ class TlsCredentialsOptions {
std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config);
// This constructor will be deprecated.
- TlsCredentialsOptions(
- grpc_ssl_client_certificate_request_type cert_request_type,
+ TlsCredentialsOptions(
+ grpc_ssl_client_certificate_request_type cert_request_type,
grpc_tls_server_verification_option server_verification_option,
- std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config,
- std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config,
- std::shared_ptr<TlsServerAuthorizationCheckConfig>
- server_authorization_check_config);
- ~TlsCredentialsOptions();
-
- /** Getters for member fields. **/
- grpc_ssl_client_certificate_request_type cert_request_type() const {
- return cert_request_type_;
- }
+ std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config,
+ std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config,
+ std::shared_ptr<TlsServerAuthorizationCheckConfig>
+ server_authorization_check_config);
+ ~TlsCredentialsOptions();
+
+ /** Getters for member fields. **/
+ grpc_ssl_client_certificate_request_type cert_request_type() const {
+ return cert_request_type_;
+ }
grpc_tls_server_verification_option server_verification_option() const {
return server_verification_option_;
}
- std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config() const {
- return key_materials_config_;
- }
- std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config() const {
- return credential_reload_config_;
- }
- std::shared_ptr<TlsServerAuthorizationCheckConfig>
- server_authorization_check_config() const {
- return server_authorization_check_config_;
- }
- grpc_tls_credentials_options* c_credentials_options() const {
- return c_credentials_options_;
- }
-
- private:
- /** The cert_request_type_ flag is only relevant when the
- * TlsCredentialsOptions are used to instantiate server credentials; the flag
- * goes unused when creating channel credentials, and the user can set it to
- * GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE. **/
- grpc_ssl_client_certificate_request_type cert_request_type_;
+ std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config() const {
+ return key_materials_config_;
+ }
+ std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config() const {
+ return credential_reload_config_;
+ }
+ std::shared_ptr<TlsServerAuthorizationCheckConfig>
+ server_authorization_check_config() const {
+ return server_authorization_check_config_;
+ }
+ grpc_tls_credentials_options* c_credentials_options() const {
+ return c_credentials_options_;
+ }
+
+ private:
+ /** The cert_request_type_ flag is only relevant when the
+ * TlsCredentialsOptions are used to instantiate server credentials; the flag
+ * goes unused when creating channel credentials, and the user can set it to
+ * GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE. **/
+ grpc_ssl_client_certificate_request_type cert_request_type_;
/** The server_verification_option_ flag is only relevant when the
* TlsCredentialsOptions are used to instantiate client credentials; **/
grpc_tls_server_verification_option server_verification_option_;
- std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config_;
- std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config_;
- std::shared_ptr<TlsServerAuthorizationCheckConfig>
- server_authorization_check_config_;
- grpc_tls_credentials_options* c_credentials_options_;
-};
-
-} // namespace experimental
+ std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config_;
+ std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config_;
+ std::shared_ptr<TlsServerAuthorizationCheckConfig>
+ server_authorization_check_config_;
+ grpc_tls_credentials_options* c_credentials_options_;
+};
+
+} // namespace experimental
} // namespace grpc
-
-#endif // GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
+
+#endif // GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
diff --git a/contrib/libs/grpc/include/grpcpp/support/channel_arguments.h b/contrib/libs/grpc/include/grpcpp/support/channel_arguments.h
index 85b6ee7dcc..70e7fd9988 100644
--- a/contrib/libs/grpc/include/grpcpp/support/channel_arguments.h
+++ b/contrib/libs/grpc/include/grpcpp/support/channel_arguments.h
@@ -32,7 +32,7 @@
#include <grpcpp/support/config.h>
namespace grpc {
-class SecureChannelCredentials;
+class SecureChannelCredentials;
namespace testing {
class ChannelArgumentsTest;
} // namespace testing
diff --git a/contrib/libs/grpc/include/grpcpp/support/message_allocator.h b/contrib/libs/grpc/include/grpcpp/support/message_allocator.h
index 20ce072b90..70ee0ac269 100644
--- a/contrib/libs/grpc/include/grpcpp/support/message_allocator.h
+++ b/contrib/libs/grpc/include/grpcpp/support/message_allocator.h
@@ -1,24 +1,24 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
-#define GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
-
-#include <grpcpp/impl/codegen/message_allocator.h>
-
-#endif // GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
+#define GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
+
+#include <grpcpp/impl/codegen/message_allocator.h>
+
+#endif // GRPCPP_SUPPORT_MESSAGE_ALLOCATOR_H
diff --git a/contrib/libs/grpc/include/grpcpp/support/method_handler.h b/contrib/libs/grpc/include/grpcpp/support/method_handler.h
index 038e76c8af..990d9c9e4f 100644
--- a/contrib/libs/grpc/include/grpcpp/support/method_handler.h
+++ b/contrib/libs/grpc/include/grpcpp/support/method_handler.h
@@ -1,24 +1,24 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SUPPORT_METHOD_HANDLER_H
-#define GRPCPP_SUPPORT_METHOD_HANDLER_H
-
-#include <grpcpp/impl/codegen/method_handler.h>
-
-#endif // GRPCPP_SUPPORT_METHOD_HANDLER_H
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_SUPPORT_METHOD_HANDLER_H
+#define GRPCPP_SUPPORT_METHOD_HANDLER_H
+
+#include <grpcpp/impl/codegen/method_handler.h>
+
+#endif // GRPCPP_SUPPORT_METHOD_HANDLER_H
diff --git a/contrib/libs/grpc/include/grpcpp/support/validate_service_config.h b/contrib/libs/grpc/include/grpcpp/support/validate_service_config.h
index f1368623b5..4812817ede 100644
--- a/contrib/libs/grpc/include/grpcpp/support/validate_service_config.h
+++ b/contrib/libs/grpc/include/grpcpp/support/validate_service_config.h
@@ -1,36 +1,36 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SUPPORT_VALIDATE_SERVICE_CONFIG_H
-#define GRPCPP_SUPPORT_VALIDATE_SERVICE_CONFIG_H
-
-#include <grpcpp/support/config.h>
-
-namespace grpc {
-
-namespace experimental {
-/// Validates \a service_config_json. If valid, returns an empty string.
-/// Otherwise, returns the validation error.
-/// TODO(yashykt): Promote it to out of experimental once it is proved useful
-/// and gRFC is accepted.
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_SUPPORT_VALIDATE_SERVICE_CONFIG_H
+#define GRPCPP_SUPPORT_VALIDATE_SERVICE_CONFIG_H
+
+#include <grpcpp/support/config.h>
+
+namespace grpc {
+
+namespace experimental {
+/// Validates \a service_config_json. If valid, returns an empty string.
+/// Otherwise, returns the validation error.
+/// TODO(yashykt): Promote it to out of experimental once it is proved useful
+/// and gRFC is accepted.
TString ValidateServiceConfigJSON(const TString& service_config_json);
-} // namespace experimental
-
-} // namespace grpc
-
-#endif // GRPCPP_SUPPORT_VALIDATE_SERVICE_CONFIG_H
+} // namespace experimental
+
+} // namespace grpc
+
+#endif // GRPCPP_SUPPORT_VALIDATE_SERVICE_CONFIG_H
diff --git a/contrib/libs/grpc/include/grpcpp/test/default_reactor_test_peer.h b/contrib/libs/grpc/include/grpcpp/test/default_reactor_test_peer.h
index a792e6f94a..8a237378e4 100644
--- a/contrib/libs/grpc/include/grpcpp/test/default_reactor_test_peer.h
+++ b/contrib/libs/grpc/include/grpcpp/test/default_reactor_test_peer.h
@@ -1,58 +1,58 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_TEST_DEFAULT_REACTOR_TEST_PEER_H
-#define GRPCPP_TEST_DEFAULT_REACTOR_TEST_PEER_H
-
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/server_callback.h>
-
-namespace grpc {
-namespace testing {
-
-/// A test-only class to monitor the behavior of the ServerContext's
-/// DefaultReactor. It is intended for allow unit-testing of a callback API
-/// service via direct invocation of the service methods rather than through
-/// RPCs. It is only applicable for unary RPC methods that use the
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPCPP_TEST_DEFAULT_REACTOR_TEST_PEER_H
+#define GRPCPP_TEST_DEFAULT_REACTOR_TEST_PEER_H
+
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/server_callback.h>
+
+namespace grpc {
+namespace testing {
+
+/// A test-only class to monitor the behavior of the ServerContext's
+/// DefaultReactor. It is intended for allow unit-testing of a callback API
+/// service via direct invocation of the service methods rather than through
+/// RPCs. It is only applicable for unary RPC methods that use the
/// DefaultReactor rather than any user-defined reactor. If it is used, it must
/// be created before the RPC is invoked so that it can bind the reactor into a
/// test mode rather than letting it follow the normal paths.
-class DefaultReactorTestPeer {
- public:
- explicit DefaultReactorTestPeer(experimental::CallbackServerContext* ctx)
- : DefaultReactorTestPeer(ctx, [](::grpc::Status) {}) {}
- DefaultReactorTestPeer(experimental::CallbackServerContext* ctx,
- std::function<void(::grpc::Status)> finish_func)
- : ctx_(ctx) {
- ctx->SetupTestDefaultReactor(std::move(finish_func));
- }
- ::grpc::experimental::ServerUnaryReactor* reactor() const {
+class DefaultReactorTestPeer {
+ public:
+ explicit DefaultReactorTestPeer(experimental::CallbackServerContext* ctx)
+ : DefaultReactorTestPeer(ctx, [](::grpc::Status) {}) {}
+ DefaultReactorTestPeer(experimental::CallbackServerContext* ctx,
+ std::function<void(::grpc::Status)> finish_func)
+ : ctx_(ctx) {
+ ctx->SetupTestDefaultReactor(std::move(finish_func));
+ }
+ ::grpc::experimental::ServerUnaryReactor* reactor() const {
return reinterpret_cast<experimental::ServerUnaryReactor*>(
&ctx_->default_reactor_);
- }
- bool test_status_set() const { return ctx_->test_status_set(); }
- Status test_status() const { return ctx_->test_status(); }
-
- private:
- experimental::CallbackServerContext* const ctx_; // not owned
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPCPP_TEST_DEFAULT_REACTOR_TEST_PEER_H
+ }
+ bool test_status_set() const { return ctx_->test_status_set(); }
+ Status test_status() const { return ctx_->test_status(); }
+
+ private:
+ experimental::CallbackServerContext* const ctx_; // not owned
+};
+
+} // namespace testing
+} // namespace grpc
+
+#endif // GRPCPP_TEST_DEFAULT_REACTOR_TEST_PEER_H
diff --git a/contrib/libs/grpc/include/grpcpp/test/mock_stream.h b/contrib/libs/grpc/include/grpcpp/test/mock_stream.h
index e33595d709..24bbffa190 100644
--- a/contrib/libs/grpc/include/grpcpp/test/mock_stream.h
+++ b/contrib/libs/grpc/include/grpcpp/test/mock_stream.h
@@ -62,7 +62,7 @@ class MockClientWriter : public ::grpc::ClientWriterInterface<W> {
};
template <class W, class R>
-class MockClientReaderWriter
+class MockClientReaderWriter
: public ::grpc::ClientReaderWriterInterface<W, R> {
public:
MockClientReaderWriter() = default;
diff --git a/contrib/libs/grpc/include/grpcpp/test/server_context_test_spouse.h b/contrib/libs/grpc/include/grpcpp/test/server_context_test_spouse.h
index 00c19dc4b8..775920c597 100644
--- a/contrib/libs/grpc/include/grpcpp/test/server_context_test_spouse.h
+++ b/contrib/libs/grpc/include/grpcpp/test/server_context_test_spouse.h
@@ -37,11 +37,11 @@ class ServerContextTestSpouse {
client_metadata_storage_.insert(
std::pair<TString, TString>(key, value));
ctx_->client_metadata_.map()->clear();
- for (const auto& item : client_metadata_storage_) {
+ for (const auto& item : client_metadata_storage_) {
ctx_->client_metadata_.map()->insert(
std::pair<grpc::string_ref, grpc::string_ref>(
- item.first.c_str(),
- grpc::string_ref(item.second.data(), item.second.size())));
+ item.first.c_str(),
+ grpc::string_ref(item.second.data(), item.second.size())));
}
}
diff --git a/contrib/libs/grpc/src/compiler/config.h b/contrib/libs/grpc/src/compiler/config.h
index 95213b0f04..b115a2c0d0 100644
--- a/contrib/libs/grpc/src/compiler/config.h
+++ b/contrib/libs/grpc/src/compiler/config.h
@@ -19,7 +19,7 @@
#ifndef SRC_COMPILER_CONFIG_H
#define SRC_COMPILER_CONFIG_H
-#include "src/compiler/config_protobuf.h"
+#include "src/compiler/config_protobuf.h"
#include <util/generic/string.h>
diff --git a/contrib/libs/grpc/src/compiler/config_protobuf.h b/contrib/libs/grpc/src/compiler/config_protobuf.h
index 06d5073f43..8fea46be9d 100644
--- a/contrib/libs/grpc/src/compiler/config_protobuf.h
+++ b/contrib/libs/grpc/src/compiler/config_protobuf.h
@@ -1,52 +1,52 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef SRC_COMPILER_CONFIG_PROTOBUF_H
-#define SRC_COMPILER_CONFIG_PROTOBUF_H
-
-#include <grpcpp/impl/codegen/config_protobuf.h>
-
-#ifndef GRPC_CUSTOM_CODEGENERATOR
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef SRC_COMPILER_CONFIG_PROTOBUF_H
+#define SRC_COMPILER_CONFIG_PROTOBUF_H
+
+#include <grpcpp/impl/codegen/config_protobuf.h>
+
+#ifndef GRPC_CUSTOM_CODEGENERATOR
#include <google/protobuf/compiler/code_generator.h>
-#define GRPC_CUSTOM_CODEGENERATOR ::google::protobuf::compiler::CodeGenerator
-#define GRPC_CUSTOM_GENERATORCONTEXT \
- ::google::protobuf::compiler::GeneratorContext
-#endif
-
-#ifndef GRPC_CUSTOM_PRINTER
+#define GRPC_CUSTOM_CODEGENERATOR ::google::protobuf::compiler::CodeGenerator
+#define GRPC_CUSTOM_GENERATORCONTEXT \
+ ::google::protobuf::compiler::GeneratorContext
+#endif
+
+#ifndef GRPC_CUSTOM_PRINTER
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
-#define GRPC_CUSTOM_PRINTER ::google::protobuf::io::Printer
-#define GRPC_CUSTOM_CODEDOUTPUTSTREAM ::google::protobuf::io::CodedOutputStream
-#define GRPC_CUSTOM_STRINGOUTPUTSTREAM \
- ::google::protobuf::io::StringOutputStream
-#endif
-
-#ifndef GRPC_CUSTOM_PLUGINMAIN
+#define GRPC_CUSTOM_PRINTER ::google::protobuf::io::Printer
+#define GRPC_CUSTOM_CODEDOUTPUTSTREAM ::google::protobuf::io::CodedOutputStream
+#define GRPC_CUSTOM_STRINGOUTPUTSTREAM \
+ ::google::protobuf::io::StringOutputStream
+#endif
+
+#ifndef GRPC_CUSTOM_PLUGINMAIN
#include <google/protobuf/compiler/plugin.h>
-#define GRPC_CUSTOM_PLUGINMAIN ::google::protobuf::compiler::PluginMain
-#endif
-
-#ifndef GRPC_CUSTOM_PARSEGENERATORPARAMETER
+#define GRPC_CUSTOM_PLUGINMAIN ::google::protobuf::compiler::PluginMain
+#endif
+
+#ifndef GRPC_CUSTOM_PARSEGENERATORPARAMETER
#include <google/protobuf/compiler/code_generator.h>
-#define GRPC_CUSTOM_PARSEGENERATORPARAMETER \
- ::google::protobuf::compiler::ParseGeneratorParameter
-#endif
-
-#endif // SRC_COMPILER_CONFIG_PROTOBUF_H
+#define GRPC_CUSTOM_PARSEGENERATORPARAMETER \
+ ::google::protobuf::compiler::ParseGeneratorParameter
+#endif
+
+#endif // SRC_COMPILER_CONFIG_PROTOBUF_H
diff --git a/contrib/libs/grpc/src/compiler/cpp_generator.cc b/contrib/libs/grpc/src/compiler/cpp_generator.cc
index 5759177474..363fb5f6cb 100644
--- a/contrib/libs/grpc/src/compiler/cpp_generator.cc
+++ b/contrib/libs/grpc/src/compiler/cpp_generator.cc
@@ -96,9 +96,9 @@ TString GetHeaderPrologue(grpc_generator::File* file,
vars["filename"] = file->filename();
vars["filename_identifier"] = FilenameIdentifier(file->filename());
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = params.message_header_extension.empty()
- ? kCppGeneratorMessageHeaderExt
- : params.message_header_extension;
+ vars["message_header_ext"] = params.message_header_extension.empty()
+ ? kCppGeneratorMessageHeaderExt
+ : params.message_header_extension;
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
@@ -123,13 +123,13 @@ TString GetHeaderPrologue(grpc_generator::File* file,
return output;
}
-// Convert from "a/b/c.proto" to "#include \"a/b/c$message_header_ext$\"\n"
+// Convert from "a/b/c.proto" to "#include \"a/b/c$message_header_ext$\"\n"
TString ImportInludeFromProtoName(const TString& proto_name) {
return TString("#include \"") +
- proto_name.substr(0, proto_name.size() - 6) +
+ proto_name.substr(0, proto_name.size() - 6) +
TString("$message_header_ext$\"\n");
-}
-
+}
+
TString GetHeaderIncludes(grpc_generator::File* file,
const Parameters& params) {
TString output;
@@ -152,38 +152,38 @@ TString GetHeaderIncludes(grpc_generator::File* file,
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/async_unary_call.h",
"grpcpp/impl/codegen/client_callback.h",
- "grpcpp/impl/codegen/client_context.h",
- "grpcpp/impl/codegen/completion_queue.h",
+ "grpcpp/impl/codegen/client_context.h",
+ "grpcpp/impl/codegen/completion_queue.h",
"grpcpp/impl/codegen/message_allocator.h",
- "grpcpp/impl/codegen/method_handler.h",
+ "grpcpp/impl/codegen/method_handler.h",
"grpcpp/impl/codegen/proto_utils.h",
"grpcpp/impl/codegen/rpc_method.h",
"grpcpp/impl/codegen/server_callback.h",
- "grpcpp/impl/codegen/server_callback_handlers.h",
- "grpcpp/impl/codegen/server_context.h",
+ "grpcpp/impl/codegen/server_callback_handlers.h",
+ "grpcpp/impl/codegen/server_context.h",
"grpcpp/impl/codegen/service_type.h",
"grpcpp/impl/codegen/status.h",
"grpcpp/impl/codegen/stub_options.h",
- "grpcpp/impl/codegen/sync_stream.h",
- };
+ "grpcpp/impl/codegen/sync_stream.h",
+ };
std::vector<TString> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params.use_system_headers,
params.grpc_search_path);
printer->Print(vars, "\n");
- vars["message_header_ext"] = params.message_header_extension.empty()
- ? kCppGeneratorMessageHeaderExt
- : params.message_header_extension;
-
- if (params.include_import_headers) {
+ vars["message_header_ext"] = params.message_header_extension.empty()
+ ? kCppGeneratorMessageHeaderExt
+ : params.message_header_extension;
+
+ if (params.include_import_headers) {
const std::vector<TString> import_names = file->GetImportNames();
- for (const auto& import_name : import_names) {
+ for (const auto& import_name : import_names) {
const TString include_name = ImportInludeFromProtoName(import_name);
- printer->Print(vars, include_name.c_str());
- }
- printer->PrintRaw("\n");
- }
-
+ printer->Print(vars, include_name.c_str());
+ }
+ printer->PrintRaw("\n");
+ }
+
if (!file->package().empty()) {
std::vector<TString> parts = file->package_parts();
@@ -612,10 +612,10 @@ void PrintHeaderClientMethodCallbackInterfaces(
"std::function<void(::grpc::Status)>) = 0;\n");
// TODO(vjpai): Remove experimental versions and macros when callback API is
// fully de-experimentalized.
- printer->Print(*vars,
+ printer->Print(*vars,
"#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"
- "virtual void $Method$(::grpc::ClientContext* context, "
- "const $Request$* request, $Response$* response, "
+ "virtual void $Method$(::grpc::ClientContext* context, "
+ "const $Request$* request, $Response$* response, "
"::grpc::ClientUnaryReactor* reactor) = 0;\n"
"#else\n"
"virtual void $Method$(::grpc::ClientContext* context, "
@@ -708,11 +708,11 @@ void PrintHeaderClientMethodCallback(grpc_generator::Printer* printer,
"void $Method$(::grpc::ClientContext* context, "
"const $Request$* request, $Response$* response, "
"std::function<void(::grpc::Status)>) override;\n");
- printer->Print(
- *vars,
+ printer->Print(
+ *vars,
"#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"
- "void $Method$(::grpc::ClientContext* context, "
- "const $Request$* request, $Response$* response, "
+ "void $Method$(::grpc::ClientContext* context, "
+ "const $Request$* request, $Response$* response, "
"::grpc::ClientUnaryReactor* reactor) override;\n"
"#else\n"
"void $Method$(::grpc::ClientContext* context, "
@@ -833,8 +833,8 @@ void PrintHeaderServerAsyncMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -854,9 +854,9 @@ void PrintHeaderServerAsyncMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, "
- "::grpc::ServerReader< $Request$>* /*reader*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -876,8 +876,8 @@ void PrintHeaderServerAsyncMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "::grpc::ServerWriter< $Response$>* /*writer*/) override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -899,8 +899,8 @@ void PrintHeaderServerAsyncMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
" override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -935,8 +935,8 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer,
"class WithAsyncMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -963,19 +963,19 @@ void PrintHeaderServerCallbackMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
- printer->Print(*vars,
+ printer->Print(*vars,
"#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"
"virtual ::grpc::ServerUnaryReactor* $Method$(\n"
" ::grpc::CallbackServerContext* /*context*/, "
"const $RealRequest$* /*request*/, "
"$RealResponse$* /*response*/)\n"
"#else\n"
- "virtual ::grpc::experimental::ServerUnaryReactor* "
+ "virtual ::grpc::experimental::ServerUnaryReactor* "
"$Method$(\n"
" ::grpc::experimental::CallbackServerContext* "
"/*context*/, const $RealRequest$* /*request*/, "
@@ -987,9 +987,9 @@ void PrintHeaderServerCallbackMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, "
- "::grpc::ServerReader< $Request$>* /*reader*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -1011,14 +1011,14 @@ void PrintHeaderServerCallbackMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "::grpc::ServerWriter< $Response$>* /*writer*/) override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
- printer->Print(
- *vars,
+ printer->Print(
+ *vars,
"#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"
"virtual ::grpc::ServerWriteReactor< $RealResponse$>* $Method$(\n"
" ::grpc::CallbackServerContext* "
@@ -1035,21 +1035,21 @@ void PrintHeaderServerCallbackMethodsHelper(
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
" override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
- printer->Print(
- *vars,
+ printer->Print(
+ *vars,
"#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"
"virtual ::grpc::ServerBidiReactor< $RealRequest$, $RealResponse$>* "
"$Method$(\n"
" ::grpc::CallbackServerContext* /*context*/)\n"
"#else\n"
- "virtual ::grpc::experimental::ServerBidiReactor< "
- "$RealRequest$, $RealResponse$>* "
+ "virtual ::grpc::experimental::ServerBidiReactor< "
+ "$RealRequest$, $RealResponse$>* "
"$Method$(\n"
" ::grpc::experimental::CallbackServerContext* /*context*/)\n"
"#endif\n"
@@ -1073,8 +1073,8 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer,
"class ExperimentalWithCallbackMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars, "ExperimentalWithCallbackMethod_$Method$() {\n");
@@ -1096,14 +1096,14 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer,
" ::grpc::experimental::CallbackServerContext*\n"
"#endif\n"
" context, "
- "const $RealRequest$* "
- "request, "
- "$RealResponse$* response) { "
- "return this->$Method$(context, request, response); }));}\n");
- printer->Print(*vars,
- "void SetMessageAllocatorFor_$Method$(\n"
- " ::grpc::experimental::MessageAllocator< "
- "$RealRequest$, $RealResponse$>* allocator) {\n"
+ "const $RealRequest$* "
+ "request, "
+ "$RealResponse$* response) { "
+ "return this->$Method$(context, request, response); }));}\n");
+ printer->Print(*vars,
+ "void SetMessageAllocatorFor_$Method$(\n"
+ " ::grpc::experimental::MessageAllocator< "
+ "$RealRequest$, $RealResponse$>* allocator) {\n"
"#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"
" ::grpc::internal::MethodHandler* const handler = "
"::grpc::Service::GetHandler($Idx$);\n"
@@ -1113,7 +1113,7 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer,
"#endif\n"
" static_cast<::grpc::internal::CallbackUnaryHandler< "
"$RealRequest$, $RealResponse$>*>(handler)\n"
- " ->SetMessageAllocator(allocator);\n");
+ " ->SetMessageAllocator(allocator);\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
@@ -1132,9 +1132,9 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer,
" ::grpc::experimental::CallbackServerContext*\n"
"#endif\n"
" context, "
- "$RealResponse$* "
- "response) { "
- "return this->$Method$(context, response); }));\n");
+ "$RealResponse$* "
+ "response) { "
+ "return this->$Method$(context, response); }));\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
@@ -1153,9 +1153,9 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer,
" ::grpc::experimental::CallbackServerContext*\n"
"#endif\n"
" context, "
- "const $RealRequest$* "
- "request) { "
- "return this->$Method$(context, request); }));\n");
+ "const $RealRequest$* "
+ "request) { "
+ "return this->$Method$(context, request); }));\n");
} else if (method->BidiStreaming()) {
printer->Print(
*vars,
@@ -1202,8 +1202,8 @@ void PrintHeaderServerMethodRawCallback(
"BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars, "ExperimentalWithRawCallbackMethod_$Method$() {\n");
@@ -1225,10 +1225,10 @@ void PrintHeaderServerMethodRawCallback(
" ::grpc::experimental::CallbackServerContext*\n"
"#endif\n"
" context, "
- "const $RealRequest$* "
- "request, "
- "$RealResponse$* response) { return "
- "this->$Method$(context, request, response); }));\n");
+ "const $RealRequest$* "
+ "request, "
+ "$RealResponse$* response) { return "
+ "this->$Method$(context, request, response); }));\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
@@ -1247,8 +1247,8 @@ void PrintHeaderServerMethodRawCallback(
" ::grpc::experimental::CallbackServerContext*\n"
"#endif\n"
" context, "
- "$RealResponse$* response) "
- "{ return this->$Method$(context, response); }));\n");
+ "$RealResponse$* response) "
+ "{ return this->$Method$(context, response); }));\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
@@ -1267,9 +1267,9 @@ void PrintHeaderServerMethodRawCallback(
" ::grpc::experimental::CallbackServerContext*\n"
"#endif\n"
" context, "
- "const"
- "$RealRequest$* request) { return "
- "this->$Method$(context, request); }));\n");
+ "const"
+ "$RealRequest$* request) { return "
+ "this->$Method$(context, request); }));\n");
} else if (method->BidiStreaming()) {
printer->Print(
*vars,
@@ -1313,7 +1313,7 @@ void PrintHeaderServerMethodStreamedUnary(
"public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
"{}\n");
printer->Print(" public:\n");
printer->Indent();
@@ -1337,8 +1337,8 @@ void PrintHeaderServerMethodStreamedUnary(
*vars,
"// disable regular version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -1367,7 +1367,7 @@ void PrintHeaderServerMethodSplitStreaming(
"public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
"{}\n");
printer->Print(" public:\n");
printer->Indent();
@@ -1391,8 +1391,8 @@ void PrintHeaderServerMethodSplitStreaming(
*vars,
"// disable regular version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "::grpc::ServerWriter< $Response$>* /*writer*/) override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -1420,8 +1420,8 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
"class WithGenericMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -1437,8 +1437,8 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -1447,9 +1447,9 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, "
- "::grpc::ServerReader< $Request$>* /*reader*/, "
- "$Response$* /*response*/) override {\n"
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReader< $Request$>* /*reader*/, "
+ "$Response$* /*response*/) override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
@@ -1458,8 +1458,8 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
- "::grpc::ServerWriter< $Response$>* /*writer*/) override "
+ "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, "
+ "::grpc::ServerWriter< $Response$>* /*writer*/) override "
"{\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -1469,8 +1469,8 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
*vars,
"// disable synchronous version of this method\n"
"::grpc::Status $Method$("
- "::grpc::ServerContext* /*context*/, "
- "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
+ "::grpc::ServerContext* /*context*/, "
+ "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) "
" override {\n"
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
@@ -1494,8 +1494,8 @@ void PrintHeaderServerMethodRaw(grpc_generator::Printer* printer,
printer->Print(*vars, "class WithRawMethod_$Method$ : public BaseClass {\n");
printer->Print(
" private:\n"
- " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
- "{}\n");
+ " void BaseClassMustBeDerivedFromService(const Service* /*service*/) "
+ "{}\n");
printer->Print(" public:\n");
printer->Indent();
printer->Print(*vars,
@@ -1544,7 +1544,7 @@ void PrintHeaderService(grpc_generator::Printer* printer,
for (int i = 0; i < service->method_count(); ++i) {
printer->Print(service->method(i)->GetLeadingComments("//").c_str());
PrintHeaderClientMethodCallbackInterfaces(printer, service->method(i).get(),
- vars);
+ vars);
printer->Print(service->method(i)->GetTrailingComments("//").c_str());
}
PrintHeaderClientMethodCallbackInterfacesEnd(printer, vars);
@@ -1569,7 +1569,7 @@ void PrintHeaderService(grpc_generator::Printer* printer,
}
PrintHeaderClientMethodCallbackStart(printer, vars);
for (int i = 0; i < service->method_count(); ++i) {
- PrintHeaderClientMethodCallback(printer, service->method(i).get(), vars);
+ PrintHeaderClientMethodCallback(printer, service->method(i).get(), vars);
}
PrintHeaderClientMethodCallbackEnd(printer, vars);
printer->Outdent();
@@ -1816,9 +1816,9 @@ TString GetSourcePrologue(grpc_generator::File* file,
vars["filename"] = file->filename();
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = params.message_header_extension.empty()
- ? kCppGeneratorMessageHeaderExt
- : params.message_header_extension;
+ vars["message_header_ext"] = params.message_header_extension.empty()
+ ? kCppGeneratorMessageHeaderExt
+ : params.message_header_extension;
vars["service_header_ext"] = kCppGeneratorServiceHeaderExt;
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
@@ -1848,11 +1848,11 @@ TString GetSourceIncludes(grpc_generator::File* file,
"grpcpp/impl/codegen/client_unary_call.h",
"grpcpp/impl/codegen/client_callback.h",
"grpcpp/impl/codegen/message_allocator.h",
- "grpcpp/impl/codegen/method_handler.h",
+ "grpcpp/impl/codegen/method_handler.h",
"grpcpp/impl/codegen/rpc_service_method.h",
"grpcpp/impl/codegen/server_callback.h",
- "grpcpp/impl/codegen/server_callback_handlers.h",
- "grpcpp/impl/codegen/server_context.h",
+ "grpcpp/impl/codegen/server_callback_handlers.h",
+ "grpcpp/impl/codegen/server_context.h",
"grpcpp/impl/codegen/service_type.h",
"grpcpp/impl/codegen/sync_stream.h"};
std::vector<TString> headers(headers_strs, array_end(headers_strs));
@@ -1906,23 +1906,23 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"(stub_->channel_.get(), stub_->rpcmethod_$Method$_, "
"context, request, response, std::move(f));\n}\n\n");
- printer->Print(*vars,
- "void $ns$$Service$::Stub::experimental_async::$Method$("
- "::grpc::ClientContext* context, "
- "const $Request$* request, $Response$* response, "
- "::grpc::experimental::ClientUnaryReactor* reactor) {\n");
- printer->Print(*vars,
+ printer->Print(*vars,
+ "void $ns$$Service$::Stub::experimental_async::$Method$("
+ "::grpc::ClientContext* context, "
+ "const $Request$* request, $Response$* response, "
+ "::grpc::experimental::ClientUnaryReactor* reactor) {\n");
+ printer->Print(*vars,
" ::grpc::internal::ClientCallbackUnaryFactory::Create"
- "(stub_->channel_.get(), stub_->rpcmethod_$Method$_, "
- "context, request, response, reactor);\n}\n\n");
-
- printer->Print(*vars,
+ "(stub_->channel_.get(), stub_->rpcmethod_$Method$_, "
+ "context, request, response, reactor);\n}\n\n");
+
+ printer->Print(*vars,
"::grpc::ClientAsyncResponseReader< $Response$>* "
"$ns$$Service$::Stub::PrepareAsync$Method$Raw(::grpc::"
"ClientContext* context, "
"const $Request$& request, "
"::grpc::CompletionQueue* cq) {\n");
- printer->Print(*vars,
+ printer->Print(*vars,
" return "
"::grpc::internal::ClientAsyncResponseReaderFactory"
"< $Response$>::Create(channel_.get(), cq, "
@@ -1946,13 +1946,13 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"::grpc::ClientWriter< $Request$>* "
"$ns$$Service$::Stub::$Method$Raw("
"::grpc::ClientContext* context, $Response$* response) {\n");
- printer->Print(*vars,
+ printer->Print(*vars,
" return ::grpc::internal::ClientWriterFactory< "
- "$Request$>::Create("
- "channel_.get(), "
- "rpcmethod_$Method$_, "
- "context, response);\n"
- "}\n\n");
+ "$Request$>::Create("
+ "channel_.get(), "
+ "rpcmethod_$Method$_, "
+ "context, response);\n"
+ "}\n\n");
printer->Print(
*vars,
@@ -1992,13 +1992,13 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"::grpc::ClientReader< $Response$>* "
"$ns$$Service$::Stub::$Method$Raw("
"::grpc::ClientContext* context, const $Request$& request) {\n");
- printer->Print(*vars,
+ printer->Print(*vars,
" return ::grpc::internal::ClientReaderFactory< "
- "$Response$>::Create("
- "channel_.get(), "
- "rpcmethod_$Method$_, "
- "context, request);\n"
- "}\n\n");
+ "$Response$>::Create("
+ "channel_.get(), "
+ "rpcmethod_$Method$_, "
+ "context, request);\n"
+ "}\n\n");
printer->Print(
*vars,
@@ -2336,9 +2336,9 @@ TString GetMockPrologue(grpc_generator::File* file,
vars["filename"] = file->filename();
vars["filename_base"] = file->filename_without_ext();
- vars["message_header_ext"] = params.message_header_extension.empty()
- ? kCppGeneratorMessageHeaderExt
- : params.message_header_extension;
+ vars["message_header_ext"] = params.message_header_extension.empty()
+ ? kCppGeneratorMessageHeaderExt
+ : params.message_header_extension;
vars["service_header_ext"] = kCppGeneratorServiceHeaderExt;
printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
@@ -2348,14 +2348,14 @@ TString GetMockPrologue(grpc_generator::File* file,
printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n");
printer->Print(vars, "#include \"$filename_base$$service_header_ext$\"\n");
- if (params.include_import_headers) {
+ if (params.include_import_headers) {
const std::vector<TString> import_names = file->GetImportNames();
- for (const auto& import_name : import_names) {
+ for (const auto& import_name : import_names) {
const TString include_name = ImportInludeFromProtoName(import_name);
- printer->Print(vars, include_name.c_str());
- }
- printer->PrintRaw("\n");
- }
+ printer->Print(vars, include_name.c_str());
+ }
+ printer->PrintRaw("\n");
+ }
printer->Print(vars, file->additional_headers().c_str());
printer->Print(vars, "\n");
}
@@ -2481,8 +2481,8 @@ void PrintMockClientMethods(grpc_generator::Printer* printer,
printer->Print(
*vars,
"MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
- "::grpc::ClientAsyncReaderWriterInterface<$Request$, "
- "$Response$>*"
+ "::grpc::ClientAsyncReaderWriterInterface<$Request$, "
+ "$Response$>*"
"(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq"
"$AsyncMethodParams$));\n");
}
diff --git a/contrib/libs/grpc/src/compiler/cpp_generator.h b/contrib/libs/grpc/src/compiler/cpp_generator.h
index 606b850a87..07166e4a1c 100644
--- a/contrib/libs/grpc/src/compiler/cpp_generator.h
+++ b/contrib/libs/grpc/src/compiler/cpp_generator.h
@@ -59,10 +59,10 @@ struct Parameters {
TString gmock_search_path;
// *EXPERIMENTAL* Additional include files in grpc.pb.h
std::vector<TString> additional_header_includes;
- // By default, use "pb.h"
+ // By default, use "pb.h"
TString message_header_extension;
- // Whether to include headers corresponding to imports in source file.
- bool include_import_headers;
+ // Whether to include headers corresponding to imports in source file.
+ bool include_import_headers;
};
// Return the prologue of the generated header file.
diff --git a/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h b/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h
index 2e34d53a65..773f6501c0 100644
--- a/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h
@@ -52,7 +52,7 @@ inline TString ClassName(const grpc::protobuf::Descriptor* descriptor,
}
// Get leading or trailing comments in a string. Comment lines start with "// ".
-// Leading detached comments are put in front of leading comments.
+// Leading detached comments are put in front of leading comments.
template <typename DescriptorType>
inline TString GetCppComments(const DescriptorType* desc, bool leading) {
return grpc_generator::GetPrefixedComments(desc, leading, "//");
diff --git a/contrib/libs/grpc/src/compiler/cpp_plugin.cc b/contrib/libs/grpc/src/compiler/cpp_plugin.cc
index 2de2745445..a234b1be70 100644
--- a/contrib/libs/grpc/src/compiler/cpp_plugin.cc
+++ b/contrib/libs/grpc/src/compiler/cpp_plugin.cc
@@ -18,7 +18,7 @@
// Generates cpp gRPC service interface out of Protobuf IDL.
//
-#include "src/compiler/cpp_plugin.h"
+#include "src/compiler/cpp_plugin.h"
int main(int argc, char* argv[]) {
CppGrpcGenerator generator;
diff --git a/contrib/libs/grpc/src/compiler/cpp_plugin.h b/contrib/libs/grpc/src/compiler/cpp_plugin.h
index 0c289a7395..f0044a2e08 100644
--- a/contrib/libs/grpc/src/compiler/cpp_plugin.h
+++ b/contrib/libs/grpc/src/compiler/cpp_plugin.h
@@ -1,158 +1,158 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_INTERNAL_COMPILER_CPP_PLUGIN_H
-#define GRPC_INTERNAL_COMPILER_CPP_PLUGIN_H
-
-#include <memory>
-#include <sstream>
-
-#include "src/compiler/config.h"
-
-#include "src/compiler/cpp_generator.h"
-#include "src/compiler/generator_helpers.h"
-#include "src/compiler/protobuf_plugin.h"
-
-// Cpp Generator for Protobug IDL
-class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
- public:
- CppGrpcGenerator() {}
- virtual ~CppGrpcGenerator() {}
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_INTERNAL_COMPILER_CPP_PLUGIN_H
+#define GRPC_INTERNAL_COMPILER_CPP_PLUGIN_H
+
+#include <memory>
+#include <sstream>
+
+#include "src/compiler/config.h"
+
+#include "src/compiler/cpp_generator.h"
+#include "src/compiler/generator_helpers.h"
+#include "src/compiler/protobuf_plugin.h"
+
+// Cpp Generator for Protobug IDL
+class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
+ public:
+ CppGrpcGenerator() {}
+ virtual ~CppGrpcGenerator() {}
+
uint64_t GetSupportedFeatures() const override {
return FEATURE_PROTO3_OPTIONAL;
}
- virtual bool Generate(const grpc::protobuf::FileDescriptor* file,
+ virtual bool Generate(const grpc::protobuf::FileDescriptor* file,
const TString& parameter,
- grpc::protobuf::compiler::GeneratorContext* context,
+ grpc::protobuf::compiler::GeneratorContext* context,
TString* error) const override {
- if (file->options().cc_generic_services()) {
- *error =
- "cpp grpc proto compiler plugin does not work with generic "
- "services. To generate cpp grpc APIs, please set \""
- "cc_generic_service = false\".";
- return false;
- }
-
- grpc_cpp_generator::Parameters generator_parameters;
- generator_parameters.use_system_headers = true;
- generator_parameters.generate_mock_code = false;
- generator_parameters.include_import_headers = false;
-
- ProtoBufFile pbfile(file);
-
- if (!parameter.empty()) {
+ if (file->options().cc_generic_services()) {
+ *error =
+ "cpp grpc proto compiler plugin does not work with generic "
+ "services. To generate cpp grpc APIs, please set \""
+ "cc_generic_service = false\".";
+ return false;
+ }
+
+ grpc_cpp_generator::Parameters generator_parameters;
+ generator_parameters.use_system_headers = true;
+ generator_parameters.generate_mock_code = false;
+ generator_parameters.include_import_headers = false;
+
+ ProtoBufFile pbfile(file);
+
+ if (!parameter.empty()) {
std::vector<TString> parameters_list =
- grpc_generator::tokenize(parameter, ",");
- for (auto parameter_string = parameters_list.begin();
- parameter_string != parameters_list.end(); parameter_string++) {
+ grpc_generator::tokenize(parameter, ",");
+ for (auto parameter_string = parameters_list.begin();
+ parameter_string != parameters_list.end(); parameter_string++) {
std::vector<TString> param =
- grpc_generator::tokenize(*parameter_string, "=");
- if (param[0] == "services_namespace") {
- generator_parameters.services_namespace = param[1];
- } else if (param[0] == "use_system_headers") {
- if (param[1] == "true") {
- generator_parameters.use_system_headers = true;
- } else if (param[1] == "false") {
- generator_parameters.use_system_headers = false;
- } else {
+ grpc_generator::tokenize(*parameter_string, "=");
+ if (param[0] == "services_namespace") {
+ generator_parameters.services_namespace = param[1];
+ } else if (param[0] == "use_system_headers") {
+ if (param[1] == "true") {
+ generator_parameters.use_system_headers = true;
+ } else if (param[1] == "false") {
+ generator_parameters.use_system_headers = false;
+ } else {
*error = TString("Invalid parameter: ") + *parameter_string;
- return false;
- }
- } else if (param[0] == "grpc_search_path") {
- generator_parameters.grpc_search_path = param[1];
- } else if (param[0] == "generate_mock_code") {
- if (param[1] == "true") {
- generator_parameters.generate_mock_code = true;
- } else if (param[1] != "false") {
+ return false;
+ }
+ } else if (param[0] == "grpc_search_path") {
+ generator_parameters.grpc_search_path = param[1];
+ } else if (param[0] == "generate_mock_code") {
+ if (param[1] == "true") {
+ generator_parameters.generate_mock_code = true;
+ } else if (param[1] != "false") {
*error = TString("Invalid parameter: ") + *parameter_string;
- return false;
- }
- } else if (param[0] == "gmock_search_path") {
- generator_parameters.gmock_search_path = param[1];
- } else if (param[0] == "additional_header_includes") {
- generator_parameters.additional_header_includes =
- grpc_generator::tokenize(param[1], ":");
- } else if (param[0] == "message_header_extension") {
- generator_parameters.message_header_extension = param[1];
- } else if (param[0] == "include_import_headers") {
- if (param[1] == "true") {
- generator_parameters.include_import_headers = true;
- } else if (param[1] != "false") {
+ return false;
+ }
+ } else if (param[0] == "gmock_search_path") {
+ generator_parameters.gmock_search_path = param[1];
+ } else if (param[0] == "additional_header_includes") {
+ generator_parameters.additional_header_includes =
+ grpc_generator::tokenize(param[1], ":");
+ } else if (param[0] == "message_header_extension") {
+ generator_parameters.message_header_extension = param[1];
+ } else if (param[0] == "include_import_headers") {
+ if (param[1] == "true") {
+ generator_parameters.include_import_headers = true;
+ } else if (param[1] != "false") {
*error = TString("Invalid parameter: ") + *parameter_string;
- return false;
- }
- } else {
+ return false;
+ }
+ } else {
*error = TString("Unknown parameter: ") + *parameter_string;
- return false;
- }
- }
- }
-
+ return false;
+ }
+ }
+ }
+
TString file_name = grpc_generator::StripProto(file->name());
-
+
TString header_code =
- grpc_cpp_generator::GetHeaderPrologue(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetHeaderIncludes(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetHeaderServices(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetHeaderEpilogue(&pbfile, generator_parameters);
- std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> header_output(
- context->Open(file_name + ".grpc.pb.h"));
- grpc::protobuf::io::CodedOutputStream header_coded_out(header_output.get());
- header_coded_out.WriteRaw(header_code.data(), header_code.size());
-
+ grpc_cpp_generator::GetHeaderPrologue(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetHeaderIncludes(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetHeaderServices(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetHeaderEpilogue(&pbfile, generator_parameters);
+ std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> header_output(
+ context->Open(file_name + ".grpc.pb.h"));
+ grpc::protobuf::io::CodedOutputStream header_coded_out(header_output.get());
+ header_coded_out.WriteRaw(header_code.data(), header_code.size());
+
TString source_code =
- grpc_cpp_generator::GetSourcePrologue(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetSourceIncludes(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetSourceServices(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetSourceEpilogue(&pbfile, generator_parameters);
- std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> source_output(
- context->Open(file_name + ".grpc.pb.cc"));
- grpc::protobuf::io::CodedOutputStream source_coded_out(source_output.get());
- source_coded_out.WriteRaw(source_code.data(), source_code.size());
-
- if (!generator_parameters.generate_mock_code) {
- return true;
- }
+ grpc_cpp_generator::GetSourcePrologue(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetSourceIncludes(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetSourceServices(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetSourceEpilogue(&pbfile, generator_parameters);
+ std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> source_output(
+ context->Open(file_name + ".grpc.pb.cc"));
+ grpc::protobuf::io::CodedOutputStream source_coded_out(source_output.get());
+ source_coded_out.WriteRaw(source_code.data(), source_code.size());
+
+ if (!generator_parameters.generate_mock_code) {
+ return true;
+ }
TString mock_code =
- grpc_cpp_generator::GetMockPrologue(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetMockIncludes(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetMockServices(&pbfile, generator_parameters) +
- grpc_cpp_generator::GetMockEpilogue(&pbfile, generator_parameters);
- std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> mock_output(
- context->Open(file_name + "_mock.grpc.pb.h"));
- grpc::protobuf::io::CodedOutputStream mock_coded_out(mock_output.get());
- mock_coded_out.WriteRaw(mock_code.data(), mock_code.size());
-
- return true;
- }
-
- private:
- // Insert the given code into the given file at the given insertion point.
- void Insert(grpc::protobuf::compiler::GeneratorContext* context,
+ grpc_cpp_generator::GetMockPrologue(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetMockIncludes(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetMockServices(&pbfile, generator_parameters) +
+ grpc_cpp_generator::GetMockEpilogue(&pbfile, generator_parameters);
+ std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> mock_output(
+ context->Open(file_name + "_mock.grpc.pb.h"));
+ grpc::protobuf::io::CodedOutputStream mock_coded_out(mock_output.get());
+ mock_coded_out.WriteRaw(mock_code.data(), mock_code.size());
+
+ return true;
+ }
+
+ private:
+ // Insert the given code into the given file at the given insertion point.
+ void Insert(grpc::protobuf::compiler::GeneratorContext* context,
const TString& filename, const TString& insertion_point,
const TString& code) const {
- std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
- context->OpenForInsert(filename, insertion_point));
- grpc::protobuf::io::CodedOutputStream coded_out(output.get());
- coded_out.WriteRaw(code.data(), code.size());
- }
-};
-
-#endif // GRPC_INTERNAL_COMPILER_CPP_PLUGIN_H
+ std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
+ context->OpenForInsert(filename, insertion_point));
+ grpc::protobuf::io::CodedOutputStream coded_out(output.get());
+ coded_out.WriteRaw(code.data(), code.size());
+ }
+};
+
+#endif // GRPC_INTERNAL_COMPILER_CPP_PLUGIN_H
diff --git a/contrib/libs/grpc/src/compiler/csharp_generator.cc b/contrib/libs/grpc/src/compiler/csharp_generator.cc
index 3b7107c4c4..89973adc8b 100644
--- a/contrib/libs/grpc/src/compiler/csharp_generator.cc
+++ b/contrib/libs/grpc/src/compiler/csharp_generator.cc
@@ -445,10 +445,10 @@ void GenerateServerClass(Printer* out, const ServiceDescriptor* service) {
"/// <summary>Base class for server-side implementations of "
"$servicename$</summary>\n",
"servicename", GetServiceClassName(service));
- out->Print(
- "[grpc::BindServiceMethod(typeof($classname$), "
- "\"BindService\")]\n",
- "classname", GetServiceClassName(service));
+ out->Print(
+ "[grpc::BindServiceMethod(typeof($classname$), "
+ "\"BindService\")]\n",
+ "classname", GetServiceClassName(service));
out->Print("public abstract partial class $name$\n", "name",
GetServerClassName(service));
out->Print("{\n");
@@ -491,8 +491,8 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
"/// <param name=\"channel\">The channel to use to make remote "
"calls.</param>\n",
"servicename", GetServiceClassName(service));
- out->Print("public $name$(grpc::ChannelBase channel) : base(channel)\n",
- "name", GetClientClassName(service));
+ out->Print("public $name$(grpc::ChannelBase channel) : base(channel)\n",
+ "name", GetClientClassName(service));
out->Print("{\n");
out->Print("}\n");
out->Print(
diff --git a/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h b/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h
index a8af7f3ccd..ec2e449d8e 100644
--- a/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h
@@ -32,7 +32,7 @@ inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file,
}
// Get leading or trailing comments in a string. Comment lines start with "// ".
-// Leading detached comments are put in front of leading comments.
+// Leading detached comments are put in front of leading comments.
template <typename DescriptorType>
inline TString GetCsharpComments(const DescriptorType* desc, bool leading) {
return grpc_generator::GetPrefixedComments(desc, leading, "//");
diff --git a/contrib/libs/grpc/src/compiler/grpc_cpp_plugin/ya.make b/contrib/libs/grpc/src/compiler/grpc_cpp_plugin/ya.make
index a4b7e363a3..4dc845bede 100644
--- a/contrib/libs/grpc/src/compiler/grpc_cpp_plugin/ya.make
+++ b/contrib/libs/grpc/src/compiler/grpc_cpp_plugin/ya.make
@@ -1,37 +1,37 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
-
-LICENSE(Apache-2.0)
-
-PEERDIR(
- contrib/libs/grpc/src/compiler/grpc_plugin_support
+
+LICENSE(Apache-2.0)
+
+PEERDIR(
+ contrib/libs/grpc/src/compiler/grpc_plugin_support
contrib/libs/protobuf
contrib/libs/protoc
-)
-
-ADDINCL(
+)
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src/compiler)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src/compiler)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- cpp_plugin.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ cpp_plugin.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make b/contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make
index 068ae1ead6..1d1a812b8d 100644
--- a/contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make
+++ b/contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make
@@ -1,37 +1,37 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
-PEERDIR(
+PEERDIR(
contrib/libs/protobuf
contrib/libs/protoc
-)
-
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+)
+
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src/compiler)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src/compiler)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- cpp_generator.cc
- python_generator.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ cpp_generator.cc
+ python_generator.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/src/compiler/grpc_python_plugin/ya.make b/contrib/libs/grpc/src/compiler/grpc_python_plugin/ya.make
index cf2a106c91..66a25d1613 100644
--- a/contrib/libs/grpc/src/compiler/grpc_python_plugin/ya.make
+++ b/contrib/libs/grpc/src/compiler/grpc_python_plugin/ya.make
@@ -1,36 +1,36 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
-
-LICENSE(Apache-2.0)
-
-PEERDIR(
- contrib/libs/grpc/src/compiler/grpc_plugin_support
+
+LICENSE(Apache-2.0)
+
+PEERDIR(
+ contrib/libs/grpc/src/compiler/grpc_plugin_support
contrib/libs/protoc
-)
-
-ADDINCL(
+)
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/src/compiler)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/src/compiler)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- python_plugin.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ python_plugin.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/src/compiler/node_generator_helpers.h b/contrib/libs/grpc/src/compiler/node_generator_helpers.h
index ccf57ec8a6..7c56eb6a99 100644
--- a/contrib/libs/grpc/src/compiler/node_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/node_generator_helpers.h
@@ -31,7 +31,7 @@ inline TString GetJSServiceFilename(const TString& filename) {
}
// Get leading or trailing comments in a string. Comment lines start with "// ".
-// Leading detached comments are put in front of leading comments.
+// Leading detached comments are put in front of leading comments.
template <typename DescriptorType>
inline TString GetNodeComments(const DescriptorType* desc, bool leading) {
return grpc_generator::GetPrefixedComments(desc, leading, "//");
diff --git a/contrib/libs/grpc/src/compiler/objective_c_generator.cc b/contrib/libs/grpc/src/compiler/objective_c_generator.cc
index 07826b6a8d..6ae14d6c76 100644
--- a/contrib/libs/grpc/src/compiler/objective_c_generator.cc
+++ b/contrib/libs/grpc/src/compiler/objective_c_generator.cc
@@ -49,8 +49,8 @@ void PrintProtoRpcDeclarationAsPragma(Printer* printer,
}
template <typename DescriptorType>
-static void PrintAllComments(const DescriptorType* desc, Printer* printer,
- bool deprecated = false) {
+static void PrintAllComments(const DescriptorType* desc, Printer* printer,
+ bool deprecated = false) {
std::vector<TString> comments;
grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED,
&comments);
@@ -70,20 +70,20 @@ static void PrintAllComments(const DescriptorType* desc, Printer* printer,
}
printer->Print("\n");
}
- if (deprecated) {
- printer->Print(" *\n");
- printer->Print(
- " * This method belongs to a set of APIs that have been deprecated. "
- "Using"
- " the v2 API is recommended.\n");
- }
+ if (deprecated) {
+ printer->Print(" *\n");
+ printer->Print(
+ " * This method belongs to a set of APIs that have been deprecated. "
+ "Using"
+ " the v2 API is recommended.\n");
+ }
printer->Print(" */\n");
}
void PrintMethodSignature(Printer* printer, const MethodDescriptor* method,
const map< ::TString, ::TString>& vars) {
// Print comment
- PrintAllComments(method, printer, true);
+ PrintAllComments(method, printer, true);
printer->Print(vars, "- ($return_type$)$method_name$With");
if (method->client_streaming()) {
@@ -237,21 +237,21 @@ void PrintV2Implementation(Printer* printer, const MethodDescriptor* method,
}
void PrintMethodImplementations(Printer* printer,
- const MethodDescriptor* method,
- const Parameters& generator_params) {
+ const MethodDescriptor* method,
+ const Parameters& generator_params) {
map< ::TString, ::TString> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
- if (!generator_params.no_v1_compatibility) {
- // TODO(jcanizales): Print documentation from the method.
- PrintSimpleSignature(printer, method, vars);
- PrintSimpleImplementation(printer, method, vars);
+ if (!generator_params.no_v1_compatibility) {
+ // TODO(jcanizales): Print documentation from the method.
+ PrintSimpleSignature(printer, method, vars);
+ PrintSimpleImplementation(printer, method, vars);
- printer->Print("// Returns a not-yet-started RPC object.\n");
- PrintAdvancedSignature(printer, method, vars);
- PrintAdvancedImplementation(printer, method, vars);
- }
+ printer->Print("// Returns a not-yet-started RPC object.\n");
+ PrintAdvancedSignature(printer, method, vars);
+ PrintAdvancedImplementation(printer, method, vars);
+ }
PrintV2Signature(printer, method, vars);
PrintV2Implementation(printer, method, vars);
@@ -281,8 +281,8 @@ void PrintMethodImplementations(Printer* printer,
const Parameters& generator_params) {
::TString output;
- if (generator_params.no_v1_compatibility) return output;
-
+ if (generator_params.no_v1_compatibility) return output;
+
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
@@ -290,13 +290,13 @@ void PrintMethodImplementations(Printer* printer,
map< ::TString, ::TString> vars = {
{"service_class", ServiceClassName(service)}};
- printer.Print(vars,
- "/**\n"
- " * The methods in this protocol belong to a set of old APIs "
- "that have been deprecated. They do not\n"
- " * recognize call options provided in the initializer. Using "
- "the v2 protocol is recommended.\n"
- " */\n");
+ printer.Print(vars,
+ "/**\n"
+ " * The methods in this protocol belong to a set of old APIs "
+ "that have been deprecated. They do not\n"
+ " * recognize call options provided in the initializer. Using "
+ "the v2 protocol is recommended.\n"
+ " */\n");
printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodDeclarations(&printer, service->method(i));
@@ -343,11 +343,11 @@ void PrintMethodImplementations(Printer* printer,
" */\n");
printer.Print(vars,
"@interface $service_class$ :"
- " GRPCProtoService<$service_class$2");
- if (!generator_params.no_v1_compatibility) {
- printer.Print(vars, ", $service_class$");
- }
- printer.Print(">\n");
+ " GRPCProtoService<$service_class$2");
+ if (!generator_params.no_v1_compatibility) {
+ printer.Print(vars, ", $service_class$");
+ }
+ printer.Print(">\n");
printer.Print(
"- (instancetype)initWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions "
@@ -356,13 +356,13 @@ void PrintMethodImplementations(Printer* printer,
printer.Print(
"+ (instancetype)serviceWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions;\n");
- if (!generator_params.no_v1_compatibility) {
- printer.Print(
- "// The following methods belong to a set of old APIs that have been "
- "deprecated.\n");
- printer.Print("- (instancetype)initWithHost:(NSString *)host;\n");
- printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
- }
+ if (!generator_params.no_v1_compatibility) {
+ printer.Print(
+ "// The following methods belong to a set of old APIs that have been "
+ "deprecated.\n");
+ printer.Print("- (instancetype)initWithHost:(NSString *)host;\n");
+ printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
+ }
printer.Print("@end\n");
return output;
@@ -393,27 +393,27 @@ void PrintMethodImplementations(Printer* printer,
" packageName:@\"$package$\"\n"
" serviceName:@\"$service_name$\"\n"
" callOptions:callOptions];\n"
- "}\n\n");
- if (!generator_params.no_v1_compatibility) {
- printer.Print(vars,
- "- (instancetype)initWithHost:(NSString *)host {\n"
- " return [super initWithHost:host\n"
- " packageName:@\"$package$\"\n"
- " serviceName:@\"$service_name$\"];\n"
- "}\n\n");
- }
- printer.Print("#pragma clang diagnostic pop\n\n");
-
- if (!generator_params.no_v1_compatibility) {
- printer.Print(
- "// Override superclass initializer to disallow different"
- " package and service names.\n"
- "- (instancetype)initWithHost:(NSString *)host\n"
- " packageName:(NSString *)packageName\n"
- " serviceName:(NSString *)serviceName {\n"
- " return [self initWithHost:host];\n"
- "}\n\n");
- }
+ "}\n\n");
+ if (!generator_params.no_v1_compatibility) {
+ printer.Print(vars,
+ "- (instancetype)initWithHost:(NSString *)host {\n"
+ " return [super initWithHost:host\n"
+ " packageName:@\"$package$\"\n"
+ " serviceName:@\"$service_name$\"];\n"
+ "}\n\n");
+ }
+ printer.Print("#pragma clang diagnostic pop\n\n");
+
+ if (!generator_params.no_v1_compatibility) {
+ printer.Print(
+ "// Override superclass initializer to disallow different"
+ " package and service names.\n"
+ "- (instancetype)initWithHost:(NSString *)host\n"
+ " packageName:(NSString *)packageName\n"
+ " serviceName:(NSString *)serviceName {\n"
+ " return [self initWithHost:host];\n"
+ "}\n\n");
+ }
printer.Print(
"- (instancetype)initWithHost:(NSString *)host\n"
" packageName:(NSString *)packageName\n"
@@ -422,13 +422,13 @@ void PrintMethodImplementations(Printer* printer,
" return [self initWithHost:host callOptions:callOptions];\n"
"}\n\n");
- printer.Print("#pragma mark - Class Methods\n\n");
- if (!generator_params.no_v1_compatibility) {
- printer.Print(
- "+ (instancetype)serviceWithHost:(NSString *)host {\n"
- " return [[self alloc] initWithHost:host];\n"
- "}\n\n");
- }
+ printer.Print("#pragma mark - Class Methods\n\n");
+ if (!generator_params.no_v1_compatibility) {
+ printer.Print(
+ "+ (instancetype)serviceWithHost:(NSString *)host {\n"
+ " return [[self alloc] initWithHost:host];\n"
+ "}\n\n");
+ }
printer.Print(
"+ (instancetype)serviceWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions {\n"
@@ -438,8 +438,8 @@ void PrintMethodImplementations(Printer* printer,
printer.Print("#pragma mark - Method Implementations\n\n");
for (int i = 0; i < service->method_count(); i++) {
- PrintMethodImplementations(&printer, service->method(i),
- generator_params);
+ PrintMethodImplementations(&printer, service->method(i),
+ generator_params);
}
printer.Print("@end\n");
diff --git a/contrib/libs/grpc/src/compiler/objective_c_generator.h b/contrib/libs/grpc/src/compiler/objective_c_generator.h
index 9770f65436..c51a1b81fa 100644
--- a/contrib/libs/grpc/src/compiler/objective_c_generator.h
+++ b/contrib/libs/grpc/src/compiler/objective_c_generator.h
@@ -23,11 +23,11 @@
namespace grpc_objective_c_generator {
-struct Parameters {
- // Do not generate V1 interface and implementation
- bool no_v1_compatibility;
-};
-
+struct Parameters {
+ // Do not generate V1 interface and implementation
+ bool no_v1_compatibility;
+};
+
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::TString;
@@ -38,8 +38,8 @@ string GetAllMessageClasses(const FileDescriptor* file);
// Returns the content to be included defining the @protocol segment at the
// insertion point of the generated implementation file. This interface is
// legacy and for backwards compatibility.
-string GetProtocol(const ServiceDescriptor* service,
- const Parameters& generator_params);
+string GetProtocol(const ServiceDescriptor* service,
+ const Parameters& generator_params);
// Returns the content to be included defining the @protocol segment at the
// insertion point of the generated implementation file.
@@ -47,13 +47,13 @@ string GetV2Protocol(const ServiceDescriptor* service);
// Returns the content to be included defining the @interface segment at the
// insertion point of the generated implementation file.
-string GetInterface(const ServiceDescriptor* service,
- const Parameters& generator_params);
+string GetInterface(const ServiceDescriptor* service,
+ const Parameters& generator_params);
// Returns the content to be included in the "global_scope" insertion point of
// the generated implementation file.
-string GetSource(const ServiceDescriptor* service,
- const Parameters& generator_params);
+string GetSource(const ServiceDescriptor* service,
+ const Parameters& generator_params);
} // namespace grpc_objective_c_generator
diff --git a/contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h b/contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h
index ae296741ce..b9be5a53dd 100644
--- a/contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h
@@ -47,14 +47,14 @@ inline ::TString LocalImport(const ::TString& import) {
inline ::TString FrameworkImport(const ::TString& import,
const ::TString& framework) {
- // Flattens the directory structure: grab the file name only
- std::size_t pos = import.rfind("/");
- // If pos is npos, pos + 1 is 0, which gives us the entire string,
- // so there's no need to check that
+ // Flattens the directory structure: grab the file name only
+ std::size_t pos = import.rfind("/");
+ // If pos is npos, pos + 1 is 0, which gives us the entire string,
+ // so there's no need to check that
::TString filename = import.substr(pos + 1, import.size() - (pos + 1));
return ::TString("#import <" + framework + "/" + filename + ">\n");
-}
-
+}
+
inline ::TString SystemImport(const ::TString& import) {
return ::TString("#import <" + import + ">\n");
}
diff --git a/contrib/libs/grpc/src/compiler/php_generator_helpers.h b/contrib/libs/grpc/src/compiler/php_generator_helpers.h
index 70a31eaf75..964bf00dff 100644
--- a/contrib/libs/grpc/src/compiler/php_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/php_generator_helpers.h
@@ -63,7 +63,7 @@ inline TString GetPHPServiceFilename(
}
// Get leading or trailing comments in a string. Comment lines start with "// ".
-// Leading detached comments are put in front of leading comments.
+// Leading detached comments are put in front of leading comments.
template <typename DescriptorType>
inline TString GetPHPComments(const DescriptorType* desc,
TString prefix) {
diff --git a/contrib/libs/grpc/src/compiler/protobuf_plugin.h b/contrib/libs/grpc/src/compiler/protobuf_plugin.h
index ef844ea055..f3edcd0413 100644
--- a/contrib/libs/grpc/src/compiler/protobuf_plugin.h
+++ b/contrib/libs/grpc/src/compiler/protobuf_plugin.h
@@ -55,23 +55,23 @@ class ProtoBufMethod : public grpc_generator::Method {
return method_->output_type()->file()->name();
}
- // TODO(https://github.com/grpc/grpc/issues/18800): Clean this up.
- bool get_module_and_message_path_input(
+ // TODO(https://github.com/grpc/grpc/issues/18800): Clean this up.
+ bool get_module_and_message_path_input(
TString* str, TString generator_file_name,
bool generate_in_pb2_grpc, TString import_prefix,
const std::vector<TString>& prefixes_to_filter) const final {
return grpc_python_generator::GetModuleAndMessagePath(
method_->input_type(), str, generator_file_name, generate_in_pb2_grpc,
- import_prefix, prefixes_to_filter);
+ import_prefix, prefixes_to_filter);
}
- bool get_module_and_message_path_output(
+ bool get_module_and_message_path_output(
TString* str, TString generator_file_name,
bool generate_in_pb2_grpc, TString import_prefix,
const std::vector<TString>& prefixes_to_filter) const final {
return grpc_python_generator::GetModuleAndMessagePath(
method_->output_type(), str, generator_file_name, generate_in_pb2_grpc,
- import_prefix, prefixes_to_filter);
+ import_prefix, prefixes_to_filter);
}
bool NoStreaming() const {
@@ -109,11 +109,11 @@ class ProtoBufService : public grpc_generator::Service {
TString name() const { return service_->name(); }
- int method_count() const { return service_->method_count(); }
+ int method_count() const { return service_->method_count(); }
std::unique_ptr<const grpc_generator::Method> method(int i) const {
return std::unique_ptr<const grpc_generator::Method>(
new ProtoBufMethod(service_->method(i)));
- }
+ }
TString GetLeadingComments(const TString prefix) const {
return GetCommentsHelper(service_, true, prefix);
@@ -167,7 +167,7 @@ class ProtoBufFile : public grpc_generator::File {
TString additional_headers() const { return ""; }
- int service_count() const { return file_->service_count(); }
+ int service_count() const { return file_->service_count(); }
std::unique_ptr<const grpc_generator::Service> service(int i) const {
return std::unique_ptr<const grpc_generator::Service>(
new ProtoBufService(file_->service(i)));
@@ -192,13 +192,13 @@ class ProtoBufFile : public grpc_generator::File {
vector<TString> GetImportNames() const {
vector<TString> proto_names;
- for (int i = 0; i < file_->dependency_count(); ++i) {
- const auto& dep = *file_->dependency(i);
- proto_names.push_back(dep.name());
- }
- return proto_names;
- }
-
+ for (int i = 0; i < file_->dependency_count(); ++i) {
+ const auto& dep = *file_->dependency(i);
+ proto_names.push_back(dep.name());
+ }
+ return proto_names;
+ }
+
private:
const grpc::protobuf::FileDescriptor* file_;
};
diff --git a/contrib/libs/grpc/src/compiler/python_generator.cc b/contrib/libs/grpc/src/compiler/python_generator.cc
index d083d19f0b..49adf20e2a 100644
--- a/contrib/libs/grpc/src/compiler/python_generator.cc
+++ b/contrib/libs/grpc/src/compiler/python_generator.cc
@@ -221,15 +221,15 @@ bool PrivateGenerator::PrintBetaServerFactory(
TString input_message_module_and_class;
if (!method->get_module_and_message_path_input(
&input_message_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
TString output_message_module_and_class;
if (!method->get_module_and_message_path_output(
&output_message_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
method_implementation_constructors.insert(
@@ -329,15 +329,15 @@ bool PrivateGenerator::PrintBetaStubFactory(
TString input_message_module_and_class;
if (!method->get_module_and_message_path_input(
&input_message_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
TString output_message_module_and_class;
if (!method->get_module_and_message_path_output(
&output_message_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
method_cardinalities.insert(
@@ -436,15 +436,15 @@ bool PrivateGenerator::PrintStub(
TString request_module_and_class;
if (!method->get_module_and_message_path_input(
&request_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
TString response_module_and_class;
if (!method->get_module_and_message_path_output(
&response_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
StringMap method_dict;
@@ -529,15 +529,15 @@ bool PrivateGenerator::PrintAddServicerToServer(
TString request_module_and_class;
if (!method->get_module_and_message_path_input(
&request_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
TString response_module_and_class;
if (!method->get_module_and_message_path_output(
&response_module_and_class, generator_file_name,
- generate_in_pb2_grpc, config.import_prefix,
- config.prefixes_to_filter)) {
+ generate_in_pb2_grpc, config.import_prefix,
+ config.prefixes_to_filter)) {
return false;
}
StringMap method_dict;
@@ -693,20 +693,20 @@ bool PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
TString input_type_file_name = method->get_input_type_name();
TString input_module_name =
ModuleName(input_type_file_name, config.import_prefix,
- config.prefixes_to_filter);
+ config.prefixes_to_filter);
TString input_module_alias =
ModuleAlias(input_type_file_name, config.import_prefix,
- config.prefixes_to_filter);
+ config.prefixes_to_filter);
imports_set.insert(
std::make_tuple(input_module_name, input_module_alias));
TString output_type_file_name = method->get_output_type_name();
TString output_module_name =
ModuleName(output_type_file_name, config.import_prefix,
- config.prefixes_to_filter);
+ config.prefixes_to_filter);
TString output_module_alias =
ModuleAlias(output_type_file_name, config.import_prefix,
- config.prefixes_to_filter);
+ config.prefixes_to_filter);
imports_set.insert(
std::make_tuple(output_module_name, output_module_alias));
}
@@ -860,24 +860,24 @@ static bool ParseParameters(const TString& parameter,
std::vector<TString>* strip_prefixes,
TString* error) {
std::vector<TString> comma_delimited_parameters;
- grpc_python_generator::Split(parameter, ',', &comma_delimited_parameters);
- if (comma_delimited_parameters.size() == 1 &&
- comma_delimited_parameters[0].empty()) {
- *grpc_version = "grpc_2_0";
- } else if (comma_delimited_parameters.size() == 1) {
- *grpc_version = comma_delimited_parameters[0];
- } else if (comma_delimited_parameters.size() == 2) {
- *grpc_version = comma_delimited_parameters[0];
- std::copy(comma_delimited_parameters.begin() + 1,
- comma_delimited_parameters.end(),
- std::back_inserter(*strip_prefixes));
- } else {
- *error = "--grpc_python_out received too many comma-delimited parameters.";
- return false;
- }
- return true;
-}
-
+ grpc_python_generator::Split(parameter, ',', &comma_delimited_parameters);
+ if (comma_delimited_parameters.size() == 1 &&
+ comma_delimited_parameters[0].empty()) {
+ *grpc_version = "grpc_2_0";
+ } else if (comma_delimited_parameters.size() == 1) {
+ *grpc_version = comma_delimited_parameters[0];
+ } else if (comma_delimited_parameters.size() == 2) {
+ *grpc_version = comma_delimited_parameters[0];
+ std::copy(comma_delimited_parameters.begin() + 1,
+ comma_delimited_parameters.end(),
+ std::back_inserter(*strip_prefixes));
+ } else {
+ *error = "--grpc_python_out received too many comma-delimited parameters.";
+ return false;
+ }
+ return true;
+}
+
uint64_t PythonGrpcGenerator::GetSupportedFeatures() const {
return FEATURE_PROTO3_OPTIONAL;
}
@@ -904,18 +904,18 @@ bool PythonGrpcGenerator::Generate(const FileDescriptor* file,
ProtoBufFile pbfile(file);
TString grpc_version;
- GeneratorConfiguration extended_config(config_);
- bool success = ParseParameters(parameter, &grpc_version,
- &(extended_config.prefixes_to_filter), error);
- PrivateGenerator generator(extended_config, &pbfile);
- if (!success) return false;
- if (grpc_version == "grpc_2_0") {
+ GeneratorConfiguration extended_config(config_);
+ bool success = ParseParameters(parameter, &grpc_version,
+ &(extended_config.prefixes_to_filter), error);
+ PrivateGenerator generator(extended_config, &pbfile);
+ if (!success) return false;
+ if (grpc_version == "grpc_2_0") {
return GenerateGrpc(context, generator, pb2_grpc_file_name, true);
- } else if (grpc_version == "grpc_1_0") {
+ } else if (grpc_version == "grpc_1_0") {
return GenerateGrpc(context, generator, pb2_grpc_file_name, true) &&
GenerateGrpc(context, generator, pb2_file_name, false);
} else {
- *error = "Invalid grpc version '" + grpc_version + "'.";
+ *error = "Invalid grpc version '" + grpc_version + "'.";
return false;
}
}
diff --git a/contrib/libs/grpc/src/compiler/python_generator.h b/contrib/libs/grpc/src/compiler/python_generator.h
index bcde0a5e35..2e26a0315d 100644
--- a/contrib/libs/grpc/src/compiler/python_generator.h
+++ b/contrib/libs/grpc/src/compiler/python_generator.h
@@ -20,7 +20,7 @@
#define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
#include <utility>
-#include <vector>
+#include <vector>
#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
diff --git a/contrib/libs/grpc/src/compiler/python_generator_helpers.h b/contrib/libs/grpc/src/compiler/python_generator_helpers.h
index 78e7efd7e0..c14b1bc3da 100644
--- a/contrib/libs/grpc/src/compiler/python_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/python_generator_helpers.h
@@ -52,15 +52,15 @@ typedef vector<TString> StringVector;
static TString StripModulePrefixes(
const TString& raw_module_name,
const std::vector<TString>& prefixes_to_filter) {
- for (const auto& prefix : prefixes_to_filter) {
- if (raw_module_name.rfind(prefix, 0) == 0) {
- return raw_module_name.substr(prefix.size(),
- raw_module_name.size() - prefix.size());
- }
- }
- return raw_module_name;
-}
-
+ for (const auto& prefix : prefixes_to_filter) {
+ if (raw_module_name.rfind(prefix, 0) == 0) {
+ return raw_module_name.substr(prefix.size(),
+ raw_module_name.size() - prefix.size());
+ }
+ }
+ return raw_module_name;
+}
+
// TODO(https://github.com/google/protobuf/issues/888):
// Export `ModuleName` from protobuf's
// `src/google/protobuf/compiler/python/python_generator.cc` file.
@@ -70,8 +70,8 @@ TString ModuleName(const TString& filename,
TString basename = StripProto(filename);
basename = StringReplace(basename, "-", "_");
basename = StringReplace(basename, "/", ".");
- return StripModulePrefixes(import_prefix + basename + "_pb2",
- prefixes_to_filter);
+ return StripModulePrefixes(import_prefix + basename + "_pb2",
+ prefixes_to_filter);
}
// TODO(https://github.com/google/protobuf/issues/888):
@@ -90,7 +90,7 @@ TString ModuleAlias(const TString& filename,
return module_name;
}
-bool GetModuleAndMessagePath(
+bool GetModuleAndMessagePath(
const Descriptor* type, TString* out, TString generator_file_name,
bool generate_in_pb2_grpc, TString& import_prefix,
const std::vector<TString>& prefixes_to_filter) {
@@ -138,14 +138,14 @@ StringVector get_all_comments(const DescriptorType* descriptor) {
inline void Split(const TString& s, char delim,
std::vector<TString>* append_to) {
- auto current = s.begin();
- while (current <= s.end()) {
- auto next = std::find(current, s.end(), delim);
- append_to->emplace_back(current, next);
- current = next + 1;
- }
-}
-
+ auto current = s.begin();
+ while (current <= s.end()) {
+ auto next = std::find(current, s.end(), delim);
+ append_to->emplace_back(current, next);
+ current = next + 1;
+ }
+}
+
} // namespace
} // namespace grpc_python_generator
diff --git a/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h b/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h
index 9a10976619..6b659e17a4 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h
+++ b/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h
@@ -47,7 +47,7 @@ inline TString MessagesRequireName(
}
// Get leading or trailing comments in a string. Comment lines start with "# ".
-// Leading detached comments are put in front of leading comments.
+// Leading detached comments are put in front of leading comments.
template <typename DescriptorType>
inline TString GetRubyComments(const DescriptorType* desc, bool leading) {
return grpc_generator::GetPrefixedComments(desc, leading, "#");
diff --git a/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h b/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h
index 956539f392..b5109d0d2f 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h
+++ b/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h
@@ -100,30 +100,30 @@ inline TString Modularize(TString s) {
return new_string;
}
-// RubyPackage gets the ruby package in either proto or ruby_package format
+// RubyPackage gets the ruby package in either proto or ruby_package format
inline TString RubyPackage(const grpc::protobuf::FileDescriptor* file) {
TString package_name = file->package();
- if (file->options().has_ruby_package()) {
- package_name = file->options().ruby_package();
-
- // If :: is in the package convert the Ruby formatted name
- // -> A::B::C
- // to use the dot seperator notation
- // -> A.B.C
- package_name = ReplaceAll(package_name, "::", ".");
- }
- return package_name;
-}
-
+ if (file->options().has_ruby_package()) {
+ package_name = file->options().ruby_package();
+
+ // If :: is in the package convert the Ruby formatted name
+ // -> A::B::C
+ // to use the dot seperator notation
+ // -> A.B.C
+ package_name = ReplaceAll(package_name, "::", ".");
+ }
+ return package_name;
+}
+
// RubyTypeOf updates a proto type to the required ruby equivalent.
inline TString RubyTypeOf(const grpc::protobuf::Descriptor* descriptor) {
TString proto_type = descriptor->full_name();
- if (descriptor->file()->options().has_ruby_package()) {
+ if (descriptor->file()->options().has_ruby_package()) {
// remove the leading package if present
ReplacePrefix(&proto_type, descriptor->file()->package(), "");
ReplacePrefix(&proto_type, ".", ""); // remove the leading . (no package)
proto_type = RubyPackage(descriptor->file()) + "." + proto_type;
- }
+ }
TString res("." + proto_type);
if (res.find('.') == TString::npos) {
return res;
diff --git a/contrib/libs/grpc/src/core/README.md b/contrib/libs/grpc/src/core/README.md
index 5dea45a692..8cc85bc198 100644
--- a/contrib/libs/grpc/src/core/README.md
+++ b/contrib/libs/grpc/src/core/README.md
@@ -1,4 +1,4 @@
# Overview
-This directory contains source code for C library (a.k.a the *gRPC C core*) that provides all gRPC's core functionality through a low level API. Libraries in other languages in this repository (C++, C#, Ruby,
+This directory contains source code for C library (a.k.a the *gRPC C core*) that provides all gRPC's core functionality through a low level API. Libraries in other languages in this repository (C++, C#, Ruby,
Python, PHP, NodeJS, Objective-C) are layered on top of this library.
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md b/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md
index ffb09fd34e..00f7b66b47 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md
@@ -4,7 +4,7 @@ Client Configuration Support for GRPC
This library provides high level configuration machinery to construct client
channels and load balance between them.
-Each `grpc_channel` is created with a `Resolver`. It is the resolver's duty
+Each `grpc_channel` is created with a `Resolver`. It is the resolver's duty
to resolve a name into a set of arguments for the channel. Such arguments
might include:
@@ -12,7 +12,7 @@ might include:
- a load balancing policy to decide which server to send a request to
- a set of filters to mutate outgoing requests (say, by adding metadata)
-The resolver provides this data as a stream of `grpc_channel_args` objects to
+The resolver provides this data as a stream of `grpc_channel_args` objects to
the channel. We represent arguments as a stream so that they can be changed
by the resolver during execution, by reacting to external events (such as
new service configuration data being pushed to some store).
@@ -21,11 +21,11 @@ new service configuration data being pushed to some store).
Load Balancing
--------------
-Load balancing configuration is provided by a `LoadBalancingPolicy` object.
+Load balancing configuration is provided by a `LoadBalancingPolicy` object.
The primary job of the load balancing policies is to pick a target server
given only the initial metadata for a request. It does this by providing
-a `ConnectedSubchannel` object to the owning channel.
+a `ConnectedSubchannel` object to the owning channel.
Sub-Channels
@@ -38,9 +38,9 @@ decisions (for example, by avoiding disconnected backends).
Configured sub-channels are fully setup to participate in the grpc data plane.
Their behavior is specified by a set of grpc channel filters defined at their
-construction. To customize this behavior, transports build
-`ClientChannelFactory` objects, which customize construction arguments for
-concrete subchannel instances.
+construction. To customize this behavior, transports build
+`ClientChannelFactory` objects, which customize construction arguments for
+concrete subchannel instances.
Naming for GRPC
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.cc
index 257663cf20..83fbb6fd7d 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.cc
@@ -1,41 +1,41 @@
-//
-// Copyright 2019 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/backend_metric.h"
-
+//
+// Copyright 2019 gRPC authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/backend_metric.h"
+
#include "y_absl/strings/string_view.h"
-#include "udpa/data/orca/v1/orca_load_report.upb.h"
+#include "udpa/data/orca/v1/orca_load_report.upb.h"
#include "upb/upb.hpp"
-
+
#include "src/core/lib/gprpp/map.h"
-namespace grpc_core {
-
-namespace {
-
-template <typename EntryType>
+namespace grpc_core {
+
+namespace {
+
+template <typename EntryType>
std::map<y_absl::string_view, double, StringLess> ParseMap(
- udpa_data_orca_v1_OrcaLoadReport* msg,
+ udpa_data_orca_v1_OrcaLoadReport* msg,
const EntryType* (*entry_func)(const udpa_data_orca_v1_OrcaLoadReport*,
size_t*),
- upb_strview (*key_func)(const EntryType*),
- double (*value_func)(const EntryType*), Arena* arena) {
+ upb_strview (*key_func)(const EntryType*),
+ double (*value_func)(const EntryType*), Arena* arena) {
std::map<y_absl::string_view, double, StringLess> result;
size_t i = UPB_MAP_BEGIN;
while (true) {
@@ -43,42 +43,42 @@ std::map<y_absl::string_view, double, StringLess> ParseMap(
if (entry == nullptr) break;
upb_strview key_view = key_func(entry);
char* key = static_cast<char*>(arena->Alloc(key_view.size));
- memcpy(key, key_view.data, key_view.size);
+ memcpy(key, key_view.data, key_view.size);
result[y_absl::string_view(key, key_view.size)] = value_func(entry);
- }
- return result;
-}
-
-} // namespace
-
-const LoadBalancingPolicy::BackendMetricData* ParseBackendMetricData(
- const grpc_slice& serialized_load_report, Arena* arena) {
- upb::Arena upb_arena;
- udpa_data_orca_v1_OrcaLoadReport* msg =
- udpa_data_orca_v1_OrcaLoadReport_parse(
- reinterpret_cast<const char*>(
- GRPC_SLICE_START_PTR(serialized_load_report)),
- GRPC_SLICE_LENGTH(serialized_load_report), upb_arena.ptr());
- if (msg == nullptr) return nullptr;
- LoadBalancingPolicy::BackendMetricData* backend_metric_data =
- arena->New<LoadBalancingPolicy::BackendMetricData>();
- backend_metric_data->cpu_utilization =
- udpa_data_orca_v1_OrcaLoadReport_cpu_utilization(msg);
- backend_metric_data->mem_utilization =
- udpa_data_orca_v1_OrcaLoadReport_mem_utilization(msg);
- backend_metric_data->requests_per_second =
- udpa_data_orca_v1_OrcaLoadReport_rps(msg);
- backend_metric_data->request_cost =
- ParseMap<udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry>(
+ }
+ return result;
+}
+
+} // namespace
+
+const LoadBalancingPolicy::BackendMetricData* ParseBackendMetricData(
+ const grpc_slice& serialized_load_report, Arena* arena) {
+ upb::Arena upb_arena;
+ udpa_data_orca_v1_OrcaLoadReport* msg =
+ udpa_data_orca_v1_OrcaLoadReport_parse(
+ reinterpret_cast<const char*>(
+ GRPC_SLICE_START_PTR(serialized_load_report)),
+ GRPC_SLICE_LENGTH(serialized_load_report), upb_arena.ptr());
+ if (msg == nullptr) return nullptr;
+ LoadBalancingPolicy::BackendMetricData* backend_metric_data =
+ arena->New<LoadBalancingPolicy::BackendMetricData>();
+ backend_metric_data->cpu_utilization =
+ udpa_data_orca_v1_OrcaLoadReport_cpu_utilization(msg);
+ backend_metric_data->mem_utilization =
+ udpa_data_orca_v1_OrcaLoadReport_mem_utilization(msg);
+ backend_metric_data->requests_per_second =
+ udpa_data_orca_v1_OrcaLoadReport_rps(msg);
+ backend_metric_data->request_cost =
+ ParseMap<udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry>(
msg, udpa_data_orca_v1_OrcaLoadReport_request_cost_next,
- udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_key,
- udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_value, arena);
- backend_metric_data->utilization =
- ParseMap<udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry>(
+ udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_key,
+ udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_value, arena);
+ backend_metric_data->utilization =
+ ParseMap<udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry>(
msg, udpa_data_orca_v1_OrcaLoadReport_utilization_next,
- udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_key,
- udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_value, arena);
- return backend_metric_data;
-}
-
-} // namespace grpc_core
+ udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_key,
+ udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_value, arena);
+ return backend_metric_data;
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.h
index d92b76c8d3..55fc5a37e4 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/backend_metric.h
@@ -1,36 +1,36 @@
-//
-// Copyright 2019 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKEND_METRIC_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKEND_METRIC_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-#include "src/core/lib/gprpp/arena.h"
-
-namespace grpc_core {
-
-// Parses the serialized load report and allocates a BackendMetricData
-// object on the arena.
-const LoadBalancingPolicy::BackendMetricData* ParseBackendMetricData(
- const grpc_slice& serialized_load_report, Arena* arena);
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKEND_METRIC_H */
+//
+// Copyright 2019 gRPC authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKEND_METRIC_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKEND_METRIC_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy.h"
+#include "src/core/lib/gprpp/arena.h"
+
+namespace grpc_core {
+
+// Parses the serialized load report and allocates a BackendMetricData
+// object on the arena.
+const LoadBalancingPolicy::BackendMetricData* ParseBackendMetricData(
+ const grpc_slice& serialized_load_report, Arena* arena);
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKEND_METRIC_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.cc
index 1b7708953a..9090f24e5c 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.cc
@@ -24,12 +24,12 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
-
+
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/surface/channel.h"
@@ -58,26 +58,26 @@ static backup_poller* g_poller = nullptr; // guarded by g_poller_mu
// treated as const.
static int g_poll_interval_ms = DEFAULT_POLL_INTERVAL_MS;
-GPR_GLOBAL_CONFIG_DEFINE_INT32(
- grpc_client_channel_backup_poll_interval_ms, DEFAULT_POLL_INTERVAL_MS,
- "Declares the interval in ms between two backup polls on client channels. "
- "These polls are run in the timer thread so that gRPC can process "
- "connection failures while there is no active polling thread. "
- "They help reconnect disconnected client channels (mostly due to "
- "idleness), so that the next RPC on this channel won't fail. Set to 0 to "
- "turn off the backup polls.");
-
-void grpc_client_channel_global_init_backup_polling() {
- gpr_once_init(&g_once, [] { gpr_mu_init(&g_poller_mu); });
- int32_t poll_interval_ms =
- GPR_GLOBAL_CONFIG_GET(grpc_client_channel_backup_poll_interval_ms);
- if (poll_interval_ms < 0) {
- gpr_log(GPR_ERROR,
- "Invalid GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS: %d, "
- "default value %d will be used.",
- poll_interval_ms, g_poll_interval_ms);
- } else {
- g_poll_interval_ms = poll_interval_ms;
+GPR_GLOBAL_CONFIG_DEFINE_INT32(
+ grpc_client_channel_backup_poll_interval_ms, DEFAULT_POLL_INTERVAL_MS,
+ "Declares the interval in ms between two backup polls on client channels. "
+ "These polls are run in the timer thread so that gRPC can process "
+ "connection failures while there is no active polling thread. "
+ "They help reconnect disconnected client channels (mostly due to "
+ "idleness), so that the next RPC on this channel won't fail. Set to 0 to "
+ "turn off the backup polls.");
+
+void grpc_client_channel_global_init_backup_polling() {
+ gpr_once_init(&g_once, [] { gpr_mu_init(&g_poller_mu); });
+ int32_t poll_interval_ms =
+ GPR_GLOBAL_CONFIG_GET(grpc_client_channel_backup_poll_interval_ms);
+ if (poll_interval_ms < 0) {
+ gpr_log(GPR_ERROR,
+ "Invalid GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS: %d, "
+ "default value %d will be used.",
+ poll_interval_ms, g_poll_interval_ms);
+ } else {
+ g_poll_interval_ms = poll_interval_ms;
}
}
@@ -89,7 +89,7 @@ static void backup_poller_shutdown_unref(backup_poller* p) {
}
}
-static void done_poller(void* arg, grpc_error* /*error*/) {
+static void done_poller(void* arg, grpc_error* /*error*/) {
backup_poller_shutdown_unref(static_cast<backup_poller*>(arg));
}
@@ -156,7 +156,7 @@ static void g_poller_init_locked() {
void grpc_client_channel_start_backup_polling(
grpc_pollset_set* interested_parties) {
- if (g_poll_interval_ms == 0 || grpc_iomgr_run_in_background()) {
+ if (g_poll_interval_ms == 0 || grpc_iomgr_run_in_background()) {
return;
}
gpr_mu_lock(&g_poller_mu);
@@ -174,7 +174,7 @@ void grpc_client_channel_start_backup_polling(
void grpc_client_channel_stop_backup_polling(
grpc_pollset_set* interested_parties) {
- if (g_poll_interval_ms == 0 || grpc_iomgr_run_in_background()) {
+ if (g_poll_interval_ms == 0 || grpc_iomgr_run_in_background()) {
return;
}
grpc_pollset_set_del_pollset(interested_parties, g_poller->pollset);
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.h
index b412081b96..eedaa1c64e 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.h
@@ -23,18 +23,18 @@
#include <grpc/grpc.h>
#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/gprpp/global_config.h"
-
-GPR_GLOBAL_CONFIG_DECLARE_INT32(grpc_client_channel_backup_poll_interval_ms);
-
-/* Initializes backup polling. */
-void grpc_client_channel_global_init_backup_polling();
-
-/* Starts polling \a interested_parties periodically in the timer thread. */
+#include "src/core/lib/gprpp/global_config.h"
+
+GPR_GLOBAL_CONFIG_DECLARE_INT32(grpc_client_channel_backup_poll_interval_ms);
+
+/* Initializes backup polling. */
+void grpc_client_channel_global_init_backup_polling();
+
+/* Starts polling \a interested_parties periodically in the timer thread. */
void grpc_client_channel_start_backup_polling(
grpc_pollset_set* interested_parties);
-/* Stops polling \a interested_parties. */
+/* Stops polling \a interested_parties. */
void grpc_client_channel_stop_backup_polling(
grpc_pollset_set* interested_parties);
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc
index 4ebb976efe..5f79007161 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc
@@ -90,7 +90,7 @@ static void delete_state_watcher(state_watcher* w) {
gpr_free(w);
}
-static void finished_completion(void* pw, grpc_cq_completion* /*ignored*/) {
+static void finished_completion(void* pw, grpc_cq_completion* /*ignored*/) {
bool should_delete = false;
state_watcher* w = static_cast<state_watcher*>(pw);
gpr_mu_lock(&w->mu);
@@ -111,12 +111,12 @@ static void finished_completion(void* pw, grpc_cq_completion* /*ignored*/) {
static void partly_done(state_watcher* w, bool due_to_completion,
grpc_error* error) {
- bool end_op = false;
- void* end_op_tag = nullptr;
- grpc_error* end_op_error = nullptr;
- grpc_completion_queue* end_op_cq = nullptr;
- grpc_cq_completion* end_op_completion_storage = nullptr;
-
+ bool end_op = false;
+ void* end_op_tag = nullptr;
+ grpc_error* end_op_error = nullptr;
+ grpc_completion_queue* end_op_cq = nullptr;
+ grpc_cq_completion* end_op_completion_storage = nullptr;
+
if (due_to_completion) {
grpc_timer_cancel(&w->alarm);
} else {
@@ -131,7 +131,7 @@ static void partly_done(state_watcher* w, bool due_to_completion,
gpr_mu_lock(&w->mu);
if (due_to_completion) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures)) {
GRPC_LOG_IF_ERROR("watch_completion_error", GRPC_ERROR_REF(error));
}
GRPC_ERROR_UNREF(error);
@@ -158,11 +158,11 @@ static void partly_done(state_watcher* w, bool due_to_completion,
w->error = error;
}
w->phase = CALLING_BACK_AND_FINISHED;
- end_op = true;
- end_op_cq = w->cq;
- end_op_tag = w->tag;
- end_op_error = w->error;
- end_op_completion_storage = &w->completion_storage;
+ end_op = true;
+ end_op_cq = w->cq;
+ end_op_tag = w->tag;
+ end_op_error = w->error;
+ end_op_completion_storage = &w->completion_storage;
break;
case CALLING_BACK_AND_FINISHED:
GPR_UNREACHABLE_CODE(return );
@@ -170,11 +170,11 @@ static void partly_done(state_watcher* w, bool due_to_completion,
}
gpr_mu_unlock(&w->mu);
- if (end_op) {
- grpc_cq_end_op(end_op_cq, end_op_tag, end_op_error, finished_completion, w,
- end_op_completion_storage);
- }
-
+ if (end_op) {
+ grpc_cq_end_op(end_op_cq, end_op_tag, end_op_error, finished_completion, w,
+ end_op_completion_storage);
+ }
+
GRPC_ERROR_UNREF(error);
}
@@ -198,7 +198,7 @@ typedef struct watcher_timer_init_arg {
gpr_timespec deadline;
} watcher_timer_init_arg;
-static void watcher_timer_init(void* arg, grpc_error* /*error_ignored*/) {
+static void watcher_timer_init(void* arg, grpc_error* /*error_ignored*/) {
watcher_timer_init_arg* wa = static_cast<watcher_timer_init_arg*>(arg);
grpc_timer_init(&wa->w->alarm, grpc_timespec_to_millis_round_up(wa->deadline),
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc
index 908a05248c..15e10d43d9 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc
@@ -26,8 +26,8 @@
#include <stdio.h>
#include <string.h>
-#include <set>
-
+#include <set>
+
#include "y_absl/strings/numbers.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/string_view.h"
@@ -40,19 +40,19 @@
#include "y_absl/container/inlined_vector.h"
#include "y_absl/types/optional.h"
-#include "src/core/ext/filters/client_channel/backend_metric.h"
+#include "src/core/ext/filters/client_channel/backend_metric.h"
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/config_selector.h"
-#include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
+#include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/ext/filters/client_channel/local_subchannel_pool.h"
+#include "src/core/ext/filters/client_channel/local_subchannel_pool.h"
#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/filters/client_channel/resolver_result_parsing.h"
-#include "src/core/ext/filters/client_channel/resolving_lb_policy.h"
+#include "src/core/ext/filters/client_channel/resolving_lb_policy.h"
#include "src/core/ext/filters/client_channel/retry_throttle.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/ext/filters/client_channel/service_config_call_data.h"
#include "src/core/ext/filters/client_channel/subchannel.h"
#include "src/core/ext/filters/deadline/deadline_filter.h"
@@ -62,8 +62,8 @@
#include "src/core/lib/channel/status_util.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/gprpp/map.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/map.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/iomgr/work_serializer.h"
@@ -78,12 +78,12 @@
#include "src/core/lib/transport/static_metadata.h"
#include "src/core/lib/transport/status_metadata.h"
-using grpc_core::internal::ClientChannelMethodParsedConfig;
+using grpc_core::internal::ClientChannelMethodParsedConfig;
using grpc_core::internal::ServerRetryThrottleData;
-//
-// Client channel filter
-//
+//
+// Client channel filter
+//
// By default, we buffer 256 KiB per RPC for retries.
// TODO(roth): Do we have any data to suggest a better value?
@@ -93,124 +93,124 @@ using grpc_core::internal::ServerRetryThrottleData;
// any even moderately compelling reason to do so.
#define RETRY_BACKOFF_JITTER 0.2
-// Max number of batches that can be pending on a call at any given
-// time. This includes one batch for each of the following ops:
-// recv_initial_metadata
-// send_initial_metadata
-// recv_message
-// send_message
-// recv_trailing_metadata
-// send_trailing_metadata
-#define MAX_PENDING_BATCHES 6
-
-namespace grpc_core {
-
-TraceFlag grpc_client_channel_call_trace(false, "client_channel_call");
-TraceFlag grpc_client_channel_routing_trace(false, "client_channel_routing");
-
-namespace {
-
-//
-// ChannelData definition
-//
-
-class ChannelData {
- public:
- struct QueuedPick {
- grpc_call_element* elem;
- QueuedPick* next = nullptr;
- };
-
- static grpc_error* Init(grpc_channel_element* elem,
- grpc_channel_element_args* args);
- static void Destroy(grpc_channel_element* elem);
- static void StartTransportOp(grpc_channel_element* elem,
- grpc_transport_op* op);
- static void GetChannelInfo(grpc_channel_element* elem,
- const grpc_channel_info* info);
-
- bool deadline_checking_enabled() const { return deadline_checking_enabled_; }
- bool enable_retries() const { return enable_retries_; }
- size_t per_rpc_retry_buffer_size() const {
- return per_rpc_retry_buffer_size_;
- }
+// Max number of batches that can be pending on a call at any given
+// time. This includes one batch for each of the following ops:
+// recv_initial_metadata
+// send_initial_metadata
+// recv_message
+// send_message
+// recv_trailing_metadata
+// send_trailing_metadata
+#define MAX_PENDING_BATCHES 6
+
+namespace grpc_core {
+
+TraceFlag grpc_client_channel_call_trace(false, "client_channel_call");
+TraceFlag grpc_client_channel_routing_trace(false, "client_channel_routing");
+
+namespace {
+
+//
+// ChannelData definition
+//
+
+class ChannelData {
+ public:
+ struct QueuedPick {
+ grpc_call_element* elem;
+ QueuedPick* next = nullptr;
+ };
+
+ static grpc_error* Init(grpc_channel_element* elem,
+ grpc_channel_element_args* args);
+ static void Destroy(grpc_channel_element* elem);
+ static void StartTransportOp(grpc_channel_element* elem,
+ grpc_transport_op* op);
+ static void GetChannelInfo(grpc_channel_element* elem,
+ const grpc_channel_info* info);
+
+ bool deadline_checking_enabled() const { return deadline_checking_enabled_; }
+ bool enable_retries() const { return enable_retries_; }
+ size_t per_rpc_retry_buffer_size() const {
+ return per_rpc_retry_buffer_size_;
+ }
grpc_channel_stack* owning_stack() const { return owning_stack_; }
- // Note: Does NOT return a new ref.
- grpc_error* disconnect_error() const {
- return disconnect_error_.Load(MemoryOrder::ACQUIRE);
- }
-
- Mutex* data_plane_mu() const { return &data_plane_mu_; }
-
- LoadBalancingPolicy::SubchannelPicker* picker() const {
- return picker_.get();
- }
- void AddQueuedPick(QueuedPick* pick, grpc_polling_entity* pollent);
- void RemoveQueuedPick(QueuedPick* to_remove, grpc_polling_entity* pollent);
-
- bool received_service_config_data() const {
- return received_service_config_data_;
- }
+ // Note: Does NOT return a new ref.
+ grpc_error* disconnect_error() const {
+ return disconnect_error_.Load(MemoryOrder::ACQUIRE);
+ }
+
+ Mutex* data_plane_mu() const { return &data_plane_mu_; }
+
+ LoadBalancingPolicy::SubchannelPicker* picker() const {
+ return picker_.get();
+ }
+ void AddQueuedPick(QueuedPick* pick, grpc_polling_entity* pollent);
+ void RemoveQueuedPick(QueuedPick* to_remove, grpc_polling_entity* pollent);
+
+ bool received_service_config_data() const {
+ return received_service_config_data_;
+ }
grpc_error* resolver_transient_failure_error() const {
return resolver_transient_failure_error_;
}
- RefCountedPtr<ServerRetryThrottleData> retry_throttle_data() const {
- return retry_throttle_data_;
- }
- RefCountedPtr<ServiceConfig> service_config() const {
- return service_config_;
- }
+ RefCountedPtr<ServerRetryThrottleData> retry_throttle_data() const {
+ return retry_throttle_data_;
+ }
+ RefCountedPtr<ServiceConfig> service_config() const {
+ return service_config_;
+ }
ConfigSelector* config_selector() const { return config_selector_.get(); }
WorkSerializer* work_serializer() const { return work_serializer_.get(); }
-
- RefCountedPtr<ConnectedSubchannel> GetConnectedSubchannelInDataPlane(
- SubchannelInterface* subchannel) const;
-
- grpc_connectivity_state CheckConnectivityState(bool try_to_connect);
-
- void AddExternalConnectivityWatcher(grpc_polling_entity pollent,
- grpc_connectivity_state* state,
- grpc_closure* on_complete,
- grpc_closure* watcher_timer_init) {
+
+ RefCountedPtr<ConnectedSubchannel> GetConnectedSubchannelInDataPlane(
+ SubchannelInterface* subchannel) const;
+
+ grpc_connectivity_state CheckConnectivityState(bool try_to_connect);
+
+ void AddExternalConnectivityWatcher(grpc_polling_entity pollent,
+ grpc_connectivity_state* state,
+ grpc_closure* on_complete,
+ grpc_closure* watcher_timer_init) {
new ExternalConnectivityWatcher(this, pollent, state, on_complete,
watcher_timer_init);
- }
-
- void RemoveExternalConnectivityWatcher(grpc_closure* on_complete,
- bool cancel) {
+ }
+
+ void RemoveExternalConnectivityWatcher(grpc_closure* on_complete,
+ bool cancel) {
ExternalConnectivityWatcher::RemoveWatcherFromExternalWatchersMap(
this, on_complete, cancel);
- }
-
- int NumExternalConnectivityWatchers() const {
- MutexLock lock(&external_watchers_mu_);
- return static_cast<int>(external_watchers_.size());
- }
-
- void AddConnectivityWatcher(
- grpc_connectivity_state initial_state,
- OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher);
- void RemoveConnectivityWatcher(
- AsyncConnectivityStateWatcherInterface* watcher);
-
- private:
- class SubchannelWrapper;
- class ClientChannelControlHelper;
- class ConnectivityWatcherAdder;
- class ConnectivityWatcherRemover;
-
- // Represents a pending connectivity callback from an external caller
- // via grpc_client_channel_watch_connectivity_state().
- class ExternalConnectivityWatcher : public ConnectivityStateWatcherInterface {
- public:
- ExternalConnectivityWatcher(ChannelData* chand, grpc_polling_entity pollent,
- grpc_connectivity_state* state,
- grpc_closure* on_complete,
- grpc_closure* watcher_timer_init);
-
- ~ExternalConnectivityWatcher();
-
+ }
+
+ int NumExternalConnectivityWatchers() const {
+ MutexLock lock(&external_watchers_mu_);
+ return static_cast<int>(external_watchers_.size());
+ }
+
+ void AddConnectivityWatcher(
+ grpc_connectivity_state initial_state,
+ OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher);
+ void RemoveConnectivityWatcher(
+ AsyncConnectivityStateWatcherInterface* watcher);
+
+ private:
+ class SubchannelWrapper;
+ class ClientChannelControlHelper;
+ class ConnectivityWatcherAdder;
+ class ConnectivityWatcherRemover;
+
+ // Represents a pending connectivity callback from an external caller
+ // via grpc_client_channel_watch_connectivity_state().
+ class ExternalConnectivityWatcher : public ConnectivityStateWatcherInterface {
+ public:
+ ExternalConnectivityWatcher(ChannelData* chand, grpc_polling_entity pollent,
+ grpc_connectivity_state* state,
+ grpc_closure* on_complete,
+ grpc_closure* watcher_timer_init);
+
+ ~ExternalConnectivityWatcher();
+
// Removes the watcher from the external_watchers_ map.
static void RemoveWatcherFromExternalWatchersMap(ChannelData* chand,
grpc_closure* on_complete,
@@ -218,24 +218,24 @@ class ChannelData {
void Notify(grpc_connectivity_state state,
const y_absl::Status& /* status */) override;
-
- void Cancel();
-
- private:
+
+ void Cancel();
+
+ private:
// Adds the watcher to state_tracker_. Consumes the ref that is passed to it
// from Start().
void AddWatcherLocked();
void RemoveWatcherLocked();
-
- ChannelData* chand_;
- grpc_polling_entity pollent_;
- grpc_connectivity_state initial_state_;
- grpc_connectivity_state* state_;
- grpc_closure* on_complete_;
- grpc_closure* watcher_timer_init_;
- Atomic<bool> done_{false};
- };
-
+
+ ChannelData* chand_;
+ grpc_polling_entity pollent_;
+ grpc_connectivity_state initial_state_;
+ grpc_connectivity_state* state_;
+ grpc_closure* on_complete_;
+ grpc_closure* watcher_timer_init_;
+ Atomic<bool> done_{false};
+ };
+
class ChannelConfigHelper
: public ResolvingLoadBalancingPolicy::ChannelConfigHelper {
public:
@@ -257,175 +257,175 @@ class ChannelData {
ChannelData* chand_;
};
- ChannelData(grpc_channel_element_args* args, grpc_error** error);
- ~ChannelData();
-
- void UpdateStateAndPickerLocked(
+ ChannelData(grpc_channel_element_args* args, grpc_error** error);
+ ~ChannelData();
+
+ void UpdateStateAndPickerLocked(
grpc_connectivity_state state, const y_absl::Status& status,
const char* reason,
- std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker);
-
+ std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker);
+
void UpdateServiceConfigInControlPlaneLocked(
RefCountedPtr<ServiceConfig> service_config,
RefCountedPtr<ConfigSelector> config_selector,
const internal::ClientChannelGlobalParsedConfig* parsed_service_config,
const char* lb_policy_name);
-
+
void UpdateServiceConfigInDataPlaneLocked();
- void CreateResolvingLoadBalancingPolicyLocked();
-
- void DestroyResolvingLoadBalancingPolicyLocked();
-
- grpc_error* DoPingLocked(grpc_transport_op* op);
-
+ void CreateResolvingLoadBalancingPolicyLocked();
+
+ void DestroyResolvingLoadBalancingPolicyLocked();
+
+ grpc_error* DoPingLocked(grpc_transport_op* op);
+
void StartTransportOpLocked(grpc_transport_op* op);
-
+
void TryToConnectLocked();
-
- //
- // Fields set at construction and never modified.
- //
- const bool deadline_checking_enabled_;
- const bool enable_retries_;
- const size_t per_rpc_retry_buffer_size_;
- grpc_channel_stack* owning_stack_;
- ClientChannelFactory* client_channel_factory_;
- const grpc_channel_args* channel_args_;
- RefCountedPtr<ServiceConfig> default_service_config_;
- grpc_core::UniquePtr<char> server_name_;
- grpc_core::UniquePtr<char> target_uri_;
- channelz::ChannelNode* channelz_node_;
+
+ //
+ // Fields set at construction and never modified.
+ //
+ const bool deadline_checking_enabled_;
+ const bool enable_retries_;
+ const size_t per_rpc_retry_buffer_size_;
+ grpc_channel_stack* owning_stack_;
+ ClientChannelFactory* client_channel_factory_;
+ const grpc_channel_args* channel_args_;
+ RefCountedPtr<ServiceConfig> default_service_config_;
+ grpc_core::UniquePtr<char> server_name_;
+ grpc_core::UniquePtr<char> target_uri_;
+ channelz::ChannelNode* channelz_node_;
ChannelConfigHelper channel_config_helper_;
-
- //
- // Fields used in the data plane. Guarded by data_plane_mu.
- //
- mutable Mutex data_plane_mu_;
- std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker_;
- QueuedPick* queued_picks_ = nullptr; // Linked list of queued picks.
- // Data from service config.
+
+ //
+ // Fields used in the data plane. Guarded by data_plane_mu.
+ //
+ mutable Mutex data_plane_mu_;
+ std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker_;
+ QueuedPick* queued_picks_ = nullptr; // Linked list of queued picks.
+ // Data from service config.
grpc_error* resolver_transient_failure_error_ = GRPC_ERROR_NONE;
- bool received_service_config_data_ = false;
- RefCountedPtr<ServerRetryThrottleData> retry_throttle_data_;
- RefCountedPtr<ServiceConfig> service_config_;
+ bool received_service_config_data_ = false;
+ RefCountedPtr<ServerRetryThrottleData> retry_throttle_data_;
+ RefCountedPtr<ServiceConfig> service_config_;
RefCountedPtr<ConfigSelector> config_selector_;
-
- //
+
+ //
// Fields used in the control plane. Guarded by work_serializer.
- //
+ //
std::shared_ptr<WorkSerializer> work_serializer_;
- grpc_pollset_set* interested_parties_;
- RefCountedPtr<SubchannelPoolInterface> subchannel_pool_;
- OrphanablePtr<ResolvingLoadBalancingPolicy> resolving_lb_policy_;
- ConnectivityStateTracker state_tracker_;
- grpc_core::UniquePtr<char> health_check_service_name_;
- RefCountedPtr<ServiceConfig> saved_service_config_;
+ grpc_pollset_set* interested_parties_;
+ RefCountedPtr<SubchannelPoolInterface> subchannel_pool_;
+ OrphanablePtr<ResolvingLoadBalancingPolicy> resolving_lb_policy_;
+ ConnectivityStateTracker state_tracker_;
+ grpc_core::UniquePtr<char> health_check_service_name_;
+ RefCountedPtr<ServiceConfig> saved_service_config_;
RefCountedPtr<ConfigSelector> saved_config_selector_;
- // The number of SubchannelWrapper instances referencing a given Subchannel.
- std::map<Subchannel*, int> subchannel_refcount_map_;
- // The set of SubchannelWrappers that currently exist.
- // No need to hold a ref, since the map is updated in the control-plane
+ // The number of SubchannelWrapper instances referencing a given Subchannel.
+ std::map<Subchannel*, int> subchannel_refcount_map_;
+ // The set of SubchannelWrappers that currently exist.
+ // No need to hold a ref, since the map is updated in the control-plane
// work_serializer when the SubchannelWrappers are created and destroyed.
- std::set<SubchannelWrapper*> subchannel_wrappers_;
- // Pending ConnectedSubchannel updates for each SubchannelWrapper.
+ std::set<SubchannelWrapper*> subchannel_wrappers_;
+ // Pending ConnectedSubchannel updates for each SubchannelWrapper.
// Updates are queued here in the control plane work_serializer and then
// applied in the data plane mutex when the picker is updated.
std::map<RefCountedPtr<SubchannelWrapper>, RefCountedPtr<ConnectedSubchannel>>
- pending_subchannel_updates_;
+ pending_subchannel_updates_;
int keepalive_time_ = -1;
-
- //
+
+ //
// Fields accessed from both data plane mutex and control plane
// work_serializer.
- //
- Atomic<grpc_error*> disconnect_error_;
-
- //
- // Fields guarded by a mutex, since they need to be accessed
- // synchronously via get_channel_info().
- //
- gpr_mu info_mu_;
- grpc_core::UniquePtr<char> info_lb_policy_name_;
- grpc_core::UniquePtr<char> info_service_config_json_;
-
- //
- // Fields guarded by a mutex, since they need to be accessed
- // synchronously via grpc_channel_num_external_connectivity_watchers().
- //
- mutable Mutex external_watchers_mu_;
+ //
+ Atomic<grpc_error*> disconnect_error_;
+
+ //
+ // Fields guarded by a mutex, since they need to be accessed
+ // synchronously via get_channel_info().
+ //
+ gpr_mu info_mu_;
+ grpc_core::UniquePtr<char> info_lb_policy_name_;
+ grpc_core::UniquePtr<char> info_service_config_json_;
+
+ //
+ // Fields guarded by a mutex, since they need to be accessed
+ // synchronously via grpc_channel_num_external_connectivity_watchers().
+ //
+ mutable Mutex external_watchers_mu_;
std::map<grpc_closure*, RefCountedPtr<ExternalConnectivityWatcher>>
external_watchers_;
-};
-
-//
-// CallData definition
-//
-
-class CallData {
- public:
- static grpc_error* Init(grpc_call_element* elem,
- const grpc_call_element_args* args);
- static void Destroy(grpc_call_element* elem,
- const grpc_call_final_info* final_info,
- grpc_closure* then_schedule_closure);
- static void StartTransportStreamOpBatch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* batch);
- static void SetPollent(grpc_call_element* elem, grpc_polling_entity* pollent);
-
- RefCountedPtr<SubchannelCall> subchannel_call() { return subchannel_call_; }
-
- // Invoked by channel for queued picks when the picker is updated.
- static void PickSubchannel(void* arg, grpc_error* error);
-
- // Helper function for performing a pick while holding the data plane
- // mutex. Returns true if the pick is complete, in which case the caller
- // must invoke PickDone() or AsyncPickDone() with the returned error.
- bool PickSubchannelLocked(grpc_call_element* elem, grpc_error** error);
-
- // Schedules a callback to process the completed pick. The callback
- // will not run until after this method returns.
- void AsyncPickDone(grpc_call_element* elem, grpc_error* error);
-
- private:
- class QueuedPickCanceller;
-
- class Metadata : public LoadBalancingPolicy::MetadataInterface {
- public:
- Metadata(CallData* calld, grpc_metadata_batch* batch)
- : calld_(calld), batch_(batch) {}
-
+};
+
+//
+// CallData definition
+//
+
+class CallData {
+ public:
+ static grpc_error* Init(grpc_call_element* elem,
+ const grpc_call_element_args* args);
+ static void Destroy(grpc_call_element* elem,
+ const grpc_call_final_info* final_info,
+ grpc_closure* then_schedule_closure);
+ static void StartTransportStreamOpBatch(
+ grpc_call_element* elem, grpc_transport_stream_op_batch* batch);
+ static void SetPollent(grpc_call_element* elem, grpc_polling_entity* pollent);
+
+ RefCountedPtr<SubchannelCall> subchannel_call() { return subchannel_call_; }
+
+ // Invoked by channel for queued picks when the picker is updated.
+ static void PickSubchannel(void* arg, grpc_error* error);
+
+ // Helper function for performing a pick while holding the data plane
+ // mutex. Returns true if the pick is complete, in which case the caller
+ // must invoke PickDone() or AsyncPickDone() with the returned error.
+ bool PickSubchannelLocked(grpc_call_element* elem, grpc_error** error);
+
+ // Schedules a callback to process the completed pick. The callback
+ // will not run until after this method returns.
+ void AsyncPickDone(grpc_call_element* elem, grpc_error* error);
+
+ private:
+ class QueuedPickCanceller;
+
+ class Metadata : public LoadBalancingPolicy::MetadataInterface {
+ public:
+ Metadata(CallData* calld, grpc_metadata_batch* batch)
+ : calld_(calld), batch_(batch) {}
+
void Add(y_absl::string_view key, y_absl::string_view value) override {
- grpc_linked_mdelem* linked_mdelem = static_cast<grpc_linked_mdelem*>(
- calld_->arena_->Alloc(sizeof(grpc_linked_mdelem)));
- linked_mdelem->md = grpc_mdelem_from_slices(
- grpc_core::ExternallyManagedSlice(key.data(), key.size()),
- grpc_core::ExternallyManagedSlice(value.data(), value.size()));
- GPR_ASSERT(grpc_metadata_batch_link_tail(batch_, linked_mdelem) ==
- GRPC_ERROR_NONE);
- }
-
- iterator begin() const override {
- static_assert(sizeof(grpc_linked_mdelem*) <= sizeof(intptr_t),
- "iterator size too large");
+ grpc_linked_mdelem* linked_mdelem = static_cast<grpc_linked_mdelem*>(
+ calld_->arena_->Alloc(sizeof(grpc_linked_mdelem)));
+ linked_mdelem->md = grpc_mdelem_from_slices(
+ grpc_core::ExternallyManagedSlice(key.data(), key.size()),
+ grpc_core::ExternallyManagedSlice(value.data(), value.size()));
+ GPR_ASSERT(grpc_metadata_batch_link_tail(batch_, linked_mdelem) ==
+ GRPC_ERROR_NONE);
+ }
+
+ iterator begin() const override {
+ static_assert(sizeof(grpc_linked_mdelem*) <= sizeof(intptr_t),
+ "iterator size too large");
return iterator(
this, reinterpret_cast<intptr_t>(MaybeSkipEntry(batch_->list.head)));
- }
- iterator end() const override {
- static_assert(sizeof(grpc_linked_mdelem*) <= sizeof(intptr_t),
- "iterator size too large");
- return iterator(this, 0);
- }
-
- iterator erase(iterator it) override {
- grpc_linked_mdelem* linked_mdelem =
- reinterpret_cast<grpc_linked_mdelem*>(GetIteratorHandle(it));
- intptr_t handle = reinterpret_cast<intptr_t>(linked_mdelem->next);
- grpc_metadata_batch_remove(batch_, linked_mdelem);
- return iterator(this, handle);
- }
-
- private:
+ }
+ iterator end() const override {
+ static_assert(sizeof(grpc_linked_mdelem*) <= sizeof(intptr_t),
+ "iterator size too large");
+ return iterator(this, 0);
+ }
+
+ iterator erase(iterator it) override {
+ grpc_linked_mdelem* linked_mdelem =
+ reinterpret_cast<grpc_linked_mdelem*>(GetIteratorHandle(it));
+ intptr_t handle = reinterpret_cast<intptr_t>(linked_mdelem->next);
+ grpc_metadata_batch_remove(batch_, linked_mdelem);
+ return iterator(this, handle);
+ }
+
+ private:
grpc_linked_mdelem* MaybeSkipEntry(grpc_linked_mdelem* entry) const {
if (entry != nullptr && batch_->idx.named.path == entry) {
return entry->next;
@@ -433,557 +433,557 @@ class CallData {
return entry;
}
- intptr_t IteratorHandleNext(intptr_t handle) const override {
- grpc_linked_mdelem* linked_mdelem =
- reinterpret_cast<grpc_linked_mdelem*>(handle);
+ intptr_t IteratorHandleNext(intptr_t handle) const override {
+ grpc_linked_mdelem* linked_mdelem =
+ reinterpret_cast<grpc_linked_mdelem*>(handle);
return reinterpret_cast<intptr_t>(MaybeSkipEntry(linked_mdelem->next));
- }
+ }
std::pair<y_absl::string_view, y_absl::string_view> IteratorHandleGet(
- intptr_t handle) const override {
- grpc_linked_mdelem* linked_mdelem =
- reinterpret_cast<grpc_linked_mdelem*>(handle);
- return std::make_pair(
- StringViewFromSlice(GRPC_MDKEY(linked_mdelem->md)),
- StringViewFromSlice(GRPC_MDVALUE(linked_mdelem->md)));
- }
-
- CallData* calld_;
- grpc_metadata_batch* batch_;
- };
-
- class LbCallState : public LoadBalancingPolicy::CallState {
- public:
- explicit LbCallState(CallData* calld) : calld_(calld) {}
-
- void* Alloc(size_t size) override { return calld_->arena_->Alloc(size); }
-
- const LoadBalancingPolicy::BackendMetricData* GetBackendMetricData()
- override {
- if (calld_->backend_metric_data_ == nullptr) {
- grpc_linked_mdelem* md = calld_->recv_trailing_metadata_->idx.named
- .x_endpoint_load_metrics_bin;
- if (md != nullptr) {
- calld_->backend_metric_data_ =
- ParseBackendMetricData(GRPC_MDVALUE(md->md), calld_->arena_);
- }
- }
- return calld_->backend_metric_data_;
- }
-
+ intptr_t handle) const override {
+ grpc_linked_mdelem* linked_mdelem =
+ reinterpret_cast<grpc_linked_mdelem*>(handle);
+ return std::make_pair(
+ StringViewFromSlice(GRPC_MDKEY(linked_mdelem->md)),
+ StringViewFromSlice(GRPC_MDVALUE(linked_mdelem->md)));
+ }
+
+ CallData* calld_;
+ grpc_metadata_batch* batch_;
+ };
+
+ class LbCallState : public LoadBalancingPolicy::CallState {
+ public:
+ explicit LbCallState(CallData* calld) : calld_(calld) {}
+
+ void* Alloc(size_t size) override { return calld_->arena_->Alloc(size); }
+
+ const LoadBalancingPolicy::BackendMetricData* GetBackendMetricData()
+ override {
+ if (calld_->backend_metric_data_ == nullptr) {
+ grpc_linked_mdelem* md = calld_->recv_trailing_metadata_->idx.named
+ .x_endpoint_load_metrics_bin;
+ if (md != nullptr) {
+ calld_->backend_metric_data_ =
+ ParseBackendMetricData(GRPC_MDVALUE(md->md), calld_->arena_);
+ }
+ }
+ return calld_->backend_metric_data_;
+ }
+
y_absl::string_view ExperimentalGetCallAttribute(const char* key) override {
auto it = calld_->call_attributes_.find(key);
if (it == calld_->call_attributes_.end()) return y_absl::string_view();
return it->second;
}
- private:
- CallData* calld_;
- };
-
- // State used for starting a retryable batch on a subchannel call.
- // This provides its own grpc_transport_stream_op_batch and other data
- // structures needed to populate the ops in the batch.
- // We allocate one struct on the arena for each attempt at starting a
- // batch on a given subchannel call.
- struct SubchannelCallBatchData {
- // Creates a SubchannelCallBatchData object on the call's arena with the
- // specified refcount. If set_on_complete is true, the batch's
- // on_complete callback will be set to point to on_complete();
- // otherwise, the batch's on_complete callback will be null.
- static SubchannelCallBatchData* Create(grpc_call_element* elem,
- int refcount, bool set_on_complete);
-
- void Unref() {
- if (gpr_unref(&refs)) Destroy();
- }
-
- SubchannelCallBatchData(grpc_call_element* elem, CallData* calld,
- int refcount, bool set_on_complete);
- // All dtor code must be added in `Destroy()`. This is because we may
- // call closures in `SubchannelCallBatchData` after they are unrefed by
- // `Unref()`, and msan would complain about accessing this class
- // after calling dtor. As a result we cannot call the `dtor` in `Unref()`.
- // TODO(soheil): We should try to call the dtor in `Unref()`.
- ~SubchannelCallBatchData() { Destroy(); }
- void Destroy();
-
- gpr_refcount refs;
- grpc_call_element* elem;
- RefCountedPtr<SubchannelCall> subchannel_call;
- // The batch to use in the subchannel call.
- // Its payload field points to SubchannelCallRetryState::batch_payload.
- grpc_transport_stream_op_batch batch;
- // For intercepting on_complete.
- grpc_closure on_complete;
- };
-
- // Retry state associated with a subchannel call.
- // Stored in the parent_data of the subchannel call object.
- struct SubchannelCallRetryState {
- explicit SubchannelCallRetryState(grpc_call_context_element* context)
- : batch_payload(context),
- started_send_initial_metadata(false),
- completed_send_initial_metadata(false),
- started_send_trailing_metadata(false),
- completed_send_trailing_metadata(false),
- started_recv_initial_metadata(false),
- completed_recv_initial_metadata(false),
- started_recv_trailing_metadata(false),
- completed_recv_trailing_metadata(false),
- retry_dispatched(false) {}
-
- // SubchannelCallBatchData.batch.payload points to this.
- grpc_transport_stream_op_batch_payload batch_payload;
- // For send_initial_metadata.
- // Note that we need to make a copy of the initial metadata for each
- // subchannel call instead of just referring to the copy in call_data,
- // because filters in the subchannel stack will probably add entries,
- // so we need to start in a pristine state for each attempt of the call.
- grpc_linked_mdelem* send_initial_metadata_storage;
- grpc_metadata_batch send_initial_metadata;
- // For send_message.
- // TODO(roth): Restructure this to eliminate use of ManualConstructor.
- ManualConstructor<ByteStreamCache::CachingByteStream> send_message;
- // For send_trailing_metadata.
- grpc_linked_mdelem* send_trailing_metadata_storage;
- grpc_metadata_batch send_trailing_metadata;
- // For intercepting recv_initial_metadata.
- grpc_metadata_batch recv_initial_metadata;
- grpc_closure recv_initial_metadata_ready;
- bool trailing_metadata_available = false;
- // For intercepting recv_message.
- grpc_closure recv_message_ready;
- OrphanablePtr<ByteStream> recv_message;
- // For intercepting recv_trailing_metadata.
- grpc_metadata_batch recv_trailing_metadata;
- grpc_transport_stream_stats collect_stats;
- grpc_closure recv_trailing_metadata_ready;
- // These fields indicate which ops have been started and completed on
- // this subchannel call.
- size_t started_send_message_count = 0;
- size_t completed_send_message_count = 0;
- size_t started_recv_message_count = 0;
- size_t completed_recv_message_count = 0;
- bool started_send_initial_metadata : 1;
- bool completed_send_initial_metadata : 1;
- bool started_send_trailing_metadata : 1;
- bool completed_send_trailing_metadata : 1;
- bool started_recv_initial_metadata : 1;
- bool completed_recv_initial_metadata : 1;
- bool started_recv_trailing_metadata : 1;
- bool completed_recv_trailing_metadata : 1;
- // State for callback processing.
- SubchannelCallBatchData* recv_initial_metadata_ready_deferred_batch =
- nullptr;
- grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE;
- SubchannelCallBatchData* recv_message_ready_deferred_batch = nullptr;
- grpc_error* recv_message_error = GRPC_ERROR_NONE;
- SubchannelCallBatchData* recv_trailing_metadata_internal_batch = nullptr;
- // NOTE: Do not move this next to the metadata bitfields above. That would
- // save space but will also result in a data race because compiler
- // will generate a 2 byte store which overwrites the meta-data
- // fields upon setting this field.
- bool retry_dispatched : 1;
- };
-
- // Pending batches stored in call data.
- struct PendingBatch {
- // The pending batch. If nullptr, this slot is empty.
- grpc_transport_stream_op_batch* batch;
- // Indicates whether payload for send ops has been cached in CallData.
- bool send_ops_cached;
- };
-
- CallData(grpc_call_element* elem, const ChannelData& chand,
- const grpc_call_element_args& args);
- ~CallData();
-
- // Caches data for send ops so that it can be retried later, if not
- // already cached.
- void MaybeCacheSendOpsForBatch(PendingBatch* pending);
- void FreeCachedSendInitialMetadata(ChannelData* chand);
- // Frees cached send_message at index idx.
- void FreeCachedSendMessage(ChannelData* chand, size_t idx);
- void FreeCachedSendTrailingMetadata(ChannelData* chand);
- // Frees cached send ops that have already been completed after
- // committing the call.
- void FreeCachedSendOpDataAfterCommit(grpc_call_element* elem,
- SubchannelCallRetryState* retry_state);
- // Frees cached send ops that were completed by the completed batch in
- // batch_data. Used when batches are completed after the call is committed.
- void FreeCachedSendOpDataForCompletedBatch(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- SubchannelCallRetryState* retry_state);
-
- static void RecvTrailingMetadataReadyForLoadBalancingPolicy(
- void* arg, grpc_error* error);
- void MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
- grpc_transport_stream_op_batch* batch);
-
- // Returns the index into pending_batches_ to be used for batch.
- static size_t GetBatchIndex(grpc_transport_stream_op_batch* batch);
- void PendingBatchesAdd(grpc_call_element* elem,
- grpc_transport_stream_op_batch* batch);
- void PendingBatchClear(PendingBatch* pending);
- void MaybeClearPendingBatch(grpc_call_element* elem, PendingBatch* pending);
- static void FailPendingBatchInCallCombiner(void* arg, grpc_error* error);
- // A predicate type and some useful implementations for PendingBatchesFail().
- typedef bool (*YieldCallCombinerPredicate)(
- const CallCombinerClosureList& closures);
- static bool YieldCallCombiner(const CallCombinerClosureList& /*closures*/) {
- return true;
- }
- static bool NoYieldCallCombiner(const CallCombinerClosureList& /*closures*/) {
- return false;
- }
- static bool YieldCallCombinerIfPendingBatchesFound(
- const CallCombinerClosureList& closures) {
- return closures.size() > 0;
- }
- // Fails all pending batches.
- // If yield_call_combiner_predicate returns true, assumes responsibility for
- // yielding the call combiner.
- void PendingBatchesFail(
- grpc_call_element* elem, grpc_error* error,
- YieldCallCombinerPredicate yield_call_combiner_predicate);
- static void ResumePendingBatchInCallCombiner(void* arg, grpc_error* ignored);
- // Resumes all pending batches on subchannel_call_.
- void PendingBatchesResume(grpc_call_element* elem);
- // Returns a pointer to the first pending batch for which predicate(batch)
- // returns true, or null if not found.
- template <typename Predicate>
- PendingBatch* PendingBatchFind(grpc_call_element* elem,
- const char* log_message, Predicate predicate);
-
- // Commits the call so that no further retry attempts will be performed.
- void RetryCommit(grpc_call_element* elem,
- SubchannelCallRetryState* retry_state);
- // Starts a retry after appropriate back-off.
- void DoRetry(grpc_call_element* elem, SubchannelCallRetryState* retry_state,
- grpc_millis server_pushback_ms);
- // Returns true if the call is being retried.
- bool MaybeRetry(grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- grpc_status_code status, grpc_mdelem* server_pushback_md);
-
- // Invokes recv_initial_metadata_ready for a subchannel batch.
- static void InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error);
- // Intercepts recv_initial_metadata_ready callback for retries.
- // Commits the call and returns the initial metadata up the stack.
- static void RecvInitialMetadataReady(void* arg, grpc_error* error);
-
- // Invokes recv_message_ready for a subchannel batch.
- static void InvokeRecvMessageCallback(void* arg, grpc_error* error);
- // Intercepts recv_message_ready callback for retries.
- // Commits the call and returns the message up the stack.
- static void RecvMessageReady(void* arg, grpc_error* error);
-
- // Sets *status and *server_pushback_md based on md_batch and error.
- // Only sets *server_pushback_md if server_pushback_md != nullptr.
- void GetCallStatus(grpc_metadata_batch* md_batch, grpc_error* error,
- grpc_status_code* status,
- grpc_mdelem** server_pushback_md);
- // Adds recv_trailing_metadata_ready closure to closures.
- void AddClosureForRecvTrailingMetadataReady(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- grpc_error* error, CallCombinerClosureList* closures);
- // Adds any necessary closures for deferred recv_initial_metadata and
- // recv_message callbacks to closures.
- static void AddClosuresForDeferredRecvCallbacks(
- SubchannelCallBatchData* batch_data,
- SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures);
- // Returns true if any op in the batch was not yet started.
- // Only looks at send ops, since recv ops are always started immediately.
- bool PendingBatchIsUnstarted(PendingBatch* pending,
- SubchannelCallRetryState* retry_state);
- // For any pending batch containing an op that has not yet been started,
- // adds the pending batch's completion closures to closures.
- void AddClosuresToFailUnstartedPendingBatches(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state,
- grpc_error* error, CallCombinerClosureList* closures);
- // Runs necessary closures upon completion of a call attempt.
- void RunClosuresForCompletedCall(SubchannelCallBatchData* batch_data,
- grpc_error* error);
- // Intercepts recv_trailing_metadata_ready callback for retries.
- // Commits the call and returns the trailing metadata up the stack.
- static void RecvTrailingMetadataReady(void* arg, grpc_error* error);
-
- // Adds the on_complete closure for the pending batch completed in
- // batch_data to closures.
- void AddClosuresForCompletedPendingBatch(grpc_call_element* elem,
- SubchannelCallBatchData* batch_data,
- grpc_error* error,
- CallCombinerClosureList* closures);
-
- // If there are any cached ops to replay or pending ops to start on the
- // subchannel call, adds a closure to closures to invoke
- // StartRetriableSubchannelBatches().
- void AddClosuresForReplayOrPendingSendOps(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures);
-
- // Callback used to intercept on_complete from subchannel calls.
- // Called only when retries are enabled.
- static void OnComplete(void* arg, grpc_error* error);
-
- static void StartBatchInCallCombiner(void* arg, grpc_error* ignored);
- // Adds a closure to closures that will execute batch in the call combiner.
- void AddClosureForSubchannelBatch(grpc_call_element* elem,
- grpc_transport_stream_op_batch* batch,
- CallCombinerClosureList* closures);
- // Adds retriable send_initial_metadata op to batch_data.
- void AddRetriableSendInitialMetadataOp(SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data);
- // Adds retriable send_message op to batch_data.
- void AddRetriableSendMessageOp(grpc_call_element* elem,
- SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data);
- // Adds retriable send_trailing_metadata op to batch_data.
- void AddRetriableSendTrailingMetadataOp(SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data);
- // Adds retriable recv_initial_metadata op to batch_data.
- void AddRetriableRecvInitialMetadataOp(SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data);
- // Adds retriable recv_message op to batch_data.
- void AddRetriableRecvMessageOp(SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data);
- // Adds retriable recv_trailing_metadata op to batch_data.
- void AddRetriableRecvTrailingMetadataOp(SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data);
- // Helper function used to start a recv_trailing_metadata batch. This
- // is used in the case where a recv_initial_metadata or recv_message
- // op fails in a way that we know the call is over but when the application
- // has not yet started its own recv_trailing_metadata op.
- void StartInternalRecvTrailingMetadata(grpc_call_element* elem);
- // If there are any cached send ops that need to be replayed on the
- // current subchannel call, creates and returns a new subchannel batch
- // to replay those ops. Otherwise, returns nullptr.
- SubchannelCallBatchData* MaybeCreateSubchannelBatchForReplay(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state);
- // Adds subchannel batches for pending batches to closures.
- void AddSubchannelBatchesForPendingBatches(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state,
- CallCombinerClosureList* closures);
- // Constructs and starts whatever subchannel batches are needed on the
- // subchannel call.
- static void StartRetriableSubchannelBatches(void* arg, grpc_error* ignored);
-
- void CreateSubchannelCall(grpc_call_element* elem);
- // Invoked when a pick is completed, on both success or failure.
- static void PickDone(void* arg, grpc_error* error);
+ private:
+ CallData* calld_;
+ };
+
+ // State used for starting a retryable batch on a subchannel call.
+ // This provides its own grpc_transport_stream_op_batch and other data
+ // structures needed to populate the ops in the batch.
+ // We allocate one struct on the arena for each attempt at starting a
+ // batch on a given subchannel call.
+ struct SubchannelCallBatchData {
+ // Creates a SubchannelCallBatchData object on the call's arena with the
+ // specified refcount. If set_on_complete is true, the batch's
+ // on_complete callback will be set to point to on_complete();
+ // otherwise, the batch's on_complete callback will be null.
+ static SubchannelCallBatchData* Create(grpc_call_element* elem,
+ int refcount, bool set_on_complete);
+
+ void Unref() {
+ if (gpr_unref(&refs)) Destroy();
+ }
+
+ SubchannelCallBatchData(grpc_call_element* elem, CallData* calld,
+ int refcount, bool set_on_complete);
+ // All dtor code must be added in `Destroy()`. This is because we may
+ // call closures in `SubchannelCallBatchData` after they are unrefed by
+ // `Unref()`, and msan would complain about accessing this class
+ // after calling dtor. As a result we cannot call the `dtor` in `Unref()`.
+ // TODO(soheil): We should try to call the dtor in `Unref()`.
+ ~SubchannelCallBatchData() { Destroy(); }
+ void Destroy();
+
+ gpr_refcount refs;
+ grpc_call_element* elem;
+ RefCountedPtr<SubchannelCall> subchannel_call;
+ // The batch to use in the subchannel call.
+ // Its payload field points to SubchannelCallRetryState::batch_payload.
+ grpc_transport_stream_op_batch batch;
+ // For intercepting on_complete.
+ grpc_closure on_complete;
+ };
+
+ // Retry state associated with a subchannel call.
+ // Stored in the parent_data of the subchannel call object.
+ struct SubchannelCallRetryState {
+ explicit SubchannelCallRetryState(grpc_call_context_element* context)
+ : batch_payload(context),
+ started_send_initial_metadata(false),
+ completed_send_initial_metadata(false),
+ started_send_trailing_metadata(false),
+ completed_send_trailing_metadata(false),
+ started_recv_initial_metadata(false),
+ completed_recv_initial_metadata(false),
+ started_recv_trailing_metadata(false),
+ completed_recv_trailing_metadata(false),
+ retry_dispatched(false) {}
+
+ // SubchannelCallBatchData.batch.payload points to this.
+ grpc_transport_stream_op_batch_payload batch_payload;
+ // For send_initial_metadata.
+ // Note that we need to make a copy of the initial metadata for each
+ // subchannel call instead of just referring to the copy in call_data,
+ // because filters in the subchannel stack will probably add entries,
+ // so we need to start in a pristine state for each attempt of the call.
+ grpc_linked_mdelem* send_initial_metadata_storage;
+ grpc_metadata_batch send_initial_metadata;
+ // For send_message.
+ // TODO(roth): Restructure this to eliminate use of ManualConstructor.
+ ManualConstructor<ByteStreamCache::CachingByteStream> send_message;
+ // For send_trailing_metadata.
+ grpc_linked_mdelem* send_trailing_metadata_storage;
+ grpc_metadata_batch send_trailing_metadata;
+ // For intercepting recv_initial_metadata.
+ grpc_metadata_batch recv_initial_metadata;
+ grpc_closure recv_initial_metadata_ready;
+ bool trailing_metadata_available = false;
+ // For intercepting recv_message.
+ grpc_closure recv_message_ready;
+ OrphanablePtr<ByteStream> recv_message;
+ // For intercepting recv_trailing_metadata.
+ grpc_metadata_batch recv_trailing_metadata;
+ grpc_transport_stream_stats collect_stats;
+ grpc_closure recv_trailing_metadata_ready;
+ // These fields indicate which ops have been started and completed on
+ // this subchannel call.
+ size_t started_send_message_count = 0;
+ size_t completed_send_message_count = 0;
+ size_t started_recv_message_count = 0;
+ size_t completed_recv_message_count = 0;
+ bool started_send_initial_metadata : 1;
+ bool completed_send_initial_metadata : 1;
+ bool started_send_trailing_metadata : 1;
+ bool completed_send_trailing_metadata : 1;
+ bool started_recv_initial_metadata : 1;
+ bool completed_recv_initial_metadata : 1;
+ bool started_recv_trailing_metadata : 1;
+ bool completed_recv_trailing_metadata : 1;
+ // State for callback processing.
+ SubchannelCallBatchData* recv_initial_metadata_ready_deferred_batch =
+ nullptr;
+ grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE;
+ SubchannelCallBatchData* recv_message_ready_deferred_batch = nullptr;
+ grpc_error* recv_message_error = GRPC_ERROR_NONE;
+ SubchannelCallBatchData* recv_trailing_metadata_internal_batch = nullptr;
+ // NOTE: Do not move this next to the metadata bitfields above. That would
+ // save space but will also result in a data race because compiler
+ // will generate a 2 byte store which overwrites the meta-data
+ // fields upon setting this field.
+ bool retry_dispatched : 1;
+ };
+
+ // Pending batches stored in call data.
+ struct PendingBatch {
+ // The pending batch. If nullptr, this slot is empty.
+ grpc_transport_stream_op_batch* batch;
+ // Indicates whether payload for send ops has been cached in CallData.
+ bool send_ops_cached;
+ };
+
+ CallData(grpc_call_element* elem, const ChannelData& chand,
+ const grpc_call_element_args& args);
+ ~CallData();
+
+ // Caches data for send ops so that it can be retried later, if not
+ // already cached.
+ void MaybeCacheSendOpsForBatch(PendingBatch* pending);
+ void FreeCachedSendInitialMetadata(ChannelData* chand);
+ // Frees cached send_message at index idx.
+ void FreeCachedSendMessage(ChannelData* chand, size_t idx);
+ void FreeCachedSendTrailingMetadata(ChannelData* chand);
+ // Frees cached send ops that have already been completed after
+ // committing the call.
+ void FreeCachedSendOpDataAfterCommit(grpc_call_element* elem,
+ SubchannelCallRetryState* retry_state);
+ // Frees cached send ops that were completed by the completed batch in
+ // batch_data. Used when batches are completed after the call is committed.
+ void FreeCachedSendOpDataForCompletedBatch(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ SubchannelCallRetryState* retry_state);
+
+ static void RecvTrailingMetadataReadyForLoadBalancingPolicy(
+ void* arg, grpc_error* error);
+ void MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
+ grpc_transport_stream_op_batch* batch);
+
+ // Returns the index into pending_batches_ to be used for batch.
+ static size_t GetBatchIndex(grpc_transport_stream_op_batch* batch);
+ void PendingBatchesAdd(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* batch);
+ void PendingBatchClear(PendingBatch* pending);
+ void MaybeClearPendingBatch(grpc_call_element* elem, PendingBatch* pending);
+ static void FailPendingBatchInCallCombiner(void* arg, grpc_error* error);
+ // A predicate type and some useful implementations for PendingBatchesFail().
+ typedef bool (*YieldCallCombinerPredicate)(
+ const CallCombinerClosureList& closures);
+ static bool YieldCallCombiner(const CallCombinerClosureList& /*closures*/) {
+ return true;
+ }
+ static bool NoYieldCallCombiner(const CallCombinerClosureList& /*closures*/) {
+ return false;
+ }
+ static bool YieldCallCombinerIfPendingBatchesFound(
+ const CallCombinerClosureList& closures) {
+ return closures.size() > 0;
+ }
+ // Fails all pending batches.
+ // If yield_call_combiner_predicate returns true, assumes responsibility for
+ // yielding the call combiner.
+ void PendingBatchesFail(
+ grpc_call_element* elem, grpc_error* error,
+ YieldCallCombinerPredicate yield_call_combiner_predicate);
+ static void ResumePendingBatchInCallCombiner(void* arg, grpc_error* ignored);
+ // Resumes all pending batches on subchannel_call_.
+ void PendingBatchesResume(grpc_call_element* elem);
+ // Returns a pointer to the first pending batch for which predicate(batch)
+ // returns true, or null if not found.
+ template <typename Predicate>
+ PendingBatch* PendingBatchFind(grpc_call_element* elem,
+ const char* log_message, Predicate predicate);
+
+ // Commits the call so that no further retry attempts will be performed.
+ void RetryCommit(grpc_call_element* elem,
+ SubchannelCallRetryState* retry_state);
+ // Starts a retry after appropriate back-off.
+ void DoRetry(grpc_call_element* elem, SubchannelCallRetryState* retry_state,
+ grpc_millis server_pushback_ms);
+ // Returns true if the call is being retried.
+ bool MaybeRetry(grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ grpc_status_code status, grpc_mdelem* server_pushback_md);
+
+ // Invokes recv_initial_metadata_ready for a subchannel batch.
+ static void InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error);
+ // Intercepts recv_initial_metadata_ready callback for retries.
+ // Commits the call and returns the initial metadata up the stack.
+ static void RecvInitialMetadataReady(void* arg, grpc_error* error);
+
+ // Invokes recv_message_ready for a subchannel batch.
+ static void InvokeRecvMessageCallback(void* arg, grpc_error* error);
+ // Intercepts recv_message_ready callback for retries.
+ // Commits the call and returns the message up the stack.
+ static void RecvMessageReady(void* arg, grpc_error* error);
+
+ // Sets *status and *server_pushback_md based on md_batch and error.
+ // Only sets *server_pushback_md if server_pushback_md != nullptr.
+ void GetCallStatus(grpc_metadata_batch* md_batch, grpc_error* error,
+ grpc_status_code* status,
+ grpc_mdelem** server_pushback_md);
+ // Adds recv_trailing_metadata_ready closure to closures.
+ void AddClosureForRecvTrailingMetadataReady(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ grpc_error* error, CallCombinerClosureList* closures);
+ // Adds any necessary closures for deferred recv_initial_metadata and
+ // recv_message callbacks to closures.
+ static void AddClosuresForDeferredRecvCallbacks(
+ SubchannelCallBatchData* batch_data,
+ SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures);
+ // Returns true if any op in the batch was not yet started.
+ // Only looks at send ops, since recv ops are always started immediately.
+ bool PendingBatchIsUnstarted(PendingBatch* pending,
+ SubchannelCallRetryState* retry_state);
+ // For any pending batch containing an op that has not yet been started,
+ // adds the pending batch's completion closures to closures.
+ void AddClosuresToFailUnstartedPendingBatches(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state,
+ grpc_error* error, CallCombinerClosureList* closures);
+ // Runs necessary closures upon completion of a call attempt.
+ void RunClosuresForCompletedCall(SubchannelCallBatchData* batch_data,
+ grpc_error* error);
+ // Intercepts recv_trailing_metadata_ready callback for retries.
+ // Commits the call and returns the trailing metadata up the stack.
+ static void RecvTrailingMetadataReady(void* arg, grpc_error* error);
+
+ // Adds the on_complete closure for the pending batch completed in
+ // batch_data to closures.
+ void AddClosuresForCompletedPendingBatch(grpc_call_element* elem,
+ SubchannelCallBatchData* batch_data,
+ grpc_error* error,
+ CallCombinerClosureList* closures);
+
+ // If there are any cached ops to replay or pending ops to start on the
+ // subchannel call, adds a closure to closures to invoke
+ // StartRetriableSubchannelBatches().
+ void AddClosuresForReplayOrPendingSendOps(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures);
+
+ // Callback used to intercept on_complete from subchannel calls.
+ // Called only when retries are enabled.
+ static void OnComplete(void* arg, grpc_error* error);
+
+ static void StartBatchInCallCombiner(void* arg, grpc_error* ignored);
+ // Adds a closure to closures that will execute batch in the call combiner.
+ void AddClosureForSubchannelBatch(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* batch,
+ CallCombinerClosureList* closures);
+ // Adds retriable send_initial_metadata op to batch_data.
+ void AddRetriableSendInitialMetadataOp(SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data);
+ // Adds retriable send_message op to batch_data.
+ void AddRetriableSendMessageOp(grpc_call_element* elem,
+ SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data);
+ // Adds retriable send_trailing_metadata op to batch_data.
+ void AddRetriableSendTrailingMetadataOp(SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data);
+ // Adds retriable recv_initial_metadata op to batch_data.
+ void AddRetriableRecvInitialMetadataOp(SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data);
+ // Adds retriable recv_message op to batch_data.
+ void AddRetriableRecvMessageOp(SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data);
+ // Adds retriable recv_trailing_metadata op to batch_data.
+ void AddRetriableRecvTrailingMetadataOp(SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data);
+ // Helper function used to start a recv_trailing_metadata batch. This
+ // is used in the case where a recv_initial_metadata or recv_message
+ // op fails in a way that we know the call is over but when the application
+ // has not yet started its own recv_trailing_metadata op.
+ void StartInternalRecvTrailingMetadata(grpc_call_element* elem);
+ // If there are any cached send ops that need to be replayed on the
+ // current subchannel call, creates and returns a new subchannel batch
+ // to replay those ops. Otherwise, returns nullptr.
+ SubchannelCallBatchData* MaybeCreateSubchannelBatchForReplay(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state);
+ // Adds subchannel batches for pending batches to closures.
+ void AddSubchannelBatchesForPendingBatches(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state,
+ CallCombinerClosureList* closures);
+ // Constructs and starts whatever subchannel batches are needed on the
+ // subchannel call.
+ static void StartRetriableSubchannelBatches(void* arg, grpc_error* ignored);
+
+ void CreateSubchannelCall(grpc_call_element* elem);
+ // Invoked when a pick is completed, on both success or failure.
+ static void PickDone(void* arg, grpc_error* error);
// Removes the call from the channel's list of queued picks if present.
void MaybeRemoveCallFromQueuedPicksLocked(grpc_call_element* elem);
// Adds the call to the channel's list of queued picks if not already present.
void MaybeAddCallToQueuedPicksLocked(grpc_call_element* elem);
- // Applies service config to the call. Must be invoked once we know
- // that the resolver has returned results to the channel.
+ // Applies service config to the call. Must be invoked once we know
+ // that the resolver has returned results to the channel.
// If an error is returned, the error indicates the status with which
// the call should be failed.
grpc_error* ApplyServiceConfigToCallLocked(
grpc_call_element* elem, grpc_metadata_batch* initial_metadata);
void MaybeInvokeConfigSelectorCommitCallback();
-
- // State for handling deadlines.
- // The code in deadline_filter.c requires this to be the first field.
- // TODO(roth): This is slightly sub-optimal in that grpc_deadline_state
- // and this struct both independently store pointers to the call stack
- // and call combiner. If/when we have time, find a way to avoid this
- // without breaking the grpc_deadline_state abstraction.
- grpc_deadline_state deadline_state_;
-
- grpc_slice path_; // Request path.
- gpr_cycle_counter call_start_time_;
- grpc_millis deadline_;
- Arena* arena_;
- grpc_call_stack* owning_call_;
- CallCombiner* call_combiner_;
- grpc_call_context_element* call_context_;
-
- RefCountedPtr<ServerRetryThrottleData> retry_throttle_data_;
- const ClientChannelMethodParsedConfig* method_params_ = nullptr;
+
+ // State for handling deadlines.
+ // The code in deadline_filter.c requires this to be the first field.
+ // TODO(roth): This is slightly sub-optimal in that grpc_deadline_state
+ // and this struct both independently store pointers to the call stack
+ // and call combiner. If/when we have time, find a way to avoid this
+ // without breaking the grpc_deadline_state abstraction.
+ grpc_deadline_state deadline_state_;
+
+ grpc_slice path_; // Request path.
+ gpr_cycle_counter call_start_time_;
+ grpc_millis deadline_;
+ Arena* arena_;
+ grpc_call_stack* owning_call_;
+ CallCombiner* call_combiner_;
+ grpc_call_context_element* call_context_;
+
+ RefCountedPtr<ServerRetryThrottleData> retry_throttle_data_;
+ const ClientChannelMethodParsedConfig* method_params_ = nullptr;
std::map<const char*, y_absl::string_view> call_attributes_;
std::function<void()> on_call_committed_;
-
- RefCountedPtr<SubchannelCall> subchannel_call_;
-
- // Set when we get a cancel_stream op.
- grpc_error* cancel_error_ = GRPC_ERROR_NONE;
-
- ChannelData::QueuedPick pick_;
- bool pick_queued_ = false;
- bool service_config_applied_ = false;
- QueuedPickCanceller* pick_canceller_ = nullptr;
- LbCallState lb_call_state_;
- const LoadBalancingPolicy::BackendMetricData* backend_metric_data_ = nullptr;
- RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
- std::function<void(grpc_error*, LoadBalancingPolicy::MetadataInterface*,
- LoadBalancingPolicy::CallState*)>
- lb_recv_trailing_metadata_ready_;
- grpc_closure pick_closure_;
-
- // For intercepting recv_trailing_metadata_ready for the LB policy.
- grpc_metadata_batch* recv_trailing_metadata_ = nullptr;
- grpc_closure recv_trailing_metadata_ready_;
- grpc_closure* original_recv_trailing_metadata_ready_ = nullptr;
-
- grpc_polling_entity* pollent_ = nullptr;
-
- // Batches are added to this list when received from above.
- // They are removed when we are done handling the batch (i.e., when
- // either we have invoked all of the batch's callbacks or we have
- // passed the batch down to the subchannel call and are not
- // intercepting any of its callbacks).
- PendingBatch pending_batches_[MAX_PENDING_BATCHES] = {};
- bool pending_send_initial_metadata_ : 1;
- bool pending_send_message_ : 1;
- bool pending_send_trailing_metadata_ : 1;
-
- // Retry state.
- bool enable_retries_ : 1;
- bool retry_committed_ : 1;
- bool last_attempt_got_server_pushback_ : 1;
- int num_attempts_completed_ = 0;
- size_t bytes_buffered_for_retry_ = 0;
- // TODO(roth): Restructure this to eliminate use of ManualConstructor.
- ManualConstructor<BackOff> retry_backoff_;
- grpc_timer retry_timer_;
-
- // The number of pending retriable subchannel batches containing send ops.
- // We hold a ref to the call stack while this is non-zero, since replay
- // batches may not complete until after all callbacks have been returned
- // to the surface, and we need to make sure that the call is not destroyed
- // until all of these batches have completed.
- // Note that we actually only need to track replay batches, but it's
- // easier to track all batches with send ops.
- int num_pending_retriable_subchannel_send_batches_ = 0;
-
- // Cached data for retrying send ops.
- // send_initial_metadata
- bool seen_send_initial_metadata_ = false;
- grpc_linked_mdelem* send_initial_metadata_storage_ = nullptr;
- grpc_metadata_batch send_initial_metadata_;
- uint32_t send_initial_metadata_flags_;
- gpr_atm* peer_string_;
- // send_message
- // When we get a send_message op, we replace the original byte stream
- // with a CachingByteStream that caches the slices to a local buffer for
- // use in retries.
- // Note: We inline the cache for the first 3 send_message ops and use
- // dynamic allocation after that. This number was essentially picked
- // at random; it could be changed in the future to tune performance.
+
+ RefCountedPtr<SubchannelCall> subchannel_call_;
+
+ // Set when we get a cancel_stream op.
+ grpc_error* cancel_error_ = GRPC_ERROR_NONE;
+
+ ChannelData::QueuedPick pick_;
+ bool pick_queued_ = false;
+ bool service_config_applied_ = false;
+ QueuedPickCanceller* pick_canceller_ = nullptr;
+ LbCallState lb_call_state_;
+ const LoadBalancingPolicy::BackendMetricData* backend_metric_data_ = nullptr;
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
+ std::function<void(grpc_error*, LoadBalancingPolicy::MetadataInterface*,
+ LoadBalancingPolicy::CallState*)>
+ lb_recv_trailing_metadata_ready_;
+ grpc_closure pick_closure_;
+
+ // For intercepting recv_trailing_metadata_ready for the LB policy.
+ grpc_metadata_batch* recv_trailing_metadata_ = nullptr;
+ grpc_closure recv_trailing_metadata_ready_;
+ grpc_closure* original_recv_trailing_metadata_ready_ = nullptr;
+
+ grpc_polling_entity* pollent_ = nullptr;
+
+ // Batches are added to this list when received from above.
+ // They are removed when we are done handling the batch (i.e., when
+ // either we have invoked all of the batch's callbacks or we have
+ // passed the batch down to the subchannel call and are not
+ // intercepting any of its callbacks).
+ PendingBatch pending_batches_[MAX_PENDING_BATCHES] = {};
+ bool pending_send_initial_metadata_ : 1;
+ bool pending_send_message_ : 1;
+ bool pending_send_trailing_metadata_ : 1;
+
+ // Retry state.
+ bool enable_retries_ : 1;
+ bool retry_committed_ : 1;
+ bool last_attempt_got_server_pushback_ : 1;
+ int num_attempts_completed_ = 0;
+ size_t bytes_buffered_for_retry_ = 0;
+ // TODO(roth): Restructure this to eliminate use of ManualConstructor.
+ ManualConstructor<BackOff> retry_backoff_;
+ grpc_timer retry_timer_;
+
+ // The number of pending retriable subchannel batches containing send ops.
+ // We hold a ref to the call stack while this is non-zero, since replay
+ // batches may not complete until after all callbacks have been returned
+ // to the surface, and we need to make sure that the call is not destroyed
+ // until all of these batches have completed.
+ // Note that we actually only need to track replay batches, but it's
+ // easier to track all batches with send ops.
+ int num_pending_retriable_subchannel_send_batches_ = 0;
+
+ // Cached data for retrying send ops.
+ // send_initial_metadata
+ bool seen_send_initial_metadata_ = false;
+ grpc_linked_mdelem* send_initial_metadata_storage_ = nullptr;
+ grpc_metadata_batch send_initial_metadata_;
+ uint32_t send_initial_metadata_flags_;
+ gpr_atm* peer_string_;
+ // send_message
+ // When we get a send_message op, we replace the original byte stream
+ // with a CachingByteStream that caches the slices to a local buffer for
+ // use in retries.
+ // Note: We inline the cache for the first 3 send_message ops and use
+ // dynamic allocation after that. This number was essentially picked
+ // at random; it could be changed in the future to tune performance.
y_absl::InlinedVector<ByteStreamCache*, 3> send_messages_;
- // send_trailing_metadata
- bool seen_send_trailing_metadata_ = false;
- grpc_linked_mdelem* send_trailing_metadata_storage_ = nullptr;
- grpc_metadata_batch send_trailing_metadata_;
-};
-
-//
-// ChannelData::SubchannelWrapper
-//
-
+ // send_trailing_metadata
+ bool seen_send_trailing_metadata_ = false;
+ grpc_linked_mdelem* send_trailing_metadata_storage_ = nullptr;
+ grpc_metadata_batch send_trailing_metadata_;
+};
+
+//
+// ChannelData::SubchannelWrapper
+//
+
using ServerAddressAttributeMap =
std::map<const char*, std::unique_ptr<ServerAddress::AttributeInterface>>;
-// This class is a wrapper for Subchannel that hides details of the
-// channel's implementation (such as the health check service name and
-// connected subchannel) from the LB policy API.
-//
-// Note that no synchronization is needed here, because even if the
-// underlying subchannel is shared between channels, this wrapper will only
-// be used within one channel, so it will always be synchronized by the
+// This class is a wrapper for Subchannel that hides details of the
+// channel's implementation (such as the health check service name and
+// connected subchannel) from the LB policy API.
+//
+// Note that no synchronization is needed here, because even if the
+// underlying subchannel is shared between channels, this wrapper will only
+// be used within one channel, so it will always be synchronized by the
// control plane work_serializer.
-class ChannelData::SubchannelWrapper : public SubchannelInterface {
- public:
- SubchannelWrapper(ChannelData* chand, Subchannel* subchannel,
+class ChannelData::SubchannelWrapper : public SubchannelInterface {
+ public:
+ SubchannelWrapper(ChannelData* chand, Subchannel* subchannel,
grpc_core::UniquePtr<char> health_check_service_name,
ServerAddressAttributeMap attributes)
- : SubchannelInterface(&grpc_client_channel_routing_trace),
- chand_(chand),
- subchannel_(subchannel),
+ : SubchannelInterface(&grpc_client_channel_routing_trace),
+ chand_(chand),
+ subchannel_(subchannel),
health_check_service_name_(std::move(health_check_service_name)),
attributes_(std::move(attributes)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p: creating subchannel wrapper %p for subchannel %p",
- chand, this, subchannel_);
- }
- GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "SubchannelWrapper");
- auto* subchannel_node = subchannel_->channelz_node();
- if (subchannel_node != nullptr) {
- auto it = chand_->subchannel_refcount_map_.find(subchannel_);
- if (it == chand_->subchannel_refcount_map_.end()) {
- chand_->channelz_node_->AddChildSubchannel(subchannel_node->uuid());
- it = chand_->subchannel_refcount_map_.emplace(subchannel_, 0).first;
- }
- ++it->second;
- }
- chand_->subchannel_wrappers_.insert(this);
- }
-
- ~SubchannelWrapper() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p: destroying subchannel wrapper %p for subchannel %p",
- chand_, this, subchannel_);
- }
- chand_->subchannel_wrappers_.erase(this);
- auto* subchannel_node = subchannel_->channelz_node();
- if (subchannel_node != nullptr) {
- auto it = chand_->subchannel_refcount_map_.find(subchannel_);
- GPR_ASSERT(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);
- }
- }
- GRPC_SUBCHANNEL_UNREF(subchannel_, "unref from LB");
- GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_, "SubchannelWrapper");
- }
-
- grpc_connectivity_state CheckConnectivityState() override {
- RefCountedPtr<ConnectedSubchannel> connected_subchannel;
- grpc_connectivity_state connectivity_state =
- subchannel_->CheckConnectivityState(health_check_service_name_.get(),
- &connected_subchannel);
- MaybeUpdateConnectedSubchannel(std::move(connected_subchannel));
- return connectivity_state;
- }
-
- void WatchConnectivityState(
- grpc_connectivity_state initial_state,
- std::unique_ptr<ConnectivityStateWatcherInterface> watcher) override {
- auto& watcher_wrapper = watcher_map_[watcher.get()];
- GPR_ASSERT(watcher_wrapper == nullptr);
- watcher_wrapper = new WatcherWrapper(std::move(watcher),
- Ref(DEBUG_LOCATION, "WatcherWrapper"),
- initial_state);
- subchannel_->WatchConnectivityState(
- initial_state,
- grpc_core::UniquePtr<char>(
- gpr_strdup(health_check_service_name_.get())),
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p: creating subchannel wrapper %p for subchannel %p",
+ chand, this, subchannel_);
+ }
+ GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "SubchannelWrapper");
+ auto* subchannel_node = subchannel_->channelz_node();
+ if (subchannel_node != nullptr) {
+ auto it = chand_->subchannel_refcount_map_.find(subchannel_);
+ if (it == chand_->subchannel_refcount_map_.end()) {
+ chand_->channelz_node_->AddChildSubchannel(subchannel_node->uuid());
+ it = chand_->subchannel_refcount_map_.emplace(subchannel_, 0).first;
+ }
+ ++it->second;
+ }
+ chand_->subchannel_wrappers_.insert(this);
+ }
+
+ ~SubchannelWrapper() {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p: destroying subchannel wrapper %p for subchannel %p",
+ chand_, this, subchannel_);
+ }
+ chand_->subchannel_wrappers_.erase(this);
+ auto* subchannel_node = subchannel_->channelz_node();
+ if (subchannel_node != nullptr) {
+ auto it = chand_->subchannel_refcount_map_.find(subchannel_);
+ GPR_ASSERT(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);
+ }
+ }
+ GRPC_SUBCHANNEL_UNREF(subchannel_, "unref from LB");
+ GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_, "SubchannelWrapper");
+ }
+
+ grpc_connectivity_state CheckConnectivityState() override {
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel;
+ grpc_connectivity_state connectivity_state =
+ subchannel_->CheckConnectivityState(health_check_service_name_.get(),
+ &connected_subchannel);
+ MaybeUpdateConnectedSubchannel(std::move(connected_subchannel));
+ return connectivity_state;
+ }
+
+ void WatchConnectivityState(
+ grpc_connectivity_state initial_state,
+ std::unique_ptr<ConnectivityStateWatcherInterface> watcher) override {
+ auto& watcher_wrapper = watcher_map_[watcher.get()];
+ GPR_ASSERT(watcher_wrapper == nullptr);
+ watcher_wrapper = new WatcherWrapper(std::move(watcher),
+ Ref(DEBUG_LOCATION, "WatcherWrapper"),
+ initial_state);
+ subchannel_->WatchConnectivityState(
+ initial_state,
+ grpc_core::UniquePtr<char>(
+ gpr_strdup(health_check_service_name_.get())),
RefCountedPtr<Subchannel::ConnectivityStateWatcherInterface>(
- watcher_wrapper));
- }
-
- void CancelConnectivityStateWatch(
- ConnectivityStateWatcherInterface* watcher) override {
- auto it = watcher_map_.find(watcher);
- GPR_ASSERT(it != watcher_map_.end());
- subchannel_->CancelConnectivityStateWatch(health_check_service_name_.get(),
- it->second);
- watcher_map_.erase(it);
- }
-
- void AttemptToConnect() override { subchannel_->AttemptToConnect(); }
-
- void ResetBackoff() override { subchannel_->ResetBackoff(); }
-
- const grpc_channel_args* channel_args() override {
- return subchannel_->channel_args();
- }
-
+ watcher_wrapper));
+ }
+
+ void CancelConnectivityStateWatch(
+ ConnectivityStateWatcherInterface* watcher) override {
+ auto it = watcher_map_.find(watcher);
+ GPR_ASSERT(it != watcher_map_.end());
+ subchannel_->CancelConnectivityStateWatch(health_check_service_name_.get(),
+ it->second);
+ watcher_map_.erase(it);
+ }
+
+ void AttemptToConnect() override { subchannel_->AttemptToConnect(); }
+
+ void ResetBackoff() override { subchannel_->ResetBackoff(); }
+
+ const grpc_channel_args* channel_args() override {
+ return subchannel_->channel_args();
+ }
+
const ServerAddress::AttributeInterface* GetAttribute(
const char* key) const override {
auto it = attributes_.find(key);
@@ -995,96 +995,96 @@ class ChannelData::SubchannelWrapper : public SubchannelInterface {
subchannel_->ThrottleKeepaliveTime(new_keepalive_time);
}
- void UpdateHealthCheckServiceName(
- grpc_core::UniquePtr<char> health_check_service_name) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p: subchannel wrapper %p: updating health check service "
- "name from \"%s\" to \"%s\"",
- chand_, this, health_check_service_name_.get(),
- health_check_service_name.get());
- }
- for (auto& p : watcher_map_) {
- WatcherWrapper*& watcher_wrapper = p.second;
- // Cancel the current watcher and create a new one using the new
- // health check service name.
- // TODO(roth): If there is not already an existing health watch
- // call for the new name, then the watcher will initially report
- // state CONNECTING. If the LB policy is currently reporting
- // state READY, this may cause it to switch to CONNECTING before
- // switching back to READY. This could cause a small delay for
- // RPCs being started on the channel. If/when this becomes a
- // problem, we may be able to handle it by waiting for the new
- // watcher to report READY before we use it to replace the old one.
- WatcherWrapper* replacement = watcher_wrapper->MakeReplacement();
- subchannel_->CancelConnectivityStateWatch(
- health_check_service_name_.get(), watcher_wrapper);
- watcher_wrapper = replacement;
- subchannel_->WatchConnectivityState(
- replacement->last_seen_state(),
- grpc_core::UniquePtr<char>(
- gpr_strdup(health_check_service_name.get())),
+ void UpdateHealthCheckServiceName(
+ grpc_core::UniquePtr<char> health_check_service_name) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p: subchannel wrapper %p: updating health check service "
+ "name from \"%s\" to \"%s\"",
+ chand_, this, health_check_service_name_.get(),
+ health_check_service_name.get());
+ }
+ for (auto& p : watcher_map_) {
+ WatcherWrapper*& watcher_wrapper = p.second;
+ // Cancel the current watcher and create a new one using the new
+ // health check service name.
+ // TODO(roth): If there is not already an existing health watch
+ // call for the new name, then the watcher will initially report
+ // state CONNECTING. If the LB policy is currently reporting
+ // state READY, this may cause it to switch to CONNECTING before
+ // switching back to READY. This could cause a small delay for
+ // RPCs being started on the channel. If/when this becomes a
+ // problem, we may be able to handle it by waiting for the new
+ // watcher to report READY before we use it to replace the old one.
+ WatcherWrapper* replacement = watcher_wrapper->MakeReplacement();
+ subchannel_->CancelConnectivityStateWatch(
+ health_check_service_name_.get(), watcher_wrapper);
+ watcher_wrapper = replacement;
+ subchannel_->WatchConnectivityState(
+ replacement->last_seen_state(),
+ grpc_core::UniquePtr<char>(
+ gpr_strdup(health_check_service_name.get())),
RefCountedPtr<Subchannel::ConnectivityStateWatcherInterface>(
- replacement));
- }
- // Save the new health check service name.
- health_check_service_name_ = std::move(health_check_service_name);
- }
-
+ replacement));
+ }
+ // Save the new health check service name.
+ health_check_service_name_ = std::move(health_check_service_name);
+ }
+
// Caller must be holding the control-plane work_serializer.
- ConnectedSubchannel* connected_subchannel() const {
- return connected_subchannel_.get();
- }
-
- // Caller must be holding the data-plane mutex.
- ConnectedSubchannel* connected_subchannel_in_data_plane() const {
- return connected_subchannel_in_data_plane_.get();
- }
- void set_connected_subchannel_in_data_plane(
- RefCountedPtr<ConnectedSubchannel> connected_subchannel) {
- connected_subchannel_in_data_plane_ = std::move(connected_subchannel);
- }
-
- private:
- // Subchannel and SubchannelInterface have different interfaces for
- // their respective ConnectivityStateWatcherInterface classes.
- // The one in Subchannel updates the ConnectedSubchannel along with
- // the state, whereas the one in SubchannelInterface does not expose
- // the ConnectedSubchannel.
- //
- // This wrapper provides a bridge between the two. It implements
- // Subchannel::ConnectivityStateWatcherInterface and wraps
- // the instance of SubchannelInterface::ConnectivityStateWatcherInterface
- // that was passed in by the LB policy. We pass an instance of this
- // class to the underlying Subchannel, and when we get updates from
- // the subchannel, we pass those on to the wrapped watcher to return
- // the update to the LB policy. This allows us to set the connected
- // subchannel before passing the result back to the LB policy.
- class WatcherWrapper : public Subchannel::ConnectivityStateWatcherInterface {
- public:
- WatcherWrapper(
- std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>
- watcher,
- RefCountedPtr<SubchannelWrapper> parent,
- grpc_connectivity_state initial_state)
- : watcher_(std::move(watcher)),
- parent_(std::move(parent)),
- last_seen_state_(initial_state) {}
-
+ ConnectedSubchannel* connected_subchannel() const {
+ return connected_subchannel_.get();
+ }
+
+ // Caller must be holding the data-plane mutex.
+ ConnectedSubchannel* connected_subchannel_in_data_plane() const {
+ return connected_subchannel_in_data_plane_.get();
+ }
+ void set_connected_subchannel_in_data_plane(
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel) {
+ connected_subchannel_in_data_plane_ = std::move(connected_subchannel);
+ }
+
+ private:
+ // Subchannel and SubchannelInterface have different interfaces for
+ // their respective ConnectivityStateWatcherInterface classes.
+ // The one in Subchannel updates the ConnectedSubchannel along with
+ // the state, whereas the one in SubchannelInterface does not expose
+ // the ConnectedSubchannel.
+ //
+ // This wrapper provides a bridge between the two. It implements
+ // Subchannel::ConnectivityStateWatcherInterface and wraps
+ // the instance of SubchannelInterface::ConnectivityStateWatcherInterface
+ // that was passed in by the LB policy. We pass an instance of this
+ // class to the underlying Subchannel, and when we get updates from
+ // the subchannel, we pass those on to the wrapped watcher to return
+ // the update to the LB policy. This allows us to set the connected
+ // subchannel before passing the result back to the LB policy.
+ class WatcherWrapper : public Subchannel::ConnectivityStateWatcherInterface {
+ public:
+ WatcherWrapper(
+ std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>
+ watcher,
+ RefCountedPtr<SubchannelWrapper> parent,
+ grpc_connectivity_state initial_state)
+ : watcher_(std::move(watcher)),
+ parent_(std::move(parent)),
+ last_seen_state_(initial_state) {}
+
~WatcherWrapper() {
auto* parent = parent_.release(); // ref owned by lambda
parent->chand_->work_serializer_->Run(
[parent]() { parent->Unref(DEBUG_LOCATION, "WatcherWrapper"); },
DEBUG_LOCATION);
}
-
+
void OnConnectivityStateChange() override {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p: connectivity change for subchannel wrapper %p "
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p: connectivity change for subchannel wrapper %p "
"subchannel %p; hopping into work_serializer",
parent_->chand_, parent_.get(), parent_->subchannel_);
- }
+ }
Ref().release(); // ref owned by lambda
parent_->chand_->work_serializer_->Run(
[this]() {
@@ -1092,25 +1092,25 @@ class ChannelData::SubchannelWrapper : public SubchannelInterface {
Unref();
},
DEBUG_LOCATION);
- }
-
- grpc_pollset_set* interested_parties() override {
- SubchannelInterface::ConnectivityStateWatcherInterface* watcher =
- watcher_.get();
- if (watcher_ == nullptr) watcher = replacement_->watcher_.get();
- return watcher->interested_parties();
- }
-
- WatcherWrapper* MakeReplacement() {
- auto* replacement =
- new WatcherWrapper(std::move(watcher_), parent_, last_seen_state_);
- replacement_ = replacement;
- return replacement;
- }
-
- grpc_connectivity_state last_seen_state() const { return last_seen_state_; }
-
- private:
+ }
+
+ grpc_pollset_set* interested_parties() override {
+ SubchannelInterface::ConnectivityStateWatcherInterface* watcher =
+ watcher_.get();
+ if (watcher_ == nullptr) watcher = replacement_->watcher_.get();
+ return watcher->interested_parties();
+ }
+
+ WatcherWrapper* MakeReplacement() {
+ auto* replacement =
+ new WatcherWrapper(std::move(watcher_), parent_, last_seen_state_);
+ replacement_ = replacement;
+ return replacement;
+ }
+
+ grpc_connectivity_state last_seen_state() const { return last_seen_state_; }
+
+ private:
void ApplyUpdateInControlPlaneWorkSerializer() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
gpr_log(GPR_INFO,
@@ -1119,7 +1119,7 @@ class ChannelData::SubchannelWrapper : public SubchannelInterface {
"watcher=%p",
parent_->chand_, parent_.get(), parent_->subchannel_,
watcher_.get());
- }
+ }
ConnectivityStateChange state_change = PopConnectivityStateChange();
y_absl::optional<y_absl::Cord> keepalive_throttling =
state_change.status.GetPayload(grpc_core::kKeepaliveThrottlingKey);
@@ -1154,70 +1154,70 @@ class ChannelData::SubchannelWrapper : public SubchannelInterface {
parent_->MaybeUpdateConnectedSubchannel(
std::move(state_change.connected_subchannel));
watcher_->OnConnectivityStateChange(state_change.state);
- }
+ }
}
-
- std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>
- watcher_;
- RefCountedPtr<SubchannelWrapper> parent_;
- grpc_connectivity_state last_seen_state_;
- WatcherWrapper* replacement_ = nullptr;
- };
-
- void MaybeUpdateConnectedSubchannel(
- RefCountedPtr<ConnectedSubchannel> connected_subchannel) {
- // Update the connected subchannel only if the channel is not shutting
- // down. This is because once the channel is shutting down, we
- // ignore picker updates from the LB policy, which means that
- // UpdateStateAndPickerLocked() will never process the entries
- // in chand_->pending_subchannel_updates_. So we don't want to add
- // entries there that will never be processed, since that would
- // leave dangling refs to the channel and prevent its destruction.
- grpc_error* disconnect_error = chand_->disconnect_error();
- if (disconnect_error != GRPC_ERROR_NONE) return;
- // Not shutting down, so do the update.
- if (connected_subchannel_ != connected_subchannel) {
- connected_subchannel_ = std::move(connected_subchannel);
- // Record the new connected subchannel so that it can be updated
- // in the data plane mutex the next time the picker is updated.
- chand_->pending_subchannel_updates_[Ref(
- DEBUG_LOCATION, "ConnectedSubchannelUpdate")] = connected_subchannel_;
- }
- }
-
- ChannelData* chand_;
- Subchannel* subchannel_;
- grpc_core::UniquePtr<char> health_check_service_name_;
+
+ std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>
+ watcher_;
+ RefCountedPtr<SubchannelWrapper> parent_;
+ grpc_connectivity_state last_seen_state_;
+ WatcherWrapper* replacement_ = nullptr;
+ };
+
+ void MaybeUpdateConnectedSubchannel(
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel) {
+ // Update the connected subchannel only if the channel is not shutting
+ // down. This is because once the channel is shutting down, we
+ // ignore picker updates from the LB policy, which means that
+ // UpdateStateAndPickerLocked() will never process the entries
+ // in chand_->pending_subchannel_updates_. So we don't want to add
+ // entries there that will never be processed, since that would
+ // leave dangling refs to the channel and prevent its destruction.
+ grpc_error* disconnect_error = chand_->disconnect_error();
+ if (disconnect_error != GRPC_ERROR_NONE) return;
+ // Not shutting down, so do the update.
+ if (connected_subchannel_ != connected_subchannel) {
+ connected_subchannel_ = std::move(connected_subchannel);
+ // Record the new connected subchannel so that it can be updated
+ // in the data plane mutex the next time the picker is updated.
+ chand_->pending_subchannel_updates_[Ref(
+ DEBUG_LOCATION, "ConnectedSubchannelUpdate")] = connected_subchannel_;
+ }
+ }
+
+ ChannelData* chand_;
+ Subchannel* subchannel_;
+ grpc_core::UniquePtr<char> health_check_service_name_;
ServerAddressAttributeMap attributes_;
- // Maps from the address of the watcher passed to us by the LB policy
- // to the address of the WrapperWatcher that we passed to the underlying
- // subchannel. This is needed so that when the LB policy calls
- // CancelConnectivityStateWatch() with its watcher, we know the
- // corresponding WrapperWatcher to cancel on the underlying subchannel.
- std::map<ConnectivityStateWatcherInterface*, WatcherWrapper*> watcher_map_;
+ // Maps from the address of the watcher passed to us by the LB policy
+ // to the address of the WrapperWatcher that we passed to the underlying
+ // subchannel. This is needed so that when the LB policy calls
+ // CancelConnectivityStateWatch() with its watcher, we know the
+ // corresponding WrapperWatcher to cancel on the underlying subchannel.
+ std::map<ConnectivityStateWatcherInterface*, WatcherWrapper*> watcher_map_;
// To be accessed only in the control plane work_serializer.
- RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
- // To be accessed only in the data plane mutex.
- RefCountedPtr<ConnectedSubchannel> connected_subchannel_in_data_plane_;
-};
-
-//
-// ChannelData::ExternalConnectivityWatcher
-//
-
-ChannelData::ExternalConnectivityWatcher::ExternalConnectivityWatcher(
- ChannelData* chand, grpc_polling_entity pollent,
- grpc_connectivity_state* state, grpc_closure* on_complete,
- grpc_closure* watcher_timer_init)
- : chand_(chand),
- pollent_(pollent),
- initial_state_(*state),
- state_(state),
- on_complete_(on_complete),
- watcher_timer_init_(watcher_timer_init) {
- grpc_polling_entity_add_to_pollset_set(&pollent_,
- chand_->interested_parties_);
- GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ExternalConnectivityWatcher");
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
+ // To be accessed only in the data plane mutex.
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel_in_data_plane_;
+};
+
+//
+// ChannelData::ExternalConnectivityWatcher
+//
+
+ChannelData::ExternalConnectivityWatcher::ExternalConnectivityWatcher(
+ ChannelData* chand, grpc_polling_entity pollent,
+ grpc_connectivity_state* state, grpc_closure* on_complete,
+ grpc_closure* watcher_timer_init)
+ : chand_(chand),
+ pollent_(pollent),
+ initial_state_(*state),
+ state_(state),
+ on_complete_(on_complete),
+ watcher_timer_init_(watcher_timer_init) {
+ grpc_polling_entity_add_to_pollset_set(&pollent_,
+ chand_->interested_parties_);
+ GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ExternalConnectivityWatcher");
{
MutexLock lock(&chand_->external_watchers_mu_);
// Will be deleted when the watch is complete.
@@ -1233,15 +1233,15 @@ ChannelData::ExternalConnectivityWatcher::ExternalConnectivityWatcher(
AddWatcherLocked();
},
DEBUG_LOCATION);
-}
-
-ChannelData::ExternalConnectivityWatcher::~ExternalConnectivityWatcher() {
- grpc_polling_entity_del_from_pollset_set(&pollent_,
- chand_->interested_parties_);
- GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_,
- "ExternalConnectivityWatcher");
-}
-
+}
+
+ChannelData::ExternalConnectivityWatcher::~ExternalConnectivityWatcher() {
+ grpc_polling_entity_del_from_pollset_set(&pollent_,
+ chand_->interested_parties_);
+ GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_,
+ "ExternalConnectivityWatcher");
+}
+
void ChannelData::ExternalConnectivityWatcher::
RemoveWatcherFromExternalWatchersMap(ChannelData* chand,
grpc_closure* on_complete,
@@ -1260,109 +1260,109 @@ void ChannelData::ExternalConnectivityWatcher::
if (watcher != nullptr && cancel) watcher->Cancel();
}
-void ChannelData::ExternalConnectivityWatcher::Notify(
+void ChannelData::ExternalConnectivityWatcher::Notify(
grpc_connectivity_state state, const y_absl::Status& /* status */) {
- bool done = false;
- if (!done_.CompareExchangeStrong(&done, true, MemoryOrder::RELAXED,
- MemoryOrder::RELAXED)) {
- return; // Already done.
- }
- // Remove external watcher.
- chand_->RemoveExternalConnectivityWatcher(on_complete_, /*cancel=*/false);
- // Report new state to the user.
- *state_ = state;
- ExecCtx::Run(DEBUG_LOCATION, on_complete_, GRPC_ERROR_NONE);
+ bool done = false;
+ if (!done_.CompareExchangeStrong(&done, true, MemoryOrder::RELAXED,
+ MemoryOrder::RELAXED)) {
+ return; // Already done.
+ }
+ // Remove external watcher.
+ chand_->RemoveExternalConnectivityWatcher(on_complete_, /*cancel=*/false);
+ // Report new state to the user.
+ *state_ = state;
+ ExecCtx::Run(DEBUG_LOCATION, on_complete_, GRPC_ERROR_NONE);
// Hop back into the work_serializer to clean up.
- // Not needed in state SHUTDOWN, because the tracker will
- // automatically remove all watchers in that case.
- if (state != GRPC_CHANNEL_SHUTDOWN) {
+ // Not needed in state SHUTDOWN, because the tracker will
+ // automatically remove all watchers in that case.
+ if (state != GRPC_CHANNEL_SHUTDOWN) {
chand_->work_serializer_->Run([this]() { RemoveWatcherLocked(); },
DEBUG_LOCATION);
- }
-}
-
-void ChannelData::ExternalConnectivityWatcher::Cancel() {
- bool done = false;
- if (!done_.CompareExchangeStrong(&done, true, MemoryOrder::RELAXED,
- MemoryOrder::RELAXED)) {
- return; // Already done.
- }
- ExecCtx::Run(DEBUG_LOCATION, on_complete_, GRPC_ERROR_CANCELLED);
+ }
+}
+
+void ChannelData::ExternalConnectivityWatcher::Cancel() {
+ bool done = false;
+ if (!done_.CompareExchangeStrong(&done, true, MemoryOrder::RELAXED,
+ MemoryOrder::RELAXED)) {
+ return; // Already done.
+ }
+ ExecCtx::Run(DEBUG_LOCATION, on_complete_, GRPC_ERROR_CANCELLED);
// Hop back into the work_serializer to clean up.
chand_->work_serializer_->Run([this]() { RemoveWatcherLocked(); },
DEBUG_LOCATION);
-}
-
+}
+
void ChannelData::ExternalConnectivityWatcher::AddWatcherLocked() {
Closure::Run(DEBUG_LOCATION, watcher_timer_init_, GRPC_ERROR_NONE);
// Add new watcher. Pass the ref of the object from creation to OrphanablePtr.
chand_->state_tracker_.AddWatcher(
initial_state_, OrphanablePtr<ConnectivityStateWatcherInterface>(this));
-}
-
+}
+
void ChannelData::ExternalConnectivityWatcher::RemoveWatcherLocked() {
chand_->state_tracker_.RemoveWatcher(this);
-}
-
-//
-// ChannelData::ConnectivityWatcherAdder
-//
-
-class ChannelData::ConnectivityWatcherAdder {
- public:
- ConnectivityWatcherAdder(
- ChannelData* chand, grpc_connectivity_state initial_state,
- OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher)
- : chand_(chand),
- initial_state_(initial_state),
- watcher_(std::move(watcher)) {
- GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ConnectivityWatcherAdder");
+}
+
+//
+// ChannelData::ConnectivityWatcherAdder
+//
+
+class ChannelData::ConnectivityWatcherAdder {
+ public:
+ ConnectivityWatcherAdder(
+ ChannelData* chand, grpc_connectivity_state initial_state,
+ OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher)
+ : chand_(chand),
+ initial_state_(initial_state),
+ watcher_(std::move(watcher)) {
+ GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ConnectivityWatcherAdder");
chand_->work_serializer_->Run([this]() { AddWatcherLocked(); },
DEBUG_LOCATION);
- }
-
- private:
+ }
+
+ private:
void AddWatcherLocked() {
chand_->state_tracker_.AddWatcher(initial_state_, std::move(watcher_));
GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_, "ConnectivityWatcherAdder");
delete this;
- }
-
- ChannelData* chand_;
- grpc_connectivity_state initial_state_;
- OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher_;
-};
-
-//
-// ChannelData::ConnectivityWatcherRemover
-//
-
-class ChannelData::ConnectivityWatcherRemover {
- public:
- ConnectivityWatcherRemover(ChannelData* chand,
- AsyncConnectivityStateWatcherInterface* watcher)
- : chand_(chand), watcher_(watcher) {
- GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ConnectivityWatcherRemover");
+ }
+
+ ChannelData* chand_;
+ grpc_connectivity_state initial_state_;
+ OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher_;
+};
+
+//
+// ChannelData::ConnectivityWatcherRemover
+//
+
+class ChannelData::ConnectivityWatcherRemover {
+ public:
+ ConnectivityWatcherRemover(ChannelData* chand,
+ AsyncConnectivityStateWatcherInterface* watcher)
+ : chand_(chand), watcher_(watcher) {
+ GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ConnectivityWatcherRemover");
chand_->work_serializer_->Run([this]() { RemoveWatcherLocked(); },
DEBUG_LOCATION);
- }
-
- private:
+ }
+
+ private:
void RemoveWatcherLocked() {
chand_->state_tracker_.RemoveWatcher(watcher_);
GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_,
- "ConnectivityWatcherRemover");
+ "ConnectivityWatcherRemover");
delete this;
- }
-
- ChannelData* chand_;
- AsyncConnectivityStateWatcherInterface* watcher_;
-};
-
-//
-// ChannelData::ClientChannelControlHelper
-//
-
+ }
+
+ ChannelData* chand_;
+ AsyncConnectivityStateWatcherInterface* watcher_;
+};
+
+//
+// ChannelData::ClientChannelControlHelper
+//
+
} // namespace
// Allows accessing the attributes from a ServerAddress.
@@ -1375,33 +1375,33 @@ class ChannelServerAddressPeer {
namespace {
-class ChannelData::ClientChannelControlHelper
- : public LoadBalancingPolicy::ChannelControlHelper {
- public:
- explicit ClientChannelControlHelper(ChannelData* chand) : chand_(chand) {
- GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ClientChannelControlHelper");
- }
-
- ~ClientChannelControlHelper() override {
- GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_,
- "ClientChannelControlHelper");
- }
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
+class ChannelData::ClientChannelControlHelper
+ : public LoadBalancingPolicy::ChannelControlHelper {
+ public:
+ explicit ClientChannelControlHelper(ChannelData* chand) : chand_(chand) {
+ GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ClientChannelControlHelper");
+ }
+
+ ~ClientChannelControlHelper() override {
+ GRPC_CHANNEL_STACK_UNREF(chand_->owning_stack_,
+ "ClientChannelControlHelper");
+ }
+
+ RefCountedPtr<SubchannelInterface> CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) override {
// Determine health check service name.
- bool inhibit_health_checking = grpc_channel_arg_get_bool(
- grpc_channel_args_find(&args, GRPC_ARG_INHIBIT_HEALTH_CHECKING), false);
- grpc_core::UniquePtr<char> health_check_service_name;
- if (!inhibit_health_checking) {
- health_check_service_name.reset(
- gpr_strdup(chand_->health_check_service_name_.get()));
- }
+ bool inhibit_health_checking = grpc_channel_arg_get_bool(
+ grpc_channel_args_find(&args, GRPC_ARG_INHIBIT_HEALTH_CHECKING), false);
+ grpc_core::UniquePtr<char> health_check_service_name;
+ if (!inhibit_health_checking) {
+ health_check_service_name.reset(
+ gpr_strdup(chand_->health_check_service_name_.get()));
+ }
// Remove channel args that should not affect subchannel uniqueness.
- static const char* args_to_remove[] = {
- GRPC_ARG_INHIBIT_HEALTH_CHECKING,
- GRPC_ARG_CHANNELZ_CHANNEL_NODE,
- };
+ static const char* args_to_remove[] = {
+ GRPC_ARG_INHIBIT_HEALTH_CHECKING,
+ GRPC_ARG_CHANNELZ_CHANNEL_NODE,
+ };
// Add channel args needed for the subchannel.
y_absl::InlinedVector<grpc_arg, 3> args_to_add = {
Subchannel::CreateSubchannelAddressArg(&address.address()),
@@ -1413,66 +1413,66 @@ class ChannelData::ClientChannelControlHelper
args_to_add.emplace_back(address.args()->args[j]);
}
}
- grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
+ grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
&args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove),
args_to_add.data(), args_to_add.size());
gpr_free(args_to_add[0].value.string);
// Create subchannel.
- Subchannel* subchannel =
- chand_->client_channel_factory_->CreateSubchannel(new_args);
- grpc_channel_args_destroy(new_args);
- if (subchannel == nullptr) return nullptr;
+ Subchannel* subchannel =
+ chand_->client_channel_factory_->CreateSubchannel(new_args);
+ grpc_channel_args_destroy(new_args);
+ if (subchannel == nullptr) return nullptr;
// Make sure the subchannel has updated keepalive time.
subchannel->ThrottleKeepaliveTime(chand_->keepalive_time_);
// Create and return wrapper for the subchannel.
- return MakeRefCounted<SubchannelWrapper>(
+ return MakeRefCounted<SubchannelWrapper>(
chand_, subchannel, std::move(health_check_service_name),
ChannelServerAddressPeer::GetAttributes(&address));
- }
-
- void UpdateState(
+ }
+
+ void UpdateState(
grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker) override {
- grpc_error* disconnect_error = chand_->disconnect_error();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- const char* extra = disconnect_error == GRPC_ERROR_NONE
- ? ""
- : " (ignoring -- channel shutting down)";
+ std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker) override {
+ grpc_error* disconnect_error = chand_->disconnect_error();
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ const char* extra = disconnect_error == GRPC_ERROR_NONE
+ ? ""
+ : " (ignoring -- channel shutting down)";
gpr_log(GPR_INFO, "chand=%p: update: state=%s status=(%s) picker=%p%s",
chand_, ConnectivityStateName(state), status.ToString().c_str(),
picker.get(), extra);
- }
- // Do update only if not shutting down.
- if (disconnect_error == GRPC_ERROR_NONE) {
+ }
+ // Do update only if not shutting down.
+ if (disconnect_error == GRPC_ERROR_NONE) {
chand_->UpdateStateAndPickerLocked(state, status, "helper",
std::move(picker));
- }
- }
-
- // No-op -- we should never get this from ResolvingLoadBalancingPolicy.
- void RequestReresolution() override {}
-
+ }
+ }
+
+ // No-op -- we should never get this from ResolvingLoadBalancingPolicy.
+ void RequestReresolution() override {}
+
void AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) override {
- if (chand_->channelz_node_ != nullptr) {
- chand_->channelz_node_->AddTraceEvent(
- ConvertSeverityEnum(severity),
- grpc_slice_from_copied_buffer(message.data(), message.size()));
- }
- }
-
- private:
- static channelz::ChannelTrace::Severity ConvertSeverityEnum(
- TraceSeverity severity) {
- if (severity == TRACE_INFO) return channelz::ChannelTrace::Info;
- if (severity == TRACE_WARNING) return channelz::ChannelTrace::Warning;
- return channelz::ChannelTrace::Error;
- }
-
- ChannelData* chand_;
-};
-
-//
+ if (chand_->channelz_node_ != nullptr) {
+ chand_->channelz_node_->AddTraceEvent(
+ ConvertSeverityEnum(severity),
+ grpc_slice_from_copied_buffer(message.data(), message.size()));
+ }
+ }
+
+ private:
+ static channelz::ChannelTrace::Severity ConvertSeverityEnum(
+ TraceSeverity severity) {
+ if (severity == TRACE_INFO) return channelz::ChannelTrace::Info;
+ if (severity == TRACE_WARNING) return channelz::ChannelTrace::Warning;
+ return channelz::ChannelTrace::Error;
+ }
+
+ ChannelData* chand_;
+};
+
+//
// ChannelData::ChannelConfigHelper
//
@@ -1606,96 +1606,96 @@ void ChannelData::ChannelConfigHelper::ChooseLbPolicy(
}
//
-// ChannelData implementation
-//
-
-grpc_error* ChannelData::Init(grpc_channel_element* elem,
- grpc_channel_element_args* args) {
- GPR_ASSERT(args->is_last);
- GPR_ASSERT(elem->filter == &grpc_client_channel_filter);
- grpc_error* error = GRPC_ERROR_NONE;
- new (elem->channel_data) ChannelData(args, &error);
- return error;
-}
-
-void ChannelData::Destroy(grpc_channel_element* elem) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->~ChannelData();
-}
-
-bool GetEnableRetries(const grpc_channel_args* args) {
- return grpc_channel_arg_get_bool(
- grpc_channel_args_find(args, GRPC_ARG_ENABLE_RETRIES), true);
-}
-
-size_t GetMaxPerRpcRetryBufferSize(const grpc_channel_args* args) {
- return static_cast<size_t>(grpc_channel_arg_get_integer(
- grpc_channel_args_find(args, GRPC_ARG_PER_RPC_RETRY_BUFFER_SIZE),
- {DEFAULT_PER_RPC_RETRY_BUFFER_SIZE, 0, INT_MAX}));
-}
-
-RefCountedPtr<SubchannelPoolInterface> GetSubchannelPool(
- const grpc_channel_args* args) {
- const bool use_local_subchannel_pool = grpc_channel_arg_get_bool(
- grpc_channel_args_find(args, GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL), false);
- if (use_local_subchannel_pool) {
- return MakeRefCounted<LocalSubchannelPool>();
- }
- return GlobalSubchannelPool::instance();
-}
-
-channelz::ChannelNode* GetChannelzNode(const grpc_channel_args* args) {
- const grpc_arg* arg =
- grpc_channel_args_find(args, GRPC_ARG_CHANNELZ_CHANNEL_NODE);
- if (arg != nullptr && arg->type == GRPC_ARG_POINTER) {
- return static_cast<channelz::ChannelNode*>(arg->value.pointer.p);
- }
- return nullptr;
-}
-
-ChannelData::ChannelData(grpc_channel_element_args* args, grpc_error** error)
- : deadline_checking_enabled_(
- grpc_deadline_checking_enabled(args->channel_args)),
- enable_retries_(GetEnableRetries(args->channel_args)),
- per_rpc_retry_buffer_size_(
- GetMaxPerRpcRetryBufferSize(args->channel_args)),
- owning_stack_(args->channel_stack),
- client_channel_factory_(
- ClientChannelFactory::GetFromChannelArgs(args->channel_args)),
- channelz_node_(GetChannelzNode(args->channel_args)),
+// ChannelData implementation
+//
+
+grpc_error* ChannelData::Init(grpc_channel_element* elem,
+ grpc_channel_element_args* args) {
+ GPR_ASSERT(args->is_last);
+ GPR_ASSERT(elem->filter == &grpc_client_channel_filter);
+ grpc_error* error = GRPC_ERROR_NONE;
+ new (elem->channel_data) ChannelData(args, &error);
+ return error;
+}
+
+void ChannelData::Destroy(grpc_channel_element* elem) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->~ChannelData();
+}
+
+bool GetEnableRetries(const grpc_channel_args* args) {
+ return grpc_channel_arg_get_bool(
+ grpc_channel_args_find(args, GRPC_ARG_ENABLE_RETRIES), true);
+}
+
+size_t GetMaxPerRpcRetryBufferSize(const grpc_channel_args* args) {
+ return static_cast<size_t>(grpc_channel_arg_get_integer(
+ grpc_channel_args_find(args, GRPC_ARG_PER_RPC_RETRY_BUFFER_SIZE),
+ {DEFAULT_PER_RPC_RETRY_BUFFER_SIZE, 0, INT_MAX}));
+}
+
+RefCountedPtr<SubchannelPoolInterface> GetSubchannelPool(
+ const grpc_channel_args* args) {
+ const bool use_local_subchannel_pool = grpc_channel_arg_get_bool(
+ grpc_channel_args_find(args, GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL), false);
+ if (use_local_subchannel_pool) {
+ return MakeRefCounted<LocalSubchannelPool>();
+ }
+ return GlobalSubchannelPool::instance();
+}
+
+channelz::ChannelNode* GetChannelzNode(const grpc_channel_args* args) {
+ const grpc_arg* arg =
+ grpc_channel_args_find(args, GRPC_ARG_CHANNELZ_CHANNEL_NODE);
+ if (arg != nullptr && arg->type == GRPC_ARG_POINTER) {
+ return static_cast<channelz::ChannelNode*>(arg->value.pointer.p);
+ }
+ return nullptr;
+}
+
+ChannelData::ChannelData(grpc_channel_element_args* args, grpc_error** error)
+ : deadline_checking_enabled_(
+ grpc_deadline_checking_enabled(args->channel_args)),
+ enable_retries_(GetEnableRetries(args->channel_args)),
+ per_rpc_retry_buffer_size_(
+ GetMaxPerRpcRetryBufferSize(args->channel_args)),
+ owning_stack_(args->channel_stack),
+ client_channel_factory_(
+ ClientChannelFactory::GetFromChannelArgs(args->channel_args)),
+ channelz_node_(GetChannelzNode(args->channel_args)),
channel_config_helper_(this),
work_serializer_(std::make_shared<WorkSerializer>()),
- interested_parties_(grpc_pollset_set_create()),
- subchannel_pool_(GetSubchannelPool(args->channel_args)),
- state_tracker_("client_channel", GRPC_CHANNEL_IDLE),
- disconnect_error_(GRPC_ERROR_NONE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO, "chand=%p: creating client_channel for channel stack %p",
- this, owning_stack_);
- }
- // Initialize data members.
- gpr_mu_init(&info_mu_);
- // Start backup polling.
- grpc_client_channel_start_backup_polling(interested_parties_);
- // Check client channel factory.
- if (client_channel_factory_ == nullptr) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Missing client channel factory in args for client channel filter");
- return;
- }
- // Get server name to resolve, using proxy mapper if needed.
- const char* server_uri = grpc_channel_arg_get_string(
- grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVER_URI));
- if (server_uri == nullptr) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "server URI channel arg missing or wrong type in client channel "
- "filter");
- return;
- }
+ interested_parties_(grpc_pollset_set_create()),
+ subchannel_pool_(GetSubchannelPool(args->channel_args)),
+ state_tracker_("client_channel", GRPC_CHANNEL_IDLE),
+ disconnect_error_(GRPC_ERROR_NONE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO, "chand=%p: creating client_channel for channel stack %p",
+ this, owning_stack_);
+ }
+ // Initialize data members.
+ gpr_mu_init(&info_mu_);
+ // Start backup polling.
+ grpc_client_channel_start_backup_polling(interested_parties_);
+ // Check client channel factory.
+ if (client_channel_factory_ == nullptr) {
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Missing client channel factory in args for client channel filter");
+ return;
+ }
+ // Get server name to resolve, using proxy mapper if needed.
+ const char* server_uri = grpc_channel_arg_get_string(
+ grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVER_URI));
+ if (server_uri == nullptr) {
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "server URI channel arg missing or wrong type in client channel "
+ "filter");
+ return;
+ }
// Get default service config. If none is specified via the client API,
// we use an empty config.
- const char* service_config_json = grpc_channel_arg_get_string(
- grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVICE_CONFIG));
+ const char* service_config_json = grpc_channel_arg_get_string(
+ grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVICE_CONFIG));
if (service_config_json == nullptr) service_config_json = "{}";
*error = GRPC_ERROR_NONE;
default_service_config_ =
@@ -1703,19 +1703,19 @@ ChannelData::ChannelData(grpc_channel_element_args* args, grpc_error** error)
if (*error != GRPC_ERROR_NONE) {
default_service_config_.reset();
return;
- }
- grpc_uri* uri = grpc_uri_parse(server_uri, true);
- if (uri != nullptr && uri->path[0] != '\0') {
- server_name_.reset(
- gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path));
- }
- grpc_uri_destroy(uri);
- char* proxy_name = nullptr;
- grpc_channel_args* new_args = nullptr;
- ProxyMapperRegistry::MapName(server_uri, args->channel_args, &proxy_name,
- &new_args);
- target_uri_.reset(proxy_name != nullptr ? proxy_name
- : gpr_strdup(server_uri));
+ }
+ grpc_uri* uri = grpc_uri_parse(server_uri, true);
+ if (uri != nullptr && uri->path[0] != '\0') {
+ server_name_.reset(
+ gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path));
+ }
+ grpc_uri_destroy(uri);
+ char* proxy_name = nullptr;
+ grpc_channel_args* new_args = nullptr;
+ ProxyMapperRegistry::MapName(server_uri, args->channel_args, &proxy_name,
+ &new_args);
+ target_uri_.reset(proxy_name != nullptr ? proxy_name
+ : gpr_strdup(server_uri));
// Strip out service config channel arg, so that it doesn't affect
// subchannel uniqueness when the args flow down to that layer.
const char* arg_to_remove = GRPC_ARG_SERVICE_CONFIG;
@@ -1725,105 +1725,105 @@ ChannelData::ChannelData(grpc_channel_element_args* args, grpc_error** error)
keepalive_time_ = grpc_channel_args_find_integer(
channel_args_, GRPC_ARG_KEEPALIVE_TIME_MS,
{-1 /* default value, unset */, 1, INT_MAX});
- if (!ResolverRegistry::IsValidTarget(target_uri_.get())) {
+ if (!ResolverRegistry::IsValidTarget(target_uri_.get())) {
TString error_message =
y_absl::StrCat("the target uri is not valid: ", target_uri_.get());
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_message.c_str());
- return;
- }
- *error = GRPC_ERROR_NONE;
-}
-
-ChannelData::~ChannelData() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO, "chand=%p: destroying channel", this);
- }
- DestroyResolvingLoadBalancingPolicyLocked();
- grpc_channel_args_destroy(channel_args_);
+ return;
+ }
+ *error = GRPC_ERROR_NONE;
+}
+
+ChannelData::~ChannelData() {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO, "chand=%p: destroying channel", this);
+ }
+ DestroyResolvingLoadBalancingPolicyLocked();
+ grpc_channel_args_destroy(channel_args_);
GRPC_ERROR_UNREF(resolver_transient_failure_error_);
- // Stop backup polling.
- grpc_client_channel_stop_backup_polling(interested_parties_);
- grpc_pollset_set_destroy(interested_parties_);
- GRPC_ERROR_UNREF(disconnect_error_.Load(MemoryOrder::RELAXED));
- gpr_mu_destroy(&info_mu_);
-}
-
-void ChannelData::UpdateStateAndPickerLocked(
+ // Stop backup polling.
+ grpc_client_channel_stop_backup_polling(interested_parties_);
+ grpc_pollset_set_destroy(interested_parties_);
+ GRPC_ERROR_UNREF(disconnect_error_.Load(MemoryOrder::RELAXED));
+ gpr_mu_destroy(&info_mu_);
+}
+
+void ChannelData::UpdateStateAndPickerLocked(
grpc_connectivity_state state, const y_absl::Status& status,
const char* reason,
- std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker) {
- // Clean the control plane when entering IDLE.
+ std::unique_ptr<LoadBalancingPolicy::SubchannelPicker> picker) {
+ // Clean the control plane when entering IDLE.
if (picker == nullptr || state == GRPC_CHANNEL_SHUTDOWN) {
- health_check_service_name_.reset();
- saved_service_config_.reset();
+ health_check_service_name_.reset();
+ saved_service_config_.reset();
saved_config_selector_.reset();
- }
- // Update connectivity state.
+ }
+ // Update connectivity state.
state_tracker_.SetState(state, status, reason);
- if (channelz_node_ != nullptr) {
- channelz_node_->SetConnectivityState(state);
- channelz_node_->AddTraceEvent(
- channelz::ChannelTrace::Severity::Info,
- grpc_slice_from_static_string(
- channelz::ChannelNode::GetChannelConnectivityStateChangeString(
- state)));
- }
- // Grab data plane lock to do subchannel updates and update the picker.
- //
- // Note that we want to minimize the work done while holding the data
- // plane lock, to keep the critical section small. So, for all of the
- // objects that we might wind up unreffing here, we actually hold onto
- // the refs until after we release the lock, and then unref them at
- // that point. This includes the following:
- // - refs to subchannel wrappers in the keys of pending_subchannel_updates_
- // - ref stored in retry_throttle_data_
- // - ref stored in service_config_
+ if (channelz_node_ != nullptr) {
+ channelz_node_->SetConnectivityState(state);
+ channelz_node_->AddTraceEvent(
+ channelz::ChannelTrace::Severity::Info,
+ grpc_slice_from_static_string(
+ channelz::ChannelNode::GetChannelConnectivityStateChangeString(
+ state)));
+ }
+ // Grab data plane lock to do subchannel updates and update the picker.
+ //
+ // Note that we want to minimize the work done while holding the data
+ // plane lock, to keep the critical section small. So, for all of the
+ // objects that we might wind up unreffing here, we actually hold onto
+ // the refs until after we release the lock, and then unref them at
+ // that point. This includes the following:
+ // - refs to subchannel wrappers in the keys of pending_subchannel_updates_
+ // - ref stored in retry_throttle_data_
+ // - ref stored in service_config_
// - ref stored in config_selector_
- // - ownership of the existing picker in picker_
- RefCountedPtr<ServerRetryThrottleData> retry_throttle_data_to_unref;
- RefCountedPtr<ServiceConfig> service_config_to_unref;
+ // - ownership of the existing picker in picker_
+ RefCountedPtr<ServerRetryThrottleData> retry_throttle_data_to_unref;
+ RefCountedPtr<ServiceConfig> service_config_to_unref;
RefCountedPtr<ConfigSelector> config_selector_to_unref;
- {
- MutexLock lock(&data_plane_mu_);
- // Handle subchannel updates.
- for (auto& p : pending_subchannel_updates_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p: updating subchannel wrapper %p data plane "
- "connected_subchannel to %p",
- this, p.first.get(), p.second.get());
- }
- // Note: We do not remove the entry from pending_subchannel_updates_
- // here, since this would unref the subchannel wrapper; instead,
- // we wait until we've released the lock to clear the map.
- p.first->set_connected_subchannel_in_data_plane(std::move(p.second));
- }
- // Swap out the picker.
- // Note: Original value will be destroyed after the lock is released.
- picker_.swap(picker);
- // Clean the data plane if the updated picker is nullptr.
+ {
+ MutexLock lock(&data_plane_mu_);
+ // Handle subchannel updates.
+ for (auto& p : pending_subchannel_updates_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p: updating subchannel wrapper %p data plane "
+ "connected_subchannel to %p",
+ this, p.first.get(), p.second.get());
+ }
+ // Note: We do not remove the entry from pending_subchannel_updates_
+ // here, since this would unref the subchannel wrapper; instead,
+ // we wait until we've released the lock to clear the map.
+ p.first->set_connected_subchannel_in_data_plane(std::move(p.second));
+ }
+ // Swap out the picker.
+ // Note: Original value will be destroyed after the lock is released.
+ picker_.swap(picker);
+ // Clean the data plane if the updated picker is nullptr.
if (picker_ == nullptr || state == GRPC_CHANNEL_SHUTDOWN) {
- received_service_config_data_ = false;
- // Note: We save the objects to unref until after the lock is released.
- retry_throttle_data_to_unref = std::move(retry_throttle_data_);
- service_config_to_unref = std::move(service_config_);
+ received_service_config_data_ = false;
+ // Note: We save the objects to unref until after the lock is released.
+ retry_throttle_data_to_unref = std::move(retry_throttle_data_);
+ service_config_to_unref = std::move(service_config_);
config_selector_to_unref = std::move(config_selector_);
- }
- // Re-process queued picks.
- for (QueuedPick* pick = queued_picks_; pick != nullptr; pick = pick->next) {
- grpc_call_element* elem = pick->elem;
- CallData* calld = static_cast<CallData*>(elem->call_data);
- grpc_error* error = GRPC_ERROR_NONE;
- if (calld->PickSubchannelLocked(elem, &error)) {
- calld->AsyncPickDone(elem, error);
- }
- }
- }
- // Clear the pending update map after releasing the lock, to keep the
- // critical section small.
- pending_subchannel_updates_.clear();
-}
-
+ }
+ // Re-process queued picks.
+ for (QueuedPick* pick = queued_picks_; pick != nullptr; pick = pick->next) {
+ grpc_call_element* elem = pick->elem;
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (calld->PickSubchannelLocked(elem, &error)) {
+ calld->AsyncPickDone(elem, error);
+ }
+ }
+ }
+ // Clear the pending update map after releasing the lock, to keep the
+ // critical section small.
+ pending_subchannel_updates_.clear();
+}
+
void ChannelData::UpdateServiceConfigInControlPlaneLocked(
RefCountedPtr<ServiceConfig> service_config,
RefCountedPtr<ConfigSelector> config_selector,
@@ -1894,238 +1894,238 @@ void ChannelData::UpdateServiceConfigInDataPlaneLocked() {
config_selector =
MakeRefCounted<DefaultConfigSelector>(saved_service_config_);
}
- // Grab data plane lock to update service config.
- //
- // We defer unreffing the old values (and deallocating memory) until
- // after releasing the lock to keep the critical section small.
- {
- MutexLock lock(&data_plane_mu_);
+ // Grab data plane lock to update service config.
+ //
+ // We defer unreffing the old values (and deallocating memory) until
+ // after releasing the lock to keep the critical section small.
+ {
+ MutexLock lock(&data_plane_mu_);
GRPC_ERROR_UNREF(resolver_transient_failure_error_);
resolver_transient_failure_error_ = GRPC_ERROR_NONE;
- // Update service config.
- received_service_config_data_ = true;
- // Old values will be unreffed after lock is released.
- retry_throttle_data_.swap(retry_throttle_data);
- service_config_.swap(service_config);
+ // Update service config.
+ received_service_config_data_ = true;
+ // Old values will be unreffed after lock is released.
+ retry_throttle_data_.swap(retry_throttle_data);
+ service_config_.swap(service_config);
config_selector_.swap(config_selector);
// Re-process queued picks.
- for (QueuedPick* pick = queued_picks_; pick != nullptr; pick = pick->next) {
+ for (QueuedPick* pick = queued_picks_; pick != nullptr; pick = pick->next) {
grpc_call_element* elem = pick->elem;
CallData* calld = static_cast<CallData*>(elem->call_data);
grpc_error* error = GRPC_ERROR_NONE;
if (calld->PickSubchannelLocked(elem, &error)) {
calld->AsyncPickDone(elem, error);
}
- }
- }
- // Old values will be unreffed after lock is released when they go out
- // of scope.
-}
-
-void ChannelData::CreateResolvingLoadBalancingPolicyLocked() {
- // Instantiate resolving LB policy.
- LoadBalancingPolicy::Args lb_args;
+ }
+ }
+ // Old values will be unreffed after lock is released when they go out
+ // of scope.
+}
+
+void ChannelData::CreateResolvingLoadBalancingPolicyLocked() {
+ // Instantiate resolving LB policy.
+ LoadBalancingPolicy::Args lb_args;
lb_args.work_serializer = work_serializer_;
lb_args.channel_control_helper =
y_absl::make_unique<ClientChannelControlHelper>(this);
- lb_args.args = channel_args_;
- grpc_core::UniquePtr<char> target_uri(gpr_strdup(target_uri_.get()));
- resolving_lb_policy_.reset(new ResolvingLoadBalancingPolicy(
- std::move(lb_args), &grpc_client_channel_routing_trace,
+ lb_args.args = channel_args_;
+ grpc_core::UniquePtr<char> target_uri(gpr_strdup(target_uri_.get()));
+ resolving_lb_policy_.reset(new ResolvingLoadBalancingPolicy(
+ std::move(lb_args), &grpc_client_channel_routing_trace,
std::move(target_uri), &channel_config_helper_));
- grpc_pollset_set_add_pollset_set(resolving_lb_policy_->interested_parties(),
- interested_parties_);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO, "chand=%p: created resolving_lb_policy=%p", this,
- resolving_lb_policy_.get());
- }
-}
-
-void ChannelData::DestroyResolvingLoadBalancingPolicyLocked() {
- if (resolving_lb_policy_ != nullptr) {
- grpc_pollset_set_del_pollset_set(resolving_lb_policy_->interested_parties(),
- interested_parties_);
- resolving_lb_policy_.reset();
- }
-}
-
-grpc_error* ChannelData::DoPingLocked(grpc_transport_op* op) {
- if (state_tracker_.state() != GRPC_CHANNEL_READY) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("channel not connected");
- }
- LoadBalancingPolicy::PickResult result =
- picker_->Pick(LoadBalancingPolicy::PickArgs());
- ConnectedSubchannel* connected_subchannel = nullptr;
- if (result.subchannel != nullptr) {
- SubchannelWrapper* subchannel =
- static_cast<SubchannelWrapper*>(result.subchannel.get());
- connected_subchannel = subchannel->connected_subchannel();
- }
- if (connected_subchannel != nullptr) {
- connected_subchannel->Ping(op->send_ping.on_initiate, op->send_ping.on_ack);
- } else {
- if (result.error == GRPC_ERROR_NONE) {
- result.error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "LB policy dropped call on ping");
- }
- }
- return result.error;
-}
-
+ grpc_pollset_set_add_pollset_set(resolving_lb_policy_->interested_parties(),
+ interested_parties_);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO, "chand=%p: created resolving_lb_policy=%p", this,
+ resolving_lb_policy_.get());
+ }
+}
+
+void ChannelData::DestroyResolvingLoadBalancingPolicyLocked() {
+ if (resolving_lb_policy_ != nullptr) {
+ grpc_pollset_set_del_pollset_set(resolving_lb_policy_->interested_parties(),
+ interested_parties_);
+ resolving_lb_policy_.reset();
+ }
+}
+
+grpc_error* ChannelData::DoPingLocked(grpc_transport_op* op) {
+ if (state_tracker_.state() != GRPC_CHANNEL_READY) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("channel not connected");
+ }
+ LoadBalancingPolicy::PickResult result =
+ picker_->Pick(LoadBalancingPolicy::PickArgs());
+ ConnectedSubchannel* connected_subchannel = nullptr;
+ if (result.subchannel != nullptr) {
+ SubchannelWrapper* subchannel =
+ static_cast<SubchannelWrapper*>(result.subchannel.get());
+ connected_subchannel = subchannel->connected_subchannel();
+ }
+ if (connected_subchannel != nullptr) {
+ connected_subchannel->Ping(op->send_ping.on_initiate, op->send_ping.on_ack);
+ } else {
+ if (result.error == GRPC_ERROR_NONE) {
+ result.error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "LB policy dropped call on ping");
+ }
+ }
+ return result.error;
+}
+
void ChannelData::StartTransportOpLocked(grpc_transport_op* op) {
- // Connectivity watch.
- if (op->start_connectivity_watch != nullptr) {
+ // Connectivity watch.
+ if (op->start_connectivity_watch != nullptr) {
state_tracker_.AddWatcher(op->start_connectivity_watch_state,
std::move(op->start_connectivity_watch));
}
- if (op->stop_connectivity_watch != nullptr) {
+ if (op->stop_connectivity_watch != nullptr) {
state_tracker_.RemoveWatcher(op->stop_connectivity_watch);
- }
- // Ping.
+ }
+ // Ping.
if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
grpc_error* error = DoPingLocked(op);
- if (error != GRPC_ERROR_NONE) {
- ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_initiate,
- GRPC_ERROR_REF(error));
- ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_ack, error);
+ if (error != GRPC_ERROR_NONE) {
+ ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_initiate,
+ GRPC_ERROR_REF(error));
+ ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_ack, error);
}
- op->bind_pollset = nullptr;
+ op->bind_pollset = nullptr;
op->send_ping.on_initiate = nullptr;
op->send_ping.on_ack = nullptr;
}
- // Reset backoff.
- if (op->reset_connect_backoff) {
+ // Reset backoff.
+ if (op->reset_connect_backoff) {
if (resolving_lb_policy_ != nullptr) {
resolving_lb_policy_->ResetBackoffLocked();
- }
- }
- // Disconnect or enter IDLE.
+ }
+ }
+ // Disconnect or enter IDLE.
if (op->disconnect_with_error != GRPC_ERROR_NONE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p: disconnect_with_error: %s", this,
- grpc_error_string(op->disconnect_with_error));
- }
+ grpc_error_string(op->disconnect_with_error));
+ }
DestroyResolvingLoadBalancingPolicyLocked();
- intptr_t value;
- if (grpc_error_get_int(op->disconnect_with_error,
- GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE, &value) &&
- static_cast<grpc_connectivity_state>(value) == GRPC_CHANNEL_IDLE) {
+ intptr_t value;
+ if (grpc_error_get_int(op->disconnect_with_error,
+ GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE, &value) &&
+ static_cast<grpc_connectivity_state>(value) == GRPC_CHANNEL_IDLE) {
if (disconnect_error() == GRPC_ERROR_NONE) {
- // Enter IDLE state.
+ // Enter IDLE state.
UpdateStateAndPickerLocked(GRPC_CHANNEL_IDLE, y_absl::Status(),
"channel entering IDLE", nullptr);
- }
- GRPC_ERROR_UNREF(op->disconnect_with_error);
- } else {
- // Disconnect.
+ }
+ GRPC_ERROR_UNREF(op->disconnect_with_error);
+ } else {
+ // Disconnect.
GPR_ASSERT(disconnect_error_.Load(MemoryOrder::RELAXED) ==
- GRPC_ERROR_NONE);
+ GRPC_ERROR_NONE);
disconnect_error_.Store(op->disconnect_with_error, MemoryOrder::RELEASE);
UpdateStateAndPickerLocked(
GRPC_CHANNEL_SHUTDOWN, y_absl::Status(), "shutdown from API",
y_absl::make_unique<LoadBalancingPolicy::TransientFailurePicker>(
- GRPC_ERROR_REF(op->disconnect_with_error)));
- }
+ GRPC_ERROR_REF(op->disconnect_with_error)));
+ }
}
GRPC_CHANNEL_STACK_UNREF(owning_stack_, "start_transport_op");
- ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
}
-void ChannelData::StartTransportOp(grpc_channel_element* elem,
- grpc_transport_op* op) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+void ChannelData::StartTransportOp(grpc_channel_element* elem,
+ grpc_transport_op* op) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
GPR_ASSERT(op->set_accept_stream == false);
- // Handle bind_pollset.
+ // Handle bind_pollset.
if (op->bind_pollset != nullptr) {
- grpc_pollset_set_add_pollset(chand->interested_parties_, op->bind_pollset);
+ grpc_pollset_set_add_pollset(chand->interested_parties_, op->bind_pollset);
}
// Pop into control plane work_serializer for remaining ops.
- GRPC_CHANNEL_STACK_REF(chand->owning_stack_, "start_transport_op");
+ GRPC_CHANNEL_STACK_REF(chand->owning_stack_, "start_transport_op");
chand->work_serializer_->Run(
[chand, op]() { chand->StartTransportOpLocked(op); }, DEBUG_LOCATION);
}
-void ChannelData::GetChannelInfo(grpc_channel_element* elem,
- const grpc_channel_info* info) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- MutexLock lock(&chand->info_mu_);
+void ChannelData::GetChannelInfo(grpc_channel_element* elem,
+ const grpc_channel_info* info) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ MutexLock lock(&chand->info_mu_);
if (info->lb_policy_name != nullptr) {
- *info->lb_policy_name = gpr_strdup(chand->info_lb_policy_name_.get());
+ *info->lb_policy_name = gpr_strdup(chand->info_lb_policy_name_.get());
}
if (info->service_config_json != nullptr) {
*info->service_config_json =
- gpr_strdup(chand->info_service_config_json_.get());
- }
-}
-
-void ChannelData::AddQueuedPick(QueuedPick* pick,
- grpc_polling_entity* pollent) {
- // Add call to queued picks list.
- pick->next = queued_picks_;
- queued_picks_ = pick;
- // Add call's pollent to channel's interested_parties, so that I/O
- // can be done under the call's CQ.
- grpc_polling_entity_add_to_pollset_set(pollent, interested_parties_);
-}
-
-void ChannelData::RemoveQueuedPick(QueuedPick* to_remove,
- grpc_polling_entity* pollent) {
- // Remove call's pollent from channel's interested_parties.
- grpc_polling_entity_del_from_pollset_set(pollent, interested_parties_);
- // Remove from queued picks list.
- for (QueuedPick** pick = &queued_picks_; *pick != nullptr;
- pick = &(*pick)->next) {
- if (*pick == to_remove) {
- *pick = to_remove->next;
- return;
- }
+ gpr_strdup(chand->info_service_config_json_.get());
}
}
-RefCountedPtr<ConnectedSubchannel>
-ChannelData::GetConnectedSubchannelInDataPlane(
- SubchannelInterface* subchannel) const {
- SubchannelWrapper* subchannel_wrapper =
- static_cast<SubchannelWrapper*>(subchannel);
- ConnectedSubchannel* connected_subchannel =
- subchannel_wrapper->connected_subchannel_in_data_plane();
- if (connected_subchannel == nullptr) return nullptr;
- return connected_subchannel->Ref();
-}
-
+void ChannelData::AddQueuedPick(QueuedPick* pick,
+ grpc_polling_entity* pollent) {
+ // Add call to queued picks list.
+ pick->next = queued_picks_;
+ queued_picks_ = pick;
+ // Add call's pollent to channel's interested_parties, so that I/O
+ // can be done under the call's CQ.
+ grpc_polling_entity_add_to_pollset_set(pollent, interested_parties_);
+}
+
+void ChannelData::RemoveQueuedPick(QueuedPick* to_remove,
+ grpc_polling_entity* pollent) {
+ // Remove call's pollent from channel's interested_parties.
+ grpc_polling_entity_del_from_pollset_set(pollent, interested_parties_);
+ // Remove from queued picks list.
+ for (QueuedPick** pick = &queued_picks_; *pick != nullptr;
+ pick = &(*pick)->next) {
+ if (*pick == to_remove) {
+ *pick = to_remove->next;
+ return;
+ }
+ }
+}
+
+RefCountedPtr<ConnectedSubchannel>
+ChannelData::GetConnectedSubchannelInDataPlane(
+ SubchannelInterface* subchannel) const {
+ SubchannelWrapper* subchannel_wrapper =
+ static_cast<SubchannelWrapper*>(subchannel);
+ ConnectedSubchannel* connected_subchannel =
+ subchannel_wrapper->connected_subchannel_in_data_plane();
+ if (connected_subchannel == nullptr) return nullptr;
+ return connected_subchannel->Ref();
+}
+
void ChannelData::TryToConnectLocked() {
if (resolving_lb_policy_ != nullptr) {
resolving_lb_policy_->ExitIdleLocked();
- } else {
+ } else {
CreateResolvingLoadBalancingPolicyLocked();
}
GRPC_CHANNEL_STACK_UNREF(owning_stack_, "TryToConnect");
-}
-
-grpc_connectivity_state ChannelData::CheckConnectivityState(
- bool try_to_connect) {
- grpc_connectivity_state out = state_tracker_.state();
- if (out == GRPC_CHANNEL_IDLE && try_to_connect) {
- GRPC_CHANNEL_STACK_REF(owning_stack_, "TryToConnect");
+}
+
+grpc_connectivity_state ChannelData::CheckConnectivityState(
+ bool try_to_connect) {
+ grpc_connectivity_state out = state_tracker_.state();
+ if (out == GRPC_CHANNEL_IDLE && try_to_connect) {
+ GRPC_CHANNEL_STACK_REF(owning_stack_, "TryToConnect");
work_serializer_->Run([this]() { TryToConnectLocked(); }, DEBUG_LOCATION);
}
- return out;
+ return out;
}
-void ChannelData::AddConnectivityWatcher(
- grpc_connectivity_state initial_state,
- OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher) {
- new ConnectivityWatcherAdder(this, initial_state, std::move(watcher));
+void ChannelData::AddConnectivityWatcher(
+ grpc_connectivity_state initial_state,
+ OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher) {
+ new ConnectivityWatcherAdder(this, initial_state, std::move(watcher));
}
-void ChannelData::RemoveConnectivityWatcher(
- AsyncConnectivityStateWatcherInterface* watcher) {
- new ConnectivityWatcherRemover(this, watcher);
-}
+void ChannelData::RemoveConnectivityWatcher(
+ AsyncConnectivityStateWatcherInterface* watcher) {
+ new ConnectivityWatcherRemover(this, watcher);
+}
-//
-// CallData implementation
-//
+//
+// CallData implementation
+//
// Retry support:
//
@@ -2162,51 +2162,51 @@ void ChannelData::RemoveConnectivityWatcher(
// (census filter is on top of this one)
// - add census stats for retries
-CallData::CallData(grpc_call_element* elem, const ChannelData& chand,
- const grpc_call_element_args& args)
- : deadline_state_(elem, args.call_stack, args.call_combiner,
- GPR_LIKELY(chand.deadline_checking_enabled())
- ? args.deadline
- : GRPC_MILLIS_INF_FUTURE),
- path_(grpc_slice_ref_internal(args.path)),
- call_start_time_(args.start_time),
- deadline_(args.deadline),
- arena_(args.arena),
- owning_call_(args.call_stack),
- call_combiner_(args.call_combiner),
- call_context_(args.context),
- lb_call_state_(this),
- pending_send_initial_metadata_(false),
- pending_send_message_(false),
- pending_send_trailing_metadata_(false),
- enable_retries_(chand.enable_retries()),
- retry_committed_(false),
- last_attempt_got_server_pushback_(false) {}
-
-CallData::~CallData() {
- grpc_slice_unref_internal(path_);
- GRPC_ERROR_UNREF(cancel_error_);
- if (backend_metric_data_ != nullptr) {
- backend_metric_data_
- ->LoadBalancingPolicy::BackendMetricData::~BackendMetricData();
- }
- // Make sure there are no remaining pending batches.
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- GPR_ASSERT(pending_batches_[i].batch == nullptr);
- }
-}
-
-grpc_error* CallData::Init(grpc_call_element* elem,
- const grpc_call_element_args* args) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- new (elem->call_data) CallData(elem, *chand, *args);
- return GRPC_ERROR_NONE;
-}
-
-void CallData::Destroy(grpc_call_element* elem,
- const grpc_call_final_info* /*final_info*/,
- grpc_closure* then_schedule_closure) {
- CallData* calld = static_cast<CallData*>(elem->call_data);
+CallData::CallData(grpc_call_element* elem, const ChannelData& chand,
+ const grpc_call_element_args& args)
+ : deadline_state_(elem, args.call_stack, args.call_combiner,
+ GPR_LIKELY(chand.deadline_checking_enabled())
+ ? args.deadline
+ : GRPC_MILLIS_INF_FUTURE),
+ path_(grpc_slice_ref_internal(args.path)),
+ call_start_time_(args.start_time),
+ deadline_(args.deadline),
+ arena_(args.arena),
+ owning_call_(args.call_stack),
+ call_combiner_(args.call_combiner),
+ call_context_(args.context),
+ lb_call_state_(this),
+ pending_send_initial_metadata_(false),
+ pending_send_message_(false),
+ pending_send_trailing_metadata_(false),
+ enable_retries_(chand.enable_retries()),
+ retry_committed_(false),
+ last_attempt_got_server_pushback_(false) {}
+
+CallData::~CallData() {
+ grpc_slice_unref_internal(path_);
+ GRPC_ERROR_UNREF(cancel_error_);
+ if (backend_metric_data_ != nullptr) {
+ backend_metric_data_
+ ->LoadBalancingPolicy::BackendMetricData::~BackendMetricData();
+ }
+ // Make sure there are no remaining pending batches.
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ GPR_ASSERT(pending_batches_[i].batch == nullptr);
+ }
+}
+
+grpc_error* CallData::Init(grpc_call_element* elem,
+ const grpc_call_element_args* args) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ new (elem->call_data) CallData(elem, *chand, *args);
+ return GRPC_ERROR_NONE;
+}
+
+void CallData::Destroy(grpc_call_element* elem,
+ const grpc_call_final_info* /*final_info*/,
+ grpc_closure* then_schedule_closure) {
+ CallData* calld = static_cast<CallData*>(elem->call_data);
RefCountedPtr<SubchannelCall> subchannel_call = calld->subchannel_call_;
calld->~CallData();
if (GPR_LIKELY(subchannel_call != nullptr)) {
@@ -2214,196 +2214,196 @@ void CallData::Destroy(grpc_call_element* elem,
} else {
// TODO(yashkt) : This can potentially be a Closure::Run
ExecCtx::Run(DEBUG_LOCATION, then_schedule_closure, GRPC_ERROR_NONE);
- }
-}
-
-void CallData::StartTransportStreamOpBatch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
- GPR_TIMER_SCOPE("cc_start_transport_stream_op_batch", 0);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- if (GPR_LIKELY(chand->deadline_checking_enabled())) {
- grpc_deadline_state_client_start_transport_stream_op_batch(elem, batch);
- }
- // If we've previously been cancelled, immediately fail any new batches.
- if (GPR_UNLIKELY(calld->cancel_error_ != GRPC_ERROR_NONE)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: failing batch with error: %s",
- chand, calld, grpc_error_string(calld->cancel_error_));
- }
- // Note: This will release the call combiner.
- grpc_transport_stream_op_batch_finish_with_failure(
- batch, GRPC_ERROR_REF(calld->cancel_error_), calld->call_combiner_);
- return;
- }
- // Handle cancellation.
- if (GPR_UNLIKELY(batch->cancel_stream)) {
- // Stash a copy of cancel_error in our call data, so that we can use
- // it for subsequent operations. This ensures that if the call is
- // cancelled before any batches are passed down (e.g., if the deadline
- // is in the past when the call starts), we can return the right
- // error to the caller when the first batch does get passed down.
- GRPC_ERROR_UNREF(calld->cancel_error_);
- calld->cancel_error_ =
- GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: recording cancel_error=%s", chand,
- calld, grpc_error_string(calld->cancel_error_));
- }
- // If we do not have a subchannel call (i.e., a pick has not yet
- // been started), fail all pending batches. Otherwise, send the
- // cancellation down to the subchannel call.
- if (calld->subchannel_call_ == nullptr) {
- // TODO(roth): If there is a pending retry callback, do we need to
- // cancel it here?
- calld->PendingBatchesFail(elem, GRPC_ERROR_REF(calld->cancel_error_),
- NoYieldCallCombiner);
- // Note: This will release the call combiner.
- grpc_transport_stream_op_batch_finish_with_failure(
- batch, GRPC_ERROR_REF(calld->cancel_error_), calld->call_combiner_);
- } else {
- // Note: This will release the call combiner.
- calld->subchannel_call_->StartTransportStreamOpBatch(batch);
- }
- return;
- }
- // Add the batch to the pending list.
- calld->PendingBatchesAdd(elem, batch);
- // Check if we've already gotten a subchannel call.
- // Note that once we have picked a subchannel, we do not need to acquire
- // the channel's data plane mutex, which is more efficient (especially for
- // streaming calls).
- if (calld->subchannel_call_ != nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: starting batch on subchannel_call=%p", chand,
- calld, calld->subchannel_call_.get());
+ }
+}
+
+void CallData::StartTransportStreamOpBatch(
+ grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
+ GPR_TIMER_SCOPE("cc_start_transport_stream_op_batch", 0);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (GPR_LIKELY(chand->deadline_checking_enabled())) {
+ grpc_deadline_state_client_start_transport_stream_op_batch(elem, batch);
+ }
+ // If we've previously been cancelled, immediately fail any new batches.
+ if (GPR_UNLIKELY(calld->cancel_error_ != GRPC_ERROR_NONE)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: failing batch with error: %s",
+ chand, calld, grpc_error_string(calld->cancel_error_));
}
- calld->PendingBatchesResume(elem);
- return;
- }
- // We do not yet have a subchannel call.
- // For batches containing a send_initial_metadata op, acquire the
- // channel's data plane mutex to pick a subchannel.
- if (GPR_LIKELY(batch->send_initial_metadata)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: grabbing data plane mutex to perform pick",
- chand, calld);
+ // Note: This will release the call combiner.
+ grpc_transport_stream_op_batch_finish_with_failure(
+ batch, GRPC_ERROR_REF(calld->cancel_error_), calld->call_combiner_);
+ return;
+ }
+ // Handle cancellation.
+ if (GPR_UNLIKELY(batch->cancel_stream)) {
+ // Stash a copy of cancel_error in our call data, so that we can use
+ // it for subsequent operations. This ensures that if the call is
+ // cancelled before any batches are passed down (e.g., if the deadline
+ // is in the past when the call starts), we can return the right
+ // error to the caller when the first batch does get passed down.
+ GRPC_ERROR_UNREF(calld->cancel_error_);
+ calld->cancel_error_ =
+ GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: recording cancel_error=%s", chand,
+ calld, grpc_error_string(calld->cancel_error_));
}
- PickSubchannel(elem, GRPC_ERROR_NONE);
- } else {
- // For all other batches, release the call combiner.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: saved batch, yielding call combiner", chand,
- calld);
- }
- GRPC_CALL_COMBINER_STOP(calld->call_combiner_,
- "batch does not include send_initial_metadata");
- }
-}
-
-void CallData::SetPollent(grpc_call_element* elem,
- grpc_polling_entity* pollent) {
- CallData* calld = static_cast<CallData*>(elem->call_data);
- calld->pollent_ = pollent;
-}
+ // If we do not have a subchannel call (i.e., a pick has not yet
+ // been started), fail all pending batches. Otherwise, send the
+ // cancellation down to the subchannel call.
+ if (calld->subchannel_call_ == nullptr) {
+ // TODO(roth): If there is a pending retry callback, do we need to
+ // cancel it here?
+ calld->PendingBatchesFail(elem, GRPC_ERROR_REF(calld->cancel_error_),
+ NoYieldCallCombiner);
+ // Note: This will release the call combiner.
+ grpc_transport_stream_op_batch_finish_with_failure(
+ batch, GRPC_ERROR_REF(calld->cancel_error_), calld->call_combiner_);
+ } else {
+ // Note: This will release the call combiner.
+ calld->subchannel_call_->StartTransportStreamOpBatch(batch);
+ }
+ return;
+ }
+ // Add the batch to the pending list.
+ calld->PendingBatchesAdd(elem, batch);
+ // Check if we've already gotten a subchannel call.
+ // Note that once we have picked a subchannel, we do not need to acquire
+ // the channel's data plane mutex, which is more efficient (especially for
+ // streaming calls).
+ if (calld->subchannel_call_ != nullptr) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: starting batch on subchannel_call=%p", chand,
+ calld, calld->subchannel_call_.get());
+ }
+ calld->PendingBatchesResume(elem);
+ return;
+ }
+ // We do not yet have a subchannel call.
+ // For batches containing a send_initial_metadata op, acquire the
+ // channel's data plane mutex to pick a subchannel.
+ if (GPR_LIKELY(batch->send_initial_metadata)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: grabbing data plane mutex to perform pick",
+ chand, calld);
+ }
+ PickSubchannel(elem, GRPC_ERROR_NONE);
+ } else {
+ // For all other batches, release the call combiner.
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: saved batch, yielding call combiner", chand,
+ calld);
+ }
+ GRPC_CALL_COMBINER_STOP(calld->call_combiner_,
+ "batch does not include send_initial_metadata");
+ }
+}
+
+void CallData::SetPollent(grpc_call_element* elem,
+ grpc_polling_entity* pollent) {
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ calld->pollent_ = pollent;
+}
//
// send op data caching
//
-void CallData::MaybeCacheSendOpsForBatch(PendingBatch* pending) {
+void CallData::MaybeCacheSendOpsForBatch(PendingBatch* pending) {
if (pending->send_ops_cached) return;
pending->send_ops_cached = true;
grpc_transport_stream_op_batch* batch = pending->batch;
// Save a copy of metadata for send_initial_metadata ops.
if (batch->send_initial_metadata) {
- seen_send_initial_metadata_ = true;
- GPR_ASSERT(send_initial_metadata_storage_ == nullptr);
+ seen_send_initial_metadata_ = true;
+ GPR_ASSERT(send_initial_metadata_storage_ == nullptr);
grpc_metadata_batch* send_initial_metadata =
batch->payload->send_initial_metadata.send_initial_metadata;
- send_initial_metadata_storage_ = (grpc_linked_mdelem*)arena_->Alloc(
+ send_initial_metadata_storage_ = (grpc_linked_mdelem*)arena_->Alloc(
sizeof(grpc_linked_mdelem) * send_initial_metadata->list.count);
- grpc_metadata_batch_copy(send_initial_metadata, &send_initial_metadata_,
- send_initial_metadata_storage_);
- send_initial_metadata_flags_ =
+ grpc_metadata_batch_copy(send_initial_metadata, &send_initial_metadata_,
+ send_initial_metadata_storage_);
+ send_initial_metadata_flags_ =
batch->payload->send_initial_metadata.send_initial_metadata_flags;
- peer_string_ = batch->payload->send_initial_metadata.peer_string;
+ peer_string_ = batch->payload->send_initial_metadata.peer_string;
}
// Set up cache for send_message ops.
if (batch->send_message) {
- ByteStreamCache* cache = arena_->New<ByteStreamCache>(
+ ByteStreamCache* cache = arena_->New<ByteStreamCache>(
std::move(batch->payload->send_message.send_message));
- send_messages_.push_back(cache);
+ send_messages_.push_back(cache);
}
// Save metadata batch for send_trailing_metadata ops.
if (batch->send_trailing_metadata) {
- seen_send_trailing_metadata_ = true;
- GPR_ASSERT(send_trailing_metadata_storage_ == nullptr);
+ seen_send_trailing_metadata_ = true;
+ GPR_ASSERT(send_trailing_metadata_storage_ == nullptr);
grpc_metadata_batch* send_trailing_metadata =
batch->payload->send_trailing_metadata.send_trailing_metadata;
- send_trailing_metadata_storage_ = (grpc_linked_mdelem*)arena_->Alloc(
- sizeof(grpc_linked_mdelem) * send_trailing_metadata->list.count);
- grpc_metadata_batch_copy(send_trailing_metadata, &send_trailing_metadata_,
- send_trailing_metadata_storage_);
+ send_trailing_metadata_storage_ = (grpc_linked_mdelem*)arena_->Alloc(
+ sizeof(grpc_linked_mdelem) * send_trailing_metadata->list.count);
+ grpc_metadata_batch_copy(send_trailing_metadata, &send_trailing_metadata_,
+ send_trailing_metadata_storage_);
}
}
-void CallData::FreeCachedSendInitialMetadata(ChannelData* chand) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::FreeCachedSendInitialMetadata(ChannelData* chand) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: destroying calld->send_initial_metadata", chand,
- this);
+ this);
}
- grpc_metadata_batch_destroy(&send_initial_metadata_);
+ grpc_metadata_batch_destroy(&send_initial_metadata_);
}
-void CallData::FreeCachedSendMessage(ChannelData* chand, size_t idx) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::FreeCachedSendMessage(ChannelData* chand, size_t idx) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR "]",
- chand, this, idx);
+ chand, this, idx);
}
- send_messages_[idx]->Destroy();
+ send_messages_[idx]->Destroy();
}
-void CallData::FreeCachedSendTrailingMetadata(ChannelData* chand) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::FreeCachedSendTrailingMetadata(ChannelData* chand) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: destroying calld->send_trailing_metadata",
- chand, this);
+ chand, this);
}
- grpc_metadata_batch_destroy(&send_trailing_metadata_);
+ grpc_metadata_batch_destroy(&send_trailing_metadata_);
}
-void CallData::FreeCachedSendOpDataAfterCommit(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+void CallData::FreeCachedSendOpDataAfterCommit(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
if (retry_state->completed_send_initial_metadata) {
- FreeCachedSendInitialMetadata(chand);
+ FreeCachedSendInitialMetadata(chand);
}
for (size_t i = 0; i < retry_state->completed_send_message_count; ++i) {
- FreeCachedSendMessage(chand, i);
+ FreeCachedSendMessage(chand, i);
}
if (retry_state->completed_send_trailing_metadata) {
- FreeCachedSendTrailingMetadata(chand);
+ FreeCachedSendTrailingMetadata(chand);
}
}
-void CallData::FreeCachedSendOpDataForCompletedBatch(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- SubchannelCallRetryState* retry_state) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+void CallData::FreeCachedSendOpDataForCompletedBatch(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ SubchannelCallRetryState* retry_state) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
if (batch_data->batch.send_initial_metadata) {
- FreeCachedSendInitialMetadata(chand);
+ FreeCachedSendInitialMetadata(chand);
}
if (batch_data->batch.send_message) {
- FreeCachedSendMessage(chand, retry_state->completed_send_message_count - 1);
+ FreeCachedSendMessage(chand, retry_state->completed_send_message_count - 1);
}
if (batch_data->batch.send_trailing_metadata) {
- FreeCachedSendTrailingMetadata(chand);
+ FreeCachedSendTrailingMetadata(chand);
}
}
@@ -2411,9 +2411,9 @@ void CallData::FreeCachedSendOpDataForCompletedBatch(
// LB recv_trailing_metadata_ready handling
//
-void CallData::RecvTrailingMetadataReadyForLoadBalancingPolicy(
- void* arg, grpc_error* error) {
- CallData* calld = static_cast<CallData*>(arg);
+void CallData::RecvTrailingMetadataReadyForLoadBalancingPolicy(
+ void* arg, grpc_error* error) {
+ CallData* calld = static_cast<CallData*>(arg);
// Set error if call did not succeed.
grpc_error* error_for_lb = GRPC_ERROR_NONE;
if (error != GRPC_ERROR_NONE) {
@@ -2435,28 +2435,28 @@ void CallData::RecvTrailingMetadataReadyForLoadBalancingPolicy(
}
}
}
- // Invoke callback to LB policy.
- Metadata trailing_metadata(calld, calld->recv_trailing_metadata_);
+ // Invoke callback to LB policy.
+ Metadata trailing_metadata(calld, calld->recv_trailing_metadata_);
calld->lb_recv_trailing_metadata_ready_(error_for_lb, &trailing_metadata,
- &calld->lb_call_state_);
+ &calld->lb_call_state_);
if (error == GRPC_ERROR_NONE) GRPC_ERROR_UNREF(error_for_lb);
- // Chain to original callback.
- Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready_,
- GRPC_ERROR_REF(error));
-}
-
-void CallData::MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
+ // Chain to original callback.
+ Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready_,
+ GRPC_ERROR_REF(error));
+}
+
+void CallData::MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
grpc_transport_stream_op_batch* batch) {
- if (lb_recv_trailing_metadata_ready_ != nullptr) {
- recv_trailing_metadata_ =
- batch->payload->recv_trailing_metadata.recv_trailing_metadata;
- original_recv_trailing_metadata_ready_ =
+ if (lb_recv_trailing_metadata_ready_ != nullptr) {
+ recv_trailing_metadata_ =
+ batch->payload->recv_trailing_metadata.recv_trailing_metadata;
+ original_recv_trailing_metadata_ready_ =
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
- GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_,
- RecvTrailingMetadataReadyForLoadBalancingPolicy, this,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_,
+ RecvTrailingMetadataReadyForLoadBalancingPolicy, this,
+ grpc_schedule_on_exec_ctx);
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
- &recv_trailing_metadata_ready_;
+ &recv_trailing_metadata_ready_;
}
}
@@ -2464,7 +2464,7 @@ void CallData::MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
// pending_batches management
//
-size_t CallData::GetBatchIndex(grpc_transport_stream_op_batch* batch) {
+size_t CallData::GetBatchIndex(grpc_transport_stream_op_batch* batch) {
// Note: It is important the send_initial_metadata be the first entry
// here, since the code in pick_subchannel_locked() assumes it will be.
if (batch->send_initial_metadata) return 0;
@@ -2477,213 +2477,213 @@ size_t CallData::GetBatchIndex(grpc_transport_stream_op_batch* batch) {
}
// This is called via the call combiner, so access to calld is synchronized.
-void CallData::PendingBatchesAdd(grpc_call_element* elem,
- grpc_transport_stream_op_batch* batch) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- const size_t idx = GetBatchIndex(batch);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::PendingBatchesAdd(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* batch) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ const size_t idx = GetBatchIndex(batch);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: adding pending batch at index %" PRIuPTR, chand,
- this, idx);
+ this, idx);
}
- PendingBatch* pending = &pending_batches_[idx];
+ PendingBatch* pending = &pending_batches_[idx];
GPR_ASSERT(pending->batch == nullptr);
pending->batch = batch;
pending->send_ops_cached = false;
- if (enable_retries_) {
+ if (enable_retries_) {
// Update state in calld about pending batches.
// Also check if the batch takes us over the retry buffer limit.
// Note: We don't check the size of trailing metadata here, because
// gRPC clients do not send trailing metadata.
if (batch->send_initial_metadata) {
- pending_send_initial_metadata_ = true;
- bytes_buffered_for_retry_ += grpc_metadata_batch_size(
+ pending_send_initial_metadata_ = true;
+ bytes_buffered_for_retry_ += grpc_metadata_batch_size(
batch->payload->send_initial_metadata.send_initial_metadata);
}
if (batch->send_message) {
- pending_send_message_ = true;
- bytes_buffered_for_retry_ +=
+ pending_send_message_ = true;
+ bytes_buffered_for_retry_ +=
batch->payload->send_message.send_message->length();
}
if (batch->send_trailing_metadata) {
- pending_send_trailing_metadata_ = true;
+ pending_send_trailing_metadata_ = true;
}
- if (GPR_UNLIKELY(bytes_buffered_for_retry_ >
- chand->per_rpc_retry_buffer_size())) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GPR_UNLIKELY(bytes_buffered_for_retry_ >
+ chand->per_rpc_retry_buffer_size())) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: exceeded retry buffer size, committing",
- chand, this);
+ chand, this);
}
- SubchannelCallRetryState* retry_state =
- subchannel_call_ == nullptr ? nullptr
- : static_cast<SubchannelCallRetryState*>(
- subchannel_call_->GetParentData());
- RetryCommit(elem, retry_state);
+ SubchannelCallRetryState* retry_state =
+ subchannel_call_ == nullptr ? nullptr
+ : static_cast<SubchannelCallRetryState*>(
+ subchannel_call_->GetParentData());
+ RetryCommit(elem, retry_state);
// If we are not going to retry and have not yet started, pretend
// retries are disabled so that we don't bother with retry overhead.
- if (num_attempts_completed_ == 0) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (num_attempts_completed_ == 0) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: disabling retries before first attempt",
- chand, this);
+ chand, this);
}
- enable_retries_ = false;
+ enable_retries_ = false;
}
}
}
}
-void CallData::PendingBatchClear(PendingBatch* pending) {
- if (enable_retries_) {
+void CallData::PendingBatchClear(PendingBatch* pending) {
+ if (enable_retries_) {
if (pending->batch->send_initial_metadata) {
- pending_send_initial_metadata_ = false;
+ pending_send_initial_metadata_ = false;
}
if (pending->batch->send_message) {
- pending_send_message_ = false;
+ pending_send_message_ = false;
}
if (pending->batch->send_trailing_metadata) {
- pending_send_trailing_metadata_ = false;
+ pending_send_trailing_metadata_ = false;
}
}
pending->batch = nullptr;
}
-void CallData::MaybeClearPendingBatch(grpc_call_element* elem,
- PendingBatch* pending) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- grpc_transport_stream_op_batch* batch = pending->batch;
- // We clear the pending batch if all of its callbacks have been
- // scheduled and reset to nullptr.
- if (batch->on_complete == nullptr &&
- (!batch->recv_initial_metadata ||
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready ==
- nullptr) &&
- (!batch->recv_message ||
- batch->payload->recv_message.recv_message_ready == nullptr) &&
- (!batch->recv_trailing_metadata ||
- batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready ==
- nullptr)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: clearing pending batch", chand,
- this);
- }
- PendingBatchClear(pending);
- }
-}
-
+void CallData::MaybeClearPendingBatch(grpc_call_element* elem,
+ PendingBatch* pending) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ grpc_transport_stream_op_batch* batch = pending->batch;
+ // We clear the pending batch if all of its callbacks have been
+ // scheduled and reset to nullptr.
+ if (batch->on_complete == nullptr &&
+ (!batch->recv_initial_metadata ||
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready ==
+ nullptr) &&
+ (!batch->recv_message ||
+ batch->payload->recv_message.recv_message_ready == nullptr) &&
+ (!batch->recv_trailing_metadata ||
+ batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready ==
+ nullptr)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: clearing pending batch", chand,
+ this);
+ }
+ PendingBatchClear(pending);
+ }
+}
+
// This is called via the call combiner, so access to calld is synchronized.
-void CallData::FailPendingBatchInCallCombiner(void* arg, grpc_error* error) {
+void CallData::FailPendingBatchInCallCombiner(void* arg, grpc_error* error) {
grpc_transport_stream_op_batch* batch =
static_cast<grpc_transport_stream_op_batch*>(arg);
- CallData* calld = static_cast<CallData*>(batch->handler_private.extra_arg);
+ CallData* calld = static_cast<CallData*>(batch->handler_private.extra_arg);
// Note: This will release the call combiner.
grpc_transport_stream_op_batch_finish_with_failure(
- batch, GRPC_ERROR_REF(error), calld->call_combiner_);
+ batch, GRPC_ERROR_REF(error), calld->call_combiner_);
}
// This is called via the call combiner, so access to calld is synchronized.
-void CallData::PendingBatchesFail(
- grpc_call_element* elem, grpc_error* error,
- YieldCallCombinerPredicate yield_call_combiner_predicate) {
+void CallData::PendingBatchesFail(
+ grpc_call_element* elem, grpc_error* error,
+ YieldCallCombinerPredicate yield_call_combiner_predicate) {
GPR_ASSERT(error != GRPC_ERROR_NONE);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
size_t num_batches = 0;
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- if (pending_batches_[i].batch != nullptr) ++num_batches;
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ if (pending_batches_[i].batch != nullptr) ++num_batches;
}
gpr_log(GPR_INFO,
"chand=%p calld=%p: failing %" PRIuPTR " pending batches: %s",
- elem->channel_data, this, num_batches, grpc_error_string(error));
+ elem->channel_data, this, num_batches, grpc_error_string(error));
}
- CallCombinerClosureList closures;
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- PendingBatch* pending = &pending_batches_[i];
+ CallCombinerClosureList closures;
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ PendingBatch* pending = &pending_batches_[i];
grpc_transport_stream_op_batch* batch = pending->batch;
if (batch != nullptr) {
- if (batch->recv_trailing_metadata) {
- MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch);
+ if (batch->recv_trailing_metadata) {
+ MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch);
}
- batch->handler_private.extra_arg = this;
+ batch->handler_private.extra_arg = this;
GRPC_CLOSURE_INIT(&batch->handler_private.closure,
- FailPendingBatchInCallCombiner, batch,
+ FailPendingBatchInCallCombiner, batch,
grpc_schedule_on_exec_ctx);
closures.Add(&batch->handler_private.closure, GRPC_ERROR_REF(error),
- "PendingBatchesFail");
- PendingBatchClear(pending);
+ "PendingBatchesFail");
+ PendingBatchClear(pending);
}
}
- if (yield_call_combiner_predicate(closures)) {
- closures.RunClosures(call_combiner_);
+ if (yield_call_combiner_predicate(closures)) {
+ closures.RunClosures(call_combiner_);
} else {
- closures.RunClosuresWithoutYielding(call_combiner_);
+ closures.RunClosuresWithoutYielding(call_combiner_);
}
GRPC_ERROR_UNREF(error);
}
// This is called via the call combiner, so access to calld is synchronized.
-void CallData::ResumePendingBatchInCallCombiner(void* arg,
- grpc_error* /*ignored*/) {
+void CallData::ResumePendingBatchInCallCombiner(void* arg,
+ grpc_error* /*ignored*/) {
grpc_transport_stream_op_batch* batch =
static_cast<grpc_transport_stream_op_batch*>(arg);
- SubchannelCall* subchannel_call =
- static_cast<SubchannelCall*>(batch->handler_private.extra_arg);
+ SubchannelCall* subchannel_call =
+ static_cast<SubchannelCall*>(batch->handler_private.extra_arg);
// Note: This will release the call combiner.
subchannel_call->StartTransportStreamOpBatch(batch);
}
// This is called via the call combiner, so access to calld is synchronized.
-void CallData::PendingBatchesResume(grpc_call_element* elem) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- if (enable_retries_) {
- StartRetriableSubchannelBatches(elem, GRPC_ERROR_NONE);
+void CallData::PendingBatchesResume(grpc_call_element* elem) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (enable_retries_) {
+ StartRetriableSubchannelBatches(elem, GRPC_ERROR_NONE);
return;
}
// Retries not enabled; send down batches as-is.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
size_t num_batches = 0;
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- if (pending_batches_[i].batch != nullptr) ++num_batches;
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ if (pending_batches_[i].batch != nullptr) ++num_batches;
}
gpr_log(GPR_INFO,
"chand=%p calld=%p: starting %" PRIuPTR
" pending batches on subchannel_call=%p",
- chand, this, num_batches, subchannel_call_.get());
+ chand, this, num_batches, subchannel_call_.get());
}
- CallCombinerClosureList closures;
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- PendingBatch* pending = &pending_batches_[i];
+ CallCombinerClosureList closures;
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ PendingBatch* pending = &pending_batches_[i];
grpc_transport_stream_op_batch* batch = pending->batch;
if (batch != nullptr) {
if (batch->recv_trailing_metadata) {
- MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch);
+ MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch);
}
- batch->handler_private.extra_arg = subchannel_call_.get();
+ batch->handler_private.extra_arg = subchannel_call_.get();
GRPC_CLOSURE_INIT(&batch->handler_private.closure,
- ResumePendingBatchInCallCombiner, batch,
+ ResumePendingBatchInCallCombiner, batch,
grpc_schedule_on_exec_ctx);
closures.Add(&batch->handler_private.closure, GRPC_ERROR_NONE,
- "PendingBatchesResume");
- PendingBatchClear(pending);
+ "PendingBatchesResume");
+ PendingBatchClear(pending);
}
}
// Note: This will release the call combiner.
- closures.RunClosures(call_combiner_);
+ closures.RunClosures(call_combiner_);
}
template <typename Predicate>
-CallData::PendingBatch* CallData::PendingBatchFind(grpc_call_element* elem,
- const char* log_message,
- Predicate predicate) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- PendingBatch* pending = &pending_batches_[i];
+CallData::PendingBatch* CallData::PendingBatchFind(grpc_call_element* elem,
+ const char* log_message,
+ Predicate predicate) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ PendingBatch* pending = &pending_batches_[i];
grpc_transport_stream_op_batch* batch = pending->batch;
if (batch != nullptr && predicate(batch)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: %s pending batch at index %" PRIuPTR, chand,
- this, log_message, i);
+ this, log_message, i);
}
return pending;
}
@@ -2695,98 +2695,98 @@ CallData::PendingBatch* CallData::PendingBatchFind(grpc_call_element* elem,
// retry code
//
-void CallData::RetryCommit(grpc_call_element* elem,
- SubchannelCallRetryState* retry_state) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- if (retry_committed_) return;
- retry_committed_ = true;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: committing retries", chand, this);
+void CallData::RetryCommit(grpc_call_element* elem,
+ SubchannelCallRetryState* retry_state) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (retry_committed_) return;
+ retry_committed_ = true;
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: committing retries", chand, this);
}
if (retry_state != nullptr) {
- FreeCachedSendOpDataAfterCommit(elem, retry_state);
+ FreeCachedSendOpDataAfterCommit(elem, retry_state);
}
}
-void CallData::DoRetry(grpc_call_element* elem,
- SubchannelCallRetryState* retry_state,
- grpc_millis server_pushback_ms) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- GPR_ASSERT(method_params_ != nullptr);
- const auto* retry_policy = method_params_->retry_policy();
+void CallData::DoRetry(grpc_call_element* elem,
+ SubchannelCallRetryState* retry_state,
+ grpc_millis server_pushback_ms) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ GPR_ASSERT(method_params_ != nullptr);
+ const auto* retry_policy = method_params_->retry_policy();
GPR_ASSERT(retry_policy != nullptr);
- // Reset subchannel call.
- subchannel_call_.reset();
+ // Reset subchannel call.
+ subchannel_call_.reset();
// Compute backoff delay.
grpc_millis next_attempt_time;
if (server_pushback_ms >= 0) {
- next_attempt_time = ExecCtx::Get()->Now() + server_pushback_ms;
- last_attempt_got_server_pushback_ = true;
+ next_attempt_time = ExecCtx::Get()->Now() + server_pushback_ms;
+ last_attempt_got_server_pushback_ = true;
} else {
- if (num_attempts_completed_ == 1 || last_attempt_got_server_pushback_) {
- retry_backoff_.Init(
- BackOff::Options()
+ if (num_attempts_completed_ == 1 || last_attempt_got_server_pushback_) {
+ retry_backoff_.Init(
+ BackOff::Options()
.set_initial_backoff(retry_policy->initial_backoff)
.set_multiplier(retry_policy->backoff_multiplier)
.set_jitter(RETRY_BACKOFF_JITTER)
.set_max_backoff(retry_policy->max_backoff));
- last_attempt_got_server_pushback_ = false;
+ last_attempt_got_server_pushback_ = false;
}
- next_attempt_time = retry_backoff_->NextAttemptTime();
+ next_attempt_time = retry_backoff_->NextAttemptTime();
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: retrying failed call in %" PRId64 " ms", chand,
- this, next_attempt_time - ExecCtx::Get()->Now());
+ this, next_attempt_time - ExecCtx::Get()->Now());
}
// Schedule retry after computed delay.
- GRPC_CLOSURE_INIT(&pick_closure_, PickSubchannel, elem,
- grpc_schedule_on_exec_ctx);
- grpc_timer_init(&retry_timer_, next_attempt_time, &pick_closure_);
+ GRPC_CLOSURE_INIT(&pick_closure_, PickSubchannel, elem,
+ grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&retry_timer_, next_attempt_time, &pick_closure_);
// Update bookkeeping.
if (retry_state != nullptr) retry_state->retry_dispatched = true;
}
-bool CallData::MaybeRetry(grpc_call_element* elem,
- SubchannelCallBatchData* batch_data,
- grpc_status_code status,
- grpc_mdelem* server_pushback_md) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+bool CallData::MaybeRetry(grpc_call_element* elem,
+ SubchannelCallBatchData* batch_data,
+ grpc_status_code status,
+ grpc_mdelem* server_pushback_md) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
// Get retry policy.
- if (method_params_ == nullptr) return false;
- const auto* retry_policy = method_params_->retry_policy();
+ if (method_params_ == nullptr) return false;
+ const auto* retry_policy = method_params_->retry_policy();
if (retry_policy == nullptr) return false;
// If we've already dispatched a retry from this call, return true.
// This catches the case where the batch has multiple callbacks
// (i.e., it includes either recv_message or recv_initial_metadata).
- SubchannelCallRetryState* retry_state = nullptr;
+ SubchannelCallRetryState* retry_state = nullptr;
if (batch_data != nullptr) {
- retry_state = static_cast<SubchannelCallRetryState*>(
+ retry_state = static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
if (retry_state->retry_dispatched) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: retry already dispatched", chand,
- this);
+ this);
}
return true;
}
}
// Check status.
if (GPR_LIKELY(status == GRPC_STATUS_OK)) {
- if (retry_throttle_data_ != nullptr) {
- retry_throttle_data_->RecordSuccess();
+ if (retry_throttle_data_ != nullptr) {
+ retry_throttle_data_->RecordSuccess();
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: call succeeded", chand, this);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: call succeeded", chand, this);
}
return false;
}
// Status is not OK. Check whether the status is retryable.
if (!retry_policy->retryable_status_codes.Contains(status)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: status %s not configured as retryable", chand,
- this, grpc_status_code_to_string(status));
+ this, grpc_status_code_to_string(status));
}
return false;
}
@@ -2797,36 +2797,36 @@ bool CallData::MaybeRetry(grpc_call_element* elem,
// things like failures due to malformed requests (INVALID_ARGUMENT).
// Conversely, it's important for this to come before the remaining
// checks, so that we don't fail to record failures due to other factors.
- if (retry_throttle_data_ != nullptr &&
- !retry_throttle_data_->RecordFailure()) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: retries throttled", chand, this);
+ if (retry_throttle_data_ != nullptr &&
+ !retry_throttle_data_->RecordFailure()) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: retries throttled", chand, this);
}
return false;
}
// Check whether the call is committed.
- if (retry_committed_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (retry_committed_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: retries already committed", chand,
- this);
+ this);
}
return false;
}
// Check whether we have retries remaining.
- ++num_attempts_completed_;
- if (num_attempts_completed_ >= retry_policy->max_attempts) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ ++num_attempts_completed_;
+ if (num_attempts_completed_ >= retry_policy->max_attempts) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: exceeded %d retry attempts", chand,
- this, retry_policy->max_attempts);
+ this, retry_policy->max_attempts);
}
return false;
}
// If the call was cancelled from the surface, don't retry.
- if (cancel_error_ != GRPC_ERROR_NONE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (cancel_error_ != GRPC_ERROR_NONE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: call cancelled from surface, not retrying",
- chand, this);
+ chand, this);
}
return false;
}
@@ -2836,55 +2836,55 @@ bool CallData::MaybeRetry(grpc_call_element* elem,
// If the value is "-1" or any other unparseable string, we do not retry.
uint32_t ms;
if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(*server_pushback_md), &ms)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: not retrying due to server push-back",
- chand, this);
+ chand, this);
}
return false;
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: server push-back: retry in %u ms",
- chand, this, ms);
+ chand, this, ms);
}
server_pushback_ms = (grpc_millis)ms;
}
}
- DoRetry(elem, retry_state, server_pushback_ms);
+ DoRetry(elem, retry_state, server_pushback_ms);
return true;
}
//
-// CallData::SubchannelCallBatchData
+// CallData::SubchannelCallBatchData
//
-CallData::SubchannelCallBatchData* CallData::SubchannelCallBatchData::Create(
- grpc_call_element* elem, int refcount, bool set_on_complete) {
- CallData* calld = static_cast<CallData*>(elem->call_data);
- return calld->arena_->New<SubchannelCallBatchData>(elem, calld, refcount,
- set_on_complete);
-}
-
-CallData::SubchannelCallBatchData::SubchannelCallBatchData(
- grpc_call_element* elem, CallData* calld, int refcount,
- bool set_on_complete)
- : elem(elem), subchannel_call(calld->subchannel_call_) {
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
- calld->subchannel_call_->GetParentData());
+CallData::SubchannelCallBatchData* CallData::SubchannelCallBatchData::Create(
+ grpc_call_element* elem, int refcount, bool set_on_complete) {
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ return calld->arena_->New<SubchannelCallBatchData>(elem, calld, refcount,
+ set_on_complete);
+}
+
+CallData::SubchannelCallBatchData::SubchannelCallBatchData(
+ grpc_call_element* elem, CallData* calld, int refcount,
+ bool set_on_complete)
+ : elem(elem), subchannel_call(calld->subchannel_call_) {
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
+ calld->subchannel_call_->GetParentData());
batch.payload = &retry_state->batch_payload;
gpr_ref_init(&refs, refcount);
if (set_on_complete) {
- GRPC_CLOSURE_INIT(&on_complete, CallData::OnComplete, this,
+ GRPC_CLOSURE_INIT(&on_complete, CallData::OnComplete, this,
grpc_schedule_on_exec_ctx);
batch.on_complete = &on_complete;
}
- GRPC_CALL_STACK_REF(calld->owning_call_, "batch_data");
+ GRPC_CALL_STACK_REF(calld->owning_call_, "batch_data");
}
-void CallData::SubchannelCallBatchData::Destroy() {
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(subchannel_call->GetParentData());
+void CallData::SubchannelCallBatchData::Destroy() {
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(subchannel_call->GetParentData());
if (batch.send_initial_metadata) {
grpc_metadata_batch_destroy(&retry_state->send_initial_metadata);
}
@@ -2898,20 +2898,20 @@ void CallData::SubchannelCallBatchData::Destroy() {
grpc_metadata_batch_destroy(&retry_state->recv_trailing_metadata);
}
subchannel_call.reset();
- CallData* calld = static_cast<CallData*>(elem->call_data);
- GRPC_CALL_STACK_UNREF(calld->owning_call_, "batch_data");
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ GRPC_CALL_STACK_UNREF(calld->owning_call_, "batch_data");
}
//
// recv_initial_metadata callback handling
//
-void CallData::InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error) {
- SubchannelCallBatchData* batch_data =
- static_cast<SubchannelCallBatchData*>(arg);
- CallData* calld = static_cast<CallData*>(batch_data->elem->call_data);
+void CallData::InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error) {
+ SubchannelCallBatchData* batch_data =
+ static_cast<SubchannelCallBatchData*>(arg);
+ CallData* calld = static_cast<CallData*>(batch_data->elem->call_data);
// Find pending batch.
- PendingBatch* pending = calld->PendingBatchFind(
+ PendingBatch* pending = calld->PendingBatchFind(
batch_data->elem, "invoking recv_initial_metadata_ready for",
[](grpc_transport_stream_op_batch* batch) {
return batch->recv_initial_metadata &&
@@ -2920,8 +2920,8 @@ void CallData::InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error) {
});
GPR_ASSERT(pending != nullptr);
// Return metadata.
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
grpc_metadata_batch_move(
&retry_state->recv_initial_metadata,
@@ -2934,33 +2934,33 @@ void CallData::InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error) {
.recv_initial_metadata_ready;
pending->batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
nullptr;
- calld->MaybeClearPendingBatch(batch_data->elem, pending);
- batch_data->Unref();
+ calld->MaybeClearPendingBatch(batch_data->elem, pending);
+ batch_data->Unref();
// Invoke callback.
- Closure::Run(DEBUG_LOCATION, recv_initial_metadata_ready,
- GRPC_ERROR_REF(error));
+ Closure::Run(DEBUG_LOCATION, recv_initial_metadata_ready,
+ GRPC_ERROR_REF(error));
}
-void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) {
- SubchannelCallBatchData* batch_data =
- static_cast<SubchannelCallBatchData*>(arg);
+void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) {
+ SubchannelCallBatchData* batch_data =
+ static_cast<SubchannelCallBatchData*>(arg);
grpc_call_element* elem = batch_data->elem;
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: got recv_initial_metadata_ready, error=%s",
chand, calld, grpc_error_string(error));
}
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
retry_state->completed_recv_initial_metadata = true;
// If a retry was already dispatched, then we're not going to use the
// result of this recv_initial_metadata op, so do nothing.
if (retry_state->retry_dispatched) {
GRPC_CALL_COMBINER_STOP(
- calld->call_combiner_,
+ calld->call_combiner_,
"recv_initial_metadata_ready after retry dispatched");
return;
}
@@ -2971,7 +2971,7 @@ void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) {
if (GPR_UNLIKELY((retry_state->trailing_metadata_available ||
error != GRPC_ERROR_NONE) &&
!retry_state->completed_recv_trailing_metadata)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: deferring recv_initial_metadata_ready "
"(Trailers-Only)",
@@ -2982,32 +2982,32 @@ void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) {
if (!retry_state->started_recv_trailing_metadata) {
// recv_trailing_metadata not yet started by application; start it
// ourselves to get status.
- calld->StartInternalRecvTrailingMetadata(elem);
+ calld->StartInternalRecvTrailingMetadata(elem);
} else {
GRPC_CALL_COMBINER_STOP(
- calld->call_combiner_,
+ calld->call_combiner_,
"recv_initial_metadata_ready trailers-only or error");
}
return;
}
// Received valid initial metadata, so commit the call.
- calld->RetryCommit(elem, retry_state);
+ calld->RetryCommit(elem, retry_state);
calld->MaybeInvokeConfigSelectorCommitCallback();
// Invoke the callback to return the result to the surface.
// Manually invoking a callback function; it does not take ownership of error.
- calld->InvokeRecvInitialMetadataCallback(batch_data, error);
+ calld->InvokeRecvInitialMetadataCallback(batch_data, error);
}
//
// recv_message callback handling
//
-void CallData::InvokeRecvMessageCallback(void* arg, grpc_error* error) {
- SubchannelCallBatchData* batch_data =
- static_cast<SubchannelCallBatchData*>(arg);
- CallData* calld = static_cast<CallData*>(batch_data->elem->call_data);
+void CallData::InvokeRecvMessageCallback(void* arg, grpc_error* error) {
+ SubchannelCallBatchData* batch_data =
+ static_cast<SubchannelCallBatchData*>(arg);
+ CallData* calld = static_cast<CallData*>(batch_data->elem->call_data);
// Find pending op.
- PendingBatch* pending = calld->PendingBatchFind(
+ PendingBatch* pending = calld->PendingBatchFind(
batch_data->elem, "invoking recv_message_ready for",
[](grpc_transport_stream_op_batch* batch) {
return batch->recv_message &&
@@ -3015,8 +3015,8 @@ void CallData::InvokeRecvMessageCallback(void* arg, grpc_error* error) {
});
GPR_ASSERT(pending != nullptr);
// Return payload.
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
*pending->batch->payload->recv_message.recv_message =
std::move(retry_state->recv_message);
@@ -3026,30 +3026,30 @@ void CallData::InvokeRecvMessageCallback(void* arg, grpc_error* error) {
grpc_closure* recv_message_ready =
pending->batch->payload->recv_message.recv_message_ready;
pending->batch->payload->recv_message.recv_message_ready = nullptr;
- calld->MaybeClearPendingBatch(batch_data->elem, pending);
- batch_data->Unref();
+ calld->MaybeClearPendingBatch(batch_data->elem, pending);
+ batch_data->Unref();
// Invoke callback.
- Closure::Run(DEBUG_LOCATION, recv_message_ready, GRPC_ERROR_REF(error));
+ Closure::Run(DEBUG_LOCATION, recv_message_ready, GRPC_ERROR_REF(error));
}
-void CallData::RecvMessageReady(void* arg, grpc_error* error) {
- SubchannelCallBatchData* batch_data =
- static_cast<SubchannelCallBatchData*>(arg);
+void CallData::RecvMessageReady(void* arg, grpc_error* error) {
+ SubchannelCallBatchData* batch_data =
+ static_cast<SubchannelCallBatchData*>(arg);
grpc_call_element* elem = batch_data->elem;
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: got recv_message_ready, error=%s",
chand, calld, grpc_error_string(error));
}
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
++retry_state->completed_recv_message_count;
// If a retry was already dispatched, then we're not going to use the
// result of this recv_message op, so do nothing.
if (retry_state->retry_dispatched) {
- GRPC_CALL_COMBINER_STOP(calld->call_combiner_,
+ GRPC_CALL_COMBINER_STOP(calld->call_combiner_,
"recv_message_ready after retry dispatched");
return;
}
@@ -3060,7 +3060,7 @@ void CallData::RecvMessageReady(void* arg, grpc_error* error) {
if (GPR_UNLIKELY(
(retry_state->recv_message == nullptr || error != GRPC_ERROR_NONE) &&
!retry_state->completed_recv_trailing_metadata)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: deferring recv_message_ready (nullptr "
"message and recv_trailing_metadata pending)",
@@ -3071,29 +3071,29 @@ void CallData::RecvMessageReady(void* arg, grpc_error* error) {
if (!retry_state->started_recv_trailing_metadata) {
// recv_trailing_metadata not yet started by application; start it
// ourselves to get status.
- calld->StartInternalRecvTrailingMetadata(elem);
+ calld->StartInternalRecvTrailingMetadata(elem);
} else {
- GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "recv_message_ready null");
+ GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "recv_message_ready null");
}
return;
}
// Received a valid message, so commit the call.
- calld->RetryCommit(elem, retry_state);
+ calld->RetryCommit(elem, retry_state);
calld->MaybeInvokeConfigSelectorCommitCallback();
// Invoke the callback to return the result to the surface.
// Manually invoking a callback function; it does not take ownership of error.
- calld->InvokeRecvMessageCallback(batch_data, error);
+ calld->InvokeRecvMessageCallback(batch_data, error);
}
//
// recv_trailing_metadata handling
//
-void CallData::GetCallStatus(grpc_metadata_batch* md_batch, grpc_error* error,
- grpc_status_code* status,
- grpc_mdelem** server_pushback_md) {
+void CallData::GetCallStatus(grpc_metadata_batch* md_batch, grpc_error* error,
+ grpc_status_code* status,
+ grpc_mdelem** server_pushback_md) {
if (error != GRPC_ERROR_NONE) {
- grpc_error_get_status(error, deadline_, status, nullptr, nullptr, nullptr);
+ grpc_error_get_status(error, deadline_, status, nullptr, nullptr, nullptr);
} else {
GPR_ASSERT(md_batch->idx.named.grpc_status != nullptr);
*status =
@@ -3106,11 +3106,11 @@ void CallData::GetCallStatus(grpc_metadata_batch* md_batch, grpc_error* error,
GRPC_ERROR_UNREF(error);
}
-void CallData::AddClosureForRecvTrailingMetadataReady(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- grpc_error* error, CallCombinerClosureList* closures) {
+void CallData::AddClosureForRecvTrailingMetadataReady(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ grpc_error* error, CallCombinerClosureList* closures) {
// Find pending batch.
- PendingBatch* pending = PendingBatchFind(
+ PendingBatch* pending = PendingBatchFind(
elem, "invoking recv_trailing_metadata for",
[](grpc_transport_stream_op_batch* batch) {
return batch->recv_trailing_metadata &&
@@ -3118,14 +3118,14 @@ void CallData::AddClosureForRecvTrailingMetadataReady(
.recv_trailing_metadata_ready != nullptr;
});
// If we generated the recv_trailing_metadata op internally via
- // StartInternalRecvTrailingMetadata(), then there will be no pending batch.
+ // StartInternalRecvTrailingMetadata(), then there will be no pending batch.
if (pending == nullptr) {
GRPC_ERROR_UNREF(error);
return;
}
// Return metadata.
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
grpc_metadata_batch_move(
&retry_state->recv_trailing_metadata,
@@ -3137,18 +3137,18 @@ void CallData::AddClosureForRecvTrailingMetadataReady(
// Update bookkeeping.
pending->batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
nullptr;
- MaybeClearPendingBatch(elem, pending);
+ MaybeClearPendingBatch(elem, pending);
}
-void CallData::AddClosuresForDeferredRecvCallbacks(
- SubchannelCallBatchData* batch_data, SubchannelCallRetryState* retry_state,
- CallCombinerClosureList* closures) {
+void CallData::AddClosuresForDeferredRecvCallbacks(
+ SubchannelCallBatchData* batch_data, SubchannelCallRetryState* retry_state,
+ CallCombinerClosureList* closures) {
if (batch_data->batch.recv_trailing_metadata) {
// Add closure for deferred recv_initial_metadata_ready.
if (GPR_UNLIKELY(retry_state->recv_initial_metadata_ready_deferred_batch !=
nullptr)) {
GRPC_CLOSURE_INIT(&retry_state->recv_initial_metadata_ready,
- InvokeRecvInitialMetadataCallback,
+ InvokeRecvInitialMetadataCallback,
retry_state->recv_initial_metadata_ready_deferred_batch,
grpc_schedule_on_exec_ctx);
closures->Add(&retry_state->recv_initial_metadata_ready,
@@ -3160,7 +3160,7 @@ void CallData::AddClosuresForDeferredRecvCallbacks(
if (GPR_UNLIKELY(retry_state->recv_message_ready_deferred_batch !=
nullptr)) {
GRPC_CLOSURE_INIT(&retry_state->recv_message_ready,
- InvokeRecvMessageCallback,
+ InvokeRecvMessageCallback,
retry_state->recv_message_ready_deferred_batch,
grpc_schedule_on_exec_ctx);
closures->Add(&retry_state->recv_message_ready,
@@ -3171,8 +3171,8 @@ void CallData::AddClosuresForDeferredRecvCallbacks(
}
}
-bool CallData::PendingBatchIsUnstarted(PendingBatch* pending,
- SubchannelCallRetryState* retry_state) {
+bool CallData::PendingBatchIsUnstarted(PendingBatch* pending,
+ SubchannelCallRetryState* retry_state) {
if (pending->batch == nullptr || pending->batch->on_complete == nullptr) {
return false;
}
@@ -3181,7 +3181,7 @@ bool CallData::PendingBatchIsUnstarted(PendingBatch* pending,
return true;
}
if (pending->batch->send_message &&
- retry_state->started_send_message_count < send_messages_.size()) {
+ retry_state->started_send_message_count < send_messages_.size()) {
return true;
}
if (pending->batch->send_trailing_metadata &&
@@ -3191,66 +3191,66 @@ bool CallData::PendingBatchIsUnstarted(PendingBatch* pending,
return false;
}
-void CallData::AddClosuresToFailUnstartedPendingBatches(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state,
- grpc_error* error, CallCombinerClosureList* closures) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- PendingBatch* pending = &pending_batches_[i];
- if (PendingBatchIsUnstarted(pending, retry_state)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::AddClosuresToFailUnstartedPendingBatches(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state,
+ grpc_error* error, CallCombinerClosureList* closures) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ PendingBatch* pending = &pending_batches_[i];
+ if (PendingBatchIsUnstarted(pending, retry_state)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: failing unstarted pending batch at index "
"%" PRIuPTR,
- chand, this, i);
+ chand, this, i);
}
closures->Add(pending->batch->on_complete, GRPC_ERROR_REF(error),
"failing on_complete for pending batch");
pending->batch->on_complete = nullptr;
- MaybeClearPendingBatch(elem, pending);
+ MaybeClearPendingBatch(elem, pending);
}
}
GRPC_ERROR_UNREF(error);
}
-void CallData::RunClosuresForCompletedCall(SubchannelCallBatchData* batch_data,
- grpc_error* error) {
+void CallData::RunClosuresForCompletedCall(SubchannelCallBatchData* batch_data,
+ grpc_error* error) {
grpc_call_element* elem = batch_data->elem;
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
// Construct list of closures to execute.
- CallCombinerClosureList closures;
+ CallCombinerClosureList closures;
// First, add closure for recv_trailing_metadata_ready.
- AddClosureForRecvTrailingMetadataReady(elem, batch_data,
- GRPC_ERROR_REF(error), &closures);
+ AddClosureForRecvTrailingMetadataReady(elem, batch_data,
+ GRPC_ERROR_REF(error), &closures);
// If there are deferred recv_initial_metadata_ready or recv_message_ready
// callbacks, add them to closures.
- AddClosuresForDeferredRecvCallbacks(batch_data, retry_state, &closures);
+ AddClosuresForDeferredRecvCallbacks(batch_data, retry_state, &closures);
// Add closures to fail any pending batches that have not yet been started.
- AddClosuresToFailUnstartedPendingBatches(elem, retry_state,
- GRPC_ERROR_REF(error), &closures);
+ AddClosuresToFailUnstartedPendingBatches(elem, retry_state,
+ GRPC_ERROR_REF(error), &closures);
// Don't need batch_data anymore.
- batch_data->Unref();
+ batch_data->Unref();
// Schedule all of the closures identified above.
// Note: This will release the call combiner.
- closures.RunClosures(call_combiner_);
+ closures.RunClosures(call_combiner_);
GRPC_ERROR_UNREF(error);
}
-void CallData::RecvTrailingMetadataReady(void* arg, grpc_error* error) {
- SubchannelCallBatchData* batch_data =
- static_cast<SubchannelCallBatchData*>(arg);
+void CallData::RecvTrailingMetadataReady(void* arg, grpc_error* error) {
+ SubchannelCallBatchData* batch_data =
+ static_cast<SubchannelCallBatchData*>(arg);
grpc_call_element* elem = batch_data->elem;
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: got recv_trailing_metadata_ready, error=%s",
chand, calld, grpc_error_string(error));
}
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
retry_state->completed_recv_trailing_metadata = true;
// Get the call's status and check for server pushback metadata.
@@ -3258,42 +3258,42 @@ void CallData::RecvTrailingMetadataReady(void* arg, grpc_error* error) {
grpc_mdelem* server_pushback_md = nullptr;
grpc_metadata_batch* md_batch =
batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata;
- calld->GetCallStatus(md_batch, GRPC_ERROR_REF(error), &status,
- &server_pushback_md);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ calld->GetCallStatus(md_batch, GRPC_ERROR_REF(error), &status,
+ &server_pushback_md);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: call finished, status=%s", chand,
calld, grpc_status_code_to_string(status));
}
// Check if we should retry.
- if (calld->MaybeRetry(elem, batch_data, status, server_pushback_md)) {
+ if (calld->MaybeRetry(elem, batch_data, status, server_pushback_md)) {
// Unref batch_data for deferred recv_initial_metadata_ready or
// recv_message_ready callbacks, if any.
if (retry_state->recv_initial_metadata_ready_deferred_batch != nullptr) {
- batch_data->Unref();
+ batch_data->Unref();
GRPC_ERROR_UNREF(retry_state->recv_initial_metadata_error);
}
if (retry_state->recv_message_ready_deferred_batch != nullptr) {
- batch_data->Unref();
+ batch_data->Unref();
GRPC_ERROR_UNREF(retry_state->recv_message_error);
}
- batch_data->Unref();
+ batch_data->Unref();
return;
}
// Not retrying, so commit the call.
- calld->RetryCommit(elem, retry_state);
+ calld->RetryCommit(elem, retry_state);
calld->MaybeInvokeConfigSelectorCommitCallback();
// Run any necessary closures.
- calld->RunClosuresForCompletedCall(batch_data, GRPC_ERROR_REF(error));
+ calld->RunClosuresForCompletedCall(batch_data, GRPC_ERROR_REF(error));
}
//
// on_complete callback handling
//
-void CallData::AddClosuresForCompletedPendingBatch(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- grpc_error* error, CallCombinerClosureList* closures) {
- PendingBatch* pending = PendingBatchFind(
+void CallData::AddClosuresForCompletedPendingBatch(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ grpc_error* error, CallCombinerClosureList* closures) {
+ PendingBatch* pending = PendingBatchFind(
elem, "completed", [batch_data](grpc_transport_stream_op_batch* batch) {
// Match the pending batch with the same set of send ops as the
// subchannel batch we've just completed.
@@ -3314,22 +3314,22 @@ void CallData::AddClosuresForCompletedPendingBatch(
closures->Add(pending->batch->on_complete, error,
"on_complete for pending batch");
pending->batch->on_complete = nullptr;
- MaybeClearPendingBatch(elem, pending);
+ MaybeClearPendingBatch(elem, pending);
}
-void CallData::AddClosuresForReplayOrPendingSendOps(
- grpc_call_element* elem, SubchannelCallBatchData* batch_data,
- SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+void CallData::AddClosuresForReplayOrPendingSendOps(
+ grpc_call_element* elem, SubchannelCallBatchData* batch_data,
+ SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
bool have_pending_send_message_ops =
- retry_state->started_send_message_count < send_messages_.size();
+ retry_state->started_send_message_count < send_messages_.size();
bool have_pending_send_trailing_metadata_op =
- seen_send_trailing_metadata_ &&
+ seen_send_trailing_metadata_ &&
!retry_state->started_send_trailing_metadata;
if (!have_pending_send_message_ops &&
!have_pending_send_trailing_metadata_op) {
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- PendingBatch* pending = &pending_batches_[i];
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ PendingBatch* pending = &pending_batches_[i];
grpc_transport_stream_op_batch* batch = pending->batch;
if (batch == nullptr || pending->send_ops_cached) continue;
if (batch->send_message) have_pending_send_message_ops = true;
@@ -3339,32 +3339,32 @@ void CallData::AddClosuresForReplayOrPendingSendOps(
}
}
if (have_pending_send_message_ops || have_pending_send_trailing_metadata_op) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: starting next batch for pending send op(s)",
- chand, this);
+ chand, this);
}
GRPC_CLOSURE_INIT(&batch_data->batch.handler_private.closure,
- StartRetriableSubchannelBatches, elem,
+ StartRetriableSubchannelBatches, elem,
grpc_schedule_on_exec_ctx);
closures->Add(&batch_data->batch.handler_private.closure, GRPC_ERROR_NONE,
"starting next batch for send_* op(s)");
}
}
-void CallData::OnComplete(void* arg, grpc_error* error) {
- SubchannelCallBatchData* batch_data =
- static_cast<SubchannelCallBatchData*>(arg);
+void CallData::OnComplete(void* arg, grpc_error* error) {
+ SubchannelCallBatchData* batch_data =
+ static_cast<SubchannelCallBatchData*>(arg);
grpc_call_element* elem = batch_data->elem;
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: got on_complete, error=%s, batch=%s",
chand, calld, grpc_error_string(error),
grpc_transport_stream_op_batch_string(&batch_data->batch).c_str());
}
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
// Update bookkeeping in retry_state.
if (batch_data->batch.send_initial_metadata) {
@@ -3378,38 +3378,38 @@ void CallData::OnComplete(void* arg, grpc_error* error) {
}
// If the call is committed, free cached data for send ops that we've just
// completed.
- if (calld->retry_committed_) {
- calld->FreeCachedSendOpDataForCompletedBatch(elem, batch_data, retry_state);
+ if (calld->retry_committed_) {
+ calld->FreeCachedSendOpDataForCompletedBatch(elem, batch_data, retry_state);
}
// Construct list of closures to execute.
- CallCombinerClosureList closures;
+ CallCombinerClosureList closures;
// If a retry was already dispatched, that means we saw
// recv_trailing_metadata before this, so we do nothing here.
// Otherwise, invoke the callback to return the result to the surface.
if (!retry_state->retry_dispatched) {
// Add closure for the completed pending batch, if any.
- calld->AddClosuresForCompletedPendingBatch(
- elem, batch_data, GRPC_ERROR_REF(error), &closures);
+ calld->AddClosuresForCompletedPendingBatch(
+ elem, batch_data, GRPC_ERROR_REF(error), &closures);
// If needed, add a callback to start any replay or pending send ops on
// the subchannel call.
if (!retry_state->completed_recv_trailing_metadata) {
- calld->AddClosuresForReplayOrPendingSendOps(elem, batch_data, retry_state,
+ calld->AddClosuresForReplayOrPendingSendOps(elem, batch_data, retry_state,
&closures);
}
}
// Track number of pending subchannel send batches and determine if this
// was the last one.
- --calld->num_pending_retriable_subchannel_send_batches_;
+ --calld->num_pending_retriable_subchannel_send_batches_;
const bool last_send_batch_complete =
- calld->num_pending_retriable_subchannel_send_batches_ == 0;
+ calld->num_pending_retriable_subchannel_send_batches_ == 0;
// Don't need batch_data anymore.
- batch_data->Unref();
+ batch_data->Unref();
// Schedule all of the closures identified above.
// Note: This yeilds the call combiner.
- closures.RunClosures(calld->call_combiner_);
+ closures.RunClosures(calld->call_combiner_);
// If this was the last subchannel send batch, unref the call stack.
if (last_send_batch_complete) {
- GRPC_CALL_STACK_UNREF(calld->owning_call_, "subchannel_send_batches");
+ GRPC_CALL_STACK_UNREF(calld->owning_call_, "subchannel_send_batches");
}
}
@@ -3417,23 +3417,23 @@ void CallData::OnComplete(void* arg, grpc_error* error) {
// subchannel batch construction
//
-void CallData::StartBatchInCallCombiner(void* arg, grpc_error* /*ignored*/) {
+void CallData::StartBatchInCallCombiner(void* arg, grpc_error* /*ignored*/) {
grpc_transport_stream_op_batch* batch =
static_cast<grpc_transport_stream_op_batch*>(arg);
- SubchannelCall* subchannel_call =
- static_cast<SubchannelCall*>(batch->handler_private.extra_arg);
+ SubchannelCall* subchannel_call =
+ static_cast<SubchannelCall*>(batch->handler_private.extra_arg);
// Note: This will release the call combiner.
subchannel_call->StartTransportStreamOpBatch(batch);
}
-void CallData::AddClosureForSubchannelBatch(
+void CallData::AddClosureForSubchannelBatch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch,
- CallCombinerClosureList* closures) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- batch->handler_private.extra_arg = subchannel_call_.get();
- GRPC_CLOSURE_INIT(&batch->handler_private.closure, StartBatchInCallCombiner,
- batch, grpc_schedule_on_exec_ctx);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ CallCombinerClosureList* closures) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ batch->handler_private.extra_arg = subchannel_call_.get();
+ GRPC_CLOSURE_INIT(&batch->handler_private.closure, StartBatchInCallCombiner,
+ batch, grpc_schedule_on_exec_ctx);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: starting subchannel batch: %s", chand,
this, grpc_transport_stream_op_batch_string(batch).c_str());
}
@@ -3441,12 +3441,12 @@ void CallData::AddClosureForSubchannelBatch(
"start_subchannel_batch");
}
-void CallData::AddRetriableSendInitialMetadataOp(
- SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data) {
+void CallData::AddRetriableSendInitialMetadataOp(
+ SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data) {
// Maps the number of retries to the corresponding metadata value slice.
- const grpc_slice* retry_count_strings[] = {&GRPC_MDSTR_1, &GRPC_MDSTR_2,
- &GRPC_MDSTR_3, &GRPC_MDSTR_4};
+ const grpc_slice* retry_count_strings[] = {&GRPC_MDSTR_1, &GRPC_MDSTR_2,
+ &GRPC_MDSTR_3, &GRPC_MDSTR_4};
// We need to make a copy of the metadata batch for each attempt, since
// the filters in the subchannel stack may modify this batch, and we don't
// want those modifications to be passed forward to subsequent attempts.
@@ -3454,26 +3454,26 @@ void CallData::AddRetriableSendInitialMetadataOp(
// If we've already completed one or more attempts, add the
// grpc-retry-attempts header.
retry_state->send_initial_metadata_storage =
- static_cast<grpc_linked_mdelem*>(arena_->Alloc(
- sizeof(grpc_linked_mdelem) *
- (send_initial_metadata_.list.count + (num_attempts_completed_ > 0))));
- grpc_metadata_batch_copy(&send_initial_metadata_,
+ static_cast<grpc_linked_mdelem*>(arena_->Alloc(
+ sizeof(grpc_linked_mdelem) *
+ (send_initial_metadata_.list.count + (num_attempts_completed_ > 0))));
+ grpc_metadata_batch_copy(&send_initial_metadata_,
&retry_state->send_initial_metadata,
retry_state->send_initial_metadata_storage);
if (GPR_UNLIKELY(retry_state->send_initial_metadata.idx.named
.grpc_previous_rpc_attempts != nullptr)) {
grpc_metadata_batch_remove(&retry_state->send_initial_metadata,
- GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS);
+ GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS);
}
- if (GPR_UNLIKELY(num_attempts_completed_ > 0)) {
+ if (GPR_UNLIKELY(num_attempts_completed_ > 0)) {
grpc_mdelem retry_md = grpc_mdelem_create(
GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS,
- *retry_count_strings[num_attempts_completed_ - 1], nullptr);
+ *retry_count_strings[num_attempts_completed_ - 1], nullptr);
grpc_error* error = grpc_metadata_batch_add_tail(
&retry_state->send_initial_metadata,
- &retry_state
- ->send_initial_metadata_storage[send_initial_metadata_.list.count],
- retry_md, GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS);
+ &retry_state
+ ->send_initial_metadata_storage[send_initial_metadata_.list.count],
+ retry_md, GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS);
if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
gpr_log(GPR_ERROR, "error adding retry metadata: %s",
grpc_error_string(error));
@@ -3485,21 +3485,21 @@ void CallData::AddRetriableSendInitialMetadataOp(
batch_data->batch.payload->send_initial_metadata.send_initial_metadata =
&retry_state->send_initial_metadata;
batch_data->batch.payload->send_initial_metadata.send_initial_metadata_flags =
- send_initial_metadata_flags_;
- batch_data->batch.payload->send_initial_metadata.peer_string = peer_string_;
+ send_initial_metadata_flags_;
+ batch_data->batch.payload->send_initial_metadata.peer_string = peer_string_;
}
-void CallData::AddRetriableSendMessageOp(grpc_call_element* elem,
- SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::AddRetriableSendMessageOp(grpc_call_element* elem,
+ SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: starting calld->send_messages[%" PRIuPTR "]",
- chand, this, retry_state->started_send_message_count);
+ chand, this, retry_state->started_send_message_count);
}
- ByteStreamCache* cache =
- send_messages_[retry_state->started_send_message_count];
+ ByteStreamCache* cache =
+ send_messages_[retry_state->started_send_message_count];
++retry_state->started_send_message_count;
retry_state->send_message.Init(cache);
batch_data->batch.send_message = true;
@@ -3507,16 +3507,16 @@ void CallData::AddRetriableSendMessageOp(grpc_call_element* elem,
retry_state->send_message.get());
}
-void CallData::AddRetriableSendTrailingMetadataOp(
- SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data) {
+void CallData::AddRetriableSendTrailingMetadataOp(
+ SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data) {
// We need to make a copy of the metadata batch for each attempt, since
// the filters in the subchannel stack may modify this batch, and we don't
// want those modifications to be passed forward to subsequent attempts.
retry_state->send_trailing_metadata_storage =
- static_cast<grpc_linked_mdelem*>(arena_->Alloc(
- sizeof(grpc_linked_mdelem) * send_trailing_metadata_.list.count));
- grpc_metadata_batch_copy(&send_trailing_metadata_,
+ static_cast<grpc_linked_mdelem*>(arena_->Alloc(
+ sizeof(grpc_linked_mdelem) * send_trailing_metadata_.list.count));
+ grpc_metadata_batch_copy(&send_trailing_metadata_,
&retry_state->send_trailing_metadata,
retry_state->send_trailing_metadata_storage);
retry_state->started_send_trailing_metadata = true;
@@ -3525,9 +3525,9 @@ void CallData::AddRetriableSendTrailingMetadataOp(
&retry_state->send_trailing_metadata;
}
-void CallData::AddRetriableRecvInitialMetadataOp(
- SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data) {
+void CallData::AddRetriableRecvInitialMetadataOp(
+ SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data) {
retry_state->started_recv_initial_metadata = true;
batch_data->batch.recv_initial_metadata = true;
grpc_metadata_batch_init(&retry_state->recv_initial_metadata);
@@ -3536,27 +3536,27 @@ void CallData::AddRetriableRecvInitialMetadataOp(
batch_data->batch.payload->recv_initial_metadata.trailing_metadata_available =
&retry_state->trailing_metadata_available;
GRPC_CLOSURE_INIT(&retry_state->recv_initial_metadata_ready,
- RecvInitialMetadataReady, batch_data,
+ RecvInitialMetadataReady, batch_data,
grpc_schedule_on_exec_ctx);
batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata_ready =
&retry_state->recv_initial_metadata_ready;
}
-void CallData::AddRetriableRecvMessageOp(SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data) {
+void CallData::AddRetriableRecvMessageOp(SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data) {
++retry_state->started_recv_message_count;
batch_data->batch.recv_message = true;
batch_data->batch.payload->recv_message.recv_message =
&retry_state->recv_message;
- GRPC_CLOSURE_INIT(&retry_state->recv_message_ready, RecvMessageReady,
+ GRPC_CLOSURE_INIT(&retry_state->recv_message_ready, RecvMessageReady,
batch_data, grpc_schedule_on_exec_ctx);
batch_data->batch.payload->recv_message.recv_message_ready =
&retry_state->recv_message_ready;
}
-void CallData::AddRetriableRecvTrailingMetadataOp(
- SubchannelCallRetryState* retry_state,
- SubchannelCallBatchData* batch_data) {
+void CallData::AddRetriableRecvTrailingMetadataOp(
+ SubchannelCallRetryState* retry_state,
+ SubchannelCallBatchData* batch_data) {
retry_state->started_recv_trailing_metadata = true;
batch_data->batch.recv_trailing_metadata = true;
grpc_metadata_batch_init(&retry_state->recv_trailing_metadata);
@@ -3565,105 +3565,105 @@ void CallData::AddRetriableRecvTrailingMetadataOp(
batch_data->batch.payload->recv_trailing_metadata.collect_stats =
&retry_state->collect_stats;
GRPC_CLOSURE_INIT(&retry_state->recv_trailing_metadata_ready,
- RecvTrailingMetadataReady, batch_data,
+ RecvTrailingMetadataReady, batch_data,
grpc_schedule_on_exec_ctx);
batch_data->batch.payload->recv_trailing_metadata
.recv_trailing_metadata_ready =
&retry_state->recv_trailing_metadata_ready;
- MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
- &batch_data->batch);
+ MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
+ &batch_data->batch);
}
-void CallData::StartInternalRecvTrailingMetadata(grpc_call_element* elem) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+void CallData::StartInternalRecvTrailingMetadata(grpc_call_element* elem) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: call failed but recv_trailing_metadata not "
"started; starting it internally",
- chand, this);
+ chand, this);
}
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(subchannel_call_->GetParentData());
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(subchannel_call_->GetParentData());
// Create batch_data with 2 refs, since this batch will be unreffed twice:
// once for the recv_trailing_metadata_ready callback when the subchannel
// batch returns, and again when we actually get a recv_trailing_metadata
// op from the surface.
- SubchannelCallBatchData* batch_data =
- SubchannelCallBatchData::Create(elem, 2, false /* set_on_complete */);
- AddRetriableRecvTrailingMetadataOp(retry_state, batch_data);
+ SubchannelCallBatchData* batch_data =
+ SubchannelCallBatchData::Create(elem, 2, false /* set_on_complete */);
+ AddRetriableRecvTrailingMetadataOp(retry_state, batch_data);
retry_state->recv_trailing_metadata_internal_batch = batch_data;
// Note: This will release the call combiner.
- subchannel_call_->StartTransportStreamOpBatch(&batch_data->batch);
+ subchannel_call_->StartTransportStreamOpBatch(&batch_data->batch);
}
// If there are any cached send ops that need to be replayed on the
// current subchannel call, creates and returns a new subchannel batch
// to replay those ops. Otherwise, returns nullptr.
-CallData::SubchannelCallBatchData*
-CallData::MaybeCreateSubchannelBatchForReplay(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- SubchannelCallBatchData* replay_batch_data = nullptr;
+CallData::SubchannelCallBatchData*
+CallData::MaybeCreateSubchannelBatchForReplay(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ SubchannelCallBatchData* replay_batch_data = nullptr;
// send_initial_metadata.
- if (seen_send_initial_metadata_ &&
+ if (seen_send_initial_metadata_ &&
!retry_state->started_send_initial_metadata &&
- !pending_send_initial_metadata_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ !pending_send_initial_metadata_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: replaying previously completed "
"send_initial_metadata op",
- chand, this);
+ chand, this);
}
- replay_batch_data =
- SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
- AddRetriableSendInitialMetadataOp(retry_state, replay_batch_data);
+ replay_batch_data =
+ SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
+ AddRetriableSendInitialMetadataOp(retry_state, replay_batch_data);
}
// send_message.
// Note that we can only have one send_message op in flight at a time.
- if (retry_state->started_send_message_count < send_messages_.size() &&
+ if (retry_state->started_send_message_count < send_messages_.size() &&
retry_state->started_send_message_count ==
retry_state->completed_send_message_count &&
- !pending_send_message_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ !pending_send_message_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: replaying previously completed "
"send_message op",
- chand, this);
+ chand, this);
}
if (replay_batch_data == nullptr) {
replay_batch_data =
- SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
+ SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
}
- AddRetriableSendMessageOp(elem, retry_state, replay_batch_data);
+ AddRetriableSendMessageOp(elem, retry_state, replay_batch_data);
}
// send_trailing_metadata.
// Note that we only add this op if we have no more send_message ops
// to start, since we can't send down any more send_message ops after
// send_trailing_metadata.
- if (seen_send_trailing_metadata_ &&
- retry_state->started_send_message_count == send_messages_.size() &&
+ if (seen_send_trailing_metadata_ &&
+ retry_state->started_send_message_count == send_messages_.size() &&
!retry_state->started_send_trailing_metadata &&
- !pending_send_trailing_metadata_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ !pending_send_trailing_metadata_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: replaying previously completed "
"send_trailing_metadata op",
- chand, this);
+ chand, this);
}
if (replay_batch_data == nullptr) {
replay_batch_data =
- SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
+ SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
}
- AddRetriableSendTrailingMetadataOp(retry_state, replay_batch_data);
+ AddRetriableSendTrailingMetadataOp(retry_state, replay_batch_data);
}
return replay_batch_data;
}
-void CallData::AddSubchannelBatchesForPendingBatches(
- grpc_call_element* elem, SubchannelCallRetryState* retry_state,
- CallCombinerClosureList* closures) {
- for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
- PendingBatch* pending = &pending_batches_[i];
+void CallData::AddSubchannelBatchesForPendingBatches(
+ grpc_call_element* elem, SubchannelCallRetryState* retry_state,
+ CallCombinerClosureList* closures) {
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) {
+ PendingBatch* pending = &pending_batches_[i];
grpc_transport_stream_op_batch* batch = pending->batch;
if (batch == nullptr) continue;
// Skip any batch that either (a) has already been started on this
@@ -3689,7 +3689,7 @@ void CallData::AddSubchannelBatchesForPendingBatches(
// send_message ops after send_trailing_metadata.
if (batch->send_trailing_metadata &&
(retry_state->started_send_message_count + batch->send_message <
- send_messages_.size() ||
+ send_messages_.size() ||
retry_state->started_send_trailing_metadata)) {
continue;
}
@@ -3704,7 +3704,7 @@ void CallData::AddSubchannelBatchesForPendingBatches(
if (batch->recv_trailing_metadata &&
retry_state->started_recv_trailing_metadata) {
// If we previously completed a recv_trailing_metadata op
- // initiated by StartInternalRecvTrailingMetadata(), use the
+ // initiated by StartInternalRecvTrailingMetadata(), use the
// result of that instead of trying to re-start this op.
if (GPR_UNLIKELY((retry_state->recv_trailing_metadata_internal_batch !=
nullptr))) {
@@ -3720,19 +3720,19 @@ void CallData::AddSubchannelBatchesForPendingBatches(
"re-executing recv_trailing_metadata_ready to propagate "
"internally triggered result");
} else {
- retry_state->recv_trailing_metadata_internal_batch->Unref();
+ retry_state->recv_trailing_metadata_internal_batch->Unref();
}
retry_state->recv_trailing_metadata_internal_batch = nullptr;
}
continue;
}
// If we're not retrying, just send the batch as-is.
- if (method_params_ == nullptr ||
- method_params_->retry_policy() == nullptr || retry_committed_) {
- // TODO(roth) : We should probably call
- // MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy here.
- AddClosureForSubchannelBatch(elem, batch, closures);
- PendingBatchClear(pending);
+ if (method_params_ == nullptr ||
+ method_params_->retry_policy() == nullptr || retry_committed_) {
+ // TODO(roth) : We should probably call
+ // MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy here.
+ AddClosureForSubchannelBatch(elem, batch, closures);
+ PendingBatchClear(pending);
continue;
}
// Create batch with the right number of callbacks.
@@ -3742,215 +3742,215 @@ void CallData::AddSubchannelBatchesForPendingBatches(
const int num_callbacks = has_send_ops + batch->recv_initial_metadata +
batch->recv_message +
batch->recv_trailing_metadata;
- SubchannelCallBatchData* batch_data = SubchannelCallBatchData::Create(
+ SubchannelCallBatchData* batch_data = SubchannelCallBatchData::Create(
elem, num_callbacks, has_send_ops /* set_on_complete */);
// Cache send ops if needed.
- MaybeCacheSendOpsForBatch(pending);
+ MaybeCacheSendOpsForBatch(pending);
// send_initial_metadata.
if (batch->send_initial_metadata) {
- AddRetriableSendInitialMetadataOp(retry_state, batch_data);
+ AddRetriableSendInitialMetadataOp(retry_state, batch_data);
}
// send_message.
if (batch->send_message) {
- AddRetriableSendMessageOp(elem, retry_state, batch_data);
+ AddRetriableSendMessageOp(elem, retry_state, batch_data);
}
// send_trailing_metadata.
if (batch->send_trailing_metadata) {
- AddRetriableSendTrailingMetadataOp(retry_state, batch_data);
+ AddRetriableSendTrailingMetadataOp(retry_state, batch_data);
}
// recv_initial_metadata.
if (batch->recv_initial_metadata) {
// recv_flags is only used on the server side.
GPR_ASSERT(batch->payload->recv_initial_metadata.recv_flags == nullptr);
- AddRetriableRecvInitialMetadataOp(retry_state, batch_data);
+ AddRetriableRecvInitialMetadataOp(retry_state, batch_data);
}
// recv_message.
if (batch->recv_message) {
- AddRetriableRecvMessageOp(retry_state, batch_data);
+ AddRetriableRecvMessageOp(retry_state, batch_data);
}
// recv_trailing_metadata.
if (batch->recv_trailing_metadata) {
- AddRetriableRecvTrailingMetadataOp(retry_state, batch_data);
+ AddRetriableRecvTrailingMetadataOp(retry_state, batch_data);
}
- AddClosureForSubchannelBatch(elem, &batch_data->batch, closures);
+ AddClosureForSubchannelBatch(elem, &batch_data->batch, closures);
// Track number of pending subchannel send batches.
// If this is the first one, take a ref to the call stack.
if (batch->send_initial_metadata || batch->send_message ||
batch->send_trailing_metadata) {
- if (num_pending_retriable_subchannel_send_batches_ == 0) {
- GRPC_CALL_STACK_REF(owning_call_, "subchannel_send_batches");
+ if (num_pending_retriable_subchannel_send_batches_ == 0) {
+ GRPC_CALL_STACK_REF(owning_call_, "subchannel_send_batches");
}
- ++num_pending_retriable_subchannel_send_batches_;
+ ++num_pending_retriable_subchannel_send_batches_;
}
}
}
-void CallData::StartRetriableSubchannelBatches(void* arg,
- grpc_error* /*ignored*/) {
+void CallData::StartRetriableSubchannelBatches(void* arg,
+ grpc_error* /*ignored*/) {
grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: constructing retriable batches",
chand, calld);
}
- SubchannelCallRetryState* retry_state =
- static_cast<SubchannelCallRetryState*>(
- calld->subchannel_call_->GetParentData());
+ SubchannelCallRetryState* retry_state =
+ static_cast<SubchannelCallRetryState*>(
+ calld->subchannel_call_->GetParentData());
// Construct list of closures to execute, one for each pending batch.
- CallCombinerClosureList closures;
+ CallCombinerClosureList closures;
// Replay previously-returned send_* ops if needed.
- SubchannelCallBatchData* replay_batch_data =
- calld->MaybeCreateSubchannelBatchForReplay(elem, retry_state);
+ SubchannelCallBatchData* replay_batch_data =
+ calld->MaybeCreateSubchannelBatchForReplay(elem, retry_state);
if (replay_batch_data != nullptr) {
- calld->AddClosureForSubchannelBatch(elem, &replay_batch_data->batch,
- &closures);
+ calld->AddClosureForSubchannelBatch(elem, &replay_batch_data->batch,
+ &closures);
// Track number of pending subchannel send batches.
// If this is the first one, take a ref to the call stack.
- if (calld->num_pending_retriable_subchannel_send_batches_ == 0) {
- GRPC_CALL_STACK_REF(calld->owning_call_, "subchannel_send_batches");
+ if (calld->num_pending_retriable_subchannel_send_batches_ == 0) {
+ GRPC_CALL_STACK_REF(calld->owning_call_, "subchannel_send_batches");
}
- ++calld->num_pending_retriable_subchannel_send_batches_;
+ ++calld->num_pending_retriable_subchannel_send_batches_;
}
// Now add pending batches.
- calld->AddSubchannelBatchesForPendingBatches(elem, retry_state, &closures);
+ calld->AddSubchannelBatchesForPendingBatches(elem, retry_state, &closures);
// Start batches on subchannel call.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
gpr_log(GPR_INFO,
"chand=%p calld=%p: starting %" PRIuPTR
" retriable batches on subchannel_call=%p",
- chand, calld, closures.size(), calld->subchannel_call_.get());
+ chand, calld, closures.size(), calld->subchannel_call_.get());
}
// Note: This will yield the call combiner.
- closures.RunClosures(calld->call_combiner_);
+ closures.RunClosures(calld->call_combiner_);
}
//
// LB pick
//
-void CallData::CreateSubchannelCall(grpc_call_element* elem) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+void CallData::CreateSubchannelCall(grpc_call_element* elem) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
const size_t parent_data_size =
- enable_retries_ ? sizeof(SubchannelCallRetryState) : 0;
- SubchannelCall::Args call_args = {
- std::move(connected_subchannel_), pollent_, path_, call_start_time_,
- deadline_, arena_,
- // TODO(roth): When we implement hedging support, we will probably
- // need to use a separate call context for each subchannel call.
- call_context_, call_combiner_, parent_data_size};
- grpc_error* error = GRPC_ERROR_NONE;
- subchannel_call_ = SubchannelCall::Create(std::move(call_args), &error);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ enable_retries_ ? sizeof(SubchannelCallRetryState) : 0;
+ SubchannelCall::Args call_args = {
+ std::move(connected_subchannel_), pollent_, path_, call_start_time_,
+ deadline_, arena_,
+ // TODO(roth): When we implement hedging support, we will probably
+ // need to use a separate call context for each subchannel call.
+ call_context_, call_combiner_, parent_data_size};
+ grpc_error* error = GRPC_ERROR_NONE;
+ subchannel_call_ = SubchannelCall::Create(std::move(call_args), &error);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: create subchannel_call=%p: error=%s",
- chand, this, subchannel_call_.get(), grpc_error_string(error));
+ chand, this, subchannel_call_.get(), grpc_error_string(error));
}
- if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
- PendingBatchesFail(elem, error, YieldCallCombiner);
+ if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
+ PendingBatchesFail(elem, error, YieldCallCombiner);
} else {
if (parent_data_size > 0) {
- new (subchannel_call_->GetParentData())
- SubchannelCallRetryState(call_context_);
+ new (subchannel_call_->GetParentData())
+ SubchannelCallRetryState(call_context_);
}
- PendingBatchesResume(elem);
+ PendingBatchesResume(elem);
}
}
-void CallData::AsyncPickDone(grpc_call_element* elem, grpc_error* error) {
- GRPC_CLOSURE_INIT(&pick_closure_, PickDone, elem, grpc_schedule_on_exec_ctx);
- ExecCtx::Run(DEBUG_LOCATION, &pick_closure_, error);
-}
-
-void CallData::PickDone(void* arg, grpc_error* error) {
+void CallData::AsyncPickDone(grpc_call_element* elem, grpc_error* error) {
+ GRPC_CLOSURE_INIT(&pick_closure_, PickDone, elem, grpc_schedule_on_exec_ctx);
+ ExecCtx::Run(DEBUG_LOCATION, &pick_closure_, error);
+}
+
+void CallData::PickDone(void* arg, grpc_error* error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (error != GRPC_ERROR_NONE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: failed to pick subchannel: error=%s", chand,
- calld, grpc_error_string(error));
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (error != GRPC_ERROR_NONE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: failed to pick subchannel: error=%s", chand,
+ calld, grpc_error_string(error));
}
- calld->PendingBatchesFail(elem, GRPC_ERROR_REF(error), YieldCallCombiner);
- return;
+ calld->PendingBatchesFail(elem, GRPC_ERROR_REF(error), YieldCallCombiner);
+ return;
}
- calld->CreateSubchannelCall(elem);
+ calld->CreateSubchannelCall(elem);
}
-// A class to handle the call combiner cancellation callback for a
-// queued pick.
-class CallData::QueuedPickCanceller {
- public:
- explicit QueuedPickCanceller(grpc_call_element* elem) : elem_(elem) {
- auto* calld = static_cast<CallData*>(elem->call_data);
- GRPC_CALL_STACK_REF(calld->owning_call_, "QueuedPickCanceller");
- GRPC_CLOSURE_INIT(&closure_, &CancelLocked, this,
- grpc_schedule_on_exec_ctx);
- calld->call_combiner_->SetNotifyOnCancel(&closure_);
- }
-
- private:
- static void CancelLocked(void* arg, grpc_error* error) {
- auto* self = static_cast<QueuedPickCanceller*>(arg);
- auto* chand = static_cast<ChannelData*>(self->elem_->channel_data);
- auto* calld = static_cast<CallData*>(self->elem_->call_data);
- MutexLock lock(chand->data_plane_mu());
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: cancelling queued pick: "
- "error=%s self=%p calld->pick_canceller=%p",
- chand, calld, grpc_error_string(error), self,
- calld->pick_canceller_);
- }
- if (calld->pick_canceller_ == self && error != GRPC_ERROR_NONE) {
- // Remove pick from list of queued picks.
+// A class to handle the call combiner cancellation callback for a
+// queued pick.
+class CallData::QueuedPickCanceller {
+ public:
+ explicit QueuedPickCanceller(grpc_call_element* elem) : elem_(elem) {
+ auto* calld = static_cast<CallData*>(elem->call_data);
+ GRPC_CALL_STACK_REF(calld->owning_call_, "QueuedPickCanceller");
+ GRPC_CLOSURE_INIT(&closure_, &CancelLocked, this,
+ grpc_schedule_on_exec_ctx);
+ calld->call_combiner_->SetNotifyOnCancel(&closure_);
+ }
+
+ private:
+ static void CancelLocked(void* arg, grpc_error* error) {
+ auto* self = static_cast<QueuedPickCanceller*>(arg);
+ auto* chand = static_cast<ChannelData*>(self->elem_->channel_data);
+ auto* calld = static_cast<CallData*>(self->elem_->call_data);
+ MutexLock lock(chand->data_plane_mu());
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: cancelling queued pick: "
+ "error=%s self=%p calld->pick_canceller=%p",
+ chand, calld, grpc_error_string(error), self,
+ calld->pick_canceller_);
+ }
+ if (calld->pick_canceller_ == self && error != GRPC_ERROR_NONE) {
+ // Remove pick from list of queued picks.
calld->MaybeInvokeConfigSelectorCommitCallback();
calld->MaybeRemoveCallFromQueuedPicksLocked(self->elem_);
- // Fail pending batches on the call.
- calld->PendingBatchesFail(self->elem_, GRPC_ERROR_REF(error),
- YieldCallCombinerIfPendingBatchesFound);
- }
- GRPC_CALL_STACK_UNREF(calld->owning_call_, "QueuedPickCanceller");
- delete self;
- }
-
- grpc_call_element* elem_;
- grpc_closure closure_;
-};
-
+ // Fail pending batches on the call.
+ calld->PendingBatchesFail(self->elem_, GRPC_ERROR_REF(error),
+ YieldCallCombinerIfPendingBatchesFound);
+ }
+ GRPC_CALL_STACK_UNREF(calld->owning_call_, "QueuedPickCanceller");
+ delete self;
+ }
+
+ grpc_call_element* elem_;
+ grpc_closure closure_;
+};
+
void CallData::MaybeRemoveCallFromQueuedPicksLocked(grpc_call_element* elem) {
if (!pick_queued_) return;
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: removing from queued picks list",
- chand, this);
- }
- chand->RemoveQueuedPick(&pick_, pollent_);
- pick_queued_ = false;
- // Lame the call combiner canceller.
- pick_canceller_ = nullptr;
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: removing from queued picks list",
+ chand, this);
+ }
+ chand->RemoveQueuedPick(&pick_, pollent_);
+ pick_queued_ = false;
+ // Lame the call combiner canceller.
+ pick_canceller_ = nullptr;
}
void CallData::MaybeAddCallToQueuedPicksLocked(grpc_call_element* elem) {
if (pick_queued_) return;
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: adding to queued picks list", chand,
- this);
- }
- pick_queued_ = true;
- pick_.elem = elem;
- chand->AddQueuedPick(&pick_, pollent_);
- // Register call combiner cancellation callback.
- pick_canceller_ = new QueuedPickCanceller(elem);
-}
-
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO, "chand=%p calld=%p: adding to queued picks list", chand,
+ this);
+ }
+ pick_queued_ = true;
+ pick_.elem = elem;
+ chand->AddQueuedPick(&pick_, pollent_);
+ // Register call combiner cancellation callback.
+ pick_canceller_ = new QueuedPickCanceller(elem);
+}
+
grpc_error* CallData::ApplyServiceConfigToCallLocked(
grpc_call_element* elem, grpc_metadata_batch* initial_metadata) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
gpr_log(GPR_INFO, "chand=%p calld=%p: applying service config to call",
- chand, this);
+ chand, this);
}
ConfigSelector* config_selector = chand->config_selector();
if (config_selector != nullptr) {
@@ -3969,9 +3969,9 @@ grpc_error* CallData::ApplyServiceConfigToCallLocked(
std::move(call_config.service_config), call_config.method_configs,
call_context_);
// Apply our own method params to the call.
- method_params_ = static_cast<ClientChannelMethodParsedConfig*>(
+ method_params_ = static_cast<ClientChannelMethodParsedConfig*>(
service_config_call_data->GetMethodParsedConfig(
- internal::ClientChannelServiceConfigParser::ParserIndex()));
+ internal::ClientChannelServiceConfigParser::ParserIndex()));
if (method_params_ != nullptr) {
// If the deadline from the service config is shorter than the one
// from the client API, reset the deadline timer.
@@ -4006,8 +4006,8 @@ grpc_error* CallData::ApplyServiceConfigToCallLocked(
}
// If no retry policy, disable retries.
// TODO(roth): Remove this when adding support for transparent retries.
- if (method_params_ == nullptr || method_params_->retry_policy() == nullptr) {
- enable_retries_ = false;
+ if (method_params_ == nullptr || method_params_->retry_policy() == nullptr) {
+ enable_retries_ = false;
}
return GRPC_ERROR_NONE;
}
@@ -4019,42 +4019,42 @@ void CallData::MaybeInvokeConfigSelectorCommitCallback() {
}
}
-const char* PickResultTypeName(
- LoadBalancingPolicy::PickResult::ResultType type) {
- switch (type) {
- case LoadBalancingPolicy::PickResult::PICK_COMPLETE:
- return "COMPLETE";
- case LoadBalancingPolicy::PickResult::PICK_QUEUE:
- return "QUEUE";
- case LoadBalancingPolicy::PickResult::PICK_FAILED:
- return "FAILED";
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
-
-void CallData::PickSubchannel(void* arg, grpc_error* error) {
+const char* PickResultTypeName(
+ LoadBalancingPolicy::PickResult::ResultType type) {
+ switch (type) {
+ case LoadBalancingPolicy::PickResult::PICK_COMPLETE:
+ return "COMPLETE";
+ case LoadBalancingPolicy::PickResult::PICK_QUEUE:
+ return "QUEUE";
+ case LoadBalancingPolicy::PickResult::PICK_FAILED:
+ return "FAILED";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
+void CallData::PickSubchannel(void* arg, grpc_error* error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- CallData* calld = static_cast<CallData*>(elem->call_data);
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- bool pick_complete;
- {
- MutexLock lock(chand->data_plane_mu());
- pick_complete = calld->PickSubchannelLocked(elem, &error);
- }
- if (pick_complete) {
- PickDone(elem, error);
- GRPC_ERROR_UNREF(error);
- }
-}
-
-bool CallData::PickSubchannelLocked(grpc_call_element* elem,
- grpc_error** error) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- GPR_ASSERT(connected_subchannel_ == nullptr);
- GPR_ASSERT(subchannel_call_ == nullptr);
- // The picker being null means that the channel is currently in IDLE state.
- // The incoming call will make the channel exit IDLE.
- if (chand->picker() == nullptr) {
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ bool pick_complete;
+ {
+ MutexLock lock(chand->data_plane_mu());
+ pick_complete = calld->PickSubchannelLocked(elem, &error);
+ }
+ if (pick_complete) {
+ PickDone(elem, error);
+ GRPC_ERROR_UNREF(error);
+ }
+}
+
+bool CallData::PickSubchannelLocked(grpc_call_element* elem,
+ grpc_error** error) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ GPR_ASSERT(connected_subchannel_ == nullptr);
+ GPR_ASSERT(subchannel_call_ == nullptr);
+ // The picker being null means that the channel is currently in IDLE state.
+ // The incoming call will make the channel exit IDLE.
+ if (chand->picker() == nullptr) {
GRPC_CHANNEL_STACK_REF(chand->owning_stack(), "PickSubchannelLocked");
// Bounce into the control plane work serializer to exit IDLE. Since we are
// holding on to the data plane mutex here, we offload it on the ExecCtx so
@@ -4074,11 +4074,11 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem,
},
chand, nullptr),
GRPC_ERROR_NONE);
- // Queue the pick, so that it will be attempted once the channel
- // becomes connected.
+ // Queue the pick, so that it will be attempted once the channel
+ // becomes connected.
MaybeAddCallToQueuedPicksLocked(elem);
- return false;
- }
+ return false;
+ }
grpc_metadata_batch* initial_metadata_batch =
seen_send_initial_metadata_
? &send_initial_metadata_
@@ -4118,161 +4118,161 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem,
// If this is a retry, use the send_initial_metadata payload that
// we've cached; otherwise, use the pending batch. The
// send_initial_metadata batch will be the first pending batch in the
- // list, as set by GetBatchIndex() above.
+ // list, as set by GetBatchIndex() above.
// TODO(roth): What if the LB policy needs to add something to the
// call's initial metadata, and then there's a retry? We don't want
// the new metadata to be added twice. We might need to somehow
// allocate the subchannel batch earlier so that we can give the
// subchannel's copy of the metadata batch (which is copied for each
// attempt) to the LB policy instead the one from the parent channel.
- LoadBalancingPolicy::PickArgs pick_args;
+ LoadBalancingPolicy::PickArgs pick_args;
pick_args.path = StringViewFromSlice(path_);
- pick_args.call_state = &lb_call_state_;
+ pick_args.call_state = &lb_call_state_;
Metadata initial_metadata(this, initial_metadata_batch);
- pick_args.initial_metadata = &initial_metadata;
- // Attempt pick.
- auto result = chand->picker()->Pick(pick_args);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: LB pick returned %s (subchannel=%p, error=%s)",
- chand, this, PickResultTypeName(result.type),
- result.subchannel.get(), grpc_error_string(result.error));
- }
- switch (result.type) {
- case LoadBalancingPolicy::PickResult::PICK_FAILED: {
- // If we're shutting down, fail all RPCs.
- grpc_error* disconnect_error = chand->disconnect_error();
- if (disconnect_error != GRPC_ERROR_NONE) {
- GRPC_ERROR_UNREF(result.error);
+ pick_args.initial_metadata = &initial_metadata;
+ // Attempt pick.
+ auto result = chand->picker()->Pick(pick_args);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_routing_trace)) {
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: LB pick returned %s (subchannel=%p, error=%s)",
+ chand, this, PickResultTypeName(result.type),
+ result.subchannel.get(), grpc_error_string(result.error));
+ }
+ switch (result.type) {
+ case LoadBalancingPolicy::PickResult::PICK_FAILED: {
+ // If we're shutting down, fail all RPCs.
+ grpc_error* disconnect_error = chand->disconnect_error();
+ if (disconnect_error != GRPC_ERROR_NONE) {
+ GRPC_ERROR_UNREF(result.error);
MaybeRemoveCallFromQueuedPicksLocked(elem);
MaybeInvokeConfigSelectorCommitCallback();
- *error = GRPC_ERROR_REF(disconnect_error);
- return true;
- }
- // If wait_for_ready is false, then the error indicates the RPC
- // attempt's final status.
- if ((send_initial_metadata_flags &
- GRPC_INITIAL_METADATA_WAIT_FOR_READY) == 0) {
- // Retry if appropriate; otherwise, fail.
- grpc_status_code status = GRPC_STATUS_OK;
- grpc_error_get_status(result.error, deadline_, &status, nullptr,
- nullptr, nullptr);
- const bool retried = enable_retries_ &&
- MaybeRetry(elem, nullptr /* batch_data */, status,
- nullptr /* server_pushback_md */);
- if (!retried) {
- grpc_error* new_error =
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed to pick subchannel", &result.error, 1);
- GRPC_ERROR_UNREF(result.error);
- *error = new_error;
+ *error = GRPC_ERROR_REF(disconnect_error);
+ return true;
+ }
+ // If wait_for_ready is false, then the error indicates the RPC
+ // attempt's final status.
+ if ((send_initial_metadata_flags &
+ GRPC_INITIAL_METADATA_WAIT_FOR_READY) == 0) {
+ // Retry if appropriate; otherwise, fail.
+ grpc_status_code status = GRPC_STATUS_OK;
+ grpc_error_get_status(result.error, deadline_, &status, nullptr,
+ nullptr, nullptr);
+ const bool retried = enable_retries_ &&
+ MaybeRetry(elem, nullptr /* batch_data */, status,
+ nullptr /* server_pushback_md */);
+ if (!retried) {
+ grpc_error* new_error =
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed to pick subchannel", &result.error, 1);
+ GRPC_ERROR_UNREF(result.error);
+ *error = new_error;
MaybeInvokeConfigSelectorCommitCallback();
- }
+ }
MaybeRemoveCallFromQueuedPicksLocked(elem);
- return !retried;
- }
- // If wait_for_ready is true, then queue to retry when we get a new
- // picker.
- GRPC_ERROR_UNREF(result.error);
+ return !retried;
+ }
+ // If wait_for_ready is true, then queue to retry when we get a new
+ // picker.
+ GRPC_ERROR_UNREF(result.error);
}
- // Fallthrough
- case LoadBalancingPolicy::PickResult::PICK_QUEUE:
+ // Fallthrough
+ case LoadBalancingPolicy::PickResult::PICK_QUEUE:
MaybeAddCallToQueuedPicksLocked(elem);
- return false;
- default: // PICK_COMPLETE
+ return false;
+ default: // PICK_COMPLETE
MaybeRemoveCallFromQueuedPicksLocked(elem);
- // Handle drops.
- if (GPR_UNLIKELY(result.subchannel == nullptr)) {
+ // Handle drops.
+ if (GPR_UNLIKELY(result.subchannel == nullptr)) {
result.error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Call dropped by load balancing policy"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
MaybeInvokeConfigSelectorCommitCallback();
- } else {
- // Grab a ref to the connected subchannel while we're still
- // holding the data plane mutex.
- connected_subchannel_ =
- chand->GetConnectedSubchannelInDataPlane(result.subchannel.get());
- GPR_ASSERT(connected_subchannel_ != nullptr);
+ } else {
+ // Grab a ref to the connected subchannel while we're still
+ // holding the data plane mutex.
+ connected_subchannel_ =
+ chand->GetConnectedSubchannelInDataPlane(result.subchannel.get());
+ GPR_ASSERT(connected_subchannel_ != nullptr);
if (!enable_retries_ || retry_committed_) {
MaybeInvokeConfigSelectorCommitCallback();
}
- }
- lb_recv_trailing_metadata_ready_ = result.recv_trailing_metadata_ready;
- *error = result.error;
- return true;
+ }
+ lb_recv_trailing_metadata_ready_ = result.recv_trailing_metadata_ready;
+ *error = result.error;
+ return true;
}
}
-} // namespace
-} // namespace grpc_core
+} // namespace
+} // namespace grpc_core
/*************************************************************************
* EXPORTED SYMBOLS
*/
-using grpc_core::CallData;
-using grpc_core::ChannelData;
-
+using grpc_core::CallData;
+using grpc_core::ChannelData;
+
const grpc_channel_filter grpc_client_channel_filter = {
- CallData::StartTransportStreamOpBatch,
- ChannelData::StartTransportOp,
- sizeof(CallData),
- CallData::Init,
- CallData::SetPollent,
- CallData::Destroy,
- sizeof(ChannelData),
- ChannelData::Init,
- ChannelData::Destroy,
- ChannelData::GetChannelInfo,
+ CallData::StartTransportStreamOpBatch,
+ ChannelData::StartTransportOp,
+ sizeof(CallData),
+ CallData::Init,
+ CallData::SetPollent,
+ CallData::Destroy,
+ sizeof(ChannelData),
+ ChannelData::Init,
+ ChannelData::Destroy,
+ ChannelData::GetChannelInfo,
"client-channel",
};
grpc_connectivity_state grpc_client_channel_check_connectivity_state(
grpc_channel_element* elem, int try_to_connect) {
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- return chand->CheckConnectivityState(try_to_connect);
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ return chand->CheckConnectivityState(try_to_connect);
}
-int grpc_client_channel_num_external_connectivity_watchers(
- grpc_channel_element* elem) {
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- return chand->NumExternalConnectivityWatchers();
+int grpc_client_channel_num_external_connectivity_watchers(
+ grpc_channel_element* elem) {
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ return chand->NumExternalConnectivityWatchers();
}
-void grpc_client_channel_watch_connectivity_state(
- grpc_channel_element* elem, grpc_polling_entity pollent,
- grpc_connectivity_state* state, grpc_closure* closure,
- grpc_closure* watcher_timer_init) {
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- if (state == nullptr) {
- // Handle cancellation.
- GPR_ASSERT(watcher_timer_init == nullptr);
- chand->RemoveExternalConnectivityWatcher(closure, /*cancel=*/true);
+void grpc_client_channel_watch_connectivity_state(
+ grpc_channel_element* elem, grpc_polling_entity pollent,
+ grpc_connectivity_state* state, grpc_closure* closure,
+ grpc_closure* watcher_timer_init) {
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ if (state == nullptr) {
+ // Handle cancellation.
+ GPR_ASSERT(watcher_timer_init == nullptr);
+ chand->RemoveExternalConnectivityWatcher(closure, /*cancel=*/true);
return;
}
- // Handle addition.
- return chand->AddExternalConnectivityWatcher(pollent, state, closure,
- watcher_timer_init);
+ // Handle addition.
+ return chand->AddExternalConnectivityWatcher(pollent, state, closure,
+ watcher_timer_init);
}
-void grpc_client_channel_start_connectivity_watch(
- grpc_channel_element* elem, grpc_connectivity_state initial_state,
- grpc_core::OrphanablePtr<grpc_core::AsyncConnectivityStateWatcherInterface>
- watcher) {
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->AddConnectivityWatcher(initial_state, std::move(watcher));
+void grpc_client_channel_start_connectivity_watch(
+ grpc_channel_element* elem, grpc_connectivity_state initial_state,
+ grpc_core::OrphanablePtr<grpc_core::AsyncConnectivityStateWatcherInterface>
+ watcher) {
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->AddConnectivityWatcher(initial_state, std::move(watcher));
}
-void grpc_client_channel_stop_connectivity_watch(
- grpc_channel_element* elem,
- grpc_core::AsyncConnectivityStateWatcherInterface* watcher) {
- auto* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->RemoveConnectivityWatcher(watcher);
+void grpc_client_channel_stop_connectivity_watch(
+ grpc_channel_element* elem,
+ grpc_core::AsyncConnectivityStateWatcherInterface* watcher) {
+ auto* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->RemoveConnectivityWatcher(watcher);
}
grpc_core::RefCountedPtr<grpc_core::SubchannelCall>
grpc_client_channel_get_subchannel_call(grpc_call_element* elem) {
- auto* calld = static_cast<CallData*>(elem->call_data);
- return calld->subchannel_call();
+ auto* calld = static_cast<CallData*>(elem->call_data);
+ return calld->subchannel_call();
}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h
index 35c2a2af6b..d745e0cbc8 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h
@@ -46,35 +46,35 @@ grpc_connectivity_state grpc_client_channel_check_connectivity_state(
int grpc_client_channel_num_external_connectivity_watchers(
grpc_channel_element* elem);
-// Starts a one-time connectivity state watch. When the channel's state
-// becomes different from *state, sets *state to the new state and
-// schedules on_complete. The watcher_timer_init callback is invoked as
-// soon as the watch is actually started (i.e., after hopping into the
-// client channel combiner). I/O will be serviced via pollent.
-//
-// This is intended to be used when starting a watch from outside of C-core
-// via grpc_channel_watch_connectivity_state(). It should not be used
-// by other callers.
+// Starts a one-time connectivity state watch. When the channel's state
+// becomes different from *state, sets *state to the new state and
+// schedules on_complete. The watcher_timer_init callback is invoked as
+// soon as the watch is actually started (i.e., after hopping into the
+// client channel combiner). I/O will be serviced via pollent.
+//
+// This is intended to be used when starting a watch from outside of C-core
+// via grpc_channel_watch_connectivity_state(). It should not be used
+// by other callers.
void grpc_client_channel_watch_connectivity_state(
grpc_channel_element* elem, grpc_polling_entity pollent,
grpc_connectivity_state* state, grpc_closure* on_complete,
grpc_closure* watcher_timer_init);
-// Starts and stops a connectivity watch. The watcher will be initially
-// notified as soon as the state changes from initial_state and then on
-// every subsequent state change until either the watch is stopped or
-// it is notified that the state has changed to SHUTDOWN.
-//
-// This is intended to be used when starting watches from code inside of
-// C-core (e.g., for a nested control plane channel for things like xds).
-void grpc_client_channel_start_connectivity_watch(
- grpc_channel_element* elem, grpc_connectivity_state initial_state,
- grpc_core::OrphanablePtr<grpc_core::AsyncConnectivityStateWatcherInterface>
- watcher);
-void grpc_client_channel_stop_connectivity_watch(
- grpc_channel_element* elem,
- grpc_core::AsyncConnectivityStateWatcherInterface* watcher);
-
+// Starts and stops a connectivity watch. The watcher will be initially
+// notified as soon as the state changes from initial_state and then on
+// every subsequent state change until either the watch is stopped or
+// it is notified that the state has changed to SHUTDOWN.
+//
+// This is intended to be used when starting watches from code inside of
+// C-core (e.g., for a nested control plane channel for things like xds).
+void grpc_client_channel_start_connectivity_watch(
+ grpc_channel_element* elem, grpc_connectivity_state initial_state,
+ grpc_core::OrphanablePtr<grpc_core::AsyncConnectivityStateWatcherInterface>
+ watcher);
+void grpc_client_channel_stop_connectivity_watch(
+ grpc_channel_element* elem,
+ grpc_core::AsyncConnectivityStateWatcherInterface* watcher);
+
/* Debug helper: pull the subchannel call from a call stack element */
grpc_core::RefCountedPtr<grpc_core::SubchannelCall>
grpc_client_channel_get_subchannel_call(grpc_call_element* elem);
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc
index a7799e449a..e557fe4f52 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc
@@ -33,26 +33,26 @@ namespace grpc_core {
namespace channelz {
SubchannelNode::SubchannelNode(TString target_address,
- size_t channel_tracer_max_nodes)
- : BaseNode(EntityType::kSubchannel, target_address),
- target_(std::move(target_address)),
- trace_(channel_tracer_max_nodes) {}
+ size_t channel_tracer_max_nodes)
+ : BaseNode(EntityType::kSubchannel, target_address),
+ target_(std::move(target_address)),
+ trace_(channel_tracer_max_nodes) {}
-SubchannelNode::~SubchannelNode() {}
+SubchannelNode::~SubchannelNode() {}
-void SubchannelNode::UpdateConnectivityState(grpc_connectivity_state state) {
- connectivity_state_.Store(state, MemoryOrder::RELAXED);
+void SubchannelNode::UpdateConnectivityState(grpc_connectivity_state state) {
+ connectivity_state_.Store(state, MemoryOrder::RELAXED);
}
-void SubchannelNode::SetChildSocket(RefCountedPtr<SocketNode> socket) {
- MutexLock lock(&socket_mu_);
- child_socket_ = std::move(socket);
+void SubchannelNode::SetChildSocket(RefCountedPtr<SocketNode> socket) {
+ MutexLock lock(&socket_mu_);
+ child_socket_ = std::move(socket);
}
Json SubchannelNode::RenderJson() {
// Create and fill the data child.
- grpc_connectivity_state state =
- connectivity_state_.Load(MemoryOrder::RELAXED);
+ grpc_connectivity_state state =
+ connectivity_state_.Load(MemoryOrder::RELAXED);
Json::Object data = {
{"state",
Json::Object{
@@ -77,12 +77,12 @@ Json SubchannelNode::RenderJson() {
{"data", std::move(data)},
};
// Populate the child socket.
- RefCountedPtr<SocketNode> child_socket;
- {
- MutexLock lock(&socket_mu_);
- child_socket = child_socket_;
- }
- if (child_socket != nullptr && child_socket->uuid() != 0) {
+ RefCountedPtr<SocketNode> child_socket;
+ {
+ MutexLock lock(&socket_mu_);
+ child_socket = child_socket_;
+ }
+ if (child_socket != nullptr && child_socket->uuid() != 0) {
object["socketRef"] = Json::Array{
Json::Object{
{"socketId", ToString(child_socket->uuid())},
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h
index cc463e26b9..05a6ddfcf3 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h
@@ -22,7 +22,7 @@
#include <grpc/support/port_platform.h>
#include <util/generic/string.h>
-
+
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channel_trace.h"
@@ -36,22 +36,22 @@ class SubchannelNode : public BaseNode {
SubchannelNode(TString target_address, size_t channel_tracer_max_nodes);
~SubchannelNode() override;
- // Sets the subchannel's connectivity state without health checking.
- void UpdateConnectivityState(grpc_connectivity_state state);
-
- // Used when the subchannel's child socket changes. This should be set when
- // the subchannel's transport is created and set to nullptr when the
- // subchannel unrefs the transport.
- void SetChildSocket(RefCountedPtr<SocketNode> socket);
+ // Sets the subchannel's connectivity state without health checking.
+ void UpdateConnectivityState(grpc_connectivity_state state);
+ // Used when the subchannel's child socket changes. This should be set when
+ // the subchannel's transport is created and set to nullptr when the
+ // subchannel unrefs the transport.
+ void SetChildSocket(RefCountedPtr<SocketNode> socket);
+
Json RenderJson() override;
// proxy methods to composed classes.
- void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
+ void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
trace_.AddTraceEvent(severity, data);
}
void AddTraceEventWithReference(ChannelTrace::Severity severity,
- const grpc_slice& data,
+ const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_channel) {
trace_.AddTraceEventWithReference(severity, data,
std::move(referenced_channel));
@@ -61,9 +61,9 @@ class SubchannelNode : public BaseNode {
void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); }
private:
- Atomic<grpc_connectivity_state> connectivity_state_{GRPC_CHANNEL_IDLE};
- Mutex socket_mu_;
- RefCountedPtr<SocketNode> child_socket_;
+ Atomic<grpc_connectivity_state> connectivity_state_{GRPC_CHANNEL_IDLE};
+ Mutex socket_mu_;
+ RefCountedPtr<SocketNode> child_socket_;
TString target_;
CallCountingHelper call_counter_;
ChannelTrace trace_;
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.cc
index c0d853ebe5..c0eab9244c 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.cc
@@ -21,35 +21,35 @@
#include "src/core/ext/filters/client_channel/client_channel_factory.h"
#include "src/core/lib/channel/channel_args.h"
-// Channel arg key for client channel factory.
-#define GRPC_ARG_CLIENT_CHANNEL_FACTORY "grpc.client_channel_factory"
+// Channel arg key for client channel factory.
+#define GRPC_ARG_CLIENT_CHANNEL_FACTORY "grpc.client_channel_factory"
-namespace grpc_core {
+namespace grpc_core {
-namespace {
+namespace {
-void* factory_arg_copy(void* f) { return f; }
-void factory_arg_destroy(void* /*f*/) {}
-int factory_arg_cmp(void* factory1, void* factory2) {
- return GPR_ICMP(factory1, factory2);
+void* factory_arg_copy(void* f) { return f; }
+void factory_arg_destroy(void* /*f*/) {}
+int factory_arg_cmp(void* factory1, void* factory2) {
+ return GPR_ICMP(factory1, factory2);
}
-const grpc_arg_pointer_vtable factory_arg_vtable = {
- factory_arg_copy, factory_arg_destroy, factory_arg_cmp};
+const grpc_arg_pointer_vtable factory_arg_vtable = {
+ factory_arg_copy, factory_arg_destroy, factory_arg_cmp};
-} // namespace
+} // namespace
-grpc_arg ClientChannelFactory::CreateChannelArg(ClientChannelFactory* factory) {
- return grpc_channel_arg_pointer_create(
- const_cast<char*>(GRPC_ARG_CLIENT_CHANNEL_FACTORY), factory,
- &factory_arg_vtable);
+grpc_arg ClientChannelFactory::CreateChannelArg(ClientChannelFactory* factory) {
+ return grpc_channel_arg_pointer_create(
+ const_cast<char*>(GRPC_ARG_CLIENT_CHANNEL_FACTORY), factory,
+ &factory_arg_vtable);
}
-ClientChannelFactory* ClientChannelFactory::GetFromChannelArgs(
- const grpc_channel_args* args) {
- const grpc_arg* arg =
- grpc_channel_args_find(args, GRPC_ARG_CLIENT_CHANNEL_FACTORY);
- if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
- return static_cast<ClientChannelFactory*>(arg->value.pointer.p);
+ClientChannelFactory* ClientChannelFactory::GetFromChannelArgs(
+ const grpc_channel_args* args) {
+ const grpc_arg* arg =
+ grpc_channel_args_find(args, GRPC_ARG_CLIENT_CHANNEL_FACTORY);
+ if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
+ return static_cast<ClientChannelFactory*>(arg->value.pointer.p);
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.h
index 79797bbc45..a3ed24bf81 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.h
@@ -25,23 +25,23 @@
#include "src/core/ext/filters/client_channel/subchannel.h"
-namespace grpc_core {
+namespace grpc_core {
-class ClientChannelFactory {
- public:
- virtual ~ClientChannelFactory() = default;
+class ClientChannelFactory {
+ public:
+ virtual ~ClientChannelFactory() = default;
- // Creates a subchannel with the specified args.
- virtual Subchannel* CreateSubchannel(const grpc_channel_args* args) = 0;
+ // Creates a subchannel with the specified args.
+ virtual Subchannel* CreateSubchannel(const grpc_channel_args* args) = 0;
- // Returns a channel arg containing the specified factory.
- static grpc_arg CreateChannelArg(ClientChannelFactory* factory);
+ // Returns a channel arg containing the specified factory.
+ static grpc_arg CreateChannelArg(ClientChannelFactory* factory);
- // Returns the factory from args, or null if not found.
- static ClientChannelFactory* GetFromChannelArgs(
- const grpc_channel_args* args);
+ // Returns the factory from args, or null if not found.
+ static ClientChannelFactory* GetFromChannelArgs(
+ const grpc_channel_args* args);
};
-} // namespace grpc_core
+} // namespace grpc_core
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc
index 2358415fc2..73d1e1823d 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc
@@ -24,7 +24,7 @@
#include <grpc/support/alloc.h>
-#include "src/core/ext/filters/client_channel/backup_poller.h"
+#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/client_channel_channelz.h"
#include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
@@ -33,7 +33,7 @@
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
-#include "src/core/ext/filters/client_channel/resolver_result_parsing.h"
+#include "src/core/ext/filters/client_channel/resolver_result_parsing.h"
#include "src/core/ext/filters/client_channel/retry_throttle.h"
#include "src/core/ext/filters/client_channel/service_config_parser.h"
#include "src/core/lib/surface/channel_init.h"
@@ -45,24 +45,24 @@ static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
void grpc_client_channel_init(void) {
grpc_core::ServiceConfigParser::Init();
- grpc_core::internal::ClientChannelServiceConfigParser::Register();
+ grpc_core::internal::ClientChannelServiceConfigParser::Register();
grpc_core::LoadBalancingPolicyRegistry::Builder::InitRegistry();
grpc_core::ResolverRegistry::Builder::InitRegistry();
grpc_core::internal::ServerRetryThrottleMap::Init();
- grpc_core::ProxyMapperRegistry::Init();
- grpc_core::RegisterHttpProxyMapper();
+ grpc_core::ProxyMapperRegistry::Init();
+ grpc_core::RegisterHttpProxyMapper();
grpc_core::GlobalSubchannelPool::Init();
grpc_channel_init_register_stage(
GRPC_CLIENT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, append_filter,
(void*)&grpc_client_channel_filter);
grpc_http_connect_register_handshaker_factory();
- grpc_client_channel_global_init_backup_polling();
+ grpc_client_channel_global_init_backup_polling();
}
void grpc_client_channel_shutdown(void) {
grpc_core::GlobalSubchannelPool::Shutdown();
grpc_channel_init_shutdown();
- grpc_core::ProxyMapperRegistry::Shutdown();
+ grpc_core::ProxyMapperRegistry::Shutdown();
grpc_core::internal::ServerRetryThrottleMap::Shutdown();
grpc_core::ResolverRegistry::Builder::ShutdownRegistry();
grpc_core::LoadBalancingPolicyRegistry::Builder::ShutdownRegistry();
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h
index 256471456e..112c8d3444 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h
@@ -22,58 +22,58 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/channel/channelz.h"
+#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/transport/transport.h"
-namespace grpc_core {
+namespace grpc_core {
-// Interface for connection-establishment functionality.
-// Each transport that supports client channels (e.g., not inproc) must
-// supply an implementation of this.
-class SubchannelConnector : public InternallyRefCounted<SubchannelConnector> {
- public:
- struct Args {
- // Set of pollsets interested in this connection.
- grpc_pollset_set* interested_parties;
- // Deadline for connection.
- grpc_millis deadline;
- // Channel args to be passed to handshakers and transport.
- const grpc_channel_args* channel_args;
- };
+// Interface for connection-establishment functionality.
+// Each transport that supports client channels (e.g., not inproc) must
+// supply an implementation of this.
+class SubchannelConnector : public InternallyRefCounted<SubchannelConnector> {
+ public:
+ struct Args {
+ // Set of pollsets interested in this connection.
+ grpc_pollset_set* interested_parties;
+ // Deadline for connection.
+ grpc_millis deadline;
+ // Channel args to be passed to handshakers and transport.
+ const grpc_channel_args* channel_args;
+ };
- struct Result {
- // The connected transport.
- grpc_transport* transport = nullptr;
- // Channel args to be passed to filters.
- const grpc_channel_args* channel_args = nullptr;
- // Channelz socket node of the connected transport, if any.
- RefCountedPtr<channelz::SocketNode> socket_node;
+ struct Result {
+ // The connected transport.
+ grpc_transport* transport = nullptr;
+ // Channel args to be passed to filters.
+ const grpc_channel_args* channel_args = nullptr;
+ // Channelz socket node of the connected transport, if any.
+ RefCountedPtr<channelz::SocketNode> socket_node;
- void Reset() {
- transport = nullptr;
- channel_args = nullptr;
- socket_node.reset();
- }
- };
+ void Reset() {
+ transport = nullptr;
+ channel_args = nullptr;
+ socket_node.reset();
+ }
+ };
- // Attempts to connect.
- // When complete, populates *result and invokes notify.
- // Only one connection attempt may be in progress at any one time.
- virtual void Connect(const Args& args, Result* result,
- grpc_closure* notify) = 0;
+ // Attempts to connect.
+ // When complete, populates *result and invokes notify.
+ // Only one connection attempt may be in progress at any one time.
+ virtual void Connect(const Args& args, Result* result,
+ grpc_closure* notify) = 0;
- // Cancels any in-flight connection attempt and shuts down the
- // connector.
- virtual void Shutdown(grpc_error* error) = 0;
+ // Cancels any in-flight connection attempt and shuts down the
+ // connector.
+ virtual void Shutdown(grpc_error* error) = 0;
- void Orphan() override {
- Shutdown(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Subchannel disconnected"));
- Unref();
- }
+ void Orphan() override {
+ Shutdown(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Subchannel disconnected"));
+ Unref();
+ }
};
-} // namespace grpc_core
+} // namespace grpc_core
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc
index 546d1c4416..ac479d77f8 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc
@@ -38,7 +38,7 @@ GlobalSubchannelPool::~GlobalSubchannelPool() {
}
void GlobalSubchannelPool::Init() {
- instance_ = new RefCountedPtr<GlobalSubchannelPool>(
+ instance_ = new RefCountedPtr<GlobalSubchannelPool>(
MakeRefCounted<GlobalSubchannelPool>());
}
@@ -48,7 +48,7 @@ void GlobalSubchannelPool::Shutdown() {
// To ensure Shutdown() was not called before.
GPR_ASSERT(*instance_ != nullptr);
instance_->reset();
- delete instance_;
+ delete instance_;
}
RefCountedPtr<GlobalSubchannelPool> GlobalSubchannelPool::instance() {
@@ -69,12 +69,12 @@ Subchannel* GlobalSubchannelPool::RegisterSubchannel(SubchannelKey* key,
// Check to see if a subchannel already exists.
c = static_cast<Subchannel*>(grpc_avl_get(old_map, key, nullptr));
if (c != nullptr) {
- // The subchannel already exists. Try to reuse it.
+ // The subchannel already exists. Try to reuse it.
c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "subchannel_register+reuse");
- if (c != nullptr) {
- GRPC_SUBCHANNEL_UNREF(constructed,
- "subchannel_register+found_existing");
- // Exit the CAS loop without modifying the shared map.
+ if (c != nullptr) {
+ GRPC_SUBCHANNEL_UNREF(constructed,
+ "subchannel_register+found_existing");
+ // Exit the CAS loop without modifying the shared map.
} else {
// Reuse of the subchannel failed, so retry CAS loop
if (attempt_count >=
@@ -100,7 +100,7 @@ Subchannel* GlobalSubchannelPool::RegisterSubchannel(SubchannelKey* key,
// Note that we should ref the old map first because grpc_avl_add() will
// unref it while we still need to access it later.
grpc_avl new_map = grpc_avl_add(
- grpc_avl_ref(old_map, nullptr), new SubchannelKey(*key),
+ grpc_avl_ref(old_map, nullptr), new SubchannelKey(*key),
GRPC_SUBCHANNEL_WEAK_REF(constructed, "subchannel_register+new"),
nullptr);
// Try to publish the change to the shared map. It may happen (but
@@ -153,7 +153,7 @@ Subchannel* GlobalSubchannelPool::FindSubchannel(SubchannelKey* key) {
grpc_avl index = grpc_avl_ref(subchannel_map_, nullptr);
gpr_mu_unlock(&mu_);
Subchannel* c = static_cast<Subchannel*>(grpc_avl_get(index, key, nullptr));
- if (c != nullptr) c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "found_from_pool");
+ if (c != nullptr) c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "found_from_pool");
grpc_avl_unref(index, nullptr);
return c;
}
@@ -162,28 +162,28 @@ RefCountedPtr<GlobalSubchannelPool>* GlobalSubchannelPool::instance_ = nullptr;
namespace {
-void sck_avl_destroy(void* p, void* /*user_data*/) {
+void sck_avl_destroy(void* p, void* /*user_data*/) {
SubchannelKey* key = static_cast<SubchannelKey*>(p);
- delete key;
+ delete key;
}
-void* sck_avl_copy(void* p, void* /*unused*/) {
+void* sck_avl_copy(void* p, void* /*unused*/) {
const SubchannelKey* key = static_cast<const SubchannelKey*>(p);
- auto* new_key = new SubchannelKey(*key);
+ auto* new_key = new SubchannelKey(*key);
return static_cast<void*>(new_key);
}
-long sck_avl_compare(void* a, void* b, void* /*unused*/) {
+long sck_avl_compare(void* a, void* b, void* /*unused*/) {
const SubchannelKey* key_a = static_cast<const SubchannelKey*>(a);
const SubchannelKey* key_b = static_cast<const SubchannelKey*>(b);
return key_a->Cmp(*key_b);
}
-void scv_avl_destroy(void* p, void* /*user_data*/) {
+void scv_avl_destroy(void* p, void* /*user_data*/) {
GRPC_SUBCHANNEL_WEAK_UNREF((Subchannel*)p, "global_subchannel_pool");
}
-void* scv_avl_copy(void* p, void* /*unused*/) {
+void* scv_avl_copy(void* p, void* /*unused*/) {
GRPC_SUBCHANNEL_WEAK_REF((Subchannel*)p, "global_subchannel_pool");
return p;
}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc
index 7995185c13..629448403e 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc
@@ -26,11 +26,11 @@
#include "upb/upb.hpp"
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/transport/error_utils.h"
#include "src/core/lib/transport/status_metadata.h"
-#include "src/proto/grpc/health/v1/health.upb.h"
+#include "src/proto/grpc/health/v1/health.upb.h"
#define HEALTH_CHECK_INITIAL_CONNECT_BACKOFF_SECONDS 1
#define HEALTH_CHECK_RECONNECT_BACKOFF_MULTIPLIER 1.6
@@ -39,8 +39,8 @@
namespace grpc_core {
-TraceFlag grpc_health_check_client_trace(false, "health_check_client");
-
+TraceFlag grpc_health_check_client_trace(false, "health_check_client");
+
//
// HealthCheckClient
//
@@ -49,14 +49,14 @@ HealthCheckClient::HealthCheckClient(
const char* service_name,
RefCountedPtr<ConnectedSubchannel> connected_subchannel,
grpc_pollset_set* interested_parties,
- RefCountedPtr<channelz::SubchannelNode> channelz_node,
- RefCountedPtr<ConnectivityStateWatcherInterface> watcher)
+ RefCountedPtr<channelz::SubchannelNode> channelz_node,
+ RefCountedPtr<ConnectivityStateWatcherInterface> watcher)
: InternallyRefCounted<HealthCheckClient>(&grpc_health_check_client_trace),
service_name_(service_name),
connected_subchannel_(std::move(connected_subchannel)),
interested_parties_(interested_parties),
channelz_node_(std::move(channelz_node)),
- watcher_(std::move(watcher)),
+ watcher_(std::move(watcher)),
retry_backoff_(
BackOff::Options()
.set_initial_backoff(
@@ -65,7 +65,7 @@ HealthCheckClient::HealthCheckClient(
.set_jitter(HEALTH_CHECK_RECONNECT_JITTER)
.set_max_backoff(HEALTH_CHECK_RECONNECT_MAX_BACKOFF_SECONDS *
1000)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "created HealthCheckClient %p", this);
}
GRPC_CLOSURE_INIT(&retry_timer_callback_, OnRetryTimer, this,
@@ -74,22 +74,22 @@ HealthCheckClient::HealthCheckClient(
}
HealthCheckClient::~HealthCheckClient() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "destroying HealthCheckClient %p", this);
}
}
void HealthCheckClient::SetHealthStatus(grpc_connectivity_state state,
- const char* reason) {
+ const char* reason) {
MutexLock lock(&mu_);
- SetHealthStatusLocked(state, reason);
+ SetHealthStatusLocked(state, reason);
}
void HealthCheckClient::SetHealthStatusLocked(grpc_connectivity_state state,
- const char* reason) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
- gpr_log(GPR_INFO, "HealthCheckClient %p: setting state=%s reason=%s", this,
- ConnectivityStateName(state), reason);
+ const char* reason) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ gpr_log(GPR_INFO, "HealthCheckClient %p: setting state=%s reason=%s", this,
+ ConnectivityStateName(state), reason);
}
if (watcher_ != nullptr) {
watcher_->Notify(state,
@@ -100,13 +100,13 @@ void HealthCheckClient::SetHealthStatusLocked(grpc_connectivity_state state,
}
void HealthCheckClient::Orphan() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: shutting down", this);
}
{
MutexLock lock(&mu_);
shutting_down_ = true;
- watcher_.reset();
+ watcher_.reset();
call_state_.reset();
if (retry_timer_callback_pending_) {
grpc_timer_cancel(&retry_timer_);
@@ -123,9 +123,9 @@ void HealthCheckClient::StartCall() {
void HealthCheckClient::StartCallLocked() {
if (shutting_down_) return;
GPR_ASSERT(call_state_ == nullptr);
- SetHealthStatusLocked(GRPC_CHANNEL_CONNECTING, "starting health watch");
+ SetHealthStatusLocked(GRPC_CHANNEL_CONNECTING, "starting health watch");
call_state_ = MakeOrphanable<CallState>(Ref(), interested_parties_);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: created CallState %p", this,
call_state_.get());
}
@@ -133,10 +133,10 @@ void HealthCheckClient::StartCallLocked() {
}
void HealthCheckClient::StartRetryTimerLocked() {
- SetHealthStatusLocked(GRPC_CHANNEL_TRANSIENT_FAILURE,
- "health check call failed; will retry after backoff");
+ SetHealthStatusLocked(GRPC_CHANNEL_TRANSIENT_FAILURE,
+ "health check call failed; will retry after backoff");
grpc_millis next_try = retry_backoff_.NextAttemptTime();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: health check call lost...", this);
grpc_millis timeout = next_try - ExecCtx::Get()->Now();
if (timeout > 0) {
@@ -161,7 +161,7 @@ void HealthCheckClient::OnRetryTimer(void* arg, grpc_error* error) {
self->retry_timer_callback_pending_ = false;
if (!self->shutting_down_ && error == GRPC_ERROR_NONE &&
self->call_state_ == nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: restarting health check call",
self);
}
@@ -179,16 +179,16 @@ namespace {
void EncodeRequest(const char* service_name,
ManualConstructor<SliceBufferByteStream>* send_message) {
- upb::Arena arena;
- grpc_health_v1_HealthCheckRequest* request_struct =
- grpc_health_v1_HealthCheckRequest_new(arena.ptr());
- grpc_health_v1_HealthCheckRequest_set_service(
- request_struct, upb_strview_makez(service_name));
- size_t buf_length;
- char* buf = grpc_health_v1_HealthCheckRequest_serialize(
- request_struct, arena.ptr(), &buf_length);
- grpc_slice request_slice = GRPC_SLICE_MALLOC(buf_length);
- memcpy(GRPC_SLICE_START_PTR(request_slice), buf, buf_length);
+ upb::Arena arena;
+ grpc_health_v1_HealthCheckRequest* request_struct =
+ grpc_health_v1_HealthCheckRequest_new(arena.ptr());
+ grpc_health_v1_HealthCheckRequest_set_service(
+ request_struct, upb_strview_makez(service_name));
+ size_t buf_length;
+ char* buf = grpc_health_v1_HealthCheckRequest_serialize(
+ request_struct, arena.ptr(), &buf_length);
+ grpc_slice request_slice = GRPC_SLICE_MALLOC(buf_length);
+ memcpy(GRPC_SLICE_START_PTR(request_slice), buf, buf_length);
grpc_slice_buffer slice_buffer;
grpc_slice_buffer_init(&slice_buffer);
grpc_slice_buffer_add(&slice_buffer, request_slice);
@@ -206,7 +206,7 @@ bool DecodeResponse(grpc_slice_buffer* slice_buffer, grpc_error** error) {
return false;
}
// Concatenate the slices to form a single string.
- std::unique_ptr<uint8_t> recv_message_deleter;
+ std::unique_ptr<uint8_t> recv_message_deleter;
uint8_t* recv_message;
if (slice_buffer->count == 1) {
recv_message = GRPC_SLICE_START_PTR(slice_buffer->slices[0]);
@@ -222,19 +222,19 @@ bool DecodeResponse(grpc_slice_buffer* slice_buffer, grpc_error** error) {
}
}
// Deserialize message.
- upb::Arena arena;
- grpc_health_v1_HealthCheckResponse* response_struct =
- grpc_health_v1_HealthCheckResponse_parse(
- reinterpret_cast<char*>(recv_message), slice_buffer->length,
- arena.ptr());
- if (response_struct == nullptr) {
+ upb::Arena arena;
+ grpc_health_v1_HealthCheckResponse* response_struct =
+ grpc_health_v1_HealthCheckResponse_parse(
+ reinterpret_cast<char*>(recv_message), slice_buffer->length,
+ arena.ptr());
+ if (response_struct == nullptr) {
// Can't parse message; assume unhealthy.
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"cannot parse health check response");
return false;
}
- int32_t status = grpc_health_v1_HealthCheckResponse_status(response_struct);
- return status == grpc_health_v1_HealthCheckResponse_SERVING;
+ int32_t status = grpc_health_v1_HealthCheckResponse_status(response_struct);
+ return status == grpc_health_v1_HealthCheckResponse_SERVING;
}
} // namespace
@@ -246,14 +246,14 @@ bool DecodeResponse(grpc_slice_buffer* slice_buffer, grpc_error** error) {
HealthCheckClient::CallState::CallState(
RefCountedPtr<HealthCheckClient> health_check_client,
grpc_pollset_set* interested_parties)
- : health_check_client_(std::move(health_check_client)),
+ : health_check_client_(std::move(health_check_client)),
pollent_(grpc_polling_entity_create_from_pollset_set(interested_parties)),
- arena_(Arena::Create(health_check_client_->connected_subchannel_
- ->GetInitialCallSizeEstimate(0))),
- payload_(context_) {}
+ arena_(Arena::Create(health_check_client_->connected_subchannel_
+ ->GetInitialCallSizeEstimate(0))),
+ payload_(context_) {}
HealthCheckClient::CallState::~CallState() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: destroying CallState %p",
health_check_client_.get(), this);
}
@@ -268,35 +268,35 @@ HealthCheckClient::CallState::~CallState() {
// holding to the call stack. Also flush the closures on exec_ctx so that
// filters that schedule cancel notification closures on exec_ctx do not
// need to take a ref of the call stack to guarantee closure liveness.
- call_combiner_.SetNotifyOnCancel(nullptr);
- ExecCtx::Get()->Flush();
- arena_->Destroy();
+ call_combiner_.SetNotifyOnCancel(nullptr);
+ ExecCtx::Get()->Flush();
+ arena_->Destroy();
}
void HealthCheckClient::CallState::Orphan() {
- call_combiner_.Cancel(GRPC_ERROR_CANCELLED);
+ call_combiner_.Cancel(GRPC_ERROR_CANCELLED);
Cancel();
}
void HealthCheckClient::CallState::StartCall() {
- SubchannelCall::Args args = {
- health_check_client_->connected_subchannel_,
+ SubchannelCall::Args args = {
+ health_check_client_->connected_subchannel_,
&pollent_,
GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH,
- gpr_get_cycle_counter(), // start_time
- GRPC_MILLIS_INF_FUTURE, // deadline
+ gpr_get_cycle_counter(), // start_time
+ GRPC_MILLIS_INF_FUTURE, // deadline
arena_,
context_,
&call_combiner_,
0, // parent_data_size
};
grpc_error* error = GRPC_ERROR_NONE;
- call_ = SubchannelCall::Create(std::move(args), &error).release();
- // Register after-destruction callback.
- GRPC_CLOSURE_INIT(&after_call_stack_destruction_, AfterCallStackDestruction,
- this, grpc_schedule_on_exec_ctx);
- call_->SetAfterCallStackDestroy(&after_call_stack_destruction_);
- // Check if creation failed.
+ call_ = SubchannelCall::Create(std::move(args), &error).release();
+ // Register after-destruction callback.
+ GRPC_CLOSURE_INIT(&after_call_stack_destruction_, AfterCallStackDestruction,
+ this, grpc_schedule_on_exec_ctx);
+ call_->SetAfterCallStackDestroy(&after_call_stack_destruction_);
+ // Check if creation failed.
if (error != GRPC_ERROR_NONE) {
gpr_log(GPR_ERROR,
"HealthCheckClient %p CallState %p: error creating health "
@@ -310,7 +310,7 @@ void HealthCheckClient::CallState::StartCall() {
payload_.context = context_;
batch_.payload = &payload_;
// on_complete callback takes ref, handled manually.
- call_->Ref(DEBUG_LOCATION, "on_complete").release();
+ call_->Ref(DEBUG_LOCATION, "on_complete").release();
batch_.on_complete = GRPC_CLOSURE_INIT(&on_complete_, OnComplete, this,
grpc_schedule_on_exec_ctx);
// Add send_initial_metadata op.
@@ -319,8 +319,8 @@ void HealthCheckClient::CallState::StartCall() {
&send_initial_metadata_, &path_metadata_storage_,
grpc_mdelem_from_slices(
GRPC_MDSTR_PATH,
- GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH),
- GRPC_BATCH_PATH);
+ GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH),
+ GRPC_BATCH_PATH);
GPR_ASSERT(error == GRPC_ERROR_NONE);
payload_.send_initial_metadata.send_initial_metadata =
&send_initial_metadata_;
@@ -344,7 +344,7 @@ void HealthCheckClient::CallState::StartCall() {
payload_.recv_initial_metadata.trailing_metadata_available = nullptr;
payload_.recv_initial_metadata.peer_string = nullptr;
// recv_initial_metadata_ready callback takes ref, handled manually.
- call_->Ref(DEBUG_LOCATION, "recv_initial_metadata_ready").release();
+ call_->Ref(DEBUG_LOCATION, "recv_initial_metadata_ready").release();
payload_.recv_initial_metadata.recv_initial_metadata_ready =
GRPC_CLOSURE_INIT(&recv_initial_metadata_ready_, RecvInitialMetadataReady,
this, grpc_schedule_on_exec_ctx);
@@ -352,7 +352,7 @@ void HealthCheckClient::CallState::StartCall() {
// Add recv_message op.
payload_.recv_message.recv_message = &recv_message_;
// recv_message callback takes ref, handled manually.
- call_->Ref(DEBUG_LOCATION, "recv_message_ready").release();
+ call_->Ref(DEBUG_LOCATION, "recv_message_ready").release();
payload_.recv_message.recv_message_ready = GRPC_CLOSURE_INIT(
&recv_message_ready_, RecvMessageReady, this, grpc_schedule_on_exec_ctx);
batch_.recv_message = true;
@@ -377,8 +377,8 @@ void HealthCheckClient::CallState::StartCall() {
StartBatch(&recv_trailing_metadata_batch_);
}
-void HealthCheckClient::CallState::StartBatchInCallCombiner(
- void* arg, grpc_error* /*error*/) {
+void HealthCheckClient::CallState::StartBatchInCallCombiner(
+ void* arg, grpc_error* /*error*/) {
grpc_transport_stream_op_batch* batch =
static_cast<grpc_transport_stream_op_batch*>(arg);
SubchannelCall* call =
@@ -388,30 +388,30 @@ void HealthCheckClient::CallState::StartBatchInCallCombiner(
void HealthCheckClient::CallState::StartBatch(
grpc_transport_stream_op_batch* batch) {
- batch->handler_private.extra_arg = call_;
+ batch->handler_private.extra_arg = call_;
GRPC_CLOSURE_INIT(&batch->handler_private.closure, StartBatchInCallCombiner,
batch, grpc_schedule_on_exec_ctx);
GRPC_CALL_COMBINER_START(&call_combiner_, &batch->handler_private.closure,
GRPC_ERROR_NONE, "start_subchannel_batch");
}
-void HealthCheckClient::CallState::AfterCallStackDestruction(
- void* arg, grpc_error* /*error*/) {
- HealthCheckClient::CallState* self =
- static_cast<HealthCheckClient::CallState*>(arg);
- delete self;
-}
-
+void HealthCheckClient::CallState::AfterCallStackDestruction(
+ void* arg, grpc_error* /*error*/) {
+ HealthCheckClient::CallState* self =
+ static_cast<HealthCheckClient::CallState*>(arg);
+ delete self;
+}
+
void HealthCheckClient::CallState::OnCancelComplete(void* arg,
- grpc_error* /*error*/) {
+ grpc_error* /*error*/) {
HealthCheckClient::CallState* self =
static_cast<HealthCheckClient::CallState*>(arg);
GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "health_cancel");
- self->call_->Unref(DEBUG_LOCATION, "cancel");
+ self->call_->Unref(DEBUG_LOCATION, "cancel");
}
-void HealthCheckClient::CallState::StartCancel(void* arg,
- grpc_error* /*error*/) {
+void HealthCheckClient::CallState::StartCancel(void* arg,
+ grpc_error* /*error*/) {
HealthCheckClient::CallState* self =
static_cast<HealthCheckClient::CallState*>(arg);
auto* batch = grpc_make_transport_stream_op(
@@ -422,10 +422,10 @@ void HealthCheckClient::CallState::StartCancel(void* arg,
}
void HealthCheckClient::CallState::Cancel() {
- bool expected = false;
- if (cancelled_.CompareExchangeStrong(&expected, true, MemoryOrder::ACQ_REL,
- MemoryOrder::ACQUIRE)) {
- call_->Ref(DEBUG_LOCATION, "cancel").release();
+ bool expected = false;
+ if (cancelled_.CompareExchangeStrong(&expected, true, MemoryOrder::ACQ_REL,
+ MemoryOrder::ACQUIRE)) {
+ call_->Ref(DEBUG_LOCATION, "cancel").release();
GRPC_CALL_COMBINER_START(
&call_combiner_,
GRPC_CLOSURE_CREATE(StartCancel, this, grpc_schedule_on_exec_ctx),
@@ -433,23 +433,23 @@ void HealthCheckClient::CallState::Cancel() {
}
}
-void HealthCheckClient::CallState::OnComplete(void* arg,
- grpc_error* /*error*/) {
+void HealthCheckClient::CallState::OnComplete(void* arg,
+ grpc_error* /*error*/) {
HealthCheckClient::CallState* self =
static_cast<HealthCheckClient::CallState*>(arg);
GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "on_complete");
grpc_metadata_batch_destroy(&self->send_initial_metadata_);
grpc_metadata_batch_destroy(&self->send_trailing_metadata_);
- self->call_->Unref(DEBUG_LOCATION, "on_complete");
+ self->call_->Unref(DEBUG_LOCATION, "on_complete");
}
-void HealthCheckClient::CallState::RecvInitialMetadataReady(
- void* arg, grpc_error* /*error*/) {
+void HealthCheckClient::CallState::RecvInitialMetadataReady(
+ void* arg, grpc_error* /*error*/) {
HealthCheckClient::CallState* self =
static_cast<HealthCheckClient::CallState*>(arg);
GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "recv_initial_metadata_ready");
grpc_metadata_batch_destroy(&self->recv_initial_metadata_);
- self->call_->Unref(DEBUG_LOCATION, "recv_initial_metadata_ready");
+ self->call_->Unref(DEBUG_LOCATION, "recv_initial_metadata_ready");
}
void HealthCheckClient::CallState::DoneReadingRecvMessage(grpc_error* error) {
@@ -458,17 +458,17 @@ void HealthCheckClient::CallState::DoneReadingRecvMessage(grpc_error* error) {
GRPC_ERROR_UNREF(error);
Cancel();
grpc_slice_buffer_destroy_internal(&recv_message_buffer_);
- call_->Unref(DEBUG_LOCATION, "recv_message_ready");
+ call_->Unref(DEBUG_LOCATION, "recv_message_ready");
return;
}
const bool healthy = DecodeResponse(&recv_message_buffer_, &error);
const grpc_connectivity_state state =
healthy ? GRPC_CHANNEL_READY : GRPC_CHANNEL_TRANSIENT_FAILURE;
- const char* reason = error == GRPC_ERROR_NONE && !healthy
- ? "backend unhealthy"
- : grpc_error_string(error);
- health_check_client_->SetHealthStatus(state, reason);
- seen_response_.Store(true, MemoryOrder::RELEASE);
+ const char* reason = error == GRPC_ERROR_NONE && !healthy
+ ? "backend unhealthy"
+ : grpc_error_string(error);
+ health_check_client_->SetHealthStatus(state, reason);
+ seen_response_.Store(true, MemoryOrder::RELEASE);
grpc_slice_buffer_destroy_internal(&recv_message_buffer_);
// Start another recv_message batch.
// This re-uses the ref we're holding.
@@ -526,12 +526,12 @@ void HealthCheckClient::CallState::OnByteStreamNext(void* arg,
}
void HealthCheckClient::CallState::RecvMessageReady(void* arg,
- grpc_error* /*error*/) {
+ grpc_error* /*error*/) {
HealthCheckClient::CallState* self =
static_cast<HealthCheckClient::CallState*>(arg);
GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "recv_message_ready");
if (self->recv_message_ == nullptr) {
- self->call_->Unref(DEBUG_LOCATION, "recv_message_ready");
+ self->call_->Unref(DEBUG_LOCATION, "recv_message_ready");
return;
}
grpc_slice_buffer_init(&self->recv_message_buffer_);
@@ -557,7 +557,7 @@ void HealthCheckClient::CallState::RecvTrailingMetadataReady(
status = grpc_get_status_code_from_metadata(
self->recv_trailing_metadata_.idx.named.grpc_status->md);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO,
"HealthCheckClient %p CallState %p: health watch failed with "
"status %d",
@@ -578,7 +578,7 @@ void HealthCheckClient::CallState::RecvTrailingMetadataReady(
grpc_slice_from_static_string(kErrorMessage));
}
self->health_check_client_->SetHealthStatus(GRPC_CHANNEL_READY,
- kErrorMessage);
+ kErrorMessage);
retry = false;
}
MutexLock lock(&self->health_check_client_->mu_);
@@ -594,7 +594,7 @@ void HealthCheckClient::CallState::CallEndedLocked(bool retry) {
health_check_client_->call_state_.reset();
if (retry) {
GPR_ASSERT(!health_check_client_->shutting_down_);
- if (seen_response_.Load(MemoryOrder::ACQUIRE)) {
+ if (seen_response_.Load(MemoryOrder::ACQUIRE)) {
// If the call fails after we've gotten a successful response, reset
// the backoff and restart the call immediately.
health_check_client_->retry_backoff_.Reset();
@@ -605,9 +605,9 @@ void HealthCheckClient::CallState::CallEndedLocked(bool retry) {
}
}
}
- // When the last ref to the call stack goes away, the CallState object
- // will be automatically destroyed.
- call_->Unref(DEBUG_LOCATION, "call_ended");
+ // When the last ref to the call stack goes away, the CallState object
+ // will be automatically destroyed.
+ call_->Unref(DEBUG_LOCATION, "call_ended");
}
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h
index e9555b5f95..a721027c62 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h
@@ -27,11 +27,11 @@
#include "src/core/ext/filters/client_channel/client_channel_channelz.h"
#include "src/core/ext/filters/client_channel/subchannel.h"
#include "src/core/lib/backoff/backoff.h"
-#include "src/core/lib/gprpp/arena.h"
-#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/polling_entity.h"
@@ -47,8 +47,8 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
HealthCheckClient(const char* service_name,
RefCountedPtr<ConnectedSubchannel> connected_subchannel,
grpc_pollset_set* interested_parties,
- RefCountedPtr<channelz::SubchannelNode> channelz_node,
- RefCountedPtr<ConnectivityStateWatcherInterface> watcher);
+ RefCountedPtr<channelz::SubchannelNode> channelz_node,
+ RefCountedPtr<ConnectivityStateWatcherInterface> watcher);
~HealthCheckClient();
@@ -56,7 +56,7 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
private:
// Contains a call to the backend and all the data related to the call.
- class CallState : public Orphanable {
+ class CallState : public Orphanable {
public:
CallState(RefCountedPtr<HealthCheckClient> health_check_client,
grpc_pollset_set* interested_parties_);
@@ -87,19 +87,19 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
grpc_error* PullSliceFromRecvMessage();
void DoneReadingRecvMessage(grpc_error* error);
- static void AfterCallStackDestruction(void* arg, grpc_error* error);
-
+ static void AfterCallStackDestruction(void* arg, grpc_error* error);
+
RefCountedPtr<HealthCheckClient> health_check_client_;
grpc_polling_entity pollent_;
- Arena* arena_;
- grpc_core::CallCombiner call_combiner_;
+ Arena* arena_;
+ grpc_core::CallCombiner call_combiner_;
grpc_call_context_element context_[GRPC_CONTEXT_COUNT] = {};
- // The streaming call to the backend. Always non-null.
- // Refs are tracked manually; when the last ref is released, the
- // CallState object will be automatically destroyed.
- SubchannelCall* call_;
+ // The streaming call to the backend. Always non-null.
+ // Refs are tracked manually; when the last ref is released, the
+ // CallState object will be automatically destroyed.
+ SubchannelCall* call_;
grpc_transport_stream_op_batch_payload payload_;
grpc_transport_stream_op_batch batch_;
@@ -126,18 +126,18 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
OrphanablePtr<ByteStream> recv_message_;
grpc_closure recv_message_ready_;
grpc_slice_buffer recv_message_buffer_;
- Atomic<bool> seen_response_{false};
+ Atomic<bool> seen_response_{false};
// recv_trailing_metadata
grpc_metadata_batch recv_trailing_metadata_;
grpc_transport_stream_stats collect_stats_;
grpc_closure recv_trailing_metadata_ready_;
-
- // True if the cancel_stream batch has been started.
- Atomic<bool> cancelled_{false};
-
- // Closure for call stack destruction.
- grpc_closure after_call_stack_destruction_;
+
+ // True if the cancel_stream batch has been started.
+ Atomic<bool> cancelled_{false};
+
+ // Closure for call stack destruction.
+ grpc_closure after_call_stack_destruction_;
};
void StartCall();
@@ -146,17 +146,17 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
void StartRetryTimerLocked(); // Requires holding mu_.
static void OnRetryTimer(void* arg, grpc_error* error);
- void SetHealthStatus(grpc_connectivity_state state, const char* reason);
+ void SetHealthStatus(grpc_connectivity_state state, const char* reason);
void SetHealthStatusLocked(grpc_connectivity_state state,
- const char* reason); // Requires holding mu_.
+ const char* reason); // Requires holding mu_.
const char* service_name_; // Do not own.
RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
grpc_pollset_set* interested_parties_; // Do not own.
RefCountedPtr<channelz::SubchannelNode> channelz_node_;
- Mutex mu_;
- RefCountedPtr<ConnectivityStateWatcherInterface> watcher_;
+ Mutex mu_;
+ RefCountedPtr<ConnectivityStateWatcherInterface> watcher_;
bool shutting_down_ = false;
// The data associated with the current health check call. It holds a ref
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc
index 190baabd0a..43515d30ed 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc
@@ -34,7 +34,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/http/format_request.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/slice/slice_internal.h"
@@ -59,10 +59,10 @@ class HttpConnectHandshaker : public Handshaker {
void HandshakeFailedLocked(grpc_error* error);
static void OnWriteDone(void* arg, grpc_error* error);
static void OnReadDone(void* arg, grpc_error* error);
- static void OnWriteDoneScheduler(void* arg, grpc_error* error);
- static void OnReadDoneScheduler(void* arg, grpc_error* error);
+ static void OnWriteDoneScheduler(void* arg, grpc_error* error);
+ static void OnReadDoneScheduler(void* arg, grpc_error* error);
- Mutex mu_;
+ Mutex mu_;
bool is_shutdown_ = false;
// Endpoint and read buffer to destroy after a shutdown.
@@ -128,59 +128,59 @@ void HttpConnectHandshaker::HandshakeFailedLocked(grpc_error* error) {
is_shutdown_ = true;
}
// Invoke callback.
- ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, error);
-}
-
-// This callback can be invoked inline while already holding onto the mutex. To
-// avoid deadlocks, schedule OnWriteDone on ExecCtx.
-void HttpConnectHandshaker::OnWriteDoneScheduler(void* arg, grpc_error* error) {
- auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- GRPC_CLOSURE_INIT(&handshaker->request_done_closure_,
- &HttpConnectHandshaker::OnWriteDone, handshaker,
- grpc_schedule_on_exec_ctx),
- GRPC_ERROR_REF(error));
+ ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, error);
}
+// This callback can be invoked inline while already holding onto the mutex. To
+// avoid deadlocks, schedule OnWriteDone on ExecCtx.
+void HttpConnectHandshaker::OnWriteDoneScheduler(void* arg, grpc_error* error) {
+ auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ GRPC_CLOSURE_INIT(&handshaker->request_done_closure_,
+ &HttpConnectHandshaker::OnWriteDone, handshaker,
+ grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_REF(error));
+}
+
// Callback invoked when finished writing HTTP CONNECT request.
void HttpConnectHandshaker::OnWriteDone(void* arg, grpc_error* error) {
auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
- ReleasableMutexLock lock(&handshaker->mu_);
+ ReleasableMutexLock lock(&handshaker->mu_);
if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) {
// If the write failed or we're shutting down, clean up and invoke the
// callback with the error.
handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error));
- lock.Unlock();
+ lock.Unlock();
handshaker->Unref();
} else {
// Otherwise, read the response.
// The read callback inherits our ref to the handshaker.
- grpc_endpoint_read(
- handshaker->args_->endpoint, handshaker->args_->read_buffer,
- GRPC_CLOSURE_INIT(&handshaker->response_read_closure_,
- &HttpConnectHandshaker::OnReadDoneScheduler,
- handshaker, grpc_schedule_on_exec_ctx),
- /*urgent=*/true);
+ grpc_endpoint_read(
+ handshaker->args_->endpoint, handshaker->args_->read_buffer,
+ GRPC_CLOSURE_INIT(&handshaker->response_read_closure_,
+ &HttpConnectHandshaker::OnReadDoneScheduler,
+ handshaker, grpc_schedule_on_exec_ctx),
+ /*urgent=*/true);
}
}
-// This callback can be invoked inline while already holding onto the mutex. To
-// avoid deadlocks, schedule OnReadDone on ExecCtx.
-void HttpConnectHandshaker::OnReadDoneScheduler(void* arg, grpc_error* error) {
- auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- GRPC_CLOSURE_INIT(&handshaker->response_read_closure_,
- &HttpConnectHandshaker::OnReadDone, handshaker,
- grpc_schedule_on_exec_ctx),
- GRPC_ERROR_REF(error));
-}
-
+// This callback can be invoked inline while already holding onto the mutex. To
+// avoid deadlocks, schedule OnReadDone on ExecCtx.
+void HttpConnectHandshaker::OnReadDoneScheduler(void* arg, grpc_error* error) {
+ auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ GRPC_CLOSURE_INIT(&handshaker->response_read_closure_,
+ &HttpConnectHandshaker::OnReadDone, handshaker,
+ grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_REF(error));
+}
+
// Callback invoked for reading HTTP CONNECT response.
void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
auto* handshaker = static_cast<HttpConnectHandshaker*>(arg);
- ReleasableMutexLock lock(&handshaker->mu_);
+ ReleasableMutexLock lock(&handshaker->mu_);
if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) {
// If the read failed or we're shutting down, clean up and invoke the
// callback with the error.
@@ -232,12 +232,12 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
// at the Content-Length: header).
if (handshaker->http_parser_.state != GRPC_HTTP_BODY) {
grpc_slice_buffer_reset_and_unref_internal(handshaker->args_->read_buffer);
- grpc_endpoint_read(
- handshaker->args_->endpoint, handshaker->args_->read_buffer,
- GRPC_CLOSURE_INIT(&handshaker->response_read_closure_,
- &HttpConnectHandshaker::OnReadDoneScheduler,
- handshaker, grpc_schedule_on_exec_ctx),
- /*urgent=*/true);
+ grpc_endpoint_read(
+ handshaker->args_->endpoint, handshaker->args_->read_buffer,
+ GRPC_CLOSURE_INIT(&handshaker->response_read_closure_,
+ &HttpConnectHandshaker::OnReadDoneScheduler,
+ handshaker, grpc_schedule_on_exec_ctx),
+ /*urgent=*/true);
return;
}
// Make sure we got a 2xx response.
@@ -251,12 +251,12 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
goto done;
}
// Success. Invoke handshake-done callback.
- ExecCtx::Run(DEBUG_LOCATION, handshaker->on_handshake_done_, error);
+ ExecCtx::Run(DEBUG_LOCATION, handshaker->on_handshake_done_, error);
done:
// Set shutdown to true so that subsequent calls to
// http_connect_handshaker_shutdown() do nothing.
handshaker->is_shutdown_ = true;
- lock.Unlock();
+ lock.Unlock();
handshaker->Unref();
}
@@ -265,18 +265,18 @@ done:
//
void HttpConnectHandshaker::Shutdown(grpc_error* why) {
- {
- MutexLock lock(&mu_);
- if (!is_shutdown_) {
- is_shutdown_ = true;
- grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why));
- CleanupArgsForFailureLocked();
- }
+ {
+ MutexLock lock(&mu_);
+ if (!is_shutdown_) {
+ is_shutdown_ = true;
+ grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why));
+ CleanupArgsForFailureLocked();
+ }
}
GRPC_ERROR_UNREF(why);
}
-void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
+void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
grpc_closure* on_handshake_done,
HandshakerArgs* args) {
// Check for HTTP CONNECT channel arg.
@@ -287,11 +287,11 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
if (server_name == nullptr) {
// Set shutdown to true so that subsequent calls to
// http_connect_handshaker_shutdown() do nothing.
- {
- MutexLock lock(&mu_);
- is_shutdown_ = true;
- }
- ExecCtx::Run(DEBUG_LOCATION, on_handshake_done, GRPC_ERROR_NONE);
+ {
+ MutexLock lock(&mu_);
+ is_shutdown_ = true;
+ }
+ ExecCtx::Run(DEBUG_LOCATION, on_handshake_done, GRPC_ERROR_NONE);
return;
}
// Get headers from channel args.
@@ -350,12 +350,12 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
gpr_free(header_strings);
// Take a new ref to be held by the write callback.
Ref().release();
- grpc_endpoint_write(
- args->endpoint, &write_buffer_,
- GRPC_CLOSURE_INIT(&request_done_closure_,
- &HttpConnectHandshaker::OnWriteDoneScheduler, this,
- grpc_schedule_on_exec_ctx),
- nullptr);
+ grpc_endpoint_write(
+ args->endpoint, &write_buffer_,
+ GRPC_CLOSURE_INIT(&request_done_closure_,
+ &HttpConnectHandshaker::OnWriteDoneScheduler, this,
+ grpc_schedule_on_exec_ctx),
+ nullptr);
}
HttpConnectHandshaker::HttpConnectHandshaker() {
@@ -369,8 +369,8 @@ HttpConnectHandshaker::HttpConnectHandshaker() {
class HttpConnectHandshakerFactory : public HandshakerFactory {
public:
- void AddHandshakers(const grpc_channel_args* /*args*/,
- grpc_pollset_set* /*interested_parties*/,
+ void AddHandshakers(const grpc_channel_args* /*args*/,
+ grpc_pollset_set* /*interested_parties*/,
HandshakeManager* handshake_mgr) override {
handshake_mgr->Add(MakeRefCounted<HttpConnectHandshaker>());
}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h
index 26c31f2a0a..f53a02b709 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h
@@ -25,7 +25,7 @@
/// Channel arg indicating HTTP CONNECT headers (string).
/// Multiple headers are separated by newlines. Key/value pairs are
-/// separated by colons.
+/// separated by colons.
#define GRPC_ARG_HTTP_CONNECT_HEADERS "grpc.http_connect_headers"
/// Registers handshaker factory.
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc
index 2187682526..df8aaeb443 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc
@@ -34,13 +34,13 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/slice/b64.h"
#include "src/core/lib/uri/uri_parser.h"
-namespace grpc_core {
-namespace {
-
+namespace grpc_core {
+namespace {
+
/**
* Parses the 'https_proxy' env var (fallback on 'http_proxy') and returns the
* proxy hostname to resolve or nullptr on error. Also sets 'user_cred' to user
@@ -64,7 +64,7 @@ char* GetHttpProxyServer(const grpc_channel_args* args, char** user_cred) {
char* uri_str =
gpr_strdup(grpc_channel_args_find_string(args, GRPC_ARG_HTTP_PROXY));
if (uri_str == nullptr) uri_str = gpr_getenv("grpc_proxy");
- if (uri_str == nullptr) uri_str = gpr_getenv("https_proxy");
+ if (uri_str == nullptr) uri_str = gpr_getenv("https_proxy");
if (uri_str == nullptr) uri_str = gpr_getenv("http_proxy");
if (uri_str == nullptr) return nullptr;
// an emtpy value means "don't use proxy"
@@ -103,116 +103,116 @@ done:
return proxy_name;
}
-class HttpProxyMapper : public ProxyMapperInterface {
- public:
- bool MapName(const char* server_uri, const grpc_channel_args* args,
- char** name_to_resolve, grpc_channel_args** new_args) override {
- if (!grpc_channel_args_find_bool(args, GRPC_ARG_ENABLE_HTTP_PROXY, true)) {
- return false;
- }
- char* user_cred = nullptr;
+class HttpProxyMapper : public ProxyMapperInterface {
+ public:
+ bool MapName(const char* server_uri, const grpc_channel_args* args,
+ char** name_to_resolve, grpc_channel_args** new_args) override {
+ if (!grpc_channel_args_find_bool(args, GRPC_ARG_ENABLE_HTTP_PROXY, true)) {
+ return false;
+ }
+ char* user_cred = nullptr;
*name_to_resolve = GetHttpProxyServer(args, &user_cred);
- if (*name_to_resolve == nullptr) return false;
- char* no_proxy_str = nullptr;
- grpc_uri* uri = grpc_uri_parse(server_uri, false /* suppress_errors */);
- if (uri == nullptr || uri->path[0] == '\0') {
- gpr_log(GPR_ERROR,
- "'http_proxy' environment variable set, but cannot "
- "parse server URI '%s' -- not using proxy",
+ if (*name_to_resolve == nullptr) return false;
+ char* no_proxy_str = nullptr;
+ grpc_uri* uri = grpc_uri_parse(server_uri, false /* suppress_errors */);
+ if (uri == nullptr || uri->path[0] == '\0') {
+ gpr_log(GPR_ERROR,
+ "'http_proxy' environment variable set, but cannot "
+ "parse server URI '%s' -- not using proxy",
server_uri);
- goto no_use_proxy;
- }
- if (strcmp(uri->scheme, "unix") == 0) {
- gpr_log(GPR_INFO, "not using proxy for Unix domain socket '%s'",
- server_uri);
- goto no_use_proxy;
- }
- /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */
- no_proxy_str = gpr_getenv("no_grpc_proxy");
- if (no_proxy_str == nullptr) no_proxy_str = gpr_getenv("no_proxy");
- if (no_proxy_str != nullptr) {
- static const char* NO_PROXY_SEPARATOR = ",";
- bool use_proxy = true;
+ goto no_use_proxy;
+ }
+ if (strcmp(uri->scheme, "unix") == 0) {
+ gpr_log(GPR_INFO, "not using proxy for Unix domain socket '%s'",
+ server_uri);
+ goto no_use_proxy;
+ }
+ /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */
+ no_proxy_str = gpr_getenv("no_grpc_proxy");
+ if (no_proxy_str == nullptr) no_proxy_str = gpr_getenv("no_proxy");
+ if (no_proxy_str != nullptr) {
+ static const char* NO_PROXY_SEPARATOR = ",";
+ bool use_proxy = true;
TString server_host;
TString server_port;
- if (!grpc_core::SplitHostPort(
- uri->path[0] == '/' ? uri->path + 1 : uri->path, &server_host,
- &server_port)) {
- gpr_log(GPR_INFO,
- "unable to split host and port, not checking no_proxy list for "
- "host '%s'",
- server_uri);
- gpr_free(no_proxy_str);
- } else {
+ if (!grpc_core::SplitHostPort(
+ uri->path[0] == '/' ? uri->path + 1 : uri->path, &server_host,
+ &server_port)) {
+ gpr_log(GPR_INFO,
+ "unable to split host and port, not checking no_proxy list for "
+ "host '%s'",
+ server_uri);
+ gpr_free(no_proxy_str);
+ } else {
size_t uri_len = server_host.size();
- char** no_proxy_hosts;
- size_t num_no_proxy_hosts;
- gpr_string_split(no_proxy_str, NO_PROXY_SEPARATOR, &no_proxy_hosts,
- &num_no_proxy_hosts);
- for (size_t i = 0; i < num_no_proxy_hosts; i++) {
- char* no_proxy_entry = no_proxy_hosts[i];
- size_t no_proxy_len = strlen(no_proxy_entry);
- if (no_proxy_len <= uri_len &&
- gpr_stricmp(no_proxy_entry,
+ char** no_proxy_hosts;
+ size_t num_no_proxy_hosts;
+ gpr_string_split(no_proxy_str, NO_PROXY_SEPARATOR, &no_proxy_hosts,
+ &num_no_proxy_hosts);
+ for (size_t i = 0; i < num_no_proxy_hosts; i++) {
+ char* no_proxy_entry = no_proxy_hosts[i];
+ size_t no_proxy_len = strlen(no_proxy_entry);
+ if (no_proxy_len <= uri_len &&
+ gpr_stricmp(no_proxy_entry,
&(server_host.c_str()[uri_len - no_proxy_len])) ==
0) {
- gpr_log(GPR_INFO, "not using proxy for host in no_proxy list '%s'",
- server_uri);
- use_proxy = false;
- break;
- }
+ gpr_log(GPR_INFO, "not using proxy for host in no_proxy list '%s'",
+ server_uri);
+ use_proxy = false;
+ break;
+ }
}
- for (size_t i = 0; i < num_no_proxy_hosts; i++) {
- gpr_free(no_proxy_hosts[i]);
- }
- gpr_free(no_proxy_hosts);
- gpr_free(no_proxy_str);
- if (!use_proxy) goto no_use_proxy;
+ for (size_t i = 0; i < num_no_proxy_hosts; i++) {
+ gpr_free(no_proxy_hosts[i]);
+ }
+ gpr_free(no_proxy_hosts);
+ gpr_free(no_proxy_str);
+ if (!use_proxy) goto no_use_proxy;
}
}
- grpc_arg args_to_add[2];
- args_to_add[0] = grpc_channel_arg_string_create(
- (char*)GRPC_ARG_HTTP_CONNECT_SERVER,
- uri->path[0] == '/' ? uri->path + 1 : uri->path);
- if (user_cred != nullptr) {
- /* Use base64 encoding for user credentials as stated in RFC 7617 */
- char* encoded_user_cred =
- grpc_base64_encode(user_cred, strlen(user_cred), 0, 0);
+ grpc_arg args_to_add[2];
+ args_to_add[0] = grpc_channel_arg_string_create(
+ (char*)GRPC_ARG_HTTP_CONNECT_SERVER,
+ uri->path[0] == '/' ? uri->path + 1 : uri->path);
+ if (user_cred != nullptr) {
+ /* Use base64 encoding for user credentials as stated in RFC 7617 */
+ char* encoded_user_cred =
+ grpc_base64_encode(user_cred, strlen(user_cred), 0, 0);
TString header =
y_absl::StrCat("Proxy-Authorization:Basic ", encoded_user_cred);
- gpr_free(encoded_user_cred);
- args_to_add[1] = grpc_channel_arg_string_create(
+ gpr_free(encoded_user_cred);
+ args_to_add[1] = grpc_channel_arg_string_create(
const_cast<char*>(GRPC_ARG_HTTP_CONNECT_HEADERS),
const_cast<char*>(header.c_str()));
- *new_args = grpc_channel_args_copy_and_add(args, args_to_add, 2);
- } else {
- *new_args = grpc_channel_args_copy_and_add(args, args_to_add, 1);
- }
- grpc_uri_destroy(uri);
- gpr_free(user_cred);
- return true;
- no_use_proxy:
- if (uri != nullptr) grpc_uri_destroy(uri);
- gpr_free(*name_to_resolve);
- *name_to_resolve = nullptr;
- gpr_free(user_cred);
- return false;
+ *new_args = grpc_channel_args_copy_and_add(args, args_to_add, 2);
+ } else {
+ *new_args = grpc_channel_args_copy_and_add(args, args_to_add, 1);
+ }
+ grpc_uri_destroy(uri);
+ gpr_free(user_cred);
+ return true;
+ no_use_proxy:
+ if (uri != nullptr) grpc_uri_destroy(uri);
+ gpr_free(*name_to_resolve);
+ *name_to_resolve = nullptr;
+ gpr_free(user_cred);
+ return false;
}
-
+
bool MapAddress(const grpc_resolved_address& /*address*/,
const grpc_channel_args* /*args*/,
grpc_resolved_address** /*new_address*/,
grpc_channel_args** /*new_args*/) override {
- return false;
+ return false;
}
-};
-
-} // namespace
+};
-void RegisterHttpProxyMapper() {
- ProxyMapperRegistry::Register(
- true /* at_start */,
- std::unique_ptr<ProxyMapperInterface>(new HttpProxyMapper()));
+} // namespace
+
+void RegisterHttpProxyMapper() {
+ ProxyMapperRegistry::Register(
+ true /* at_start */,
+ std::unique_ptr<ProxyMapperInterface>(new HttpProxyMapper()));
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.h
index cecdaf8478..8c290cf624 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.h
@@ -19,10 +19,10 @@
#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H
#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H
-namespace grpc_core {
-
-void RegisterHttpProxyMapper();
-
-} // namespace grpc_core
+namespace grpc_core {
+void RegisterHttpProxyMapper();
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc
index 6c639ef86c..e82d94da8d 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc
@@ -25,84 +25,84 @@
namespace grpc_core {
-DebugOnlyTraceFlag grpc_trace_lb_policy_refcount(false, "lb_policy_refcount");
-
-//
-// LoadBalancingPolicy
-//
-
-LoadBalancingPolicy::LoadBalancingPolicy(Args args, intptr_t initial_refcount)
- : InternallyRefCounted(&grpc_trace_lb_policy_refcount, initial_refcount),
+DebugOnlyTraceFlag grpc_trace_lb_policy_refcount(false, "lb_policy_refcount");
+
+//
+// LoadBalancingPolicy
+//
+
+LoadBalancingPolicy::LoadBalancingPolicy(Args args, intptr_t initial_refcount)
+ : InternallyRefCounted(&grpc_trace_lb_policy_refcount, initial_refcount),
work_serializer_(std::move(args.work_serializer)),
interested_parties_(grpc_pollset_set_create()),
- channel_control_helper_(std::move(args.channel_control_helper)) {}
+ channel_control_helper_(std::move(args.channel_control_helper)) {}
LoadBalancingPolicy::~LoadBalancingPolicy() {
grpc_pollset_set_destroy(interested_parties_);
}
-void LoadBalancingPolicy::Orphan() {
- ShutdownLocked();
+void LoadBalancingPolicy::Orphan() {
+ ShutdownLocked();
Unref(DEBUG_LOCATION, "Orphan");
-}
-
-//
-// LoadBalancingPolicy::UpdateArgs
-//
-
-LoadBalancingPolicy::UpdateArgs::UpdateArgs(const UpdateArgs& other) {
- addresses = other.addresses;
- config = other.config;
- args = grpc_channel_args_copy(other.args);
-}
-
+}
+
+//
+// LoadBalancingPolicy::UpdateArgs
+//
+
+LoadBalancingPolicy::UpdateArgs::UpdateArgs(const UpdateArgs& other) {
+ addresses = other.addresses;
+ config = other.config;
+ args = grpc_channel_args_copy(other.args);
+}
+
LoadBalancingPolicy::UpdateArgs::UpdateArgs(UpdateArgs&& other) noexcept {
- addresses = std::move(other.addresses);
- config = std::move(other.config);
- // TODO(roth): Use std::move() once channel args is converted to C++.
- args = other.args;
- other.args = nullptr;
-}
-
-LoadBalancingPolicy::UpdateArgs& LoadBalancingPolicy::UpdateArgs::operator=(
- const UpdateArgs& other) {
- addresses = other.addresses;
- config = other.config;
- grpc_channel_args_destroy(args);
- args = grpc_channel_args_copy(other.args);
- return *this;
-}
-
-LoadBalancingPolicy::UpdateArgs& LoadBalancingPolicy::UpdateArgs::operator=(
+ addresses = std::move(other.addresses);
+ config = std::move(other.config);
+ // TODO(roth): Use std::move() once channel args is converted to C++.
+ args = other.args;
+ other.args = nullptr;
+}
+
+LoadBalancingPolicy::UpdateArgs& LoadBalancingPolicy::UpdateArgs::operator=(
+ const UpdateArgs& other) {
+ addresses = other.addresses;
+ config = other.config;
+ grpc_channel_args_destroy(args);
+ args = grpc_channel_args_copy(other.args);
+ return *this;
+}
+
+LoadBalancingPolicy::UpdateArgs& LoadBalancingPolicy::UpdateArgs::operator=(
UpdateArgs&& other) noexcept {
- addresses = std::move(other.addresses);
- config = std::move(other.config);
- // TODO(roth): Use std::move() once channel args is converted to C++.
- grpc_channel_args_destroy(args);
- args = other.args;
- other.args = nullptr;
- return *this;
-}
-
-//
-// LoadBalancingPolicy::QueuePicker
-//
-
-LoadBalancingPolicy::PickResult LoadBalancingPolicy::QueuePicker::Pick(
- PickArgs /*args*/) {
- // We invoke the parent's ExitIdleLocked() via a closure instead
- // of doing it directly here, for two reasons:
- // 1. ExitIdleLocked() may cause the policy's state to change and
- // a new picker to be delivered to the channel. If that new
- // picker is delivered before ExitIdleLocked() returns, then by
- // the time this function returns, the pick will already have
- // been processed, and we'll be trying to re-process the same
- // pick again, leading to a crash.
+ addresses = std::move(other.addresses);
+ config = std::move(other.config);
+ // TODO(roth): Use std::move() once channel args is converted to C++.
+ grpc_channel_args_destroy(args);
+ args = other.args;
+ other.args = nullptr;
+ return *this;
+}
+
+//
+// LoadBalancingPolicy::QueuePicker
+//
+
+LoadBalancingPolicy::PickResult LoadBalancingPolicy::QueuePicker::Pick(
+ PickArgs /*args*/) {
+ // We invoke the parent's ExitIdleLocked() via a closure instead
+ // of doing it directly here, for two reasons:
+ // 1. ExitIdleLocked() may cause the policy's state to change and
+ // a new picker to be delivered to the channel. If that new
+ // picker is delivered before ExitIdleLocked() returns, then by
+ // the time this function returns, the pick will already have
+ // been processed, and we'll be trying to re-process the same
+ // pick again, leading to a crash.
// 2. We are currently running in the data plane mutex, but we
// need to bounce into the control plane work_serializer to call
- // ExitIdleLocked().
- if (!exit_idle_called_) {
- exit_idle_called_ = true;
+ // ExitIdleLocked().
+ if (!exit_idle_called_) {
+ exit_idle_called_ = true;
auto* parent = parent_->Ref().release(); // ref held by lambda.
ExecCtx::Run(DEBUG_LOCATION,
GRPC_CLOSURE_CREATE(
@@ -118,21 +118,21 @@ LoadBalancingPolicy::PickResult LoadBalancingPolicy::QueuePicker::Pick(
parent, nullptr),
GRPC_ERROR_NONE);
}
- PickResult result;
- result.type = PickResult::PICK_QUEUE;
- return result;
-}
-
-//
-// LoadBalancingPolicy::TransientFailurePicker
-//
-
-LoadBalancingPolicy::PickResult
-LoadBalancingPolicy::TransientFailurePicker::Pick(PickArgs /*args*/) {
- PickResult result;
- result.type = PickResult::PICK_FAILED;
- result.error = GRPC_ERROR_REF(error_);
- return result;
+ PickResult result;
+ result.type = PickResult::PICK_QUEUE;
+ return result;
}
+//
+// LoadBalancingPolicy::TransientFailurePicker
+//
+
+LoadBalancingPolicy::PickResult
+LoadBalancingPolicy::TransientFailurePicker::Pick(PickArgs /*args*/) {
+ PickResult result;
+ result.type = PickResult::PICK_FAILED;
+ result.error = GRPC_ERROR_REF(error_);
+ return result;
+}
+
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h
index 1cbc074484..8672a7cab2 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h
@@ -21,16 +21,16 @@
#include <grpc/support/port_platform.h>
-#include <functional>
-#include <iterator>
-
+#include <functional>
+#include <iterator>
+
#include "y_absl/status/status.h"
#include "y_absl/strings/string_view.h"
-#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
-#include "src/core/ext/filters/client_channel/subchannel_interface.h"
-#include "src/core/lib/gprpp/map.h"
+#include "src/core/ext/filters/client_channel/server_address.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/subchannel_interface.h"
+#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/polling_entity.h"
@@ -39,88 +39,88 @@
namespace grpc_core {
-extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount;
-
+extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount;
+
/// Interface for load balancing policies.
///
-/// The following concepts are used here:
-///
-/// Channel: An abstraction that manages connections to backend servers
-/// on behalf of a client application. The application creates a channel
-/// for a given server name and then sends calls (RPCs) on it, and the
-/// channel figures out which backend server to send each call to. A channel
-/// contains a resolver, a load balancing policy (or a tree of LB policies),
-/// and a set of one or more subchannels.
-///
-/// Subchannel: A subchannel represents a connection to one backend server.
-/// The LB policy decides which subchannels to create, manages the
-/// connectivity state of those subchannels, and decides which subchannel
-/// to send any given call to.
-///
-/// Resolver: A plugin that takes a gRPC server URI and resolves it to a
-/// list of one or more addresses and a service config, as described
-/// in https://github.com/grpc/grpc/blob/master/doc/naming.md. See
-/// resolver.h for the resolver API.
-///
-/// Load Balancing (LB) Policy: A plugin that takes a list of addresses
-/// from the resolver, maintains and manages a subchannel for each
-/// backend address, and decides which subchannel to send each call on.
-/// An LB policy has two parts:
-/// - A LoadBalancingPolicy, which deals with the control plane work of
-/// managing subchannels.
-/// - A SubchannelPicker, which handles the data plane work of
-/// determining which subchannel a given call should be sent on.
-
-/// LoadBalacingPolicy API.
-///
+/// The following concepts are used here:
+///
+/// Channel: An abstraction that manages connections to backend servers
+/// on behalf of a client application. The application creates a channel
+/// for a given server name and then sends calls (RPCs) on it, and the
+/// channel figures out which backend server to send each call to. A channel
+/// contains a resolver, a load balancing policy (or a tree of LB policies),
+/// and a set of one or more subchannels.
+///
+/// Subchannel: A subchannel represents a connection to one backend server.
+/// The LB policy decides which subchannels to create, manages the
+/// connectivity state of those subchannels, and decides which subchannel
+/// to send any given call to.
+///
+/// Resolver: A plugin that takes a gRPC server URI and resolves it to a
+/// list of one or more addresses and a service config, as described
+/// in https://github.com/grpc/grpc/blob/master/doc/naming.md. See
+/// resolver.h for the resolver API.
+///
+/// Load Balancing (LB) Policy: A plugin that takes a list of addresses
+/// from the resolver, maintains and manages a subchannel for each
+/// backend address, and decides which subchannel to send each call on.
+/// An LB policy has two parts:
+/// - A LoadBalancingPolicy, which deals with the control plane work of
+/// managing subchannels.
+/// - A SubchannelPicker, which handles the data plane work of
+/// determining which subchannel a given call should be sent on.
+
+/// LoadBalacingPolicy API.
+///
/// Note: All methods with a "Locked" suffix must be called from the
/// work_serializer passed to the constructor.
///
/// Any I/O done by the LB policy should be done under the pollset_set
/// returned by \a interested_parties().
-// TODO(roth): Once we move to EventManager-based polling, remove the
-// interested_parties() hooks from the API.
+// TODO(roth): Once we move to EventManager-based polling, remove the
+// interested_parties() hooks from the API.
class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
public:
- // Represents backend metrics reported by the backend to the client.
- struct BackendMetricData {
- /// CPU utilization expressed as a fraction of available CPU resources.
- double cpu_utilization;
- /// Memory utilization expressed as a fraction of available memory
- /// resources.
- double mem_utilization;
- /// Total requests per second being served by the backend. This
- /// should include all services that a backend is responsible for.
- uint64_t requests_per_second;
- /// Application-specific requests cost metrics. Metric names are
- /// determined by the application. Each value is an absolute cost
- /// (e.g. 3487 bytes of storage) associated with the request.
+ // Represents backend metrics reported by the backend to the client.
+ struct BackendMetricData {
+ /// CPU utilization expressed as a fraction of available CPU resources.
+ double cpu_utilization;
+ /// Memory utilization expressed as a fraction of available memory
+ /// resources.
+ double mem_utilization;
+ /// Total requests per second being served by the backend. This
+ /// should include all services that a backend is responsible for.
+ uint64_t requests_per_second;
+ /// Application-specific requests cost metrics. Metric names are
+ /// determined by the application. Each value is an absolute cost
+ /// (e.g. 3487 bytes of storage) associated with the request.
std::map<y_absl::string_view, double, StringLess> request_cost;
- /// Application-specific resource utilization metrics. Metric names
- /// are determined by the application. Each value is expressed as a
- /// fraction of total resources available.
+ /// Application-specific resource utilization metrics. Metric names
+ /// are determined by the application. Each value is expressed as a
+ /// fraction of total resources available.
std::map<y_absl::string_view, double, StringLess> utilization;
- };
-
- /// Interface for accessing per-call state.
- /// Implemented by the client channel and used by the SubchannelPicker.
- class CallState {
- public:
- CallState() = default;
- virtual ~CallState() = default;
-
- /// Allocates memory associated with the call, which will be
- /// automatically freed when the call is complete.
- /// It is more efficient to use this than to allocate memory directly
- /// for allocations that need to be made on a per-call basis.
- virtual void* Alloc(size_t size) = 0;
-
- /// Returns the backend metric data returned by the server for the call,
- /// or null if no backend metric data was returned.
+ };
+
+ /// Interface for accessing per-call state.
+ /// Implemented by the client channel and used by the SubchannelPicker.
+ class CallState {
+ public:
+ CallState() = default;
+ virtual ~CallState() = default;
+
+ /// Allocates memory associated with the call, which will be
+ /// automatically freed when the call is complete.
+ /// It is more efficient to use this than to allocate memory directly
+ /// for allocations that need to be made on a per-call basis.
+ virtual void* Alloc(size_t size) = 0;
+
+ /// Returns the backend metric data returned by the server for the call,
+ /// or null if no backend metric data was returned.
// TODO(roth): Move this out of CallState, since it should not be
// accessible to the picker, only to the recv_trailing_metadata_ready
// callback. It should instead be in its own interface.
- virtual const BackendMetricData* GetBackendMetricData() = 0;
+ virtual const BackendMetricData* GetBackendMetricData() = 0;
/// EXPERIMENTAL API.
/// Returns the value of the call attribute \a key.
@@ -128,13 +128,13 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// policy implementation only if it knows about the internal key.
/// Returns a null string_view if key not found.
virtual y_absl::string_view ExperimentalGetCallAttribute(const char* key) = 0;
- };
-
- /// Interface for accessing metadata.
- /// Implemented by the client channel and used by the SubchannelPicker.
- class MetadataInterface {
- public:
- class iterator
+ };
+
+ /// Interface for accessing metadata.
+ /// Implemented by the client channel and used by the SubchannelPicker.
+ class MetadataInterface {
+ public:
+ class iterator
: public std::iterator<
std::input_iterator_tag,
std::pair<y_absl::string_view, y_absl::string_view>, // value_type
@@ -142,282 +142,282 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
std::pair<y_absl::string_view, y_absl::string_view>*, // pointer
std::pair<y_absl::string_view, y_absl::string_view>& // reference
> {
- public:
- iterator(const MetadataInterface* md, intptr_t handle)
- : md_(md), handle_(handle) {}
- iterator& operator++() {
- handle_ = md_->IteratorHandleNext(handle_);
- return *this;
- }
- bool operator==(iterator other) const {
- return md_ == other.md_ && handle_ == other.handle_;
- }
- bool operator!=(iterator other) const { return !(*this == other); }
- value_type operator*() const { return md_->IteratorHandleGet(handle_); }
-
- private:
- friend class MetadataInterface;
- const MetadataInterface* md_;
- intptr_t handle_;
- };
-
- virtual ~MetadataInterface() = default;
-
- /// Adds a key/value pair.
- /// Does NOT take ownership of \a key or \a value.
- /// Implementations must ensure that the key and value remain alive
- /// until the call ends. If desired, they may be allocated via
- /// CallState::Alloc().
+ public:
+ iterator(const MetadataInterface* md, intptr_t handle)
+ : md_(md), handle_(handle) {}
+ iterator& operator++() {
+ handle_ = md_->IteratorHandleNext(handle_);
+ return *this;
+ }
+ bool operator==(iterator other) const {
+ return md_ == other.md_ && handle_ == other.handle_;
+ }
+ bool operator!=(iterator other) const { return !(*this == other); }
+ value_type operator*() const { return md_->IteratorHandleGet(handle_); }
+
+ private:
+ friend class MetadataInterface;
+ const MetadataInterface* md_;
+ intptr_t handle_;
+ };
+
+ virtual ~MetadataInterface() = default;
+
+ /// Adds a key/value pair.
+ /// Does NOT take ownership of \a key or \a value.
+ /// Implementations must ensure that the key and value remain alive
+ /// until the call ends. If desired, they may be allocated via
+ /// CallState::Alloc().
virtual void Add(y_absl::string_view key, y_absl::string_view value) = 0;
-
- /// Iteration interface.
- virtual iterator begin() const = 0;
- virtual iterator end() const = 0;
-
- /// Removes the element pointed to by \a it.
- /// Returns an iterator pointing to the next element.
- virtual iterator erase(iterator it) = 0;
-
- protected:
- intptr_t GetIteratorHandle(const iterator& it) const { return it.handle_; }
-
- private:
- friend class iterator;
-
- virtual intptr_t IteratorHandleNext(intptr_t handle) const = 0;
+
+ /// Iteration interface.
+ virtual iterator begin() const = 0;
+ virtual iterator end() const = 0;
+
+ /// Removes the element pointed to by \a it.
+ /// Returns an iterator pointing to the next element.
+ virtual iterator erase(iterator it) = 0;
+
+ protected:
+ intptr_t GetIteratorHandle(const iterator& it) const { return it.handle_; }
+
+ private:
+ friend class iterator;
+
+ virtual intptr_t IteratorHandleNext(intptr_t handle) const = 0;
virtual std::pair<y_absl::string_view /*key*/, y_absl::string_view /*value */>
- IteratorHandleGet(intptr_t handle) const = 0;
- };
-
- /// Arguments used when picking a subchannel for a call.
- struct PickArgs {
+ IteratorHandleGet(intptr_t handle) const = 0;
+ };
+
+ /// Arguments used when picking a subchannel for a call.
+ struct PickArgs {
/// The path of the call. Indicates the RPC service and method name.
y_absl::string_view path;
- /// Initial metadata associated with the picking call.
- /// The LB policy may use the existing metadata to influence its routing
- /// decision, and it may add new metadata elements to be sent with the
- /// call to the chosen backend.
- MetadataInterface* initial_metadata;
- /// An interface for accessing call state. Can be used to allocate
+ /// Initial metadata associated with the picking call.
+ /// The LB policy may use the existing metadata to influence its routing
+ /// decision, and it may add new metadata elements to be sent with the
+ /// call to the chosen backend.
+ MetadataInterface* initial_metadata;
+ /// An interface for accessing call state. Can be used to allocate
/// memory associated with the call in an efficient way.
- CallState* call_state;
- };
-
- /// The result of picking a subchannel for a call.
- struct PickResult {
- enum ResultType {
- /// Pick complete. If \a subchannel is non-null, the client channel
- /// will immediately proceed with the call on that subchannel;
- /// otherwise, it will drop the call.
- PICK_COMPLETE,
- /// Pick cannot be completed until something changes on the control
- /// plane. The client channel will queue the pick and try again the
- /// next time the picker is updated.
- PICK_QUEUE,
- /// Pick failed. If the call is wait_for_ready, the client channel
- /// will wait for the next picker and try again; otherwise, it
- /// will immediately fail the call with the status indicated via
- /// \a error (although the call may be retried if the client channel
- /// is configured to do so).
- PICK_FAILED,
- };
- ResultType type;
-
- /// Used only if type is PICK_COMPLETE. Will be set to the selected
- /// subchannel, or nullptr if the LB policy decides to drop the call.
- RefCountedPtr<SubchannelInterface> subchannel;
-
- /// Used only if type is PICK_FAILED.
- /// Error to be set when returning a failure.
- // TODO(roth): Replace this with something similar to grpc::Status,
- // so that we don't expose grpc_error to this API.
- grpc_error* error = GRPC_ERROR_NONE;
-
- /// Used only if type is PICK_COMPLETE.
- /// Callback set by LB policy to be notified of trailing metadata.
- /// If set by LB policy, the client channel will invoke the callback
- /// when trailing metadata is returned.
- /// The metadata may be modified by the callback. However, the callback
- /// does not take ownership, so any data that needs to be used after
- /// returning must be copied.
- /// The call state can be used to obtain backend metric data.
+ CallState* call_state;
+ };
+
+ /// The result of picking a subchannel for a call.
+ struct PickResult {
+ enum ResultType {
+ /// Pick complete. If \a subchannel is non-null, the client channel
+ /// will immediately proceed with the call on that subchannel;
+ /// otherwise, it will drop the call.
+ PICK_COMPLETE,
+ /// Pick cannot be completed until something changes on the control
+ /// plane. The client channel will queue the pick and try again the
+ /// next time the picker is updated.
+ PICK_QUEUE,
+ /// Pick failed. If the call is wait_for_ready, the client channel
+ /// will wait for the next picker and try again; otherwise, it
+ /// will immediately fail the call with the status indicated via
+ /// \a error (although the call may be retried if the client channel
+ /// is configured to do so).
+ PICK_FAILED,
+ };
+ ResultType type;
+
+ /// Used only if type is PICK_COMPLETE. Will be set to the selected
+ /// subchannel, or nullptr if the LB policy decides to drop the call.
+ RefCountedPtr<SubchannelInterface> subchannel;
+
+ /// Used only if type is PICK_FAILED.
+ /// Error to be set when returning a failure.
+ // TODO(roth): Replace this with something similar to grpc::Status,
+ // so that we don't expose grpc_error to this API.
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ /// Used only if type is PICK_COMPLETE.
+ /// Callback set by LB policy to be notified of trailing metadata.
+ /// If set by LB policy, the client channel will invoke the callback
+ /// when trailing metadata is returned.
+ /// The metadata may be modified by the callback. However, the callback
+ /// does not take ownership, so any data that needs to be used after
+ /// returning must be copied.
+ /// The call state can be used to obtain backend metric data.
// TODO(roth): The arguments to this callback should be moved into a
// struct, so that we can later add new fields without breaking
// existing implementations.
- std::function<void(grpc_error*, MetadataInterface*, CallState*)>
- recv_trailing_metadata_ready;
- };
-
- /// A subchannel picker is the object used to pick the subchannel to
- /// use for a given call. This is implemented by the LB policy and
- /// used by the client channel to perform picks.
- ///
- /// Pickers are intended to encapsulate all of the state and logic
- /// needed on the data plane (i.e., to actually process picks for
- /// individual calls sent on the channel) while excluding all of the
- /// state and logic needed on the control plane (i.e., resolver
- /// updates, connectivity state notifications, etc); the latter should
- /// live in the LB policy object itself.
- ///
- /// Currently, pickers are always accessed from within the
+ std::function<void(grpc_error*, MetadataInterface*, CallState*)>
+ recv_trailing_metadata_ready;
+ };
+
+ /// A subchannel picker is the object used to pick the subchannel to
+ /// use for a given call. This is implemented by the LB policy and
+ /// used by the client channel to perform picks.
+ ///
+ /// Pickers are intended to encapsulate all of the state and logic
+ /// needed on the data plane (i.e., to actually process picks for
+ /// individual calls sent on the channel) while excluding all of the
+ /// state and logic needed on the control plane (i.e., resolver
+ /// updates, connectivity state notifications, etc); the latter should
+ /// live in the LB policy object itself.
+ ///
+ /// Currently, pickers are always accessed from within the
/// client_channel data plane mutex, so they do not have to be
- /// thread-safe.
- class SubchannelPicker {
- public:
- SubchannelPicker() = default;
- virtual ~SubchannelPicker() = default;
-
- virtual PickResult Pick(PickArgs args) = 0;
- };
-
- /// A proxy object implemented by the client channel and used by the
- /// LB policy to communicate with the channel.
- class ChannelControlHelper {
- public:
- ChannelControlHelper() = default;
- virtual ~ChannelControlHelper() = default;
-
- /// Creates a new subchannel with the specified channel args.
- virtual RefCountedPtr<SubchannelInterface> CreateSubchannel(
+ /// thread-safe.
+ class SubchannelPicker {
+ public:
+ SubchannelPicker() = default;
+ virtual ~SubchannelPicker() = default;
+
+ virtual PickResult Pick(PickArgs args) = 0;
+ };
+
+ /// A proxy object implemented by the client channel and used by the
+ /// LB policy to communicate with the channel.
+ class ChannelControlHelper {
+ public:
+ ChannelControlHelper() = default;
+ virtual ~ChannelControlHelper() = default;
+
+ /// Creates a new subchannel with the specified channel args.
+ virtual RefCountedPtr<SubchannelInterface> CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) = 0;
-
- /// Sets the connectivity state and returns a new picker to be used
- /// by the client channel.
- virtual void UpdateState(grpc_connectivity_state state,
+
+ /// Sets the connectivity state and returns a new picker to be used
+ /// by the client channel.
+ virtual void UpdateState(grpc_connectivity_state state,
const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker>) = 0;
-
- /// Requests that the resolver re-resolve.
- virtual void RequestReresolution() = 0;
-
- /// Adds a trace message associated with the channel.
- enum TraceSeverity { TRACE_INFO, TRACE_WARNING, TRACE_ERROR };
+ std::unique_ptr<SubchannelPicker>) = 0;
+
+ /// Requests that the resolver re-resolve.
+ virtual void RequestReresolution() = 0;
+
+ /// Adds a trace message associated with the channel.
+ enum TraceSeverity { TRACE_INFO, TRACE_WARNING, TRACE_ERROR };
virtual void AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) = 0;
- };
-
- /// Interface for configuration data used by an LB policy implementation.
- /// Individual implementations will create a subclass that adds methods to
- /// return the parameters they need.
- class Config : public RefCounted<Config> {
- public:
- virtual ~Config() = default;
-
- // Returns the load balancing policy name
- virtual const char* name() const = 0;
- };
-
- /// Data passed to the UpdateLocked() method when new addresses and
- /// config are available.
- struct UpdateArgs {
- ServerAddressList addresses;
- RefCountedPtr<Config> config;
- const grpc_channel_args* args = nullptr;
-
- // TODO(roth): Remove everything below once channel args is
- // converted to a copyable and movable C++ object.
- UpdateArgs() = default;
- ~UpdateArgs() { grpc_channel_args_destroy(args); }
- UpdateArgs(const UpdateArgs& other);
+ };
+
+ /// Interface for configuration data used by an LB policy implementation.
+ /// Individual implementations will create a subclass that adds methods to
+ /// return the parameters they need.
+ class Config : public RefCounted<Config> {
+ public:
+ virtual ~Config() = default;
+
+ // Returns the load balancing policy name
+ virtual const char* name() const = 0;
+ };
+
+ /// Data passed to the UpdateLocked() method when new addresses and
+ /// config are available.
+ struct UpdateArgs {
+ ServerAddressList addresses;
+ RefCountedPtr<Config> config;
+ const grpc_channel_args* args = nullptr;
+
+ // TODO(roth): Remove everything below once channel args is
+ // converted to a copyable and movable C++ object.
+ UpdateArgs() = default;
+ ~UpdateArgs() { grpc_channel_args_destroy(args); }
+ UpdateArgs(const UpdateArgs& other);
UpdateArgs(UpdateArgs&& other) noexcept;
- UpdateArgs& operator=(const UpdateArgs& other);
+ UpdateArgs& operator=(const UpdateArgs& other);
UpdateArgs& operator=(UpdateArgs&& other) noexcept;
- };
-
- /// Args used to instantiate an LB policy.
+ };
+
+ /// Args used to instantiate an LB policy.
struct Args {
/// The work_serializer under which all LB policy calls will be run.
std::shared_ptr<WorkSerializer> work_serializer;
- /// Channel control helper.
- /// Note: LB policies MUST NOT call any method on the helper from
- /// their constructor.
- std::unique_ptr<ChannelControlHelper> channel_control_helper;
- /// Channel args.
- // TODO(roth): Find a better channel args representation for this API.
- // TODO(roth): Clarify ownership semantics here -- currently, this
- // does not take ownership of args, which is the opposite of how we
- // handle them in UpdateArgs.
- const grpc_channel_args* args = nullptr;
+ /// Channel control helper.
+ /// Note: LB policies MUST NOT call any method on the helper from
+ /// their constructor.
+ std::unique_ptr<ChannelControlHelper> channel_control_helper;
+ /// Channel args.
+ // TODO(roth): Find a better channel args representation for this API.
+ // TODO(roth): Clarify ownership semantics here -- currently, this
+ // does not take ownership of args, which is the opposite of how we
+ // handle them in UpdateArgs.
+ const grpc_channel_args* args = nullptr;
};
- explicit LoadBalancingPolicy(Args args, intptr_t initial_refcount = 1);
- virtual ~LoadBalancingPolicy();
+ explicit LoadBalancingPolicy(Args args, intptr_t initial_refcount = 1);
+ virtual ~LoadBalancingPolicy();
// Not copyable nor movable.
LoadBalancingPolicy(const LoadBalancingPolicy&) = delete;
LoadBalancingPolicy& operator=(const LoadBalancingPolicy&) = delete;
/// Returns the name of the LB policy.
- virtual const char* name() const = 0;
+ virtual const char* name() const = 0;
- /// Updates the policy with new data from the resolver. Will be invoked
- /// immediately after LB policy is constructed, and then again whenever
- /// the resolver returns a new result.
- virtual void UpdateLocked(UpdateArgs) = 0; // NOLINT
+ /// Updates the policy with new data from the resolver. Will be invoked
+ /// immediately after LB policy is constructed, and then again whenever
+ /// the resolver returns a new result.
+ virtual void UpdateLocked(UpdateArgs) = 0; // NOLINT
- /// Tries to enter a READY connectivity state.
- /// This is a no-op by default, since most LB policies never go into
- /// IDLE state.
- virtual void ExitIdleLocked() {}
+ /// Tries to enter a READY connectivity state.
+ /// This is a no-op by default, since most LB policies never go into
+ /// IDLE state.
+ virtual void ExitIdleLocked() {}
- /// Resets connection backoff.
- virtual void ResetBackoffLocked() = 0;
+ /// Resets connection backoff.
+ virtual void ResetBackoffLocked() = 0;
- grpc_pollset_set* interested_parties() const { return interested_parties_; }
+ grpc_pollset_set* interested_parties() const { return interested_parties_; }
// Note: This must be invoked while holding the work_serializer.
- void Orphan() override;
+ void Orphan() override;
- // A picker that returns PICK_QUEUE for all picks.
- // Also calls the parent LB policy's ExitIdleLocked() method when the
- // first pick is seen.
- class QueuePicker : public SubchannelPicker {
- public:
- explicit QueuePicker(RefCountedPtr<LoadBalancingPolicy> parent)
- : parent_(std::move(parent)) {}
+ // A picker that returns PICK_QUEUE for all picks.
+ // Also calls the parent LB policy's ExitIdleLocked() method when the
+ // first pick is seen.
+ class QueuePicker : public SubchannelPicker {
+ public:
+ explicit QueuePicker(RefCountedPtr<LoadBalancingPolicy> parent)
+ : parent_(std::move(parent)) {}
- ~QueuePicker() { parent_.reset(DEBUG_LOCATION, "QueuePicker"); }
+ ~QueuePicker() { parent_.reset(DEBUG_LOCATION, "QueuePicker"); }
- PickResult Pick(PickArgs args) override;
+ PickResult Pick(PickArgs args) override;
- private:
- RefCountedPtr<LoadBalancingPolicy> parent_;
- bool exit_idle_called_ = false;
- };
+ private:
+ RefCountedPtr<LoadBalancingPolicy> parent_;
+ bool exit_idle_called_ = false;
+ };
- // A picker that returns PICK_TRANSIENT_FAILURE for all picks.
- class TransientFailurePicker : public SubchannelPicker {
- public:
- explicit TransientFailurePicker(grpc_error* error) : error_(error) {}
- ~TransientFailurePicker() override { GRPC_ERROR_UNREF(error_); }
+ // A picker that returns PICK_TRANSIENT_FAILURE for all picks.
+ class TransientFailurePicker : public SubchannelPicker {
+ public:
+ explicit TransientFailurePicker(grpc_error* error) : error_(error) {}
+ ~TransientFailurePicker() override { GRPC_ERROR_UNREF(error_); }
- PickResult Pick(PickArgs args) override;
+ PickResult Pick(PickArgs args) override;
- private:
- grpc_error* error_;
- };
+ private:
+ grpc_error* error_;
+ };
protected:
std::shared_ptr<WorkSerializer> work_serializer() const {
return work_serializer_;
}
- // Note: LB policies MUST NOT call any method on the helper from their
- // constructor.
- ChannelControlHelper* channel_control_helper() const {
- return channel_control_helper_.get();
+ // Note: LB policies MUST NOT call any method on the helper from their
+ // constructor.
+ ChannelControlHelper* channel_control_helper() const {
+ return channel_control_helper_.get();
}
- /// Shuts down the policy.
- virtual void ShutdownLocked() = 0;
+ /// Shuts down the policy.
+ virtual void ShutdownLocked() = 0;
private:
/// Work Serializer under which LB policy actions take place.
std::shared_ptr<WorkSerializer> work_serializer_;
/// Owned pointer to interested parties in load balancing decisions.
grpc_pollset_set* interested_parties_;
- /// Channel control helper.
- std::unique_ptr<ChannelControlHelper> channel_control_helper_;
+ /// Channel control helper.
+ std::unique_ptr<ChannelControlHelper> channel_control_helper_;
};
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc
index c8d1b1d7af..19fed3efad 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc
@@ -20,22 +20,22 @@
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h"
-#include <string.h>
-
+#include <string.h>
+
#include <grpc/support/atm.h>
#include <grpc/support/log.h>
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/profiling/timers.h"
-static grpc_error* clr_init_channel_elem(grpc_channel_element* /*elem*/,
- grpc_channel_element_args* /*args*/) {
+static grpc_error* clr_init_channel_elem(grpc_channel_element* /*elem*/,
+ grpc_channel_element_args* /*args*/) {
return GRPC_ERROR_NONE;
}
-static void clr_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
+static void clr_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
namespace {
@@ -59,8 +59,8 @@ static void on_complete_for_send(void* arg, grpc_error* error) {
if (error == GRPC_ERROR_NONE) {
calld->send_initial_metadata_succeeded = true;
}
- grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_on_complete_for_send,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_on_complete_for_send,
+ GRPC_ERROR_REF(error));
}
static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
@@ -68,21 +68,21 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
if (error == GRPC_ERROR_NONE) {
calld->recv_initial_metadata_succeeded = true;
}
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_recv_initial_metadata_ready,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_recv_initial_metadata_ready,
+ GRPC_ERROR_REF(error));
}
-static grpc_error* clr_init_call_elem(grpc_call_element* elem,
- const grpc_call_element_args* args) {
+static grpc_error* clr_init_call_elem(grpc_call_element* elem,
+ const grpc_call_element_args* args) {
GPR_ASSERT(args->context != nullptr);
- new (elem->call_data) call_data();
+ new (elem->call_data) call_data();
return GRPC_ERROR_NONE;
}
-static void clr_destroy_call_elem(grpc_call_element* elem,
- const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void clr_destroy_call_elem(grpc_call_element* elem,
+ const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
if (calld->client_stats != nullptr) {
// Record call finished, optionally setting client_failed_to_send and
@@ -94,64 +94,64 @@ static void clr_destroy_call_elem(grpc_call_element* elem,
calld->~call_data();
}
-static void clr_start_transport_stream_op_batch(
+static void clr_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
call_data* calld = static_cast<call_data*>(elem->call_data);
GPR_TIMER_SCOPE("clr_start_transport_stream_op_batch", 0);
- // Handle send_initial_metadata.
- if (batch->send_initial_metadata) {
- // Grab client stats object from metadata.
- grpc_linked_mdelem* client_stats_md =
- batch->payload->send_initial_metadata.send_initial_metadata->list.head;
- for (; client_stats_md != nullptr;
- client_stats_md = client_stats_md->next) {
- if (GRPC_SLICE_START_PTR(GRPC_MDKEY(client_stats_md->md)) ==
- static_cast<const void*>(grpc_core::kGrpcLbClientStatsMetadataKey)) {
- break;
- }
+ // Handle send_initial_metadata.
+ if (batch->send_initial_metadata) {
+ // Grab client stats object from metadata.
+ grpc_linked_mdelem* client_stats_md =
+ batch->payload->send_initial_metadata.send_initial_metadata->list.head;
+ for (; client_stats_md != nullptr;
+ client_stats_md = client_stats_md->next) {
+ if (GRPC_SLICE_START_PTR(GRPC_MDKEY(client_stats_md->md)) ==
+ static_cast<const void*>(grpc_core::kGrpcLbClientStatsMetadataKey)) {
+ break;
+ }
}
- if (client_stats_md != nullptr) {
- grpc_core::GrpcLbClientStats* client_stats =
- const_cast<grpc_core::GrpcLbClientStats*>(
- reinterpret_cast<const grpc_core::GrpcLbClientStats*>(
- GRPC_SLICE_START_PTR(GRPC_MDVALUE(client_stats_md->md))));
- if (client_stats != nullptr) {
- calld->client_stats.reset(client_stats);
- // Intercept completion.
- calld->original_on_complete_for_send = batch->on_complete;
- GRPC_CLOSURE_INIT(&calld->on_complete_for_send, on_complete_for_send,
- calld, grpc_schedule_on_exec_ctx);
- batch->on_complete = &calld->on_complete_for_send;
- }
- // Remove metadata so it doesn't go out on the wire.
- grpc_metadata_batch_remove(
- batch->payload->send_initial_metadata.send_initial_metadata,
- client_stats_md);
+ if (client_stats_md != nullptr) {
+ grpc_core::GrpcLbClientStats* client_stats =
+ const_cast<grpc_core::GrpcLbClientStats*>(
+ reinterpret_cast<const grpc_core::GrpcLbClientStats*>(
+ GRPC_SLICE_START_PTR(GRPC_MDVALUE(client_stats_md->md))));
+ if (client_stats != nullptr) {
+ calld->client_stats.reset(client_stats);
+ // Intercept completion.
+ calld->original_on_complete_for_send = batch->on_complete;
+ GRPC_CLOSURE_INIT(&calld->on_complete_for_send, on_complete_for_send,
+ calld, grpc_schedule_on_exec_ctx);
+ batch->on_complete = &calld->on_complete_for_send;
+ }
+ // Remove metadata so it doesn't go out on the wire.
+ grpc_metadata_batch_remove(
+ batch->payload->send_initial_metadata.send_initial_metadata,
+ client_stats_md);
}
}
- // Intercept completion of recv_initial_metadata.
- if (batch->recv_initial_metadata) {
- calld->original_recv_initial_metadata_ready =
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready;
- GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready,
- recv_initial_metadata_ready, calld,
- grpc_schedule_on_exec_ctx);
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
- &calld->recv_initial_metadata_ready;
- }
+ // Intercept completion of recv_initial_metadata.
+ if (batch->recv_initial_metadata) {
+ calld->original_recv_initial_metadata_ready =
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready;
+ GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready,
+ recv_initial_metadata_ready, calld,
+ grpc_schedule_on_exec_ctx);
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ &calld->recv_initial_metadata_ready;
+ }
// Chain to next filter.
grpc_call_next_op(elem, batch);
}
const grpc_channel_filter grpc_client_load_reporting_filter = {
- clr_start_transport_stream_op_batch,
+ clr_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- clr_init_call_elem,
+ clr_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- clr_destroy_call_elem,
+ clr_destroy_call_elem,
0, // sizeof(channel_data)
- clr_init_channel_elem,
- clr_destroy_channel_elem,
+ clr_init_channel_elem,
+ clr_destroy_channel_elem,
grpc_channel_next_get_info,
"client_load_reporting"};
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc
index ccfdb5f215..45d7dc50b2 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc
@@ -26,27 +26,27 @@
/// channel that uses pick_first to select from the list of balancer
/// addresses.
///
-/// When we get our initial update, we instantiate the internal *streaming*
-/// call to the LB server (whichever address pick_first chose). The call
-/// will be complete when either the balancer sends status or when we cancel
-/// the call (e.g., because we are shutting down). In needed, we retry the
-/// call. If we received at least one valid message from the server, a new
-/// call attempt will be made immediately; otherwise, we apply back-off
-/// delays between attempts.
+/// When we get our initial update, we instantiate the internal *streaming*
+/// call to the LB server (whichever address pick_first chose). The call
+/// will be complete when either the balancer sends status or when we cancel
+/// the call (e.g., because we are shutting down). In needed, we retry the
+/// call. If we received at least one valid message from the server, a new
+/// call attempt will be made immediately; otherwise, we apply back-off
+/// delays between attempts.
///
/// We maintain an internal round_robin policy instance for distributing
/// requests across backends. Whenever we receive a new serverlist from
/// the balancer, we update the round_robin policy with the new list of
/// addresses. If we cannot communicate with the balancer on startup,
/// however, we may enter fallback mode, in which case we will populate
-/// the child policy's addresses from the backend addresses returned by the
+/// the child policy's addresses from the backend addresses returned by the
/// resolver.
///
-/// Once a child policy instance is in place (and getting updated as described),
+/// Once a child policy instance is in place (and getting updated as described),
/// calls for a pick, a ping, or a cancellation will be serviced right
-/// away by forwarding them to the child policy instance. Any time there's no
-/// child policy available (i.e., right after the creation of the gRPCLB
-/// policy), pick requests are queued.
+/// away by forwarding them to the child policy instance. Any time there's no
+/// child policy available (i.e., right after the creation of the gRPCLB
+/// policy), pick requests are queued.
///
/// \see https://github.com/grpc/grpc/blob/master/doc/load-balancing.md for the
/// high level design and details.
@@ -115,15 +115,15 @@
#define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000
#define GRPC_ARG_GRPCLB_ADDRESS_LB_TOKEN "grpc.grpclb_address_lb_token"
-#define GRPC_ARG_GRPCLB_ADDRESS_CLIENT_STATS "grpc.grpclb_address_client_stats"
+#define GRPC_ARG_GRPCLB_ADDRESS_CLIENT_STATS "grpc.grpclb_address_client_stats"
namespace grpc_core {
TraceFlag grpc_lb_glb_trace(false, "glb");
-const char kGrpcLbClientStatsMetadataKey[] = "grpclb_client_stats";
-const char kGrpcLbLbTokenMetadataKey[] = "lb-token";
-
+const char kGrpcLbClientStatsMetadataKey[] = "grpclb_client_stats";
+const char kGrpcLbLbTokenMetadataKey[] = "lb-token";
+
const char kGrpcLbAddressAttributeKey[] = "grpclb";
namespace {
@@ -131,31 +131,31 @@ namespace {
constexpr char kGrpclb[] = "grpclb";
class GrpcLbConfig : public LoadBalancingPolicy::Config {
- public:
+ public:
GrpcLbConfig(RefCountedPtr<LoadBalancingPolicy::Config> child_policy,
TString service_name)
: child_policy_(std::move(child_policy)),
service_name_(std::move(service_name)) {}
- const char* name() const override { return kGrpclb; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> child_policy() const {
- return child_policy_;
- }
-
+ const char* name() const override { return kGrpclb; }
+
+ RefCountedPtr<LoadBalancingPolicy::Config> child_policy() const {
+ return child_policy_;
+ }
+
const TString& service_name() const { return service_name_; }
- private:
- RefCountedPtr<LoadBalancingPolicy::Config> child_policy_;
+ private:
+ RefCountedPtr<LoadBalancingPolicy::Config> child_policy_;
TString service_name_;
-};
-
+};
+
class GrpcLb : public LoadBalancingPolicy {
public:
explicit GrpcLb(Args args);
const char* name() const override { return kGrpclb; }
- void UpdateLocked(UpdateArgs args) override;
+ void UpdateLocked(UpdateArgs args) override;
void ResetBackoffLocked() override;
private:
@@ -164,7 +164,7 @@ class GrpcLb : public LoadBalancingPolicy {
public:
explicit BalancerCallState(
RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy);
- ~BalancerCallState();
+ ~BalancerCallState();
// It's the caller's responsibility to ensure that Orphan() is called from
// inside the combiner.
@@ -175,7 +175,7 @@ class GrpcLb : public LoadBalancingPolicy {
GrpcLbClientStats* client_stats() const { return client_stats_.get(); }
bool seen_initial_response() const { return seen_initial_response_; }
- bool seen_serverlist() const { return seen_serverlist_; }
+ bool seen_serverlist() const { return seen_serverlist_; }
private:
GrpcLb* grpclb_policy() const {
@@ -185,12 +185,12 @@ class GrpcLb : public LoadBalancingPolicy {
void ScheduleNextClientLoadReportLocked();
void SendClientLoadReportLocked();
- static void MaybeSendClientLoadReport(void* arg, grpc_error* error);
- static void ClientLoadReportDone(void* arg, grpc_error* error);
- static void OnInitialRequestSent(void* arg, grpc_error* error);
- static void OnBalancerMessageReceived(void* arg, grpc_error* error);
- static void OnBalancerStatusReceived(void* arg, grpc_error* error);
-
+ static void MaybeSendClientLoadReport(void* arg, grpc_error* error);
+ static void ClientLoadReportDone(void* arg, grpc_error* error);
+ static void OnInitialRequestSent(void* arg, grpc_error* error);
+ static void OnBalancerMessageReceived(void* arg, grpc_error* error);
+ static void OnBalancerStatusReceived(void* arg, grpc_error* error);
+
void MaybeSendClientLoadReportLocked(grpc_error* error);
void ClientLoadReportDoneLocked(grpc_error* error);
void OnInitialRequestSentLocked();
@@ -214,7 +214,7 @@ class GrpcLb : public LoadBalancingPolicy {
grpc_byte_buffer* recv_message_payload_ = nullptr;
grpc_closure lb_on_balancer_message_received_;
bool seen_initial_response_ = false;
- bool seen_serverlist_ = false;
+ bool seen_serverlist_ = false;
// recv_trailing_metadata
grpc_closure lb_on_balancer_status_received_;
@@ -269,86 +269,86 @@ class GrpcLb : public LoadBalancingPolicy {
RefCountedPtr<GrpcLbClientStats> client_stats_;
};
- class Serverlist : public RefCounted<Serverlist> {
- public:
- // Takes ownership of serverlist.
+ class Serverlist : public RefCounted<Serverlist> {
+ public:
+ // Takes ownership of serverlist.
explicit Serverlist(std::vector<GrpcLbServer> serverlist)
: serverlist_(std::move(serverlist)) {}
-
- bool operator==(const Serverlist& other) const;
-
+
+ bool operator==(const Serverlist& other) const;
+
const std::vector<GrpcLbServer>& serverlist() const { return serverlist_; }
-
- // Returns a text representation suitable for logging.
+
+ // Returns a text representation suitable for logging.
TString AsText() const;
-
- // Extracts all non-drop entries into a ServerAddressList.
- ServerAddressList GetServerAddressList(
- GrpcLbClientStats* client_stats) const;
-
- // Returns true if the serverlist contains at least one drop entry and
- // no backend address entries.
- bool ContainsAllDropEntries() const;
-
- // Returns the LB token to use for a drop, or null if the call
- // should not be dropped.
- //
- // Note: This is called from the picker, so it will be invoked in
+
+ // Extracts all non-drop entries into a ServerAddressList.
+ ServerAddressList GetServerAddressList(
+ GrpcLbClientStats* client_stats) const;
+
+ // Returns true if the serverlist contains at least one drop entry and
+ // no backend address entries.
+ bool ContainsAllDropEntries() const;
+
+ // Returns the LB token to use for a drop, or null if the call
+ // should not be dropped.
+ //
+ // Note: This is called from the picker, so it will be invoked in
// the channel's data plane mutex, NOT the control plane
// work_serializer. It should not be accessed by any other part of the LB
- // policy.
- const char* ShouldDrop();
-
- private:
+ // policy.
+ const char* ShouldDrop();
+
+ private:
std::vector<GrpcLbServer> serverlist_;
-
+
// Guarded by the channel's data plane mutex, NOT the control
// plane work_serializer. It should not be accessed by anything but the
- // picker via the ShouldDrop() method.
- size_t drop_index_ = 0;
- };
-
- class Picker : public SubchannelPicker {
- public:
- Picker(GrpcLb* parent, RefCountedPtr<Serverlist> serverlist,
- std::unique_ptr<SubchannelPicker> child_picker,
- RefCountedPtr<GrpcLbClientStats> client_stats)
- : parent_(parent),
- serverlist_(std::move(serverlist)),
- child_picker_(std::move(child_picker)),
- client_stats_(std::move(client_stats)) {}
-
- PickResult Pick(PickArgs args) override;
-
- private:
- // Storing the address for logging, but not holding a ref.
- // DO NOT DEFERENCE!
- GrpcLb* parent_;
-
- // Serverlist to be used for determining drops.
- RefCountedPtr<Serverlist> serverlist_;
-
- std::unique_ptr<SubchannelPicker> child_picker_;
- RefCountedPtr<GrpcLbClientStats> client_stats_;
- };
-
- class Helper : public ChannelControlHelper {
- public:
- explicit Helper(RefCountedPtr<GrpcLb> parent)
- : parent_(std::move(parent)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
+ // picker via the ShouldDrop() method.
+ size_t drop_index_ = 0;
+ };
+
+ class Picker : public SubchannelPicker {
+ public:
+ Picker(GrpcLb* parent, RefCountedPtr<Serverlist> serverlist,
+ std::unique_ptr<SubchannelPicker> child_picker,
+ RefCountedPtr<GrpcLbClientStats> client_stats)
+ : parent_(parent),
+ serverlist_(std::move(serverlist)),
+ child_picker_(std::move(child_picker)),
+ client_stats_(std::move(client_stats)) {}
+
+ PickResult Pick(PickArgs args) override;
+
+ private:
+ // Storing the address for logging, but not holding a ref.
+ // DO NOT DEFERENCE!
+ GrpcLb* parent_;
+
+ // Serverlist to be used for determining drops.
+ RefCountedPtr<Serverlist> serverlist_;
+
+ std::unique_ptr<SubchannelPicker> child_picker_;
+ RefCountedPtr<GrpcLbClientStats> client_stats_;
+ };
+
+ class Helper : public ChannelControlHelper {
+ public:
+ explicit Helper(RefCountedPtr<GrpcLb> parent)
+ : parent_(std::move(parent)) {}
+
+ RefCountedPtr<SubchannelInterface> CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) override;
void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override;
- void RequestReresolution() override;
+ std::unique_ptr<SubchannelPicker> picker) override;
+ void RequestReresolution() override;
void AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) override;
-
- private:
- RefCountedPtr<GrpcLb> parent_;
- };
-
+
+ private:
+ RefCountedPtr<GrpcLb> parent_;
+ };
+
class StateWatcher : public AsyncConnectivityStateWatcherInterface {
public:
explicit StateWatcher(RefCountedPtr<GrpcLb> parent)
@@ -385,31 +385,31 @@ class GrpcLb : public LoadBalancingPolicy {
void ShutdownLocked() override;
- // Helper functions used in UpdateLocked().
- void ProcessAddressesAndChannelArgsLocked(const ServerAddressList& addresses,
- const grpc_channel_args& args);
+ // Helper functions used in UpdateLocked().
+ void ProcessAddressesAndChannelArgsLocked(const ServerAddressList& addresses,
+ const grpc_channel_args& args);
static ServerAddressList AddNullLbTokenToAddresses(
const ServerAddressList& addresses);
- void CancelBalancerChannelConnectivityWatchLocked();
+ void CancelBalancerChannelConnectivityWatchLocked();
- // Methods for dealing with fallback state.
- void MaybeEnterFallbackModeAfterStartup();
- static void OnFallbackTimer(void* arg, grpc_error* error);
+ // Methods for dealing with fallback state.
+ void MaybeEnterFallbackModeAfterStartup();
+ static void OnFallbackTimer(void* arg, grpc_error* error);
void OnFallbackTimerLocked(grpc_error* error);
-
- // Methods for dealing with the balancer call.
+
+ // Methods for dealing with the balancer call.
void StartBalancerCallLocked();
void StartBalancerCallRetryTimerLocked();
- static void OnBalancerCallRetryTimer(void* arg, grpc_error* error);
+ static void OnBalancerCallRetryTimer(void* arg, grpc_error* error);
void OnBalancerCallRetryTimerLocked(grpc_error* error);
- // Methods for dealing with the child policy.
- grpc_channel_args* CreateChildPolicyArgsLocked(
- bool is_backend_from_grpclb_load_balancer);
- OrphanablePtr<LoadBalancingPolicy> CreateChildPolicyLocked(
+ // Methods for dealing with the child policy.
+ grpc_channel_args* CreateChildPolicyArgsLocked(
+ bool is_backend_from_grpclb_load_balancer);
+ OrphanablePtr<LoadBalancingPolicy> CreateChildPolicyLocked(
const grpc_channel_args* args);
- void CreateOrUpdateChildPolicyLocked();
+ void CreateOrUpdateChildPolicyLocked();
// Who the client is trying to communicate with.
const char* server_name_ = nullptr;
@@ -446,55 +446,55 @@ class GrpcLb : public LoadBalancingPolicy {
// The deserialized response from the balancer. May be nullptr until one
// such response has arrived.
- RefCountedPtr<Serverlist> serverlist_;
+ RefCountedPtr<Serverlist> serverlist_;
- // Whether we're in fallback mode.
- bool fallback_mode_ = false;
+ // Whether we're in fallback mode.
+ bool fallback_mode_ = false;
// The backend addresses from the resolver.
- ServerAddressList fallback_backend_addresses_;
- // State for fallback-at-startup checks.
- // Timeout after startup after which we will go into fallback mode if
- // we have not received a serverlist from the balancer.
- int fallback_at_startup_timeout_ = 0;
- bool fallback_at_startup_checks_pending_ = false;
+ ServerAddressList fallback_backend_addresses_;
+ // State for fallback-at-startup checks.
+ // Timeout after startup after which we will go into fallback mode if
+ // we have not received a serverlist from the balancer.
+ int fallback_at_startup_timeout_ = 0;
+ bool fallback_at_startup_checks_pending_ = false;
grpc_timer lb_fallback_timer_;
grpc_closure lb_on_fallback_;
- // The child policy to use for the backends.
- OrphanablePtr<LoadBalancingPolicy> child_policy_;
- // Child policy in state READY.
- bool child_policy_ready_ = false;
+ // The child policy to use for the backends.
+ OrphanablePtr<LoadBalancingPolicy> child_policy_;
+ // Child policy in state READY.
+ bool child_policy_ready_ = false;
};
//
-// GrpcLb::Serverlist
+// GrpcLb::Serverlist
//
-bool GrpcLb::Serverlist::operator==(const Serverlist& other) const {
+bool GrpcLb::Serverlist::operator==(const Serverlist& other) const {
return serverlist_ == other.serverlist_;
}
-
+
void ParseServer(const GrpcLbServer& server, grpc_resolved_address* addr) {
- memset(addr, 0, sizeof(*addr));
+ memset(addr, 0, sizeof(*addr));
if (server.drop) return;
const uint16_t netorder_port = grpc_htons((uint16_t)server.port);
- /* the addresses are given in binary format (a in(6)_addr struct) in
- * server->ip_address.bytes. */
+ /* the addresses are given in binary format (a in(6)_addr struct) in
+ * server->ip_address.bytes. */
if (server.ip_size == 4) {
- addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
- grpc_sockaddr_in* addr4 = reinterpret_cast<grpc_sockaddr_in*>(&addr->addr);
- addr4->sin_family = GRPC_AF_INET;
+ addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
+ grpc_sockaddr_in* addr4 = reinterpret_cast<grpc_sockaddr_in*>(&addr->addr);
+ addr4->sin_family = GRPC_AF_INET;
memcpy(&addr4->sin_addr, server.ip_addr, server.ip_size);
- addr4->sin_port = netorder_port;
+ addr4->sin_port = netorder_port;
} else if (server.ip_size == 16) {
- addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
- grpc_sockaddr_in6* addr6 = (grpc_sockaddr_in6*)&addr->addr;
- addr6->sin6_family = GRPC_AF_INET6;
+ addr->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
+ grpc_sockaddr_in6* addr6 = (grpc_sockaddr_in6*)&addr->addr;
+ addr6->sin6_family = GRPC_AF_INET6;
memcpy(&addr6->sin6_addr, server.ip_addr, server.ip_size);
- addr6->sin6_port = netorder_port;
+ addr6->sin6_port = netorder_port;
}
}
-
+
TString GrpcLb::Serverlist::AsText() const {
std::vector<TString> entries;
for (size_t i = 0; i < serverlist_.size(); ++i) {
@@ -502,17 +502,17 @@ TString GrpcLb::Serverlist::AsText() const {
TString ipport;
if (server.drop) {
ipport = "(drop)";
- } else {
- grpc_resolved_address addr;
- ParseServer(server, &addr);
+ } else {
+ grpc_resolved_address addr;
+ ParseServer(server, &addr);
ipport = grpc_sockaddr_to_string(&addr, false);
- }
+ }
entries.push_back(y_absl::StrFormat(" %" PRIuPTR ": %s token=%s\n", i,
ipport, server.load_balance_token));
- }
+ }
return y_absl::StrJoin(entries, "");
-}
-
+}
+
bool IsServerValid(const GrpcLbServer& server, size_t idx, bool log) {
if (server.drop) return false;
if (GPR_UNLIKELY(server.port >> 16 != 0)) {
@@ -535,9 +535,9 @@ bool IsServerValid(const GrpcLbServer& server, size_t idx, bool log) {
return true;
}
-// Returns addresses extracted from the serverlist.
-ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
- GrpcLbClientStats* client_stats) const {
+// Returns addresses extracted from the serverlist.
+ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
+ GrpcLbClientStats* client_stats) const {
RefCountedPtr<GrpcLbClientStats> stats;
if (client_stats != nullptr) stats = client_stats->Ref();
ServerAddressList addresses;
@@ -569,46 +569,46 @@ ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
return addresses;
}
-bool GrpcLb::Serverlist::ContainsAllDropEntries() const {
+bool GrpcLb::Serverlist::ContainsAllDropEntries() const {
if (serverlist_.empty()) return false;
for (const GrpcLbServer& server : serverlist_) {
if (!server.drop) return false;
- }
- return true;
-}
-
-const char* GrpcLb::Serverlist::ShouldDrop() {
+ }
+ return true;
+}
+
+const char* GrpcLb::Serverlist::ShouldDrop() {
if (serverlist_.empty()) return nullptr;
GrpcLbServer& server = serverlist_[drop_index_];
drop_index_ = (drop_index_ + 1) % serverlist_.size();
return server.drop ? server.load_balance_token : nullptr;
-}
-
+}
+
//
-// GrpcLb::Picker
-//
-
-GrpcLb::PickResult GrpcLb::Picker::Pick(PickArgs args) {
- PickResult result;
- // Check if we should drop the call.
- const char* drop_token = serverlist_->ShouldDrop();
- if (drop_token != nullptr) {
- // Update client load reporting stats to indicate the number of
- // dropped calls. Note that we have to do this here instead of in
- // the client_load_reporting filter, because we do not create a
- // subchannel call (and therefore no client_load_reporting filter)
- // for dropped calls.
- if (client_stats_ != nullptr) {
- client_stats_->AddCallDropped(drop_token);
- }
- result.type = PickResult::PICK_COMPLETE;
- return result;
- }
- // Forward pick to child policy.
- result = child_picker_->Pick(args);
- // If pick succeeded, add LB token to initial metadata.
- if (result.type == PickResult::PICK_COMPLETE &&
- result.subchannel != nullptr) {
+// GrpcLb::Picker
+//
+
+GrpcLb::PickResult GrpcLb::Picker::Pick(PickArgs args) {
+ PickResult result;
+ // Check if we should drop the call.
+ const char* drop_token = serverlist_->ShouldDrop();
+ if (drop_token != nullptr) {
+ // Update client load reporting stats to indicate the number of
+ // dropped calls. Note that we have to do this here instead of in
+ // the client_load_reporting filter, because we do not create a
+ // subchannel call (and therefore no client_load_reporting filter)
+ // for dropped calls.
+ if (client_stats_ != nullptr) {
+ client_stats_->AddCallDropped(drop_token);
+ }
+ result.type = PickResult::PICK_COMPLETE;
+ return result;
+ }
+ // Forward pick to child policy.
+ result = child_picker_->Pick(args);
+ // If pick succeeded, add LB token to initial metadata.
+ if (result.type == PickResult::PICK_COMPLETE &&
+ result.subchannel != nullptr) {
const TokenAndClientStatsAttribute* attribute =
static_cast<const TokenAndClientStatsAttribute*>(
result.subchannel->GetAttribute(kGrpcLbAddressAttributeKey));
@@ -617,21 +617,21 @@ GrpcLb::PickResult GrpcLb::Picker::Pick(PickArgs args) {
parent_, this, result.subchannel.get());
abort();
}
- // Encode client stats object into metadata for use by
- // client_load_reporting filter.
+ // Encode client stats object into metadata for use by
+ // client_load_reporting filter.
GrpcLbClientStats* client_stats = attribute->client_stats();
if (client_stats != nullptr) {
- client_stats->Ref().release(); // Ref passed via metadata.
- // The metadata value is a hack: we pretend the pointer points to
- // a string and rely on the client_load_reporting filter to know
- // how to interpret it.
- args.initial_metadata->Add(
- kGrpcLbClientStatsMetadataKey,
+ client_stats->Ref().release(); // Ref passed via metadata.
+ // The metadata value is a hack: we pretend the pointer points to
+ // a string and rely on the client_load_reporting filter to know
+ // how to interpret it.
+ args.initial_metadata->Add(
+ kGrpcLbClientStatsMetadataKey,
y_absl::string_view(reinterpret_cast<const char*>(client_stats), 0));
- // Update calls-started.
- client_stats->AddCallStarted();
- }
- // Encode the LB token in metadata.
+ // Update calls-started.
+ client_stats->AddCallStarted();
+ }
+ // Encode the LB token in metadata.
// Create a new copy on the call arena, since the subchannel list
// may get refreshed between when we return this pick and when the
// initial metadata goes out on the wire.
@@ -639,100 +639,100 @@ GrpcLb::PickResult GrpcLb::Picker::Pick(PickArgs args) {
args.call_state->Alloc(attribute->lb_token().size() + 1));
strcpy(lb_token, attribute->lb_token().c_str());
args.initial_metadata->Add(kGrpcLbLbTokenMetadataKey, lb_token);
- }
- return result;
-}
-
-//
-// GrpcLb::Helper
-//
-
-RefCountedPtr<SubchannelInterface> GrpcLb::Helper::CreateSubchannel(
+ }
+ return result;
+}
+
+//
+// GrpcLb::Helper
+//
+
+RefCountedPtr<SubchannelInterface> GrpcLb::Helper::CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) {
if (parent_->shutting_down_) return nullptr;
return parent_->channel_control_helper()->CreateSubchannel(std::move(address),
args);
-}
-
-void GrpcLb::Helper::UpdateState(grpc_connectivity_state state,
+}
+
+void GrpcLb::Helper::UpdateState(grpc_connectivity_state state,
const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) {
- if (parent_->shutting_down_) return;
- // Record whether child policy reports READY.
- parent_->child_policy_ready_ = state == GRPC_CHANNEL_READY;
- // Enter fallback mode if needed.
- parent_->MaybeEnterFallbackModeAfterStartup();
- // There are three cases to consider here:
- // 1. We're in fallback mode. In this case, we're always going to use
- // the child policy's result, so we pass its picker through as-is.
- // 2. The serverlist contains only drop entries. In this case, we
- // want to use our own picker so that we can return the drops.
- // 3. Not in fallback mode and serverlist is not all drops (i.e., it
- // may be empty or contain at least one backend address). There are
- // two sub-cases:
- // a. The child policy is reporting state READY. In this case, we wrap
- // the child's picker in our own, so that we can handle drops and LB
- // token metadata for each pick.
- // b. The child policy is reporting a state other than READY. In this
- // case, we don't want to use our own picker, because we don't want
- // to process drops for picks that yield a QUEUE result; this would
- // result in dropping too many calls, since we will see the
- // queued picks multiple times, and we'd consider each one a
- // separate call for the drop calculation.
- //
- // Cases 1 and 3b: return picker from the child policy as-is.
- if (parent_->serverlist_ == nullptr ||
- (!parent_->serverlist_->ContainsAllDropEntries() &&
- state != GRPC_CHANNEL_READY)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
- gpr_log(GPR_INFO,
+ std::unique_ptr<SubchannelPicker> picker) {
+ if (parent_->shutting_down_) return;
+ // Record whether child policy reports READY.
+ parent_->child_policy_ready_ = state == GRPC_CHANNEL_READY;
+ // Enter fallback mode if needed.
+ parent_->MaybeEnterFallbackModeAfterStartup();
+ // There are three cases to consider here:
+ // 1. We're in fallback mode. In this case, we're always going to use
+ // the child policy's result, so we pass its picker through as-is.
+ // 2. The serverlist contains only drop entries. In this case, we
+ // want to use our own picker so that we can return the drops.
+ // 3. Not in fallback mode and serverlist is not all drops (i.e., it
+ // may be empty or contain at least one backend address). There are
+ // two sub-cases:
+ // a. The child policy is reporting state READY. In this case, we wrap
+ // the child's picker in our own, so that we can handle drops and LB
+ // token metadata for each pick.
+ // b. The child policy is reporting a state other than READY. In this
+ // case, we don't want to use our own picker, because we don't want
+ // to process drops for picks that yield a QUEUE result; this would
+ // result in dropping too many calls, since we will see the
+ // queued picks multiple times, and we'd consider each one a
+ // separate call for the drop calculation.
+ //
+ // Cases 1 and 3b: return picker from the child policy as-is.
+ if (parent_->serverlist_ == nullptr ||
+ (!parent_->serverlist_->ContainsAllDropEntries() &&
+ state != GRPC_CHANNEL_READY)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ gpr_log(GPR_INFO,
"[grpclb %p helper %p] state=%s (%s) passing "
"child picker %p as-is",
parent_.get(), this, ConnectivityStateName(state),
status.ToString().c_str(), picker.get());
- }
+ }
parent_->channel_control_helper()->UpdateState(state, status,
std::move(picker));
- return;
- }
- // Cases 2 and 3a: wrap picker from the child in our own picker.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ return;
+ }
+ // Cases 2 and 3a: wrap picker from the child in our own picker.
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"[grpclb %p helper %p] state=%s (%s) wrapping child "
"picker %p",
parent_.get(), this, ConnectivityStateName(state),
status.ToString().c_str(), picker.get());
- }
- RefCountedPtr<GrpcLbClientStats> client_stats;
- if (parent_->lb_calld_ != nullptr &&
- parent_->lb_calld_->client_stats() != nullptr) {
- client_stats = parent_->lb_calld_->client_stats()->Ref();
- }
- parent_->channel_control_helper()->UpdateState(
+ }
+ RefCountedPtr<GrpcLbClientStats> client_stats;
+ if (parent_->lb_calld_ != nullptr &&
+ parent_->lb_calld_->client_stats() != nullptr) {
+ client_stats = parent_->lb_calld_->client_stats()->Ref();
+ }
+ parent_->channel_control_helper()->UpdateState(
state, status,
y_absl::make_unique<Picker>(parent_.get(), parent_->serverlist_,
- std::move(picker), std::move(client_stats)));
-}
-
-void GrpcLb::Helper::RequestReresolution() {
- if (parent_->shutting_down_) return;
- // If we are talking to a balancer, we expect to get updated addresses
- // from the balancer, so we can ignore the re-resolution request from
- // the child policy. Otherwise, pass the re-resolution request up to the
- // channel.
- if (parent_->lb_calld_ == nullptr ||
- !parent_->lb_calld_->seen_initial_response()) {
- parent_->channel_control_helper()->RequestReresolution();
- }
-}
-
+ std::move(picker), std::move(client_stats)));
+}
+
+void GrpcLb::Helper::RequestReresolution() {
+ if (parent_->shutting_down_) return;
+ // If we are talking to a balancer, we expect to get updated addresses
+ // from the balancer, so we can ignore the re-resolution request from
+ // the child policy. Otherwise, pass the re-resolution request up to the
+ // channel.
+ if (parent_->lb_calld_ == nullptr ||
+ !parent_->lb_calld_->seen_initial_response()) {
+ parent_->channel_control_helper()->RequestReresolution();
+ }
+}
+
void GrpcLb::Helper::AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) {
if (parent_->shutting_down_) return;
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
-}
-
-//
+ parent_->channel_control_helper()->AddTraceEvent(severity, message);
+}
+
+//
// GrpcLb::BalancerCallState
//
@@ -766,7 +766,7 @@ GrpcLb::BalancerCallState::BalancerCallState(
GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD,
nullptr, deadline, nullptr);
// Init the LB call request payload.
- upb::Arena arena;
+ upb::Arena arena;
grpc_slice request_payload_slice = GrpcLbRequestCreate(
grpclb_policy()->config_->service_name().empty()
? grpclb_policy()->server_name_
@@ -807,7 +807,7 @@ void GrpcLb::BalancerCallState::Orphan() {
void GrpcLb::BalancerCallState::StartQuery() {
GPR_ASSERT(lb_call_ != nullptr);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "[grpclb %p] lb_calld=%p: Starting LB call %p",
grpclb_policy_.get(), this, lb_call_);
}
@@ -819,8 +819,8 @@ void GrpcLb::BalancerCallState::StartQuery() {
grpc_op* op = ops;
op->op = GRPC_OP_SEND_INITIAL_METADATA;
op->data.send_initial_metadata.count = 0;
- op->flags = GRPC_INITIAL_METADATA_WAIT_FOR_READY |
- GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET;
+ op->flags = GRPC_INITIAL_METADATA_WAIT_FOR_READY |
+ GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET;
op->reserved = nullptr;
op++;
// Op: send request message.
@@ -876,27 +876,27 @@ void GrpcLb::BalancerCallState::StartQuery() {
call_error = grpc_call_start_batch_and_execute(
lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_status_received_);
GPR_ASSERT(GRPC_CALL_OK == call_error);
-}
+}
void GrpcLb::BalancerCallState::ScheduleNextClientLoadReportLocked() {
const grpc_millis next_client_load_report_time =
ExecCtx::Get()->Now() + client_stats_report_interval_;
- GRPC_CLOSURE_INIT(&client_load_report_closure_, MaybeSendClientLoadReport,
- this, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&client_load_report_closure_, MaybeSendClientLoadReport,
+ this, grpc_schedule_on_exec_ctx);
grpc_timer_init(&client_load_report_timer_, next_client_load_report_time,
&client_load_report_closure_);
client_load_report_timer_callback_pending_ = true;
}
-void GrpcLb::BalancerCallState::MaybeSendClientLoadReport(void* arg,
- grpc_error* error) {
- BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
+void GrpcLb::BalancerCallState::MaybeSendClientLoadReport(void* arg,
+ grpc_error* error) {
+ BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
lb_calld->grpclb_policy()->work_serializer()->Run(
[lb_calld, error]() { lb_calld->MaybeSendClientLoadReportLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void GrpcLb::BalancerCallState::MaybeSendClientLoadReportLocked(
grpc_error* error) {
client_load_report_timer_callback_pending_ = false;
@@ -955,8 +955,8 @@ void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
memset(&op, 0, sizeof(op));
op.op = GRPC_OP_SEND_MESSAGE;
op.data.send_message.send_message = send_message_payload_;
- GRPC_CLOSURE_INIT(&client_load_report_closure_, ClientLoadReportDone, this,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&client_load_report_closure_, ClientLoadReportDone, this,
+ grpc_schedule_on_exec_ctx);
grpc_call_error call_error = grpc_call_start_batch_and_execute(
lb_call_, &op, 1, &client_load_report_closure_);
if (GPR_UNLIKELY(call_error != GRPC_CALL_OK)) {
@@ -967,15 +967,15 @@ void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
}
}
-void GrpcLb::BalancerCallState::ClientLoadReportDone(void* arg,
- grpc_error* error) {
- BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
+void GrpcLb::BalancerCallState::ClientLoadReportDone(void* arg,
+ grpc_error* error) {
+ BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
lb_calld->grpclb_policy()->work_serializer()->Run(
[lb_calld, error]() { lb_calld->ClientLoadReportDoneLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void GrpcLb::BalancerCallState::ClientLoadReportDoneLocked(grpc_error* error) {
grpc_byte_buffer_destroy(send_message_payload_);
send_message_payload_ = nullptr;
@@ -987,13 +987,13 @@ void GrpcLb::BalancerCallState::ClientLoadReportDoneLocked(grpc_error* error) {
ScheduleNextClientLoadReportLocked();
}
-void GrpcLb::BalancerCallState::OnInitialRequestSent(void* arg,
+void GrpcLb::BalancerCallState::OnInitialRequestSent(void* arg,
grpc_error* /*error*/) {
BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
lb_calld->grpclb_policy()->work_serializer()->Run(
[lb_calld]() { lb_calld->OnInitialRequestSentLocked(); }, DEBUG_LOCATION);
-}
-
+}
+
void GrpcLb::BalancerCallState::OnInitialRequestSentLocked() {
grpc_byte_buffer_destroy(send_message_payload_);
send_message_payload_ = nullptr;
@@ -1008,12 +1008,12 @@ void GrpcLb::BalancerCallState::OnInitialRequestSentLocked() {
void GrpcLb::BalancerCallState::OnBalancerMessageReceived(
void* arg, grpc_error* /*error*/) {
- BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
+ BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
lb_calld->grpclb_policy()->work_serializer()->Run(
[lb_calld]() { lb_calld->OnBalancerMessageReceivedLocked(); },
DEBUG_LOCATION);
-}
-
+}
+
void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() {
// Null payload means the LB call was cancelled.
if (this != grpclb_policy()->lb_calld_.get() ||
@@ -1028,7 +1028,7 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() {
grpc_byte_buffer_destroy(recv_message_payload_);
recv_message_payload_ = nullptr;
GrpcLbResponse response;
- upb::Arena arena;
+ upb::Arena arena;
if (!GrpcLbResponseParse(response_slice, arena.ptr(), &response) ||
(response.type == response.INITIAL && seen_initial_response_)) {
char* response_slice_str =
@@ -1169,19 +1169,19 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() {
}
}
-void GrpcLb::BalancerCallState::OnBalancerStatusReceived(void* arg,
- grpc_error* error) {
- BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
+void GrpcLb::BalancerCallState::OnBalancerStatusReceived(void* arg,
+ grpc_error* error) {
+ BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
GRPC_ERROR_REF(error); // owned by lambda
lb_calld->grpclb_policy()->work_serializer()->Run(
[lb_calld, error]() { lb_calld->OnBalancerStatusReceivedLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
grpc_error* error) {
GPR_ASSERT(lb_call_ != nullptr);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
char* status_details = grpc_slice_to_c_string(lb_call_status_details_);
gpr_log(GPR_INFO,
"[grpclb %p] lb_calld=%p: Status from LB server received. "
@@ -1195,24 +1195,24 @@ void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
// we want to retry connecting. Otherwise, we have deliberately ended this
// call and no further action is required.
if (this == grpclb_policy()->lb_calld_.get()) {
- // If the fallback-at-startup checks are pending, go into fallback mode
- // immediately. This short-circuits the timeout for the fallback-at-startup
- // case.
+ // If the fallback-at-startup checks are pending, go into fallback mode
+ // immediately. This short-circuits the timeout for the fallback-at-startup
+ // case.
if (grpclb_policy()->fallback_at_startup_checks_pending_) {
GPR_ASSERT(!seen_serverlist_);
- gpr_log(GPR_INFO,
- "[grpclb %p] Balancer call finished without receiving "
- "serverlist; entering fallback mode",
+ gpr_log(GPR_INFO,
+ "[grpclb %p] Balancer call finished without receiving "
+ "serverlist; entering fallback mode",
grpclb_policy());
grpclb_policy()->fallback_at_startup_checks_pending_ = false;
grpc_timer_cancel(&grpclb_policy()->lb_fallback_timer_);
grpclb_policy()->CancelBalancerChannelConnectivityWatchLocked();
grpclb_policy()->fallback_mode_ = true;
grpclb_policy()->CreateOrUpdateChildPolicyLocked();
- } else {
- // This handles the fallback-after-startup case.
+ } else {
+ // This handles the fallback-after-startup case.
grpclb_policy()->MaybeEnterFallbackModeAfterStartup();
- }
+ }
grpclb_policy()->lb_calld_.reset();
GPR_ASSERT(!grpclb_policy()->shutting_down_);
grpclb_policy()->channel_control_helper()->RequestReresolution();
@@ -1270,16 +1270,16 @@ grpc_channel_args* BuildBalancerChannelArgs(
// the LB channel.
GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
// The LB channel should use the authority indicated by the target
- // authority table (see \a ModifyGrpclbBalancerChannelArgs),
+ // authority table (see \a ModifyGrpclbBalancerChannelArgs),
// as opposed to the authority from the parent channel.
GRPC_ARG_DEFAULT_AUTHORITY,
// Just as for \a GRPC_ARG_DEFAULT_AUTHORITY, the LB channel should be
// treated as a stand-alone channel and not inherit this argument from the
// args of the parent channel.
GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
- // Don't want to pass down channelz node from parent; the balancer
- // channel will get its own.
- GRPC_ARG_CHANNELZ_CHANNEL_NODE,
+ // Don't want to pass down channelz node from parent; the balancer
+ // channel will get its own.
+ GRPC_ARG_CHANNELZ_CHANNEL_NODE,
};
// Channel args to add.
y_absl::InlinedVector<grpc_arg, 3> args_to_add = {
@@ -1296,17 +1296,17 @@ grpc_channel_args* BuildBalancerChannelArgs(
};
// Construct channel args.
grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
- args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), args_to_add.data(),
- args_to_add.size());
+ args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), args_to_add.data(),
+ args_to_add.size());
// Make any necessary modifications for security.
- return ModifyGrpclbBalancerChannelArgs(addresses, new_args);
+ return ModifyGrpclbBalancerChannelArgs(addresses, new_args);
}
//
// ctor and dtor
//
-GrpcLb::GrpcLb(Args args)
+GrpcLb::GrpcLb(Args args)
: LoadBalancingPolicy(std::move(args)),
response_generator_(MakeRefCounted<FakeResolverResponseGenerator>()),
lb_call_backoff_(
@@ -1329,7 +1329,7 @@ GrpcLb::GrpcLb(Args args)
grpc_uri* uri = grpc_uri_parse(server_uri, true);
GPR_ASSERT(uri->path[0] != '\0');
server_name_ = gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"[grpclb %p] Will use '%s' as the server name for LB request.",
this, server_name_);
@@ -1338,9 +1338,9 @@ GrpcLb::GrpcLb(Args args)
// Record LB call timeout.
arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_CALL_TIMEOUT_MS);
lb_call_timeout_ms_ = grpc_channel_arg_get_integer(arg, {0, 0, INT_MAX});
- // Record fallback-at-startup timeout.
+ // Record fallback-at-startup timeout.
arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS);
- fallback_at_startup_timeout_ = grpc_channel_arg_get_integer(
+ fallback_at_startup_timeout_ = grpc_channel_arg_get_integer(
arg, {GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS, 0, INT_MAX});
}
@@ -1355,16 +1355,16 @@ void GrpcLb::ShutdownLocked() {
if (retry_timer_callback_pending_) {
grpc_timer_cancel(&lb_call_retry_timer_);
}
- if (fallback_at_startup_checks_pending_) {
+ if (fallback_at_startup_checks_pending_) {
fallback_at_startup_checks_pending_ = false;
grpc_timer_cancel(&lb_fallback_timer_);
- CancelBalancerChannelConnectivityWatchLocked();
+ CancelBalancerChannelConnectivityWatchLocked();
}
- if (child_policy_ != nullptr) {
- grpc_pollset_set_del_pollset_set(child_policy_->interested_parties(),
- interested_parties());
+ if (child_policy_ != nullptr) {
+ grpc_pollset_set_del_pollset_set(child_policy_->interested_parties(),
+ interested_parties());
child_policy_.reset();
- }
+ }
// We destroy the LB channel here instead of in our destructor because
// destroying the channel triggers a last callback to
// OnBalancerChannelConnectivityChangedLocked(), and we need to be
@@ -1389,45 +1389,45 @@ void GrpcLb::ResetBackoffLocked() {
if (lb_channel_ != nullptr) {
grpc_channel_reset_connect_backoff(lb_channel_);
}
- if (child_policy_ != nullptr) {
- child_policy_->ResetBackoffLocked();
+ if (child_policy_ != nullptr) {
+ child_policy_->ResetBackoffLocked();
}
}
-void GrpcLb::UpdateLocked(UpdateArgs args) {
- const bool is_initial_update = lb_channel_ == nullptr;
+void GrpcLb::UpdateLocked(UpdateArgs args) {
+ const bool is_initial_update = lb_channel_ == nullptr;
config_ = args.config;
GPR_ASSERT(config_ != nullptr);
- ProcessAddressesAndChannelArgsLocked(args.addresses, *args.args);
- // Update the existing child policy.
- if (child_policy_ != nullptr) CreateOrUpdateChildPolicyLocked();
- // If this is the initial update, start the fallback-at-startup checks
- // and the balancer call.
- if (is_initial_update) {
- fallback_at_startup_checks_pending_ = true;
- // Start timer.
- grpc_millis deadline = ExecCtx::Get()->Now() + fallback_at_startup_timeout_;
- Ref(DEBUG_LOCATION, "on_fallback_timer").release(); // Ref for callback
- grpc_timer_init(&lb_fallback_timer_, deadline, &lb_on_fallback_);
- // Start watching the channel's connectivity state. If the channel
- // goes into state TRANSIENT_FAILURE before the timer fires, we go into
- // fallback mode even if the fallback timeout has not elapsed.
- grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
- grpc_channel_get_channel_stack(lb_channel_));
- GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
- // Ref held by callback.
+ ProcessAddressesAndChannelArgsLocked(args.addresses, *args.args);
+ // Update the existing child policy.
+ if (child_policy_ != nullptr) CreateOrUpdateChildPolicyLocked();
+ // If this is the initial update, start the fallback-at-startup checks
+ // and the balancer call.
+ if (is_initial_update) {
+ fallback_at_startup_checks_pending_ = true;
+ // Start timer.
+ grpc_millis deadline = ExecCtx::Get()->Now() + fallback_at_startup_timeout_;
+ Ref(DEBUG_LOCATION, "on_fallback_timer").release(); // Ref for callback
+ grpc_timer_init(&lb_fallback_timer_, deadline, &lb_on_fallback_);
+ // Start watching the channel's connectivity state. If the channel
+ // goes into state TRANSIENT_FAILURE before the timer fires, we go into
+ // fallback mode even if the fallback timeout has not elapsed.
+ grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
+ grpc_channel_get_channel_stack(lb_channel_));
+ GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
+ // Ref held by callback.
watcher_ = new StateWatcher(Ref(DEBUG_LOCATION, "StateWatcher"));
grpc_client_channel_start_connectivity_watch(
client_channel_elem, GRPC_CHANNEL_IDLE,
OrphanablePtr<AsyncConnectivityStateWatcherInterface>(watcher_));
- // Start balancer call.
- StartBalancerCallLocked();
+ // Start balancer call.
+ StartBalancerCallLocked();
}
}
-//
-// helpers for UpdateLocked()
-//
+//
+// helpers for UpdateLocked()
+//
ServerAddressList GrpcLb::AddNullLbTokenToAddresses(
const ServerAddressList& addresses) {
@@ -1440,8 +1440,8 @@ ServerAddressList GrpcLb::AddNullLbTokenToAddresses(
return addresses_out;
}
-void GrpcLb::ProcessAddressesAndChannelArgsLocked(
- const ServerAddressList& addresses, const grpc_channel_args& args) {
+void GrpcLb::ProcessAddressesAndChannelArgsLocked(
+ const ServerAddressList& addresses, const grpc_channel_args& args) {
// Update fallback address list.
fallback_backend_addresses_ = AddNullLbTokenToAddresses(addresses);
// Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args,
@@ -1454,8 +1454,8 @@ void GrpcLb::ProcessAddressesAndChannelArgsLocked(
&args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
// Construct args for balancer channel.
ServerAddressList balancer_addresses = ExtractBalancerAddresses(args);
- grpc_channel_args* lb_channel_args = BuildBalancerChannelArgs(
- balancer_addresses, response_generator_.get(), &args);
+ grpc_channel_args* lb_channel_args = BuildBalancerChannelArgs(
+ balancer_addresses, response_generator_.get(), &args);
// Create balancer channel if needed.
if (lb_channel_ == nullptr) {
TString uri_str = y_absl::StrCat("fake:///", server_name_);
@@ -1475,19 +1475,19 @@ void GrpcLb::ProcessAddressesAndChannelArgsLocked(
}
// Propagate updates to the LB channel (pick_first) through the fake
// resolver.
- Resolver::Result result;
- result.addresses = std::move(balancer_addresses);
- result.args = lb_channel_args;
- response_generator_->SetResponse(std::move(result));
+ Resolver::Result result;
+ result.addresses = std::move(balancer_addresses);
+ result.args = lb_channel_args;
+ response_generator_->SetResponse(std::move(result));
}
-void GrpcLb::CancelBalancerChannelConnectivityWatchLocked() {
- grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
- grpc_channel_get_channel_stack(lb_channel_));
- GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
+void GrpcLb::CancelBalancerChannelConnectivityWatchLocked() {
+ grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
+ grpc_channel_get_channel_stack(lb_channel_));
+ GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
grpc_client_channel_stop_connectivity_watch(client_channel_elem, watcher_);
-}
-
+}
+
//
// code for balancer channel and call
//
@@ -1498,7 +1498,7 @@ void GrpcLb::StartBalancerCallLocked() {
// Init the LB call data.
GPR_ASSERT(lb_calld_ == nullptr);
lb_calld_ = MakeOrphanable<BalancerCallState>(Ref());
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"[grpclb %p] Query for backends (lb_channel: %p, lb_calld: %p)",
this, lb_channel_, lb_calld_.get());
@@ -1508,7 +1508,7 @@ void GrpcLb::StartBalancerCallLocked() {
void GrpcLb::StartBalancerCallRetryTimerLocked() {
grpc_millis next_try = lb_call_backoff_.NextAttemptTime();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "[grpclb %p] Connection to LB server lost...", this);
grpc_millis timeout = next_try - ExecCtx::Get()->Now();
if (timeout > 0) {
@@ -1528,20 +1528,20 @@ void GrpcLb::StartBalancerCallRetryTimerLocked() {
grpc_timer_init(&lb_call_retry_timer_, next_try, &lb_on_call_retry_);
}
-void GrpcLb::OnBalancerCallRetryTimer(void* arg, grpc_error* error) {
- GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
+void GrpcLb::OnBalancerCallRetryTimer(void* arg, grpc_error* error) {
+ GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
grpclb_policy->work_serializer()->Run(
[grpclb_policy, error]() {
grpclb_policy->OnBalancerCallRetryTimerLocked(error);
},
DEBUG_LOCATION);
-}
-
+}
+
void GrpcLb::OnBalancerCallRetryTimerLocked(grpc_error* error) {
retry_timer_callback_pending_ = false;
if (!shutting_down_ && error == GRPC_ERROR_NONE && lb_calld_ == nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "[grpclb %p] Restarting call to LB server", this);
}
StartBalancerCallLocked();
@@ -1551,29 +1551,29 @@ void GrpcLb::OnBalancerCallRetryTimerLocked(grpc_error* error) {
}
//
-// code for handling fallback mode
+// code for handling fallback mode
//
-void GrpcLb::MaybeEnterFallbackModeAfterStartup() {
- // Enter fallback mode if all of the following are true:
- // - We are not currently in fallback mode.
- // - We are not currently waiting for the initial fallback timeout.
- // - We are not currently in contact with the balancer.
- // - The child policy is not in state READY.
- if (!fallback_mode_ && !fallback_at_startup_checks_pending_ &&
- (lb_calld_ == nullptr || !lb_calld_->seen_serverlist()) &&
- !child_policy_ready_) {
- gpr_log(GPR_INFO,
- "[grpclb %p] lost contact with balancer and backends from "
- "most recent serverlist; entering fallback mode",
- this);
- fallback_mode_ = true;
- CreateOrUpdateChildPolicyLocked();
- }
+void GrpcLb::MaybeEnterFallbackModeAfterStartup() {
+ // Enter fallback mode if all of the following are true:
+ // - We are not currently in fallback mode.
+ // - We are not currently waiting for the initial fallback timeout.
+ // - We are not currently in contact with the balancer.
+ // - The child policy is not in state READY.
+ if (!fallback_mode_ && !fallback_at_startup_checks_pending_ &&
+ (lb_calld_ == nullptr || !lb_calld_->seen_serverlist()) &&
+ !child_policy_ready_) {
+ gpr_log(GPR_INFO,
+ "[grpclb %p] lost contact with balancer and backends from "
+ "most recent serverlist; entering fallback mode",
+ this);
+ fallback_mode_ = true;
+ CreateOrUpdateChildPolicyLocked();
+ }
}
-void GrpcLb::OnFallbackTimer(void* arg, grpc_error* error) {
- GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
+void GrpcLb::OnFallbackTimer(void* arg, grpc_error* error) {
+ GrpcLb* grpclb_policy = static_cast<GrpcLb*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
grpclb_policy->work_serializer()->Run(
[grpclb_policy, error]() { grpclb_policy->OnFallbackTimerLocked(error); },
@@ -1581,13 +1581,13 @@ void GrpcLb::OnFallbackTimer(void* arg, grpc_error* error) {
}
void GrpcLb::OnFallbackTimerLocked(grpc_error* error) {
- // If we receive a serverlist after the timer fires but before this callback
- // actually runs, don't fall back.
+ // If we receive a serverlist after the timer fires but before this callback
+ // actually runs, don't fall back.
if (fallback_at_startup_checks_pending_ && !shutting_down_ &&
error == GRPC_ERROR_NONE) {
- gpr_log(GPR_INFO,
- "[grpclb %p] No response from balancer after fallback timeout; "
- "entering fallback mode",
+ gpr_log(GPR_INFO,
+ "[grpclb %p] No response from balancer after fallback timeout; "
+ "entering fallback mode",
this);
fallback_at_startup_checks_pending_ = false;
CancelBalancerChannelConnectivityWatchLocked();
@@ -1599,71 +1599,71 @@ void GrpcLb::OnFallbackTimerLocked(grpc_error* error) {
}
//
-// code for interacting with the child policy
+// code for interacting with the child policy
//
-grpc_channel_args* GrpcLb::CreateChildPolicyArgsLocked(
- bool is_backend_from_grpclb_load_balancer) {
+grpc_channel_args* GrpcLb::CreateChildPolicyArgsLocked(
+ bool is_backend_from_grpclb_load_balancer) {
y_absl::InlinedVector<grpc_arg, 2> args_to_add;
- args_to_add.emplace_back(grpc_channel_arg_integer_create(
- const_cast<char*>(GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER),
- is_backend_from_grpclb_load_balancer));
- if (is_backend_from_grpclb_load_balancer) {
- args_to_add.emplace_back(grpc_channel_arg_integer_create(
- const_cast<char*>(GRPC_ARG_INHIBIT_HEALTH_CHECKING), 1));
+ args_to_add.emplace_back(grpc_channel_arg_integer_create(
+ const_cast<char*>(GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER),
+ is_backend_from_grpclb_load_balancer));
+ if (is_backend_from_grpclb_load_balancer) {
+ args_to_add.emplace_back(grpc_channel_arg_integer_create(
+ const_cast<char*>(GRPC_ARG_INHIBIT_HEALTH_CHECKING), 1));
}
- return grpc_channel_args_copy_and_add(args_, args_to_add.data(),
- args_to_add.size());
+ return grpc_channel_args_copy_and_add(args_, args_to_add.data(),
+ args_to_add.size());
}
-OrphanablePtr<LoadBalancingPolicy> GrpcLb::CreateChildPolicyLocked(
+OrphanablePtr<LoadBalancingPolicy> GrpcLb::CreateChildPolicyLocked(
const grpc_channel_args* args) {
- LoadBalancingPolicy::Args lb_policy_args;
+ LoadBalancingPolicy::Args lb_policy_args;
lb_policy_args.work_serializer = work_serializer();
- lb_policy_args.args = args;
+ lb_policy_args.args = args;
lb_policy_args.channel_control_helper = y_absl::make_unique<Helper>(Ref());
- OrphanablePtr<LoadBalancingPolicy> lb_policy =
+ OrphanablePtr<LoadBalancingPolicy> lb_policy =
MakeOrphanable<ChildPolicyHandler>(std::move(lb_policy_args),
&grpc_lb_glb_trace);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "[grpclb %p] Created new child policy handler (%p)", this,
lb_policy.get());
}
// Add the gRPC LB's interested_parties pollset_set to that of the newly
- // created child policy. This will make the child policy progress upon
- // activity on gRPC LB, which in turn is tied to the application's call.
- grpc_pollset_set_add_pollset_set(lb_policy->interested_parties(),
+ // created child policy. This will make the child policy progress upon
+ // activity on gRPC LB, which in turn is tied to the application's call.
+ grpc_pollset_set_add_pollset_set(lb_policy->interested_parties(),
interested_parties());
- return lb_policy;
+ return lb_policy;
}
-void GrpcLb::CreateOrUpdateChildPolicyLocked() {
- if (shutting_down_) return;
- // Construct update args.
- UpdateArgs update_args;
+void GrpcLb::CreateOrUpdateChildPolicyLocked() {
+ if (shutting_down_) return;
+ // Construct update args.
+ UpdateArgs update_args;
bool is_backend_from_grpclb_load_balancer = false;
- if (fallback_mode_) {
- // If CreateOrUpdateChildPolicyLocked() is invoked when we haven't
+ if (fallback_mode_) {
+ // If CreateOrUpdateChildPolicyLocked() is invoked when we haven't
// received any serverlist from the balancer, we use the fallback backends
// returned by the resolver. Note that the fallback backend list may be
// empty, in which case the new round_robin policy will keep the requested
// picks pending.
- update_args.addresses = fallback_backend_addresses_;
- } else {
- update_args.addresses = serverlist_->GetServerAddressList(
- lb_calld_ == nullptr ? nullptr : lb_calld_->client_stats());
- is_backend_from_grpclb_load_balancer = true;
+ update_args.addresses = fallback_backend_addresses_;
+ } else {
+ update_args.addresses = serverlist_->GetServerAddressList(
+ lb_calld_ == nullptr ? nullptr : lb_calld_->client_stats());
+ is_backend_from_grpclb_load_balancer = true;
}
- update_args.args =
- CreateChildPolicyArgsLocked(is_backend_from_grpclb_load_balancer);
- GPR_ASSERT(update_args.args != nullptr);
+ update_args.args =
+ CreateChildPolicyArgsLocked(is_backend_from_grpclb_load_balancer);
+ GPR_ASSERT(update_args.args != nullptr);
update_args.config = config_->child_policy();
// Create child policy if needed.
if (child_policy_ == nullptr) {
child_policy_ = CreateChildPolicyLocked(update_args.args);
}
- // Update the policy.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
+ // Update the policy.
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "[grpclb %p] Updating child policy handler %p", this,
child_policy_.get());
}
@@ -1678,17 +1678,17 @@ class GrpcLbFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<GrpcLb>(std::move(args));
- }
-
- const char* name() const override { return kGrpclb; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+ return MakeOrphanable<GrpcLb>(std::move(args));
+ }
+
+ const char* name() const override { return kGrpclb; }
+
+ RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error) const override {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
if (json.type() == Json::Type::JSON_NULL) {
return MakeRefCounted<GrpcLbConfig>(nullptr, "");
- }
+ }
std::vector<grpc_error*> error_list;
Json child_policy_config_json_tmp;
const Json* child_policy_config_json;
@@ -1722,13 +1722,13 @@ class GrpcLbFactory : public LoadBalancingPolicyFactory {
error_list.push_back(
GRPC_ERROR_CREATE_FROM_VECTOR("field:childPolicy", &child_errors));
}
- if (error_list.empty()) {
+ if (error_list.empty()) {
return MakeRefCounted<GrpcLbConfig>(std::move(child_policy_config),
std::move(service_name));
- } else {
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("GrpcLb Parser", &error_list);
- return nullptr;
- }
+ } else {
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("GrpcLb Parser", &error_list);
+ return nullptr;
+ }
}
};
@@ -1751,12 +1751,12 @@ bool maybe_add_client_load_reporting_filter(grpc_channel_stack_builder* builder,
grpc_channel_args_find(args, GRPC_ARG_LB_POLICY_NAME);
if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_STRING &&
strcmp(channel_arg->value.string, "grpclb") == 0) {
- // TODO(roth): When we get around to re-attempting
- // https://github.com/grpc/grpc/pull/16214, we should try to keep
- // this filter at the very top of the subchannel stack, since that
- // will minimize the number of metadata elements that the filter
- // needs to iterate through to find the ClientStats object.
- return grpc_channel_stack_builder_prepend_filter(
+ // TODO(roth): When we get around to re-attempting
+ // https://github.com/grpc/grpc/pull/16214, we should try to keep
+ // this filter at the very top of the subchannel stack, since that
+ // will minimize the number of metadata elements that the filter
+ // needs to iterate through to find the ClientStats object.
+ return grpc_channel_stack_builder_prepend_filter(
builder, (const grpc_channel_filter*)arg, nullptr, nullptr);
}
return true;
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h
index a032b5dbf1..87ff71ccd6 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h
@@ -32,12 +32,12 @@
#define GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER \
"grpc.address_is_backend_from_grpclb_load_balancer"
-namespace grpc_core {
-
-extern const char kGrpcLbClientStatsMetadataKey[];
-extern const char kGrpcLbLbTokenMetadataKey[];
-
-} // namespace grpc_core
-
+namespace grpc_core {
+
+extern const char kGrpcLbClientStatsMetadataKey[];
+extern const char kGrpcLbLbTokenMetadataKey[];
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H \
*/
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc
index f8197a89bf..3f3f655a4c 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc
@@ -18,20 +18,20 @@
#include <grpc/support/port_platform.h>
-#include <grpc/grpc.h>
-
+#include <grpc/grpc.h>
+
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
-namespace grpc_core {
-
-grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
- const ServerAddressList& /*addresses*/, grpc_channel_args* args) {
+namespace grpc_core {
+
+grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
+ const ServerAddressList& /*addresses*/, grpc_channel_args* args) {
return args;
}
-
-grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
- const grpc_channel_args& args) {
- return grpc_insecure_channel_create(target_uri, &args, nullptr);
-}
-
-} // namespace grpc_core
+
+grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
+ const grpc_channel_args& args) {
+ return grpc_insecure_channel_create(target_uri, &args, nullptr);
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h
index 1458233022..bfcd3799be 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h
@@ -23,23 +23,23 @@
#include <grpc/impl/codegen/grpc_types.h>
-#include "src/core/ext/filters/client_channel/server_address.h"
-
-namespace grpc_core {
-
+#include "src/core/ext/filters/client_channel/server_address.h"
+
+namespace grpc_core {
+
/// Makes any necessary modifications to \a args for use in the grpclb
/// balancer channel.
///
/// Takes ownership of \a args.
///
/// Caller takes ownership of the returned args.
-grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
- const ServerAddressList& addresses, grpc_channel_args* args);
-
-grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
- const grpc_channel_args& args);
-
-} // namespace grpc_core
-
+grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
+ const ServerAddressList& addresses, grpc_channel_args* args);
+
+grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
+ const grpc_channel_args& args);
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H \
*/
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc
index e918ee0836..0462cca377 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc
@@ -24,7 +24,7 @@
#include "y_absl/container/inlined_vector.h"
-#include <grpc/grpc_security.h>
+#include <grpc/grpc_security.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
@@ -38,9 +38,9 @@
#include "src/core/lib/slice/slice_internal.h"
namespace grpc_core {
-
-grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
- const ServerAddressList& addresses, grpc_channel_args* args) {
+
+grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
+ const ServerAddressList& addresses, grpc_channel_args* args) {
y_absl::InlinedVector<const char*, 1> args_to_remove;
y_absl::InlinedVector<grpc_arg, 1> args_to_add;
// Substitute the channel credentials with a version without call
@@ -48,38 +48,38 @@ grpc_channel_args* ModifyGrpclbBalancerChannelArgs(
// bearer token credentials.
grpc_channel_credentials* channel_credentials =
grpc_channel_credentials_find_in_args(args);
- RefCountedPtr<grpc_channel_credentials> creds_sans_call_creds;
+ RefCountedPtr<grpc_channel_credentials> creds_sans_call_creds;
if (channel_credentials != nullptr) {
creds_sans_call_creds =
channel_credentials->duplicate_without_call_credentials();
GPR_ASSERT(creds_sans_call_creds != nullptr);
- args_to_remove.emplace_back(GRPC_ARG_CHANNEL_CREDENTIALS);
- args_to_add.emplace_back(
- grpc_channel_credentials_to_arg(creds_sans_call_creds.get()));
+ args_to_remove.emplace_back(GRPC_ARG_CHANNEL_CREDENTIALS);
+ args_to_add.emplace_back(
+ grpc_channel_credentials_to_arg(creds_sans_call_creds.get()));
}
grpc_channel_args* result = grpc_channel_args_copy_and_add_and_remove(
- args, args_to_remove.data(), args_to_remove.size(), args_to_add.data(),
- args_to_add.size());
+ args, args_to_remove.data(), args_to_remove.size(), args_to_add.data(),
+ args_to_add.size());
// Clean up.
grpc_channel_args_destroy(args);
return result;
}
-
-grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
- const grpc_channel_args& args) {
- grpc_channel_credentials* creds =
- grpc_channel_credentials_find_in_args(&args);
- if (creds == nullptr) {
- // Build with security but parent channel is insecure.
- return grpc_insecure_channel_create(target_uri, &args, nullptr);
- }
- const char* arg_to_remove = GRPC_ARG_CHANNEL_CREDENTIALS;
- grpc_channel_args* new_args =
- grpc_channel_args_copy_and_remove(&args, &arg_to_remove, 1);
- grpc_channel* channel =
- grpc_secure_channel_create(creds, target_uri, new_args, nullptr);
- grpc_channel_args_destroy(new_args);
- return channel;
-}
-
-} // namespace grpc_core
+
+grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
+ const grpc_channel_args& args) {
+ grpc_channel_credentials* creds =
+ grpc_channel_credentials_find_in_args(&args);
+ if (creds == nullptr) {
+ // Build with security but parent channel is insecure.
+ return grpc_insecure_channel_create(target_uri, &args, nullptr);
+ }
+ const char* arg_to_remove = GRPC_ARG_CHANNEL_CREDENTIALS;
+ grpc_channel_args* new_args =
+ grpc_channel_args_copy_and_remove(&args, &arg_to_remove, 1);
+ grpc_channel* channel =
+ grpc_secure_channel_create(creds, target_uri, new_args, nullptr);
+ grpc_channel_args_destroy(new_args);
+ return channel;
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc
index 1566e7b5f1..2e33fcfca9 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc
@@ -25,8 +25,8 @@
#include <grpc/support/atm.h>
#include <grpc/support/string_util.h>
-#include "src/core/lib/gprpp/sync.h"
-
+#include "src/core/lib/gprpp/sync.h"
+
namespace grpc_core {
void GrpcLbClientStats::AddCallStarted() {
@@ -45,14 +45,14 @@ void GrpcLbClientStats::AddCallFinished(
}
}
-void GrpcLbClientStats::AddCallDropped(const char* token) {
+void GrpcLbClientStats::AddCallDropped(const char* token) {
// Increment num_calls_started and num_calls_finished.
gpr_atm_full_fetch_add(&num_calls_started_, (gpr_atm)1);
gpr_atm_full_fetch_add(&num_calls_finished_, (gpr_atm)1);
// Record the drop.
- MutexLock lock(&drop_count_mu_);
+ MutexLock lock(&drop_count_mu_);
if (drop_token_counts_ == nullptr) {
- drop_token_counts_.reset(new DroppedCallCounts());
+ drop_token_counts_.reset(new DroppedCallCounts());
}
for (size_t i = 0; i < drop_token_counts_->size(); ++i) {
if (strcmp((*drop_token_counts_)[i].token.get(), token) == 0) {
@@ -61,8 +61,8 @@ void GrpcLbClientStats::AddCallDropped(const char* token) {
}
}
// Not found, so add a new entry.
- drop_token_counts_->emplace_back(
- grpc_core::UniquePtr<char>(gpr_strdup(token)), 1);
+ drop_token_counts_->emplace_back(
+ grpc_core::UniquePtr<char>(gpr_strdup(token)), 1);
}
namespace {
@@ -73,18 +73,18 @@ void AtomicGetAndResetCounter(int64_t* value, gpr_atm* counter) {
} // namespace
-void GrpcLbClientStats::Get(
+void GrpcLbClientStats::Get(
int64_t* num_calls_started, int64_t* num_calls_finished,
int64_t* num_calls_finished_with_client_failed_to_send,
int64_t* num_calls_finished_known_received,
- std::unique_ptr<DroppedCallCounts>* drop_token_counts) {
+ std::unique_ptr<DroppedCallCounts>* drop_token_counts) {
AtomicGetAndResetCounter(num_calls_started, &num_calls_started_);
AtomicGetAndResetCounter(num_calls_finished, &num_calls_finished_);
AtomicGetAndResetCounter(num_calls_finished_with_client_failed_to_send,
&num_calls_finished_with_client_failed_to_send_);
AtomicGetAndResetCounter(num_calls_finished_known_received,
&num_calls_finished_known_received_);
- MutexLock lock(&drop_count_mu_);
+ MutexLock lock(&drop_count_mu_);
*drop_token_counts = std::move(drop_token_counts_);
}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h
index e5304fda6b..7774b2ae2d 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h
@@ -27,17 +27,17 @@
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
namespace grpc_core {
class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> {
public:
struct DropTokenCount {
- grpc_core::UniquePtr<char> token;
+ grpc_core::UniquePtr<char> token;
int64_t count;
- DropTokenCount(grpc_core::UniquePtr<char> token, int64_t count)
+ DropTokenCount(grpc_core::UniquePtr<char> token, int64_t count)
: token(std::move(token)), count(count) {}
};
@@ -47,26 +47,26 @@ class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> {
void AddCallFinished(bool finished_with_client_failed_to_send,
bool finished_known_received);
- void AddCallDropped(const char* token);
+ void AddCallDropped(const char* token);
- void Get(int64_t* num_calls_started, int64_t* num_calls_finished,
- int64_t* num_calls_finished_with_client_failed_to_send,
- int64_t* num_calls_finished_known_received,
- std::unique_ptr<DroppedCallCounts>* drop_token_counts);
-
- // A destruction function to use as the user_data key when attaching
- // client stats to a grpc_mdelem.
- static void Destroy(void* arg) {
- static_cast<GrpcLbClientStats*>(arg)->Unref();
- }
+ void Get(int64_t* num_calls_started, int64_t* num_calls_finished,
+ int64_t* num_calls_finished_with_client_failed_to_send,
+ int64_t* num_calls_finished_known_received,
+ std::unique_ptr<DroppedCallCounts>* drop_token_counts);
+ // A destruction function to use as the user_data key when attaching
+ // client stats to a grpc_mdelem.
+ static void Destroy(void* arg) {
+ static_cast<GrpcLbClientStats*>(arg)->Unref();
+ }
+
private:
gpr_atm num_calls_started_ = 0;
gpr_atm num_calls_finished_ = 0;
gpr_atm num_calls_finished_with_client_failed_to_send_ = 0;
gpr_atm num_calls_finished_known_received_ = 0;
- Mutex drop_count_mu_; // Guards drop_token_counts_.
- std::unique_ptr<DroppedCallCounts> drop_token_counts_;
+ Mutex drop_count_mu_; // Guards drop_token_counts_.
+ std::unique_ptr<DroppedCallCounts> drop_token_counts_;
};
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc
index 3185b993c4..f90bedcec4 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc
@@ -19,15 +19,15 @@
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h"
-#include "src/core/lib/gpr/useful.h"
-
-#include "google/protobuf/duration.upb.h"
-#include "google/protobuf/timestamp.upb.h"
+#include "src/core/lib/gpr/useful.h"
+#include "google/protobuf/duration.upb.h"
+#include "google/protobuf/timestamp.upb.h"
+
#include <grpc/support/alloc.h>
-namespace grpc_core {
-
+namespace grpc_core {
+
bool GrpcLbServer::operator==(const GrpcLbServer& other) const {
if (ip_size != other.ip_size) return false;
int r = memcmp(ip_addr, other.ip_addr, ip_size);
@@ -53,24 +53,24 @@ grpc_slice grpc_grpclb_request_encode(
grpc_slice GrpcLbRequestCreate(const char* lb_service_name, upb_arena* arena) {
grpc_lb_v1_LoadBalanceRequest* req = grpc_lb_v1_LoadBalanceRequest_new(arena);
- grpc_lb_v1_InitialLoadBalanceRequest* initial_request =
- grpc_lb_v1_LoadBalanceRequest_mutable_initial_request(req, arena);
- size_t name_len =
- GPR_MIN(strlen(lb_service_name), GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH);
- grpc_lb_v1_InitialLoadBalanceRequest_set_name(
- initial_request, upb_strview_make(lb_service_name, name_len));
+ grpc_lb_v1_InitialLoadBalanceRequest* initial_request =
+ grpc_lb_v1_LoadBalanceRequest_mutable_initial_request(req, arena);
+ size_t name_len =
+ GPR_MIN(strlen(lb_service_name), GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH);
+ grpc_lb_v1_InitialLoadBalanceRequest_set_name(
+ initial_request, upb_strview_make(lb_service_name, name_len));
return grpc_grpclb_request_encode(req, arena);
}
-namespace {
+namespace {
-void google_protobuf_Timestamp_assign(google_protobuf_Timestamp* timestamp,
- const gpr_timespec& value) {
- google_protobuf_Timestamp_set_seconds(timestamp, value.tv_sec);
- google_protobuf_Timestamp_set_nanos(timestamp, value.tv_nsec);
+void google_protobuf_Timestamp_assign(google_protobuf_Timestamp* timestamp,
+ const gpr_timespec& value) {
+ google_protobuf_Timestamp_set_seconds(timestamp, value.tv_sec);
+ google_protobuf_Timestamp_set_nanos(timestamp, value.tv_nsec);
}
-} // namespace
+} // namespace
grpc_slice GrpcLbLoadReportRequestCreate(
int64_t num_calls_started, int64_t num_calls_finished,
@@ -79,28 +79,28 @@ grpc_slice GrpcLbLoadReportRequestCreate(
const GrpcLbClientStats::DroppedCallCounts* drop_token_counts,
upb_arena* arena) {
grpc_lb_v1_LoadBalanceRequest* req = grpc_lb_v1_LoadBalanceRequest_new(arena);
- grpc_lb_v1_ClientStats* req_stats =
- grpc_lb_v1_LoadBalanceRequest_mutable_client_stats(req, arena);
- google_protobuf_Timestamp_assign(
- grpc_lb_v1_ClientStats_mutable_timestamp(req_stats, arena),
- gpr_now(GPR_CLOCK_REALTIME));
- grpc_lb_v1_ClientStats_set_num_calls_started(req_stats, num_calls_started);
- grpc_lb_v1_ClientStats_set_num_calls_finished(req_stats, num_calls_finished);
- grpc_lb_v1_ClientStats_set_num_calls_finished_with_client_failed_to_send(
- req_stats, num_calls_finished_with_client_failed_to_send);
- grpc_lb_v1_ClientStats_set_num_calls_finished_known_received(
- req_stats, num_calls_finished_known_received);
- if (drop_token_counts != nullptr) {
- for (size_t i = 0; i < drop_token_counts->size(); ++i) {
+ grpc_lb_v1_ClientStats* req_stats =
+ grpc_lb_v1_LoadBalanceRequest_mutable_client_stats(req, arena);
+ google_protobuf_Timestamp_assign(
+ grpc_lb_v1_ClientStats_mutable_timestamp(req_stats, arena),
+ gpr_now(GPR_CLOCK_REALTIME));
+ grpc_lb_v1_ClientStats_set_num_calls_started(req_stats, num_calls_started);
+ grpc_lb_v1_ClientStats_set_num_calls_finished(req_stats, num_calls_finished);
+ grpc_lb_v1_ClientStats_set_num_calls_finished_with_client_failed_to_send(
+ req_stats, num_calls_finished_with_client_failed_to_send);
+ grpc_lb_v1_ClientStats_set_num_calls_finished_known_received(
+ req_stats, num_calls_finished_known_received);
+ if (drop_token_counts != nullptr) {
+ for (size_t i = 0; i < drop_token_counts->size(); ++i) {
const GrpcLbClientStats::DropTokenCount& cur = (*drop_token_counts)[i];
- grpc_lb_v1_ClientStatsPerToken* cur_msg =
- grpc_lb_v1_ClientStats_add_calls_finished_with_drop(req_stats, arena);
- const size_t token_len = strlen(cur.token.get());
- char* token = reinterpret_cast<char*>(upb_arena_malloc(arena, token_len));
- memcpy(token, cur.token.get(), token_len);
- grpc_lb_v1_ClientStatsPerToken_set_load_balance_token(
- cur_msg, upb_strview_make(token, token_len));
- grpc_lb_v1_ClientStatsPerToken_set_num_calls(cur_msg, cur.count);
+ grpc_lb_v1_ClientStatsPerToken* cur_msg =
+ grpc_lb_v1_ClientStats_add_calls_finished_with_drop(req_stats, arena);
+ const size_t token_len = strlen(cur.token.get());
+ char* token = reinterpret_cast<char*>(upb_arena_malloc(arena, token_len));
+ memcpy(token, cur.token.get(), token_len);
+ grpc_lb_v1_ClientStatsPerToken_set_load_balance_token(
+ cur_msg, upb_strview_make(token, token_len));
+ grpc_lb_v1_ClientStatsPerToken_set_num_calls(cur_msg, cur.count);
}
}
return grpc_grpclb_request_encode(req, arena);
@@ -111,35 +111,35 @@ namespace {
bool ParseServerList(const grpc_lb_v1_LoadBalanceResponse& response,
std::vector<GrpcLbServer>* server_list) {
// Determine the number of servers.
- const grpc_lb_v1_ServerList* server_list_msg =
+ const grpc_lb_v1_ServerList* server_list_msg =
grpc_lb_v1_LoadBalanceResponse_server_list(&response);
if (server_list_msg == nullptr) return false;
- size_t server_count = 0;
+ size_t server_count = 0;
const grpc_lb_v1_Server* const* servers =
grpc_lb_v1_ServerList_servers(server_list_msg, &server_count);
// Populate servers.
- if (server_count > 0) {
+ if (server_count > 0) {
server_list->reserve(server_count);
- for (size_t i = 0; i < server_count; ++i) {
+ for (size_t i = 0; i < server_count; ++i) {
GrpcLbServer& cur = *server_list->emplace(server_list->end());
- upb_strview address = grpc_lb_v1_Server_ip_address(servers[i]);
- if (address.size == 0) {
- ; // Nothing to do because cur->ip_address is an empty string.
- } else if (address.size <= GRPC_GRPCLB_SERVER_IP_ADDRESS_MAX_SIZE) {
+ upb_strview address = grpc_lb_v1_Server_ip_address(servers[i]);
+ if (address.size == 0) {
+ ; // Nothing to do because cur->ip_address is an empty string.
+ } else if (address.size <= GRPC_GRPCLB_SERVER_IP_ADDRESS_MAX_SIZE) {
cur.ip_size = static_cast<int32_t>(address.size);
memcpy(cur.ip_addr, address.data, address.size);
- }
+ }
cur.port = grpc_lb_v1_Server_port(servers[i]);
- upb_strview token = grpc_lb_v1_Server_load_balance_token(servers[i]);
- if (token.size == 0) {
- ; // Nothing to do because cur->load_balance_token is an empty string.
- } else if (token.size <= GRPC_GRPCLB_SERVER_LOAD_BALANCE_TOKEN_MAX_SIZE) {
+ upb_strview token = grpc_lb_v1_Server_load_balance_token(servers[i]);
+ if (token.size == 0) {
+ ; // Nothing to do because cur->load_balance_token is an empty string.
+ } else if (token.size <= GRPC_GRPCLB_SERVER_LOAD_BALANCE_TOKEN_MAX_SIZE) {
memcpy(cur.load_balance_token, token.data, token.size);
- } else {
- gpr_log(GPR_ERROR,
- "grpc_lb_v1_LoadBalanceResponse has too long token. len=%zu",
- token.size);
- }
+ } else {
+ gpr_log(GPR_ERROR,
+ "grpc_lb_v1_LoadBalanceResponse has too long token. len=%zu",
+ token.size);
+ }
cur.drop = grpc_lb_v1_Server_drop(servers[i]);
}
}
@@ -190,4 +190,4 @@ bool GrpcLbResponseParse(const grpc_slice& encoded_grpc_grpclb_response,
return false;
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h
index 6caa120f58..dabc7b3d6f 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h
@@ -27,23 +27,23 @@
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/proto/grpc/lb/v1/load_balancer.upb.h"
+#include "src/proto/grpc/lb/v1/load_balancer.upb.h"
#define GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH 128
-#define GRPC_GRPCLB_SERVER_IP_ADDRESS_MAX_SIZE 16
-#define GRPC_GRPCLB_SERVER_LOAD_BALANCE_TOKEN_MAX_SIZE 50
+#define GRPC_GRPCLB_SERVER_IP_ADDRESS_MAX_SIZE 16
+#define GRPC_GRPCLB_SERVER_LOAD_BALANCE_TOKEN_MAX_SIZE 50
-namespace grpc_core {
-
-// Contains server information. When the drop field is not true, use the other
-// fields.
+namespace grpc_core {
+
+// Contains server information. When the drop field is not true, use the other
+// fields.
struct GrpcLbServer {
int32_t ip_size;
char ip_addr[GRPC_GRPCLB_SERVER_IP_ADDRESS_MAX_SIZE];
- int32_t port;
- char load_balance_token[GRPC_GRPCLB_SERVER_LOAD_BALANCE_TOKEN_MAX_SIZE];
- bool drop;
-
+ int32_t port;
+ char load_balance_token[GRPC_GRPCLB_SERVER_LOAD_BALANCE_TOKEN_MAX_SIZE];
+ bool drop;
+
bool operator==(const GrpcLbServer& other) const;
};
@@ -68,7 +68,7 @@ grpc_slice GrpcLbLoadReportRequestCreate(
bool GrpcLbResponseParse(const grpc_slice& serialized_response,
upb_arena* arena, GrpcLbResponse* response);
-} // namespace grpc_core
+} // namespace grpc_core
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_LOAD_BALANCER_API_H \
*/
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc
index ab78053008..55c2e7784a 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc
@@ -27,7 +27,7 @@
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/filters/client_channel/subchannel.h"
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/error_utils.h"
@@ -50,7 +50,7 @@ class PickFirst : public LoadBalancingPolicy {
const char* name() const override { return kPickFirst; }
- void UpdateLocked(UpdateArgs args) override;
+ void UpdateLocked(UpdateArgs args) override;
void ExitIdleLocked() override;
void ResetBackoffLocked() override;
@@ -66,12 +66,12 @@ class PickFirst : public LoadBalancingPolicy {
PickFirstSubchannelData(
SubchannelList<PickFirstSubchannelList, PickFirstSubchannelData>*
subchannel_list,
- const ServerAddress& address,
- RefCountedPtr<SubchannelInterface> subchannel)
- : SubchannelData(subchannel_list, address, std::move(subchannel)) {}
+ const ServerAddress& address,
+ RefCountedPtr<SubchannelInterface> subchannel)
+ : SubchannelData(subchannel_list, address, std::move(subchannel)) {}
void ProcessConnectivityChangeLocked(
- grpc_connectivity_state connectivity_state) override;
+ grpc_connectivity_state connectivity_state) override;
// Processes the connectivity change to READY for an unselected subchannel.
void ProcessUnselectedReadyLocked();
@@ -87,7 +87,7 @@ class PickFirst : public LoadBalancingPolicy {
ServerAddressList addresses,
const grpc_channel_args& args)
: SubchannelList(policy, tracer, std::move(addresses),
- policy->channel_control_helper(), args) {
+ policy->channel_control_helper(), args) {
// Need to maintain a ref to the LB policy as long as we maintain
// any references to subchannels, since the subchannels'
// pollset_sets will include the LB policy's pollset_set.
@@ -98,58 +98,58 @@ class PickFirst : public LoadBalancingPolicy {
PickFirst* p = static_cast<PickFirst*>(policy());
p->Unref(DEBUG_LOCATION, "subchannel_list");
}
-
- bool in_transient_failure() const { return in_transient_failure_; }
- void set_in_transient_failure(bool in_transient_failure) {
- in_transient_failure_ = in_transient_failure;
- }
-
- private:
- bool in_transient_failure_ = false;
+
+ bool in_transient_failure() const { return in_transient_failure_; }
+ void set_in_transient_failure(bool in_transient_failure) {
+ in_transient_failure_ = in_transient_failure;
+ }
+
+ private:
+ bool in_transient_failure_ = false;
};
- class Picker : public SubchannelPicker {
+ class Picker : public SubchannelPicker {
public:
- explicit Picker(RefCountedPtr<SubchannelInterface> subchannel)
- : subchannel_(std::move(subchannel)) {}
-
- PickResult Pick(PickArgs /*args*/) override {
- PickResult result;
- result.type = PickResult::PICK_COMPLETE;
- result.subchannel = subchannel_;
- return result;
- }
-
+ explicit Picker(RefCountedPtr<SubchannelInterface> subchannel)
+ : subchannel_(std::move(subchannel)) {}
+
+ PickResult Pick(PickArgs /*args*/) override {
+ PickResult result;
+ result.type = PickResult::PICK_COMPLETE;
+ result.subchannel = subchannel_;
+ return result;
+ }
+
private:
- RefCountedPtr<SubchannelInterface> subchannel_;
+ RefCountedPtr<SubchannelInterface> subchannel_;
};
void ShutdownLocked() override;
- void AttemptToConnectUsingLatestUpdateArgsLocked();
+ void AttemptToConnectUsingLatestUpdateArgsLocked();
- // Lateset update args.
- UpdateArgs latest_update_args_;
+ // Lateset update args.
+ UpdateArgs latest_update_args_;
// All our subchannels.
OrphanablePtr<PickFirstSubchannelList> subchannel_list_;
// Latest pending subchannel list.
OrphanablePtr<PickFirstSubchannelList> latest_pending_subchannel_list_;
// Selected subchannel in \a subchannel_list_.
PickFirstSubchannelData* selected_ = nullptr;
- // Are we in IDLE state?
- bool idle_ = false;
+ // Are we in IDLE state?
+ bool idle_ = false;
// Are we shut down?
bool shutdown_ = false;
};
PickFirst::PickFirst(Args args) : LoadBalancingPolicy(std::move(args)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO, "Pick First %p created.", this);
}
}
PickFirst::~PickFirst() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO, "Destroying Pick First %p", this);
}
GPR_ASSERT(subchannel_list_ == nullptr);
@@ -157,7 +157,7 @@ PickFirst::~PickFirst() {
}
void PickFirst::ShutdownLocked() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO, "Pick First %p Shutting down", this);
}
shutdown_ = true;
@@ -165,42 +165,42 @@ void PickFirst::ShutdownLocked() {
latest_pending_subchannel_list_.reset();
}
-void PickFirst::ExitIdleLocked() {
- if (shutdown_) return;
- if (idle_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
- gpr_log(GPR_INFO, "Pick First %p exiting idle", this);
+void PickFirst::ExitIdleLocked() {
+ if (shutdown_) return;
+ if (idle_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ gpr_log(GPR_INFO, "Pick First %p exiting idle", this);
}
- idle_ = false;
- AttemptToConnectUsingLatestUpdateArgsLocked();
+ idle_ = false;
+ AttemptToConnectUsingLatestUpdateArgsLocked();
}
}
void PickFirst::ResetBackoffLocked() {
- if (subchannel_list_ != nullptr) subchannel_list_->ResetBackoffLocked();
+ if (subchannel_list_ != nullptr) subchannel_list_->ResetBackoffLocked();
if (latest_pending_subchannel_list_ != nullptr) {
latest_pending_subchannel_list_->ResetBackoffLocked();
}
}
-void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
- // Create a subchannel list from the latest_update_args_.
+void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
+ // Create a subchannel list from the latest_update_args_.
auto subchannel_list = MakeOrphanable<PickFirstSubchannelList>(
- this, &grpc_lb_pick_first_trace, latest_update_args_.addresses,
- *latest_update_args_.args);
- // Empty update or no valid subchannels.
+ this, &grpc_lb_pick_first_trace, latest_update_args_.addresses,
+ *latest_update_args_.args);
+ // Empty update or no valid subchannels.
if (subchannel_list->num_subchannels() == 0) {
- // Unsubscribe from all current subchannels.
+ // Unsubscribe from all current subchannels.
subchannel_list_ = std::move(subchannel_list); // Empty list.
selected_ = nullptr;
- // If not idle, put the channel in TRANSIENT_FAILURE.
- // (If we are idle, then this will happen in ExitIdleLocked() if we
- // haven't gotten a non-empty update by the time the application tries
- // to start a new call.)
- grpc_error* error =
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Empty update"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- channel_control_helper()->UpdateState(
+ // If not idle, put the channel in TRANSIENT_FAILURE.
+ // (If we are idle, then this will happen in ExitIdleLocked() if we
+ // haven't gotten a non-empty update by the time the application tries
+ // to start a new call.)
+ grpc_error* error =
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Empty update"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
return;
@@ -209,13 +209,13 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
// READY, then select it immediately. This can happen when the
// currently selected subchannel is also present in the update. It
// can also happen if one of the subchannels in the update is already
- // in the global subchannel pool because it's in use by another channel.
+ // in the global subchannel pool because it's in use by another channel.
for (size_t i = 0; i < subchannel_list->num_subchannels(); ++i) {
PickFirstSubchannelData* sd = subchannel_list->subchannel(i);
- grpc_connectivity_state state = sd->CheckConnectivityStateLocked();
+ grpc_connectivity_state state = sd->CheckConnectivityStateLocked();
if (state == GRPC_CHANNEL_READY) {
subchannel_list_ = std::move(subchannel_list);
- sd->StartConnectivityWatchLocked();
+ sd->StartConnectivityWatchLocked();
sd->ProcessUnselectedReadyLocked();
// If there was a previously pending update (which may or may
// not have contained the currently selected subchannel), drop
@@ -228,18 +228,18 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
// We don't yet have a selected subchannel, so replace the current
// subchannel list immediately.
subchannel_list_ = std::move(subchannel_list);
- // If we're not in IDLE state, start trying to connect to the first
+ // If we're not in IDLE state, start trying to connect to the first
// subchannel in the new list.
- // Note: No need to use CheckConnectivityStateAndStartWatchingLocked()
- // here, since we've already checked the initial connectivity
- // state of all subchannels above.
- subchannel_list_->subchannel(0)->StartConnectivityWatchLocked();
- subchannel_list_->subchannel(0)->subchannel()->AttemptToConnect();
+ // Note: No need to use CheckConnectivityStateAndStartWatchingLocked()
+ // here, since we've already checked the initial connectivity
+ // state of all subchannels above.
+ subchannel_list_->subchannel(0)->StartConnectivityWatchLocked();
+ subchannel_list_->subchannel(0)->subchannel()->AttemptToConnect();
} else {
- // We do have a selected subchannel (which means it's READY), so keep
- // using it until one of the subchannels in the new list reports READY.
+ // We do have a selected subchannel (which means it's READY), so keep
+ // using it until one of the subchannels in the new list reports READY.
if (latest_pending_subchannel_list_ != nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO,
"Pick First %p Shutting down latest pending subchannel list "
"%p, about to be replaced by newer latest %p",
@@ -248,42 +248,42 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
}
}
latest_pending_subchannel_list_ = std::move(subchannel_list);
- // If we're not in IDLE state, start trying to connect to the first
+ // If we're not in IDLE state, start trying to connect to the first
// subchannel in the new list.
- // Note: No need to use CheckConnectivityStateAndStartWatchingLocked()
- // here, since we've already checked the initial connectivity
- // state of all subchannels above.
- latest_pending_subchannel_list_->subchannel(0)
- ->StartConnectivityWatchLocked();
- latest_pending_subchannel_list_->subchannel(0)
- ->subchannel()
- ->AttemptToConnect();
- }
-}
-
-void PickFirst::UpdateLocked(UpdateArgs args) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
- gpr_log(GPR_INFO,
- "Pick First %p received update with %" PRIuPTR " addresses", this,
- args.addresses.size());
- }
- // Update the latest_update_args_
- grpc_arg new_arg = grpc_channel_arg_integer_create(
- const_cast<char*>(GRPC_ARG_INHIBIT_HEALTH_CHECKING), 1);
- const grpc_channel_args* new_args =
- grpc_channel_args_copy_and_add(args.args, &new_arg, 1);
- GPR_SWAP(const grpc_channel_args*, new_args, args.args);
- grpc_channel_args_destroy(new_args);
- latest_update_args_ = std::move(args);
- // If we are not in idle, start connection attempt immediately.
- // Otherwise, we defer the attempt into ExitIdleLocked().
- if (!idle_) {
- AttemptToConnectUsingLatestUpdateArgsLocked();
+ // Note: No need to use CheckConnectivityStateAndStartWatchingLocked()
+ // here, since we've already checked the initial connectivity
+ // state of all subchannels above.
+ latest_pending_subchannel_list_->subchannel(0)
+ ->StartConnectivityWatchLocked();
+ latest_pending_subchannel_list_->subchannel(0)
+ ->subchannel()
+ ->AttemptToConnect();
}
}
+void PickFirst::UpdateLocked(UpdateArgs args) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ gpr_log(GPR_INFO,
+ "Pick First %p received update with %" PRIuPTR " addresses", this,
+ args.addresses.size());
+ }
+ // Update the latest_update_args_
+ grpc_arg new_arg = grpc_channel_arg_integer_create(
+ const_cast<char*>(GRPC_ARG_INHIBIT_HEALTH_CHECKING), 1);
+ const grpc_channel_args* new_args =
+ grpc_channel_args_copy_and_add(args.args, &new_arg, 1);
+ GPR_SWAP(const grpc_channel_args*, new_args, args.args);
+ grpc_channel_args_destroy(new_args);
+ latest_update_args_ = std::move(args);
+ // If we are not in idle, start connection attempt immediately.
+ // Otherwise, we defer the attempt into ExitIdleLocked().
+ if (!idle_) {
+ AttemptToConnectUsingLatestUpdateArgsLocked();
+ }
+}
+
void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
- grpc_connectivity_state connectivity_state) {
+ grpc_connectivity_state connectivity_state) {
PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy());
// The notification must be for a subchannel in either the current or
// latest pending subchannel lists.
@@ -292,16 +292,16 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
GPR_ASSERT(connectivity_state != GRPC_CHANNEL_SHUTDOWN);
// Handle updates for the currently selected subchannel.
if (p->selected_ == this) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO,
- "Pick First %p selected subchannel connectivity changed to %s", p,
- ConnectivityStateName(connectivity_state));
+ "Pick First %p selected subchannel connectivity changed to %s", p,
+ ConnectivityStateName(connectivity_state));
}
// If the new state is anything other than READY and there is a
// pending update, switch to the pending update.
if (connectivity_state != GRPC_CHANNEL_READY &&
p->latest_pending_subchannel_list_ != nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO,
"Pick First %p promoting pending subchannel list %p to "
"replace %p",
@@ -309,54 +309,54 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
p->subchannel_list_.get());
}
p->selected_ = nullptr;
- CancelConnectivityWatchLocked(
- "selected subchannel failed; switching to pending update");
+ CancelConnectivityWatchLocked(
+ "selected subchannel failed; switching to pending update");
p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_);
- // Set our state to that of the pending subchannel list.
- if (p->subchannel_list_->in_transient_failure()) {
- grpc_error* error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "selected subchannel failed; switching to pending update"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- p->channel_control_helper()->UpdateState(
+ // Set our state to that of the pending subchannel list.
+ if (p->subchannel_list_->in_transient_failure()) {
+ grpc_error* error = grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "selected subchannel failed; switching to pending update"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
- } else {
- p->channel_control_helper()->UpdateState(
+ } else {
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING, y_absl::Status(),
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
- }
+ }
} else {
if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
- // If the selected subchannel goes bad, request a re-resolution. We
- // also set the channel state to IDLE. The reason is that if the new
- // state is TRANSIENT_FAILURE due to a GOAWAY reception we don't want
- // to connect to the re-resolved backends until we leave IDLE state.
- // TODO(qianchengz): We may want to request re-resolution in
- // ExitIdleLocked().
- p->idle_ = true;
- p->channel_control_helper()->RequestReresolution();
+ // If the selected subchannel goes bad, request a re-resolution. We
+ // also set the channel state to IDLE. The reason is that if the new
+ // state is TRANSIENT_FAILURE due to a GOAWAY reception we don't want
+ // to connect to the re-resolved backends until we leave IDLE state.
+ // TODO(qianchengz): We may want to request re-resolution in
+ // ExitIdleLocked().
+ p->idle_ = true;
+ p->channel_control_helper()->RequestReresolution();
p->selected_ = nullptr;
- p->subchannel_list_.reset();
- p->channel_control_helper()->UpdateState(
+ p->subchannel_list_.reset();
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_IDLE, y_absl::Status(),
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
} else {
- // This is unlikely but can happen when a subchannel has been asked
- // to reconnect by a different channel and this channel has dropped
- // some connectivity state notifications.
- if (connectivity_state == GRPC_CHANNEL_READY) {
- p->channel_control_helper()->UpdateState(
+ // This is unlikely but can happen when a subchannel has been asked
+ // to reconnect by a different channel and this channel has dropped
+ // some connectivity state notifications.
+ if (connectivity_state == GRPC_CHANNEL_READY) {
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY, y_absl::Status(),
y_absl::make_unique<Picker>(subchannel()->Ref()));
- } else { // CONNECTING
- p->channel_control_helper()->UpdateState(
+ } else { // CONNECTING
+ p->channel_control_helper()->UpdateState(
connectivity_state, y_absl::Status(),
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
- }
+ }
}
}
return;
@@ -370,37 +370,37 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
// for a subchannel in p->latest_pending_subchannel_list_. The
// goal here is to find a subchannel from the update that we can
// select in place of the current one.
- subchannel_list()->set_in_transient_failure(false);
+ subchannel_list()->set_in_transient_failure(false);
switch (connectivity_state) {
case GRPC_CHANNEL_READY: {
ProcessUnselectedReadyLocked();
break;
}
case GRPC_CHANNEL_TRANSIENT_FAILURE: {
- CancelConnectivityWatchLocked("connection attempt failed");
+ CancelConnectivityWatchLocked("connection attempt failed");
PickFirstSubchannelData* sd = this;
size_t next_index =
(sd->Index() + 1) % subchannel_list()->num_subchannels();
sd = subchannel_list()->subchannel(next_index);
- // If we're tried all subchannels, set state to TRANSIENT_FAILURE.
- if (sd->Index() == 0) {
- // Re-resolve if this is the most recent subchannel list.
- if (subchannel_list() == (p->latest_pending_subchannel_list_ != nullptr
- ? p->latest_pending_subchannel_list_.get()
- : p->subchannel_list_.get())) {
- p->channel_control_helper()->RequestReresolution();
- }
- subchannel_list()->set_in_transient_failure(true);
- // Only report new state in case 1.
- if (subchannel_list() == p->subchannel_list_.get()) {
- grpc_error* error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "failed to connect to all addresses"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- p->channel_control_helper()->UpdateState(
+ // If we're tried all subchannels, set state to TRANSIENT_FAILURE.
+ if (sd->Index() == 0) {
+ // Re-resolve if this is the most recent subchannel list.
+ if (subchannel_list() == (p->latest_pending_subchannel_list_ != nullptr
+ ? p->latest_pending_subchannel_list_.get()
+ : p->subchannel_list_.get())) {
+ p->channel_control_helper()->RequestReresolution();
+ }
+ subchannel_list()->set_in_transient_failure(true);
+ // Only report new state in case 1.
+ if (subchannel_list() == p->subchannel_list_.get()) {
+ grpc_error* error = grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "failed to connect to all addresses"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
- }
+ }
}
sd->CheckConnectivityStateAndStartWatchingLocked();
break;
@@ -409,7 +409,7 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
case GRPC_CHANNEL_IDLE: {
// Only update connectivity state in case 1.
if (subchannel_list() == p->subchannel_list_.get()) {
- p->channel_control_helper()->UpdateState(
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING, y_absl::Status(),
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
@@ -436,7 +436,7 @@ void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() {
subchannel_list() == p->latest_pending_subchannel_list_.get());
// Case 2. Promote p->latest_pending_subchannel_list_ to p->subchannel_list_.
if (subchannel_list() == p->latest_pending_subchannel_list_.get()) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO,
"Pick First %p promoting pending subchannel list %p to "
"replace %p",
@@ -446,16 +446,16 @@ void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() {
p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_);
}
// Cases 1 and 2.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
gpr_log(GPR_INFO, "Pick First %p selected subchannel %p", p, subchannel());
}
- p->selected_ = this;
- p->channel_control_helper()->UpdateState(
+ p->selected_ = this;
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY, y_absl::Status(),
y_absl::make_unique<Picker>(subchannel()->Ref()));
- for (size_t i = 0; i < subchannel_list()->num_subchannels(); ++i) {
- if (i != Index()) {
- subchannel_list()->subchannel(i)->ShutdownLocked();
+ for (size_t i = 0; i < subchannel_list()->num_subchannels(); ++i) {
+ if (i != Index()) {
+ subchannel_list()->subchannel(i)->ShutdownLocked();
}
}
}
@@ -463,26 +463,26 @@ void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() {
void PickFirst::PickFirstSubchannelData::
CheckConnectivityStateAndStartWatchingLocked() {
PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy());
- // Check current state.
- grpc_connectivity_state current_state = CheckConnectivityStateLocked();
- // Start watch.
- StartConnectivityWatchLocked();
- // If current state is READY, select the subchannel now, since we started
- // watching from this state and will not get a notification of it
- // transitioning into this state.
- // If the current state is not READY, attempt to connect.
- if (current_state == GRPC_CHANNEL_READY) {
- if (p->selected_ != this) ProcessUnselectedReadyLocked();
- } else {
- subchannel()->AttemptToConnect();
+ // Check current state.
+ grpc_connectivity_state current_state = CheckConnectivityStateLocked();
+ // Start watch.
+ StartConnectivityWatchLocked();
+ // If current state is READY, select the subchannel now, since we started
+ // watching from this state and will not get a notification of it
+ // transitioning into this state.
+ // If the current state is not READY, attempt to connect.
+ if (current_state == GRPC_CHANNEL_READY) {
+ if (p->selected_ != this) ProcessUnselectedReadyLocked();
+ } else {
+ subchannel()->AttemptToConnect();
}
}
class PickFirstConfig : public LoadBalancingPolicy::Config {
- public:
- const char* name() const override { return kPickFirst; }
-};
-
+ public:
+ const char* name() const override { return kPickFirst; }
+};
+
//
// factory
//
@@ -491,15 +491,15 @@ class PickFirstFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<PickFirst>(std::move(args));
+ return MakeOrphanable<PickFirst>(std::move(args));
}
const char* name() const override { return kPickFirst; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+
+ RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** /*error*/) const override {
return MakeRefCounted<PickFirstConfig>();
- }
+ }
};
} // namespace
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc
index b277add32a..5c7707811b 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc
@@ -26,7 +26,7 @@
#include <grpc/support/port_platform.h>
-#include <stdlib.h>
+#include <stdlib.h>
#include <string.h>
#include <grpc/support/alloc.h>
@@ -37,7 +37,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/error_utils.h"
@@ -61,7 +61,7 @@ class RoundRobin : public LoadBalancingPolicy {
const char* name() const override { return kRoundRobin; }
- void UpdateLocked(UpdateArgs args) override;
+ void UpdateLocked(UpdateArgs args) override;
void ResetBackoffLocked() override;
private:
@@ -81,29 +81,29 @@ class RoundRobin : public LoadBalancingPolicy {
RoundRobinSubchannelData(
SubchannelList<RoundRobinSubchannelList, RoundRobinSubchannelData>*
subchannel_list,
- const ServerAddress& address,
- RefCountedPtr<SubchannelInterface> subchannel)
- : SubchannelData(subchannel_list, address, std::move(subchannel)) {}
+ const ServerAddress& address,
+ RefCountedPtr<SubchannelInterface> subchannel)
+ : SubchannelData(subchannel_list, address, std::move(subchannel)) {}
grpc_connectivity_state connectivity_state() const {
return last_connectivity_state_;
}
- bool seen_failure_since_ready() const { return seen_failure_since_ready_; }
-
- // Performs connectivity state updates that need to be done both when we
- // first start watching and when a watcher notification is received.
+ bool seen_failure_since_ready() const { return seen_failure_since_ready_; }
+
+ // Performs connectivity state updates that need to be done both when we
+ // first start watching and when a watcher notification is received.
void UpdateConnectivityStateLocked(
- grpc_connectivity_state connectivity_state);
+ grpc_connectivity_state connectivity_state);
private:
- // Performs connectivity state updates that need to be done only
- // after we have started watching.
+ // Performs connectivity state updates that need to be done only
+ // after we have started watching.
void ProcessConnectivityChangeLocked(
- grpc_connectivity_state connectivity_state) override;
+ grpc_connectivity_state connectivity_state) override;
grpc_connectivity_state last_connectivity_state_ = GRPC_CHANNEL_IDLE;
- bool seen_failure_since_ready_ = false;
+ bool seen_failure_since_ready_ = false;
};
// A list of subchannels.
@@ -111,11 +111,11 @@ class RoundRobin : public LoadBalancingPolicy {
: public SubchannelList<RoundRobinSubchannelList,
RoundRobinSubchannelData> {
public:
- RoundRobinSubchannelList(RoundRobin* policy, TraceFlag* tracer,
+ RoundRobinSubchannelList(RoundRobin* policy, TraceFlag* tracer,
ServerAddressList addresses,
- const grpc_channel_args& args)
+ const grpc_channel_args& args)
: SubchannelList(policy, tracer, std::move(addresses),
- policy->channel_control_helper(), args) {
+ policy->channel_control_helper(), args) {
// Need to maintain a ref to the LB policy as long as we maintain
// any references to subchannels, since the subchannels'
// pollset_sets will include the LB policy's pollset_set.
@@ -133,7 +133,7 @@ class RoundRobin : public LoadBalancingPolicy {
// Updates the counters of subchannels in each state when a
// subchannel transitions from old_state to new_state.
void UpdateStateCountersLocked(grpc_connectivity_state old_state,
- grpc_connectivity_state new_state);
+ grpc_connectivity_state new_state);
// If this subchannel list is the RR policy's current subchannel
// list, updates the RR policy's connectivity state based on the
@@ -150,17 +150,17 @@ class RoundRobin : public LoadBalancingPolicy {
size_t num_transient_failure_ = 0;
};
- class Picker : public SubchannelPicker {
+ class Picker : public SubchannelPicker {
public:
- Picker(RoundRobin* parent, RoundRobinSubchannelList* subchannel_list);
-
- PickResult Pick(PickArgs args) override;
+ Picker(RoundRobin* parent, RoundRobinSubchannelList* subchannel_list);
+ PickResult Pick(PickArgs args) override;
+
private:
- // Using pointer value only, no ref held -- do not dereference!
- RoundRobin* parent_;
-
- size_t last_picked_index_;
+ // Using pointer value only, no ref held -- do not dereference!
+ RoundRobin* parent_;
+
+ size_t last_picked_index_;
y_absl::InlinedVector<RefCountedPtr<SubchannelInterface>, 10> subchannels_;
};
@@ -178,59 +178,59 @@ class RoundRobin : public LoadBalancingPolicy {
bool shutdown_ = false;
};
-//
-// RoundRobin::Picker
-//
-
-RoundRobin::Picker::Picker(RoundRobin* parent,
- RoundRobinSubchannelList* subchannel_list)
- : parent_(parent) {
- for (size_t i = 0; i < subchannel_list->num_subchannels(); ++i) {
- RoundRobinSubchannelData* sd = subchannel_list->subchannel(i);
- if (sd->connectivity_state() == GRPC_CHANNEL_READY) {
- subchannels_.push_back(sd->subchannel()->Ref());
- }
- }
- // For discussion on why we generate a random starting index for
- // the picker, see https://github.com/grpc/grpc-go/issues/2580.
- // TODO(roth): rand(3) is not thread-safe. This should be replaced with
- // something better as part of https://github.com/grpc/grpc/issues/17891.
- last_picked_index_ = rand() % subchannels_.size();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
- gpr_log(GPR_INFO,
- "[RR %p picker %p] created picker from subchannel_list=%p "
- "with %" PRIuPTR " READY subchannels; last_picked_index_=%" PRIuPTR,
- parent_, this, subchannel_list, subchannels_.size(),
- last_picked_index_);
- }
-}
-
-RoundRobin::PickResult RoundRobin::Picker::Pick(PickArgs /*args*/) {
- last_picked_index_ = (last_picked_index_ + 1) % subchannels_.size();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
- gpr_log(GPR_INFO,
- "[RR %p picker %p] returning index %" PRIuPTR ", subchannel=%p",
- parent_, this, last_picked_index_,
- subchannels_[last_picked_index_].get());
- }
- PickResult result;
- result.type = PickResult::PICK_COMPLETE;
- result.subchannel = subchannels_[last_picked_index_];
- return result;
-}
-
-//
-// RoundRobin
-//
-
+//
+// RoundRobin::Picker
+//
+
+RoundRobin::Picker::Picker(RoundRobin* parent,
+ RoundRobinSubchannelList* subchannel_list)
+ : parent_(parent) {
+ for (size_t i = 0; i < subchannel_list->num_subchannels(); ++i) {
+ RoundRobinSubchannelData* sd = subchannel_list->subchannel(i);
+ if (sd->connectivity_state() == GRPC_CHANNEL_READY) {
+ subchannels_.push_back(sd->subchannel()->Ref());
+ }
+ }
+ // For discussion on why we generate a random starting index for
+ // the picker, see https://github.com/grpc/grpc-go/issues/2580.
+ // TODO(roth): rand(3) is not thread-safe. This should be replaced with
+ // something better as part of https://github.com/grpc/grpc/issues/17891.
+ last_picked_index_ = rand() % subchannels_.size();
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ gpr_log(GPR_INFO,
+ "[RR %p picker %p] created picker from subchannel_list=%p "
+ "with %" PRIuPTR " READY subchannels; last_picked_index_=%" PRIuPTR,
+ parent_, this, subchannel_list, subchannels_.size(),
+ last_picked_index_);
+ }
+}
+
+RoundRobin::PickResult RoundRobin::Picker::Pick(PickArgs /*args*/) {
+ last_picked_index_ = (last_picked_index_ + 1) % subchannels_.size();
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ gpr_log(GPR_INFO,
+ "[RR %p picker %p] returning index %" PRIuPTR ", subchannel=%p",
+ parent_, this, last_picked_index_,
+ subchannels_[last_picked_index_].get());
+ }
+ PickResult result;
+ result.type = PickResult::PICK_COMPLETE;
+ result.subchannel = subchannels_[last_picked_index_];
+ return result;
+}
+
+//
+// RoundRobin
+//
+
RoundRobin::RoundRobin(Args args) : LoadBalancingPolicy(std::move(args)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
- gpr_log(GPR_INFO, "[RR %p] Created", this);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ gpr_log(GPR_INFO, "[RR %p] Created", this);
}
}
RoundRobin::~RoundRobin() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
gpr_log(GPR_INFO, "[RR %p] Destroying Round Robin policy", this);
}
GPR_ASSERT(subchannel_list_ == nullptr);
@@ -238,7 +238,7 @@ RoundRobin::~RoundRobin() {
}
void RoundRobin::ShutdownLocked() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
gpr_log(GPR_INFO, "[RR %p] Shutting down", this);
}
shutdown_ = true;
@@ -260,24 +260,24 @@ void RoundRobin::RoundRobinSubchannelList::StartWatchingLocked() {
// state.
for (size_t i = 0; i < num_subchannels(); ++i) {
grpc_connectivity_state state =
- subchannel(i)->CheckConnectivityStateLocked();
+ subchannel(i)->CheckConnectivityStateLocked();
if (state != GRPC_CHANNEL_IDLE) {
- subchannel(i)->UpdateConnectivityStateLocked(state);
+ subchannel(i)->UpdateConnectivityStateLocked(state);
}
}
// Start connectivity watch for each subchannel.
for (size_t i = 0; i < num_subchannels(); i++) {
if (subchannel(i)->subchannel() != nullptr) {
subchannel(i)->StartConnectivityWatchLocked();
- subchannel(i)->subchannel()->AttemptToConnect();
+ subchannel(i)->subchannel()->AttemptToConnect();
}
}
- // Now set the LB policy's state based on the subchannels' states.
- UpdateRoundRobinStateFromSubchannelStateCountsLocked();
+ // Now set the LB policy's state based on the subchannels' states.
+ UpdateRoundRobinStateFromSubchannelStateCountsLocked();
}
void RoundRobin::RoundRobinSubchannelList::UpdateStateCountersLocked(
- grpc_connectivity_state old_state, grpc_connectivity_state new_state) {
+ grpc_connectivity_state old_state, grpc_connectivity_state new_state) {
GPR_ASSERT(old_state != GRPC_CHANNEL_SHUTDOWN);
GPR_ASSERT(new_state != GRPC_CHANNEL_SHUTDOWN);
if (old_state == GRPC_CHANNEL_READY) {
@@ -299,8 +299,8 @@ void RoundRobin::RoundRobinSubchannelList::UpdateStateCountersLocked(
}
}
-// Sets the RR policy's connectivity state and generates a new picker based
-// on the current subchannel list.
+// Sets the RR policy's connectivity state and generates a new picker based
+// on the current subchannel list.
void RoundRobin::RoundRobinSubchannelList::
MaybeUpdateRoundRobinConnectivityStateLocked() {
RoundRobin* p = static_cast<RoundRobin*>(policy());
@@ -326,16 +326,16 @@ void RoundRobin::RoundRobinSubchannelList::
GRPC_CHANNEL_READY, y_absl::Status(), y_absl::make_unique<Picker>(p, this));
} else if (num_connecting_ > 0) {
/* 2) CONNECTING */
- p->channel_control_helper()->UpdateState(
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING, y_absl::Status(),
y_absl::make_unique<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker")));
} else if (num_transient_failure_ == num_subchannels()) {
/* 3) TRANSIENT_FAILURE */
- grpc_error* error =
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "connections to all backends failing"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- p->channel_control_helper()->UpdateState(
+ grpc_error* error =
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "connections to all backends failing"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
}
@@ -352,7 +352,7 @@ void RoundRobin::RoundRobinSubchannelList::
// therefore we would not be receiving a notification for them.
GPR_ASSERT(p->latest_pending_subchannel_list_.get() == this);
GPR_ASSERT(!shutting_down());
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
const size_t old_num_subchannels =
p->subchannel_list_ != nullptr
? p->subchannel_list_->num_subchannels()
@@ -371,42 +371,42 @@ void RoundRobin::RoundRobinSubchannelList::
}
void RoundRobin::RoundRobinSubchannelData::UpdateConnectivityStateLocked(
- grpc_connectivity_state connectivity_state) {
+ grpc_connectivity_state connectivity_state) {
RoundRobin* p = static_cast<RoundRobin*>(subchannel_list()->policy());
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
gpr_log(
GPR_INFO,
"[RR %p] connectivity changed for subchannel %p, subchannel_list %p "
"(index %" PRIuPTR " of %" PRIuPTR "): prev_state=%s new_state=%s",
p, subchannel(), subchannel_list(), Index(),
subchannel_list()->num_subchannels(),
- ConnectivityStateName(last_connectivity_state_),
- ConnectivityStateName(connectivity_state));
- }
- // Decide what state to report for aggregation purposes.
- // If we haven't seen a failure since the last time we were in state
- // READY, then we report the state change as-is. However, once we do see
- // a failure, we report TRANSIENT_FAILURE and do not report any subsequent
- // state changes until we go back into state READY.
- if (!seen_failure_since_ready_) {
- if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
- seen_failure_since_ready_ = true;
- }
- subchannel_list()->UpdateStateCountersLocked(last_connectivity_state_,
- connectivity_state);
- } else {
- if (connectivity_state == GRPC_CHANNEL_READY) {
- seen_failure_since_ready_ = false;
- subchannel_list()->UpdateStateCountersLocked(
- GRPC_CHANNEL_TRANSIENT_FAILURE, connectivity_state);
- }
+ ConnectivityStateName(last_connectivity_state_),
+ ConnectivityStateName(connectivity_state));
}
- // Record last seen connectivity state.
+ // Decide what state to report for aggregation purposes.
+ // If we haven't seen a failure since the last time we were in state
+ // READY, then we report the state change as-is. However, once we do see
+ // a failure, we report TRANSIENT_FAILURE and do not report any subsequent
+ // state changes until we go back into state READY.
+ if (!seen_failure_since_ready_) {
+ if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
+ seen_failure_since_ready_ = true;
+ }
+ subchannel_list()->UpdateStateCountersLocked(last_connectivity_state_,
+ connectivity_state);
+ } else {
+ if (connectivity_state == GRPC_CHANNEL_READY) {
+ seen_failure_since_ready_ = false;
+ subchannel_list()->UpdateStateCountersLocked(
+ GRPC_CHANNEL_TRANSIENT_FAILURE, connectivity_state);
+ }
+ }
+ // Record last seen connectivity state.
last_connectivity_state_ = connectivity_state;
}
void RoundRobin::RoundRobinSubchannelData::ProcessConnectivityChangeLocked(
- grpc_connectivity_state connectivity_state) {
+ grpc_connectivity_state connectivity_state) {
RoundRobin* p = static_cast<RoundRobin*>(subchannel_list()->policy());
GPR_ASSERT(subchannel() != nullptr);
// If the new state is TRANSIENT_FAILURE, re-resolve.
@@ -414,31 +414,31 @@ void RoundRobin::RoundRobinSubchannelData::ProcessConnectivityChangeLocked(
// Otherwise, if the subchannel was already in state TRANSIENT_FAILURE
// when the subchannel list was created, we'd wind up in a constant
// loop of re-resolution.
- // Also attempt to reconnect.
+ // Also attempt to reconnect.
if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
gpr_log(GPR_INFO,
"[RR %p] Subchannel %p has gone into TRANSIENT_FAILURE. "
"Requesting re-resolution",
p, subchannel());
}
- p->channel_control_helper()->RequestReresolution();
- subchannel()->AttemptToConnect();
+ p->channel_control_helper()->RequestReresolution();
+ subchannel()->AttemptToConnect();
}
// Update state counters.
- UpdateConnectivityStateLocked(connectivity_state);
+ UpdateConnectivityStateLocked(connectivity_state);
// Update overall state and renew notification.
subchannel_list()->UpdateRoundRobinStateFromSubchannelStateCountsLocked();
}
-void RoundRobin::UpdateLocked(UpdateArgs args) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+void RoundRobin::UpdateLocked(UpdateArgs args) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
gpr_log(GPR_INFO, "[RR %p] received update with %" PRIuPTR " addresses",
- this, args.addresses.size());
+ this, args.addresses.size());
}
// Replace latest_pending_subchannel_list_.
if (latest_pending_subchannel_list_ != nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
gpr_log(GPR_INFO,
"[RR %p] Shutting down previous pending subchannel list %p", this,
latest_pending_subchannel_list_.get());
@@ -446,33 +446,33 @@ void RoundRobin::UpdateLocked(UpdateArgs args) {
}
latest_pending_subchannel_list_ = MakeOrphanable<RoundRobinSubchannelList>(
this, &grpc_lb_round_robin_trace, std::move(args.addresses), *args.args);
- if (latest_pending_subchannel_list_->num_subchannels() == 0) {
- // If the new list is empty, immediately promote the new list to the
- // current list and transition to TRANSIENT_FAILURE.
- grpc_error* error =
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Empty update"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- channel_control_helper()->UpdateState(
+ if (latest_pending_subchannel_list_->num_subchannels() == 0) {
+ // If the new list is empty, immediately promote the new list to the
+ // current list and transition to TRANSIENT_FAILURE.
+ grpc_error* error =
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Empty update"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
subchannel_list_ = std::move(latest_pending_subchannel_list_);
- } else if (subchannel_list_ == nullptr) {
- // If there is no current list, immediately promote the new list to
- // the current list and start watching it.
- subchannel_list_ = std::move(latest_pending_subchannel_list_);
- subchannel_list_->StartWatchingLocked();
+ } else if (subchannel_list_ == nullptr) {
+ // If there is no current list, immediately promote the new list to
+ // the current list and start watching it.
+ subchannel_list_ = std::move(latest_pending_subchannel_list_);
+ subchannel_list_->StartWatchingLocked();
} else {
- // Start watching the pending list. It will get swapped into the
- // current list when it reports READY.
+ // Start watching the pending list. It will get swapped into the
+ // current list when it reports READY.
latest_pending_subchannel_list_->StartWatchingLocked();
}
}
class RoundRobinConfig : public LoadBalancingPolicy::Config {
- public:
- const char* name() const override { return kRoundRobin; }
-};
-
+ public:
+ const char* name() const override { return kRoundRobin; }
+};
+
//
// factory
//
@@ -481,15 +481,15 @@ class RoundRobinFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<RoundRobin>(std::move(args));
+ return MakeOrphanable<RoundRobin>(std::move(args));
}
const char* name() const override { return kRoundRobin; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+
+ RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& /*json*/, grpc_error** /*error*/) const override {
return MakeRefCounted<RoundRobinConfig>();
- }
+ }
};
} // namespace
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h
index db46cd1104..7ff48974ef 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h
@@ -30,10 +30,10 @@
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
#include "src/core/ext/filters/client_channel/server_address.h"
-// TODO(roth): Should not need the include of subchannel.h here, since
-// that implementation should be hidden from the LB policy API.
+// TODO(roth): Should not need the include of subchannel.h here, since
+// that implementation should be hidden from the LB policy API.
#include "src/core/ext/filters/client_channel/subchannel.h"
-#include "src/core/ext/filters/client_channel/subchannel_interface.h"
+#include "src/core/ext/filters/client_channel/subchannel_interface.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/orphanable.h"
@@ -54,7 +54,7 @@ class MySubchannelData
: public SubchannelData<MySubchannelList, MySubchannelData> {
public:
void ProcessConnectivityChangeLocked(
- grpc_connectivity_state connectivity_state) override {
+ grpc_connectivity_state connectivity_state) override {
// ...code to handle connectivity changes...
}
};
@@ -90,16 +90,16 @@ class SubchannelData {
}
// Returns a pointer to the subchannel.
- SubchannelInterface* subchannel() const { return subchannel_.get(); }
+ SubchannelInterface* subchannel() const { return subchannel_.get(); }
// Synchronously checks the subchannel's connectivity state.
// Must not be called while there is a connectivity notification
- // pending (i.e., between calling StartConnectivityWatchLocked() and
- // calling CancelConnectivityWatchLocked()).
- grpc_connectivity_state CheckConnectivityStateLocked() {
- GPR_ASSERT(pending_watcher_ == nullptr);
- connectivity_state_ = subchannel_->CheckConnectivityState();
- return connectivity_state_;
+ // pending (i.e., between calling StartConnectivityWatchLocked() and
+ // calling CancelConnectivityWatchLocked()).
+ grpc_connectivity_state CheckConnectivityStateLocked() {
+ GPR_ASSERT(pending_watcher_ == nullptr);
+ connectivity_state_ = subchannel_->CheckConnectivityState();
+ return connectivity_state_;
}
// Resets the connection backoff.
@@ -108,7 +108,7 @@ class SubchannelData {
void ResetBackoffLocked();
// Starts watching the connectivity state of the subchannel.
- // ProcessConnectivityChangeLocked() will be called whenever the
+ // ProcessConnectivityChangeLocked() will be called whenever the
// connectivity state changes.
void StartConnectivityWatchLocked();
@@ -121,53 +121,53 @@ class SubchannelData {
protected:
SubchannelData(
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list,
- const ServerAddress& address,
- RefCountedPtr<SubchannelInterface> subchannel);
+ const ServerAddress& address,
+ RefCountedPtr<SubchannelInterface> subchannel);
virtual ~SubchannelData();
- // After StartConnectivityWatchLocked() is called, this method will be
- // invoked whenever the subchannel's connectivity state changes.
- // To stop watching, use CancelConnectivityWatchLocked().
+ // After StartConnectivityWatchLocked() is called, this method will be
+ // invoked whenever the subchannel's connectivity state changes.
+ // To stop watching, use CancelConnectivityWatchLocked().
virtual void ProcessConnectivityChangeLocked(
- grpc_connectivity_state connectivity_state) = 0;
-
- private:
- // Watcher for subchannel connectivity state.
- class Watcher
- : public SubchannelInterface::ConnectivityStateWatcherInterface {
- public:
- Watcher(
- SubchannelData<SubchannelListType, SubchannelDataType>* subchannel_data,
- RefCountedPtr<SubchannelListType> subchannel_list)
- : subchannel_data_(subchannel_data),
- subchannel_list_(std::move(subchannel_list)) {}
-
- ~Watcher() { subchannel_list_.reset(DEBUG_LOCATION, "Watcher dtor"); }
-
- void OnConnectivityStateChange(grpc_connectivity_state new_state) override;
-
- grpc_pollset_set* interested_parties() override {
- return subchannel_list_->policy()->interested_parties();
- }
-
- private:
- SubchannelData<SubchannelListType, SubchannelDataType>* subchannel_data_;
- RefCountedPtr<SubchannelListType> subchannel_list_;
- };
-
+ grpc_connectivity_state connectivity_state) = 0;
+
+ private:
+ // Watcher for subchannel connectivity state.
+ class Watcher
+ : public SubchannelInterface::ConnectivityStateWatcherInterface {
+ public:
+ Watcher(
+ SubchannelData<SubchannelListType, SubchannelDataType>* subchannel_data,
+ RefCountedPtr<SubchannelListType> subchannel_list)
+ : subchannel_data_(subchannel_data),
+ subchannel_list_(std::move(subchannel_list)) {}
+
+ ~Watcher() { subchannel_list_.reset(DEBUG_LOCATION, "Watcher dtor"); }
+
+ void OnConnectivityStateChange(grpc_connectivity_state new_state) override;
+
+ grpc_pollset_set* interested_parties() override {
+ return subchannel_list_->policy()->interested_parties();
+ }
+
+ private:
+ SubchannelData<SubchannelListType, SubchannelDataType>* subchannel_data_;
+ RefCountedPtr<SubchannelListType> subchannel_list_;
+ };
+
// Unrefs the subchannel.
void UnrefSubchannelLocked(const char* reason);
// Backpointer to owning subchannel list. Not owned.
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list_;
- // The subchannel.
- RefCountedPtr<SubchannelInterface> subchannel_;
- // Will be non-null when the subchannel's state is being watched.
- SubchannelInterface::ConnectivityStateWatcherInterface* pending_watcher_ =
- nullptr;
- // Data updated by the watcher.
- grpc_connectivity_state connectivity_state_;
+ // The subchannel.
+ RefCountedPtr<SubchannelInterface> subchannel_;
+ // Will be non-null when the subchannel's state is being watched.
+ SubchannelInterface::ConnectivityStateWatcherInterface* pending_watcher_ =
+ nullptr;
+ // Data updated by the watcher.
+ grpc_connectivity_state connectivity_state_;
};
// A list of subchannels.
@@ -202,7 +202,7 @@ class SubchannelList : public InternallyRefCounted<SubchannelListType> {
protected:
SubchannelList(LoadBalancingPolicy* policy, TraceFlag* tracer,
ServerAddressList addresses,
- LoadBalancingPolicy::ChannelControlHelper* helper,
+ LoadBalancingPolicy::ChannelControlHelper* helper,
const grpc_channel_args& args);
virtual ~SubchannelList();
@@ -232,65 +232,65 @@ class SubchannelList : public InternallyRefCounted<SubchannelListType> {
//
//
-// SubchannelData::Watcher
-//
-
-template <typename SubchannelListType, typename SubchannelDataType>
-void SubchannelData<SubchannelListType, SubchannelDataType>::Watcher::
- OnConnectivityStateChange(grpc_connectivity_state new_state) {
- if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
- gpr_log(GPR_INFO,
- "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
- " (subchannel %p): connectivity changed: state=%s, "
- "shutting_down=%d, pending_watcher=%p",
- subchannel_list_->tracer()->name(), subchannel_list_->policy(),
- subchannel_list_.get(), subchannel_data_->Index(),
- subchannel_list_->num_subchannels(),
- subchannel_data_->subchannel_.get(),
- ConnectivityStateName(new_state), subchannel_list_->shutting_down(),
- subchannel_data_->pending_watcher_);
- }
- if (!subchannel_list_->shutting_down() &&
- subchannel_data_->pending_watcher_ != nullptr) {
- subchannel_data_->connectivity_state_ = new_state;
- // Call the subclass's ProcessConnectivityChangeLocked() method.
- subchannel_data_->ProcessConnectivityChangeLocked(new_state);
- }
-}
-
-//
+// SubchannelData::Watcher
+//
+
+template <typename SubchannelListType, typename SubchannelDataType>
+void SubchannelData<SubchannelListType, SubchannelDataType>::Watcher::
+ OnConnectivityStateChange(grpc_connectivity_state new_state) {
+ if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
+ gpr_log(GPR_INFO,
+ "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
+ " (subchannel %p): connectivity changed: state=%s, "
+ "shutting_down=%d, pending_watcher=%p",
+ subchannel_list_->tracer()->name(), subchannel_list_->policy(),
+ subchannel_list_.get(), subchannel_data_->Index(),
+ subchannel_list_->num_subchannels(),
+ subchannel_data_->subchannel_.get(),
+ ConnectivityStateName(new_state), subchannel_list_->shutting_down(),
+ subchannel_data_->pending_watcher_);
+ }
+ if (!subchannel_list_->shutting_down() &&
+ subchannel_data_->pending_watcher_ != nullptr) {
+ subchannel_data_->connectivity_state_ = new_state;
+ // Call the subclass's ProcessConnectivityChangeLocked() method.
+ subchannel_data_->ProcessConnectivityChangeLocked(new_state);
+ }
+}
+
+//
// SubchannelData
//
template <typename SubchannelListType, typename SubchannelDataType>
SubchannelData<SubchannelListType, SubchannelDataType>::SubchannelData(
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list,
- const ServerAddress& /*address*/,
- RefCountedPtr<SubchannelInterface> subchannel)
+ const ServerAddress& /*address*/,
+ RefCountedPtr<SubchannelInterface> subchannel)
: subchannel_list_(subchannel_list),
- subchannel_(std::move(subchannel)),
+ subchannel_(std::move(subchannel)),
// We assume that the current state is IDLE. If not, we'll get a
// callback telling us that.
- connectivity_state_(GRPC_CHANNEL_IDLE) {}
+ connectivity_state_(GRPC_CHANNEL_IDLE) {}
template <typename SubchannelListType, typename SubchannelDataType>
SubchannelData<SubchannelListType, SubchannelDataType>::~SubchannelData() {
- GPR_ASSERT(subchannel_ == nullptr);
+ GPR_ASSERT(subchannel_ == nullptr);
}
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelData<SubchannelListType, SubchannelDataType>::
UnrefSubchannelLocked(const char* reason) {
if (subchannel_ != nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
+ if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
gpr_log(GPR_INFO,
"[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
- " (subchannel %p): unreffing subchannel (%s)",
+ " (subchannel %p): unreffing subchannel (%s)",
subchannel_list_->tracer()->name(), subchannel_list_->policy(),
subchannel_list_, Index(), subchannel_list_->num_subchannels(),
- subchannel_.get(), reason);
+ subchannel_.get(), reason);
}
- subchannel_.reset();
+ subchannel_.reset();
}
}
@@ -305,44 +305,44 @@ void SubchannelData<SubchannelListType,
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelData<SubchannelListType,
SubchannelDataType>::StartConnectivityWatchLocked() {
- if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
+ if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
gpr_log(GPR_INFO,
"[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
- " (subchannel %p): starting watch (from %s)",
+ " (subchannel %p): starting watch (from %s)",
subchannel_list_->tracer()->name(), subchannel_list_->policy(),
subchannel_list_, Index(), subchannel_list_->num_subchannels(),
- subchannel_.get(), ConnectivityStateName(connectivity_state_));
+ subchannel_.get(), ConnectivityStateName(connectivity_state_));
}
- GPR_ASSERT(pending_watcher_ == nullptr);
- pending_watcher_ =
- new Watcher(this, subchannel_list()->Ref(DEBUG_LOCATION, "Watcher"));
- subchannel_->WatchConnectivityState(
- connectivity_state_,
- std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>(
- pending_watcher_));
+ GPR_ASSERT(pending_watcher_ == nullptr);
+ pending_watcher_ =
+ new Watcher(this, subchannel_list()->Ref(DEBUG_LOCATION, "Watcher"));
+ subchannel_->WatchConnectivityState(
+ connectivity_state_,
+ std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>(
+ pending_watcher_));
}
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelData<SubchannelListType, SubchannelDataType>::
CancelConnectivityWatchLocked(const char* reason) {
- if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
+ if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
gpr_log(GPR_INFO,
"[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
" (subchannel %p): canceling connectivity watch (%s)",
subchannel_list_->tracer()->name(), subchannel_list_->policy(),
subchannel_list_, Index(), subchannel_list_->num_subchannels(),
- subchannel_.get(), reason);
+ subchannel_.get(), reason);
}
- if (pending_watcher_ != nullptr) {
- subchannel_->CancelConnectivityStateWatch(pending_watcher_);
- pending_watcher_ = nullptr;
+ if (pending_watcher_ != nullptr) {
+ subchannel_->CancelConnectivityStateWatch(pending_watcher_);
+ pending_watcher_ = nullptr;
}
}
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelData<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
- if (pending_watcher_ != nullptr) CancelConnectivityWatchLocked("shutdown");
- UnrefSubchannelLocked("shutdown");
+ if (pending_watcher_ != nullptr) CancelConnectivityWatchLocked("shutdown");
+ UnrefSubchannelLocked("shutdown");
}
//
@@ -352,12 +352,12 @@ void SubchannelData<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
template <typename SubchannelListType, typename SubchannelDataType>
SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
LoadBalancingPolicy* policy, TraceFlag* tracer, ServerAddressList addresses,
- LoadBalancingPolicy::ChannelControlHelper* helper,
+ LoadBalancingPolicy::ChannelControlHelper* helper,
const grpc_channel_args& args) Y_NO_SANITIZE("undefined")
: InternallyRefCounted<SubchannelListType>(tracer),
policy_(policy),
- tracer_(tracer) {
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ tracer_(tracer) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO,
"[%s %p] Creating subchannel list %p for %" PRIuPTR " subchannels",
tracer_->name(), policy, this, addresses.size());
@@ -365,11 +365,11 @@ SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
subchannels_.reserve(addresses.size());
// Create a subchannel for each address.
for (const ServerAddress& address : addresses) {
- RefCountedPtr<SubchannelInterface> subchannel =
+ RefCountedPtr<SubchannelInterface> subchannel =
helper->CreateSubchannel(std::move(address), args);
if (subchannel == nullptr) {
// Subchannel could not be created.
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO,
"[%s %p] could not create subchannel for address %s, "
"ignoring",
@@ -377,11 +377,11 @@ SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
}
continue;
}
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO,
"[%s %p] subchannel list %p index %" PRIuPTR
": Created subchannel %p for address %s",
- tracer_->name(), policy_, this, subchannels_.size(),
+ tracer_->name(), policy_, this, subchannels_.size(),
subchannel.get(), address.ToString().c_str());
}
subchannels_.emplace_back(this, address, std::move(subchannel));
@@ -390,7 +390,7 @@ SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
template <typename SubchannelListType, typename SubchannelDataType>
SubchannelList<SubchannelListType, SubchannelDataType>::~SubchannelList() {
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO, "[%s %p] Destroying subchannel_list %p", tracer_->name(),
policy_, this);
}
@@ -398,7 +398,7 @@ SubchannelList<SubchannelListType, SubchannelDataType>::~SubchannelList() {
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelList<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO, "[%s %p] Shutting down subchannel_list %p",
tracer_->name(), policy_, this);
}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/cds.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/cds.cc
index b81106cc31..413ba22dc0 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/cds.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/cds.cc
@@ -1,81 +1,81 @@
-//
-// Copyright 2019 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <grpc/support/port_platform.h>
-
-#include <string.h>
-
+//
+// Copyright 2019 gRPC authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/lb_policy.h"
+#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
+#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/ext/xds/xds_client.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/transport/error_utils.h"
-
-namespace grpc_core {
-
-TraceFlag grpc_cds_lb_trace(false, "cds_lb");
-
-namespace {
-
-constexpr char kCds[] = "cds_experimental";
-
+
+namespace grpc_core {
+
+TraceFlag grpc_cds_lb_trace(false, "cds_lb");
+
+namespace {
+
+constexpr char kCds[] = "cds_experimental";
+
// Config for this LB policy.
class CdsLbConfig : public LoadBalancingPolicy::Config {
- public:
+ public:
explicit CdsLbConfig(TString cluster) : cluster_(std::move(cluster)) {}
const TString& cluster() const { return cluster_; }
- const char* name() const override { return kCds; }
-
- private:
+ const char* name() const override { return kCds; }
+
+ private:
TString cluster_;
-};
-
-// CDS LB policy.
-class CdsLb : public LoadBalancingPolicy {
- public:
+};
+
+// CDS LB policy.
+class CdsLb : public LoadBalancingPolicy {
+ public:
CdsLb(RefCountedPtr<XdsClient> xds_client, Args args);
-
- const char* name() const override { return kCds; }
-
- void UpdateLocked(UpdateArgs args) override;
- void ResetBackoffLocked() override;
-
- private:
- // Watcher for getting cluster data from XdsClient.
- class ClusterWatcher : public XdsClient::ClusterWatcherInterface {
- public:
- explicit ClusterWatcher(RefCountedPtr<CdsLb> parent)
- : parent_(std::move(parent)) {}
-
+
+ const char* name() const override { return kCds; }
+
+ void UpdateLocked(UpdateArgs args) override;
+ void ResetBackoffLocked() override;
+
+ private:
+ // Watcher for getting cluster data from XdsClient.
+ class ClusterWatcher : public XdsClient::ClusterWatcherInterface {
+ public:
+ explicit ClusterWatcher(RefCountedPtr<CdsLb> parent)
+ : parent_(std::move(parent)) {}
+
void OnClusterChanged(XdsApi::CdsUpdate cluster_data) override {
new Notifier(parent_, std::move(cluster_data));
}
void OnError(grpc_error* error) override { new Notifier(parent_, error); }
void OnResourceDoesNotExist() override { new Notifier(parent_); }
- private:
+ private:
class Notifier {
public:
Notifier(RefCountedPtr<CdsLb> parent, XdsApi::CdsUpdate update);
@@ -94,71 +94,71 @@ class CdsLb : public LoadBalancingPolicy {
Type type_;
};
- RefCountedPtr<CdsLb> parent_;
- };
-
- // Delegating helper to be passed to child policy.
- class Helper : public ChannelControlHelper {
- public:
- explicit Helper(RefCountedPtr<CdsLb> parent) : parent_(std::move(parent)) {}
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
+ RefCountedPtr<CdsLb> parent_;
+ };
+
+ // Delegating helper to be passed to child policy.
+ class Helper : public ChannelControlHelper {
+ public:
+ explicit Helper(RefCountedPtr<CdsLb> parent) : parent_(std::move(parent)) {}
+ RefCountedPtr<SubchannelInterface> CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) override;
void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override;
- void RequestReresolution() override;
+ std::unique_ptr<SubchannelPicker> picker) override;
+ void RequestReresolution() override;
void AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) override;
-
- private:
- RefCountedPtr<CdsLb> parent_;
- };
-
- ~CdsLb();
-
- void ShutdownLocked() override;
-
+
+ private:
+ RefCountedPtr<CdsLb> parent_;
+ };
+
+ ~CdsLb();
+
+ void ShutdownLocked() override;
+
void OnClusterChanged(XdsApi::CdsUpdate cluster_data);
void OnError(grpc_error* error);
void OnResourceDoesNotExist();
void MaybeDestroyChildPolicyLocked();
-
+
RefCountedPtr<CdsLbConfig> config_;
- // Current channel args from the resolver.
- const grpc_channel_args* args_ = nullptr;
-
- // The xds client.
- RefCountedPtr<XdsClient> xds_client_;
- // A pointer to the cluster watcher, to be used when cancelling the watch.
- // Note that this is not owned, so this pointer must never be derefernced.
- ClusterWatcher* cluster_watcher_ = nullptr;
-
- // Child LB policy.
- OrphanablePtr<LoadBalancingPolicy> child_policy_;
-
- // Internal state.
- bool shutting_down_ = false;
-};
-
-//
+ // Current channel args from the resolver.
+ const grpc_channel_args* args_ = nullptr;
+
+ // The xds client.
+ RefCountedPtr<XdsClient> xds_client_;
+ // A pointer to the cluster watcher, to be used when cancelling the watch.
+ // Note that this is not owned, so this pointer must never be derefernced.
+ ClusterWatcher* cluster_watcher_ = nullptr;
+
+ // Child LB policy.
+ OrphanablePtr<LoadBalancingPolicy> child_policy_;
+
+ // Internal state.
+ bool shutting_down_ = false;
+};
+
+//
// CdsLb::ClusterWatcher::Notifier
-//
-
+//
+
CdsLb::ClusterWatcher::Notifier::Notifier(RefCountedPtr<CdsLb> parent,
XdsApi::CdsUpdate update)
: parent_(std::move(parent)), update_(std::move(update)), type_(kUpdate) {
GRPC_CLOSURE_INIT(&closure_, &RunInExecCtx, this, nullptr);
ExecCtx::Run(DEBUG_LOCATION, &closure_, GRPC_ERROR_NONE);
-}
-
+}
+
CdsLb::ClusterWatcher::Notifier::Notifier(RefCountedPtr<CdsLb> parent,
grpc_error* error)
: parent_(std::move(parent)), type_(kError) {
GRPC_CLOSURE_INIT(&closure_, &RunInExecCtx, this, nullptr);
ExecCtx::Run(DEBUG_LOCATION, &closure_, error);
-}
-
+}
+
CdsLb::ClusterWatcher::Notifier::Notifier(RefCountedPtr<CdsLb> parent)
: parent_(std::move(parent)), type_(kDoesNotExist) {
GRPC_CLOSURE_INIT(&closure_, &RunInExecCtx, this, nullptr);
@@ -188,83 +188,83 @@ void CdsLb::ClusterWatcher::Notifier::RunInWorkSerializer(grpc_error* error) {
delete this;
}
-//
-// CdsLb::Helper
-//
-
-RefCountedPtr<SubchannelInterface> CdsLb::Helper::CreateSubchannel(
+//
+// CdsLb::Helper
+//
+
+RefCountedPtr<SubchannelInterface> CdsLb::Helper::CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) {
- if (parent_->shutting_down_) return nullptr;
+ if (parent_->shutting_down_) return nullptr;
return parent_->channel_control_helper()->CreateSubchannel(std::move(address),
args);
-}
-
-void CdsLb::Helper::UpdateState(grpc_connectivity_state state,
+}
+
+void CdsLb::Helper::UpdateState(grpc_connectivity_state state,
const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) {
+ std::unique_ptr<SubchannelPicker> picker) {
if (parent_->shutting_down_ || parent_->child_policy_ == nullptr) return;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO,
"[cdslb %p] state updated by child: %s message_state: (%s)", this,
ConnectivityStateName(state), status.ToString().c_str());
- }
+ }
parent_->channel_control_helper()->UpdateState(state, status,
std::move(picker));
-}
-
-void CdsLb::Helper::RequestReresolution() {
- if (parent_->shutting_down_) return;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
- gpr_log(GPR_INFO, "[cdslb %p] Re-resolution requested from child policy.",
- parent_.get());
- }
- parent_->channel_control_helper()->RequestReresolution();
-}
-
+}
+
+void CdsLb::Helper::RequestReresolution() {
+ if (parent_->shutting_down_) return;
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
+ gpr_log(GPR_INFO, "[cdslb %p] Re-resolution requested from child policy.",
+ parent_.get());
+ }
+ parent_->channel_control_helper()->RequestReresolution();
+}
+
void CdsLb::Helper::AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) {
- if (parent_->shutting_down_) return;
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
-}
-
-//
-// CdsLb
-//
-
+ if (parent_->shutting_down_) return;
+ parent_->channel_control_helper()->AddTraceEvent(severity, message);
+}
+
+//
+// CdsLb
+//
+
CdsLb::CdsLb(RefCountedPtr<XdsClient> xds_client, Args args)
: LoadBalancingPolicy(std::move(args)), xds_client_(std::move(xds_client)) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO, "[cdslb %p] created -- using xds client %p", this,
xds_client_.get());
- }
-}
-
-CdsLb::~CdsLb() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
- gpr_log(GPR_INFO, "[cdslb %p] destroying cds LB policy", this);
- }
-}
-
-void CdsLb::ShutdownLocked() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
- gpr_log(GPR_INFO, "[cdslb %p] shutting down", this);
- }
- shutting_down_ = true;
+ }
+}
+
+CdsLb::~CdsLb() {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
+ gpr_log(GPR_INFO, "[cdslb %p] destroying cds LB policy", this);
+ }
+}
+
+void CdsLb::ShutdownLocked() {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
+ gpr_log(GPR_INFO, "[cdslb %p] shutting down", this);
+ }
+ shutting_down_ = true;
MaybeDestroyChildPolicyLocked();
- if (xds_client_ != nullptr) {
- if (cluster_watcher_ != nullptr) {
+ if (xds_client_ != nullptr) {
+ if (cluster_watcher_ != nullptr) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO, "[cdslb %p] cancelling watch for cluster %s", this,
config_->cluster().c_str());
}
xds_client_->CancelClusterDataWatch(config_->cluster(), cluster_watcher_);
- }
+ }
xds_client_.reset(DEBUG_LOCATION, "CdsLb");
- }
+ }
grpc_channel_args_destroy(args_);
args_ = nullptr;
-}
-
+}
+
void CdsLb::MaybeDestroyChildPolicyLocked() {
if (child_policy_ != nullptr) {
grpc_pollset_set_del_pollset_set(child_policy_->interested_parties(),
@@ -273,25 +273,25 @@ void CdsLb::MaybeDestroyChildPolicyLocked() {
}
}
-void CdsLb::ResetBackoffLocked() {
- if (child_policy_ != nullptr) child_policy_->ResetBackoffLocked();
-}
-
-void CdsLb::UpdateLocked(UpdateArgs args) {
- // Update config.
- auto old_config = std::move(config_);
- config_ = std::move(args.config);
+void CdsLb::ResetBackoffLocked() {
+ if (child_policy_ != nullptr) child_policy_->ResetBackoffLocked();
+}
+
+void CdsLb::UpdateLocked(UpdateArgs args) {
+ // Update config.
+ auto old_config = std::move(config_);
+ config_ = std::move(args.config);
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO, "[cdslb %p] received update: cluster=%s", this,
config_->cluster().c_str());
}
- // Update args.
- grpc_channel_args_destroy(args_);
- args_ = args.args;
- args.args = nullptr;
- // If cluster name changed, cancel watcher and restart.
+ // Update args.
+ grpc_channel_args_destroy(args_);
+ args_ = args.args;
+ args.args = nullptr;
+ // If cluster name changed, cancel watcher and restart.
if (old_config == nullptr || old_config->cluster() != config_->cluster()) {
- if (old_config != nullptr) {
+ if (old_config != nullptr) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO, "[cdslb %p] cancelling watch for cluster %s", this,
old_config->cluster().c_str());
@@ -299,17 +299,17 @@ void CdsLb::UpdateLocked(UpdateArgs args) {
xds_client_->CancelClusterDataWatch(old_config->cluster(),
cluster_watcher_,
/*delay_unsubscription=*/true);
- }
+ }
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO, "[cdslb %p] starting watch for cluster %s", this,
config_->cluster().c_str());
}
auto watcher = y_absl::make_unique<ClusterWatcher>(Ref());
- cluster_watcher_ = watcher.get();
+ cluster_watcher_ = watcher.get();
xds_client_->WatchClusterData(config_->cluster(), std::move(watcher));
- }
-}
-
+ }
+}
+
void CdsLb::OnClusterChanged(XdsApi::CdsUpdate cluster_data) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO,
@@ -425,14 +425,14 @@ void CdsLb::OnResourceDoesNotExist() {
MaybeDestroyChildPolicyLocked();
}
-//
-// factory
-//
-
+//
+// factory
+//
+
class CdsLbFactory : public LoadBalancingPolicyFactory {
- public:
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args args) const override {
+ public:
+ OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+ LoadBalancingPolicy::Args args) const override {
grpc_error* error = GRPC_ERROR_NONE;
RefCountedPtr<XdsClient> xds_client = XdsClient::GetOrCreate(&error);
if (error != GRPC_ERROR_NONE) {
@@ -443,53 +443,53 @@ class CdsLbFactory : public LoadBalancingPolicyFactory {
return nullptr;
}
return MakeOrphanable<CdsLb>(std::move(xds_client), std::move(args));
- }
-
- const char* name() const override { return kCds; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+ }
+
+ const char* name() const override { return kCds; }
+
+ RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error) const override {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
if (json.type() == Json::Type::JSON_NULL) {
- // xds was mentioned as a policy in the deprecated loadBalancingPolicy
- // field or in the client API.
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:loadBalancingPolicy error:cds policy requires configuration. "
- "Please use loadBalancingConfig field of service config instead.");
- return nullptr;
- }
+ // xds was mentioned as a policy in the deprecated loadBalancingPolicy
+ // field or in the client API.
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:loadBalancingPolicy error:cds policy requires configuration. "
+ "Please use loadBalancingConfig field of service config instead.");
+ return nullptr;
+ }
std::vector<grpc_error*> error_list;
TString cluster;
auto it = json.object_value().find("cluster");
if (it == json.object_value().end()) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "required field 'cluster' not present"));
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "required field 'cluster' not present"));
} else if (it->second.type() != Json::Type::STRING) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:cluster error:type should be string"));
} else {
cluster = it->second.string_value();
- }
+ }
if (!error_list.empty()) {
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("Cds Parser", &error_list);
- return nullptr;
- }
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("Cds Parser", &error_list);
+ return nullptr;
+ }
return MakeRefCounted<CdsLbConfig>(std::move(cluster));
- }
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-//
-// Plugin registration
-//
-
-void grpc_lb_policy_cds_init() {
- grpc_core::LoadBalancingPolicyRegistry::Builder::
- RegisterLoadBalancingPolicyFactory(
+ }
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+//
+// Plugin registration
+//
+
+void grpc_lb_policy_cds_init() {
+ grpc_core::LoadBalancingPolicyRegistry::Builder::
+ RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<grpc_core::CdsLbFactory>());
-}
-
-void grpc_lb_policy_cds_shutdown() {}
+}
+
+void grpc_lb_policy_cds_shutdown() {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h
index 1de3472a3a..e80e42af38 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h
@@ -24,8 +24,8 @@
/** Channel arg indicating if a target corresponding to the address is a backend
* received from a balancer. The type of this arg is an integer and the value is
* treated as a bool. */
-// TODO(roth): Depending on how we ultimately decide to handle fallback,
-// this may no longer be needed.
+// TODO(roth): Depending on how we ultimately decide to handle fallback,
+// this may no longer be needed.
#define GRPC_ARG_ADDRESS_IS_BACKEND_FROM_XDS_LOAD_BALANCER \
"grpc.address_is_backend_from_xds_load_balancer"
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h
index 9e4425fa44..fc090f62e8 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h
@@ -32,13 +32,13 @@ class LoadBalancingPolicyFactory {
/// Returns a new LB policy instance.
virtual OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args) const = 0;
+ LoadBalancingPolicy::Args) const = 0;
/// Returns the LB policy name that this factory provides.
/// Caller does NOT take ownership of result.
- virtual const char* name() const = 0;
+ virtual const char* name() const = 0;
- virtual RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+ virtual RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error) const = 0;
};
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc
index 463e54a2e6..23bd2aa623 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc
@@ -38,7 +38,7 @@ class RegistryState {
RegistryState() {}
void RegisterLoadBalancingPolicyFactory(
- std::unique_ptr<LoadBalancingPolicyFactory> factory) {
+ std::unique_ptr<LoadBalancingPolicyFactory> factory) {
gpr_log(GPR_DEBUG, "registering LB policy factory for \"%s\"",
factory->name());
for (size_t i = 0; i < factories_.size(); ++i) {
@@ -71,16 +71,16 @@ RegistryState* g_state = nullptr;
//
void LoadBalancingPolicyRegistry::Builder::InitRegistry() {
- if (g_state == nullptr) g_state = new RegistryState();
+ if (g_state == nullptr) g_state = new RegistryState();
}
void LoadBalancingPolicyRegistry::Builder::ShutdownRegistry() {
- delete g_state;
+ delete g_state;
g_state = nullptr;
}
void LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
- std::unique_ptr<LoadBalancingPolicyFactory> factory) {
+ std::unique_ptr<LoadBalancingPolicyFactory> factory) {
InitRegistry();
g_state->RegisterLoadBalancingPolicyFactory(std::move(factory));
}
@@ -101,77 +101,77 @@ LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
return factory->CreateLoadBalancingPolicy(std::move(args));
}
-bool LoadBalancingPolicyRegistry::LoadBalancingPolicyExists(
- const char* name, bool* requires_config) {
+bool LoadBalancingPolicyRegistry::LoadBalancingPolicyExists(
+ const char* name, bool* requires_config) {
GPR_ASSERT(g_state != nullptr);
- auto* factory = g_state->GetLoadBalancingPolicyFactory(name);
- if (factory == nullptr) {
- return false;
- }
- if (requires_config != nullptr) {
- grpc_error* error = GRPC_ERROR_NONE;
- // Check if the load balancing policy allows an empty config
- *requires_config =
+ auto* factory = g_state->GetLoadBalancingPolicyFactory(name);
+ if (factory == nullptr) {
+ return false;
+ }
+ if (requires_config != nullptr) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ // Check if the load balancing policy allows an empty config
+ *requires_config =
factory->ParseLoadBalancingConfig(Json(), &error) == nullptr;
- GRPC_ERROR_UNREF(error);
- }
- return true;
+ GRPC_ERROR_UNREF(error);
+ }
+ return true;
}
-namespace {
+namespace {
-// Returns the JSON node of policy (with both policy name and config content)
-// given the JSON node of a LoadBalancingConfig array.
+// Returns the JSON node of policy (with both policy name and config content)
+// given the JSON node of a LoadBalancingConfig array.
grpc_error* ParseLoadBalancingConfigHelper(
const Json& lb_config_array, Json::Object::const_iterator* result) {
if (lb_config_array.type() != Json::Type::ARRAY) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING("type should be array");
- }
- // Find the first LB policy that this client supports.
+ }
+ // Find the first LB policy that this client supports.
std::vector<y_absl::string_view> policies_tried;
for (const Json& lb_config : lb_config_array.array_value()) {
if (lb_config.type() != Json::Type::OBJECT) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"child entry should be of type object");
- }
+ }
if (lb_config.object_value().empty()) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"no policy found in child entry");
- }
+ }
if (lb_config.object_value().size() > 1) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING("oneOf violation");
- }
+ }
auto it = lb_config.object_value().begin();
if (it->second.type() != Json::Type::OBJECT) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"child entry should be of type object");
}
- // If we support this policy, then select it.
+ // If we support this policy, then select it.
if (LoadBalancingPolicyRegistry::LoadBalancingPolicyExists(
it->first.c_str(), nullptr)) {
*result = it;
return GRPC_ERROR_NONE;
- }
+ }
policies_tried.push_back(it->first);
- }
+ }
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("No known policies in list: ",
y_absl::StrJoin(policies_tried, " "))
.c_str());
-}
+}
-} // namespace
-
-RefCountedPtr<LoadBalancingPolicy::Config>
+} // namespace
+
+RefCountedPtr<LoadBalancingPolicy::Config>
LoadBalancingPolicyRegistry::ParseLoadBalancingConfig(const Json& json,
- grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
- GPR_ASSERT(g_state != nullptr);
+ grpc_error** error) {
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ GPR_ASSERT(g_state != nullptr);
Json::Object::const_iterator policy;
*error = ParseLoadBalancingConfigHelper(json, &policy);
if (*error != GRPC_ERROR_NONE) {
- return nullptr;
- }
+ return nullptr;
+ }
// Find factory.
LoadBalancingPolicyFactory* factory =
g_state->GetLoadBalancingPolicyFactory(policy->first.c_str());
@@ -183,6 +183,6 @@ LoadBalancingPolicyRegistry::ParseLoadBalancingConfig(const Json& json,
}
// Parse load balancing config via factory.
return factory->ParseLoadBalancingConfig(policy->second, error);
-}
-
+}
+
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h
index 8d2e3e395d..bef317c9de 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h
@@ -41,7 +41,7 @@ class LoadBalancingPolicyRegistry {
/// Registers an LB policy factory. The factory will be used to create an
/// LB policy whose name matches that of the factory.
static void RegisterLoadBalancingPolicyFactory(
- std::unique_ptr<LoadBalancingPolicyFactory> factory);
+ std::unique_ptr<LoadBalancingPolicyFactory> factory);
};
/// Creates an LB policy of the type specified by \a name.
@@ -49,14 +49,14 @@ class LoadBalancingPolicyRegistry {
const char* name, LoadBalancingPolicy::Args args);
/// Returns true if the LB policy factory specified by \a name exists in this
- /// registry. If the load balancing policy requires a config to be specified
- /// then sets \a requires_config to true.
- static bool LoadBalancingPolicyExists(const char* name,
- bool* requires_config);
-
- /// Returns a parsed object of the load balancing policy to be used from a
- /// LoadBalancingConfig array \a json.
- static RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+ /// registry. If the load balancing policy requires a config to be specified
+ /// then sets \a requires_config to true.
+ static bool LoadBalancingPolicyExists(const char* name,
+ bool* requires_config);
+
+ /// Returns a parsed object of the load balancing policy to be used from a
+ /// LoadBalancingConfig array \a json.
+ static RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error);
};
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc
index e57599962a..6452979ae2 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc
@@ -43,7 +43,7 @@ Subchannel* LocalSubchannelPool::RegisterSubchannel(SubchannelKey* key,
GRPC_SUBCHANNEL_UNREF(constructed, "subchannel_register+found_existing");
} else {
// There hasn't been such subchannel. Add one.
- subchannel_map_ = grpc_avl_add(subchannel_map_, new SubchannelKey(*key),
+ subchannel_map_ = grpc_avl_add(subchannel_map_, new SubchannelKey(*key),
constructed, nullptr);
c = constructed;
}
@@ -62,26 +62,26 @@ Subchannel* LocalSubchannelPool::FindSubchannel(SubchannelKey* key) {
namespace {
-void sck_avl_destroy(void* p, void* /*user_data*/) {
+void sck_avl_destroy(void* p, void* /*user_data*/) {
SubchannelKey* key = static_cast<SubchannelKey*>(p);
- delete key;
+ delete key;
}
-void* sck_avl_copy(void* p, void* /*unused*/) {
+void* sck_avl_copy(void* p, void* /*unused*/) {
const SubchannelKey* key = static_cast<const SubchannelKey*>(p);
- auto new_key = new SubchannelKey(*key);
+ auto new_key = new SubchannelKey(*key);
return static_cast<void*>(new_key);
}
-long sck_avl_compare(void* a, void* b, void* /*unused*/) {
+long sck_avl_compare(void* a, void* b, void* /*unused*/) {
const SubchannelKey* key_a = static_cast<const SubchannelKey*>(a);
const SubchannelKey* key_b = static_cast<const SubchannelKey*>(b);
return key_a->Cmp(*key_b);
}
-void scv_avl_destroy(void* /*p*/, void* /*user_data*/) {}
+void scv_avl_destroy(void* /*p*/, void* /*user_data*/) {}
-void* scv_avl_copy(void* p, void* /*unused*/) { return p; }
+void* scv_avl_copy(void* p, void* /*unused*/) { return p; }
} // namespace
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper.h
index 3e297d9a6f..87da943f10 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper.h
@@ -25,30 +25,30 @@
#include "src/core/lib/iomgr/resolve_address.h"
-namespace grpc_core {
-
-class ProxyMapperInterface {
- public:
- virtual ~ProxyMapperInterface() = default;
+namespace grpc_core {
+class ProxyMapperInterface {
+ public:
+ virtual ~ProxyMapperInterface() = default;
+
/// Determines the proxy name to resolve for \a server_uri.
/// If no proxy is needed, returns false.
/// Otherwise, sets \a name_to_resolve, optionally sets \a new_args,
/// and returns true.
- virtual bool MapName(const char* server_uri, const grpc_channel_args* args,
- char** name_to_resolve,
- grpc_channel_args** new_args) = 0;
-
+ virtual bool MapName(const char* server_uri, const grpc_channel_args* args,
+ char** name_to_resolve,
+ grpc_channel_args** new_args) = 0;
+
/// Determines the proxy address to use to contact \a address.
/// If no proxy is needed, returns false.
/// Otherwise, sets \a new_address, optionally sets \a new_args, and
/// returns true.
- virtual bool MapAddress(const grpc_resolved_address& address,
- const grpc_channel_args* args,
- grpc_resolved_address** new_address,
- grpc_channel_args** new_args) = 0;
+ virtual bool MapAddress(const grpc_resolved_address& address,
+ const grpc_channel_args* args,
+ grpc_resolved_address** new_address,
+ grpc_channel_args** new_args) = 0;
};
-} // namespace grpc_core
+} // namespace grpc_core
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.cc
index 2fc2572525..e3cfdc2cb1 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.cc
@@ -20,70 +20,70 @@
#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
-#include <memory>
-#include <vector>
+#include <memory>
+#include <vector>
-namespace grpc_core {
+namespace grpc_core {
-namespace {
+namespace {
-using ProxyMapperList = std::vector<std::unique_ptr<ProxyMapperInterface>>;
-ProxyMapperList* g_proxy_mapper_list;
+using ProxyMapperList = std::vector<std::unique_ptr<ProxyMapperInterface>>;
+ProxyMapperList* g_proxy_mapper_list;
-} // namespace
-
-void ProxyMapperRegistry::Init() {
- if (g_proxy_mapper_list == nullptr) {
- g_proxy_mapper_list = new ProxyMapperList();
- }
-}
-
-void ProxyMapperRegistry::Shutdown() {
- delete g_proxy_mapper_list;
- // Clean up in case we re-initialze later.
- // TODO(roth): This should ideally live in Init(). However, if we did this
- // there, then we would do it AFTER we start registering proxy mappers from
- // third-party plugins, so they'd never show up (and would leak memory).
- // We probably need some sort of dependency system for plugins to fix
- // this.
- g_proxy_mapper_list = nullptr;
-}
-
-void ProxyMapperRegistry::Register(
- bool at_start, std::unique_ptr<ProxyMapperInterface> mapper) {
- Init();
+} // namespace
+
+void ProxyMapperRegistry::Init() {
+ if (g_proxy_mapper_list == nullptr) {
+ g_proxy_mapper_list = new ProxyMapperList();
+ }
+}
+
+void ProxyMapperRegistry::Shutdown() {
+ delete g_proxy_mapper_list;
+ // Clean up in case we re-initialze later.
+ // TODO(roth): This should ideally live in Init(). However, if we did this
+ // there, then we would do it AFTER we start registering proxy mappers from
+ // third-party plugins, so they'd never show up (and would leak memory).
+ // We probably need some sort of dependency system for plugins to fix
+ // this.
+ g_proxy_mapper_list = nullptr;
+}
+
+void ProxyMapperRegistry::Register(
+ bool at_start, std::unique_ptr<ProxyMapperInterface> mapper) {
+ Init();
if (at_start) {
- g_proxy_mapper_list->insert(g_proxy_mapper_list->begin(),
- std::move(mapper));
+ g_proxy_mapper_list->insert(g_proxy_mapper_list->begin(),
+ std::move(mapper));
} else {
- g_proxy_mapper_list->emplace_back(std::move(mapper));
+ g_proxy_mapper_list->emplace_back(std::move(mapper));
}
}
-bool ProxyMapperRegistry::MapName(const char* server_uri,
- const grpc_channel_args* args,
- char** name_to_resolve,
- grpc_channel_args** new_args) {
- Init();
- for (const auto& mapper : *g_proxy_mapper_list) {
- if (mapper->MapName(server_uri, args, name_to_resolve, new_args)) {
+bool ProxyMapperRegistry::MapName(const char* server_uri,
+ const grpc_channel_args* args,
+ char** name_to_resolve,
+ grpc_channel_args** new_args) {
+ Init();
+ for (const auto& mapper : *g_proxy_mapper_list) {
+ if (mapper->MapName(server_uri, args, name_to_resolve, new_args)) {
return true;
}
}
return false;
}
-bool ProxyMapperRegistry::MapAddress(const grpc_resolved_address& address,
- const grpc_channel_args* args,
- grpc_resolved_address** new_address,
- grpc_channel_args** new_args) {
- Init();
- for (const auto& mapper : *g_proxy_mapper_list) {
- if (mapper->MapAddress(address, args, new_address, new_args)) {
+bool ProxyMapperRegistry::MapAddress(const grpc_resolved_address& address,
+ const grpc_channel_args* args,
+ grpc_resolved_address** new_address,
+ grpc_channel_args** new_args) {
+ Init();
+ for (const auto& mapper : *g_proxy_mapper_list) {
+ if (mapper->MapAddress(address, args, new_address, new_args)) {
return true;
}
}
return false;
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h
index b6273e1adf..1a3108d89e 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h
@@ -23,28 +23,28 @@
#include "src/core/ext/filters/client_channel/proxy_mapper.h"
-namespace grpc_core {
-
-class ProxyMapperRegistry {
- public:
- static void Init();
- static void Shutdown();
-
- /// Registers a new proxy mapper.
- /// If \a at_start is true, the new mapper will be at the beginning of
- /// the list. Otherwise, it will be added to the end.
- static void Register(bool at_start,
- std::unique_ptr<ProxyMapperInterface> mapper);
-
- static bool MapName(const char* server_uri, const grpc_channel_args* args,
- char** name_to_resolve, grpc_channel_args** new_args);
-
- static bool MapAddress(const grpc_resolved_address& address,
- const grpc_channel_args* args,
- grpc_resolved_address** new_address,
- grpc_channel_args** new_args);
-};
-
-} // namespace grpc_core
-
+namespace grpc_core {
+
+class ProxyMapperRegistry {
+ public:
+ static void Init();
+ static void Shutdown();
+
+ /// Registers a new proxy mapper.
+ /// If \a at_start is true, the new mapper will be at the beginning of
+ /// the list. Otherwise, it will be added to the end.
+ static void Register(bool at_start,
+ std::unique_ptr<ProxyMapperInterface> mapper);
+
+ static bool MapName(const char* server_uri, const grpc_channel_args* args,
+ char** name_to_resolve, grpc_channel_args** new_args);
+
+ static bool MapAddress(const grpc_resolved_address& address,
+ const grpc_channel_args* args,
+ grpc_resolved_address** new_address,
+ grpc_channel_args** new_args);
+};
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc
index 4a76a7d7bd..4a45ebeab4 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc
@@ -25,61 +25,61 @@ grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount(false,
namespace grpc_core {
-//
-// Resolver
-//
-
+//
+// Resolver
+//
+
Resolver::Resolver(std::shared_ptr<WorkSerializer> work_serializer,
- std::unique_ptr<ResultHandler> result_handler)
+ std::unique_ptr<ResultHandler> result_handler)
: InternallyRefCounted(&grpc_trace_resolver_refcount),
work_serializer_(std::move(work_serializer)),
result_handler_(std::move(result_handler)) {}
-//
-// Resolver::Result
-//
-
-Resolver::Result::~Result() {
- GRPC_ERROR_UNREF(service_config_error);
- grpc_channel_args_destroy(args);
-}
-
-Resolver::Result::Result(const Result& other) {
- addresses = other.addresses;
- service_config = other.service_config;
- service_config_error = GRPC_ERROR_REF(other.service_config_error);
- args = grpc_channel_args_copy(other.args);
-}
-
+//
+// Resolver::Result
+//
+
+Resolver::Result::~Result() {
+ GRPC_ERROR_UNREF(service_config_error);
+ grpc_channel_args_destroy(args);
+}
+
+Resolver::Result::Result(const Result& other) {
+ addresses = other.addresses;
+ service_config = other.service_config;
+ service_config_error = GRPC_ERROR_REF(other.service_config_error);
+ args = grpc_channel_args_copy(other.args);
+}
+
Resolver::Result::Result(Result&& other) noexcept {
- addresses = std::move(other.addresses);
- service_config = std::move(other.service_config);
- service_config_error = other.service_config_error;
- other.service_config_error = GRPC_ERROR_NONE;
- args = other.args;
- other.args = nullptr;
-}
-
-Resolver::Result& Resolver::Result::operator=(const Result& other) {
- addresses = other.addresses;
- service_config = other.service_config;
- GRPC_ERROR_UNREF(service_config_error);
- service_config_error = GRPC_ERROR_REF(other.service_config_error);
- grpc_channel_args_destroy(args);
- args = grpc_channel_args_copy(other.args);
- return *this;
-}
-
+ addresses = std::move(other.addresses);
+ service_config = std::move(other.service_config);
+ service_config_error = other.service_config_error;
+ other.service_config_error = GRPC_ERROR_NONE;
+ args = other.args;
+ other.args = nullptr;
+}
+
+Resolver::Result& Resolver::Result::operator=(const Result& other) {
+ addresses = other.addresses;
+ service_config = other.service_config;
+ GRPC_ERROR_UNREF(service_config_error);
+ service_config_error = GRPC_ERROR_REF(other.service_config_error);
+ grpc_channel_args_destroy(args);
+ args = grpc_channel_args_copy(other.args);
+ return *this;
+}
+
Resolver::Result& Resolver::Result::operator=(Result&& other) noexcept {
- addresses = std::move(other.addresses);
- service_config = std::move(other.service_config);
- GRPC_ERROR_UNREF(service_config_error);
- service_config_error = other.service_config_error;
- other.service_config_error = GRPC_ERROR_NONE;
- grpc_channel_args_destroy(args);
- args = other.args;
- other.args = nullptr;
- return *this;
-}
-
+ addresses = std::move(other.addresses);
+ service_config = std::move(other.service_config);
+ GRPC_ERROR_UNREF(service_config_error);
+ service_config_error = other.service_config_error;
+ other.service_config_error = GRPC_ERROR_NONE;
+ grpc_channel_args_destroy(args);
+ args = other.args;
+ other.args = nullptr;
+ return *this;
+}
+
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h
index de941a063b..053325ee9e 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h
@@ -23,10 +23,10 @@
#include <grpc/impl/codegen/grpc_types.h>
-#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/server_address.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/work_serializer.h"
@@ -48,49 +48,49 @@ namespace grpc_core {
/// work_serializer passed to the constructor.
class Resolver : public InternallyRefCounted<Resolver> {
public:
- /// Results returned by the resolver.
- struct Result {
- ServerAddressList addresses;
- RefCountedPtr<ServiceConfig> service_config;
- grpc_error* service_config_error = GRPC_ERROR_NONE;
- const grpc_channel_args* args = nullptr;
-
- // TODO(roth): Remove everything below once grpc_error and
- // grpc_channel_args are convert to copyable and movable C++ objects.
- Result() = default;
- ~Result();
- Result(const Result& other);
+ /// Results returned by the resolver.
+ struct Result {
+ ServerAddressList addresses;
+ RefCountedPtr<ServiceConfig> service_config;
+ grpc_error* service_config_error = GRPC_ERROR_NONE;
+ const grpc_channel_args* args = nullptr;
+
+ // TODO(roth): Remove everything below once grpc_error and
+ // grpc_channel_args are convert to copyable and movable C++ objects.
+ Result() = default;
+ ~Result();
+ Result(const Result& other);
Result(Result&& other) noexcept;
- Result& operator=(const Result& other);
+ Result& operator=(const Result& other);
Result& operator=(Result&& other) noexcept;
- };
-
- /// A proxy object used by the resolver to return results to the
- /// client channel.
- class ResultHandler {
- public:
- virtual ~ResultHandler() {}
-
- /// Returns a result to the channel.
- /// Takes ownership of \a result.args.
- virtual void ReturnResult(Result result) = 0; // NOLINT
-
- /// Returns a transient error to the channel.
- /// If the resolver does not set the GRPC_ERROR_INT_GRPC_STATUS
- /// attribute on the error, calls will be failed with status UNKNOWN.
- virtual void ReturnError(grpc_error* error) = 0;
-
- // TODO(yashkt): As part of the service config error handling
- // changes, add a method to parse the service config JSON string.
- };
-
+ };
+
+ /// A proxy object used by the resolver to return results to the
+ /// client channel.
+ class ResultHandler {
+ public:
+ virtual ~ResultHandler() {}
+
+ /// Returns a result to the channel.
+ /// Takes ownership of \a result.args.
+ virtual void ReturnResult(Result result) = 0; // NOLINT
+
+ /// Returns a transient error to the channel.
+ /// If the resolver does not set the GRPC_ERROR_INT_GRPC_STATUS
+ /// attribute on the error, calls will be failed with status UNKNOWN.
+ virtual void ReturnError(grpc_error* error) = 0;
+
+ // TODO(yashkt): As part of the service config error handling
+ // changes, add a method to parse the service config JSON string.
+ };
+
// Not copyable nor movable.
Resolver(const Resolver&) = delete;
Resolver& operator=(const Resolver&) = delete;
virtual ~Resolver() = default;
- /// Starts resolving.
- virtual void StartLocked() = 0;
+ /// Starts resolving.
+ virtual void StartLocked() = 0;
/// Asks the resolver to obtain an updated resolver result, if
/// applicable.
@@ -103,8 +103,8 @@ class Resolver : public InternallyRefCounted<Resolver> {
///
/// For push-based implementations, this may be a no-op.
///
- /// Note: Implementations must not invoke any method on the
- /// ResultHandler from within this call.
+ /// Note: Implementations must not invoke any method on the
+ /// ResultHandler from within this call.
virtual void RequestReresolutionLocked() {}
/// Resets the re-resolution backoff, if any.
@@ -117,26 +117,26 @@ class Resolver : public InternallyRefCounted<Resolver> {
// Note: This must be invoked while holding the work_serializer.
void Orphan() override {
- ShutdownLocked();
- Unref();
+ ShutdownLocked();
+ Unref();
}
protected:
Resolver(std::shared_ptr<WorkSerializer> work_serializer,
std::unique_ptr<ResultHandler> result_handler);
- /// Shuts down the resolver.
- virtual void ShutdownLocked() = 0;
+ /// Shuts down the resolver.
+ virtual void ShutdownLocked() = 0;
std::shared_ptr<WorkSerializer> work_serializer() const {
return work_serializer_;
}
- ResultHandler* result_handler() const { return result_handler_.get(); }
+ ResultHandler* result_handler() const { return result_handler_.get(); }
private:
std::shared_ptr<WorkSerializer> work_serializer_;
- std::unique_ptr<ResultHandler> result_handler_;
+ std::unique_ptr<ResultHandler> result_handler_;
};
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
index 43d638ab3f..353964b36a 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
-#if GRPC_ARES == 1
+#if GRPC_ARES == 1
#include <limits.h>
#include <stdio.h>
@@ -36,16 +36,16 @@
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
-#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
+#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/lib/backoff/backoff.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/iomgr/gethostname.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/iomgr/work_serializer.h"
@@ -64,9 +64,9 @@ const char kDefaultPort[] = "https";
class AresDnsResolver : public Resolver {
public:
- explicit AresDnsResolver(ResolverArgs args);
+ explicit AresDnsResolver(ResolverArgs args);
- void StartLocked() override;
+ void StartLocked() override;
void RequestReresolutionLocked() override;
@@ -80,8 +80,8 @@ class AresDnsResolver : public Resolver {
void MaybeStartResolvingLocked();
void StartResolvingLocked();
- static void OnNextResolution(void* arg, grpc_error* error);
- static void OnResolved(void* arg, grpc_error* error);
+ static void OnNextResolution(void* arg, grpc_error* error);
+ static void OnResolved(void* arg, grpc_error* error);
void OnNextResolutionLocked(grpc_error* error);
void OnResolvedLocked(grpc_error* error);
@@ -112,7 +112,7 @@ class AresDnsResolver : public Resolver {
/// retry backoff state
BackOff backoff_;
/// currently resolving backend addresses
- std::unique_ptr<ServerAddressList> addresses_;
+ std::unique_ptr<ServerAddressList> addresses_;
/// currently resolving balancer addresses
std::unique_ptr<ServerAddressList> balancer_addresses_;
/// currently resolving service config
@@ -125,7 +125,7 @@ class AresDnsResolver : public Resolver {
bool enable_srv_queries_;
};
-AresDnsResolver::AresDnsResolver(ResolverArgs args)
+AresDnsResolver::AresDnsResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
backoff_(
BackOff::Options()
@@ -156,7 +156,7 @@ AresDnsResolver::AresDnsResolver(ResolverArgs args)
arg = grpc_channel_args_find(channel_args_,
GRPC_ARG_DNS_MIN_TIME_BETWEEN_RESOLUTIONS_MS);
min_time_between_resolutions_ =
- grpc_channel_arg_get_integer(arg, {1000 * 30, 0, INT_MAX});
+ grpc_channel_arg_get_integer(arg, {1000 * 30, 0, INT_MAX});
// Enable SRV queries option
arg = grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_ENABLE_SRV_QUERIES);
enable_srv_queries_ = grpc_channel_arg_get_bool(arg, false);
@@ -164,7 +164,7 @@ AresDnsResolver::AresDnsResolver(ResolverArgs args)
if (args.pollset_set != nullptr) {
grpc_pollset_set_add_pollset_set(interested_parties_, args.pollset_set);
}
-
+
const grpc_arg* query_timeout_ms_arg =
grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS);
query_timeout_ms_ = grpc_channel_arg_get_integer(
@@ -180,10 +180,10 @@ AresDnsResolver::~AresDnsResolver() {
grpc_channel_args_destroy(channel_args_);
}
-void AresDnsResolver::StartLocked() {
- GRPC_CARES_TRACE_LOG("resolver:%p AresDnsResolver::StartLocked() is called.",
+void AresDnsResolver::StartLocked() {
+ GRPC_CARES_TRACE_LOG("resolver:%p AresDnsResolver::StartLocked() is called.",
this);
- MaybeStartResolvingLocked();
+ MaybeStartResolvingLocked();
}
void AresDnsResolver::RequestReresolutionLocked() {
@@ -209,13 +209,13 @@ void AresDnsResolver::ShutdownLocked() {
}
}
-void AresDnsResolver::OnNextResolution(void* arg, grpc_error* error) {
- AresDnsResolver* r = static_cast<AresDnsResolver*>(arg);
+void AresDnsResolver::OnNextResolution(void* arg, grpc_error* error) {
+ AresDnsResolver* r = static_cast<AresDnsResolver*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
r->work_serializer()->Run([r, error]() { r->OnNextResolutionLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void AresDnsResolver::OnNextResolutionLocked(grpc_error* error) {
GRPC_CARES_TRACE_LOG(
"resolver:%p re-resolution timer fired. error: %s. shutdown_initiated_: "
@@ -247,17 +247,17 @@ TString ChooseServiceConfig(char* service_config_choice_json,
Json json = Json::Parse(service_config_choice_json, error);
if (*error != GRPC_ERROR_NONE) return "";
if (json.type() != Json::Type::ARRAY) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Service Config Choices, error: should be of type array");
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Service Config Choices, error: should be of type array");
return "";
- }
+ }
const Json* service_config = nullptr;
y_absl::InlinedVector<grpc_error*, 4> error_list;
for (const Json& choice : json.array_value()) {
if (choice.type() != Json::Type::OBJECT) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Service Config Choice, error: should be of type object"));
- continue;
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Service Config Choice, error: should be of type object"));
+ continue;
}
// Check client language, if specified.
auto it = choice.object_value().find("clientLanguage");
@@ -279,8 +279,8 @@ TString ChooseServiceConfig(char* service_config_choice_json,
char* hostname = grpc_gethostname();
if (hostname == nullptr ||
!ValueInJsonArray(it->second.array_value(), hostname)) {
- continue;
- }
+ continue;
+ }
}
}
// Check percentage, if specified.
@@ -293,10 +293,10 @@ TString ChooseServiceConfig(char* service_config_choice_json,
int random_pct = rand() % 100;
int percentage;
if (sscanf(it->second.string_value().c_str(), "%d", &percentage) != 1) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:percentage error:should be of type integer"));
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:percentage error:should be of type integer"));
} else if (random_pct > percentage || percentage == 0) {
- continue;
+ continue;
}
}
}
@@ -312,22 +312,22 @@ TString ChooseServiceConfig(char* service_config_choice_json,
service_config = &it->second;
}
}
- if (!error_list.empty()) {
- service_config = nullptr;
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("Service Config Choices Parser",
- &error_list);
- }
+ if (!error_list.empty()) {
+ service_config = nullptr;
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("Service Config Choices Parser",
+ &error_list);
+ }
if (service_config == nullptr) return "";
return service_config->Dump();
}
-void AresDnsResolver::OnResolved(void* arg, grpc_error* error) {
- AresDnsResolver* r = static_cast<AresDnsResolver*>(arg);
+void AresDnsResolver::OnResolved(void* arg, grpc_error* error) {
+ AresDnsResolver* r = static_cast<AresDnsResolver*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
r->work_serializer()->Run([r, error]() { r->OnResolvedLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
GPR_ASSERT(resolving_);
resolving_ = false;
@@ -336,10 +336,10 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
if (shutdown_initiated_) {
Unref(DEBUG_LOCATION, "OnResolvedLocked() shutdown");
GRPC_ERROR_UNREF(error);
- return;
- }
+ return;
+ }
if (addresses_ != nullptr || balancer_addresses_ != nullptr) {
- Result result;
+ Result result;
if (addresses_ != nullptr) {
result.addresses = std::move(*addresses_);
}
@@ -347,11 +347,11 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
TString service_config_string = ChooseServiceConfig(
service_config_json_, &result.service_config_error);
gpr_free(service_config_json_);
- if (result.service_config_error == GRPC_ERROR_NONE &&
+ if (result.service_config_error == GRPC_ERROR_NONE &&
!service_config_string.empty()) {
GRPC_CARES_TRACE_LOG("resolver:%p selected service config choice: %s",
this, service_config_string.c_str());
- result.service_config = ServiceConfig::Create(
+ result.service_config = ServiceConfig::Create(
channel_args_, service_config_string, &result.service_config_error);
}
}
@@ -368,16 +368,16 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
// Reset backoff state so that we start from the beginning when the
// next request gets triggered.
backoff_.Reset();
- } else {
+ } else {
GRPC_CARES_TRACE_LOG("resolver:%p dns resolution failed: %s", this,
- grpc_error_string(error));
+ grpc_error_string(error));
TString error_message =
y_absl::StrCat("DNS resolution failed for service: ", name_to_resolve_);
result_handler()->ReturnError(grpc_error_set_int(
GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(error_message.c_str(),
&error, 1),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- // Set retry timer.
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+ // Set retry timer.
grpc_millis next_try = backoff_.NextAttemptTime();
grpc_millis timeout = next_try - ExecCtx::Get()->Now();
GRPC_CARES_TRACE_LOG("resolver:%p dns resolution failed (will retry): %s",
@@ -420,9 +420,9 @@ void AresDnsResolver::MaybeStartResolvingLocked() {
// TODO(roth): We currently deal with this ref manually. Once the
// new closure API is done, find a way to track this ref with the timer
// callback as part of the type system.
- Ref(DEBUG_LOCATION, "next_resolution_timer_cooldown").release();
- grpc_timer_init(&next_resolution_timer_,
- ExecCtx::Get()->Now() + ms_until_next_resolution,
+ Ref(DEBUG_LOCATION, "next_resolution_timer_cooldown").release();
+ grpc_timer_init(&next_resolution_timer_,
+ ExecCtx::Get()->Now() + ms_until_next_resolution,
&on_next_resolution_);
return;
}
@@ -434,7 +434,7 @@ void AresDnsResolver::StartResolvingLocked() {
// TODO(roth): We currently deal with this ref manually. Once the
// new closure API is done, find a way to track this ref with the timer
// callback as part of the type system.
- Ref(DEBUG_LOCATION, "dns-resolving").release();
+ Ref(DEBUG_LOCATION, "dns-resolving").release();
GPR_ASSERT(!resolving_);
resolving_ = true;
service_config_json_ = nullptr;
@@ -455,10 +455,10 @@ void AresDnsResolver::StartResolvingLocked() {
class AresDnsResolverFactory : public ResolverFactory {
public:
- bool IsValidUri(const grpc_uri* /*uri*/) const override { return true; }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- return MakeOrphanable<AresDnsResolver>(std::move(args));
+ bool IsValidUri(const grpc_uri* /*uri*/) const override { return true; }
+
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ return MakeOrphanable<AresDnsResolver>(std::move(args));
}
const char* scheme() const override { return "dns"; }
@@ -481,32 +481,32 @@ static grpc_error* blocking_resolve_address_ares(
static grpc_address_resolver_vtable ares_resolver = {
grpc_resolve_address_ares, blocking_resolve_address_ares};
-#ifdef GRPC_UV
-/* TODO(murgatroid99): Remove this when we want the cares resolver to be the
- * default when using libuv */
+#ifdef GRPC_UV
+/* TODO(murgatroid99): Remove this when we want the cares resolver to be the
+ * default when using libuv */
static bool should_use_ares(const char* resolver_env) {
- return resolver_env != nullptr && gpr_stricmp(resolver_env, "ares") == 0;
+ return resolver_env != nullptr && gpr_stricmp(resolver_env, "ares") == 0;
}
-#else /* GRPC_UV */
-static bool should_use_ares(const char* resolver_env) {
- // TODO(lidiz): Remove the "g_custom_iomgr_enabled" flag once c-ares support
- // custom IO managers (e.g. gevent).
+#else /* GRPC_UV */
+static bool should_use_ares(const char* resolver_env) {
+ // TODO(lidiz): Remove the "g_custom_iomgr_enabled" flag once c-ares support
+ // custom IO managers (e.g. gevent).
return !g_custom_iomgr_enabled && resolver_env != nullptr && (gpr_stricmp(resolver_env, "ares") == 0);
-}
-#endif /* GRPC_UV */
-
-static bool g_use_ares_dns_resolver;
+}
+#endif /* GRPC_UV */
+static bool g_use_ares_dns_resolver;
+
void grpc_resolver_dns_ares_init() {
- grpc_core::UniquePtr<char> resolver =
- GPR_GLOBAL_CONFIG_GET(grpc_dns_resolver);
- if (should_use_ares(resolver.get())) {
- g_use_ares_dns_resolver = true;
+ grpc_core::UniquePtr<char> resolver =
+ GPR_GLOBAL_CONFIG_GET(grpc_dns_resolver);
+ if (should_use_ares(resolver.get())) {
+ g_use_ares_dns_resolver = true;
gpr_log(GPR_DEBUG, "Using ares dns resolver");
address_sorting_init();
grpc_error* error = grpc_ares_init();
if (error != GRPC_ERROR_NONE) {
- GRPC_LOG_IF_ERROR("grpc_ares_init() failed", error);
+ GRPC_LOG_IF_ERROR("grpc_ares_init() failed", error);
return;
}
if (default_resolver == nullptr) {
@@ -515,22 +515,22 @@ void grpc_resolver_dns_ares_init() {
grpc_set_resolver_impl(&ares_resolver);
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::AresDnsResolverFactory>());
- } else {
- g_use_ares_dns_resolver = false;
+ } else {
+ g_use_ares_dns_resolver = false;
}
}
void grpc_resolver_dns_ares_shutdown() {
- if (g_use_ares_dns_resolver) {
+ if (g_use_ares_dns_resolver) {
address_sorting_shutdown();
grpc_ares_cleanup();
}
}
-#else /* GRPC_ARES == 1 */
+#else /* GRPC_ARES == 1 */
void grpc_resolver_dns_ares_init(void) {}
void grpc_resolver_dns_ares_shutdown(void) {}
-#endif /* GRPC_ARES == 1 */
+#endif /* GRPC_ARES == 1 */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
index 9e6bd87622..08ea54792b 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
-#if GRPC_ARES == 1
+#if GRPC_ARES == 1
#include <ares.h>
#include <string.h>
@@ -78,17 +78,17 @@ struct grpc_ares_ev_driver {
/** request object that's using this ev driver */
grpc_ares_request* request;
/** Owned by the ev_driver. Creates new GrpcPolledFd's */
- std::unique_ptr<grpc_core::GrpcPolledFdFactory> polled_fd_factory;
+ std::unique_ptr<grpc_core::GrpcPolledFdFactory> polled_fd_factory;
/** query timeout in milliseconds */
int query_timeout_ms;
/** alarm to cancel active queries */
grpc_timer query_timeout;
/** cancels queries on a timeout */
grpc_closure on_timeout_locked;
- /** alarm to poll ares_process on in case fd events don't happen */
- grpc_timer ares_backup_poll_alarm;
- /** polls ares_process on a periodic timer */
- grpc_closure on_ares_backup_poll_alarm_locked;
+ /** alarm to poll ares_process on in case fd events don't happen */
+ grpc_timer ares_backup_poll_alarm;
+ /** polls ares_process on a periodic timer */
+ grpc_closure on_ares_backup_poll_alarm_locked;
};
static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver);
@@ -110,7 +110,7 @@ static void grpc_ares_ev_driver_unref(grpc_ares_ev_driver* ev_driver) {
GPR_ASSERT(ev_driver->fds == nullptr);
ares_destroy(ev_driver->channel);
grpc_ares_complete_request_locked(ev_driver->request);
- delete ev_driver;
+ delete ev_driver;
}
}
@@ -120,7 +120,7 @@ static void fd_node_destroy_locked(fd_node* fdn) {
GPR_ASSERT(!fdn->readable_registered);
GPR_ASSERT(!fdn->writable_registered);
GPR_ASSERT(fdn->already_shutdown);
- delete fdn->grpc_polled_fd;
+ delete fdn->grpc_polled_fd;
gpr_free(fdn);
}
@@ -132,29 +132,29 @@ static void fd_node_shutdown_locked(fd_node* fdn, const char* reason) {
}
}
-static void on_timeout(void* arg, grpc_error* error);
+static void on_timeout(void* arg, grpc_error* error);
static void on_timeout_locked(grpc_ares_ev_driver* arg, grpc_error* error);
-static void on_ares_backup_poll_alarm(void* arg, grpc_error* error);
+static void on_ares_backup_poll_alarm(void* arg, grpc_error* error);
static void on_ares_backup_poll_alarm_locked(grpc_ares_ev_driver* arg,
grpc_error* error);
-
-static void noop_inject_channel_config(ares_channel /*channel*/) {}
-
-void (*grpc_ares_test_only_inject_config)(ares_channel channel) =
- noop_inject_channel_config;
-
+
+static void noop_inject_channel_config(ares_channel /*channel*/) {}
+
+void (*grpc_ares_test_only_inject_config)(ares_channel channel) =
+ noop_inject_channel_config;
+
grpc_error* grpc_ares_ev_driver_create_locked(
grpc_ares_ev_driver** ev_driver, grpc_pollset_set* pollset_set,
int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer,
grpc_ares_request* request) {
- *ev_driver = new grpc_ares_ev_driver();
+ *ev_driver = new grpc_ares_ev_driver();
ares_options opts;
memset(&opts, 0, sizeof(opts));
opts.flags |= ARES_FLAG_STAYOPEN;
int status = ares_init_options(&(*ev_driver)->channel, &opts, ARES_OPT_FLAGS);
- grpc_ares_test_only_inject_config((*ev_driver)->channel);
+ grpc_ares_test_only_inject_config((*ev_driver)->channel);
GRPC_CARES_TRACE_LOG("request:%p grpc_ares_ev_driver_create_locked", request);
if (status != ARES_SUCCESS) {
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
@@ -186,7 +186,7 @@ void grpc_ares_ev_driver_on_queries_complete_locked(
// fds; if it's not working, there are no fds to shut down.
ev_driver->shutting_down = true;
grpc_timer_cancel(&ev_driver->query_timeout);
- grpc_timer_cancel(&ev_driver->ares_backup_poll_alarm);
+ grpc_timer_cancel(&ev_driver->ares_backup_poll_alarm);
grpc_ares_ev_driver_unref(ev_driver);
}
@@ -217,28 +217,28 @@ static fd_node* pop_fd_node_locked(fd_node** head, ares_socket_t as) {
return nullptr;
}
-static grpc_millis calculate_next_ares_backup_poll_alarm_ms(
- grpc_ares_ev_driver* driver) {
- // An alternative here could be to use ares_timeout to try to be more
- // accurate, but that would require using "struct timeval"'s, which just makes
- // things a bit more complicated. So just poll every second, as suggested
- // by the c-ares code comments.
- grpc_millis ms_until_next_ares_backup_poll_alarm = 1000;
- GRPC_CARES_TRACE_LOG(
- "request:%p ev_driver=%p. next ares process poll time in "
- "%" PRId64 " ms",
- driver->request, driver, ms_until_next_ares_backup_poll_alarm);
- return ms_until_next_ares_backup_poll_alarm +
- grpc_core::ExecCtx::Get()->Now();
-}
-
-static void on_timeout(void* arg, grpc_error* error) {
- grpc_ares_ev_driver* driver = static_cast<grpc_ares_ev_driver*>(arg);
+static grpc_millis calculate_next_ares_backup_poll_alarm_ms(
+ grpc_ares_ev_driver* driver) {
+ // An alternative here could be to use ares_timeout to try to be more
+ // accurate, but that would require using "struct timeval"'s, which just makes
+ // things a bit more complicated. So just poll every second, as suggested
+ // by the c-ares code comments.
+ grpc_millis ms_until_next_ares_backup_poll_alarm = 1000;
+ GRPC_CARES_TRACE_LOG(
+ "request:%p ev_driver=%p. next ares process poll time in "
+ "%" PRId64 " ms",
+ driver->request, driver, ms_until_next_ares_backup_poll_alarm);
+ return ms_until_next_ares_backup_poll_alarm +
+ grpc_core::ExecCtx::Get()->Now();
+}
+
+static void on_timeout(void* arg, grpc_error* error) {
+ grpc_ares_ev_driver* driver = static_cast<grpc_ares_ev_driver*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
driver->work_serializer->Run(
[driver, error]() { on_timeout_locked(driver, error); }, DEBUG_LOCATION);
-}
-
+}
+
static void on_timeout_locked(grpc_ares_ev_driver* driver, grpc_error* error) {
GRPC_CARES_TRACE_LOG(
"request:%p ev_driver=%p on_timeout_locked. driver->shutting_down=%d. "
@@ -251,61 +251,61 @@ static void on_timeout_locked(grpc_ares_ev_driver* driver, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
-static void on_ares_backup_poll_alarm(void* arg, grpc_error* error) {
- grpc_ares_ev_driver* driver = static_cast<grpc_ares_ev_driver*>(arg);
+static void on_ares_backup_poll_alarm(void* arg, grpc_error* error) {
+ grpc_ares_ev_driver* driver = static_cast<grpc_ares_ev_driver*>(arg);
GRPC_ERROR_REF(error);
driver->work_serializer->Run(
[driver, error]() { on_ares_backup_poll_alarm_locked(driver, error); },
DEBUG_LOCATION);
-}
-
-/* In case of non-responsive DNS servers, dropped packets, etc., c-ares has
- * intelligent timeout and retry logic, which we can take advantage of by
- * polling ares_process_fd on time intervals. Overall, the c-ares library is
- * meant to be called into and given a chance to proceed name resolution:
- * a) when fd events happen
- * b) when some time has passed without fd events having happened
- * For the latter, we use this backup poller. Also see
- * https://github.com/grpc/grpc/pull/17688 description for more details. */
+}
+
+/* In case of non-responsive DNS servers, dropped packets, etc., c-ares has
+ * intelligent timeout and retry logic, which we can take advantage of by
+ * polling ares_process_fd on time intervals. Overall, the c-ares library is
+ * meant to be called into and given a chance to proceed name resolution:
+ * a) when fd events happen
+ * b) when some time has passed without fd events having happened
+ * For the latter, we use this backup poller. Also see
+ * https://github.com/grpc/grpc/pull/17688 description for more details. */
static void on_ares_backup_poll_alarm_locked(grpc_ares_ev_driver* driver,
grpc_error* error) {
- GRPC_CARES_TRACE_LOG(
- "request:%p ev_driver=%p on_ares_backup_poll_alarm_locked. "
- "driver->shutting_down=%d. "
- "err=%s",
- driver->request, driver, driver->shutting_down, grpc_error_string(error));
- if (!driver->shutting_down && error == GRPC_ERROR_NONE) {
- fd_node* fdn = driver->fds;
- while (fdn != nullptr) {
- if (!fdn->already_shutdown) {
- GRPC_CARES_TRACE_LOG(
- "request:%p ev_driver=%p on_ares_backup_poll_alarm_locked; "
- "ares_process_fd. fd=%s",
- driver->request, driver, fdn->grpc_polled_fd->GetName());
- ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked();
- ares_process_fd(driver->channel, as, as);
- }
- fdn = fdn->next;
- }
- if (!driver->shutting_down) {
- grpc_millis next_ares_backup_poll_alarm =
- calculate_next_ares_backup_poll_alarm_ms(driver);
- grpc_ares_ev_driver_ref(driver);
- GRPC_CLOSURE_INIT(&driver->on_ares_backup_poll_alarm_locked,
- on_ares_backup_poll_alarm, driver,
- grpc_schedule_on_exec_ctx);
- grpc_timer_init(&driver->ares_backup_poll_alarm,
- next_ares_backup_poll_alarm,
- &driver->on_ares_backup_poll_alarm_locked);
- }
- grpc_ares_notify_on_event_locked(driver);
- }
- grpc_ares_ev_driver_unref(driver);
+ GRPC_CARES_TRACE_LOG(
+ "request:%p ev_driver=%p on_ares_backup_poll_alarm_locked. "
+ "driver->shutting_down=%d. "
+ "err=%s",
+ driver->request, driver, driver->shutting_down, grpc_error_string(error));
+ if (!driver->shutting_down && error == GRPC_ERROR_NONE) {
+ fd_node* fdn = driver->fds;
+ while (fdn != nullptr) {
+ if (!fdn->already_shutdown) {
+ GRPC_CARES_TRACE_LOG(
+ "request:%p ev_driver=%p on_ares_backup_poll_alarm_locked; "
+ "ares_process_fd. fd=%s",
+ driver->request, driver, fdn->grpc_polled_fd->GetName());
+ ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked();
+ ares_process_fd(driver->channel, as, as);
+ }
+ fdn = fdn->next;
+ }
+ if (!driver->shutting_down) {
+ grpc_millis next_ares_backup_poll_alarm =
+ calculate_next_ares_backup_poll_alarm_ms(driver);
+ grpc_ares_ev_driver_ref(driver);
+ GRPC_CLOSURE_INIT(&driver->on_ares_backup_poll_alarm_locked,
+ on_ares_backup_poll_alarm, driver,
+ grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&driver->ares_backup_poll_alarm,
+ next_ares_backup_poll_alarm,
+ &driver->on_ares_backup_poll_alarm_locked);
+ }
+ grpc_ares_notify_on_event_locked(driver);
+ }
+ grpc_ares_ev_driver_unref(driver);
GRPC_ERROR_UNREF(error);
-}
-
+}
+
static void on_readable_locked(fd_node* fdn, grpc_error* error) {
- GPR_ASSERT(fdn->readable_registered);
+ GPR_ASSERT(fdn->readable_registered);
grpc_ares_ev_driver* ev_driver = fdn->ev_driver;
const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked();
fdn->readable_registered = false;
@@ -329,15 +329,15 @@ static void on_readable_locked(fd_node* fdn, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
-static void on_readable(void* arg, grpc_error* error) {
- fd_node* fdn = static_cast<fd_node*>(arg);
+static void on_readable(void* arg, grpc_error* error) {
+ fd_node* fdn = static_cast<fd_node*>(arg);
GRPC_ERROR_REF(error); /* ref owned by lambda */
fdn->ev_driver->work_serializer->Run(
[fdn, error]() { on_readable_locked(fdn, error); }, DEBUG_LOCATION);
-}
-
+}
+
static void on_writable_locked(fd_node* fdn, grpc_error* error) {
- GPR_ASSERT(fdn->writable_registered);
+ GPR_ASSERT(fdn->writable_registered);
grpc_ares_ev_driver* ev_driver = fdn->ev_driver;
const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked();
fdn->writable_registered = false;
@@ -359,13 +359,13 @@ static void on_writable_locked(fd_node* fdn, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
-static void on_writable(void* arg, grpc_error* error) {
- fd_node* fdn = static_cast<fd_node*>(arg);
+static void on_writable(void* arg, grpc_error* error) {
+ fd_node* fdn = static_cast<fd_node*>(arg);
GRPC_ERROR_REF(error); /* ref owned by lambda */
fdn->ev_driver->work_serializer->Run(
[fdn, error]() { on_writable_locked(fdn, error); }, DEBUG_LOCATION);
-}
-
+}
+
ares_channel* grpc_ares_ev_driver_get_channel_locked(
grpc_ares_ev_driver* ev_driver) {
return &ev_driver->channel;
@@ -406,8 +406,8 @@ static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver) {
GRPC_CARES_TRACE_LOG("request:%p notify read on: %s",
ev_driver->request,
fdn->grpc_polled_fd->GetName());
- GRPC_CLOSURE_INIT(&fdn->read_closure, on_readable, fdn,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&fdn->read_closure, on_readable, fdn,
+ grpc_schedule_on_exec_ctx);
fdn->grpc_polled_fd->RegisterForOnReadableLocked(&fdn->read_closure);
fdn->readable_registered = true;
}
@@ -419,8 +419,8 @@ static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver) {
ev_driver->request,
fdn->grpc_polled_fd->GetName());
grpc_ares_ev_driver_ref(ev_driver);
- GRPC_CLOSURE_INIT(&fdn->write_closure, on_writable, fdn,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&fdn->write_closure, on_writable, fdn,
+ grpc_schedule_on_exec_ctx);
fdn->grpc_polled_fd->RegisterForOnWriteableLocked(
&fdn->write_closure);
fdn->writable_registered = true;
@@ -455,7 +455,7 @@ void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver) {
if (!ev_driver->working) {
ev_driver->working = true;
grpc_ares_notify_on_event_locked(ev_driver);
- // Initialize overall DNS resolution timeout alarm
+ // Initialize overall DNS resolution timeout alarm
grpc_millis timeout =
ev_driver->query_timeout_ms == 0
? GRPC_MILLIS_INF_FUTURE
@@ -465,21 +465,21 @@ void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver) {
"%" PRId64 " ms",
ev_driver->request, ev_driver, timeout);
grpc_ares_ev_driver_ref(ev_driver);
- GRPC_CLOSURE_INIT(&ev_driver->on_timeout_locked, on_timeout, ev_driver,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&ev_driver->on_timeout_locked, on_timeout, ev_driver,
+ grpc_schedule_on_exec_ctx);
grpc_timer_init(&ev_driver->query_timeout, timeout,
&ev_driver->on_timeout_locked);
- // Initialize the backup poll alarm
- grpc_millis next_ares_backup_poll_alarm =
- calculate_next_ares_backup_poll_alarm_ms(ev_driver);
- grpc_ares_ev_driver_ref(ev_driver);
- GRPC_CLOSURE_INIT(&ev_driver->on_ares_backup_poll_alarm_locked,
- on_ares_backup_poll_alarm, ev_driver,
- grpc_schedule_on_exec_ctx);
- grpc_timer_init(&ev_driver->ares_backup_poll_alarm,
- next_ares_backup_poll_alarm,
- &ev_driver->on_ares_backup_poll_alarm_locked);
+ // Initialize the backup poll alarm
+ grpc_millis next_ares_backup_poll_alarm =
+ calculate_next_ares_backup_poll_alarm_ms(ev_driver);
+ grpc_ares_ev_driver_ref(ev_driver);
+ GRPC_CLOSURE_INIT(&ev_driver->on_ares_backup_poll_alarm_locked,
+ on_ares_backup_poll_alarm, ev_driver,
+ grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&ev_driver->ares_backup_poll_alarm,
+ next_ares_backup_poll_alarm,
+ &ev_driver->on_ares_backup_poll_alarm_locked);
}
}
-#endif /* GRPC_ARES == 1 */
+#endif /* GRPC_ARES == 1 */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h
index cedf0c3970..38c04dd087 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h
@@ -53,9 +53,9 @@ void grpc_ares_ev_driver_on_queries_complete_locked(
/* Shutdown all the grpc_fds used by \a ev_driver */
void grpc_ares_ev_driver_shutdown_locked(grpc_ares_ev_driver* ev_driver);
-/* Exposed in this header for C-core tests only */
-extern void (*grpc_ares_test_only_inject_config)(ares_channel channel);
-
+/* Exposed in this header for C-core tests only */
+extern void (*grpc_ares_test_only_inject_config)(ares_channel channel);
+
namespace grpc_core {
/* A wrapped fd that integrates with the grpc iomgr of the current platform.
@@ -66,18 +66,18 @@ class GrpcPolledFd {
public:
virtual ~GrpcPolledFd() {}
/* Called when c-ares library is interested and there's no pending callback */
- virtual void RegisterForOnReadableLocked(grpc_closure* read_closure) = 0;
+ virtual void RegisterForOnReadableLocked(grpc_closure* read_closure) = 0;
/* Called when c-ares library is interested and there's no pending callback */
- virtual void RegisterForOnWriteableLocked(grpc_closure* write_closure) = 0;
+ virtual void RegisterForOnWriteableLocked(grpc_closure* write_closure) = 0;
/* Indicates if there is data left even after just being read from */
- virtual bool IsFdStillReadableLocked() = 0;
+ virtual bool IsFdStillReadableLocked() = 0;
/* Called once and only once. Must cause cancellation of any pending
* read/write callbacks. */
- virtual void ShutdownLocked(grpc_error* error) = 0;
+ virtual void ShutdownLocked(grpc_error* error) = 0;
/* Get the underlying ares_socket_t that this was created from */
- virtual ares_socket_t GetWrappedAresSocketLocked() = 0;
+ virtual ares_socket_t GetWrappedAresSocketLocked() = 0;
/* A unique name, for logging */
- virtual const char* GetName() = 0;
+ virtual const char* GetName() = 0;
};
/* A GrpcPolledFdFactory is 1-to-1 with and owned by the
@@ -92,7 +92,7 @@ class GrpcPolledFdFactory {
ares_socket_t as, grpc_pollset_set* driver_pollset_set,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) = 0;
/* Optionally configures the ares channel after creation */
- virtual void ConfigureAresChannelLocked(ares_channel channel) = 0;
+ virtual void ConfigureAresChannelLocked(ares_channel channel) = 0;
};
std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
index 36d4b24c65..3fd28924ae 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
@@ -1,179 +1,179 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-#if GRPC_ARES == 1 && defined(GRPC_UV)
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+#if GRPC_ARES == 1 && defined(GRPC_UV)
+
#include "y_absl/strings/str_format.h"
-#include <ares.h>
+#include <ares.h>
#error #include <uv.h>
-
-#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
-#include "src/core/lib/gpr/string.h"
+
+#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/work_serializer.h"
-
-namespace grpc_core {
-
-void ares_uv_poll_cb(uv_poll_t* handle, int status, int events);
-
-void ares_uv_poll_close_cb(uv_handle_t* handle) { delete handle; }
-
-class GrpcPolledFdLibuv : public GrpcPolledFd {
- public:
+
+namespace grpc_core {
+
+void ares_uv_poll_cb(uv_poll_t* handle, int status, int events);
+
+void ares_uv_poll_close_cb(uv_handle_t* handle) { delete handle; }
+
+class GrpcPolledFdLibuv : public GrpcPolledFd {
+ public:
GrpcPolledFdLibuv(ares_socket_t as,
std::shared_ptr<WorkSerializer> work_serializer)
: name_(y_absl::StrFormat("c-ares socket: %" PRIdPTR, (intptr_t)as)),
as_(as),
work_serializer_(std::move(work_serializer)) {
- handle_ = new uv_poll_t();
- uv_poll_init_socket(uv_default_loop(), handle_, as);
- handle_->data = this;
- }
-
- void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
- GPR_ASSERT(read_closure_ == nullptr);
- GPR_ASSERT((poll_events_ & UV_READABLE) == 0);
- read_closure_ = read_closure;
- poll_events_ |= UV_READABLE;
- uv_poll_start(handle_, poll_events_, ares_uv_poll_cb);
- }
-
- void RegisterForOnWriteableLocked(grpc_closure* write_closure) override {
- GPR_ASSERT(write_closure_ == nullptr);
- GPR_ASSERT((poll_events_ & UV_WRITABLE) == 0);
- write_closure_ = write_closure;
- poll_events_ |= UV_WRITABLE;
- uv_poll_start(handle_, poll_events_, ares_uv_poll_cb);
- }
-
- bool IsFdStillReadableLocked() override {
- /* uv_poll_t is based on poll, which is level triggered. So, if cares
- * leaves some data unread, the event will trigger again. */
- return false;
- }
-
- void ShutdownInternalLocked(grpc_error* error) {
- uv_poll_stop(handle_);
- uv_close(reinterpret_cast<uv_handle_t*>(handle_), ares_uv_poll_close_cb);
- if (read_closure_ != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, read_closure_,
- GRPC_ERROR_CANCELLED);
- }
- if (write_closure_ != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, write_closure_,
- GRPC_ERROR_CANCELLED);
- }
- }
-
- void ShutdownLocked(grpc_error* error) override {
- if (grpc_core::ExecCtx::Get() == nullptr) {
- grpc_core::ExecCtx exec_ctx;
- ShutdownInternalLocked(error);
- } else {
- ShutdownInternalLocked(error);
- }
- }
-
- ares_socket_t GetWrappedAresSocketLocked() override { return as_; }
-
+ handle_ = new uv_poll_t();
+ uv_poll_init_socket(uv_default_loop(), handle_, as);
+ handle_->data = this;
+ }
+
+ void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
+ GPR_ASSERT(read_closure_ == nullptr);
+ GPR_ASSERT((poll_events_ & UV_READABLE) == 0);
+ read_closure_ = read_closure;
+ poll_events_ |= UV_READABLE;
+ uv_poll_start(handle_, poll_events_, ares_uv_poll_cb);
+ }
+
+ void RegisterForOnWriteableLocked(grpc_closure* write_closure) override {
+ GPR_ASSERT(write_closure_ == nullptr);
+ GPR_ASSERT((poll_events_ & UV_WRITABLE) == 0);
+ write_closure_ = write_closure;
+ poll_events_ |= UV_WRITABLE;
+ uv_poll_start(handle_, poll_events_, ares_uv_poll_cb);
+ }
+
+ bool IsFdStillReadableLocked() override {
+ /* uv_poll_t is based on poll, which is level triggered. So, if cares
+ * leaves some data unread, the event will trigger again. */
+ return false;
+ }
+
+ void ShutdownInternalLocked(grpc_error* error) {
+ uv_poll_stop(handle_);
+ uv_close(reinterpret_cast<uv_handle_t*>(handle_), ares_uv_poll_close_cb);
+ if (read_closure_ != nullptr) {
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, read_closure_,
+ GRPC_ERROR_CANCELLED);
+ }
+ if (write_closure_ != nullptr) {
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, write_closure_,
+ GRPC_ERROR_CANCELLED);
+ }
+ }
+
+ void ShutdownLocked(grpc_error* error) override {
+ if (grpc_core::ExecCtx::Get() == nullptr) {
+ grpc_core::ExecCtx exec_ctx;
+ ShutdownInternalLocked(error);
+ } else {
+ ShutdownInternalLocked(error);
+ }
+ }
+
+ ares_socket_t GetWrappedAresSocketLocked() override { return as_; }
+
const char* GetName() override { return name_.c_str(); }
-
+
// TODO(apolcyn): Data members should be private.
TString name_;
- ares_socket_t as_;
- uv_poll_t* handle_;
- grpc_closure* read_closure_ = nullptr;
- grpc_closure* write_closure_ = nullptr;
- int poll_events_ = 0;
+ ares_socket_t as_;
+ uv_poll_t* handle_;
+ grpc_closure* read_closure_ = nullptr;
+ grpc_closure* write_closure_ = nullptr;
+ int poll_events_ = 0;
std::shared_ptr<WorkSerializer> work_serializer_;
-};
-
-struct AresUvPollCbArg {
- AresUvPollCbArg(uv_poll_t* handle, int status, int events)
- : handle(handle), status(status), events(events) {}
-
- uv_poll_t* handle;
- int status;
- int events;
-};
-
+};
+
+struct AresUvPollCbArg {
+ AresUvPollCbArg(uv_poll_t* handle, int status, int events)
+ : handle(handle), status(status), events(events) {}
+
+ uv_poll_t* handle;
+ int status;
+ int events;
+};
+
static void ares_uv_poll_cb_locked(AresUvPollCbArg* arg) {
std::unique_ptr<AresUvPollCbArg> arg_struct(arg);
- uv_poll_t* handle = arg_struct->handle;
- int status = arg_struct->status;
- int events = arg_struct->events;
- GrpcPolledFdLibuv* polled_fd =
- reinterpret_cast<GrpcPolledFdLibuv*>(handle->data);
+ uv_poll_t* handle = arg_struct->handle;
+ int status = arg_struct->status;
+ int events = arg_struct->events;
+ GrpcPolledFdLibuv* polled_fd =
+ reinterpret_cast<GrpcPolledFdLibuv*>(handle->data);
grpc_error* error = GRPC_ERROR_NONE;
- if (status < 0) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("cares polling error");
- error =
- grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
- grpc_slice_from_static_string(uv_strerror(status)));
- }
- if (events & UV_READABLE) {
- GPR_ASSERT(polled_fd->read_closure_ != nullptr);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, polled_fd->read_closure_, error);
- polled_fd->read_closure_ = nullptr;
- polled_fd->poll_events_ &= ~UV_READABLE;
- }
- if (events & UV_WRITABLE) {
- GPR_ASSERT(polled_fd->write_closure_ != nullptr);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, polled_fd->write_closure_, error);
- polled_fd->write_closure_ = nullptr;
- polled_fd->poll_events_ &= ~UV_WRITABLE;
- }
- uv_poll_start(handle, polled_fd->poll_events_, ares_uv_poll_cb);
-}
-
-void ares_uv_poll_cb(uv_poll_t* handle, int status, int events) {
- grpc_core::ExecCtx exec_ctx;
- GrpcPolledFdLibuv* polled_fd =
- reinterpret_cast<GrpcPolledFdLibuv*>(handle->data);
- AresUvPollCbArg* arg = new AresUvPollCbArg(handle, status, events);
+ if (status < 0) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("cares polling error");
+ error =
+ grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
+ grpc_slice_from_static_string(uv_strerror(status)));
+ }
+ if (events & UV_READABLE) {
+ GPR_ASSERT(polled_fd->read_closure_ != nullptr);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, polled_fd->read_closure_, error);
+ polled_fd->read_closure_ = nullptr;
+ polled_fd->poll_events_ &= ~UV_READABLE;
+ }
+ if (events & UV_WRITABLE) {
+ GPR_ASSERT(polled_fd->write_closure_ != nullptr);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, polled_fd->write_closure_, error);
+ polled_fd->write_closure_ = nullptr;
+ polled_fd->poll_events_ &= ~UV_WRITABLE;
+ }
+ uv_poll_start(handle, polled_fd->poll_events_, ares_uv_poll_cb);
+}
+
+void ares_uv_poll_cb(uv_poll_t* handle, int status, int events) {
+ grpc_core::ExecCtx exec_ctx;
+ GrpcPolledFdLibuv* polled_fd =
+ reinterpret_cast<GrpcPolledFdLibuv*>(handle->data);
+ AresUvPollCbArg* arg = new AresUvPollCbArg(handle, status, events);
polled_fd->work_serializer_->Run([arg]() { ares_uv_poll_cb_locked(arg); },
DEBUG_LOCATION);
-}
-
-class GrpcPolledFdFactoryLibuv : public GrpcPolledFdFactory {
- public:
+}
+
+class GrpcPolledFdFactoryLibuv : public GrpcPolledFdFactory {
+ public:
GrpcPolledFd* NewGrpcPolledFdLocked(
ares_socket_t as, grpc_pollset_set* driver_pollset_set,
std::shared_ptr<WorkSerializer> work_serializer) override {
return new GrpcPolledFdLibuv(as, std::move(work_serializer));
- }
-
- void ConfigureAresChannelLocked(ares_channel channel) override {}
-};
-
-std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
+ }
+
+ void ConfigureAresChannelLocked(ares_channel channel) override {}
+};
+
+std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
std::shared_ptr<WorkSerializer> work_serializer) {
return y_absl::make_unique<GrpcPolledFdFactoryLibuv>();
-}
-
-} // namespace grpc_core
-
-#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */
+}
+
+} // namespace grpc_core
+
+#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
index e1fcaa5090..48338a3ce2 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
@@ -92,13 +92,13 @@ class GrpcPolledFdFactoryPosix : public GrpcPolledFdFactory {
GrpcPolledFd* NewGrpcPolledFdLocked(
ares_socket_t as, grpc_pollset_set* driver_pollset_set,
std::shared_ptr<WorkSerializer> /*work_serializer*/) override {
- return new GrpcPolledFdPosix(as, driver_pollset_set);
+ return new GrpcPolledFdPosix(as, driver_pollset_set);
}
- void ConfigureAresChannelLocked(ares_channel /*channel*/) override {}
+ void ConfigureAresChannelLocked(ares_channel /*channel*/) override {}
};
-std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
+std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
std::shared_ptr<WorkSerializer> work_serializer) {
(void)work_serializer;
return y_absl::make_unique<GrpcPolledFdFactoryPosix>();
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
index e228469517..1385b8fce1 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
-#if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER)
+#if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER)
#include "y_absl/strings/str_format.h"
@@ -32,9 +32,9 @@
#include <string.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/sockaddr_windows.h"
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/sockaddr_windows.h"
#include "src/core/lib/iomgr/socket_windows.h"
#include "src/core/lib/iomgr/tcp_windows.h"
#include "src/core/lib/iomgr/work_serializer.h"
@@ -55,32 +55,32 @@ struct iovec {
namespace grpc_core {
-/* c-ares reads and takes action on the error codes of the
- * "virtual socket operations" in this file, via the WSAGetLastError
- * APIs. If code in this file wants to set a specific WSA error that
- * c-ares should read, it must do so by calling SetWSAError() on the
- * WSAErrorContext instance passed to it. A WSAErrorContext must only be
- * instantiated at the top of the virtual socket function callstack. */
-class WSAErrorContext {
- public:
- explicit WSAErrorContext(){};
-
- ~WSAErrorContext() {
- if (error_ != 0) {
- WSASetLastError(error_);
- }
- }
-
- /* Disallow copy and assignment operators */
- WSAErrorContext(const WSAErrorContext&) = delete;
- WSAErrorContext& operator=(const WSAErrorContext&) = delete;
-
- void SetWSAError(int error) { error_ = error; }
-
- private:
- int error_ = 0;
-};
-
+/* c-ares reads and takes action on the error codes of the
+ * "virtual socket operations" in this file, via the WSAGetLastError
+ * APIs. If code in this file wants to set a specific WSA error that
+ * c-ares should read, it must do so by calling SetWSAError() on the
+ * WSAErrorContext instance passed to it. A WSAErrorContext must only be
+ * instantiated at the top of the virtual socket function callstack. */
+class WSAErrorContext {
+ public:
+ explicit WSAErrorContext(){};
+
+ ~WSAErrorContext() {
+ if (error_ != 0) {
+ WSASetLastError(error_);
+ }
+ }
+
+ /* Disallow copy and assignment operators */
+ WSAErrorContext(const WSAErrorContext&) = delete;
+ WSAErrorContext& operator=(const WSAErrorContext&) = delete;
+
+ void SetWSAError(int error) { error_ = error; }
+
+ private:
+ int error_ = 0;
+};
+
/* c-ares creates its own sockets and is meant to read them when readable and
* write them when writeable. To fit this socket usage model into the grpc
* windows poller (which gives notifications when attempted reads and writes are
@@ -90,7 +90,7 @@ class WSAErrorContext {
* from c-ares and are used with the grpc windows poller, and it, e.g.,
* manufactures virtual socket error codes when it e.g. needs to tell the c-ares
* library to wait for an async read. */
-class GrpcPolledFdWindows {
+class GrpcPolledFdWindows {
public:
enum WriteState {
WRITE_IDLE,
@@ -105,11 +105,11 @@ class GrpcPolledFdWindows {
: work_serializer_(std::move(work_serializer)),
read_buf_(grpc_empty_slice()),
write_buf_(grpc_empty_slice()),
- tcp_write_state_(WRITE_IDLE),
+ tcp_write_state_(WRITE_IDLE),
name_(y_absl::StrFormat("c-ares socket: %" PRIdPTR, as)),
- gotten_into_driver_list_(false),
- address_family_(address_family),
- socket_type_(socket_type) {
+ gotten_into_driver_list_(false),
+ address_family_(address_family),
+ socket_type_(socket_type) {
// Closure Initialization
GRPC_CLOSURE_INIT(&outer_read_closure_,
&GrpcPolledFdWindows::OnIocpReadable, this,
@@ -132,41 +132,41 @@ class GrpcPolledFdWindows {
}
void ScheduleAndNullReadClosure(grpc_error* error) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, read_closure_, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, read_closure_, error);
read_closure_ = nullptr;
}
void ScheduleAndNullWriteClosure(grpc_error* error) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, write_closure_, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, write_closure_, error);
write_closure_ = nullptr;
}
- void RegisterForOnReadableLocked(grpc_closure* read_closure) {
+ void RegisterForOnReadableLocked(grpc_closure* read_closure) {
GPR_ASSERT(read_closure_ == nullptr);
read_closure_ = read_closure;
GPR_ASSERT(GRPC_SLICE_LENGTH(read_buf_) == 0);
grpc_slice_unref_internal(read_buf_);
- GPR_ASSERT(!read_buf_has_data_);
+ GPR_ASSERT(!read_buf_has_data_);
read_buf_ = GRPC_SLICE_MALLOC(4192);
- if (connect_done_) {
+ if (connect_done_) {
work_serializer_->Run([this]() { ContinueRegisterForOnReadableLocked(); },
DEBUG_LOCATION);
- } else {
+ } else {
GPR_ASSERT(pending_continue_register_for_on_readable_locked_ == false);
pending_continue_register_for_on_readable_locked_ = true;
- }
- }
-
+ }
+ }
+
void ContinueRegisterForOnReadableLocked() {
- GRPC_CARES_TRACE_LOG(
- "fd:|%s| InnerContinueRegisterForOnReadableLocked "
- "wsa_connect_error_:%d",
- GetName(), wsa_connect_error_);
- GPR_ASSERT(connect_done_);
- if (wsa_connect_error_ != 0) {
- ScheduleAndNullReadClosure(GRPC_WSA_ERROR(wsa_connect_error_, "connect"));
- return;
- }
+ GRPC_CARES_TRACE_LOG(
+ "fd:|%s| InnerContinueRegisterForOnReadableLocked "
+ "wsa_connect_error_:%d",
+ GetName(), wsa_connect_error_);
+ GPR_ASSERT(connect_done_);
+ if (wsa_connect_error_ != 0) {
+ ScheduleAndNullReadClosure(GRPC_WSA_ERROR(wsa_connect_error_, "connect"));
+ return;
+ }
WSABUF buffer;
buffer.buf = (char*)GRPC_SLICE_START_PTR(read_buf_);
buffer.len = GRPC_SLICE_LENGTH(read_buf_);
@@ -180,98 +180,98 @@ class GrpcPolledFdWindows {
int wsa_last_error = WSAGetLastError();
char* msg = gpr_format_message(wsa_last_error);
GRPC_CARES_TRACE_LOG(
- "fd:|%s| RegisterForOnReadableLocked WSARecvFrom error code:|%d| "
- "msg:|%s|",
- GetName(), wsa_last_error, msg);
+ "fd:|%s| RegisterForOnReadableLocked WSARecvFrom error code:|%d| "
+ "msg:|%s|",
+ GetName(), wsa_last_error, msg);
gpr_free(msg);
if (wsa_last_error != WSA_IO_PENDING) {
- ScheduleAndNullReadClosure(
- GRPC_WSA_ERROR(wsa_last_error, "WSARecvFrom"));
+ ScheduleAndNullReadClosure(
+ GRPC_WSA_ERROR(wsa_last_error, "WSARecvFrom"));
return;
}
}
grpc_socket_notify_on_read(winsocket_, &outer_read_closure_);
}
- void RegisterForOnWriteableLocked(grpc_closure* write_closure) {
- if (socket_type_ == SOCK_DGRAM) {
- GRPC_CARES_TRACE_LOG("fd:|%s| RegisterForOnWriteableLocked called",
- GetName());
- } else {
- GPR_ASSERT(socket_type_ == SOCK_STREAM);
- GRPC_CARES_TRACE_LOG(
- "fd:|%s| RegisterForOnWriteableLocked called tcp_write_state_: %d",
- GetName(), tcp_write_state_);
- }
+ void RegisterForOnWriteableLocked(grpc_closure* write_closure) {
+ if (socket_type_ == SOCK_DGRAM) {
+ GRPC_CARES_TRACE_LOG("fd:|%s| RegisterForOnWriteableLocked called",
+ GetName());
+ } else {
+ GPR_ASSERT(socket_type_ == SOCK_STREAM);
+ GRPC_CARES_TRACE_LOG(
+ "fd:|%s| RegisterForOnWriteableLocked called tcp_write_state_: %d",
+ GetName(), tcp_write_state_);
+ }
GPR_ASSERT(write_closure_ == nullptr);
write_closure_ = write_closure;
- if (connect_done_) {
+ if (connect_done_) {
work_serializer_->Run(
[this]() { ContinueRegisterForOnWriteableLocked(); }, DEBUG_LOCATION);
- } else {
+ } else {
GPR_ASSERT(pending_continue_register_for_on_writeable_locked_ == false);
pending_continue_register_for_on_writeable_locked_ = true;
}
}
void ContinueRegisterForOnWriteableLocked() {
- GRPC_CARES_TRACE_LOG(
- "fd:|%s| InnerContinueRegisterForOnWriteableLocked "
- "wsa_connect_error_:%d",
- GetName(), wsa_connect_error_);
- GPR_ASSERT(connect_done_);
- if (wsa_connect_error_ != 0) {
- ScheduleAndNullWriteClosure(
- GRPC_WSA_ERROR(wsa_connect_error_, "connect"));
- return;
- }
- if (socket_type_ == SOCK_DGRAM) {
- ScheduleAndNullWriteClosure(GRPC_ERROR_NONE);
- } else {
- GPR_ASSERT(socket_type_ == SOCK_STREAM);
- int wsa_error_code = 0;
- switch (tcp_write_state_) {
- case WRITE_IDLE:
- ScheduleAndNullWriteClosure(GRPC_ERROR_NONE);
- break;
- case WRITE_REQUESTED:
- tcp_write_state_ = WRITE_PENDING;
- if (SendWriteBuf(nullptr, &winsocket_->write_info.overlapped,
- &wsa_error_code) != 0) {
- ScheduleAndNullWriteClosure(
- GRPC_WSA_ERROR(wsa_error_code, "WSASend (overlapped)"));
- } else {
+ GRPC_CARES_TRACE_LOG(
+ "fd:|%s| InnerContinueRegisterForOnWriteableLocked "
+ "wsa_connect_error_:%d",
+ GetName(), wsa_connect_error_);
+ GPR_ASSERT(connect_done_);
+ if (wsa_connect_error_ != 0) {
+ ScheduleAndNullWriteClosure(
+ GRPC_WSA_ERROR(wsa_connect_error_, "connect"));
+ return;
+ }
+ if (socket_type_ == SOCK_DGRAM) {
+ ScheduleAndNullWriteClosure(GRPC_ERROR_NONE);
+ } else {
+ GPR_ASSERT(socket_type_ == SOCK_STREAM);
+ int wsa_error_code = 0;
+ switch (tcp_write_state_) {
+ case WRITE_IDLE:
+ ScheduleAndNullWriteClosure(GRPC_ERROR_NONE);
+ break;
+ case WRITE_REQUESTED:
+ tcp_write_state_ = WRITE_PENDING;
+ if (SendWriteBuf(nullptr, &winsocket_->write_info.overlapped,
+ &wsa_error_code) != 0) {
+ ScheduleAndNullWriteClosure(
+ GRPC_WSA_ERROR(wsa_error_code, "WSASend (overlapped)"));
+ } else {
grpc_socket_notify_on_write(winsocket_, &outer_write_closure_);
- }
- break;
- case WRITE_PENDING:
- case WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY:
- abort();
- }
- }
- }
-
- bool IsFdStillReadableLocked() { return GRPC_SLICE_LENGTH(read_buf_) > 0; }
-
- void ShutdownLocked(grpc_error* error) {
+ }
+ break;
+ case WRITE_PENDING:
+ case WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY:
+ abort();
+ }
+ }
+ }
+
+ bool IsFdStillReadableLocked() { return GRPC_SLICE_LENGTH(read_buf_) > 0; }
+
+ void ShutdownLocked(grpc_error* error) {
grpc_winsocket_shutdown(winsocket_);
}
- ares_socket_t GetWrappedAresSocketLocked() {
+ ares_socket_t GetWrappedAresSocketLocked() {
return grpc_winsocket_wrapped_socket(winsocket_);
}
const char* GetName() { return name_.c_str(); }
- ares_ssize_t RecvFrom(WSAErrorContext* wsa_error_ctx, void* data,
- ares_socket_t data_len, int flags,
+ ares_ssize_t RecvFrom(WSAErrorContext* wsa_error_ctx, void* data,
+ ares_socket_t data_len, int flags,
struct sockaddr* from, ares_socklen_t* from_len) {
GRPC_CARES_TRACE_LOG(
- "fd:|%s| RecvFrom called read_buf_has_data:%d Current read buf "
- "length:|%d|",
- GetName(), read_buf_has_data_, GRPC_SLICE_LENGTH(read_buf_));
- if (!read_buf_has_data_) {
- wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
+ "fd:|%s| RecvFrom called read_buf_has_data:%d Current read buf "
+ "length:|%d|",
+ GetName(), read_buf_has_data_, GRPC_SLICE_LENGTH(read_buf_));
+ if (!read_buf_has_data_) {
+ wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
return -1;
}
ares_ssize_t bytes_read = 0;
@@ -281,9 +281,9 @@ class GrpcPolledFdWindows {
}
read_buf_ = grpc_slice_sub_no_ref(read_buf_, bytes_read,
GRPC_SLICE_LENGTH(read_buf_));
- if (GRPC_SLICE_LENGTH(read_buf_) == 0) {
- read_buf_has_data_ = false;
- }
+ if (GRPC_SLICE_LENGTH(read_buf_) == 0) {
+ read_buf_has_data_ = false;
+ }
/* c-ares overloads this recv_from virtual socket function to receive
* data on both UDP and TCP sockets, and from is nullptr for TCP. */
if (from != nullptr) {
@@ -309,99 +309,99 @@ class GrpcPolledFdWindows {
return out;
}
- int SendWriteBuf(LPDWORD bytes_sent_ptr, LPWSAOVERLAPPED overlapped,
- int* wsa_error_code) {
+ int SendWriteBuf(LPDWORD bytes_sent_ptr, LPWSAOVERLAPPED overlapped,
+ int* wsa_error_code) {
WSABUF buf;
buf.len = GRPC_SLICE_LENGTH(write_buf_);
buf.buf = (char*)GRPC_SLICE_START_PTR(write_buf_);
DWORD flags = 0;
int out = WSASend(grpc_winsocket_wrapped_socket(winsocket_), &buf, 1,
bytes_sent_ptr, flags, overlapped, nullptr);
- *wsa_error_code = WSAGetLastError();
+ *wsa_error_code = WSAGetLastError();
GRPC_CARES_TRACE_LOG(
- "fd:|%s| SendWriteBuf WSASend buf.len:%d *bytes_sent_ptr:%d "
- "overlapped:%p "
- "return:%d *wsa_error_code:%d",
- GetName(), buf.len, bytes_sent_ptr != nullptr ? *bytes_sent_ptr : 0,
- overlapped, out, *wsa_error_code);
+ "fd:|%s| SendWriteBuf WSASend buf.len:%d *bytes_sent_ptr:%d "
+ "overlapped:%p "
+ "return:%d *wsa_error_code:%d",
+ GetName(), buf.len, bytes_sent_ptr != nullptr ? *bytes_sent_ptr : 0,
+ overlapped, out, *wsa_error_code);
return out;
}
- ares_ssize_t SendV(WSAErrorContext* wsa_error_ctx, const struct iovec* iov,
- int iov_count) {
- GRPC_CARES_TRACE_LOG(
- "fd:|%s| SendV called connect_done_:%d wsa_connect_error_:%d",
- GetName(), connect_done_, wsa_connect_error_);
- if (!connect_done_) {
- wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
- return -1;
- }
- if (wsa_connect_error_ != 0) {
- wsa_error_ctx->SetWSAError(wsa_connect_error_);
- return -1;
- }
- switch (socket_type_) {
- case SOCK_DGRAM:
- return SendVUDP(wsa_error_ctx, iov, iov_count);
- case SOCK_STREAM:
- return SendVTCP(wsa_error_ctx, iov, iov_count);
- default:
- abort();
- }
- }
-
- ares_ssize_t SendVUDP(WSAErrorContext* wsa_error_ctx, const struct iovec* iov,
- int iov_count) {
- // c-ares doesn't handle retryable errors on writes of UDP sockets.
- // Therefore, the sendv handler for UDP sockets must only attempt
- // to write everything inline.
- GRPC_CARES_TRACE_LOG("fd:|%s| SendVUDP called", GetName());
- GPR_ASSERT(GRPC_SLICE_LENGTH(write_buf_) == 0);
- grpc_slice_unref_internal(write_buf_);
- write_buf_ = FlattenIovec(iov, iov_count);
+ ares_ssize_t SendV(WSAErrorContext* wsa_error_ctx, const struct iovec* iov,
+ int iov_count) {
+ GRPC_CARES_TRACE_LOG(
+ "fd:|%s| SendV called connect_done_:%d wsa_connect_error_:%d",
+ GetName(), connect_done_, wsa_connect_error_);
+ if (!connect_done_) {
+ wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
+ return -1;
+ }
+ if (wsa_connect_error_ != 0) {
+ wsa_error_ctx->SetWSAError(wsa_connect_error_);
+ return -1;
+ }
+ switch (socket_type_) {
+ case SOCK_DGRAM:
+ return SendVUDP(wsa_error_ctx, iov, iov_count);
+ case SOCK_STREAM:
+ return SendVTCP(wsa_error_ctx, iov, iov_count);
+ default:
+ abort();
+ }
+ }
+
+ ares_ssize_t SendVUDP(WSAErrorContext* wsa_error_ctx, const struct iovec* iov,
+ int iov_count) {
+ // c-ares doesn't handle retryable errors on writes of UDP sockets.
+ // Therefore, the sendv handler for UDP sockets must only attempt
+ // to write everything inline.
+ GRPC_CARES_TRACE_LOG("fd:|%s| SendVUDP called", GetName());
+ GPR_ASSERT(GRPC_SLICE_LENGTH(write_buf_) == 0);
+ grpc_slice_unref_internal(write_buf_);
+ write_buf_ = FlattenIovec(iov, iov_count);
DWORD bytes_sent = 0;
- int wsa_error_code = 0;
- if (SendWriteBuf(&bytes_sent, nullptr, &wsa_error_code) != 0) {
- wsa_error_ctx->SetWSAError(wsa_error_code);
- char* msg = gpr_format_message(wsa_error_code);
+ int wsa_error_code = 0;
+ if (SendWriteBuf(&bytes_sent, nullptr, &wsa_error_code) != 0) {
+ wsa_error_ctx->SetWSAError(wsa_error_code);
+ char* msg = gpr_format_message(wsa_error_code);
GRPC_CARES_TRACE_LOG(
- "fd:|%s| SendVUDP SendWriteBuf error code:%d msg:|%s|", GetName(),
- wsa_error_code, msg);
+ "fd:|%s| SendVUDP SendWriteBuf error code:%d msg:|%s|", GetName(),
+ wsa_error_code, msg);
gpr_free(msg);
- return -1;
+ return -1;
}
write_buf_ = grpc_slice_sub_no_ref(write_buf_, bytes_sent,
GRPC_SLICE_LENGTH(write_buf_));
return bytes_sent;
}
- ares_ssize_t SendVTCP(WSAErrorContext* wsa_error_ctx, const struct iovec* iov,
- int iov_count) {
- // The "sendv" handler on TCP sockets buffers up write
- // requests and returns an artificial WSAEWOULDBLOCK. Writing that buffer
- // out in the background, and making further send progress in general, will
- // happen as long as c-ares continues to show interest in writeability on
- // this fd.
- GRPC_CARES_TRACE_LOG("fd:|%s| SendVTCP called tcp_write_state_:%d",
- GetName(), tcp_write_state_);
- switch (tcp_write_state_) {
+ ares_ssize_t SendVTCP(WSAErrorContext* wsa_error_ctx, const struct iovec* iov,
+ int iov_count) {
+ // The "sendv" handler on TCP sockets buffers up write
+ // requests and returns an artificial WSAEWOULDBLOCK. Writing that buffer
+ // out in the background, and making further send progress in general, will
+ // happen as long as c-ares continues to show interest in writeability on
+ // this fd.
+ GRPC_CARES_TRACE_LOG("fd:|%s| SendVTCP called tcp_write_state_:%d",
+ GetName(), tcp_write_state_);
+ switch (tcp_write_state_) {
case WRITE_IDLE:
- tcp_write_state_ = WRITE_REQUESTED;
+ tcp_write_state_ = WRITE_REQUESTED;
GPR_ASSERT(GRPC_SLICE_LENGTH(write_buf_) == 0);
grpc_slice_unref_internal(write_buf_);
write_buf_ = FlattenIovec(iov, iov_count);
- wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
- return -1;
+ wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
+ return -1;
case WRITE_REQUESTED:
case WRITE_PENDING:
- wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
+ wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
return -1;
case WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY:
- // c-ares is retrying a send on data that we previously returned
- // WSAEWOULDBLOCK for, but then subsequently wrote out in the
- // background. Right now, we assume that c-ares is retrying the same
- // send again. If c-ares still needs to send even more data, we'll get
- // to it eventually.
+ // c-ares is retrying a send on data that we previously returned
+ // WSAEWOULDBLOCK for, but then subsequently wrote out in the
+ // background. Right now, we assume that c-ares is retrying the same
+ // send again. If c-ares still needs to send even more data, we'll get
+ // to it eventually.
grpc_slice currently_attempted = FlattenIovec(iov, iov_count);
GPR_ASSERT(GRPC_SLICE_LENGTH(currently_attempted) >=
GRPC_SLICE_LENGTH(write_buf_));
@@ -411,166 +411,166 @@ class GrpcPolledFdWindows {
GRPC_SLICE_START_PTR(write_buf_)[i]);
total_sent++;
}
- grpc_slice_unref_internal(currently_attempted);
- tcp_write_state_ = WRITE_IDLE;
+ grpc_slice_unref_internal(currently_attempted);
+ tcp_write_state_ = WRITE_IDLE;
return total_sent;
}
abort();
}
- static void OnTcpConnect(void* arg, grpc_error* error) {
- GrpcPolledFdWindows* grpc_polled_fd =
- static_cast<GrpcPolledFdWindows*>(arg);
+ static void OnTcpConnect(void* arg, grpc_error* error) {
+ GrpcPolledFdWindows* grpc_polled_fd =
+ static_cast<GrpcPolledFdWindows*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
grpc_polled_fd->work_serializer_->Run(
[grpc_polled_fd, error]() {
grpc_polled_fd->OnTcpConnectLocked(error);
},
DEBUG_LOCATION);
- }
-
+ }
+
void OnTcpConnectLocked(grpc_error* error) {
- GRPC_CARES_TRACE_LOG(
- "fd:%s InnerOnTcpConnectLocked error:|%s| "
+ GRPC_CARES_TRACE_LOG(
+ "fd:%s InnerOnTcpConnectLocked error:|%s| "
"pending_register_for_readable:%d"
" pending_register_for_writeable:%d",
- GetName(), grpc_error_string(error),
- pending_continue_register_for_on_readable_locked_,
- pending_continue_register_for_on_writeable_locked_);
- GPR_ASSERT(!connect_done_);
- connect_done_ = true;
- GPR_ASSERT(wsa_connect_error_ == 0);
- if (error == GRPC_ERROR_NONE) {
- DWORD transferred_bytes = 0;
- DWORD flags;
- BOOL wsa_success =
- WSAGetOverlappedResult(grpc_winsocket_wrapped_socket(winsocket_),
- &winsocket_->write_info.overlapped,
- &transferred_bytes, FALSE, &flags);
- GPR_ASSERT(transferred_bytes == 0);
- if (!wsa_success) {
- wsa_connect_error_ = WSAGetLastError();
- char* msg = gpr_format_message(wsa_connect_error_);
- GRPC_CARES_TRACE_LOG(
- "fd:%s InnerOnTcpConnectLocked WSA overlapped result code:%d "
- "msg:|%s|",
- GetName(), wsa_connect_error_, msg);
- gpr_free(msg);
- }
- } else {
- // Spoof up an error code that will cause any future c-ares operations on
- // this fd to abort.
- wsa_connect_error_ = WSA_OPERATION_ABORTED;
- }
+ GetName(), grpc_error_string(error),
+ pending_continue_register_for_on_readable_locked_,
+ pending_continue_register_for_on_writeable_locked_);
+ GPR_ASSERT(!connect_done_);
+ connect_done_ = true;
+ GPR_ASSERT(wsa_connect_error_ == 0);
+ if (error == GRPC_ERROR_NONE) {
+ DWORD transferred_bytes = 0;
+ DWORD flags;
+ BOOL wsa_success =
+ WSAGetOverlappedResult(grpc_winsocket_wrapped_socket(winsocket_),
+ &winsocket_->write_info.overlapped,
+ &transferred_bytes, FALSE, &flags);
+ GPR_ASSERT(transferred_bytes == 0);
+ if (!wsa_success) {
+ wsa_connect_error_ = WSAGetLastError();
+ char* msg = gpr_format_message(wsa_connect_error_);
+ GRPC_CARES_TRACE_LOG(
+ "fd:%s InnerOnTcpConnectLocked WSA overlapped result code:%d "
+ "msg:|%s|",
+ GetName(), wsa_connect_error_, msg);
+ gpr_free(msg);
+ }
+ } else {
+ // Spoof up an error code that will cause any future c-ares operations on
+ // this fd to abort.
+ wsa_connect_error_ = WSA_OPERATION_ABORTED;
+ }
if (pending_continue_register_for_on_readable_locked_) {
work_serializer_->Run([this]() { ContinueRegisterForOnReadableLocked(); },
DEBUG_LOCATION);
- }
+ }
if (pending_continue_register_for_on_writeable_locked_) {
work_serializer_->Run(
[this]() { ContinueRegisterForOnWriteableLocked(); }, DEBUG_LOCATION);
- }
+ }
GRPC_ERROR_UNREF(error);
- }
-
- int Connect(WSAErrorContext* wsa_error_ctx, const struct sockaddr* target,
- ares_socklen_t target_len) {
- switch (socket_type_) {
- case SOCK_DGRAM:
- return ConnectUDP(wsa_error_ctx, target, target_len);
- case SOCK_STREAM:
- return ConnectTCP(wsa_error_ctx, target, target_len);
- default:
- abort();
- }
- }
-
- int ConnectUDP(WSAErrorContext* wsa_error_ctx, const struct sockaddr* target,
- ares_socklen_t target_len) {
- GRPC_CARES_TRACE_LOG("fd:%s ConnectUDP", GetName());
- GPR_ASSERT(!connect_done_);
- GPR_ASSERT(wsa_connect_error_ == 0);
+ }
+
+ int Connect(WSAErrorContext* wsa_error_ctx, const struct sockaddr* target,
+ ares_socklen_t target_len) {
+ switch (socket_type_) {
+ case SOCK_DGRAM:
+ return ConnectUDP(wsa_error_ctx, target, target_len);
+ case SOCK_STREAM:
+ return ConnectTCP(wsa_error_ctx, target, target_len);
+ default:
+ abort();
+ }
+ }
+
+ int ConnectUDP(WSAErrorContext* wsa_error_ctx, const struct sockaddr* target,
+ ares_socklen_t target_len) {
+ GRPC_CARES_TRACE_LOG("fd:%s ConnectUDP", GetName());
+ GPR_ASSERT(!connect_done_);
+ GPR_ASSERT(wsa_connect_error_ == 0);
SOCKET s = grpc_winsocket_wrapped_socket(winsocket_);
int out =
WSAConnect(s, target, target_len, nullptr, nullptr, nullptr, nullptr);
- wsa_connect_error_ = WSAGetLastError();
- wsa_error_ctx->SetWSAError(wsa_connect_error_);
- connect_done_ = true;
- char* msg = gpr_format_message(wsa_connect_error_);
- GRPC_CARES_TRACE_LOG("fd:%s WSAConnect error code:|%d| msg:|%s|", GetName(),
- wsa_connect_error_, msg);
- gpr_free(msg);
- // c-ares expects a posix-style connect API
- return out == 0 ? 0 : -1;
- }
-
- int ConnectTCP(WSAErrorContext* wsa_error_ctx, const struct sockaddr* target,
- ares_socklen_t target_len) {
- GRPC_CARES_TRACE_LOG("fd:%s ConnectTCP", GetName());
- LPFN_CONNECTEX ConnectEx;
- GUID guid = WSAID_CONNECTEX;
- DWORD ioctl_num_bytes;
- SOCKET s = grpc_winsocket_wrapped_socket(winsocket_);
- if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
- &ConnectEx, sizeof(ConnectEx), &ioctl_num_bytes, nullptr,
- nullptr) != 0) {
+ wsa_connect_error_ = WSAGetLastError();
+ wsa_error_ctx->SetWSAError(wsa_connect_error_);
+ connect_done_ = true;
+ char* msg = gpr_format_message(wsa_connect_error_);
+ GRPC_CARES_TRACE_LOG("fd:%s WSAConnect error code:|%d| msg:|%s|", GetName(),
+ wsa_connect_error_, msg);
+ gpr_free(msg);
+ // c-ares expects a posix-style connect API
+ return out == 0 ? 0 : -1;
+ }
+
+ int ConnectTCP(WSAErrorContext* wsa_error_ctx, const struct sockaddr* target,
+ ares_socklen_t target_len) {
+ GRPC_CARES_TRACE_LOG("fd:%s ConnectTCP", GetName());
+ LPFN_CONNECTEX ConnectEx;
+ GUID guid = WSAID_CONNECTEX;
+ DWORD ioctl_num_bytes;
+ SOCKET s = grpc_winsocket_wrapped_socket(winsocket_);
+ if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
+ &ConnectEx, sizeof(ConnectEx), &ioctl_num_bytes, nullptr,
+ nullptr) != 0) {
int wsa_last_error = WSAGetLastError();
- wsa_error_ctx->SetWSAError(wsa_last_error);
+ wsa_error_ctx->SetWSAError(wsa_last_error);
char* msg = gpr_format_message(wsa_last_error);
- GRPC_CARES_TRACE_LOG(
- "fd:%s WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) error code:%d "
- "msg:|%s|",
- GetName(), wsa_last_error, msg);
+ GRPC_CARES_TRACE_LOG(
+ "fd:%s WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) error code:%d "
+ "msg:|%s|",
+ GetName(), wsa_last_error, msg);
gpr_free(msg);
- connect_done_ = true;
- wsa_connect_error_ = wsa_last_error;
- return -1;
- }
- grpc_resolved_address wildcard4_addr;
- grpc_resolved_address wildcard6_addr;
- grpc_sockaddr_make_wildcards(0, &wildcard4_addr, &wildcard6_addr);
- grpc_resolved_address* local_address = nullptr;
- if (address_family_ == AF_INET) {
- local_address = &wildcard4_addr;
- } else {
- local_address = &wildcard6_addr;
- }
- if (bind(s, (struct sockaddr*)local_address->addr,
- (int)local_address->len) != 0) {
- int wsa_last_error = WSAGetLastError();
- wsa_error_ctx->SetWSAError(wsa_last_error);
- char* msg = gpr_format_message(wsa_last_error);
- GRPC_CARES_TRACE_LOG("fd:%s bind error code:%d msg:|%s|", GetName(),
- wsa_last_error, msg);
- gpr_free(msg);
- connect_done_ = true;
- wsa_connect_error_ = wsa_last_error;
- return -1;
- }
- int out = 0;
- if (ConnectEx(s, target, target_len, nullptr, 0, nullptr,
- &winsocket_->write_info.overlapped) == 0) {
+ connect_done_ = true;
+ wsa_connect_error_ = wsa_last_error;
+ return -1;
+ }
+ grpc_resolved_address wildcard4_addr;
+ grpc_resolved_address wildcard6_addr;
+ grpc_sockaddr_make_wildcards(0, &wildcard4_addr, &wildcard6_addr);
+ grpc_resolved_address* local_address = nullptr;
+ if (address_family_ == AF_INET) {
+ local_address = &wildcard4_addr;
+ } else {
+ local_address = &wildcard6_addr;
+ }
+ if (bind(s, (struct sockaddr*)local_address->addr,
+ (int)local_address->len) != 0) {
+ int wsa_last_error = WSAGetLastError();
+ wsa_error_ctx->SetWSAError(wsa_last_error);
+ char* msg = gpr_format_message(wsa_last_error);
+ GRPC_CARES_TRACE_LOG("fd:%s bind error code:%d msg:|%s|", GetName(),
+ wsa_last_error, msg);
+ gpr_free(msg);
+ connect_done_ = true;
+ wsa_connect_error_ = wsa_last_error;
+ return -1;
+ }
+ int out = 0;
+ if (ConnectEx(s, target, target_len, nullptr, 0, nullptr,
+ &winsocket_->write_info.overlapped) == 0) {
out = -1;
- int wsa_last_error = WSAGetLastError();
- wsa_error_ctx->SetWSAError(wsa_last_error);
- char* msg = gpr_format_message(wsa_last_error);
- GRPC_CARES_TRACE_LOG("fd:%s ConnectEx error code:%d msg:|%s|", GetName(),
- wsa_last_error, msg);
- gpr_free(msg);
- if (wsa_last_error == WSA_IO_PENDING) {
- // c-ares only understands WSAEINPROGRESS and EWOULDBLOCK error codes on
- // connect, but an async connect on IOCP socket will give
- // WSA_IO_PENDING, so we need to convert.
- wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
- } else {
- // By returning a non-retryable error to c-ares at this point,
- // we're aborting the possibility of any future operations on this fd.
- connect_done_ = true;
- wsa_connect_error_ = wsa_last_error;
- return -1;
- }
- }
- grpc_socket_notify_on_write(winsocket_, &on_tcp_connect_locked_);
+ int wsa_last_error = WSAGetLastError();
+ wsa_error_ctx->SetWSAError(wsa_last_error);
+ char* msg = gpr_format_message(wsa_last_error);
+ GRPC_CARES_TRACE_LOG("fd:%s ConnectEx error code:%d msg:|%s|", GetName(),
+ wsa_last_error, msg);
+ gpr_free(msg);
+ if (wsa_last_error == WSA_IO_PENDING) {
+ // c-ares only understands WSAEINPROGRESS and EWOULDBLOCK error codes on
+ // connect, but an async connect on IOCP socket will give
+ // WSA_IO_PENDING, so we need to convert.
+ wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK);
+ } else {
+ // By returning a non-retryable error to c-ares at this point,
+ // we're aborting the possibility of any future operations on this fd.
+ connect_done_ = true;
+ wsa_connect_error_ = wsa_last_error;
+ return -1;
+ }
+ }
+ grpc_socket_notify_on_write(winsocket_, &on_tcp_connect_locked_);
return out;
}
@@ -580,13 +580,13 @@ class GrpcPolledFdWindows {
polled_fd->work_serializer_->Run(
[polled_fd, error]() { polled_fd->OnIocpReadableLocked(error); },
DEBUG_LOCATION);
- }
-
- // TODO(apolcyn): improve this error handling to be less conversative.
- // An e.g. ECONNRESET error here should result in errors when
- // c-ares reads from this socket later, but it shouldn't necessarily cancel
- // the entire resolution attempt. Doing so will allow the "inject broken
- // nameserver list" test to pass on Windows.
+ }
+
+ // TODO(apolcyn): improve this error handling to be less conversative.
+ // An e.g. ECONNRESET error here should result in errors when
+ // c-ares reads from this socket later, but it shouldn't necessarily cancel
+ // the entire resolution attempt. Doing so will allow the "inject broken
+ // nameserver list" test to pass on Windows.
void OnIocpReadableLocked(grpc_error* error) {
if (error == GRPC_ERROR_NONE) {
if (winsocket_->read_info.wsa_error != 0) {
@@ -595,27 +595,27 @@ class GrpcPolledFdWindows {
* the connection is TCP and read the leftovers
* in subsequent c-ares reads. */
if (winsocket_->read_info.wsa_error != WSAEMSGSIZE) {
- error = GRPC_WSA_ERROR(winsocket_->read_info.wsa_error,
- "OnIocpReadableInner");
+ error = GRPC_WSA_ERROR(winsocket_->read_info.wsa_error,
+ "OnIocpReadableInner");
GRPC_CARES_TRACE_LOG(
- "fd:|%s| OnIocpReadableInner winsocket_->read_info.wsa_error "
- "code:|%d| msg:|%s|",
- GetName(), winsocket_->read_info.wsa_error,
- grpc_error_string(error));
+ "fd:|%s| OnIocpReadableInner winsocket_->read_info.wsa_error "
+ "code:|%d| msg:|%s|",
+ GetName(), winsocket_->read_info.wsa_error,
+ grpc_error_string(error));
}
}
}
if (error == GRPC_ERROR_NONE) {
- read_buf_ = grpc_slice_sub_no_ref(
- read_buf_, 0, winsocket_->read_info.bytes_transferred);
- read_buf_has_data_ = true;
+ read_buf_ = grpc_slice_sub_no_ref(
+ read_buf_, 0, winsocket_->read_info.bytes_transferred);
+ read_buf_has_data_ = true;
} else {
grpc_slice_unref_internal(read_buf_);
read_buf_ = grpc_empty_slice();
}
GRPC_CARES_TRACE_LOG(
- "fd:|%s| OnIocpReadable finishing. read buf length now:|%d|", GetName(),
- GRPC_SLICE_LENGTH(read_buf_));
+ "fd:|%s| OnIocpReadable finishing. read buf length now:|%d|", GetName(),
+ GRPC_SLICE_LENGTH(read_buf_));
ScheduleAndNullReadClosure(error);
}
@@ -625,29 +625,29 @@ class GrpcPolledFdWindows {
polled_fd->work_serializer_->Run(
[polled_fd, error]() { polled_fd->OnIocpWriteableLocked(error); },
DEBUG_LOCATION);
- }
-
+ }
+
void OnIocpWriteableLocked(grpc_error* error) {
GRPC_CARES_TRACE_LOG("OnIocpWriteableInner. fd:|%s|", GetName());
- GPR_ASSERT(socket_type_ == SOCK_STREAM);
+ GPR_ASSERT(socket_type_ == SOCK_STREAM);
if (error == GRPC_ERROR_NONE) {
if (winsocket_->write_info.wsa_error != 0) {
- error = GRPC_WSA_ERROR(winsocket_->write_info.wsa_error,
- "OnIocpWriteableInner");
+ error = GRPC_WSA_ERROR(winsocket_->write_info.wsa_error,
+ "OnIocpWriteableInner");
GRPC_CARES_TRACE_LOG(
- "fd:|%s| OnIocpWriteableInner. winsocket_->write_info.wsa_error "
- "code:|%d| msg:|%s|",
- GetName(), winsocket_->write_info.wsa_error,
- grpc_error_string(error));
+ "fd:|%s| OnIocpWriteableInner. winsocket_->write_info.wsa_error "
+ "code:|%d| msg:|%s|",
+ GetName(), winsocket_->write_info.wsa_error,
+ grpc_error_string(error));
}
}
- GPR_ASSERT(tcp_write_state_ == WRITE_PENDING);
+ GPR_ASSERT(tcp_write_state_ == WRITE_PENDING);
if (error == GRPC_ERROR_NONE) {
- tcp_write_state_ = WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY;
+ tcp_write_state_ = WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY;
write_buf_ = grpc_slice_sub_no_ref(
- write_buf_, 0, winsocket_->write_info.bytes_transferred);
- GRPC_CARES_TRACE_LOG("fd:|%s| OnIocpWriteableInner. bytes transferred:%d",
- GetName(), winsocket_->write_info.bytes_transferred);
+ write_buf_, 0, winsocket_->write_info.bytes_transferred);
+ GRPC_CARES_TRACE_LOG("fd:|%s| OnIocpWriteableInner. bytes transferred:%d",
+ GetName(), winsocket_->write_info.bytes_transferred);
} else {
grpc_slice_unref_internal(write_buf_);
write_buf_ = grpc_empty_slice();
@@ -663,25 +663,25 @@ class GrpcPolledFdWindows {
char recv_from_source_addr_[200];
ares_socklen_t recv_from_source_addr_len_;
grpc_slice read_buf_;
- bool read_buf_has_data_ = false;
+ bool read_buf_has_data_ = false;
grpc_slice write_buf_;
grpc_closure* read_closure_ = nullptr;
grpc_closure* write_closure_ = nullptr;
grpc_closure outer_read_closure_;
grpc_closure outer_write_closure_;
grpc_winsocket* winsocket_;
- // tcp_write_state_ is only used on TCP GrpcPolledFds
- WriteState tcp_write_state_;
+ // tcp_write_state_ is only used on TCP GrpcPolledFds
+ WriteState tcp_write_state_;
TString name_;
bool gotten_into_driver_list_;
- int address_family_;
- int socket_type_;
- grpc_closure on_tcp_connect_locked_;
- bool connect_done_ = false;
- int wsa_connect_error_ = 0;
- // We don't run register_for_{readable,writeable} logic until
- // a socket is connected. In the interim, we queue readable/writeable
- // registrations with the following state.
+ int address_family_;
+ int socket_type_;
+ grpc_closure on_tcp_connect_locked_;
+ bool connect_done_ = false;
+ int wsa_connect_error_ = 0;
+ // We don't run register_for_{readable,writeable} logic until
+ // a socket is connected. In the interim, we queue readable/writeable
+ // registrations with the following state.
bool pending_continue_register_for_on_readable_locked_ = false;
bool pending_continue_register_for_on_writeable_locked_ = false;
};
@@ -707,7 +707,7 @@ class SockToPolledFdMap {
~SockToPolledFdMap() { GPR_ASSERT(head_ == nullptr); }
void AddNewSocket(SOCKET s, GrpcPolledFdWindows* polled_fd) {
- SockToPolledFdEntry* new_node = new SockToPolledFdEntry(s, polled_fd);
+ SockToPolledFdEntry* new_node = new SockToPolledFdEntry(s, polled_fd);
new_node->next = head_;
head_ = new_node;
}
@@ -730,7 +730,7 @@ class SockToPolledFdMap {
node = node->next) {
if (node->socket == s) {
*prev = node->next;
- delete node;
+ delete node;
return;
}
prev = &node->next;
@@ -745,64 +745,64 @@ class SockToPolledFdMap {
* objects.
*/
static ares_socket_t Socket(int af, int type, int protocol, void* user_data) {
- if (type != SOCK_DGRAM && type != SOCK_STREAM) {
- GRPC_CARES_TRACE_LOG("Socket called with invalid socket type:%d", type);
- return INVALID_SOCKET;
- }
+ if (type != SOCK_DGRAM && type != SOCK_STREAM) {
+ GRPC_CARES_TRACE_LOG("Socket called with invalid socket type:%d", type);
+ return INVALID_SOCKET;
+ }
SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data);
- SOCKET s = WSASocket(af, type, protocol, nullptr, 0,
- grpc_get_default_wsa_socket_flags());
+ SOCKET s = WSASocket(af, type, protocol, nullptr, 0,
+ grpc_get_default_wsa_socket_flags());
if (s == INVALID_SOCKET) {
- GRPC_CARES_TRACE_LOG(
- "WSASocket failed with params af:%d type:%d protocol:%d", af, type,
- protocol);
+ GRPC_CARES_TRACE_LOG(
+ "WSASocket failed with params af:%d type:%d protocol:%d", af, type,
+ protocol);
return s;
}
grpc_tcp_set_non_block(s);
GrpcPolledFdWindows* polled_fd =
new GrpcPolledFdWindows(s, map->work_serializer_, af, type);
- GRPC_CARES_TRACE_LOG(
- "fd:|%s| created with params af:%d type:%d protocol:%d",
- polled_fd->GetName(), af, type, protocol);
+ GRPC_CARES_TRACE_LOG(
+ "fd:|%s| created with params af:%d type:%d protocol:%d",
+ polled_fd->GetName(), af, type, protocol);
map->AddNewSocket(s, polled_fd);
return s;
}
static int Connect(ares_socket_t as, const struct sockaddr* target,
ares_socklen_t target_len, void* user_data) {
- WSAErrorContext wsa_error_ctx;
+ WSAErrorContext wsa_error_ctx;
SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data);
GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as);
- return polled_fd->Connect(&wsa_error_ctx, target, target_len);
+ return polled_fd->Connect(&wsa_error_ctx, target, target_len);
}
static ares_ssize_t SendV(ares_socket_t as, const struct iovec* iov,
int iovec_count, void* user_data) {
- WSAErrorContext wsa_error_ctx;
+ WSAErrorContext wsa_error_ctx;
SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data);
GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as);
- return polled_fd->SendV(&wsa_error_ctx, iov, iovec_count);
+ return polled_fd->SendV(&wsa_error_ctx, iov, iovec_count);
}
static ares_ssize_t RecvFrom(ares_socket_t as, void* data, size_t data_len,
int flags, struct sockaddr* from,
ares_socklen_t* from_len, void* user_data) {
- WSAErrorContext wsa_error_ctx;
+ WSAErrorContext wsa_error_ctx;
SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data);
GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as);
- return polled_fd->RecvFrom(&wsa_error_ctx, data, data_len, flags, from,
- from_len);
+ return polled_fd->RecvFrom(&wsa_error_ctx, data, data_len, flags, from,
+ from_len);
}
static int CloseSocket(SOCKET s, void* user_data) {
SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data);
GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(s);
map->RemoveEntry(s);
- // See https://github.com/grpc/grpc/pull/20284, this trace log is
- // intentionally placed to attempt to trigger a crash in case of a
- // use after free on polled_fd.
- GRPC_CARES_TRACE_LOG("CloseSocket called for socket: %s",
- polled_fd->GetName());
+ // See https://github.com/grpc/grpc/pull/20284, this trace log is
+ // intentionally placed to attempt to trigger a crash in case of a
+ // use after free on polled_fd.
+ GRPC_CARES_TRACE_LOG("CloseSocket called for socket: %s",
+ polled_fd->GetName());
// If a gRPC polled fd has not made it in to the driver's list yet, then
// the driver has not and will never see this socket.
if (!polled_fd->gotten_into_driver_list()) {
@@ -810,7 +810,7 @@ class SockToPolledFdMap {
"Shut down c-ares fd before without it ever having made it into the "
"driver's list"));
}
- delete polled_fd;
+ delete polled_fd;
return 0;
}
@@ -827,42 +827,42 @@ const struct ares_socket_functions custom_ares_sock_funcs = {
&SockToPolledFdMap::SendV /* sendv */,
};
-/* A thin wrapper over a GrpcPolledFdWindows object but with a shorter
- lifetime. This object releases it's GrpcPolledFdWindows upon destruction,
- so that c-ares can close it via usual socket teardown. */
-class GrpcPolledFdWindowsWrapper : public GrpcPolledFd {
- public:
+/* A thin wrapper over a GrpcPolledFdWindows object but with a shorter
+ lifetime. This object releases it's GrpcPolledFdWindows upon destruction,
+ so that c-ares can close it via usual socket teardown. */
+class GrpcPolledFdWindowsWrapper : public GrpcPolledFd {
+ public:
explicit GrpcPolledFdWindowsWrapper(GrpcPolledFdWindows* wrapped)
- : wrapped_(wrapped) {}
-
- ~GrpcPolledFdWindowsWrapper() {}
-
- void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
- wrapped_->RegisterForOnReadableLocked(read_closure);
- }
-
- void RegisterForOnWriteableLocked(grpc_closure* write_closure) override {
- wrapped_->RegisterForOnWriteableLocked(write_closure);
- }
-
- bool IsFdStillReadableLocked() override {
- return wrapped_->IsFdStillReadableLocked();
- }
-
- void ShutdownLocked(grpc_error* error) override {
- wrapped_->ShutdownLocked(error);
- }
-
- ares_socket_t GetWrappedAresSocketLocked() override {
- return wrapped_->GetWrappedAresSocketLocked();
- }
-
- const char* GetName() override { return wrapped_->GetName(); }
-
- private:
- GrpcPolledFdWindows* wrapped_;
-};
-
+ : wrapped_(wrapped) {}
+
+ ~GrpcPolledFdWindowsWrapper() {}
+
+ void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
+ wrapped_->RegisterForOnReadableLocked(read_closure);
+ }
+
+ void RegisterForOnWriteableLocked(grpc_closure* write_closure) override {
+ wrapped_->RegisterForOnWriteableLocked(write_closure);
+ }
+
+ bool IsFdStillReadableLocked() override {
+ return wrapped_->IsFdStillReadableLocked();
+ }
+
+ void ShutdownLocked(grpc_error* error) override {
+ wrapped_->ShutdownLocked(error);
+ }
+
+ ares_socket_t GetWrappedAresSocketLocked() override {
+ return wrapped_->GetWrappedAresSocketLocked();
+ }
+
+ const char* GetName() override { return wrapped_->GetName(); }
+
+ private:
+ GrpcPolledFdWindows* wrapped_;
+};
+
class GrpcPolledFdFactoryWindows : public GrpcPolledFdFactory {
public:
explicit GrpcPolledFdFactoryWindows(
@@ -876,7 +876,7 @@ class GrpcPolledFdFactoryWindows : public GrpcPolledFdFactory {
// Set a flag so that the virtual socket "close" method knows it
// doesn't need to call ShutdownLocked, since now the driver will.
polled_fd->set_gotten_into_driver_list();
- return new GrpcPolledFdWindowsWrapper(polled_fd);
+ return new GrpcPolledFdWindowsWrapper(polled_fd);
}
void ConfigureAresChannelLocked(ares_channel channel) override {
@@ -888,7 +888,7 @@ class GrpcPolledFdFactoryWindows : public GrpcPolledFdFactory {
SockToPolledFdMap sock_to_polled_fd_map_;
};
-std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
+std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
std::shared_ptr<WorkSerializer> work_serializer) {
return y_absl::make_unique<GrpcPolledFdFactoryWindows>(
std::move(work_serializer));
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
index c3b236af68..7f7a81e584 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
-#if GRPC_ARES == 1
+#if GRPC_ARES == 1
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/lib/iomgr/sockaddr.h"
@@ -39,7 +39,7 @@
#include <address_sorting/address_sorting.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
@@ -63,7 +63,7 @@ struct grpc_ares_request {
/** closure to call when the request completes */
grpc_closure* on_done;
/** the pointer to receive the resolved addresses */
- std::unique_ptr<grpc_core::ServerAddressList>* addresses_out;
+ std::unique_ptr<grpc_core::ServerAddressList>* addresses_out;
/** the pointer to receive the resolved balancer addresses */
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addresses_out;
/** the pointer to receive the service config in JSON */
@@ -73,7 +73,7 @@ struct grpc_ares_request {
/** number of ongoing queries */
size_t pending_queries;
- /** the errors explaining query failures, appended to in query callbacks */
+ /** the errors explaining query failures, appended to in query callbacks */
grpc_error* error;
};
@@ -136,7 +136,7 @@ static void log_address_sorting_list(const grpc_ares_request* r,
void grpc_cares_wrapper_address_sorting_sort(const grpc_ares_request* r,
ServerAddressList* addresses) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_address_sorting)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_address_sorting)) {
log_address_sorting_list(r, *addresses, "input");
}
address_sorting_sortable* sortables = (address_sorting_sortable*)gpr_zalloc(
@@ -155,7 +155,7 @@ void grpc_cares_wrapper_address_sorting_sort(const grpc_ares_request* r,
}
gpr_free(sortables);
*addresses = std::move(sorted);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_address_sorting)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_address_sorting)) {
log_address_sorting_list(r, *addresses, "output");
}
}
@@ -178,10 +178,10 @@ void grpc_ares_complete_request_locked(grpc_ares_request* r) {
ServerAddressList* addresses = r->addresses_out->get();
if (addresses != nullptr) {
grpc_cares_wrapper_address_sorting_sort(r, addresses);
- GRPC_ERROR_UNREF(r->error);
- r->error = GRPC_ERROR_NONE;
- // TODO(apolcyn): allow c-ares to return a service config
- // with no addresses along side it
+ GRPC_ERROR_UNREF(r->error);
+ r->error = GRPC_ERROR_NONE;
+ // TODO(apolcyn): allow c-ares to return a service config
+ // with no addresses along side it
}
if (r->balancer_addresses_out != nullptr) {
ServerAddressList* balancer_addresses = r->balancer_addresses_out->get();
@@ -189,7 +189,7 @@ void grpc_ares_complete_request_locked(grpc_ares_request* r) {
grpc_cares_wrapper_address_sorting_sort(r, balancer_addresses);
}
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, r->error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, r->error);
}
/* Note that the returned object takes a reference to qtype, so
@@ -197,8 +197,8 @@ void grpc_ares_complete_request_locked(grpc_ares_request* r) {
static grpc_ares_hostbyname_request* create_hostbyname_request_locked(
grpc_ares_request* parent_request, const char* host, uint16_t port,
bool is_balancer, const char* qtype) {
- GRPC_CARES_TRACE_LOG(
- "request:%p create_hostbyname_request_locked host:%s port:%d "
+ GRPC_CARES_TRACE_LOG(
+ "request:%p create_hostbyname_request_locked host:%s port:%d "
"is_balancer:%d qtype:%s",
parent_request, host, port, is_balancer, qtype);
grpc_ares_hostbyname_request* hr = new grpc_ares_hostbyname_request();
@@ -218,13 +218,13 @@ static void destroy_hostbyname_request_locked(
delete hr;
}
-static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
+static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
struct hostent* hostent) {
grpc_ares_hostbyname_request* hr =
static_cast<grpc_ares_hostbyname_request*>(arg);
grpc_ares_request* r = hr->parent_request;
if (status == ARES_SUCCESS) {
- GRPC_CARES_TRACE_LOG(
+ GRPC_CARES_TRACE_LOG(
"request:%p on_hostbyname_done_locked qtype=%s host=%s ARES_SUCCESS", r,
hr->qtype, hr->host);
std::unique_ptr<ServerAddressList>* address_list_ptr =
@@ -278,19 +278,19 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
}
}
}
- } else {
+ } else {
TString error_msg = y_absl::StrFormat(
"C-ares status is not ARES_SUCCESS qtype=%s name=%s is_balancer=%d: %s",
hr->qtype, hr->host, hr->is_balancer, ares_strerror(status));
GRPC_CARES_TRACE_LOG("request:%p on_hostbyname_done_locked: %s", r,
error_msg.c_str());
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str());
- r->error = grpc_error_add_child(error, r->error);
+ r->error = grpc_error_add_child(error, r->error);
}
destroy_hostbyname_request_locked(hr);
}
-static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/,
+static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/,
unsigned char* abuf, int alen) {
GrpcAresQuery* q = static_cast<GrpcAresQuery*>(arg);
grpc_ares_request* r = q->parent_request();
@@ -300,8 +300,8 @@ static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/,
q->name().c_str());
struct ares_srv_reply* reply;
const int parse_status = ares_parse_srv_reply(abuf, alen, &reply);
- GRPC_CARES_TRACE_LOG("request:%p ares_parse_srv_reply: %d", r,
- parse_status);
+ GRPC_CARES_TRACE_LOG("request:%p ares_parse_srv_reply: %d", r,
+ parse_status);
if (parse_status == ARES_SUCCESS) {
ares_channel* channel =
grpc_ares_ev_driver_get_channel_locked(r->ev_driver);
@@ -324,21 +324,21 @@ static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/,
if (reply != nullptr) {
ares_free_data(reply);
}
- } else {
+ } else {
TString error_msg = y_absl::StrFormat(
"C-ares status is not ARES_SUCCESS qtype=SRV name=%s: %s", q->name(),
ares_strerror(status));
GRPC_CARES_TRACE_LOG("request:%p on_srv_query_done_locked: %s", r,
error_msg.c_str());
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str());
- r->error = grpc_error_add_child(error, r->error);
+ r->error = grpc_error_add_child(error, r->error);
}
delete q;
}
static const char g_service_config_attribute_prefix[] = "grpc_config=";
-static void on_txt_done_locked(void* arg, int status, int /*timeouts*/,
+static void on_txt_done_locked(void* arg, int status, int /*timeouts*/,
unsigned char* buf, int len) {
GrpcAresQuery* q = static_cast<GrpcAresQuery*>(arg);
std::unique_ptr<GrpcAresQuery> query_deleter(q);
@@ -390,7 +390,7 @@ fail:
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str());
GRPC_CARES_TRACE_LOG("request:%p on_txt_done_locked %s", r,
error_msg.c_str());
- r->error = grpc_error_add_child(error, r->error);
+ r->error = grpc_error_add_child(error, r->error);
}
void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
@@ -404,7 +404,7 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
/* parse name, splitting it into host and port parts */
TString host;
TString port;
- grpc_core::SplitHostPort(name, &host, &port);
+ grpc_core::SplitHostPort(name, &host, &port);
if (host.empty()) {
error = grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"),
@@ -490,7 +490,7 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
return;
error_cleanup:
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
}
static bool inner_resolve_as_ip_literal_locked(
@@ -517,9 +517,9 @@ static bool inner_resolve_as_ip_literal_locked(
grpc_resolved_address addr;
*hostport = grpc_core::JoinHostPort(*host, atoi(port->c_str()));
if (grpc_parse_ipv4_hostport(hostport->c_str(), &addr,
- false /* log errors */) ||
+ false /* log errors */) ||
grpc_parse_ipv6_hostport(hostport->c_str(), &addr,
- false /* log errors */)) {
+ false /* log errors */)) {
GPR_ASSERT(*addrs == nullptr);
*addrs = y_absl::make_unique<ServerAddressList>();
(*addrs)->emplace_back(addr.addr, addr.len, nullptr /* args */);
@@ -530,7 +530,7 @@ static bool inner_resolve_as_ip_literal_locked(
static bool resolve_as_ip_literal_locked(
const char* name, const char* default_port,
- std::unique_ptr<grpc_core::ServerAddressList>* addrs) {
+ std::unique_ptr<grpc_core::ServerAddressList>* addrs) {
TString host;
TString port;
TString hostport;
@@ -541,7 +541,7 @@ static bool resolve_as_ip_literal_locked(
static bool target_matches_localhost_inner(const char* name, TString* host,
TString* port) {
- if (!grpc_core::SplitHostPort(name, host, port)) {
+ if (!grpc_core::SplitHostPort(name, host, port)) {
gpr_log(GPR_ERROR, "Unable to split host and port for name: %s", name);
return false;
}
@@ -555,83 +555,83 @@ static bool target_matches_localhost_inner(const char* name, TString* host,
static bool target_matches_localhost(const char* name) {
TString host;
TString port;
- return target_matches_localhost_inner(name, &host, &port);
+ return target_matches_localhost_inner(name, &host, &port);
}
-#ifdef GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY
-static bool inner_maybe_resolve_localhost_manually_locked(
+#ifdef GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY
+static bool inner_maybe_resolve_localhost_manually_locked(
const grpc_ares_request* r, const char* name, const char* default_port,
std::unique_ptr<grpc_core::ServerAddressList>* addrs, TString* host,
TString* port) {
- grpc_core::SplitHostPort(name, host, port);
+ grpc_core::SplitHostPort(name, host, port);
if (host->empty()) {
- gpr_log(GPR_ERROR,
- "Failed to parse %s into host:port during manual localhost "
- "resolution check.",
- name);
- return false;
- }
+ gpr_log(GPR_ERROR,
+ "Failed to parse %s into host:port during manual localhost "
+ "resolution check.",
+ name);
+ return false;
+ }
if (port->empty()) {
- if (default_port == nullptr) {
- gpr_log(GPR_ERROR,
- "No port or default port for %s during manual localhost "
- "resolution check.",
- name);
- return false;
- }
+ if (default_port == nullptr) {
+ gpr_log(GPR_ERROR,
+ "No port or default port for %s during manual localhost "
+ "resolution check.",
+ name);
+ return false;
+ }
*port = default_port;
- }
+ }
if (gpr_stricmp(host->c_str(), "localhost") == 0) {
- GPR_ASSERT(*addrs == nullptr);
+ GPR_ASSERT(*addrs == nullptr);
*addrs = y_absl::make_unique<grpc_core::ServerAddressList>();
uint16_t numeric_port = grpc_strhtons(port->c_str());
- // Append the ipv6 loopback address.
- struct sockaddr_in6 ipv6_loopback_addr;
- memset(&ipv6_loopback_addr, 0, sizeof(ipv6_loopback_addr));
- ((char*)&ipv6_loopback_addr.sin6_addr)[15] = 1;
- ipv6_loopback_addr.sin6_family = AF_INET6;
- ipv6_loopback_addr.sin6_port = numeric_port;
- (*addrs)->emplace_back(&ipv6_loopback_addr, sizeof(ipv6_loopback_addr),
- nullptr /* args */);
- // Append the ipv4 loopback address.
- struct sockaddr_in ipv4_loopback_addr;
- memset(&ipv4_loopback_addr, 0, sizeof(ipv4_loopback_addr));
- ((char*)&ipv4_loopback_addr.sin_addr)[0] = 0x7f;
- ((char*)&ipv4_loopback_addr.sin_addr)[3] = 0x01;
- ipv4_loopback_addr.sin_family = AF_INET;
- ipv4_loopback_addr.sin_port = numeric_port;
- (*addrs)->emplace_back(&ipv4_loopback_addr, sizeof(ipv4_loopback_addr),
- nullptr /* args */);
- // Let the address sorter figure out which one should be tried first.
+ // Append the ipv6 loopback address.
+ struct sockaddr_in6 ipv6_loopback_addr;
+ memset(&ipv6_loopback_addr, 0, sizeof(ipv6_loopback_addr));
+ ((char*)&ipv6_loopback_addr.sin6_addr)[15] = 1;
+ ipv6_loopback_addr.sin6_family = AF_INET6;
+ ipv6_loopback_addr.sin6_port = numeric_port;
+ (*addrs)->emplace_back(&ipv6_loopback_addr, sizeof(ipv6_loopback_addr),
+ nullptr /* args */);
+ // Append the ipv4 loopback address.
+ struct sockaddr_in ipv4_loopback_addr;
+ memset(&ipv4_loopback_addr, 0, sizeof(ipv4_loopback_addr));
+ ((char*)&ipv4_loopback_addr.sin_addr)[0] = 0x7f;
+ ((char*)&ipv4_loopback_addr.sin_addr)[3] = 0x01;
+ ipv4_loopback_addr.sin_family = AF_INET;
+ ipv4_loopback_addr.sin_port = numeric_port;
+ (*addrs)->emplace_back(&ipv4_loopback_addr, sizeof(ipv4_loopback_addr),
+ nullptr /* args */);
+ // Let the address sorter figure out which one should be tried first.
grpc_cares_wrapper_address_sorting_sort(r, addrs->get());
- return true;
- }
- return false;
-}
-
-static bool grpc_ares_maybe_resolve_localhost_manually_locked(
+ return true;
+ }
+ return false;
+}
+
+static bool grpc_ares_maybe_resolve_localhost_manually_locked(
const grpc_ares_request* r, const char* name, const char* default_port,
- std::unique_ptr<grpc_core::ServerAddressList>* addrs) {
+ std::unique_ptr<grpc_core::ServerAddressList>* addrs) {
TString host;
TString port;
return inner_maybe_resolve_localhost_manually_locked(r, name, default_port,
- addrs, &host, &port);
-}
-#else /* GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY */
-static bool grpc_ares_maybe_resolve_localhost_manually_locked(
+ addrs, &host, &port);
+}
+#else /* GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY */
+static bool grpc_ares_maybe_resolve_localhost_manually_locked(
const grpc_ares_request* /*r*/, const char* /*name*/,
const char* /*default_port*/,
- std::unique_ptr<grpc_core::ServerAddressList>* /*addrs*/) {
- return false;
-}
-#endif /* GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY */
-
+ std::unique_ptr<grpc_core::ServerAddressList>* /*addrs*/) {
+ return false;
+}
+#endif /* GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY */
+
static grpc_ares_request* grpc_dns_lookup_ares_locked_impl(
const char* dns_server, const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs,
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addrs,
- char** service_config_json, int query_timeout_ms,
+ char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) {
grpc_ares_request* r =
static_cast<grpc_ares_request*>(gpr_zalloc(sizeof(grpc_ares_request)));
@@ -676,7 +676,7 @@ grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs,
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addrs,
- char** service_config_json, int query_timeout_ms,
+ char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) =
grpc_dns_lookup_ares_locked_impl;
@@ -690,10 +690,10 @@ static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) {
void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) =
grpc_cancel_ares_request_locked_impl;
-// ares_library_init and ares_library_cleanup are currently no-op except under
-// Windows. Calling them may cause race conditions when other parts of the
-// binary calls these functions concurrently.
-#ifdef GPR_WINDOWS
+// ares_library_init and ares_library_cleanup are currently no-op except under
+// Windows. Calling them may cause race conditions when other parts of the
+// binary calls these functions concurrently.
+#ifdef GPR_WINDOWS
grpc_error* grpc_ares_init(void) {
int status = ares_library_init(ARES_LIB_INIT_ALL);
if (status != ARES_SUCCESS) {
@@ -704,11 +704,11 @@ grpc_error* grpc_ares_init(void) {
return GRPC_ERROR_NONE;
}
-void grpc_ares_cleanup(void) { ares_library_cleanup(); }
-#else
-grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; }
-void grpc_ares_cleanup(void) {}
-#endif // GPR_WINDOWS
+void grpc_ares_cleanup(void) { ares_library_cleanup(); }
+#else
+grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; }
+void grpc_ares_cleanup(void) {}
+#endif // GPR_WINDOWS
/*
* grpc_resolve_address_ares related structs and functions
@@ -720,7 +720,7 @@ typedef struct grpc_resolve_address_ares_request {
/** the pointer to receive the resolved addresses */
grpc_resolved_addresses** addrs_out;
/** currently resolving addresses */
- std::unique_ptr<ServerAddressList> addresses;
+ std::unique_ptr<ServerAddressList> addresses;
/** closure to call when the resolve_address_ares request completes */
grpc_closure* on_resolve_address_done;
/** a closure wrapping on_resolve_address_done, which should be invoked when
@@ -755,22 +755,22 @@ static void on_dns_lookup_done_locked(grpc_resolve_address_ares_request* r,
}
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_resolve_address_done, error);
- delete r;
+ delete r;
}
-static void on_dns_lookup_done(void* arg, grpc_error* error) {
- grpc_resolve_address_ares_request* r =
- static_cast<grpc_resolve_address_ares_request*>(arg);
+static void on_dns_lookup_done(void* arg, grpc_error* error) {
+ grpc_resolve_address_ares_request* r =
+ static_cast<grpc_resolve_address_ares_request*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
r->work_serializer->Run([r, error]() { on_dns_lookup_done_locked(r, error); },
DEBUG_LOCATION);
-}
-
+}
+
static void grpc_resolve_address_invoke_dns_lookup_ares_locked(void* arg) {
grpc_resolve_address_ares_request* r =
static_cast<grpc_resolve_address_ares_request*>(arg);
- GRPC_CLOSURE_INIT(&r->on_dns_lookup_done_locked, on_dns_lookup_done, r,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&r->on_dns_lookup_done_locked, on_dns_lookup_done, r,
+ grpc_schedule_on_exec_ctx);
r->ares_request = grpc_dns_lookup_ares_locked(
nullptr /* dns_server */, r->name, r->default_port, r->interested_parties,
&r->on_dns_lookup_done_locked, &r->addresses,
@@ -784,7 +784,7 @@ static void grpc_resolve_address_ares_impl(const char* name,
grpc_closure* on_done,
grpc_resolved_addresses** addrs) {
grpc_resolve_address_ares_request* r =
- new grpc_resolve_address_ares_request();
+ new grpc_resolve_address_ares_request();
r->work_serializer = std::make_shared<grpc_core::WorkSerializer>();
r->addrs_out = addrs;
r->on_resolve_address_done = on_done;
@@ -801,4 +801,4 @@ void (*grpc_resolve_address_ares)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
-#endif /* GRPC_ARES == 1 */
+#endif /* GRPC_ARES == 1 */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h
index ddce754934..93f218e0bc 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h
@@ -27,18 +27,18 @@
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/work_serializer.h"
-#define GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS 120000
+#define GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS 120000
extern grpc_core::TraceFlag grpc_trace_cares_address_sorting;
extern grpc_core::TraceFlag grpc_trace_cares_resolver;
-#define GRPC_CARES_TRACE_LOG(format, ...) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_resolver)) { \
- gpr_log(GPR_DEBUG, "(c-ares resolver) " format, __VA_ARGS__); \
- } \
- } while (0)
+#define GRPC_CARES_TRACE_LOG(format, ...) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_resolver)) { \
+ gpr_log(GPR_DEBUG, "(c-ares resolver) " format, __VA_ARGS__); \
+ } \
+ } while (0)
typedef struct grpc_ares_request grpc_ares_request;
@@ -66,7 +66,7 @@ extern grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addresses,
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addresses,
- char** service_config_json, int query_timeout_ms,
+ char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer);
/* Cancel the pending grpc_ares_request \a request */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
index 2049f37118..e88ac3f7cf 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
-#if GRPC_ARES != 1
+#if GRPC_ARES != 1
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
@@ -31,7 +31,7 @@ static grpc_ares_request* grpc_dns_lookup_ares_locked_impl(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs,
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addrs,
- char** service_config_json, int query_timeout_ms,
+ char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) {
return NULL;
}
@@ -41,7 +41,7 @@ grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs,
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addrs,
- char** service_config_json, int query_timeout_ms,
+ char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) =
grpc_dns_lookup_ares_locked_impl;
@@ -65,4 +65,4 @@ void (*grpc_resolve_address_ares)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
-#endif /* GRPC_ARES != 1 */
+#endif /* GRPC_ARES != 1 */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
index 1d4a90fbd9..8139215908 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
@@ -1,38 +1,38 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-#if GRPC_ARES == 1 && defined(GRPC_UV)
-
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
-#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/lib/gpr/string.h"
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+#if GRPC_ARES == 1 && defined(GRPC_UV)
+
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
+#include "src/core/ext/filters/client_channel/server_address.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/parse_address.h"
-
-bool grpc_ares_query_ipv6() {
- /* The libuv grpc code currently does not have the code to probe for this,
- * so we assume for now that IPv6 is always available in contexts where this
- * code will be used. */
- return true;
-}
-
-#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */
+
+bool grpc_ares_query_ipv6() {
+ /* The libuv grpc code currently does not have the code to probe for this,
+ * so we assume for now that IPv6 is always available in contexts where this
+ * code will be used. */
+ return true;
+}
+
+#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
index df11db3624..7b31c1c98d 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
@@ -19,7 +19,7 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
-#if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER)
+#if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER)
#include <grpc/support/string_util.h>
@@ -31,4 +31,4 @@
bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); }
-#endif /* GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER) */
+#endif /* GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER) */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc
index 07a617c14d..30d35b0d75 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc
@@ -1,28 +1,28 @@
-//
-// Copyright 2019 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-// This is similar to the sockaddr resolver, except that it supports a
-// bunch of query args that are useful for dependency injection in tests.
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
-
-GPR_GLOBAL_CONFIG_DEFINE_STRING(
- grpc_dns_resolver, "",
- "Declares which DNS resolver to use. The default is ares if gRPC is built "
- "with c-ares support. Otherwise, the value of this environment variable is "
- "ignored.")
+//
+// Copyright 2019 gRPC authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// This is similar to the sockaddr resolver, except that it supports a
+// bunch of query args that are useful for dependency injection in tests.
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
+
+GPR_GLOBAL_CONFIG_DEFINE_STRING(
+ grpc_dns_resolver, "",
+ "Declares which DNS resolver to use. The default is ares if gRPC is built "
+ "with c-ares support. Otherwise, the value of this environment variable is "
+ "ignored.")
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h
index d0a3486ea3..ed1092b475 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h
@@ -1,29 +1,29 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_DNS_RESOLVER_SELECTION_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_DNS_RESOLVER_SELECTION_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/global_config.h"
-
-GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_dns_resolver);
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_DNS_RESOLVER_SELECTION_H \
- */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_DNS_RESOLVER_SELECTION_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_DNS_RESOLVER_SELECTION_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/global_config.h"
+
+GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_dns_resolver);
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_DNS_RESOLVER_SELECTION_H \
+ */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc
index a0e3566190..d6d17e2483 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc
@@ -28,7 +28,7 @@
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
-#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
+#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/backoff/backoff.h"
@@ -52,9 +52,9 @@ const char kDefaultPort[] = "https";
class NativeDnsResolver : public Resolver {
public:
- explicit NativeDnsResolver(ResolverArgs args);
+ explicit NativeDnsResolver(ResolverArgs args);
- void StartLocked() override;
+ void StartLocked() override;
void RequestReresolutionLocked() override;
@@ -68,9 +68,9 @@ class NativeDnsResolver : public Resolver {
void MaybeStartResolvingLocked();
void StartResolvingLocked();
- static void OnNextResolution(void* arg, grpc_error* error);
+ static void OnNextResolution(void* arg, grpc_error* error);
void OnNextResolutionLocked(grpc_error* error);
- static void OnResolved(void* arg, grpc_error* error);
+ static void OnResolved(void* arg, grpc_error* error);
void OnResolvedLocked(grpc_error* error);
/// name to resolve
@@ -79,8 +79,8 @@ class NativeDnsResolver : public Resolver {
grpc_channel_args* channel_args_ = nullptr;
/// pollset_set to drive the name resolution process
grpc_pollset_set* interested_parties_ = nullptr;
- /// are we shutting down?
- bool shutdown_ = false;
+ /// are we shutting down?
+ bool shutdown_ = false;
/// are we currently resolving?
bool resolving_ = false;
grpc_closure on_resolved_;
@@ -98,7 +98,7 @@ class NativeDnsResolver : public Resolver {
grpc_resolved_addresses* addresses_ = nullptr;
};
-NativeDnsResolver::NativeDnsResolver(ResolverArgs args)
+NativeDnsResolver::NativeDnsResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
backoff_(
BackOff::Options()
@@ -114,7 +114,7 @@ NativeDnsResolver::NativeDnsResolver(ResolverArgs args)
const grpc_arg* arg = grpc_channel_args_find(
args.args, GRPC_ARG_DNS_MIN_TIME_BETWEEN_RESOLUTIONS_MS);
min_time_between_resolutions_ =
- grpc_channel_arg_get_integer(arg, {1000 * 30, 0, INT_MAX});
+ grpc_channel_arg_get_integer(arg, {1000 * 30, 0, INT_MAX});
interested_parties_ = grpc_pollset_set_create();
if (args.pollset_set != nullptr) {
grpc_pollset_set_add_pollset_set(interested_parties_, args.pollset_set);
@@ -122,12 +122,12 @@ NativeDnsResolver::NativeDnsResolver(ResolverArgs args)
}
NativeDnsResolver::~NativeDnsResolver() {
- grpc_channel_args_destroy(channel_args_);
+ grpc_channel_args_destroy(channel_args_);
grpc_pollset_set_destroy(interested_parties_);
gpr_free(name_to_resolve_);
}
-void NativeDnsResolver::StartLocked() { MaybeStartResolvingLocked(); }
+void NativeDnsResolver::StartLocked() { MaybeStartResolvingLocked(); }
void NativeDnsResolver::RequestReresolutionLocked() {
if (!resolving_) {
@@ -143,19 +143,19 @@ void NativeDnsResolver::ResetBackoffLocked() {
}
void NativeDnsResolver::ShutdownLocked() {
- shutdown_ = true;
+ shutdown_ = true;
if (have_next_resolution_timer_) {
grpc_timer_cancel(&next_resolution_timer_);
}
}
-void NativeDnsResolver::OnNextResolution(void* arg, grpc_error* error) {
- NativeDnsResolver* r = static_cast<NativeDnsResolver*>(arg);
+void NativeDnsResolver::OnNextResolution(void* arg, grpc_error* error) {
+ NativeDnsResolver* r = static_cast<NativeDnsResolver*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
r->work_serializer()->Run([r, error]() { r->OnNextResolutionLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void NativeDnsResolver::OnNextResolutionLocked(grpc_error* error) {
have_next_resolution_timer_ = false;
if (error == GRPC_ERROR_NONE && !resolving_) {
@@ -165,13 +165,13 @@ void NativeDnsResolver::OnNextResolutionLocked(grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
-void NativeDnsResolver::OnResolved(void* arg, grpc_error* error) {
- NativeDnsResolver* r = static_cast<NativeDnsResolver*>(arg);
+void NativeDnsResolver::OnResolved(void* arg, grpc_error* error) {
+ NativeDnsResolver* r = static_cast<NativeDnsResolver*>(arg);
GRPC_ERROR_REF(error); // owned by lambda
r->work_serializer()->Run([r, error]() { r->OnResolvedLocked(error); },
DEBUG_LOCATION);
-}
-
+}
+
void NativeDnsResolver::OnResolvedLocked(grpc_error* error) {
GPR_ASSERT(resolving_);
resolving_ = false;
@@ -181,14 +181,14 @@ void NativeDnsResolver::OnResolvedLocked(grpc_error* error) {
}
Unref(DEBUG_LOCATION, "dns-resolving");
GRPC_ERROR_UNREF(error);
- return;
- }
+ return;
+ }
if (addresses_ != nullptr) {
- Result result;
+ Result result;
for (size_t i = 0; i < addresses_->naddrs; ++i) {
result.addresses.emplace_back(&addresses_->addrs[i].addr,
addresses_->addrs[i].len,
- nullptr /* args */);
+ nullptr /* args */);
}
grpc_resolved_addresses_destroy(addresses_);
result.args = grpc_channel_args_copy(channel_args_);
@@ -197,16 +197,16 @@ void NativeDnsResolver::OnResolvedLocked(grpc_error* error) {
// next request gets triggered.
backoff_.Reset();
} else {
- gpr_log(GPR_INFO, "dns resolution failed (will retry): %s",
- grpc_error_string(error));
- // Return transient error.
+ gpr_log(GPR_INFO, "dns resolution failed (will retry): %s",
+ grpc_error_string(error));
+ // Return transient error.
TString error_message =
y_absl::StrCat("DNS resolution failed for service: ", name_to_resolve_);
result_handler()->ReturnError(grpc_error_set_int(
GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(error_message.c_str(),
&error, 1),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- // Set up for retry.
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+ // Set up for retry.
grpc_millis next_try = backoff_.NextAttemptTime();
grpc_millis timeout = next_try - ExecCtx::Get()->Now();
GPR_ASSERT(!have_next_resolution_timer_);
@@ -248,12 +248,12 @@ void NativeDnsResolver::MaybeStartResolvingLocked() {
// TODO(roth): We currently deal with this ref manually. Once the
// new closure API is done, find a way to track this ref with the timer
// callback as part of the type system.
- Ref(DEBUG_LOCATION, "next_resolution_timer_cooldown").release();
- GRPC_CLOSURE_INIT(&on_next_resolution_,
- NativeDnsResolver::OnNextResolution, this,
- grpc_schedule_on_exec_ctx);
- grpc_timer_init(&next_resolution_timer_,
- ExecCtx::Get()->Now() + ms_until_next_resolution,
+ Ref(DEBUG_LOCATION, "next_resolution_timer_cooldown").release();
+ GRPC_CLOSURE_INIT(&on_next_resolution_,
+ NativeDnsResolver::OnNextResolution, this,
+ grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&next_resolution_timer_,
+ ExecCtx::Get()->Now() + ms_until_next_resolution,
&on_next_resolution_);
return;
}
@@ -266,12 +266,12 @@ void NativeDnsResolver::StartResolvingLocked() {
// TODO(roth): We currently deal with this ref manually. Once the
// new closure API is done, find a way to track this ref with the timer
// callback as part of the type system.
- Ref(DEBUG_LOCATION, "dns-resolving").release();
+ Ref(DEBUG_LOCATION, "dns-resolving").release();
GPR_ASSERT(!resolving_);
resolving_ = true;
addresses_ = nullptr;
- GRPC_CLOSURE_INIT(&on_resolved_, NativeDnsResolver::OnResolved, this,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&on_resolved_, NativeDnsResolver::OnResolved, this,
+ grpc_schedule_on_exec_ctx);
grpc_resolve_address(name_to_resolve_, kDefaultPort, interested_parties_,
&on_resolved_, &addresses_);
last_resolution_timestamp_ = grpc_core::ExecCtx::Get()->Now();
@@ -283,19 +283,19 @@ void NativeDnsResolver::StartResolvingLocked() {
class NativeDnsResolverFactory : public ResolverFactory {
public:
- bool IsValidUri(const grpc_uri* uri) const override {
- if (GPR_UNLIKELY(0 != strcmp(uri->authority, ""))) {
+ bool IsValidUri(const grpc_uri* uri) const override {
+ if (GPR_UNLIKELY(0 != strcmp(uri->authority, ""))) {
gpr_log(GPR_ERROR, "authority based dns uri's not supported");
- return false;
+ return false;
}
- return true;
- }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- if (!IsValidUri(args.uri)) return nullptr;
- return MakeOrphanable<NativeDnsResolver>(std::move(args));
+ return true;
}
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ if (!IsValidUri(args.uri)) return nullptr;
+ return MakeOrphanable<NativeDnsResolver>(std::move(args));
+ }
+
const char* scheme() const override { return "dns"; }
};
@@ -304,9 +304,9 @@ class NativeDnsResolverFactory : public ResolverFactory {
} // namespace grpc_core
void grpc_resolver_dns_native_init() {
- grpc_core::UniquePtr<char> resolver =
- GPR_GLOBAL_CONFIG_GET(grpc_dns_resolver);
- if (gpr_stricmp(resolver.get(), "native") == 0) {
+ grpc_core::UniquePtr<char> resolver =
+ GPR_GLOBAL_CONFIG_GET(grpc_dns_resolver);
+ if (gpr_stricmp(resolver.get(), "native") == 0) {
gpr_log(GPR_DEBUG, "Using native dns resolver");
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::NativeDnsResolverFactory>());
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc
index 792146ed04..5941c6ad7f 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc
@@ -49,9 +49,9 @@ namespace grpc_core {
// FakeResolverResponseGenerator.
class FakeResolver : public Resolver {
public:
- explicit FakeResolver(ResolverArgs args);
+ explicit FakeResolver(ResolverArgs args);
- void StartLocked() override;
+ void StartLocked() override;
void RequestReresolutionLocked() override;
@@ -63,67 +63,67 @@ class FakeResolver : public Resolver {
void ShutdownLocked() override;
- void MaybeSendResultLocked();
+ void MaybeSendResultLocked();
void ReturnReresolutionResult();
-
+
// passed-in parameters
grpc_channel_args* channel_args_ = nullptr;
- RefCountedPtr<FakeResolverResponseGenerator> response_generator_;
- // If has_next_result_ is true, next_result_ is the next resolution result
- // to be returned.
- bool has_next_result_ = false;
- Result next_result_;
- // Result to use for the pretended re-resolution in
+ RefCountedPtr<FakeResolverResponseGenerator> response_generator_;
+ // If has_next_result_ is true, next_result_ is the next resolution result
+ // to be returned.
+ bool has_next_result_ = false;
+ Result next_result_;
+ // Result to use for the pretended re-resolution in
// RequestReresolutionLocked().
- bool has_reresolution_result_ = false;
- Result reresolution_result_;
- // True after the call to StartLocked().
- bool started_ = false;
- // True after the call to ShutdownLocked().
- bool shutdown_ = false;
+ bool has_reresolution_result_ = false;
+ Result reresolution_result_;
+ // True after the call to StartLocked().
+ bool started_ = false;
+ // True after the call to ShutdownLocked().
+ bool shutdown_ = false;
// if true, return failure
bool return_failure_ = false;
- // pending re-resolution
- bool reresolution_closure_pending_ = false;
+ // pending re-resolution
+ bool reresolution_closure_pending_ = false;
};
-FakeResolver::FakeResolver(ResolverArgs args)
+FakeResolver::FakeResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
- response_generator_(
- FakeResolverResponseGenerator::GetFromArgs(args.args)) {
- // Channels sharing the same subchannels may have different resolver response
- // generators. If we don't remove this arg, subchannel pool will create new
- // subchannels for the same address instead of reusing existing ones because
- // of different values of this channel arg.
- const char* args_to_remove[] = {GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR};
- channel_args_ = grpc_channel_args_copy_and_remove(
- args.args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove));
- if (response_generator_ != nullptr) {
- response_generator_->SetFakeResolver(Ref());
- }
+ response_generator_(
+ FakeResolverResponseGenerator::GetFromArgs(args.args)) {
+ // Channels sharing the same subchannels may have different resolver response
+ // generators. If we don't remove this arg, subchannel pool will create new
+ // subchannels for the same address instead of reusing existing ones because
+ // of different values of this channel arg.
+ const char* args_to_remove[] = {GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR};
+ channel_args_ = grpc_channel_args_copy_and_remove(
+ args.args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove));
+ if (response_generator_ != nullptr) {
+ response_generator_->SetFakeResolver(Ref());
+ }
}
-FakeResolver::~FakeResolver() { grpc_channel_args_destroy(channel_args_); }
+FakeResolver::~FakeResolver() { grpc_channel_args_destroy(channel_args_); }
-void FakeResolver::StartLocked() {
- started_ = true;
- MaybeSendResultLocked();
+void FakeResolver::StartLocked() {
+ started_ = true;
+ MaybeSendResultLocked();
}
void FakeResolver::RequestReresolutionLocked() {
- if (has_reresolution_result_ || return_failure_) {
- next_result_ = reresolution_result_;
- has_next_result_ = true;
- // Return the result in a different closure, so that we don't call
- // back into the LB policy while it's still processing the previous
- // update.
- if (!reresolution_closure_pending_) {
- reresolution_closure_pending_ = true;
- Ref().release(); // ref held by closure
+ if (has_reresolution_result_ || return_failure_) {
+ next_result_ = reresolution_result_;
+ has_next_result_ = true;
+ // Return the result in a different closure, so that we don't call
+ // back into the LB policy while it's still processing the previous
+ // update.
+ if (!reresolution_closure_pending_) {
+ reresolution_closure_pending_ = true;
+ Ref().release(); // ref held by closure
work_serializer()->Run([this]() { ReturnReresolutionResult(); },
DEBUG_LOCATION);
- }
+ }
}
}
@@ -135,28 +135,28 @@ void FakeResolver::ShutdownLocked() {
}
}
-void FakeResolver::MaybeSendResultLocked() {
- if (!started_ || shutdown_) return;
- if (return_failure_) {
- // TODO(roth): Change resolver result generator to be able to inject
- // the error to be returned.
- result_handler()->ReturnError(grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver transient failure"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+void FakeResolver::MaybeSendResultLocked() {
+ if (!started_ || shutdown_) return;
+ if (return_failure_) {
+ // TODO(roth): Change resolver result generator to be able to inject
+ // the error to be returned.
+ result_handler()->ReturnError(grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver transient failure"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
return_failure_ = false;
- } else if (has_next_result_) {
- Result result;
- result.addresses = std::move(next_result_.addresses);
- result.service_config = std::move(next_result_.service_config);
- // TODO(roth): Use std::move() once grpc_error is converted to C++.
- result.service_config_error = next_result_.service_config_error;
- next_result_.service_config_error = GRPC_ERROR_NONE;
- // When both next_results_ and channel_args_ contain an arg with the same
- // name, only the one in next_results_ will be kept since next_results_ is
- // before channel_args_.
- result.args = grpc_channel_args_union(next_result_.args, channel_args_);
- result_handler()->ReturnResult(std::move(result));
- has_next_result_ = false;
+ } else if (has_next_result_) {
+ Result result;
+ result.addresses = std::move(next_result_.addresses);
+ result.service_config = std::move(next_result_.service_config);
+ // TODO(roth): Use std::move() once grpc_error is converted to C++.
+ result.service_config_error = next_result_.service_config_error;
+ next_result_.service_config_error = GRPC_ERROR_NONE;
+ // When both next_results_ and channel_args_ contain an arg with the same
+ // name, only the one in next_results_ will be kept since next_results_ is
+ // before channel_args_.
+ result.args = grpc_channel_args_union(next_result_.args, channel_args_);
+ result_handler()->ReturnResult(std::move(result));
+ has_next_result_ = false;
}
}
@@ -219,21 +219,21 @@ void FakeResolverResponseSetter::SetFailureLocked() {
// FakeResolverResponseGenerator
//
-FakeResolverResponseGenerator::FakeResolverResponseGenerator() {}
-
-FakeResolverResponseGenerator::~FakeResolverResponseGenerator() {}
-
-void FakeResolverResponseGenerator::SetResponse(Resolver::Result result) {
- RefCountedPtr<FakeResolver> resolver;
- {
- MutexLock lock(&mu_);
- if (resolver_ == nullptr) {
- has_result_ = true;
- result_ = std::move(result);
- return;
- }
- resolver = resolver_->Ref();
- }
+FakeResolverResponseGenerator::FakeResolverResponseGenerator() {}
+
+FakeResolverResponseGenerator::~FakeResolverResponseGenerator() {}
+
+void FakeResolverResponseGenerator::SetResponse(Resolver::Result result) {
+ RefCountedPtr<FakeResolver> resolver;
+ {
+ MutexLock lock(&mu_);
+ if (resolver_ == nullptr) {
+ has_result_ = true;
+ result_ = std::move(result);
+ return;
+ }
+ resolver = resolver_->Ref();
+ }
FakeResolverResponseSetter* arg =
new FakeResolverResponseSetter(resolver, std::move(result));
resolver->work_serializer()->Run([arg]() { arg->SetResponseLocked(); },
@@ -241,39 +241,39 @@ void FakeResolverResponseGenerator::SetResponse(Resolver::Result result) {
}
void FakeResolverResponseGenerator::SetReresolutionResponse(
- Resolver::Result result) {
- RefCountedPtr<FakeResolver> resolver;
- {
- MutexLock lock(&mu_);
- GPR_ASSERT(resolver_ != nullptr);
- resolver = resolver_->Ref();
- }
+ Resolver::Result result) {
+ RefCountedPtr<FakeResolver> resolver;
+ {
+ MutexLock lock(&mu_);
+ GPR_ASSERT(resolver_ != nullptr);
+ resolver = resolver_->Ref();
+ }
FakeResolverResponseSetter* arg = new FakeResolverResponseSetter(
resolver, std::move(result), true /* has_result */);
resolver->work_serializer()->Run(
[arg]() { arg->SetReresolutionResponseLocked(); }, DEBUG_LOCATION);
}
-void FakeResolverResponseGenerator::UnsetReresolutionResponse() {
- RefCountedPtr<FakeResolver> resolver;
- {
- MutexLock lock(&mu_);
- GPR_ASSERT(resolver_ != nullptr);
- resolver = resolver_->Ref();
- }
+void FakeResolverResponseGenerator::UnsetReresolutionResponse() {
+ RefCountedPtr<FakeResolver> resolver;
+ {
+ MutexLock lock(&mu_);
+ GPR_ASSERT(resolver_ != nullptr);
+ resolver = resolver_->Ref();
+ }
FakeResolverResponseSetter* arg =
new FakeResolverResponseSetter(resolver, Resolver::Result());
resolver->work_serializer()->Run(
[arg]() { arg->SetReresolutionResponseLocked(); }, DEBUG_LOCATION);
-}
-
+}
+
void FakeResolverResponseGenerator::SetFailure() {
- RefCountedPtr<FakeResolver> resolver;
- {
- MutexLock lock(&mu_);
- GPR_ASSERT(resolver_ != nullptr);
- resolver = resolver_->Ref();
- }
+ RefCountedPtr<FakeResolver> resolver;
+ {
+ MutexLock lock(&mu_);
+ GPR_ASSERT(resolver_ != nullptr);
+ resolver = resolver_->Ref();
+ }
FakeResolverResponseSetter* arg =
new FakeResolverResponseSetter(resolver, Resolver::Result());
resolver->work_serializer()->Run([arg]() { arg->SetFailureLocked(); },
@@ -281,12 +281,12 @@ void FakeResolverResponseGenerator::SetFailure() {
}
void FakeResolverResponseGenerator::SetFailureOnReresolution() {
- RefCountedPtr<FakeResolver> resolver;
- {
- MutexLock lock(&mu_);
- GPR_ASSERT(resolver_ != nullptr);
- resolver = resolver_->Ref();
- }
+ RefCountedPtr<FakeResolver> resolver;
+ {
+ MutexLock lock(&mu_);
+ GPR_ASSERT(resolver_ != nullptr);
+ resolver = resolver_->Ref();
+ }
FakeResolverResponseSetter* arg = new FakeResolverResponseSetter(
resolver, Resolver::Result(), false /* has_result */,
false /* immediate */);
@@ -294,20 +294,20 @@ void FakeResolverResponseGenerator::SetFailureOnReresolution() {
DEBUG_LOCATION);
}
-void FakeResolverResponseGenerator::SetFakeResolver(
- RefCountedPtr<FakeResolver> resolver) {
- MutexLock lock(&mu_);
- resolver_ = std::move(resolver);
- if (resolver_ == nullptr) return;
- if (has_result_) {
+void FakeResolverResponseGenerator::SetFakeResolver(
+ RefCountedPtr<FakeResolver> resolver) {
+ MutexLock lock(&mu_);
+ resolver_ = std::move(resolver);
+ if (resolver_ == nullptr) return;
+ if (has_result_) {
FakeResolverResponseSetter* arg =
new FakeResolverResponseSetter(resolver_, std::move(result_));
resolver_->work_serializer()->Run([arg]() { arg->SetResponseLocked(); },
DEBUG_LOCATION);
- has_result_ = false;
- }
-}
-
+ has_result_ = false;
+ }
+}
+
namespace {
static void* response_generator_arg_copy(void* p) {
@@ -345,13 +345,13 @@ grpc_arg FakeResolverResponseGenerator::MakeChannelArg(
return arg;
}
-RefCountedPtr<FakeResolverResponseGenerator>
-FakeResolverResponseGenerator::GetFromArgs(const grpc_channel_args* args) {
+RefCountedPtr<FakeResolverResponseGenerator>
+FakeResolverResponseGenerator::GetFromArgs(const grpc_channel_args* args) {
const grpc_arg* arg =
grpc_channel_args_find(args, GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR);
if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
- return static_cast<FakeResolverResponseGenerator*>(arg->value.pointer.p)
- ->Ref();
+ return static_cast<FakeResolverResponseGenerator*>(arg->value.pointer.p)
+ ->Ref();
}
//
@@ -362,10 +362,10 @@ namespace {
class FakeResolverFactory : public ResolverFactory {
public:
- bool IsValidUri(const grpc_uri* /*uri*/) const override { return true; }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- return MakeOrphanable<FakeResolver>(std::move(args));
+ bool IsValidUri(const grpc_uri* /*uri*/) const override { return true; }
+
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ return MakeOrphanable<FakeResolver>(std::move(args));
}
const char* scheme() const override { return "fake"; }
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h
index b9fd90c069..aa83e33f09 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h
@@ -19,7 +19,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/ext/filters/client_channel/resolver.h"
+#include "src/core/ext/filters/client_channel/resolver.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/iomgr/error.h"
@@ -42,26 +42,26 @@ class FakeResolver;
class FakeResolverResponseGenerator
: public RefCounted<FakeResolverResponseGenerator> {
public:
- FakeResolverResponseGenerator();
- ~FakeResolverResponseGenerator();
+ FakeResolverResponseGenerator();
+ ~FakeResolverResponseGenerator();
// Instructs the fake resolver associated with the response generator
- // instance to trigger a new resolution with the specified result. If the
- // resolver is not available yet, delays response setting until it is. This
- // can be called at most once before the resolver is available.
- void SetResponse(Resolver::Result result);
+ // instance to trigger a new resolution with the specified result. If the
+ // resolver is not available yet, delays response setting until it is. This
+ // can be called at most once before the resolver is available.
+ void SetResponse(Resolver::Result result);
// Sets the re-resolution response, which is returned by the fake resolver
// when re-resolution is requested (via \a RequestReresolutionLocked()).
// The new re-resolution response replaces any previous re-resolution
// response that may have been set by a previous call.
- void SetReresolutionResponse(Resolver::Result result);
+ void SetReresolutionResponse(Resolver::Result result);
- // Unsets the re-resolution response. After this, the fake resolver will
- // not return anything when \a RequestReresolutionLocked() is called.
- void UnsetReresolutionResponse();
-
- // Tells the resolver to return a transient failure.
+ // Unsets the re-resolution response. After this, the fake resolver will
+ // not return anything when \a RequestReresolutionLocked() is called.
+ void UnsetReresolutionResponse();
+
+ // Tells the resolver to return a transient failure.
void SetFailure();
// Same as SetFailure(), but instead of returning the error
@@ -72,19 +72,19 @@ class FakeResolverResponseGenerator
static grpc_arg MakeChannelArg(FakeResolverResponseGenerator* generator);
// Returns the response generator in \a args, or null if not found.
- static RefCountedPtr<FakeResolverResponseGenerator> GetFromArgs(
+ static RefCountedPtr<FakeResolverResponseGenerator> GetFromArgs(
const grpc_channel_args* args);
private:
friend class FakeResolver;
- // Set the corresponding FakeResolver to this generator.
- void SetFakeResolver(RefCountedPtr<FakeResolver> resolver);
-
- // Mutex protecting the members below.
- Mutex mu_;
- RefCountedPtr<FakeResolver> resolver_;
- Resolver::Result result_;
- bool has_result_ = false;
+ // Set the corresponding FakeResolver to this generator.
+ void SetFakeResolver(RefCountedPtr<FakeResolver> resolver);
+
+ // Mutex protecting the members below.
+ Mutex mu_;
+ RefCountedPtr<FakeResolver> resolver_;
+ Resolver::Result result_;
+ bool has_result_ = false;
};
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc
index b52bd8afba..c1599b1636 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc
@@ -43,20 +43,20 @@ namespace {
class SockaddrResolver : public Resolver {
public:
- SockaddrResolver(ServerAddressList addresses, ResolverArgs args);
- ~SockaddrResolver() override;
+ SockaddrResolver(ServerAddressList addresses, ResolverArgs args);
+ ~SockaddrResolver() override;
- void StartLocked() override;
+ void StartLocked() override;
- void ShutdownLocked() override {}
+ void ShutdownLocked() override {}
private:
- ServerAddressList addresses_;
- const grpc_channel_args* channel_args_ = nullptr;
+ ServerAddressList addresses_;
+ const grpc_channel_args* channel_args_ = nullptr;
};
-SockaddrResolver::SockaddrResolver(ServerAddressList addresses,
- ResolverArgs args)
+SockaddrResolver::SockaddrResolver(ServerAddressList addresses,
+ ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
addresses_(std::move(addresses)),
channel_args_(grpc_channel_args_copy(args.args)) {}
@@ -65,107 +65,107 @@ SockaddrResolver::~SockaddrResolver() {
grpc_channel_args_destroy(channel_args_);
}
-void SockaddrResolver::StartLocked() {
- Result result;
- result.addresses = std::move(addresses_);
- // TODO(roth): Use std::move() once channel args is converted to C++.
- result.args = channel_args_;
- channel_args_ = nullptr;
- result_handler()->ReturnResult(std::move(result));
+void SockaddrResolver::StartLocked() {
+ Result result;
+ result.addresses = std::move(addresses_);
+ // TODO(roth): Use std::move() once channel args is converted to C++.
+ result.args = channel_args_;
+ channel_args_ = nullptr;
+ result_handler()->ReturnResult(std::move(result));
}
//
// Factory
//
-void DoNothing(void* /*ignored*/) {}
+void DoNothing(void* /*ignored*/) {}
-bool ParseUri(const grpc_uri* uri,
- bool parse(const grpc_uri* uri, grpc_resolved_address* dst),
- ServerAddressList* addresses) {
- if (0 != strcmp(uri->authority, "")) {
+bool ParseUri(const grpc_uri* uri,
+ bool parse(const grpc_uri* uri, grpc_resolved_address* dst),
+ ServerAddressList* addresses) {
+ if (0 != strcmp(uri->authority, "")) {
gpr_log(GPR_ERROR, "authority-based URIs not supported by the %s scheme",
- uri->scheme);
- return false;
+ uri->scheme);
+ return false;
}
// Construct addresses.
grpc_slice path_slice =
- grpc_slice_new(uri->path, strlen(uri->path), DoNothing);
+ grpc_slice_new(uri->path, strlen(uri->path), DoNothing);
grpc_slice_buffer path_parts;
grpc_slice_buffer_init(&path_parts);
grpc_slice_split(path_slice, ",", &path_parts);
bool errors_found = false;
for (size_t i = 0; i < path_parts.count; i++) {
- grpc_uri ith_uri = *uri;
- grpc_core::UniquePtr<char> part_str(
- grpc_slice_to_c_string(path_parts.slices[i]));
+ grpc_uri ith_uri = *uri;
+ grpc_core::UniquePtr<char> part_str(
+ grpc_slice_to_c_string(path_parts.slices[i]));
ith_uri.path = part_str.get();
grpc_resolved_address addr;
if (!parse(&ith_uri, &addr)) {
- errors_found = true;
+ errors_found = true;
break;
}
- if (addresses != nullptr) {
- addresses->emplace_back(addr, nullptr /* args */);
- }
+ if (addresses != nullptr) {
+ addresses->emplace_back(addr, nullptr /* args */);
+ }
}
grpc_slice_buffer_destroy_internal(&path_parts);
grpc_slice_unref_internal(path_slice);
- return !errors_found;
-}
-
-OrphanablePtr<Resolver> CreateSockaddrResolver(
- ResolverArgs args,
- bool parse(const grpc_uri* uri, grpc_resolved_address* dst)) {
- ServerAddressList addresses;
- if (!ParseUri(args.uri, parse, &addresses)) return nullptr;
+ return !errors_found;
+}
+
+OrphanablePtr<Resolver> CreateSockaddrResolver(
+ ResolverArgs args,
+ bool parse(const grpc_uri* uri, grpc_resolved_address* dst)) {
+ ServerAddressList addresses;
+ if (!ParseUri(args.uri, parse, &addresses)) return nullptr;
// Instantiate resolver.
- return MakeOrphanable<SockaddrResolver>(std::move(addresses),
- std::move(args));
+ return MakeOrphanable<SockaddrResolver>(std::move(addresses),
+ std::move(args));
}
class IPv4ResolverFactory : public ResolverFactory {
public:
- bool IsValidUri(const grpc_uri* uri) const override {
- return ParseUri(uri, grpc_parse_ipv4, nullptr);
- }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- return CreateSockaddrResolver(std::move(args), grpc_parse_ipv4);
+ bool IsValidUri(const grpc_uri* uri) const override {
+ return ParseUri(uri, grpc_parse_ipv4, nullptr);
}
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ return CreateSockaddrResolver(std::move(args), grpc_parse_ipv4);
+ }
+
const char* scheme() const override { return "ipv4"; }
};
class IPv6ResolverFactory : public ResolverFactory {
public:
- bool IsValidUri(const grpc_uri* uri) const override {
- return ParseUri(uri, grpc_parse_ipv6, nullptr);
- }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- return CreateSockaddrResolver(std::move(args), grpc_parse_ipv6);
+ bool IsValidUri(const grpc_uri* uri) const override {
+ return ParseUri(uri, grpc_parse_ipv6, nullptr);
}
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ return CreateSockaddrResolver(std::move(args), grpc_parse_ipv6);
+ }
+
const char* scheme() const override { return "ipv6"; }
};
#ifdef GRPC_HAVE_UNIX_SOCKET
class UnixResolverFactory : public ResolverFactory {
public:
- bool IsValidUri(const grpc_uri* uri) const override {
- return ParseUri(uri, grpc_parse_unix, nullptr);
- }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- return CreateSockaddrResolver(std::move(args), grpc_parse_unix);
+ bool IsValidUri(const grpc_uri* uri) const override {
+ return ParseUri(uri, grpc_parse_unix, nullptr);
}
- grpc_core::UniquePtr<char> GetDefaultAuthority(
- grpc_uri* /*uri*/) const override {
- return grpc_core::UniquePtr<char>(gpr_strdup("localhost"));
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ return CreateSockaddrResolver(std::move(args), grpc_parse_unix);
}
+ grpc_core::UniquePtr<char> GetDefaultAuthority(
+ grpc_uri* /*uri*/) const override {
+ return grpc_core::UniquePtr<char>(gpr_strdup("localhost"));
+ }
+
const char* scheme() const override { return "unix"; }
};
#endif // GRPC_HAVE_UNIX_SOCKET
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc
index 03f98d0fa3..cadbe06c37 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc
@@ -1,78 +1,78 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
#include "y_absl/strings/match.h"
#include "y_absl/strings/str_join.h"
#include "y_absl/strings/str_split.h"
#include "re2/re2.h"
#include "src/core/ext/filters/client_channel/config_selector.h"
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
+#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/xds/xds_client.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/transport/timeout_encoding.h"
-
-namespace grpc_core {
-
+
+namespace grpc_core {
+
TraceFlag grpc_xds_resolver_trace(false, "xds_resolver");
const char* kXdsClusterAttribute = "xds_cluster_name";
-namespace {
-
-//
-// XdsResolver
-//
-
-class XdsResolver : public Resolver {
- public:
- explicit XdsResolver(ResolverArgs args)
+namespace {
+
+//
+// XdsResolver
+//
+
+class XdsResolver : public Resolver {
+ public:
+ explicit XdsResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer),
std::move(args.result_handler)),
- args_(grpc_channel_args_copy(args.args)),
- interested_parties_(args.pollset_set) {
- char* path = args.uri->path;
- if (path[0] == '/') ++path;
+ args_(grpc_channel_args_copy(args.args)),
+ interested_parties_(args.pollset_set) {
+ char* path = args.uri->path;
+ if (path[0] == '/') ++path;
server_name_ = path;
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] created for server name %s", this,
server_name_.c_str());
}
- }
-
+ }
+
~XdsResolver() override {
grpc_channel_args_destroy(args_);
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] destroyed", this);
}
}
-
- void StartLocked() override;
-
+
+ void StartLocked() override;
+
void ShutdownLocked() override;
-
- private:
+
+ private:
class Notifier {
- public:
+ public:
Notifier(RefCountedPtr<XdsResolver> resolver, XdsApi::LdsUpdate update);
Notifier(RefCountedPtr<XdsResolver> resolver, XdsApi::RdsUpdate update);
Notifier(RefCountedPtr<XdsResolver> resolver, grpc_error* error);
@@ -93,17 +93,17 @@ class XdsResolver : public Resolver {
class ListenerWatcher : public XdsClient::ListenerWatcherInterface {
public:
explicit ListenerWatcher(RefCountedPtr<XdsResolver> resolver)
- : resolver_(std::move(resolver)) {}
+ : resolver_(std::move(resolver)) {}
void OnListenerChanged(XdsApi::LdsUpdate listener) override {
new Notifier(resolver_, std::move(listener));
}
void OnError(grpc_error* error) override { new Notifier(resolver_, error); }
void OnResourceDoesNotExist() override { new Notifier(resolver_); }
-
- private:
- RefCountedPtr<XdsResolver> resolver_;
- };
-
+
+ private:
+ RefCountedPtr<XdsResolver> resolver_;
+ };
+
class RouteConfigWatcher : public XdsClient::RouteConfigWatcherInterface {
public:
explicit RouteConfigWatcher(RefCountedPtr<XdsResolver> resolver)
@@ -181,16 +181,16 @@ class XdsResolver : public Resolver {
void MaybeRemoveUnusedClusters();
TString server_name_;
- const grpc_channel_args* args_;
- grpc_pollset_set* interested_parties_;
+ const grpc_channel_args* args_;
+ grpc_pollset_set* interested_parties_;
RefCountedPtr<XdsClient> xds_client_;
XdsClient::ListenerWatcherInterface* listener_watcher_ = nullptr;
TString route_config_name_;
XdsClient::RouteConfigWatcherInterface* route_config_watcher_ = nullptr;
ClusterState::ClusterStateMap cluster_state_map_;
std::vector<XdsApi::Route> current_update_;
-};
-
+};
+
//
// XdsResolver::Notifier
//
@@ -297,8 +297,8 @@ XdsResolver::XdsConfigSelector::XdsConfigSelector(
}
}
}
-}
-
+}
+
XdsResolver::XdsConfigSelector::~XdsConfigSelector() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] destroying XdsConfigSelector %p",
@@ -306,8 +306,8 @@ XdsResolver::XdsConfigSelector::~XdsConfigSelector() {
}
clusters_.clear();
resolver_->MaybeRemoveUnusedClusters();
-}
-
+}
+
void XdsResolver::XdsConfigSelector::MaybeAddCluster(const TString& name) {
if (clusters_.find(name) == clusters_.end()) {
auto it = resolver_->cluster_state_map_.find(name);
@@ -511,17 +511,17 @@ ConfigSelector::CallConfig XdsResolver::XdsConfigSelector::GetCallConfig(
// XdsResolver
//
-void XdsResolver::StartLocked() {
- grpc_error* error = GRPC_ERROR_NONE;
+void XdsResolver::StartLocked() {
+ grpc_error* error = GRPC_ERROR_NONE;
xds_client_ = XdsClient::GetOrCreate(&error);
- if (error != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR,
- "Failed to create xds client -- channel will remain in "
- "TRANSIENT_FAILURE: %s",
- grpc_error_string(error));
- result_handler()->ReturnError(error);
+ if (error != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR,
+ "Failed to create xds client -- channel will remain in "
+ "TRANSIENT_FAILURE: %s",
+ grpc_error_string(error));
+ result_handler()->ReturnError(error);
return;
- }
+ }
grpc_pollset_set_add_pollset_set(xds_client_->interested_parties(),
interested_parties_);
channelz::ChannelNode* parent_channelz_node =
@@ -533,8 +533,8 @@ void XdsResolver::StartLocked() {
auto watcher = y_absl::make_unique<ListenerWatcher>(Ref());
listener_watcher_ = watcher.get();
xds_client_->WatchListenerData(server_name_, std::move(watcher));
-}
-
+}
+
void XdsResolver::ShutdownLocked() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_resolver_trace)) {
gpr_log(GPR_INFO, "[xds_resolver %p] shutting down", this);
@@ -697,35 +697,35 @@ void XdsResolver::MaybeRemoveUnusedClusters() {
}
}
-//
-// Factory
-//
-
-class XdsResolverFactory : public ResolverFactory {
- public:
- bool IsValidUri(const grpc_uri* uri) const override {
- if (GPR_UNLIKELY(0 != strcmp(uri->authority, ""))) {
- gpr_log(GPR_ERROR, "URI authority not supported");
- return false;
- }
- return true;
- }
-
- OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
- if (!IsValidUri(args.uri)) return nullptr;
- return MakeOrphanable<XdsResolver>(std::move(args));
- }
-
+//
+// Factory
+//
+
+class XdsResolverFactory : public ResolverFactory {
+ public:
+ bool IsValidUri(const grpc_uri* uri) const override {
+ if (GPR_UNLIKELY(0 != strcmp(uri->authority, ""))) {
+ gpr_log(GPR_ERROR, "URI authority not supported");
+ return false;
+ }
+ return true;
+ }
+
+ OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
+ if (!IsValidUri(args.uri)) return nullptr;
+ return MakeOrphanable<XdsResolver>(std::move(args));
+ }
+
const char* scheme() const override { return "xds"; }
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-void grpc_resolver_xds_init() {
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+void grpc_resolver_xds_init() {
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::XdsResolverFactory>());
-}
-
-void grpc_resolver_xds_shutdown() {}
+}
+
+void grpc_resolver_xds_shutdown() {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h
index d8dd801ae0..8b42c2b1d2 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h
@@ -40,30 +40,30 @@ struct ResolverArgs {
grpc_pollset_set* pollset_set = nullptr;
/// The work_serializer under which all resolver calls will be run.
std::shared_ptr<WorkSerializer> work_serializer;
- /// The result handler to be used by the resolver.
- std::unique_ptr<Resolver::ResultHandler> result_handler;
+ /// The result handler to be used by the resolver.
+ std::unique_ptr<Resolver::ResultHandler> result_handler;
};
class ResolverFactory {
public:
- /// Returns a bool indicating whether the input uri is valid to create a
- /// resolver.
- virtual bool IsValidUri(const grpc_uri* uri) const = 0;
-
+ /// Returns a bool indicating whether the input uri is valid to create a
+ /// resolver.
+ virtual bool IsValidUri(const grpc_uri* uri) const = 0;
+
/// Returns a new resolver instance.
- virtual OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const = 0;
+ virtual OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const = 0;
/// Returns a string representing the default authority to use for this
/// scheme.
- virtual grpc_core::UniquePtr<char> GetDefaultAuthority(grpc_uri* uri) const {
+ virtual grpc_core::UniquePtr<char> GetDefaultAuthority(grpc_uri* uri) const {
const char* path = uri->path;
if (path[0] == '/') ++path;
- return grpc_core::UniquePtr<char>(gpr_strdup(path));
+ return grpc_core::UniquePtr<char>(gpr_strdup(path));
}
/// Returns the URI scheme that this factory implements.
/// Caller does NOT take ownership of result.
- virtual const char* scheme() const = 0;
+ virtual const char* scheme() const = 0;
virtual ~ResolverFactory() {}
};
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.cc
index 4cea1ec382..eefe265d60 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.cc
@@ -43,7 +43,7 @@ class RegistryState {
default_prefix_.reset(gpr_strdup(default_resolver_prefix));
}
- void RegisterResolverFactory(std::unique_ptr<ResolverFactory> factory) {
+ void RegisterResolverFactory(std::unique_ptr<ResolverFactory> factory) {
for (size_t i = 0; i < factories_.size(); ++i) {
GPR_ASSERT(strcmp(factories_[i]->scheme(), factory->scheme()) != 0);
}
@@ -94,7 +94,7 @@ class RegistryState {
// hurting performance (which is unlikely, since these allocations
// only occur at gRPC initialization time).
y_absl::InlinedVector<std::unique_ptr<ResolverFactory>, 10> factories_;
- grpc_core::UniquePtr<char> default_prefix_;
+ grpc_core::UniquePtr<char> default_prefix_;
};
static RegistryState* g_state = nullptr;
@@ -106,11 +106,11 @@ static RegistryState* g_state = nullptr;
//
void ResolverRegistry::Builder::InitRegistry() {
- if (g_state == nullptr) g_state = new RegistryState();
+ if (g_state == nullptr) g_state = new RegistryState();
}
void ResolverRegistry::Builder::ShutdownRegistry() {
- delete g_state;
+ delete g_state;
g_state = nullptr;
}
@@ -121,7 +121,7 @@ void ResolverRegistry::Builder::SetDefaultPrefix(
}
void ResolverRegistry::Builder::RegisterResolverFactory(
- std::unique_ptr<ResolverFactory> factory) {
+ std::unique_ptr<ResolverFactory> factory) {
InitRegistry();
g_state->RegisterResolverFactory(std::move(factory));
}
@@ -135,21 +135,21 @@ ResolverFactory* ResolverRegistry::LookupResolverFactory(const char* scheme) {
return g_state->LookupResolverFactory(scheme);
}
-bool ResolverRegistry::IsValidTarget(const char* target) {
- grpc_uri* uri = nullptr;
+bool ResolverRegistry::IsValidTarget(const char* target) {
+ grpc_uri* uri = nullptr;
TString canonical_target;
- ResolverFactory* factory =
- g_state->FindResolverFactory(target, &uri, &canonical_target);
- bool result = factory == nullptr ? false : factory->IsValidUri(uri);
- grpc_uri_destroy(uri);
- return result;
-}
-
+ ResolverFactory* factory =
+ g_state->FindResolverFactory(target, &uri, &canonical_target);
+ bool result = factory == nullptr ? false : factory->IsValidUri(uri);
+ grpc_uri_destroy(uri);
+ return result;
+}
+
OrphanablePtr<Resolver> ResolverRegistry::CreateResolver(
const char* target, const grpc_channel_args* args,
grpc_pollset_set* pollset_set,
std::shared_ptr<WorkSerializer> work_serializer,
- std::unique_ptr<Resolver::ResultHandler> result_handler) {
+ std::unique_ptr<Resolver::ResultHandler> result_handler) {
GPR_ASSERT(g_state != nullptr);
grpc_uri* uri = nullptr;
TString canonical_target;
@@ -160,29 +160,29 @@ OrphanablePtr<Resolver> ResolverRegistry::CreateResolver(
resolver_args.args = args;
resolver_args.pollset_set = pollset_set;
resolver_args.work_serializer = std::move(work_serializer);
- resolver_args.result_handler = std::move(result_handler);
+ resolver_args.result_handler = std::move(result_handler);
OrphanablePtr<Resolver> resolver =
- factory == nullptr ? nullptr
- : factory->CreateResolver(std::move(resolver_args));
+ factory == nullptr ? nullptr
+ : factory->CreateResolver(std::move(resolver_args));
grpc_uri_destroy(uri);
return resolver;
}
-grpc_core::UniquePtr<char> ResolverRegistry::GetDefaultAuthority(
- const char* target) {
+grpc_core::UniquePtr<char> ResolverRegistry::GetDefaultAuthority(
+ const char* target) {
GPR_ASSERT(g_state != nullptr);
grpc_uri* uri = nullptr;
TString canonical_target;
ResolverFactory* factory =
g_state->FindResolverFactory(target, &uri, &canonical_target);
- grpc_core::UniquePtr<char> authority =
+ grpc_core::UniquePtr<char> authority =
factory == nullptr ? nullptr : factory->GetDefaultAuthority(uri);
grpc_uri_destroy(uri);
return authority;
}
-grpc_core::UniquePtr<char> ResolverRegistry::AddDefaultPrefixIfNeeded(
- const char* target) {
+grpc_core::UniquePtr<char> ResolverRegistry::AddDefaultPrefixIfNeeded(
+ const char* target) {
GPR_ASSERT(g_state != nullptr);
grpc_uri* uri = nullptr;
TString canonical_target;
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.h
index bf34216b2c..98dcff1516 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.h
@@ -46,13 +46,13 @@ class ResolverRegistry {
/// Registers a resolver factory. The factory will be used to create a
/// resolver for any URI whose scheme matches that of the factory.
/// Calls InitRegistry() if it has not already been called.
- static void RegisterResolverFactory(
- std::unique_ptr<ResolverFactory> factory);
+ static void RegisterResolverFactory(
+ std::unique_ptr<ResolverFactory> factory);
};
- /// Checks whether the user input \a target is valid to create a resolver.
- static bool IsValidTarget(const char* target);
-
+ /// Checks whether the user input \a target is valid to create a resolver.
+ static bool IsValidTarget(const char* target);
+
/// Creates a resolver given \a target.
/// First tries to parse \a target as a URI. If this succeeds, tries
/// to locate a registered resolver factory based on the URI scheme.
@@ -66,18 +66,18 @@ class ResolverRegistry {
/// name resolution process. \a work_serializer is the work_serializer under
/// which all resolver calls will be run. \a result_handler is used to return
/// results from the resolver.
- static OrphanablePtr<Resolver> CreateResolver(
- const char* target, const grpc_channel_args* args,
+ static OrphanablePtr<Resolver> CreateResolver(
+ const char* target, const grpc_channel_args* args,
grpc_pollset_set* pollset_set,
std::shared_ptr<WorkSerializer> work_serializer,
- std::unique_ptr<Resolver::ResultHandler> result_handler);
+ std::unique_ptr<Resolver::ResultHandler> result_handler);
/// Returns the default authority to pass from a client for \a target.
- static grpc_core::UniquePtr<char> GetDefaultAuthority(const char* target);
+ static grpc_core::UniquePtr<char> GetDefaultAuthority(const char* target);
/// Returns \a target with the default prefix prepended, if needed.
- static grpc_core::UniquePtr<char> AddDefaultPrefixIfNeeded(
- const char* target);
+ static grpc_core::UniquePtr<char> AddDefaultPrefixIfNeeded(
+ const char* target);
/// Returns the resolver factory for \a scheme.
/// Caller does NOT own the return value.
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc
index e800b1e8f3..6c8cc869fe 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc
@@ -34,7 +34,7 @@
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
#include "src/core/ext/filters/client_channel/server_address.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/gpr/string.h"
#include "src/core/lib/gprpp/memory.h"
@@ -47,15 +47,15 @@
namespace grpc_core {
namespace internal {
-namespace {
-size_t g_client_channel_service_config_parser_index;
+namespace {
+size_t g_client_channel_service_config_parser_index;
}
-size_t ClientChannelServiceConfigParser::ParserIndex() {
- return g_client_channel_service_config_parser_index;
+size_t ClientChannelServiceConfigParser::ParserIndex() {
+ return g_client_channel_service_config_parser_index;
}
-void ClientChannelServiceConfigParser::Register() {
+void ClientChannelServiceConfigParser::Register() {
g_client_channel_service_config_parser_index =
ServiceConfigParser::RegisterParser(
y_absl::make_unique<ClientChannelServiceConfigParser>());
@@ -63,16 +63,16 @@ void ClientChannelServiceConfigParser::Register() {
namespace {
-std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy(
+std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy(
const Json& json, grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
- auto retry_policy =
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ auto retry_policy =
y_absl::make_unique<ClientChannelMethodParsedConfig::RetryPolicy>();
if (json.type() != Json::Type::OBJECT) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:retryPolicy error:should be of type object");
- return nullptr;
- }
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:retryPolicy error:should be of type object");
+ return nullptr;
+ }
std::vector<grpc_error*> error_list;
// Parse maxAttempts.
auto it = json.object_value().find("maxAttempts");
@@ -83,9 +83,9 @@ std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy(
} else {
retry_policy->max_attempts =
gpr_parse_nonnegative_int(it->second.string_value().c_str());
- if (retry_policy->max_attempts <= 1) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:maxAttempts error:should be at least 2"));
+ if (retry_policy->max_attempts <= 1) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:maxAttempts error:should be at least 2"));
} else if (retry_policy->max_attempts > MAX_MAX_RETRY_ATTEMPTS) {
gpr_log(GPR_ERROR,
"service config: clamped retryPolicy.maxAttempts at %d",
@@ -125,12 +125,12 @@ std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy(
} else {
if (sscanf(it->second.string_value().c_str(), "%f",
&retry_policy->backoff_multiplier) != 1) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:backoffMultiplier error:failed to parse"));
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:backoffMultiplier error:failed to parse"));
} else if (retry_policy->backoff_multiplier <= 0) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:backoffMultiplier error:should be greater than 0"));
- }
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:backoffMultiplier error:should be greater than 0"));
+ }
}
}
// Parse retryableStatusCodes.
@@ -142,41 +142,41 @@ std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy(
} else {
for (const Json& element : it->second.array_value()) {
if (element.type() != Json::Type::STRING) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:retryableStatusCodes error:status codes should be of type "
- "string"));
- continue;
- }
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:retryableStatusCodes error:status codes should be of type "
+ "string"));
+ continue;
+ }
grpc_status_code status;
if (!grpc_status_code_from_string(element.string_value().c_str(),
&status)) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:retryableStatusCodes error:failed to parse status code"));
- continue;
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:retryableStatusCodes error:failed to parse status code"));
+ continue;
}
retry_policy->retryable_status_codes.Add(status);
}
- if (retry_policy->retryable_status_codes.Empty()) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:retryableStatusCodes error:should be non-empty"));
- };
+ if (retry_policy->retryable_status_codes.Empty()) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:retryableStatusCodes error:should be non-empty"));
+ };
}
}
// Make sure required fields are set.
- if (error_list.empty()) {
- if (retry_policy->max_attempts == 0 || retry_policy->initial_backoff == 0 ||
- retry_policy->max_backoff == 0 ||
- retry_policy->backoff_multiplier == 0 ||
- retry_policy->retryable_status_codes.Empty()) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:retryPolicy error:Missing required field(s)");
- return nullptr;
- }
- }
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("retryPolicy", &error_list);
- return *error == GRPC_ERROR_NONE ? std::move(retry_policy) : nullptr;
-}
-
+ if (error_list.empty()) {
+ if (retry_policy->max_attempts == 0 || retry_policy->initial_backoff == 0 ||
+ retry_policy->max_backoff == 0 ||
+ retry_policy->backoff_multiplier == 0 ||
+ retry_policy->retryable_status_codes.Empty()) {
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:retryPolicy error:Missing required field(s)");
+ return nullptr;
+ }
+ }
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("retryPolicy", &error_list);
+ return *error == GRPC_ERROR_NONE ? std::move(retry_policy) : nullptr;
+}
+
grpc_error* ParseRetryThrottling(
const Json& json,
ClientChannelGlobalParsedConfig::RetryThrottling* retry_throttling) {
@@ -256,11 +256,11 @@ grpc_error* ParseRetryThrottling(
}
const char* ParseHealthCheckConfig(const Json& field, grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
- const char* service_name = nullptr;
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ const char* service_name = nullptr;
if (field.type() != Json::Type::OBJECT) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:healthCheckConfig error:should be of type object");
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:healthCheckConfig error:should be of type object");
return nullptr;
}
std::vector<grpc_error*> error_list;
@@ -271,14 +271,14 @@ const char* ParseHealthCheckConfig(const Json& field, grpc_error** error) {
"field:serviceName error:should be of type string"));
} else {
service_name = it->second.string_value().c_str();
- }
- }
- if (!error_list.empty()) {
- return nullptr;
- }
- *error =
- GRPC_ERROR_CREATE_FROM_VECTOR("field:healthCheckConfig", &error_list);
- return service_name;
+ }
+ }
+ if (!error_list.empty()) {
+ return nullptr;
+ }
+ *error =
+ GRPC_ERROR_CREATE_FROM_VECTOR("field:healthCheckConfig", &error_list);
+ return service_name;
}
} // namespace
@@ -286,13 +286,13 @@ const char* ParseHealthCheckConfig(const Json& field, grpc_error** error) {
std::unique_ptr<ServiceConfigParser::ParsedConfig>
ClientChannelServiceConfigParser::ParseGlobalParams(
const grpc_channel_args* /*args*/, const Json& json, grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
std::vector<grpc_error*> error_list;
- RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config;
+ RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config;
TString lb_policy_name;
y_absl::optional<ClientChannelGlobalParsedConfig::RetryThrottling>
retry_throttling;
- const char* health_check_service_name = nullptr;
+ const char* health_check_service_name = nullptr;
// Parse LB config.
auto it = json.object_value().find("loadBalancingConfig");
if (it != json.object_value().end()) {
@@ -304,7 +304,7 @@ ClientChannelServiceConfigParser::ParseGlobalParams(
lb_errors.push_back(parse_error);
error_list.push_back(GRPC_ERROR_CREATE_FROM_VECTOR(
"field:loadBalancingConfig", &lb_errors));
- }
+ }
}
// Parse deprecated LB policy.
it = json.object_value().find("loadBalancingPolicy");
@@ -316,20 +316,20 @@ ClientChannelServiceConfigParser::ParseGlobalParams(
lb_policy_name = it->second.string_value();
for (size_t i = 0; i < lb_policy_name.size(); ++i) {
lb_policy_name[i] = tolower(lb_policy_name[i]);
- }
- bool requires_config = false;
- if (!LoadBalancingPolicyRegistry::LoadBalancingPolicyExists(
+ }
+ bool requires_config = false;
+ if (!LoadBalancingPolicyRegistry::LoadBalancingPolicyExists(
lb_policy_name.c_str(), &requires_config)) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:loadBalancingPolicy error:Unknown lb policy"));
- } else if (requires_config) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:loadBalancingPolicy error:Unknown lb policy"));
+ } else if (requires_config) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("field:loadBalancingPolicy error:", lb_policy_name,
" requires a config. Please use loadBalancingConfig "
"instead.")
.c_str()));
- }
- }
+ }
+ }
}
// Parse retry throttling.
it = json.object_value().find("retryThrottling");
@@ -340,7 +340,7 @@ ClientChannelServiceConfigParser::ParseGlobalParams(
error_list.push_back(parsing_error);
} else {
retry_throttling.emplace(data);
- }
+ }
}
// Parse health check config.
it = json.object_value().find("healthCheckConfig");
@@ -350,26 +350,26 @@ ClientChannelServiceConfigParser::ParseGlobalParams(
ParseHealthCheckConfig(it->second, &parsing_error);
if (parsing_error != GRPC_ERROR_NONE) {
error_list.push_back(parsing_error);
- }
- }
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("Client channel global parser",
- &error_list);
- if (*error == GRPC_ERROR_NONE) {
+ }
+ }
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("Client channel global parser",
+ &error_list);
+ if (*error == GRPC_ERROR_NONE) {
return y_absl::make_unique<ClientChannelGlobalParsedConfig>(
- std::move(parsed_lb_config), std::move(lb_policy_name),
- retry_throttling, health_check_service_name);
- }
- return nullptr;
-}
-
+ std::move(parsed_lb_config), std::move(lb_policy_name),
+ retry_throttling, health_check_service_name);
+ }
+ return nullptr;
+}
+
std::unique_ptr<ServiceConfigParser::ParsedConfig>
ClientChannelServiceConfigParser::ParsePerMethodParams(
const grpc_channel_args* /*args*/, const Json& json, grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
std::vector<grpc_error*> error_list;
y_absl::optional<bool> wait_for_ready;
- grpc_millis timeout = 0;
- std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> retry_policy;
+ grpc_millis timeout = 0;
+ std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> retry_policy;
// Parse waitForReady.
auto it = json.object_value().find("waitForReady");
if (it != json.object_value().end()) {
@@ -399,12 +399,12 @@ ClientChannelServiceConfigParser::ParsePerMethodParams(
error_list.push_back(error);
}
}
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("Client channel parser", &error_list);
- if (*error == GRPC_ERROR_NONE) {
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("Client channel parser", &error_list);
+ if (*error == GRPC_ERROR_NONE) {
return y_absl::make_unique<ClientChannelMethodParsedConfig>(
timeout, wait_for_ready, std::move(retry_policy));
- }
- return nullptr;
+ }
+ return nullptr;
}
} // namespace internal
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h
index 6149ebe32b..5aeb18fe8e 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h
@@ -23,11 +23,11 @@
#include "y_absl/types/optional.h"
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
-#include "src/core/ext/filters/client_channel/resolver.h"
+#include "src/core/ext/filters/client_channel/lb_policy.h"
+#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
+#include "src/core/ext/filters/client_channel/resolver.h"
#include "src/core/ext/filters/client_channel/retry_throttle.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/lib/channel/status_util.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
@@ -39,43 +39,43 @@ namespace internal {
class ClientChannelGlobalParsedConfig
: public ServiceConfigParser::ParsedConfig {
- public:
- struct RetryThrottling {
- intptr_t max_milli_tokens = 0;
- intptr_t milli_token_ratio = 0;
- };
-
- ClientChannelGlobalParsedConfig(
- RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config,
+ public:
+ struct RetryThrottling {
+ intptr_t max_milli_tokens = 0;
+ intptr_t milli_token_ratio = 0;
+ };
+
+ ClientChannelGlobalParsedConfig(
+ RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config,
TString parsed_deprecated_lb_policy,
const y_absl::optional<RetryThrottling>& retry_throttling,
- const char* health_check_service_name)
- : parsed_lb_config_(std::move(parsed_lb_config)),
- parsed_deprecated_lb_policy_(std::move(parsed_deprecated_lb_policy)),
- retry_throttling_(retry_throttling),
- health_check_service_name_(health_check_service_name) {}
+ const char* health_check_service_name)
+ : parsed_lb_config_(std::move(parsed_lb_config)),
+ parsed_deprecated_lb_policy_(std::move(parsed_deprecated_lb_policy)),
+ retry_throttling_(retry_throttling),
+ health_check_service_name_(health_check_service_name) {}
y_absl::optional<RetryThrottling> retry_throttling() const {
- return retry_throttling_;
- }
+ return retry_throttling_;
+ }
- RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config() const {
- return parsed_lb_config_;
+ RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config() const {
+ return parsed_lb_config_;
}
-
+
const TString& parsed_deprecated_lb_policy() const {
return parsed_deprecated_lb_policy_;
}
-
- const char* health_check_service_name() const {
- return health_check_service_name_;
+
+ const char* health_check_service_name() const {
+ return health_check_service_name_;
}
private:
- RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config_;
+ RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config_;
TString parsed_deprecated_lb_policy_;
y_absl::optional<RetryThrottling> retry_throttling_;
- const char* health_check_service_name_;
+ const char* health_check_service_name_;
};
class ClientChannelMethodParsedConfig
@@ -89,27 +89,27 @@ class ClientChannelMethodParsedConfig
StatusCodeSet retryable_status_codes;
};
- ClientChannelMethodParsedConfig(grpc_millis timeout,
+ ClientChannelMethodParsedConfig(grpc_millis timeout,
const y_absl::optional<bool>& wait_for_ready,
- std::unique_ptr<RetryPolicy> retry_policy)
- : timeout_(timeout),
- wait_for_ready_(wait_for_ready),
- retry_policy_(std::move(retry_policy)) {}
+ std::unique_ptr<RetryPolicy> retry_policy)
+ : timeout_(timeout),
+ wait_for_ready_(wait_for_ready),
+ retry_policy_(std::move(retry_policy)) {}
grpc_millis timeout() const { return timeout_; }
-
+
y_absl::optional<bool> wait_for_ready() const { return wait_for_ready_; }
-
+
const RetryPolicy* retry_policy() const { return retry_policy_.get(); }
private:
- grpc_millis timeout_ = 0;
+ grpc_millis timeout_ = 0;
y_absl::optional<bool> wait_for_ready_;
- std::unique_ptr<RetryPolicy> retry_policy_;
-};
+ std::unique_ptr<RetryPolicy> retry_policy_;
+};
class ClientChannelServiceConfigParser : public ServiceConfigParser::Parser {
- public:
+ public:
std::unique_ptr<ServiceConfigParser::ParsedConfig> ParseGlobalParams(
const grpc_channel_args* /*args*/, const Json& json,
grpc_error** error) override;
@@ -118,8 +118,8 @@ class ClientChannelServiceConfigParser : public ServiceConfigParser::Parser {
const grpc_channel_args* /*args*/, const Json& json,
grpc_error** error) override;
- static size_t ParserIndex();
- static void Register();
+ static size_t ParserIndex();
+ static void Register();
};
} // namespace internal
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.cc
index af27e2eeae..6640ad7741 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.cc
@@ -1,238 +1,238 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/resolving_lb_policy.h"
-
-#include <inttypes.h>
-#include <limits.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/resolving_lb_policy.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/ext/filters/client_channel/backup_poller.h"
-#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/ext/filters/client_channel/backup_poller.h"
+#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
#include "src/core/ext/filters/client_channel/lb_policy/child_policy_handler.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
-#include "src/core/ext/filters/client_channel/retry_throttle.h"
-#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
-#include "src/core/ext/filters/client_channel/subchannel.h"
-#include "src/core/ext/filters/deadline/deadline_filter.h"
-#include "src/core/lib/backoff/backoff.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/connected_channel.h"
-#include "src/core/lib/channel/status_util.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/gprpp/sync.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/iomgr/polling_entity.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/transport/connectivity_state.h"
-#include "src/core/lib/transport/error_utils.h"
-#include "src/core/lib/transport/metadata.h"
-#include "src/core/lib/transport/metadata_batch.h"
-#include "src/core/lib/transport/static_metadata.h"
-#include "src/core/lib/transport/status_metadata.h"
-
-namespace grpc_core {
-
-//
-// ResolvingLoadBalancingPolicy::ResolverResultHandler
-//
-
-class ResolvingLoadBalancingPolicy::ResolverResultHandler
- : public Resolver::ResultHandler {
- public:
- explicit ResolverResultHandler(
- RefCountedPtr<ResolvingLoadBalancingPolicy> parent)
- : parent_(std::move(parent)) {}
-
- ~ResolverResultHandler() {
- if (GRPC_TRACE_FLAG_ENABLED(*(parent_->tracer_))) {
- gpr_log(GPR_INFO, "resolving_lb=%p: resolver shutdown complete",
- parent_.get());
- }
- }
-
- void ReturnResult(Resolver::Result result) override {
- parent_->OnResolverResultChangedLocked(std::move(result));
- }
-
- void ReturnError(grpc_error* error) override {
- parent_->OnResolverError(error);
- }
-
- private:
- RefCountedPtr<ResolvingLoadBalancingPolicy> parent_;
-};
-
-//
-// ResolvingLoadBalancingPolicy::ResolvingControlHelper
-//
-
-class ResolvingLoadBalancingPolicy::ResolvingControlHelper
- : public LoadBalancingPolicy::ChannelControlHelper {
- public:
- explicit ResolvingControlHelper(
- RefCountedPtr<ResolvingLoadBalancingPolicy> parent)
- : parent_(std::move(parent)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
+#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
+#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
+#include "src/core/ext/filters/client_channel/resolver_registry.h"
+#include "src/core/ext/filters/client_channel/retry_throttle.h"
+#include "src/core/ext/filters/client_channel/server_address.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/subchannel.h"
+#include "src/core/ext/filters/deadline/deadline_filter.h"
+#include "src/core/lib/backoff/backoff.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/connected_channel.h"
+#include "src/core/lib/channel/status_util.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/polling_entity.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/error_utils.h"
+#include "src/core/lib/transport/metadata.h"
+#include "src/core/lib/transport/metadata_batch.h"
+#include "src/core/lib/transport/static_metadata.h"
+#include "src/core/lib/transport/status_metadata.h"
+
+namespace grpc_core {
+
+//
+// ResolvingLoadBalancingPolicy::ResolverResultHandler
+//
+
+class ResolvingLoadBalancingPolicy::ResolverResultHandler
+ : public Resolver::ResultHandler {
+ public:
+ explicit ResolverResultHandler(
+ RefCountedPtr<ResolvingLoadBalancingPolicy> parent)
+ : parent_(std::move(parent)) {}
+
+ ~ResolverResultHandler() {
+ if (GRPC_TRACE_FLAG_ENABLED(*(parent_->tracer_))) {
+ gpr_log(GPR_INFO, "resolving_lb=%p: resolver shutdown complete",
+ parent_.get());
+ }
+ }
+
+ void ReturnResult(Resolver::Result result) override {
+ parent_->OnResolverResultChangedLocked(std::move(result));
+ }
+
+ void ReturnError(grpc_error* error) override {
+ parent_->OnResolverError(error);
+ }
+
+ private:
+ RefCountedPtr<ResolvingLoadBalancingPolicy> parent_;
+};
+
+//
+// ResolvingLoadBalancingPolicy::ResolvingControlHelper
+//
+
+class ResolvingLoadBalancingPolicy::ResolvingControlHelper
+ : public LoadBalancingPolicy::ChannelControlHelper {
+ public:
+ explicit ResolvingControlHelper(
+ RefCountedPtr<ResolvingLoadBalancingPolicy> parent)
+ : parent_(std::move(parent)) {}
+
+ RefCountedPtr<SubchannelInterface> CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) override {
- if (parent_->resolver_ == nullptr) return nullptr; // Shutting down.
+ if (parent_->resolver_ == nullptr) return nullptr; // Shutting down.
return parent_->channel_control_helper()->CreateSubchannel(
std::move(address), args);
- }
-
+ }
+
void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override {
- if (parent_->resolver_ == nullptr) return; // Shutting down.
+ std::unique_ptr<SubchannelPicker> picker) override {
+ if (parent_->resolver_ == nullptr) return; // Shutting down.
parent_->channel_control_helper()->UpdateState(state, status,
std::move(picker));
- }
-
- void RequestReresolution() override {
+ }
+
+ void RequestReresolution() override {
if (parent_->resolver_ == nullptr) return; // Shutting down.
- if (GRPC_TRACE_FLAG_ENABLED(*(parent_->tracer_))) {
- gpr_log(GPR_INFO, "resolving_lb=%p: started name re-resolving",
- parent_.get());
- }
+ if (GRPC_TRACE_FLAG_ENABLED(*(parent_->tracer_))) {
+ gpr_log(GPR_INFO, "resolving_lb=%p: started name re-resolving",
+ parent_.get());
+ }
parent_->resolver_->RequestReresolutionLocked();
- }
-
+ }
+
void AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) override {
if (parent_->resolver_ == nullptr) return; // Shutting down.
parent_->channel_control_helper()->AddTraceEvent(severity, message);
}
-
- private:
- RefCountedPtr<ResolvingLoadBalancingPolicy> parent_;
-};
-
-//
-// ResolvingLoadBalancingPolicy
-//
-
-ResolvingLoadBalancingPolicy::ResolvingLoadBalancingPolicy(
- Args args, TraceFlag* tracer, grpc_core::UniquePtr<char> target_uri,
+
+ private:
+ RefCountedPtr<ResolvingLoadBalancingPolicy> parent_;
+};
+
+//
+// ResolvingLoadBalancingPolicy
+//
+
+ResolvingLoadBalancingPolicy::ResolvingLoadBalancingPolicy(
+ Args args, TraceFlag* tracer, grpc_core::UniquePtr<char> target_uri,
ChannelConfigHelper* helper)
- : LoadBalancingPolicy(std::move(args)),
- tracer_(tracer),
- target_uri_(std::move(target_uri)),
+ : LoadBalancingPolicy(std::move(args)),
+ tracer_(tracer),
+ target_uri_(std::move(target_uri)),
helper_(helper) {
GPR_ASSERT(helper_ != nullptr);
- resolver_ = ResolverRegistry::CreateResolver(
+ resolver_ = ResolverRegistry::CreateResolver(
target_uri_.get(), args.args, interested_parties(), work_serializer(),
y_absl::make_unique<ResolverResultHandler>(Ref()));
- // Since the validity of args has been checked when create the channel,
- // CreateResolver() must return a non-null result.
- GPR_ASSERT(resolver_ != nullptr);
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO, "resolving_lb=%p: starting name resolution", this);
- }
+ // Since the validity of args has been checked when create the channel,
+ // CreateResolver() must return a non-null result.
+ GPR_ASSERT(resolver_ != nullptr);
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ gpr_log(GPR_INFO, "resolving_lb=%p: starting name resolution", this);
+ }
channel_control_helper()->UpdateState(GRPC_CHANNEL_CONNECTING, y_absl::Status(),
y_absl::make_unique<QueuePicker>(Ref()));
- resolver_->StartLocked();
-}
-
-ResolvingLoadBalancingPolicy::~ResolvingLoadBalancingPolicy() {
- GPR_ASSERT(resolver_ == nullptr);
- GPR_ASSERT(lb_policy_ == nullptr);
-}
-
-void ResolvingLoadBalancingPolicy::ShutdownLocked() {
- if (resolver_ != nullptr) {
+ resolver_->StartLocked();
+}
+
+ResolvingLoadBalancingPolicy::~ResolvingLoadBalancingPolicy() {
+ GPR_ASSERT(resolver_ == nullptr);
+ GPR_ASSERT(lb_policy_ == nullptr);
+}
+
+void ResolvingLoadBalancingPolicy::ShutdownLocked() {
+ if (resolver_ != nullptr) {
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO, "resolving_lb=%p: shutting down resolver=%p", this,
resolver_.get());
}
- resolver_.reset();
- if (lb_policy_ != nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO, "resolving_lb=%p: shutting down lb_policy=%p", this,
- lb_policy_.get());
- }
- grpc_pollset_set_del_pollset_set(lb_policy_->interested_parties(),
- interested_parties());
- lb_policy_.reset();
- }
- }
-}
-
-void ResolvingLoadBalancingPolicy::ExitIdleLocked() {
+ resolver_.reset();
+ if (lb_policy_ != nullptr) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ gpr_log(GPR_INFO, "resolving_lb=%p: shutting down lb_policy=%p", this,
+ lb_policy_.get());
+ }
+ grpc_pollset_set_del_pollset_set(lb_policy_->interested_parties(),
+ interested_parties());
+ lb_policy_.reset();
+ }
+ }
+}
+
+void ResolvingLoadBalancingPolicy::ExitIdleLocked() {
if (lb_policy_ != nullptr) lb_policy_->ExitIdleLocked();
-}
-
-void ResolvingLoadBalancingPolicy::ResetBackoffLocked() {
- if (resolver_ != nullptr) {
- resolver_->ResetBackoffLocked();
- resolver_->RequestReresolutionLocked();
- }
- if (lb_policy_ != nullptr) lb_policy_->ResetBackoffLocked();
-}
-
-void ResolvingLoadBalancingPolicy::OnResolverError(grpc_error* error) {
- if (resolver_ == nullptr) {
- GRPC_ERROR_UNREF(error);
- return;
- }
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO, "resolving_lb=%p: resolver transient failure: %s", this,
- grpc_error_string(error));
- }
- // If we already have an LB policy from a previous resolution
- // result, then we continue to let it set the connectivity state.
- // Otherwise, we go into TRANSIENT_FAILURE.
- if (lb_policy_ == nullptr) {
- grpc_error* state_error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Resolver transient failure", &error, 1);
+}
+
+void ResolvingLoadBalancingPolicy::ResetBackoffLocked() {
+ if (resolver_ != nullptr) {
+ resolver_->ResetBackoffLocked();
+ resolver_->RequestReresolutionLocked();
+ }
+ if (lb_policy_ != nullptr) lb_policy_->ResetBackoffLocked();
+}
+
+void ResolvingLoadBalancingPolicy::OnResolverError(grpc_error* error) {
+ if (resolver_ == nullptr) {
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ gpr_log(GPR_INFO, "resolving_lb=%p: resolver transient failure: %s", this,
+ grpc_error_string(error));
+ }
+ // If we already have an LB policy from a previous resolution
+ // result, then we continue to let it set the connectivity state.
+ // Otherwise, we go into TRANSIENT_FAILURE.
+ if (lb_policy_ == nullptr) {
+ grpc_error* state_error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Resolver transient failure", &error, 1);
helper_->ResolverTransientFailure(GRPC_ERROR_REF(state_error));
- channel_control_helper()->UpdateState(
+ channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(state_error),
y_absl::make_unique<TransientFailurePicker>(state_error));
- }
- GRPC_ERROR_UNREF(error);
-}
-
-void ResolvingLoadBalancingPolicy::CreateOrUpdateLbPolicyLocked(
- RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
+ }
+ GRPC_ERROR_UNREF(error);
+}
+
+void ResolvingLoadBalancingPolicy::CreateOrUpdateLbPolicyLocked(
+ RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
Resolver::Result result) {
// Construct update.
- UpdateArgs update_args;
- update_args.addresses = std::move(result.addresses);
- update_args.config = std::move(lb_policy_config);
+ UpdateArgs update_args;
+ update_args.addresses = std::move(result.addresses);
+ update_args.config = std::move(lb_policy_config);
// Remove the config selector from channel args so that we're not holding
// unnecessary refs that cause it to be destroyed somewhere other than in the
// WorkSerializer.
@@ -249,67 +249,67 @@ void ResolvingLoadBalancingPolicy::CreateOrUpdateLbPolicyLocked(
lb_policy_.get());
}
lb_policy_->UpdateLocked(std::move(update_args));
-}
-
-// Creates a new LB policy.
-OrphanablePtr<LoadBalancingPolicy>
-ResolvingLoadBalancingPolicy::CreateLbPolicyLocked(
+}
+
+// Creates a new LB policy.
+OrphanablePtr<LoadBalancingPolicy>
+ResolvingLoadBalancingPolicy::CreateLbPolicyLocked(
const grpc_channel_args& args) {
- LoadBalancingPolicy::Args lb_policy_args;
+ LoadBalancingPolicy::Args lb_policy_args;
lb_policy_args.work_serializer = work_serializer();
- lb_policy_args.channel_control_helper =
+ lb_policy_args.channel_control_helper =
y_absl::make_unique<ResolvingControlHelper>(Ref());
- lb_policy_args.args = &args;
- OrphanablePtr<LoadBalancingPolicy> lb_policy =
+ lb_policy_args.args = &args;
+ OrphanablePtr<LoadBalancingPolicy> lb_policy =
MakeOrphanable<ChildPolicyHandler>(std::move(lb_policy_args), tracer_);
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO, "resolving_lb=%p: created new LB policy %p", this,
lb_policy.get());
- }
- grpc_pollset_set_add_pollset_set(lb_policy->interested_parties(),
- interested_parties());
- return lb_policy;
-}
-
-void ResolvingLoadBalancingPolicy::MaybeAddTraceMessagesForAddressChangesLocked(
- bool resolution_contains_addresses, TraceStringVector* trace_strings) {
- if (!resolution_contains_addresses &&
- previous_resolution_contained_addresses_) {
+ }
+ grpc_pollset_set_add_pollset_set(lb_policy->interested_parties(),
+ interested_parties());
+ return lb_policy;
+}
+
+void ResolvingLoadBalancingPolicy::MaybeAddTraceMessagesForAddressChangesLocked(
+ bool resolution_contains_addresses, TraceStringVector* trace_strings) {
+ if (!resolution_contains_addresses &&
+ previous_resolution_contained_addresses_) {
trace_strings->push_back("Address list became empty");
- } else if (resolution_contains_addresses &&
- !previous_resolution_contained_addresses_) {
+ } else if (resolution_contains_addresses &&
+ !previous_resolution_contained_addresses_) {
trace_strings->push_back("Address list became non-empty");
- }
- previous_resolution_contained_addresses_ = resolution_contains_addresses;
-}
-
-void ResolvingLoadBalancingPolicy::ConcatenateAndAddChannelTraceLocked(
+ }
+ previous_resolution_contained_addresses_ = resolution_contains_addresses;
+}
+
+void ResolvingLoadBalancingPolicy::ConcatenateAndAddChannelTraceLocked(
const TraceStringVector& trace_strings) const {
if (!trace_strings.empty()) {
TString message =
y_absl::StrCat("Resolution event: ", y_absl::StrJoin(trace_strings, ", "));
- channel_control_helper()->AddTraceEvent(ChannelControlHelper::TRACE_INFO,
+ channel_control_helper()->AddTraceEvent(ChannelControlHelper::TRACE_INFO,
message);
- }
-}
-
-void ResolvingLoadBalancingPolicy::OnResolverResultChangedLocked(
- Resolver::Result result) {
- // Handle race conditions.
- if (resolver_ == nullptr) return;
- if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO, "resolving_lb=%p: got resolver result", this);
- }
- // We only want to trace the address resolution in the follow cases:
- // (a) Address resolution resulted in service config change.
- // (b) Address resolution that causes number of backends to go from
- // zero to non-zero.
- // (c) Address resolution that causes number of backends to go from
- // non-zero to zero.
- // (d) Address resolution that causes a new LB policy to be created.
- //
- // We track a list of strings to eventually be concatenated and traced.
- TraceStringVector trace_strings;
+ }
+}
+
+void ResolvingLoadBalancingPolicy::OnResolverResultChangedLocked(
+ Resolver::Result result) {
+ // Handle race conditions.
+ if (resolver_ == nullptr) return;
+ if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
+ gpr_log(GPR_INFO, "resolving_lb=%p: got resolver result", this);
+ }
+ // We only want to trace the address resolution in the follow cases:
+ // (a) Address resolution resulted in service config change.
+ // (b) Address resolution that causes number of backends to go from
+ // zero to non-zero.
+ // (c) Address resolution that causes number of backends to go from
+ // non-zero to zero.
+ // (d) Address resolution that causes a new LB policy to be created.
+ //
+ // We track a list of strings to eventually be concatenated and traced.
+ TraceStringVector trace_strings;
MaybeAddTraceMessagesForAddressChangesLocked(!result.addresses.empty(),
&trace_strings);
// The result of grpc_error_string() is owned by the error itself.
@@ -324,16 +324,16 @@ void ResolvingLoadBalancingPolicy::OnResolverResultChangedLocked(
ChannelConfigHelper::ChooseServiceConfigResult service_config_result;
if (helper_ != nullptr) {
service_config_result = helper_->ChooseServiceConfig(result);
- } else {
+ } else {
service_config_result.lb_policy_config = child_lb_config_;
- }
+ }
if (service_config_result.no_valid_service_config) {
// We received an invalid service config and we don't have a
// previous service config to fall back to.
OnResolverError(GRPC_ERROR_REF(service_config_error));
trace_strings.push_back("no valid service config");
} else {
- // Create or update LB policy, as needed.
+ // Create or update LB policy, as needed.
CreateOrUpdateLbPolicyLocked(
std::move(service_config_result.lb_policy_config), std::move(result));
if (service_config_result.service_config_changed) {
@@ -346,10 +346,10 @@ void ResolvingLoadBalancingPolicy::OnResolverResultChangedLocked(
// config in the trace, at the risk of bloating the trace logs.
trace_strings.push_back("Service config changed");
}
- }
- // Add channel trace event.
+ }
+ // Add channel trace event.
ConcatenateAndAddChannelTraceLocked(trace_strings);
GRPC_ERROR_UNREF(service_config_error);
-}
-
-} // namespace grpc_core
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.h
index 1bd1db8b78..a3e5e62482 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolving_lb_policy.h
@@ -1,58 +1,58 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVING_LB_POLICY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVING_LB_POLICY_H
-
-#include <grpc/support/port_platform.h>
-
+/*
+ *
+ * Copyright 2018 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVING_LB_POLICY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVING_LB_POLICY_H
+
+#include <grpc/support/port_platform.h>
+
#include "y_absl/container/inlined_vector.h"
#include "src/core/ext/filters/client_channel/config_selector.h"
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
-#include "src/core/ext/filters/client_channel/resolver.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/iomgr/call_combiner.h"
-#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/polling_entity.h"
-#include "src/core/lib/iomgr/pollset_set.h"
-#include "src/core/lib/transport/connectivity_state.h"
-#include "src/core/lib/transport/metadata_batch.h"
-
-namespace grpc_core {
-
-// An LB policy that wraps a resolver and a child LB policy to make use
-// of the addresses returned by the resolver.
-//
-// When used in the client_channel code, the resolver will attempt to
-// fetch the service config, and the child LB policy name and config
-// will be determined based on the service config.
-//
-// When used in an LB policy implementation that needs to do another
-// round of resolution before creating a child policy, the resolver does
-// not fetch the service config, and the caller must pre-determine the
-// child LB policy and config to use.
-class ResolvingLoadBalancingPolicy : public LoadBalancingPolicy {
- public:
+#include "src/core/ext/filters/client_channel/lb_policy.h"
+#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
+#include "src/core/ext/filters/client_channel/resolver.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/channel_stack.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/iomgr/call_combiner.h"
+#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/polling_entity.h"
+#include "src/core/lib/iomgr/pollset_set.h"
+#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/metadata_batch.h"
+
+namespace grpc_core {
+
+// An LB policy that wraps a resolver and a child LB policy to make use
+// of the addresses returned by the resolver.
+//
+// When used in the client_channel code, the resolver will attempt to
+// fetch the service config, and the child LB policy name and config
+// will be determined based on the service config.
+//
+// When used in an LB policy implementation that needs to do another
+// round of resolution before creating a child policy, the resolver does
+// not fetch the service config, and the caller must pre-determine the
+// child LB policy and config to use.
+class ResolvingLoadBalancingPolicy : public LoadBalancingPolicy {
+ public:
class ChannelConfigHelper {
public:
struct ChooseServiceConfigResult {
@@ -65,7 +65,7 @@ class ResolvingLoadBalancingPolicy : public LoadBalancingPolicy {
// The LB policy config to use.
RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config;
};
-
+
virtual ~ChannelConfigHelper() = default;
// Chooses the service config for the channel.
@@ -83,56 +83,56 @@ class ResolvingLoadBalancingPolicy : public LoadBalancingPolicy {
grpc_core::UniquePtr<char> target_uri,
ChannelConfigHelper* helper);
- virtual const char* name() const override { return "resolving_lb"; }
-
- // No-op -- should never get updates from the channel.
- // TODO(roth): Need to support updating child LB policy's config for xds
- // use case.
- void UpdateLocked(UpdateArgs /*args*/) override {}
-
- void ExitIdleLocked() override;
-
- void ResetBackoffLocked() override;
-
- private:
+ virtual const char* name() const override { return "resolving_lb"; }
+
+ // No-op -- should never get updates from the channel.
+ // TODO(roth): Need to support updating child LB policy's config for xds
+ // use case.
+ void UpdateLocked(UpdateArgs /*args*/) override {}
+
+ void ExitIdleLocked() override;
+
+ void ResetBackoffLocked() override;
+
+ private:
using TraceStringVector = y_absl::InlinedVector<const char*, 3>;
-
- class ResolverResultHandler;
- class ResolvingControlHelper;
-
- ~ResolvingLoadBalancingPolicy();
-
- void ShutdownLocked() override;
-
- void OnResolverError(grpc_error* error);
- void CreateOrUpdateLbPolicyLocked(
- RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
+
+ class ResolverResultHandler;
+ class ResolvingControlHelper;
+
+ ~ResolvingLoadBalancingPolicy();
+
+ void ShutdownLocked() override;
+
+ void OnResolverError(grpc_error* error);
+ void CreateOrUpdateLbPolicyLocked(
+ RefCountedPtr<LoadBalancingPolicy::Config> lb_policy_config,
Resolver::Result result);
- OrphanablePtr<LoadBalancingPolicy> CreateLbPolicyLocked(
+ OrphanablePtr<LoadBalancingPolicy> CreateLbPolicyLocked(
const grpc_channel_args& args);
- void MaybeAddTraceMessagesForAddressChangesLocked(
- bool resolution_contains_addresses, TraceStringVector* trace_strings);
- void ConcatenateAndAddChannelTraceLocked(
+ void MaybeAddTraceMessagesForAddressChangesLocked(
+ bool resolution_contains_addresses, TraceStringVector* trace_strings);
+ void ConcatenateAndAddChannelTraceLocked(
const TraceStringVector& trace_strings) const;
- void OnResolverResultChangedLocked(Resolver::Result result);
-
- // Passed in from caller at construction time.
- TraceFlag* tracer_;
- grpc_core::UniquePtr<char> target_uri_;
+ void OnResolverResultChangedLocked(Resolver::Result result);
+
+ // Passed in from caller at construction time.
+ TraceFlag* tracer_;
+ grpc_core::UniquePtr<char> target_uri_;
ChannelConfigHelper* helper_;
-
- // Resolver and associated state.
- OrphanablePtr<Resolver> resolver_;
- bool previous_resolution_contained_addresses_ = false;
-
+
+ // Resolver and associated state.
+ OrphanablePtr<Resolver> resolver_;
+ bool previous_resolution_contained_addresses_ = false;
+
// Determined by resolver results.
grpc_core::UniquePtr<char> child_policy_name_;
RefCountedPtr<LoadBalancingPolicy::Config> child_lb_config_;
- // Child LB policy.
- OrphanablePtr<LoadBalancingPolicy> lb_policy_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVING_LB_POLICY_H */
+ // Child LB policy.
+ OrphanablePtr<LoadBalancingPolicy> lb_policy_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVING_LB_POLICY_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.cc
index 65df8034d7..2005efa8e0 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.cc
@@ -118,27 +118,27 @@ void ServerRetryThrottleData::RecordSuccess() {
namespace {
-void* copy_server_name(void* key, void* /*unused*/) {
+void* copy_server_name(void* key, void* /*unused*/) {
return gpr_strdup(static_cast<const char*>(key));
}
-long compare_server_name(void* key1, void* key2, void* /*unused*/) {
+long compare_server_name(void* key1, void* key2, void* /*unused*/) {
return strcmp(static_cast<const char*>(key1), static_cast<const char*>(key2));
}
-void destroy_server_retry_throttle_data(void* value, void* /*unused*/) {
+void destroy_server_retry_throttle_data(void* value, void* /*unused*/) {
ServerRetryThrottleData* throttle_data =
static_cast<ServerRetryThrottleData*>(value);
throttle_data->Unref();
}
-void* copy_server_retry_throttle_data(void* value, void* /*unused*/) {
+void* copy_server_retry_throttle_data(void* value, void* /*unused*/) {
ServerRetryThrottleData* throttle_data =
static_cast<ServerRetryThrottleData*>(value);
return throttle_data->Ref().release();
}
-void destroy_server_name(void* key, void* /*unused*/) { gpr_free(key); }
+void destroy_server_name(void* key, void* /*unused*/) { gpr_free(key); }
const grpc_avl_vtable avl_vtable = {
destroy_server_name, copy_server_name, compare_server_name,
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.h
index 897a617f59..68af565f4b 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.h
@@ -21,7 +21,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
namespace grpc_core {
@@ -32,7 +32,7 @@ class ServerRetryThrottleData : public RefCounted<ServerRetryThrottleData> {
public:
ServerRetryThrottleData(intptr_t max_milli_tokens, intptr_t milli_token_ratio,
ServerRetryThrottleData* old_throttle_data);
- ~ServerRetryThrottleData();
+ ~ServerRetryThrottleData();
/// Records a failure. Returns true if it's okay to send a retry.
bool RecordFailure();
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.cc
index 9ff2ad942b..7b32a40157 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.cc
@@ -1,55 +1,55 @@
-//
-// Copyright 2015 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.
-//
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/service_config.h"
-
+//
+// Copyright 2015 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.
+//
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/service_config.h"
+
#include <util/generic/string.h>
-
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/log.h>
-
+#include <grpc/support/log.h>
+
#include "src/core/ext/filters/client_channel/service_config_parser.h"
-#include "src/core/lib/json/json.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-namespace grpc_core {
-
+#include "src/core/lib/json/json.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+namespace grpc_core {
+
RefCountedPtr<ServiceConfig> ServiceConfig::Create(
const grpc_channel_args* args, y_absl::string_view json_string,
grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr);
+ GPR_DEBUG_ASSERT(error != nullptr);
Json json = Json::Parse(json_string, error);
if (*error != GRPC_ERROR_NONE) return nullptr;
return MakeRefCounted<ServiceConfig>(args, TString(json_string),
std::move(json), error);
-}
-
+}
+
ServiceConfig::ServiceConfig(const grpc_channel_args* args,
TString json_string, Json json,
grpc_error** error)
: json_string_(std::move(json_string)), json_(std::move(json)) {
- GPR_DEBUG_ASSERT(error != nullptr);
+ GPR_DEBUG_ASSERT(error != nullptr);
if (json_.type() != Json::Type::OBJECT) {
*error =
GRPC_ERROR_CREATE_FROM_STATIC_STRING("JSON value is not an object");
- return;
- }
+ return;
+ }
std::vector<grpc_error*> error_list;
grpc_error* global_error = GRPC_ERROR_NONE;
parsed_global_configs_ =
@@ -60,15 +60,15 @@ ServiceConfig::ServiceConfig(const grpc_channel_args* args,
if (!error_list.empty()) {
*error = GRPC_ERROR_CREATE_FROM_VECTOR("Service config parsing error",
&error_list);
- }
-}
-
+ }
+}
+
ServiceConfig::~ServiceConfig() {
for (auto& p : parsed_method_configs_map_) {
grpc_slice_unref_internal(p.first);
- }
-}
-
+ }
+}
+
grpc_error* ServiceConfig::ParseJsonMethodConfig(const grpc_channel_args* args,
const Json& json) {
std::vector<grpc_error*> error_list;
@@ -80,7 +80,7 @@ grpc_error* ServiceConfig::ParseJsonMethodConfig(const grpc_channel_args* args,
ServiceConfigParser::ParsePerMethodParameters(args, json, &parser_error);
if (parser_error != GRPC_ERROR_NONE) {
error_list.push_back(parser_error);
- }
+ }
parsed_method_config_vectors_storage_.push_back(std::move(parsed_configs));
const auto* vector_ptr = parsed_method_config_vectors_storage_.back().get();
// Add an entry for each path.
@@ -121,45 +121,45 @@ grpc_error* ServiceConfig::ParseJsonMethodConfig(const grpc_channel_args* args,
value = vector_ptr;
}
}
- }
- }
- }
+ }
+ }
+ }
if (!found_name) {
parsed_method_config_vectors_storage_.pop_back();
- }
- return GRPC_ERROR_CREATE_FROM_VECTOR("methodConfig", &error_list);
-}
-
+ }
+ return GRPC_ERROR_CREATE_FROM_VECTOR("methodConfig", &error_list);
+}
+
grpc_error* ServiceConfig::ParsePerMethodParams(const grpc_channel_args* args) {
std::vector<grpc_error*> error_list;
auto it = json_.object_value().find("methodConfig");
if (it != json_.object_value().end()) {
if (it->second.type() != Json::Type::ARRAY) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:methodConfig error:not of type Array"));
- }
+ }
for (const Json& method_config : it->second.array_value()) {
if (method_config.type() != Json::Type::OBJECT) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:methodConfig error:not of type Object"));
continue;
- }
+ }
grpc_error* error = ParseJsonMethodConfig(args, method_config);
if (error != GRPC_ERROR_NONE) {
error_list.push_back(error);
- }
- }
- }
- return GRPC_ERROR_CREATE_FROM_VECTOR("Method Params", &error_list);
-}
-
+ }
+ }
+ }
+ return GRPC_ERROR_CREATE_FROM_VECTOR("Method Params", &error_list);
+}
+
TString ServiceConfig::ParseJsonMethodName(const Json& json,
grpc_error** error) {
if (json.type() != Json::Type::OBJECT) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "field:name error:type is not object");
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "field:name error:type is not object");
return "";
- }
+ }
// Find service name.
const TString* service_name = nullptr;
auto it = json.object_value().find("service");
@@ -180,10 +180,10 @@ TString ServiceConfig::ParseJsonMethodName(const Json& json,
if (it != json.object_value().end() &&
it->second.type() != Json::Type::JSON_NULL) {
if (it->second.type() != Json::Type::STRING) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error: field:method error:not of type string");
return "";
- }
+ }
if (!it->second.string_value().empty()) {
method_name = &it->second.string_value();
}
@@ -192,23 +192,23 @@ TString ServiceConfig::ParseJsonMethodName(const Json& json,
// Method name may not be specified without service name.
if (service_name == nullptr) {
if (method_name != nullptr) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:name error:method name populated without service name");
- }
+ }
return "";
- }
+ }
// Construct path.
return y_absl::StrCat("/", *service_name, "/",
method_name == nullptr ? "" : *method_name);
-}
-
+}
+
const ServiceConfigParser::ParsedConfigVector*
ServiceConfig::GetMethodParsedConfigVector(const grpc_slice& path) const {
if (parsed_method_configs_map_.empty()) return nullptr;
// Try looking up the full path in the map.
auto it = parsed_method_configs_map_.find(path);
if (it != parsed_method_configs_map_.end()) return it->second;
- // If we didn't find a match for the path, try looking for a wildcard
+ // If we didn't find a match for the path, try looking for a wildcard
// entry (i.e., change "/service/method" to "/service/").
UniquePtr<char> path_str(grpc_slice_to_c_string(path));
char* sep = strrchr(path_str.get(), '/');
@@ -219,6 +219,6 @@ ServiceConfig::GetMethodParsedConfigVector(const grpc_slice& path) const {
if (it != parsed_method_configs_map_.end()) return it->second;
// Try default method config, if set.
return default_method_config_vector_;
-}
-
-} // namespace grpc_core
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.h
index 718f6026c2..cf0caafb45 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/service_config.h
@@ -1,126 +1,126 @@
-//
-// Copyright 2016 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVICE_CONFIG_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVICE_CONFIG_H
-
-#include <grpc/support/port_platform.h>
-
+//
+// Copyright 2016 gRPC authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVICE_CONFIG_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVICE_CONFIG_H
+
+#include <grpc/support/port_platform.h>
+
#include <unordered_map>
#include "y_absl/container/inlined_vector.h"
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/support/string_util.h>
-
+#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/support/string_util.h>
+
#include "src/core/ext/filters/client_channel/service_config_parser.h"
-#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/json/json.h"
+#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/json/json.h"
#include "src/core/lib/slice/slice_internal.h"
-
-// The main purpose of the code here is to parse the service config in
-// JSON form, which will look like this:
-//
-// {
-// "loadBalancingPolicy": "string", // optional
-// "methodConfig": [ // array of one or more method_config objects
-// {
-// "name": [ // array of one or more name objects
-// {
-// "service": "string", // required
-// "method": "string", // optional
-// }
-// ],
-// // remaining fields are optional.
-// // see https://developers.google.com/protocol-buffers/docs/proto3#json
-// // for format details.
-// "waitForReady": bool,
-// "timeout": "duration_string",
-// "maxRequestMessageBytes": "int64_string",
-// "maxResponseMessageBytes": "int64_string",
-// }
-// ]
-// }
-
-namespace grpc_core {
-
+
+// The main purpose of the code here is to parse the service config in
+// JSON form, which will look like this:
+//
+// {
+// "loadBalancingPolicy": "string", // optional
+// "methodConfig": [ // array of one or more method_config objects
+// {
+// "name": [ // array of one or more name objects
+// {
+// "service": "string", // required
+// "method": "string", // optional
+// }
+// ],
+// // remaining fields are optional.
+// // see https://developers.google.com/protocol-buffers/docs/proto3#json
+// // for format details.
+// "waitForReady": bool,
+// "timeout": "duration_string",
+// "maxRequestMessageBytes": "int64_string",
+// "maxResponseMessageBytes": "int64_string",
+// }
+// ]
+// }
+
+namespace grpc_core {
+
// TODO(roth): Consider stripping this down further to the completely minimal
// interface requied to be exposed as part of the resolver API.
-class ServiceConfig : public RefCounted<ServiceConfig> {
- public:
- /// Creates a new service config from parsing \a json_string.
- /// Returns null on parse error.
+class ServiceConfig : public RefCounted<ServiceConfig> {
+ public:
+ /// Creates a new service config from parsing \a json_string.
+ /// Returns null on parse error.
static RefCountedPtr<ServiceConfig> Create(const grpc_channel_args* args,
y_absl::string_view json_string,
- grpc_error** error);
-
+ grpc_error** error);
+
ServiceConfig(const grpc_channel_args* args, TString json_string,
Json json, grpc_error** error);
~ServiceConfig();
-
+
const TString& json_string() const { return json_string_; }
-
- /// Retrieves the global parsed config at index \a index. The
- /// lifetime of the returned object is tied to the lifetime of the
- /// ServiceConfig object.
+
+ /// Retrieves the global parsed config at index \a index. The
+ /// lifetime of the returned object is tied to the lifetime of the
+ /// ServiceConfig object.
ServiceConfigParser::ParsedConfig* GetGlobalParsedConfig(size_t index) {
- GPR_DEBUG_ASSERT(index < parsed_global_configs_.size());
- return parsed_global_configs_[index].get();
- }
-
- /// Retrieves the vector of parsed configs for the method identified
- /// by \a path. The lifetime of the returned vector and contained objects
- /// is tied to the lifetime of the ServiceConfig object.
+ GPR_DEBUG_ASSERT(index < parsed_global_configs_.size());
+ return parsed_global_configs_[index].get();
+ }
+
+ /// Retrieves the vector of parsed configs for the method identified
+ /// by \a path. The lifetime of the returned vector and contained objects
+ /// is tied to the lifetime of the ServiceConfig object.
const ServiceConfigParser::ParsedConfigVector* GetMethodParsedConfigVector(
const grpc_slice& path) const;
-
- private:
+
+ private:
// Helper functions for parsing the method configs.
grpc_error* ParsePerMethodParams(const grpc_channel_args* args);
grpc_error* ParseJsonMethodConfig(const grpc_channel_args* args,
const Json& json);
-
+
// Returns a path string for the JSON name object specified by json.
// Sets *error on error.
static TString ParseJsonMethodName(const Json& json, grpc_error** error);
-
+
TString json_string_;
Json json_;
-
+
y_absl::InlinedVector<std::unique_ptr<ServiceConfigParser::ParsedConfig>,
ServiceConfigParser::kNumPreallocatedParsers>
- parsed_global_configs_;
- // A map from the method name to the parsed config vector. Note that we are
- // using a raw pointer and not a unique pointer so that we can use the same
- // vector for multiple names.
+ parsed_global_configs_;
+ // A map from the method name to the parsed config vector. Note that we are
+ // using a raw pointer and not a unique pointer so that we can use the same
+ // vector for multiple names.
std::unordered_map<grpc_slice, const ServiceConfigParser::ParsedConfigVector*,
SliceHash>
parsed_method_configs_map_;
// Default method config.
const ServiceConfigParser::ParsedConfigVector* default_method_config_vector_ =
nullptr;
- // Storage for all the vectors that are being used in
- // parsed_method_configs_table_.
+ // Storage for all the vectors that are being used in
+ // parsed_method_configs_table_.
y_absl::InlinedVector<std::unique_ptr<ServiceConfigParser::ParsedConfigVector>,
32>
- parsed_method_config_vectors_storage_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVICE_CONFIG_H */
+ parsed_method_config_vectors_storage_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVICE_CONFIG_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc
index 39800681e0..5504955f83 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc
@@ -34,7 +34,7 @@
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/health/health_check_client.h"
#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h"
#include "src/core/lib/backoff/backoff.h"
#include "src/core/lib/channel/channel_args.h"
@@ -44,7 +44,7 @@
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/parse_address.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/profiling/timers.h"
@@ -77,34 +77,34 @@
namespace grpc_core {
-TraceFlag grpc_trace_subchannel(false, "subchannel");
-DebugOnlyTraceFlag grpc_trace_subchannel_refcount(false, "subchannel_refcount");
-
+TraceFlag grpc_trace_subchannel(false, "subchannel");
+DebugOnlyTraceFlag grpc_trace_subchannel_refcount(false, "subchannel_refcount");
+
//
// ConnectedSubchannel
//
ConnectedSubchannel::ConnectedSubchannel(
grpc_channel_stack* channel_stack, const grpc_channel_args* args,
- RefCountedPtr<channelz::SubchannelNode> channelz_subchannel)
- : RefCounted<ConnectedSubchannel>(&grpc_trace_subchannel_refcount),
+ RefCountedPtr<channelz::SubchannelNode> channelz_subchannel)
+ : RefCounted<ConnectedSubchannel>(&grpc_trace_subchannel_refcount),
channel_stack_(channel_stack),
args_(grpc_channel_args_copy(args)),
- channelz_subchannel_(std::move(channelz_subchannel)) {}
+ channelz_subchannel_(std::move(channelz_subchannel)) {}
ConnectedSubchannel::~ConnectedSubchannel() {
grpc_channel_args_destroy(args_);
GRPC_CHANNEL_STACK_UNREF(channel_stack_, "connected_subchannel_dtor");
}
-void ConnectedSubchannel::StartWatch(
- grpc_pollset_set* interested_parties,
- OrphanablePtr<ConnectivityStateWatcherInterface> watcher) {
+void ConnectedSubchannel::StartWatch(
+ grpc_pollset_set* interested_parties,
+ OrphanablePtr<ConnectivityStateWatcherInterface> watcher) {
grpc_transport_op* op = grpc_make_transport_op(nullptr);
- op->start_connectivity_watch = std::move(watcher);
- op->start_connectivity_watch_state = GRPC_CHANNEL_READY;
+ op->start_connectivity_watch = std::move(watcher);
+ op->start_connectivity_watch_state = GRPC_CHANNEL_READY;
op->bind_pollset_set = interested_parties;
- grpc_channel_element* elem = grpc_channel_stack_element(channel_stack_, 0);
+ grpc_channel_element* elem = grpc_channel_stack_element(channel_stack_, 0);
elem->filter->start_transport_op(elem, op);
}
@@ -118,38 +118,38 @@ void ConnectedSubchannel::Ping(grpc_closure* on_initiate,
elem->filter->start_transport_op(elem, op);
}
-size_t ConnectedSubchannel::GetInitialCallSizeEstimate(
- size_t parent_data_size) const {
- size_t allocation_size =
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall));
- if (parent_data_size > 0) {
- allocation_size +=
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(channel_stack_->call_stack_size) +
- parent_data_size;
- } else {
- allocation_size += channel_stack_->call_stack_size;
- }
- return allocation_size;
-}
-
-//
-// SubchannelCall
-//
-
-RefCountedPtr<SubchannelCall> SubchannelCall::Create(Args args,
- grpc_error** error) {
+size_t ConnectedSubchannel::GetInitialCallSizeEstimate(
+ size_t parent_data_size) const {
+ size_t allocation_size =
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall));
+ if (parent_data_size > 0) {
+ allocation_size +=
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(channel_stack_->call_stack_size) +
+ parent_data_size;
+ } else {
+ allocation_size += channel_stack_->call_stack_size;
+ }
+ return allocation_size;
+}
+
+//
+// SubchannelCall
+//
+
+RefCountedPtr<SubchannelCall> SubchannelCall::Create(Args args,
+ grpc_error** error) {
const size_t allocation_size =
- args.connected_subchannel->GetInitialCallSizeEstimate(
- args.parent_data_size);
- Arena* arena = args.arena;
- return RefCountedPtr<SubchannelCall>(new (
- arena->Alloc(allocation_size)) SubchannelCall(std::move(args), error));
-}
-
-SubchannelCall::SubchannelCall(Args args, grpc_error** error)
- : connected_subchannel_(std::move(args.connected_subchannel)),
- deadline_(args.deadline) {
- grpc_call_stack* callstk = SUBCHANNEL_CALL_TO_CALL_STACK(this);
+ args.connected_subchannel->GetInitialCallSizeEstimate(
+ args.parent_data_size);
+ Arena* arena = args.arena;
+ return RefCountedPtr<SubchannelCall>(new (
+ arena->Alloc(allocation_size)) SubchannelCall(std::move(args), error));
+}
+
+SubchannelCall::SubchannelCall(Args args, grpc_error** error)
+ : connected_subchannel_(std::move(args.connected_subchannel)),
+ deadline_(args.deadline) {
+ grpc_call_stack* callstk = SUBCHANNEL_CALL_TO_CALL_STACK(this);
const grpc_call_element_args call_args = {
callstk, /* call_stack */
nullptr, /* server_transport_data */
@@ -160,17 +160,17 @@ SubchannelCall::SubchannelCall(Args args, grpc_error** error)
args.arena, /* arena */
args.call_combiner /* call_combiner */
};
- *error = grpc_call_stack_init(connected_subchannel_->channel_stack(), 1,
- SubchannelCall::Destroy, this, &call_args);
+ *error = grpc_call_stack_init(connected_subchannel_->channel_stack(), 1,
+ SubchannelCall::Destroy, this, &call_args);
if (GPR_UNLIKELY(*error != GRPC_ERROR_NONE)) {
const char* error_string = grpc_error_string(*error);
gpr_log(GPR_ERROR, "error: %s", error_string);
- return;
+ return;
}
grpc_call_stack_set_pollset_or_pollset_set(callstk, args.pollent);
- auto* channelz_node = connected_subchannel_->channelz_subchannel();
- if (channelz_node != nullptr) {
- channelz_node->RecordCallStarted();
+ auto* channelz_node = connected_subchannel_->channelz_subchannel();
+ if (channelz_node != nullptr) {
+ channelz_node->RecordCallStarted();
}
}
@@ -215,12 +215,12 @@ void SubchannelCall::Unref() {
GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), "");
}
-void SubchannelCall::Unref(const DebugLocation& /*location*/,
- const char* reason) {
+void SubchannelCall::Unref(const DebugLocation& /*location*/,
+ const char* reason) {
GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason);
}
-void SubchannelCall::Destroy(void* arg, grpc_error* /*error*/) {
+void SubchannelCall::Destroy(void* arg, grpc_error* /*error*/) {
GPR_TIMER_SCOPE("subchannel_call_destroy", 0);
SubchannelCall* self = static_cast<SubchannelCall*>(arg);
// Keep some members before destroying the subchannel call.
@@ -295,16 +295,16 @@ void SubchannelCall::RecvTrailingMetadataReady(void* arg, grpc_error* error) {
} else {
channelz_subchannel->RecordCallFailed();
}
- Closure::Run(DEBUG_LOCATION, call->original_recv_trailing_metadata_,
- GRPC_ERROR_REF(error));
+ Closure::Run(DEBUG_LOCATION, call->original_recv_trailing_metadata_,
+ GRPC_ERROR_REF(error));
}
void SubchannelCall::IncrementRefCount() {
GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), "");
}
-void SubchannelCall::IncrementRefCount(
- const grpc_core::DebugLocation& /*location*/, const char* reason) {
+void SubchannelCall::IncrementRefCount(
+ const grpc_core::DebugLocation& /*location*/, const char* reason) {
GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason);
}
@@ -313,7 +313,7 @@ void SubchannelCall::IncrementRefCount(
//
class Subchannel::ConnectedSubchannelStateWatcher
- : public AsyncConnectivityStateWatcherInterface {
+ : public AsyncConnectivityStateWatcherInterface {
public:
// Must be instantiated while holding c->mu.
explicit ConnectedSubchannelStateWatcher(Subchannel* c) : subchannel_(c) {
@@ -329,22 +329,22 @@ class Subchannel::ConnectedSubchannelStateWatcher
private:
void OnConnectivityStateChange(grpc_connectivity_state new_state,
const y_absl::Status& status) override {
- Subchannel* c = subchannel_;
- MutexLock lock(&c->mu_);
- switch (new_state) {
- case GRPC_CHANNEL_TRANSIENT_FAILURE:
- case GRPC_CHANNEL_SHUTDOWN: {
- if (!c->disconnected_ && c->connected_subchannel_ != nullptr) {
- if (grpc_trace_subchannel.enabled()) {
- gpr_log(GPR_INFO,
- "Connected subchannel %p of subchannel %p has gone into "
- "%s. Attempting to reconnect.",
- c->connected_subchannel_.get(), c,
- ConnectivityStateName(new_state));
+ Subchannel* c = subchannel_;
+ MutexLock lock(&c->mu_);
+ switch (new_state) {
+ case GRPC_CHANNEL_TRANSIENT_FAILURE:
+ case GRPC_CHANNEL_SHUTDOWN: {
+ if (!c->disconnected_ && c->connected_subchannel_ != nullptr) {
+ if (grpc_trace_subchannel.enabled()) {
+ gpr_log(GPR_INFO,
+ "Connected subchannel %p of subchannel %p has gone into "
+ "%s. Attempting to reconnect.",
+ c->connected_subchannel_.get(), c,
+ ConnectivityStateName(new_state));
}
- c->connected_subchannel_.reset();
- if (c->channelz_node() != nullptr) {
- c->channelz_node()->SetChildSocket(nullptr);
+ c->connected_subchannel_.reset();
+ if (c->channelz_node() != nullptr) {
+ c->channelz_node()->SetChildSocket(nullptr);
}
// We need to construct our own status if the underlying state was
// shutdown since the accompanying status will be StatusCode::OK
@@ -355,24 +355,24 @@ class Subchannel::ConnectedSubchannelStateWatcher
? y_absl::Status(y_absl::StatusCode::kUnavailable,
"Subchannel has disconnected.")
: status);
- c->backoff_begun_ = false;
- c->backoff_.Reset();
+ c->backoff_begun_ = false;
+ c->backoff_.Reset();
}
- break;
+ break;
}
- default: {
- // In principle, this should never happen. We should not get
- // a callback for READY, because that was the state we started
- // this watch from. And a connected subchannel should never go
- // from READY to CONNECTING or IDLE.
+ default: {
+ // In principle, this should never happen. We should not get
+ // a callback for READY, because that was the state we started
+ // this watch from. And a connected subchannel should never go
+ // from READY to CONNECTING or IDLE.
c->SetConnectivityStateLocked(new_state, status);
- }
+ }
}
}
- Subchannel* subchannel_;
-};
-
+ Subchannel* subchannel_;
+};
+
// Asynchronously notifies the \a watcher of a change in the connectvity state
// of \a subchannel to the current \a state. Deletes itself when done.
class Subchannel::AsyncWatcherNotifierLocked {
@@ -406,191 +406,191 @@ class Subchannel::AsyncWatcherNotifierLocked {
grpc_closure closure_;
};
-//
-// Subchannel::ConnectivityStateWatcherList
-//
-
-void Subchannel::ConnectivityStateWatcherList::AddWatcherLocked(
+//
+// Subchannel::ConnectivityStateWatcherList
+//
+
+void Subchannel::ConnectivityStateWatcherList::AddWatcherLocked(
RefCountedPtr<ConnectivityStateWatcherInterface> watcher) {
- watchers_.insert(std::make_pair(watcher.get(), std::move(watcher)));
-}
-
-void Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked(
- ConnectivityStateWatcherInterface* watcher) {
- watchers_.erase(watcher);
-}
-
-void Subchannel::ConnectivityStateWatcherList::NotifyLocked(
+ watchers_.insert(std::make_pair(watcher.get(), std::move(watcher)));
+}
+
+void Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked(
+ ConnectivityStateWatcherInterface* watcher) {
+ watchers_.erase(watcher);
+}
+
+void Subchannel::ConnectivityStateWatcherList::NotifyLocked(
Subchannel* subchannel, grpc_connectivity_state state,
const y_absl::Status& status) {
- for (const auto& p : watchers_) {
+ for (const auto& p : watchers_) {
new AsyncWatcherNotifierLocked(p.second, subchannel, state, status);
- }
-}
-
-//
-// Subchannel::HealthWatcherMap::HealthWatcher
-//
-
-// State needed for tracking the connectivity state with a particular
-// health check service name.
-class Subchannel::HealthWatcherMap::HealthWatcher
- : public AsyncConnectivityStateWatcherInterface {
- public:
- HealthWatcher(Subchannel* c,
- grpc_core::UniquePtr<char> health_check_service_name,
- grpc_connectivity_state subchannel_state)
- : subchannel_(c),
- health_check_service_name_(std::move(health_check_service_name)),
- state_(subchannel_state == GRPC_CHANNEL_READY ? GRPC_CHANNEL_CONNECTING
- : subchannel_state) {
- GRPC_SUBCHANNEL_WEAK_REF(subchannel_, "health_watcher");
- // If the subchannel is already connected, start health checking.
- if (subchannel_state == GRPC_CHANNEL_READY) StartHealthCheckingLocked();
- }
-
- ~HealthWatcher() {
- GRPC_SUBCHANNEL_WEAK_UNREF(subchannel_, "health_watcher");
- }
-
- const char* health_check_service_name() const {
- return health_check_service_name_.get();
- }
-
- grpc_connectivity_state state() const { return state_; }
-
- void AddWatcherLocked(
- grpc_connectivity_state initial_state,
+ }
+}
+
+//
+// Subchannel::HealthWatcherMap::HealthWatcher
+//
+
+// State needed for tracking the connectivity state with a particular
+// health check service name.
+class Subchannel::HealthWatcherMap::HealthWatcher
+ : public AsyncConnectivityStateWatcherInterface {
+ public:
+ HealthWatcher(Subchannel* c,
+ grpc_core::UniquePtr<char> health_check_service_name,
+ grpc_connectivity_state subchannel_state)
+ : subchannel_(c),
+ health_check_service_name_(std::move(health_check_service_name)),
+ state_(subchannel_state == GRPC_CHANNEL_READY ? GRPC_CHANNEL_CONNECTING
+ : subchannel_state) {
+ GRPC_SUBCHANNEL_WEAK_REF(subchannel_, "health_watcher");
+ // If the subchannel is already connected, start health checking.
+ if (subchannel_state == GRPC_CHANNEL_READY) StartHealthCheckingLocked();
+ }
+
+ ~HealthWatcher() {
+ GRPC_SUBCHANNEL_WEAK_UNREF(subchannel_, "health_watcher");
+ }
+
+ const char* health_check_service_name() const {
+ return health_check_service_name_.get();
+ }
+
+ grpc_connectivity_state state() const { return state_; }
+
+ void AddWatcherLocked(
+ grpc_connectivity_state initial_state,
RefCountedPtr<Subchannel::ConnectivityStateWatcherInterface> watcher) {
- if (state_ != initial_state) {
+ if (state_ != initial_state) {
new AsyncWatcherNotifierLocked(watcher, subchannel_, state_, status_);
}
- watcher_list_.AddWatcherLocked(std::move(watcher));
+ watcher_list_.AddWatcherLocked(std::move(watcher));
}
- void RemoveWatcherLocked(
- Subchannel::ConnectivityStateWatcherInterface* watcher) {
- watcher_list_.RemoveWatcherLocked(watcher);
- }
-
- bool HasWatchers() const { return !watcher_list_.empty(); }
-
+ void RemoveWatcherLocked(
+ Subchannel::ConnectivityStateWatcherInterface* watcher) {
+ watcher_list_.RemoveWatcherLocked(watcher);
+ }
+
+ bool HasWatchers() const { return !watcher_list_.empty(); }
+
void NotifyLocked(grpc_connectivity_state state, const y_absl::Status& status) {
- if (state == GRPC_CHANNEL_READY) {
- // If we had not already notified for CONNECTING state, do so now.
- // (We may have missed this earlier, because if the transition
- // from IDLE to CONNECTING to READY was too quick, the connected
- // subchannel may not have sent us a notification for CONNECTING.)
- if (state_ != GRPC_CHANNEL_CONNECTING) {
- state_ = GRPC_CHANNEL_CONNECTING;
+ if (state == GRPC_CHANNEL_READY) {
+ // If we had not already notified for CONNECTING state, do so now.
+ // (We may have missed this earlier, because if the transition
+ // from IDLE to CONNECTING to READY was too quick, the connected
+ // subchannel may not have sent us a notification for CONNECTING.)
+ if (state_ != GRPC_CHANNEL_CONNECTING) {
+ state_ = GRPC_CHANNEL_CONNECTING;
status_ = status;
watcher_list_.NotifyLocked(subchannel_, state_, status);
- }
- // If we've become connected, start health checking.
- StartHealthCheckingLocked();
- } else {
- state_ = state;
+ }
+ // If we've become connected, start health checking.
+ StartHealthCheckingLocked();
+ } else {
+ state_ = state;
status_ = status;
watcher_list_.NotifyLocked(subchannel_, state_, status);
- // We're not connected, so stop health checking.
- health_check_client_.reset();
- }
- }
-
- void Orphan() override {
- watcher_list_.Clear();
- health_check_client_.reset();
- Unref();
- }
-
- private:
+ // We're not connected, so stop health checking.
+ health_check_client_.reset();
+ }
+ }
+
+ void Orphan() override {
+ watcher_list_.Clear();
+ health_check_client_.reset();
+ Unref();
+ }
+
+ private:
void OnConnectivityStateChange(grpc_connectivity_state new_state,
const y_absl::Status& status) override {
- MutexLock lock(&subchannel_->mu_);
- if (new_state != GRPC_CHANNEL_SHUTDOWN && health_check_client_ != nullptr) {
- state_ = new_state;
+ MutexLock lock(&subchannel_->mu_);
+ if (new_state != GRPC_CHANNEL_SHUTDOWN && health_check_client_ != nullptr) {
+ state_ = new_state;
status_ = status;
watcher_list_.NotifyLocked(subchannel_, new_state, status);
- }
- }
-
- void StartHealthCheckingLocked() {
- GPR_ASSERT(health_check_client_ == nullptr);
- health_check_client_ = MakeOrphanable<HealthCheckClient>(
- health_check_service_name_.get(), subchannel_->connected_subchannel_,
- subchannel_->pollset_set_, subchannel_->channelz_node_, Ref());
- }
-
+ }
+ }
+
+ void StartHealthCheckingLocked() {
+ GPR_ASSERT(health_check_client_ == nullptr);
+ health_check_client_ = MakeOrphanable<HealthCheckClient>(
+ health_check_service_name_.get(), subchannel_->connected_subchannel_,
+ subchannel_->pollset_set_, subchannel_->channelz_node_, Ref());
+ }
+
Subchannel* subchannel_;
- grpc_core::UniquePtr<char> health_check_service_name_;
+ grpc_core::UniquePtr<char> health_check_service_name_;
OrphanablePtr<HealthCheckClient> health_check_client_;
- grpc_connectivity_state state_;
+ grpc_connectivity_state state_;
y_absl::Status status_;
- ConnectivityStateWatcherList watcher_list_;
+ ConnectivityStateWatcherList watcher_list_;
};
//
-// Subchannel::HealthWatcherMap
+// Subchannel::HealthWatcherMap
//
-void Subchannel::HealthWatcherMap::AddWatcherLocked(
- Subchannel* subchannel, grpc_connectivity_state initial_state,
- grpc_core::UniquePtr<char> health_check_service_name,
+void Subchannel::HealthWatcherMap::AddWatcherLocked(
+ Subchannel* subchannel, grpc_connectivity_state initial_state,
+ grpc_core::UniquePtr<char> health_check_service_name,
RefCountedPtr<ConnectivityStateWatcherInterface> watcher) {
- // If the health check service name is not already present in the map,
- // add it.
- auto it = map_.find(health_check_service_name.get());
- HealthWatcher* health_watcher;
- if (it == map_.end()) {
- const char* key = health_check_service_name.get();
- auto w = MakeOrphanable<HealthWatcher>(
- subchannel, std::move(health_check_service_name), subchannel->state_);
- health_watcher = w.get();
- map_[key] = std::move(w);
- } else {
- health_watcher = it->second.get();
+ // If the health check service name is not already present in the map,
+ // add it.
+ auto it = map_.find(health_check_service_name.get());
+ HealthWatcher* health_watcher;
+ if (it == map_.end()) {
+ const char* key = health_check_service_name.get();
+ auto w = MakeOrphanable<HealthWatcher>(
+ subchannel, std::move(health_check_service_name), subchannel->state_);
+ health_watcher = w.get();
+ map_[key] = std::move(w);
+ } else {
+ health_watcher = it->second.get();
}
- // Add the watcher to the entry.
- health_watcher->AddWatcherLocked(initial_state, std::move(watcher));
-}
-
-void Subchannel::HealthWatcherMap::RemoveWatcherLocked(
- const char* health_check_service_name,
- ConnectivityStateWatcherInterface* watcher) {
- auto it = map_.find(health_check_service_name);
- GPR_ASSERT(it != map_.end());
- it->second->RemoveWatcherLocked(watcher);
- // If we just removed the last watcher for this service name, remove
- // the map entry.
- if (!it->second->HasWatchers()) map_.erase(it);
-}
-
+ // Add the watcher to the entry.
+ health_watcher->AddWatcherLocked(initial_state, std::move(watcher));
+}
+
+void Subchannel::HealthWatcherMap::RemoveWatcherLocked(
+ const char* health_check_service_name,
+ ConnectivityStateWatcherInterface* watcher) {
+ auto it = map_.find(health_check_service_name);
+ GPR_ASSERT(it != map_.end());
+ it->second->RemoveWatcherLocked(watcher);
+ // If we just removed the last watcher for this service name, remove
+ // the map entry.
+ if (!it->second->HasWatchers()) map_.erase(it);
+}
+
void Subchannel::HealthWatcherMap::NotifyLocked(grpc_connectivity_state state,
const y_absl::Status& status) {
- for (const auto& p : map_) {
+ for (const auto& p : map_) {
p.second->NotifyLocked(state, status);
}
-}
-
-grpc_connectivity_state
-Subchannel::HealthWatcherMap::CheckConnectivityStateLocked(
- Subchannel* subchannel, const char* health_check_service_name) {
- auto it = map_.find(health_check_service_name);
- if (it == map_.end()) {
- // If the health check service name is not found in the map, we're
- // not currently doing a health check for that service name. If the
- // subchannel's state without health checking is READY, report
- // CONNECTING, since that's what we'd be in as soon as we do start a
- // watch. Otherwise, report the channel's state without health checking.
- return subchannel->state_ == GRPC_CHANNEL_READY ? GRPC_CHANNEL_CONNECTING
- : subchannel->state_;
- }
- HealthWatcher* health_watcher = it->second.get();
- return health_watcher->state();
-}
-
-void Subchannel::HealthWatcherMap::ShutdownLocked() { map_.clear(); }
-
+}
+
+grpc_connectivity_state
+Subchannel::HealthWatcherMap::CheckConnectivityStateLocked(
+ Subchannel* subchannel, const char* health_check_service_name) {
+ auto it = map_.find(health_check_service_name);
+ if (it == map_.end()) {
+ // If the health check service name is not found in the map, we're
+ // not currently doing a health check for that service name. If the
+ // subchannel's state without health checking is READY, report
+ // CONNECTING, since that's what we'd be in as soon as we do start a
+ // watch. Otherwise, report the channel's state without health checking.
+ return subchannel->state_ == GRPC_CHANNEL_READY ? GRPC_CHANNEL_CONNECTING
+ : subchannel->state_;
+ }
+ HealthWatcher* health_watcher = it->second.get();
+ return health_watcher->state();
+}
+
+void Subchannel::HealthWatcherMap::ShutdownLocked() { map_.clear(); }
+
//
// Subchannel
//
@@ -662,11 +662,11 @@ Subchannel::ConnectivityStateWatcherInterface::PopConnectivityStateChange() {
return state_change;
}
-Subchannel::Subchannel(SubchannelKey* key,
- OrphanablePtr<SubchannelConnector> connector,
+Subchannel::Subchannel(SubchannelKey* key,
+ OrphanablePtr<SubchannelConnector> connector,
const grpc_channel_args* args)
: key_(key),
- connector_(std::move(connector)),
+ connector_(std::move(connector)),
backoff_(ParseArgsForBackoffValues(args, &min_connect_timeout_ms_)) {
GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED();
gpr_atm_no_barrier_store(&ref_pair_, 1 << INTERNAL_REF_BITS);
@@ -676,7 +676,7 @@ Subchannel::Subchannel(SubchannelKey* key,
GetAddressFromSubchannelAddressArg(args, addr);
grpc_resolved_address* new_address = nullptr;
grpc_channel_args* new_args = nullptr;
- if (ProxyMapperRegistry::MapAddress(*addr, args, &new_address, &new_args)) {
+ if (ProxyMapperRegistry::MapAddress(*addr, args, &new_address, &new_args)) {
GPR_ASSERT(new_address != nullptr);
gpr_free(addr);
addr = new_address;
@@ -702,7 +702,7 @@ Subchannel::Subchannel(SubchannelKey* key,
(size_t)grpc_channel_arg_get_integer(arg, options);
if (channelz_enabled) {
channelz_node_ = MakeRefCounted<channelz::SubchannelNode>(
- GetTargetAddress(), channel_tracer_max_memory);
+ GetTargetAddress(), channel_tracer_max_memory);
channelz_node_->AddTraceEvent(
channelz::ChannelTrace::Severity::Info,
grpc_slice_from_static_string("subchannel created"));
@@ -714,26 +714,26 @@ Subchannel::~Subchannel() {
channelz_node_->AddTraceEvent(
channelz::ChannelTrace::Severity::Info,
grpc_slice_from_static_string("Subchannel destroyed"));
- channelz_node_->UpdateConnectivityState(GRPC_CHANNEL_SHUTDOWN);
+ channelz_node_->UpdateConnectivityState(GRPC_CHANNEL_SHUTDOWN);
}
grpc_channel_args_destroy(args_);
- connector_.reset();
+ connector_.reset();
grpc_pollset_set_destroy(pollset_set_);
- delete key_;
+ delete key_;
}
-Subchannel* Subchannel::Create(OrphanablePtr<SubchannelConnector> connector,
+Subchannel* Subchannel::Create(OrphanablePtr<SubchannelConnector> connector,
const grpc_channel_args* args) {
- SubchannelKey* key = new SubchannelKey(args);
+ SubchannelKey* key = new SubchannelKey(args);
SubchannelPoolInterface* subchannel_pool =
SubchannelPoolInterface::GetSubchannelPoolFromChannelArgs(args);
GPR_ASSERT(subchannel_pool != nullptr);
Subchannel* c = subchannel_pool->FindSubchannel(key);
if (c != nullptr) {
- delete key;
+ delete key;
return c;
}
- c = new Subchannel(key, std::move(connector), args);
+ c = new Subchannel(key, std::move(connector), args);
// Try to register the subchannel before setting the subchannel pool.
// Otherwise, in case of a registration race, unreffing c in
// RegisterSubchannel() will cause c to be tried to be unregistered, while
@@ -791,9 +791,9 @@ Subchannel* Subchannel::WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
namespace {
-void subchannel_destroy(void* arg, grpc_error* /*error*/) {
+void subchannel_destroy(void* arg, grpc_error* /*error*/) {
Subchannel* self = static_cast<Subchannel*>(arg);
- delete self;
+ delete self;
}
} // namespace
@@ -803,14 +803,14 @@ void Subchannel::WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
old_refs = RefMutate(-static_cast<gpr_atm>(1),
1 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("WEAK_UNREF"));
if (old_refs == 1) {
- ExecCtx::Run(DEBUG_LOCATION,
- GRPC_CLOSURE_CREATE(subchannel_destroy, this,
- grpc_schedule_on_exec_ctx),
- GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION,
+ GRPC_CLOSURE_CREATE(subchannel_destroy, this,
+ grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_NONE);
}
}
-Subchannel* Subchannel::RefFromWeakRef() {
+Subchannel* Subchannel::RefFromWeakRef() {
for (;;) {
gpr_atm old_refs = gpr_atm_acq_load(&ref_pair_);
if (old_refs >= (1 << INTERNAL_REF_BITS)) {
@@ -836,64 +836,64 @@ channelz::SubchannelNode* Subchannel::channelz_node() {
return channelz_node_.get();
}
-grpc_connectivity_state Subchannel::CheckConnectivityState(
- const char* health_check_service_name,
- RefCountedPtr<ConnectedSubchannel>* connected_subchannel) {
+grpc_connectivity_state Subchannel::CheckConnectivityState(
+ const char* health_check_service_name,
+ RefCountedPtr<ConnectedSubchannel>* connected_subchannel) {
MutexLock lock(&mu_);
- grpc_connectivity_state state;
- if (health_check_service_name == nullptr) {
- state = state_;
- } else {
- state = health_watcher_map_.CheckConnectivityStateLocked(
- this, health_check_service_name);
- }
- if (connected_subchannel != nullptr && state == GRPC_CHANNEL_READY) {
- *connected_subchannel = connected_subchannel_;
- }
+ grpc_connectivity_state state;
+ if (health_check_service_name == nullptr) {
+ state = state_;
+ } else {
+ state = health_watcher_map_.CheckConnectivityStateLocked(
+ this, health_check_service_name);
+ }
+ if (connected_subchannel != nullptr && state == GRPC_CHANNEL_READY) {
+ *connected_subchannel = connected_subchannel_;
+ }
return state;
}
-void Subchannel::WatchConnectivityState(
- grpc_connectivity_state initial_state,
- grpc_core::UniquePtr<char> health_check_service_name,
+void Subchannel::WatchConnectivityState(
+ grpc_connectivity_state initial_state,
+ grpc_core::UniquePtr<char> health_check_service_name,
RefCountedPtr<ConnectivityStateWatcherInterface> watcher) {
- MutexLock lock(&mu_);
- grpc_pollset_set* interested_parties = watcher->interested_parties();
- if (interested_parties != nullptr) {
- grpc_pollset_set_add_pollset_set(pollset_set_, interested_parties);
- }
- if (health_check_service_name == nullptr) {
- if (state_ != initial_state) {
+ MutexLock lock(&mu_);
+ grpc_pollset_set* interested_parties = watcher->interested_parties();
+ if (interested_parties != nullptr) {
+ grpc_pollset_set_add_pollset_set(pollset_set_, interested_parties);
+ }
+ if (health_check_service_name == nullptr) {
+ if (state_ != initial_state) {
new AsyncWatcherNotifierLocked(watcher, this, state_, status_);
}
- watcher_list_.AddWatcherLocked(std::move(watcher));
- } else {
- health_watcher_map_.AddWatcherLocked(this, initial_state,
- std::move(health_check_service_name),
- std::move(watcher));
- }
-}
-
-void Subchannel::CancelConnectivityStateWatch(
- const char* health_check_service_name,
- ConnectivityStateWatcherInterface* watcher) {
- MutexLock lock(&mu_);
- grpc_pollset_set* interested_parties = watcher->interested_parties();
- if (interested_parties != nullptr) {
- grpc_pollset_set_del_pollset_set(pollset_set_, interested_parties);
- }
- if (health_check_service_name == nullptr) {
- watcher_list_.RemoveWatcherLocked(watcher);
+ watcher_list_.AddWatcherLocked(std::move(watcher));
} else {
- health_watcher_map_.RemoveWatcherLocked(health_check_service_name, watcher);
+ health_watcher_map_.AddWatcherLocked(this, initial_state,
+ std::move(health_check_service_name),
+ std::move(watcher));
}
}
-void Subchannel::AttemptToConnect() {
- MutexLock lock(&mu_);
- MaybeStartConnectingLocked();
-}
-
+void Subchannel::CancelConnectivityStateWatch(
+ const char* health_check_service_name,
+ ConnectivityStateWatcherInterface* watcher) {
+ MutexLock lock(&mu_);
+ grpc_pollset_set* interested_parties = watcher->interested_parties();
+ if (interested_parties != nullptr) {
+ grpc_pollset_set_del_pollset_set(pollset_set_, interested_parties);
+ }
+ if (health_check_service_name == nullptr) {
+ watcher_list_.RemoveWatcherLocked(watcher);
+ } else {
+ health_watcher_map_.RemoveWatcherLocked(health_check_service_name, watcher);
+ }
+}
+
+void Subchannel::AttemptToConnect() {
+ MutexLock lock(&mu_);
+ MaybeStartConnectingLocked();
+}
+
void Subchannel::ResetBackoff() {
MutexLock lock(&mu_);
backoff_.Reset();
@@ -965,21 +965,21 @@ const char* SubchannelConnectivityStateChangeString(
} // namespace
-// Note: Must be called with a state that is different from the current state.
+// Note: Must be called with a state that is different from the current state.
void Subchannel::SetConnectivityStateLocked(grpc_connectivity_state state,
const y_absl::Status& status) {
- state_ = state;
+ state_ = state;
status_ = status;
if (channelz_node_ != nullptr) {
- channelz_node_->UpdateConnectivityState(state);
+ channelz_node_->UpdateConnectivityState(state);
channelz_node_->AddTraceEvent(
channelz::ChannelTrace::Severity::Info,
grpc_slice_from_static_string(
SubchannelConnectivityStateChangeString(state)));
}
- // Notify non-health watchers.
+ // Notify non-health watchers.
watcher_list_.NotifyLocked(this, state, status);
- // Notify health watchers.
+ // Notify health watchers.
health_watcher_map_.NotifyLocked(state, status);
}
@@ -1020,9 +1020,9 @@ void Subchannel::MaybeStartConnectingLocked() {
void Subchannel::OnRetryAlarm(void* arg, grpc_error* error) {
Subchannel* c = static_cast<Subchannel*>(arg);
- // TODO(soheilhy): Once subchannel refcounting is simplified, we can get use
- // MutexLock instead of ReleasableMutexLock, here.
- ReleasableMutexLock lock(&c->mu_);
+ // TODO(soheilhy): Once subchannel refcounting is simplified, we can get use
+ // MutexLock instead of ReleasableMutexLock, here.
+ ReleasableMutexLock lock(&c->mu_);
c->have_retry_alarm_ = false;
if (c->disconnected_) {
error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Disconnected",
@@ -1036,16 +1036,16 @@ void Subchannel::OnRetryAlarm(void* arg, grpc_error* error) {
if (error == GRPC_ERROR_NONE) {
gpr_log(GPR_INFO, "Failed to connect to channel, retrying");
c->ContinueConnectingLocked();
- lock.Unlock();
+ lock.Unlock();
} else {
- lock.Unlock();
+ lock.Unlock();
GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting");
}
GRPC_ERROR_UNREF(error);
}
void Subchannel::ContinueConnectingLocked() {
- SubchannelConnector::Args args;
+ SubchannelConnector::Args args;
args.interested_parties = pollset_set_;
const grpc_millis min_deadline =
min_connect_timeout_ms_ + ExecCtx::Get()->Now();
@@ -1053,28 +1053,28 @@ void Subchannel::ContinueConnectingLocked() {
args.deadline = std::max(next_attempt_deadline_, min_deadline);
args.channel_args = args_;
SetConnectivityStateLocked(GRPC_CHANNEL_CONNECTING, y_absl::Status());
- connector_->Connect(args, &connecting_result_, &on_connecting_finished_);
+ connector_->Connect(args, &connecting_result_, &on_connecting_finished_);
}
void Subchannel::OnConnectingFinished(void* arg, grpc_error* error) {
auto* c = static_cast<Subchannel*>(arg);
- const grpc_channel_args* delete_channel_args =
- c->connecting_result_.channel_args;
+ const grpc_channel_args* delete_channel_args =
+ c->connecting_result_.channel_args;
GRPC_SUBCHANNEL_WEAK_REF(c, "on_connecting_finished");
- {
- MutexLock lock(&c->mu_);
- c->connecting_ = false;
- if (c->connecting_result_.transport != nullptr &&
- c->PublishTransportLocked()) {
- // Do nothing, transport was published.
- } else if (c->disconnected_) {
- GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting");
- } else {
- gpr_log(GPR_INFO, "Connect failed: %s", grpc_error_string(error));
+ {
+ MutexLock lock(&c->mu_);
+ c->connecting_ = false;
+ if (c->connecting_result_.transport != nullptr &&
+ c->PublishTransportLocked()) {
+ // Do nothing, transport was published.
+ } else if (c->disconnected_) {
+ GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting");
+ } else {
+ gpr_log(GPR_INFO, "Connect failed: %s", grpc_error_string(error));
c->SetConnectivityStateLocked(GRPC_CHANNEL_TRANSIENT_FAILURE,
grpc_error_to_absl_status(error));
- GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting");
- }
+ GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting");
+ }
}
GRPC_SUBCHANNEL_WEAK_UNREF(c, "on_connecting_finished");
grpc_channel_args_destroy(delete_channel_args);
@@ -1082,7 +1082,7 @@ void Subchannel::OnConnectingFinished(void* arg, grpc_error* error) {
namespace {
-void ConnectionDestroy(void* arg, grpc_error* /*error*/) {
+void ConnectionDestroy(void* arg, grpc_error* /*error*/) {
grpc_channel_stack* stk = static_cast<grpc_channel_stack*>(arg);
grpc_channel_stack_destroy(stk);
gpr_free(stk);
@@ -1112,9 +1112,9 @@ bool Subchannel::PublishTransportLocked() {
GRPC_ERROR_UNREF(error);
return false;
}
- RefCountedPtr<channelz::SocketNode> socket =
- std::move(connecting_result_.socket_node);
- connecting_result_.Reset();
+ RefCountedPtr<channelz::SocketNode> socket =
+ std::move(connecting_result_.socket_node);
+ connecting_result_.Reset();
if (disconnected_) {
grpc_channel_stack_destroy(stk);
gpr_free(stk);
@@ -1122,16 +1122,16 @@ bool Subchannel::PublishTransportLocked() {
}
// Publish.
connected_subchannel_.reset(
- new ConnectedSubchannel(stk, args_, channelz_node_));
+ new ConnectedSubchannel(stk, args_, channelz_node_));
gpr_log(GPR_INFO, "New connected subchannel at %p for subchannel %p",
connected_subchannel_.get(), this);
- if (channelz_node_ != nullptr) {
- channelz_node_->SetChildSocket(std::move(socket));
- }
- // Start watching connected subchannel.
- connected_subchannel_->StartWatch(
- pollset_set_, MakeOrphanable<ConnectedSubchannelStateWatcher>(this));
- // Report initial state.
+ if (channelz_node_ != nullptr) {
+ channelz_node_->SetChildSocket(std::move(socket));
+ }
+ // Start watching connected subchannel.
+ connected_subchannel_->StartWatch(
+ pollset_set_, MakeOrphanable<ConnectedSubchannelStateWatcher>(this));
+ // Report initial state.
SetConnectivityStateLocked(GRPC_CHANNEL_READY, y_absl::Status());
return true;
}
@@ -1146,9 +1146,9 @@ void Subchannel::Disconnect() {
MutexLock lock(&mu_);
GPR_ASSERT(!disconnected_);
disconnected_ = true;
- connector_.reset();
+ connector_.reset();
connected_subchannel_.reset();
- health_watcher_map_.ShutdownLocked();
+ health_watcher_map_.ShutdownLocked();
}
gpr_atm Subchannel::RefMutate(
@@ -1156,7 +1156,7 @@ gpr_atm Subchannel::RefMutate(
gpr_atm old_val = barrier ? gpr_atm_full_fetch_add(&ref_pair_, delta)
: gpr_atm_no_barrier_fetch_add(&ref_pair_, delta);
#ifndef NDEBUG
- if (grpc_trace_subchannel_refcount.enabled()) {
+ if (grpc_trace_subchannel_refcount.enabled()) {
gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
"SUBCHANNEL: %p %12s 0x%" PRIxPTR " -> 0x%" PRIxPTR " [%s]", this,
purpose, old_val, old_val + delta, reason);
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h
index 0ced846c38..817cf11863 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h
@@ -28,12 +28,12 @@
#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h"
#include "src/core/lib/backoff/backoff.h"
#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/gpr/time_precise.h"
-#include "src/core/lib/gprpp/arena.h"
-#include "src/core/lib/gprpp/map.h"
+#include "src/core/lib/gpr/time_precise.h"
+#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/transport/connectivity_state.h"
@@ -45,7 +45,7 @@
// For debugging refcounting.
#ifndef NDEBUG
#define GRPC_SUBCHANNEL_REF(p, r) (p)->Ref(__FILE__, __LINE__, (r))
-#define GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(p, r) (p)->RefFromWeakRef()
+#define GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(p, r) (p)->RefFromWeakRef()
#define GRPC_SUBCHANNEL_UNREF(p, r) (p)->Unref(__FILE__, __LINE__, (r))
#define GRPC_SUBCHANNEL_WEAK_REF(p, r) (p)->WeakRef(__FILE__, __LINE__, (r))
#define GRPC_SUBCHANNEL_WEAK_UNREF(p, r) (p)->WeakUnref(__FILE__, __LINE__, (r))
@@ -75,12 +75,12 @@ class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> {
public:
ConnectedSubchannel(
grpc_channel_stack* channel_stack, const grpc_channel_args* args,
- RefCountedPtr<channelz::SubchannelNode> channelz_subchannel);
+ RefCountedPtr<channelz::SubchannelNode> channelz_subchannel);
~ConnectedSubchannel();
- void StartWatch(grpc_pollset_set* interested_parties,
- OrphanablePtr<ConnectivityStateWatcherInterface> watcher);
-
+ void StartWatch(grpc_pollset_set* interested_parties,
+ OrphanablePtr<ConnectivityStateWatcherInterface> watcher);
+
void Ping(grpc_closure* on_initiate, grpc_closure* on_ack);
grpc_channel_stack* channel_stack() const { return channel_stack_; }
@@ -102,18 +102,18 @@ class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> {
// Implements the interface of RefCounted<>.
class SubchannelCall {
public:
- struct Args {
- RefCountedPtr<ConnectedSubchannel> connected_subchannel;
- grpc_polling_entity* pollent;
- grpc_slice path;
- gpr_cycle_counter start_time;
- grpc_millis deadline;
- Arena* arena;
- grpc_call_context_element* context;
- CallCombiner* call_combiner;
- size_t parent_data_size;
- };
- static RefCountedPtr<SubchannelCall> Create(Args args, grpc_error** error);
+ struct Args {
+ RefCountedPtr<ConnectedSubchannel> connected_subchannel;
+ grpc_polling_entity* pollent;
+ grpc_slice path;
+ gpr_cycle_counter start_time;
+ grpc_millis deadline;
+ Arena* arena;
+ grpc_call_context_element* context;
+ CallCombiner* call_combiner;
+ size_t parent_data_size;
+ };
+ static RefCountedPtr<SubchannelCall> Create(Args args, grpc_error** error);
// Continues processing a transport stream op batch.
void StartTransportStreamOpBatch(grpc_transport_stream_op_batch* batch);
@@ -146,8 +146,8 @@ class SubchannelCall {
template <typename T>
friend class RefCountedPtr;
- SubchannelCall(Args args, grpc_error** error);
-
+ SubchannelCall(Args args, grpc_error** error);
+
// If channelz is enabled, intercepts recv_trailing so that we may check the
// status and associate it to a subchannel.
void MaybeInterceptRecvTrailingMetadata(
@@ -170,27 +170,27 @@ class SubchannelCall {
// A subchannel that knows how to connect to exactly one target address. It
// provides a target for load balancing.
-//
-// Note that this is the "real" subchannel implementation, whose API is
-// different from the SubchannelInterface that is exposed to LB policy
-// implementations. The client channel provides an adaptor class
-// (SubchannelWrapper) that "converts" between the two.
+//
+// Note that this is the "real" subchannel implementation, whose API is
+// different from the SubchannelInterface that is exposed to LB policy
+// implementations. The client channel provides an adaptor class
+// (SubchannelWrapper) that "converts" between the two.
class Subchannel {
public:
- class ConnectivityStateWatcherInterface
+ class ConnectivityStateWatcherInterface
: public RefCounted<ConnectivityStateWatcherInterface> {
- public:
+ public:
struct ConnectivityStateChange {
grpc_connectivity_state state;
y_absl::Status status;
RefCountedPtr<ConnectedSubchannel> connected_subchannel;
};
- virtual ~ConnectivityStateWatcherInterface() = default;
-
- // Will be invoked whenever the subchannel's connectivity state
- // changes. There will be only one invocation of this method on a
- // given watcher instance at any given time.
+ virtual ~ConnectivityStateWatcherInterface() = default;
+
+ // Will be invoked whenever the subchannel's connectivity state
+ // changes. There will be only one invocation of this method on a
+ // given watcher instance at any given time.
// Implementations should call PopConnectivityStateChange to get the next
// connectivity state change.
virtual void OnConnectivityStateChange() = 0;
@@ -198,15 +198,15 @@ class Subchannel {
virtual grpc_pollset_set* interested_parties() = 0;
// Enqueues connectivity state change notifications.
- // When the state changes to READY, connected_subchannel will
- // contain a ref to the connected subchannel. When it changes from
- // READY to some other state, the implementation must release its
- // ref to the connected subchannel.
+ // When the state changes to READY, connected_subchannel will
+ // contain a ref to the connected subchannel. When it changes from
+ // READY to some other state, the implementation must release its
+ // ref to the connected subchannel.
// TODO(yashkt): This is currently needed to send the state updates in the
// right order when asynchronously notifying. This will no longer be
// necessary when we have access to EventManager.
void PushConnectivityStateChange(ConnectivityStateChange state_change);
-
+
// Dequeues connectivity state change notifications.
ConnectivityStateChange PopConnectivityStateChange();
@@ -217,15 +217,15 @@ class Subchannel {
// necessary when we have access to EventManager.
std::deque<ConnectivityStateChange> connectivity_state_queue_;
Mutex mu_; // protects the queue
- };
-
+ };
+
// The ctor and dtor are not intended to use directly.
- Subchannel(SubchannelKey* key, OrphanablePtr<SubchannelConnector> connector,
+ Subchannel(SubchannelKey* key, OrphanablePtr<SubchannelConnector> connector,
const grpc_channel_args* args);
~Subchannel();
// Creates a subchannel given \a connector and \a args.
- static Subchannel* Create(OrphanablePtr<SubchannelConnector> connector,
+ static Subchannel* Create(OrphanablePtr<SubchannelConnector> connector,
const grpc_channel_args* args);
// Throttles keepalive time to \a new_keepalive_time iff \a new_keepalive_time
@@ -238,49 +238,49 @@ class Subchannel {
void Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS);
Subchannel* WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS);
void WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS);
- // Attempts to return a strong ref when only the weak refcount is guaranteed
- // non-zero. If the strong refcount is zero, does not alter the refcount and
- // returns null.
- Subchannel* RefFromWeakRef();
+ // Attempts to return a strong ref when only the weak refcount is guaranteed
+ // non-zero. If the strong refcount is zero, does not alter the refcount and
+ // returns null.
+ Subchannel* RefFromWeakRef();
// Gets the string representing the subchannel address.
// Caller doesn't take ownership.
const char* GetTargetAddress();
- const grpc_channel_args* channel_args() const { return args_; }
+ const grpc_channel_args* channel_args() const { return args_; }
channelz::SubchannelNode* channelz_node();
- // Returns the current connectivity state of the subchannel.
- // If health_check_service_name is non-null, the returned connectivity
- // state will be based on the state reported by the backend for that
- // service name.
- // If the return value is GRPC_CHANNEL_READY, also sets *connected_subchannel.
- grpc_connectivity_state CheckConnectivityState(
- const char* health_check_service_name,
- RefCountedPtr<ConnectedSubchannel>* connected_subchannel);
-
- // Starts watching the subchannel's connectivity state.
- // The first callback to the watcher will be delivered when the
- // subchannel's connectivity state becomes a value other than
- // initial_state, which may happen immediately.
- // Subsequent callbacks will be delivered as the subchannel's state
- // changes.
- // The watcher will be destroyed either when the subchannel is
- // destroyed or when CancelConnectivityStateWatch() is called.
- void WatchConnectivityState(
- grpc_connectivity_state initial_state,
- grpc_core::UniquePtr<char> health_check_service_name,
+ // Returns the current connectivity state of the subchannel.
+ // If health_check_service_name is non-null, the returned connectivity
+ // state will be based on the state reported by the backend for that
+ // service name.
+ // If the return value is GRPC_CHANNEL_READY, also sets *connected_subchannel.
+ grpc_connectivity_state CheckConnectivityState(
+ const char* health_check_service_name,
+ RefCountedPtr<ConnectedSubchannel>* connected_subchannel);
+
+ // Starts watching the subchannel's connectivity state.
+ // The first callback to the watcher will be delivered when the
+ // subchannel's connectivity state becomes a value other than
+ // initial_state, which may happen immediately.
+ // Subsequent callbacks will be delivered as the subchannel's state
+ // changes.
+ // The watcher will be destroyed either when the subchannel is
+ // destroyed or when CancelConnectivityStateWatch() is called.
+ void WatchConnectivityState(
+ grpc_connectivity_state initial_state,
+ grpc_core::UniquePtr<char> health_check_service_name,
RefCountedPtr<ConnectivityStateWatcherInterface> watcher);
- // Cancels a connectivity state watch.
- // If the watcher has already been destroyed, this is a no-op.
- void CancelConnectivityStateWatch(const char* health_check_service_name,
- ConnectivityStateWatcherInterface* watcher);
-
- // Attempt to connect to the backend. Has no effect if already connected.
- void AttemptToConnect();
-
+ // Cancels a connectivity state watch.
+ // If the watcher has already been destroyed, this is a no-op.
+ void CancelConnectivityStateWatch(const char* health_check_service_name,
+ ConnectivityStateWatcherInterface* watcher);
+
+ // Attempt to connect to the backend. Has no effect if already connected.
+ void AttemptToConnect();
+
// Resets the connection backoff of the subchannel.
// TODO(roth): Move connection backoff out of subchannels and up into LB
// policy code (probably by adding a SubchannelGroup between
@@ -301,65 +301,65 @@ class Subchannel {
grpc_resolved_address* addr);
private:
- // A linked list of ConnectivityStateWatcherInterfaces that are monitoring
- // the subchannel's state.
- class ConnectivityStateWatcherList {
- public:
- ~ConnectivityStateWatcherList() { Clear(); }
-
- void AddWatcherLocked(
+ // A linked list of ConnectivityStateWatcherInterfaces that are monitoring
+ // the subchannel's state.
+ class ConnectivityStateWatcherList {
+ public:
+ ~ConnectivityStateWatcherList() { Clear(); }
+
+ void AddWatcherLocked(
RefCountedPtr<ConnectivityStateWatcherInterface> watcher);
- void RemoveWatcherLocked(ConnectivityStateWatcherInterface* watcher);
-
- // Notifies all watchers in the list about a change to state.
+ void RemoveWatcherLocked(ConnectivityStateWatcherInterface* watcher);
+
+ // Notifies all watchers in the list about a change to state.
void NotifyLocked(Subchannel* subchannel, grpc_connectivity_state state,
const y_absl::Status& status);
-
- void Clear() { watchers_.clear(); }
-
- bool empty() const { return watchers_.empty(); }
-
- private:
- // TODO(roth): Once we can use C++-14 heterogeneous lookups, this can
- // be a set instead of a map.
- std::map<ConnectivityStateWatcherInterface*,
+
+ void Clear() { watchers_.clear(); }
+
+ bool empty() const { return watchers_.empty(); }
+
+ private:
+ // TODO(roth): Once we can use C++-14 heterogeneous lookups, this can
+ // be a set instead of a map.
+ std::map<ConnectivityStateWatcherInterface*,
RefCountedPtr<ConnectivityStateWatcherInterface>>
- watchers_;
- };
-
- // A map that tracks ConnectivityStateWatcherInterfaces using a particular
- // health check service name.
- //
- // There is one entry in the map for each health check service name.
- // Entries exist only as long as there are watchers using the
- // corresponding service name.
- //
- // A health check client is maintained only while the subchannel is in
- // state READY.
- class HealthWatcherMap {
- public:
- void AddWatcherLocked(
- Subchannel* subchannel, grpc_connectivity_state initial_state,
- grpc_core::UniquePtr<char> health_check_service_name,
+ watchers_;
+ };
+
+ // A map that tracks ConnectivityStateWatcherInterfaces using a particular
+ // health check service name.
+ //
+ // There is one entry in the map for each health check service name.
+ // Entries exist only as long as there are watchers using the
+ // corresponding service name.
+ //
+ // A health check client is maintained only while the subchannel is in
+ // state READY.
+ class HealthWatcherMap {
+ public:
+ void AddWatcherLocked(
+ Subchannel* subchannel, grpc_connectivity_state initial_state,
+ grpc_core::UniquePtr<char> health_check_service_name,
RefCountedPtr<ConnectivityStateWatcherInterface> watcher);
- void RemoveWatcherLocked(const char* health_check_service_name,
- ConnectivityStateWatcherInterface* watcher);
-
- // Notifies the watcher when the subchannel's state changes.
+ void RemoveWatcherLocked(const char* health_check_service_name,
+ ConnectivityStateWatcherInterface* watcher);
+
+ // Notifies the watcher when the subchannel's state changes.
void NotifyLocked(grpc_connectivity_state state,
const y_absl::Status& status);
-
- grpc_connectivity_state CheckConnectivityStateLocked(
- Subchannel* subchannel, const char* health_check_service_name);
-
- void ShutdownLocked();
-
- private:
- class HealthWatcher;
-
- std::map<const char*, OrphanablePtr<HealthWatcher>, StringLess> map_;
- };
-
+
+ grpc_connectivity_state CheckConnectivityStateLocked(
+ Subchannel* subchannel, const char* health_check_service_name);
+
+ void ShutdownLocked();
+
+ private:
+ class HealthWatcher;
+
+ std::map<const char*, OrphanablePtr<HealthWatcher>, StringLess> map_;
+ };
+
class ConnectedSubchannelStateWatcher;
class AsyncWatcherNotifierLocked;
@@ -389,7 +389,7 @@ class Subchannel {
// pollset_set tracking who's interested in a connection being setup.
grpc_pollset_set* pollset_set_;
// Protects the other members.
- Mutex mu_;
+ Mutex mu_;
// Refcount
// - lower INTERNAL_REF_BITS bits are for internal references:
// these do not keep the subchannel open.
@@ -398,9 +398,9 @@ class Subchannel {
gpr_atm ref_pair_;
// Connection states.
- OrphanablePtr<SubchannelConnector> connector_;
+ OrphanablePtr<SubchannelConnector> connector_;
// Set during connection.
- SubchannelConnector::Result connecting_result_;
+ SubchannelConnector::Result connecting_result_;
grpc_closure on_connecting_finished_;
// Active connection, or null.
RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
@@ -408,12 +408,12 @@ class Subchannel {
bool disconnected_ = false;
// Connectivity state tracking.
- grpc_connectivity_state state_ = GRPC_CHANNEL_IDLE;
+ grpc_connectivity_state state_ = GRPC_CHANNEL_IDLE;
y_absl::Status status_;
- // The list of watchers without a health check service name.
- ConnectivityStateWatcherList watcher_list_;
- // The map of watchers with health check service names.
- HealthWatcherMap health_watcher_map_;
+ // The list of watchers without a health check service name.
+ ConnectivityStateWatcherList watcher_list_;
+ // The map of watchers with health check service names.
+ HealthWatcherMap health_watcher_map_;
// Backoff state.
BackOff backoff_;
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_interface.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_interface.h
index ccaca4ef08..04f3d6974a 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_interface.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_interface.h
@@ -1,100 +1,100 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INTERFACE_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INTERFACE_H
-
-#include <grpc/support/port_platform.h>
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INTERFACE_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INTERFACE_H
+
+#include <grpc/support/port_platform.h>
+
#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
-
-namespace grpc_core {
-
-// The interface for subchannels that is exposed to LB policy implementations.
-class SubchannelInterface : public RefCounted<SubchannelInterface> {
- public:
- class ConnectivityStateWatcherInterface {
- public:
- virtual ~ConnectivityStateWatcherInterface() = default;
-
- // Will be invoked whenever the subchannel's connectivity state
- // changes. There will be only one invocation of this method on a
- // given watcher instance at any given time.
- virtual void OnConnectivityStateChange(
- grpc_connectivity_state new_state) = 0;
-
- // TODO(roth): Remove this as soon as we move to EventManager-based
- // polling.
- virtual grpc_pollset_set* interested_parties() = 0;
- };
-
- template <typename TraceFlagT = TraceFlag>
- explicit SubchannelInterface(TraceFlagT* trace_flag = nullptr)
- : RefCounted<SubchannelInterface>(trace_flag) {}
-
- virtual ~SubchannelInterface() = default;
-
- // Returns the current connectivity state of the subchannel.
- virtual grpc_connectivity_state CheckConnectivityState() = 0;
-
- // Starts watching the subchannel's connectivity state.
- // The first callback to the watcher will be delivered when the
- // subchannel's connectivity state becomes a value other than
- // initial_state, which may happen immediately.
- // Subsequent callbacks will be delivered as the subchannel's state
- // changes.
- // The watcher will be destroyed either when the subchannel is
- // destroyed or when CancelConnectivityStateWatch() is called.
- // There can be only one watcher of a given subchannel. It is not
- // valid to call this method a second time without first cancelling
- // the previous watcher using CancelConnectivityStateWatch().
- virtual void WatchConnectivityState(
- grpc_connectivity_state initial_state,
- std::unique_ptr<ConnectivityStateWatcherInterface> watcher) = 0;
-
- // Cancels a connectivity state watch.
- // If the watcher has already been destroyed, this is a no-op.
- virtual void CancelConnectivityStateWatch(
- ConnectivityStateWatcherInterface* watcher) = 0;
-
- // Attempt to connect to the backend. Has no effect if already connected.
- // If the subchannel is currently in backoff delay due to a previously
- // failed attempt, the new connection attempt will not start until the
- // backoff delay has elapsed.
- virtual void AttemptToConnect() = 0;
-
- // Resets the subchannel's connection backoff state. If AttemptToConnect()
- // has been called since the subchannel entered TRANSIENT_FAILURE state,
- // starts a new connection attempt immediately; otherwise, a new connection
- // attempt will be started as soon as AttemptToConnect() is called.
- virtual void ResetBackoff() = 0;
-
- // TODO(roth): Need a better non-grpc-specific abstraction here.
- virtual const grpc_channel_args* channel_args() = 0;
+#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+
+namespace grpc_core {
+
+// The interface for subchannels that is exposed to LB policy implementations.
+class SubchannelInterface : public RefCounted<SubchannelInterface> {
+ public:
+ class ConnectivityStateWatcherInterface {
+ public:
+ virtual ~ConnectivityStateWatcherInterface() = default;
+
+ // Will be invoked whenever the subchannel's connectivity state
+ // changes. There will be only one invocation of this method on a
+ // given watcher instance at any given time.
+ virtual void OnConnectivityStateChange(
+ grpc_connectivity_state new_state) = 0;
+
+ // TODO(roth): Remove this as soon as we move to EventManager-based
+ // polling.
+ virtual grpc_pollset_set* interested_parties() = 0;
+ };
+
+ template <typename TraceFlagT = TraceFlag>
+ explicit SubchannelInterface(TraceFlagT* trace_flag = nullptr)
+ : RefCounted<SubchannelInterface>(trace_flag) {}
+
+ virtual ~SubchannelInterface() = default;
+
+ // Returns the current connectivity state of the subchannel.
+ virtual grpc_connectivity_state CheckConnectivityState() = 0;
+
+ // Starts watching the subchannel's connectivity state.
+ // The first callback to the watcher will be delivered when the
+ // subchannel's connectivity state becomes a value other than
+ // initial_state, which may happen immediately.
+ // Subsequent callbacks will be delivered as the subchannel's state
+ // changes.
+ // The watcher will be destroyed either when the subchannel is
+ // destroyed or when CancelConnectivityStateWatch() is called.
+ // There can be only one watcher of a given subchannel. It is not
+ // valid to call this method a second time without first cancelling
+ // the previous watcher using CancelConnectivityStateWatch().
+ virtual void WatchConnectivityState(
+ grpc_connectivity_state initial_state,
+ std::unique_ptr<ConnectivityStateWatcherInterface> watcher) = 0;
+
+ // Cancels a connectivity state watch.
+ // If the watcher has already been destroyed, this is a no-op.
+ virtual void CancelConnectivityStateWatch(
+ ConnectivityStateWatcherInterface* watcher) = 0;
+
+ // Attempt to connect to the backend. Has no effect if already connected.
+ // If the subchannel is currently in backoff delay due to a previously
+ // failed attempt, the new connection attempt will not start until the
+ // backoff delay has elapsed.
+ virtual void AttemptToConnect() = 0;
+
+ // Resets the subchannel's connection backoff state. If AttemptToConnect()
+ // has been called since the subchannel entered TRANSIENT_FAILURE state,
+ // starts a new connection attempt immediately; otherwise, a new connection
+ // attempt will be started as soon as AttemptToConnect() is called.
+ virtual void ResetBackoff() = 0;
+
+ // TODO(roth): Need a better non-grpc-specific abstraction here.
+ virtual const grpc_channel_args* channel_args() = 0;
// Allows accessing the attributes associated with the address for
// this subchannel.
virtual const ServerAddress::AttributeInterface* GetAttribute(
const char* key) const = 0;
-};
-
+};
+
// A class that delegates to another subchannel, to be used in cases
// where an LB policy needs to wrap a subchannel.
class DelegatingSubchannel : public SubchannelInterface {
@@ -133,6 +133,6 @@ class DelegatingSubchannel : public SubchannelInterface {
RefCountedPtr<SubchannelInterface> wrapped_subchannel_;
};
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INTERFACE_H */
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INTERFACE_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h
index 2fe5fa3fd0..5134625cdd 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h
@@ -69,14 +69,14 @@ class SubchannelPoolInterface : public RefCounted<SubchannelPoolInterface> {
// with \a key, which may be different from \a constructed because we reuse
// (instead of update) any existing subchannel already registered with \a key.
virtual Subchannel* RegisterSubchannel(SubchannelKey* key,
- Subchannel* constructed) = 0;
+ Subchannel* constructed) = 0;
// Removes the registered subchannel found by \a key.
- virtual void UnregisterSubchannel(SubchannelKey* key) = 0;
+ virtual void UnregisterSubchannel(SubchannelKey* key) = 0;
// Finds the subchannel registered for the given subchannel key. Returns NULL
// if no such channel exists. Thread-safe.
- virtual Subchannel* FindSubchannel(SubchannelKey* key) = 0;
+ virtual Subchannel* FindSubchannel(SubchannelKey* key) = 0;
// Creates a channel arg from \a subchannel pool.
static grpc_arg CreateChannelArg(SubchannelPoolInterface* subchannel_pool);
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_idle/client_idle_filter.cc b/contrib/libs/grpc/src/core/ext/filters/client_idle/client_idle_filter.cc
index 2ea3eadeec..b92a0274dd 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_idle/client_idle_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/client_idle/client_idle_filter.cc
@@ -1,440 +1,440 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <limits.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channel_stack_builder.h"
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/http2_errors.h"
-
-// TODO(juanlishen): The idle filter is disabled in client channel by default
-// due to b/143502997. Try to fix the bug and enable the filter by default.
-#define DEFAULT_IDLE_TIMEOUT_MS INT_MAX
-// The user input idle timeout smaller than this would be capped to it.
-#define MIN_IDLE_TIMEOUT_MS (1 /*second*/ * 1000)
-
-namespace grpc_core {
-
-TraceFlag grpc_trace_client_idle_filter(false, "client_idle_filter");
-
-#define GRPC_IDLE_FILTER_LOG(format, ...) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_client_idle_filter)) { \
- gpr_log(GPR_INFO, "(client idle filter) " format, ##__VA_ARGS__); \
- } \
- } while (0)
-
-namespace {
-
-/*
- client_idle_filter maintains a state tracking if there are active calls in the
- channel and its internal idle_timer_. The states are specified as following:
-
- +--------------------------------------------+-------------+---------+
- | ChannelState | idle_timer_ | channel |
- +--------------------------------------------+-------------+---------+
- | IDLE | unset | idle |
- | CALLS_ACTIVE | unset | busy |
- | TIMER_PENDING | set-valid | idle |
- | TIMER_PENDING_CALLS_ACTIVE | set-invalid | busy |
- | TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START | set-invalid | idle |
- +--------------------------------------------+-------------+---------+
-
- IDLE: The initial state of the client_idle_filter, indicating the channel is
- in IDLE.
-
- CALLS_ACTIVE: The channel has 1 or 1+ active calls and the timer is not set.
-
- TIMER_PENDING: The state after the timer is set and no calls have arrived
- after the timer is set. The channel must have 0 active call in this state. If
- the timer is fired in this state, the channel will go into IDLE state.
-
- TIMER_PENDING_CALLS_ACTIVE: The state after the timer is set and at least one
- call has arrived after the timer is set. The channel must have 1 or 1+ active
- calls in this state. If the timer is fired in this state, we won't reschedule
- it.
-
- TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START: The state after the timer is set
- and at least one call has arrived after the timer is set, BUT the channel
- currently has 0 active call. If the timer is fired in this state, we will
- reschedule it according to the finish time of the latest call.
-
- PROCESSING: The state set to block other threads when the setting thread is
- doing some work to keep state consistency.
-
- idle_timer_ will not be cancelled (unless the channel is shutting down).
- If the timer callback is called when the idle_timer_ is valid (i.e. idle_state
- is TIMER_PENDING), the channel will enter IDLE, otherwise the channel won't be
- changed.
-
- State transitions:
- IDLE
- | ^
- --------------------------------- *
- | *
- v *
- CALLS_ACTIVE =================> TIMER_PENDING
- ^ | ^
- * ------------------------------ *
- * | *
- * v *
-TIMER_PENDING_CALLS_ACTIVE ===> TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START
- ^ |
- | |
- ---------------------------------
-
- ---> Triggered by IncreaseCallCount()
- ===> Triggered by DecreaseCallCount()
- ***> Triggered by IdleTimerCallback()
-*/
-enum ChannelState {
- IDLE,
- CALLS_ACTIVE,
- TIMER_PENDING,
- TIMER_PENDING_CALLS_ACTIVE,
- TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START,
- PROCESSING
-};
-
-grpc_millis GetClientIdleTimeout(const grpc_channel_args* args) {
- return GPR_MAX(
- grpc_channel_arg_get_integer(
- grpc_channel_args_find(args, GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS),
- {DEFAULT_IDLE_TIMEOUT_MS, 0, INT_MAX}),
- MIN_IDLE_TIMEOUT_MS);
-}
-
-class ChannelData {
- public:
- static grpc_error* Init(grpc_channel_element* elem,
- grpc_channel_element_args* args);
- static void Destroy(grpc_channel_element* elem);
-
- static void StartTransportOp(grpc_channel_element* elem,
- grpc_transport_op* op);
-
- void IncreaseCallCount();
-
- void DecreaseCallCount();
-
- private:
- ChannelData(grpc_channel_element* elem, grpc_channel_element_args* args,
- grpc_error** error);
- ~ChannelData() = default;
-
- static void IdleTimerCallback(void* arg, grpc_error* error);
- static void IdleTransportOpCompleteCallback(void* arg, grpc_error* error);
-
- void StartIdleTimer();
-
- void EnterIdle();
-
- grpc_channel_element* elem_;
- // The channel stack to which we take refs for pending callbacks.
- grpc_channel_stack* channel_stack_;
- // Timeout after the last RPC finishes on the client channel at which the
- // channel goes back into IDLE state.
- const grpc_millis client_idle_timeout_;
-
- // Member data used to track the state of channel.
- grpc_millis last_idle_time_;
- Atomic<intptr_t> call_count_{0};
- Atomic<ChannelState> state_{IDLE};
-
- // Idle timer and its callback closure.
- grpc_timer idle_timer_;
- grpc_closure idle_timer_callback_;
-
- // The transport op telling the client channel to enter IDLE.
- grpc_transport_op idle_transport_op_;
- grpc_closure idle_transport_op_complete_callback_;
-};
-
-grpc_error* ChannelData::Init(grpc_channel_element* elem,
- grpc_channel_element_args* args) {
- grpc_error* error = GRPC_ERROR_NONE;
- new (elem->channel_data) ChannelData(elem, args, &error);
- return error;
-}
-
-void ChannelData::Destroy(grpc_channel_element* elem) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->~ChannelData();
-}
-
-void ChannelData::StartTransportOp(grpc_channel_element* elem,
- grpc_transport_op* op) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- // Catch the disconnect_with_error transport op.
- if (op->disconnect_with_error != nullptr) {
- // IncreaseCallCount() introduces a dummy call and prevent the timer from
- // being reset by other threads.
- chand->IncreaseCallCount();
- // If the timer has been set, cancel the timer.
- // No synchronization issues here. grpc_timer_cancel() is valid as long as
- // the timer has been init()ed before.
- grpc_timer_cancel(&chand->idle_timer_);
- }
- // Pass the op to the next filter.
- grpc_channel_next_op(elem, op);
-}
-
-void ChannelData::IncreaseCallCount() {
- const intptr_t previous_value = call_count_.FetchAdd(1, MemoryOrder::RELAXED);
- GRPC_IDLE_FILTER_LOG("call counter has increased to %" PRIuPTR,
- previous_value + 1);
- if (previous_value == 0) {
- // This call is the one that makes the channel busy.
- // Loop here to make sure the previous decrease operation has finished.
- ChannelState state = state_.Load(MemoryOrder::RELAXED);
- while (true) {
- switch (state) {
- // Timer has not been set. Switch to CALLS_ACTIVE.
- case IDLE:
- // In this case, no other threads will modify the state, so we can
- // just store the value.
- state_.Store(CALLS_ACTIVE, MemoryOrder::RELAXED);
- return;
- // Timer has been set. Switch to TIMER_PENDING_CALLS_ACTIVE.
- case TIMER_PENDING:
- case TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START:
- // At this point, the state may have been switched to IDLE by the
- // idle timer callback. Therefore, use CAS operation to change the
- // state atomically.
- // Use MemoryOrder::ACQUIRE on success to ensure last_idle_time_ has
- // been properly set in DecreaseCallCount().
- if (state_.CompareExchangeWeak(&state, TIMER_PENDING_CALLS_ACTIVE,
- MemoryOrder::ACQUIRE,
- MemoryOrder::RELAXED)) {
- return;
- }
- break;
- default:
- // The state has not been switched to desired value yet, try again.
- state = state_.Load(MemoryOrder::RELAXED);
- break;
- }
- }
- }
-}
-
-void ChannelData::DecreaseCallCount() {
- const intptr_t previous_value = call_count_.FetchSub(1, MemoryOrder::RELAXED);
- GRPC_IDLE_FILTER_LOG("call counter has decreased to %" PRIuPTR,
- previous_value - 1);
- if (previous_value == 1) {
- // This call is the one that makes the channel idle.
- // last_idle_time_ does not need to be Atomic<> because busy-loops in
- // IncreaseCallCount(), DecreaseCallCount() and IdleTimerCallback() will
- // prevent multiple threads from simultaneously accessing this variable.
- last_idle_time_ = ExecCtx::Get()->Now();
- ChannelState state = state_.Load(MemoryOrder::RELAXED);
- while (true) {
- switch (state) {
- // Timer has not been set. Set the timer and switch to TIMER_PENDING
- case CALLS_ACTIVE:
- // Release store here to make other threads see the updated value of
- // last_idle_time_.
- StartIdleTimer();
- state_.Store(TIMER_PENDING, MemoryOrder::RELEASE);
- return;
- // Timer has been set. Switch to
- // TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START
- case TIMER_PENDING_CALLS_ACTIVE:
- // At this point, the state may have been switched to CALLS_ACTIVE by
- // the idle timer callback. Therefore, use CAS operation to change the
- // state atomically.
- // Release store here to make the idle timer callback see the updated
- // value of last_idle_time_ to properly reset the idle timer.
- if (state_.CompareExchangeWeak(
- &state, TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START,
- MemoryOrder::RELEASE, MemoryOrder::RELAXED)) {
- return;
- }
- break;
- default:
- // The state has not been switched to desired value yet, try again.
- state = state_.Load(MemoryOrder::RELAXED);
- break;
- }
- }
- }
-}
-
-ChannelData::ChannelData(grpc_channel_element* elem,
- grpc_channel_element_args* args,
- grpc_error** /*error*/)
- : elem_(elem),
- channel_stack_(args->channel_stack),
- client_idle_timeout_(GetClientIdleTimeout(args->channel_args)) {
- // If the idle filter is explicitly disabled in channel args, this ctor should
- // not get called.
- GPR_ASSERT(client_idle_timeout_ != GRPC_MILLIS_INF_FUTURE);
- GRPC_IDLE_FILTER_LOG("created with max_leisure_time = %" PRId64 " ms",
- client_idle_timeout_);
- // Initialize the idle timer without setting it.
- grpc_timer_init_unset(&idle_timer_);
- // Initialize the idle timer callback closure.
- GRPC_CLOSURE_INIT(&idle_timer_callback_, IdleTimerCallback, this,
- grpc_schedule_on_exec_ctx);
- // Initialize the idle transport op complete callback.
- GRPC_CLOSURE_INIT(&idle_transport_op_complete_callback_,
- IdleTransportOpCompleteCallback, this,
- grpc_schedule_on_exec_ctx);
-}
-
-void ChannelData::IdleTimerCallback(void* arg, grpc_error* error) {
- GRPC_IDLE_FILTER_LOG("timer alarms");
- ChannelData* chand = static_cast<ChannelData*>(arg);
- if (error != GRPC_ERROR_NONE) {
- GRPC_IDLE_FILTER_LOG("timer canceled");
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack_, "max idle timer callback");
- return;
- }
- bool finished = false;
- ChannelState state = chand->state_.Load(MemoryOrder::RELAXED);
- while (!finished) {
- switch (state) {
- case TIMER_PENDING:
- // Change the state to PROCESSING to block IncreaseCallCout() until the
- // EnterIdle() operation finishes, preventing mistakenly entering IDLE
- // when active RPC exists.
- finished = chand->state_.CompareExchangeWeak(
- &state, PROCESSING, MemoryOrder::ACQUIRE, MemoryOrder::RELAXED);
- if (finished) {
- chand->EnterIdle();
- chand->state_.Store(IDLE, MemoryOrder::RELAXED);
- }
- break;
- case TIMER_PENDING_CALLS_ACTIVE:
- finished = chand->state_.CompareExchangeWeak(
- &state, CALLS_ACTIVE, MemoryOrder::RELAXED, MemoryOrder::RELAXED);
- break;
- case TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START:
- // Change the state to PROCESSING to block IncreaseCallCount() until the
- // StartIdleTimer() operation finishes, preventing mistakenly restarting
- // the timer after grpc_timer_cancel() when shutdown.
- finished = chand->state_.CompareExchangeWeak(
- &state, PROCESSING, MemoryOrder::ACQUIRE, MemoryOrder::RELAXED);
- if (finished) {
- chand->StartIdleTimer();
- chand->state_.Store(TIMER_PENDING, MemoryOrder::RELAXED);
- }
- break;
- default:
- // The state has not been switched to desired value yet, try again.
- state = chand->state_.Load(MemoryOrder::RELAXED);
- break;
- }
- }
- GRPC_IDLE_FILTER_LOG("timer finishes");
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack_, "max idle timer callback");
-}
-
-void ChannelData::IdleTransportOpCompleteCallback(void* arg,
- grpc_error* /*error*/) {
- ChannelData* chand = static_cast<ChannelData*>(arg);
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack_, "idle transport op");
-}
-
-void ChannelData::StartIdleTimer() {
- GRPC_IDLE_FILTER_LOG("timer has started");
- // Hold a ref to the channel stack for the timer callback.
- GRPC_CHANNEL_STACK_REF(channel_stack_, "max idle timer callback");
- grpc_timer_init(&idle_timer_, last_idle_time_ + client_idle_timeout_,
- &idle_timer_callback_);
-}
-
-void ChannelData::EnterIdle() {
- GRPC_IDLE_FILTER_LOG("the channel will enter IDLE");
- // Hold a ref to the channel stack for the transport op.
- GRPC_CHANNEL_STACK_REF(channel_stack_, "idle transport op");
- // Initialize the transport op.
- idle_transport_op_ = {};
- idle_transport_op_.disconnect_with_error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("enter idle"),
- GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE, GRPC_CHANNEL_IDLE);
- idle_transport_op_.on_consumed = &idle_transport_op_complete_callback_;
- // Pass the transport op down to the channel stack.
- grpc_channel_next_op(elem_, &idle_transport_op_);
-}
-
-class CallData {
- public:
- static grpc_error* Init(grpc_call_element* elem,
- const grpc_call_element_args* args);
- static void Destroy(grpc_call_element* elem,
- const grpc_call_final_info* final_info,
- grpc_closure* then_schedule_closure);
-};
-
-grpc_error* CallData::Init(grpc_call_element* elem,
- const grpc_call_element_args* /*args*/) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->IncreaseCallCount();
- return GRPC_ERROR_NONE;
-}
-
-void CallData::Destroy(grpc_call_element* elem,
- const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->DecreaseCallCount();
-}
-
-const grpc_channel_filter grpc_client_idle_filter = {
- grpc_call_next_op,
- ChannelData::StartTransportOp,
- sizeof(CallData),
- CallData::Init,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
- CallData::Destroy,
- sizeof(ChannelData),
- ChannelData::Init,
- ChannelData::Destroy,
- grpc_channel_next_get_info,
- "client_idle"};
-
-static bool MaybeAddClientIdleFilter(grpc_channel_stack_builder* builder,
- void* /*arg*/) {
- const grpc_channel_args* channel_args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- if (!grpc_channel_args_want_minimal_stack(channel_args) &&
- GetClientIdleTimeout(channel_args) != INT_MAX) {
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_client_idle_filter, nullptr, nullptr);
- } else {
- return true;
- }
-}
-
-} // namespace
-} // namespace grpc_core
-
-void grpc_client_idle_filter_init(void) {
- grpc_channel_init_register_stage(
- GRPC_CLIENT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- grpc_core::MaybeAddClientIdleFilter, nullptr);
-}
-
-void grpc_client_idle_filter_shutdown(void) {}
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <limits.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/channel_stack_builder.h"
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/transport/http2_errors.h"
+
+// TODO(juanlishen): The idle filter is disabled in client channel by default
+// due to b/143502997. Try to fix the bug and enable the filter by default.
+#define DEFAULT_IDLE_TIMEOUT_MS INT_MAX
+// The user input idle timeout smaller than this would be capped to it.
+#define MIN_IDLE_TIMEOUT_MS (1 /*second*/ * 1000)
+
+namespace grpc_core {
+
+TraceFlag grpc_trace_client_idle_filter(false, "client_idle_filter");
+
+#define GRPC_IDLE_FILTER_LOG(format, ...) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_client_idle_filter)) { \
+ gpr_log(GPR_INFO, "(client idle filter) " format, ##__VA_ARGS__); \
+ } \
+ } while (0)
+
+namespace {
+
+/*
+ client_idle_filter maintains a state tracking if there are active calls in the
+ channel and its internal idle_timer_. The states are specified as following:
+
+ +--------------------------------------------+-------------+---------+
+ | ChannelState | idle_timer_ | channel |
+ +--------------------------------------------+-------------+---------+
+ | IDLE | unset | idle |
+ | CALLS_ACTIVE | unset | busy |
+ | TIMER_PENDING | set-valid | idle |
+ | TIMER_PENDING_CALLS_ACTIVE | set-invalid | busy |
+ | TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START | set-invalid | idle |
+ +--------------------------------------------+-------------+---------+
+
+ IDLE: The initial state of the client_idle_filter, indicating the channel is
+ in IDLE.
+
+ CALLS_ACTIVE: The channel has 1 or 1+ active calls and the timer is not set.
+
+ TIMER_PENDING: The state after the timer is set and no calls have arrived
+ after the timer is set. The channel must have 0 active call in this state. If
+ the timer is fired in this state, the channel will go into IDLE state.
+
+ TIMER_PENDING_CALLS_ACTIVE: The state after the timer is set and at least one
+ call has arrived after the timer is set. The channel must have 1 or 1+ active
+ calls in this state. If the timer is fired in this state, we won't reschedule
+ it.
+
+ TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START: The state after the timer is set
+ and at least one call has arrived after the timer is set, BUT the channel
+ currently has 0 active call. If the timer is fired in this state, we will
+ reschedule it according to the finish time of the latest call.
+
+ PROCESSING: The state set to block other threads when the setting thread is
+ doing some work to keep state consistency.
+
+ idle_timer_ will not be cancelled (unless the channel is shutting down).
+ If the timer callback is called when the idle_timer_ is valid (i.e. idle_state
+ is TIMER_PENDING), the channel will enter IDLE, otherwise the channel won't be
+ changed.
+
+ State transitions:
+ IDLE
+ | ^
+ --------------------------------- *
+ | *
+ v *
+ CALLS_ACTIVE =================> TIMER_PENDING
+ ^ | ^
+ * ------------------------------ *
+ * | *
+ * v *
+TIMER_PENDING_CALLS_ACTIVE ===> TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START
+ ^ |
+ | |
+ ---------------------------------
+
+ ---> Triggered by IncreaseCallCount()
+ ===> Triggered by DecreaseCallCount()
+ ***> Triggered by IdleTimerCallback()
+*/
+enum ChannelState {
+ IDLE,
+ CALLS_ACTIVE,
+ TIMER_PENDING,
+ TIMER_PENDING_CALLS_ACTIVE,
+ TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START,
+ PROCESSING
+};
+
+grpc_millis GetClientIdleTimeout(const grpc_channel_args* args) {
+ return GPR_MAX(
+ grpc_channel_arg_get_integer(
+ grpc_channel_args_find(args, GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS),
+ {DEFAULT_IDLE_TIMEOUT_MS, 0, INT_MAX}),
+ MIN_IDLE_TIMEOUT_MS);
+}
+
+class ChannelData {
+ public:
+ static grpc_error* Init(grpc_channel_element* elem,
+ grpc_channel_element_args* args);
+ static void Destroy(grpc_channel_element* elem);
+
+ static void StartTransportOp(grpc_channel_element* elem,
+ grpc_transport_op* op);
+
+ void IncreaseCallCount();
+
+ void DecreaseCallCount();
+
+ private:
+ ChannelData(grpc_channel_element* elem, grpc_channel_element_args* args,
+ grpc_error** error);
+ ~ChannelData() = default;
+
+ static void IdleTimerCallback(void* arg, grpc_error* error);
+ static void IdleTransportOpCompleteCallback(void* arg, grpc_error* error);
+
+ void StartIdleTimer();
+
+ void EnterIdle();
+
+ grpc_channel_element* elem_;
+ // The channel stack to which we take refs for pending callbacks.
+ grpc_channel_stack* channel_stack_;
+ // Timeout after the last RPC finishes on the client channel at which the
+ // channel goes back into IDLE state.
+ const grpc_millis client_idle_timeout_;
+
+ // Member data used to track the state of channel.
+ grpc_millis last_idle_time_;
+ Atomic<intptr_t> call_count_{0};
+ Atomic<ChannelState> state_{IDLE};
+
+ // Idle timer and its callback closure.
+ grpc_timer idle_timer_;
+ grpc_closure idle_timer_callback_;
+
+ // The transport op telling the client channel to enter IDLE.
+ grpc_transport_op idle_transport_op_;
+ grpc_closure idle_transport_op_complete_callback_;
+};
+
+grpc_error* ChannelData::Init(grpc_channel_element* elem,
+ grpc_channel_element_args* args) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ new (elem->channel_data) ChannelData(elem, args, &error);
+ return error;
+}
+
+void ChannelData::Destroy(grpc_channel_element* elem) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->~ChannelData();
+}
+
+void ChannelData::StartTransportOp(grpc_channel_element* elem,
+ grpc_transport_op* op) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ // Catch the disconnect_with_error transport op.
+ if (op->disconnect_with_error != nullptr) {
+ // IncreaseCallCount() introduces a dummy call and prevent the timer from
+ // being reset by other threads.
+ chand->IncreaseCallCount();
+ // If the timer has been set, cancel the timer.
+ // No synchronization issues here. grpc_timer_cancel() is valid as long as
+ // the timer has been init()ed before.
+ grpc_timer_cancel(&chand->idle_timer_);
+ }
+ // Pass the op to the next filter.
+ grpc_channel_next_op(elem, op);
+}
+
+void ChannelData::IncreaseCallCount() {
+ const intptr_t previous_value = call_count_.FetchAdd(1, MemoryOrder::RELAXED);
+ GRPC_IDLE_FILTER_LOG("call counter has increased to %" PRIuPTR,
+ previous_value + 1);
+ if (previous_value == 0) {
+ // This call is the one that makes the channel busy.
+ // Loop here to make sure the previous decrease operation has finished.
+ ChannelState state = state_.Load(MemoryOrder::RELAXED);
+ while (true) {
+ switch (state) {
+ // Timer has not been set. Switch to CALLS_ACTIVE.
+ case IDLE:
+ // In this case, no other threads will modify the state, so we can
+ // just store the value.
+ state_.Store(CALLS_ACTIVE, MemoryOrder::RELAXED);
+ return;
+ // Timer has been set. Switch to TIMER_PENDING_CALLS_ACTIVE.
+ case TIMER_PENDING:
+ case TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START:
+ // At this point, the state may have been switched to IDLE by the
+ // idle timer callback. Therefore, use CAS operation to change the
+ // state atomically.
+ // Use MemoryOrder::ACQUIRE on success to ensure last_idle_time_ has
+ // been properly set in DecreaseCallCount().
+ if (state_.CompareExchangeWeak(&state, TIMER_PENDING_CALLS_ACTIVE,
+ MemoryOrder::ACQUIRE,
+ MemoryOrder::RELAXED)) {
+ return;
+ }
+ break;
+ default:
+ // The state has not been switched to desired value yet, try again.
+ state = state_.Load(MemoryOrder::RELAXED);
+ break;
+ }
+ }
+ }
+}
+
+void ChannelData::DecreaseCallCount() {
+ const intptr_t previous_value = call_count_.FetchSub(1, MemoryOrder::RELAXED);
+ GRPC_IDLE_FILTER_LOG("call counter has decreased to %" PRIuPTR,
+ previous_value - 1);
+ if (previous_value == 1) {
+ // This call is the one that makes the channel idle.
+ // last_idle_time_ does not need to be Atomic<> because busy-loops in
+ // IncreaseCallCount(), DecreaseCallCount() and IdleTimerCallback() will
+ // prevent multiple threads from simultaneously accessing this variable.
+ last_idle_time_ = ExecCtx::Get()->Now();
+ ChannelState state = state_.Load(MemoryOrder::RELAXED);
+ while (true) {
+ switch (state) {
+ // Timer has not been set. Set the timer and switch to TIMER_PENDING
+ case CALLS_ACTIVE:
+ // Release store here to make other threads see the updated value of
+ // last_idle_time_.
+ StartIdleTimer();
+ state_.Store(TIMER_PENDING, MemoryOrder::RELEASE);
+ return;
+ // Timer has been set. Switch to
+ // TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START
+ case TIMER_PENDING_CALLS_ACTIVE:
+ // At this point, the state may have been switched to CALLS_ACTIVE by
+ // the idle timer callback. Therefore, use CAS operation to change the
+ // state atomically.
+ // Release store here to make the idle timer callback see the updated
+ // value of last_idle_time_ to properly reset the idle timer.
+ if (state_.CompareExchangeWeak(
+ &state, TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START,
+ MemoryOrder::RELEASE, MemoryOrder::RELAXED)) {
+ return;
+ }
+ break;
+ default:
+ // The state has not been switched to desired value yet, try again.
+ state = state_.Load(MemoryOrder::RELAXED);
+ break;
+ }
+ }
+ }
+}
+
+ChannelData::ChannelData(grpc_channel_element* elem,
+ grpc_channel_element_args* args,
+ grpc_error** /*error*/)
+ : elem_(elem),
+ channel_stack_(args->channel_stack),
+ client_idle_timeout_(GetClientIdleTimeout(args->channel_args)) {
+ // If the idle filter is explicitly disabled in channel args, this ctor should
+ // not get called.
+ GPR_ASSERT(client_idle_timeout_ != GRPC_MILLIS_INF_FUTURE);
+ GRPC_IDLE_FILTER_LOG("created with max_leisure_time = %" PRId64 " ms",
+ client_idle_timeout_);
+ // Initialize the idle timer without setting it.
+ grpc_timer_init_unset(&idle_timer_);
+ // Initialize the idle timer callback closure.
+ GRPC_CLOSURE_INIT(&idle_timer_callback_, IdleTimerCallback, this,
+ grpc_schedule_on_exec_ctx);
+ // Initialize the idle transport op complete callback.
+ GRPC_CLOSURE_INIT(&idle_transport_op_complete_callback_,
+ IdleTransportOpCompleteCallback, this,
+ grpc_schedule_on_exec_ctx);
+}
+
+void ChannelData::IdleTimerCallback(void* arg, grpc_error* error) {
+ GRPC_IDLE_FILTER_LOG("timer alarms");
+ ChannelData* chand = static_cast<ChannelData*>(arg);
+ if (error != GRPC_ERROR_NONE) {
+ GRPC_IDLE_FILTER_LOG("timer canceled");
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack_, "max idle timer callback");
+ return;
+ }
+ bool finished = false;
+ ChannelState state = chand->state_.Load(MemoryOrder::RELAXED);
+ while (!finished) {
+ switch (state) {
+ case TIMER_PENDING:
+ // Change the state to PROCESSING to block IncreaseCallCout() until the
+ // EnterIdle() operation finishes, preventing mistakenly entering IDLE
+ // when active RPC exists.
+ finished = chand->state_.CompareExchangeWeak(
+ &state, PROCESSING, MemoryOrder::ACQUIRE, MemoryOrder::RELAXED);
+ if (finished) {
+ chand->EnterIdle();
+ chand->state_.Store(IDLE, MemoryOrder::RELAXED);
+ }
+ break;
+ case TIMER_PENDING_CALLS_ACTIVE:
+ finished = chand->state_.CompareExchangeWeak(
+ &state, CALLS_ACTIVE, MemoryOrder::RELAXED, MemoryOrder::RELAXED);
+ break;
+ case TIMER_PENDING_CALLS_SEEN_SINCE_TIMER_START:
+ // Change the state to PROCESSING to block IncreaseCallCount() until the
+ // StartIdleTimer() operation finishes, preventing mistakenly restarting
+ // the timer after grpc_timer_cancel() when shutdown.
+ finished = chand->state_.CompareExchangeWeak(
+ &state, PROCESSING, MemoryOrder::ACQUIRE, MemoryOrder::RELAXED);
+ if (finished) {
+ chand->StartIdleTimer();
+ chand->state_.Store(TIMER_PENDING, MemoryOrder::RELAXED);
+ }
+ break;
+ default:
+ // The state has not been switched to desired value yet, try again.
+ state = chand->state_.Load(MemoryOrder::RELAXED);
+ break;
+ }
+ }
+ GRPC_IDLE_FILTER_LOG("timer finishes");
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack_, "max idle timer callback");
+}
+
+void ChannelData::IdleTransportOpCompleteCallback(void* arg,
+ grpc_error* /*error*/) {
+ ChannelData* chand = static_cast<ChannelData*>(arg);
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack_, "idle transport op");
+}
+
+void ChannelData::StartIdleTimer() {
+ GRPC_IDLE_FILTER_LOG("timer has started");
+ // Hold a ref to the channel stack for the timer callback.
+ GRPC_CHANNEL_STACK_REF(channel_stack_, "max idle timer callback");
+ grpc_timer_init(&idle_timer_, last_idle_time_ + client_idle_timeout_,
+ &idle_timer_callback_);
+}
+
+void ChannelData::EnterIdle() {
+ GRPC_IDLE_FILTER_LOG("the channel will enter IDLE");
+ // Hold a ref to the channel stack for the transport op.
+ GRPC_CHANNEL_STACK_REF(channel_stack_, "idle transport op");
+ // Initialize the transport op.
+ idle_transport_op_ = {};
+ idle_transport_op_.disconnect_with_error = grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("enter idle"),
+ GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE, GRPC_CHANNEL_IDLE);
+ idle_transport_op_.on_consumed = &idle_transport_op_complete_callback_;
+ // Pass the transport op down to the channel stack.
+ grpc_channel_next_op(elem_, &idle_transport_op_);
+}
+
+class CallData {
+ public:
+ static grpc_error* Init(grpc_call_element* elem,
+ const grpc_call_element_args* args);
+ static void Destroy(grpc_call_element* elem,
+ const grpc_call_final_info* final_info,
+ grpc_closure* then_schedule_closure);
+};
+
+grpc_error* CallData::Init(grpc_call_element* elem,
+ const grpc_call_element_args* /*args*/) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->IncreaseCallCount();
+ return GRPC_ERROR_NONE;
+}
+
+void CallData::Destroy(grpc_call_element* elem,
+ const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->DecreaseCallCount();
+}
+
+const grpc_channel_filter grpc_client_idle_filter = {
+ grpc_call_next_op,
+ ChannelData::StartTransportOp,
+ sizeof(CallData),
+ CallData::Init,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ CallData::Destroy,
+ sizeof(ChannelData),
+ ChannelData::Init,
+ ChannelData::Destroy,
+ grpc_channel_next_get_info,
+ "client_idle"};
+
+static bool MaybeAddClientIdleFilter(grpc_channel_stack_builder* builder,
+ void* /*arg*/) {
+ const grpc_channel_args* channel_args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ if (!grpc_channel_args_want_minimal_stack(channel_args) &&
+ GetClientIdleTimeout(channel_args) != INT_MAX) {
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_client_idle_filter, nullptr, nullptr);
+ } else {
+ return true;
+ }
+}
+
+} // namespace
+} // namespace grpc_core
+
+void grpc_client_idle_filter_init(void) {
+ grpc_channel_init_register_stage(
+ GRPC_CLIENT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ grpc_core::MaybeAddClientIdleFilter, nullptr);
+}
+
+void grpc_client_idle_filter_shutdown(void) {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc
index e4027b0719..6565444d9f 100644
--- a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc
@@ -38,7 +38,7 @@
// The on_complete callback used when sending a cancel_error batch down the
// filter stack. Yields the call combiner when the batch returns.
-static void yield_call_combiner(void* arg, grpc_error* /*ignored*/) {
+static void yield_call_combiner(void* arg, grpc_error* /*ignored*/) {
grpc_deadline_state* deadline_state = static_cast<grpc_deadline_state*>(arg);
GRPC_CALL_COMBINER_STOP(deadline_state->call_combiner,
"got on_complete from cancel_stream batch");
@@ -68,7 +68,7 @@ static void timer_callback(void* arg, grpc_error* error) {
error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Deadline Exceeded"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_DEADLINE_EXCEEDED);
- deadline_state->call_combiner->Cancel(GRPC_ERROR_REF(error));
+ deadline_state->call_combiner->Cancel(GRPC_ERROR_REF(error));
GRPC_CLOSURE_INIT(&deadline_state->timer_callback,
send_cancel_op_in_call_combiner, elem,
grpc_schedule_on_exec_ctx);
@@ -123,7 +123,7 @@ static void cancel_timer_if_needed(grpc_deadline_state* deadline_state) {
deadline_state->timer_state = GRPC_DEADLINE_STATE_FINISHED;
grpc_timer_cancel(&deadline_state->timer);
} else {
- // timer was either in STATE_INITIAL (nothing to cancel)
+ // timer was either in STATE_INITIAL (nothing to cancel)
// OR in STATE_FINISHED (again nothing to cancel)
}
}
@@ -133,9 +133,9 @@ static void recv_trailing_metadata_ready(void* arg, grpc_error* error) {
grpc_deadline_state* deadline_state = static_cast<grpc_deadline_state*>(arg);
cancel_timer_if_needed(deadline_state);
// Invoke the original callback.
- grpc_core::Closure::Run(DEBUG_LOCATION,
- deadline_state->original_recv_trailing_metadata_ready,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ deadline_state->original_recv_trailing_metadata_ready,
+ GRPC_ERROR_REF(error));
}
// Inject our own recv_trailing_metadata_ready callback into op.
@@ -176,14 +176,14 @@ static void start_timer_after_init(void* arg, grpc_error* error) {
"scheduling deadline timer");
return;
}
- delete state;
+ delete state;
GRPC_CALL_COMBINER_STOP(deadline_state->call_combiner,
"done scheduling deadline timer");
}
grpc_deadline_state::grpc_deadline_state(grpc_call_element* elem,
grpc_call_stack* call_stack,
- grpc_core::CallCombiner* call_combiner,
+ grpc_core::CallCombiner* call_combiner,
grpc_millis deadline)
: call_stack(call_stack), call_combiner(call_combiner) {
// Deadline will always be infinite on servers, so the timer will only be
@@ -197,10 +197,10 @@ grpc_deadline_state::grpc_deadline_state(grpc_call_element* elem,
// create a closure to start the timer, and we schedule that closure
// to be run after call stack initialization is done.
struct start_timer_after_init_state* state =
- new start_timer_after_init_state(elem, deadline);
+ new start_timer_after_init_state(elem, deadline);
GRPC_CLOSURE_INIT(&state->closure, start_timer_after_init, state,
grpc_schedule_on_exec_ctx);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, &state->closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, &state->closure, GRPC_ERROR_NONE);
}
}
@@ -234,14 +234,14 @@ void grpc_deadline_state_client_start_transport_stream_op_batch(
//
// Constructor for channel_data. Used for both client and server filters.
-static grpc_error* deadline_init_channel_elem(grpc_channel_element* /*elem*/,
- grpc_channel_element_args* args) {
+static grpc_error* deadline_init_channel_elem(grpc_channel_element* /*elem*/,
+ grpc_channel_element_args* args) {
GPR_ASSERT(!args->is_last);
return GRPC_ERROR_NONE;
}
// Destructor for channel_data. Used for both client and server filters.
-static void deadline_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
+static void deadline_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
// Call data used for both client and server filter.
typedef struct base_call_data {
@@ -261,24 +261,24 @@ typedef struct server_call_data {
} server_call_data;
// Constructor for call_data. Used for both client and server filters.
-static grpc_error* deadline_init_call_elem(grpc_call_element* elem,
- const grpc_call_element_args* args) {
+static grpc_error* deadline_init_call_elem(grpc_call_element* elem,
+ const grpc_call_element_args* args) {
new (elem->call_data) grpc_deadline_state(
elem, args->call_stack, args->call_combiner, args->deadline);
return GRPC_ERROR_NONE;
}
// Destructor for call_data. Used for both client and server filters.
-static void deadline_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void deadline_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
grpc_deadline_state* deadline_state =
static_cast<grpc_deadline_state*>(elem->call_data);
deadline_state->~grpc_deadline_state();
}
// Method for starting a call op for client filter.
-static void deadline_client_start_transport_stream_op_batch(
+static void deadline_client_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
grpc_deadline_state_client_start_transport_stream_op_batch(elem, op);
// Chain to next filter.
@@ -291,13 +291,13 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
server_call_data* calld = static_cast<server_call_data*>(elem->call_data);
start_timer_if_needed(elem, calld->recv_initial_metadata->deadline);
// Invoke the next callback.
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->next_recv_initial_metadata_ready,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->next_recv_initial_metadata_ready,
+ GRPC_ERROR_REF(error));
}
// Method for starting a call op for server filter.
-static void deadline_server_start_transport_stream_op_batch(
+static void deadline_server_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
server_call_data* calld = static_cast<server_call_data*>(elem->call_data);
if (op->cancel_stream) {
@@ -331,29 +331,29 @@ static void deadline_server_start_transport_stream_op_batch(
}
const grpc_channel_filter grpc_client_deadline_filter = {
- deadline_client_start_transport_stream_op_batch,
+ deadline_client_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(base_call_data),
- deadline_init_call_elem,
+ deadline_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- deadline_destroy_call_elem,
+ deadline_destroy_call_elem,
0, // sizeof(channel_data)
- deadline_init_channel_elem,
- deadline_destroy_channel_elem,
+ deadline_init_channel_elem,
+ deadline_destroy_channel_elem,
grpc_channel_next_get_info,
"deadline",
};
const grpc_channel_filter grpc_server_deadline_filter = {
- deadline_server_start_transport_stream_op_batch,
+ deadline_server_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(server_call_data),
- deadline_init_call_elem,
+ deadline_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- deadline_destroy_call_elem,
+ deadline_destroy_call_elem,
0, // sizeof(channel_data)
- deadline_init_channel_elem,
- deadline_destroy_channel_elem,
+ deadline_init_channel_elem,
+ deadline_destroy_channel_elem,
grpc_channel_next_get_info,
"deadline",
};
diff --git a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h
index 7c4e9aaed0..128d949aab 100644
--- a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h
@@ -32,13 +32,13 @@ enum grpc_deadline_timer_state {
// Must be the first field in the filter's call_data.
struct grpc_deadline_state {
grpc_deadline_state(grpc_call_element* elem, grpc_call_stack* call_stack,
- grpc_core::CallCombiner* call_combiner,
- grpc_millis deadline);
+ grpc_core::CallCombiner* call_combiner,
+ grpc_millis deadline);
~grpc_deadline_state();
// We take a reference to the call stack for the timer callback.
grpc_call_stack* call_stack;
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
grpc_deadline_timer_state timer_state = GRPC_DEADLINE_STATE_INITIAL;
grpc_timer timer;
grpc_closure timer_callback;
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc
index f5f18474da..656710d42f 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc
@@ -45,7 +45,7 @@
#define EXPECTED_CONTENT_TYPE "application/grpc"
#define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1
-/* default maximum size of payload eligible for GET request */
+/* default maximum size of payload eligible for GET request */
static constexpr size_t kMaxPayloadSizeForGet = 2048;
static void recv_initial_metadata_ready(void* user_data, grpc_error* error);
@@ -71,7 +71,7 @@ struct call_data {
~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); }
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
// State for handling send_initial_metadata ops.
grpc_linked_mdelem method;
grpc_linked_mdelem scheme;
@@ -108,16 +108,16 @@ struct channel_data {
};
} // namespace
-static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
+static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
if (b->idx.named.status != nullptr) {
/* If both gRPC status and HTTP status are provided in the response, we
* should prefer the gRPC status code, as mentioned in
* https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md.
*/
if (b->idx.named.grpc_status != nullptr ||
- grpc_mdelem_static_value_eq(b->idx.named.status->md,
- GRPC_MDELEM_STATUS_200)) {
- grpc_metadata_batch_remove(b, GRPC_BATCH_STATUS);
+ grpc_mdelem_static_value_eq(b->idx.named.status->md,
+ GRPC_MDELEM_STATUS_200)) {
+ grpc_metadata_batch_remove(b, GRPC_BATCH_STATUS);
} else {
char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.status->md),
GPR_DUMP_ASCII);
@@ -150,9 +150,9 @@ static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
}
if (b->idx.named.content_type != nullptr) {
- if (!grpc_mdelem_static_value_eq(
- b->idx.named.content_type->md,
- GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) {
+ if (!grpc_mdelem_static_value_eq(
+ b->idx.named.content_type->md,
+ GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) {
if (grpc_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md),
EXPECTED_CONTENT_TYPE,
EXPECTED_CONTENT_TYPE_LENGTH) &&
@@ -176,7 +176,7 @@ static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
gpr_free(val);
}
}
- grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_TYPE);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_TYPE);
}
return GRPC_ERROR_NONE;
@@ -186,7 +186,7 @@ static void recv_initial_metadata_ready(void* user_data, grpc_error* error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
call_data* calld = static_cast<call_data*>(elem->call_data);
if (error == GRPC_ERROR_NONE) {
- error = client_filter_incoming_metadata(calld->recv_initial_metadata);
+ error = client_filter_incoming_metadata(calld->recv_initial_metadata);
calld->recv_initial_metadata_error = GRPC_ERROR_REF(error);
} else {
GRPC_ERROR_REF(error);
@@ -198,7 +198,7 @@ static void recv_initial_metadata_ready(void* user_data, grpc_error* error) {
calld->call_combiner, &calld->recv_trailing_metadata_ready,
calld->recv_trailing_metadata_error, "continue recv_trailing_metadata");
}
- grpc_core::Closure::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::Closure::Run(DEBUG_LOCATION, closure, error);
}
static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) {
@@ -213,23 +213,23 @@ static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) {
return;
}
if (error == GRPC_ERROR_NONE) {
- error = client_filter_incoming_metadata(calld->recv_trailing_metadata);
+ error = client_filter_incoming_metadata(calld->recv_trailing_metadata);
} else {
GRPC_ERROR_REF(error);
}
error = grpc_error_add_child(
error, GRPC_ERROR_REF(calld->recv_initial_metadata_error));
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_recv_trailing_metadata_ready, error);
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_recv_trailing_metadata_ready, error);
}
static void send_message_on_complete(void* arg, grpc_error* error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->send_message_cache.Destroy();
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_send_message_on_complete,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_send_message_on_complete,
+ GRPC_ERROR_REF(error));
}
// Pulls a slice from the send_message byte stream, updating
@@ -312,9 +312,9 @@ static grpc_error* update_path_for_get(grpc_call_element* elem,
size_t estimated_len = GRPC_SLICE_LENGTH(path_slice);
estimated_len++; /* for the '?' */
estimated_len += grpc_base64_estimate_encoded_size(
- batch->payload->send_message.send_message->length(),
+ batch->payload->send_message.send_message->length(),
false /* multi_line */);
- grpc_core::UnmanagedMemorySlice path_with_query_slice(estimated_len);
+ grpc_core::UnmanagedMemorySlice path_with_query_slice(estimated_len);
/* memcopy individual pieces into this slice */
char* write_ptr =
reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_with_query_slice);
@@ -346,15 +346,15 @@ static grpc_error* update_path_for_get(grpc_call_element* elem,
static void remove_if_present(grpc_metadata_batch* batch,
grpc_metadata_batch_callouts_index idx) {
if (batch->idx.array[idx] != nullptr) {
- grpc_metadata_batch_remove(batch, idx);
+ grpc_metadata_batch_remove(batch, idx);
}
}
-static void http_client_start_transport_stream_op_batch(
+static void http_client_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
call_data* calld = static_cast<call_data*>(elem->call_data);
channel_data* channeld = static_cast<channel_data*>(elem->channel_data);
- GPR_TIMER_SCOPE("http_client_start_transport_stream_op_batch", 0);
+ GPR_TIMER_SCOPE("http_client_start_transport_stream_op_batch", 0);
if (batch->recv_initial_metadata) {
/* substitute our callback for the higher callback */
@@ -443,25 +443,25 @@ static void http_client_start_transport_stream_op_batch(
layer headers. */
error = grpc_metadata_batch_add_head(
batch->payload->send_initial_metadata.send_initial_metadata,
- &calld->method, method, GRPC_BATCH_METHOD);
+ &calld->method, method, GRPC_BATCH_METHOD);
if (error != GRPC_ERROR_NONE) goto done;
error = grpc_metadata_batch_add_head(
batch->payload->send_initial_metadata.send_initial_metadata,
- &calld->scheme, channeld->static_scheme, GRPC_BATCH_SCHEME);
+ &calld->scheme, channeld->static_scheme, GRPC_BATCH_SCHEME);
if (error != GRPC_ERROR_NONE) goto done;
error = grpc_metadata_batch_add_tail(
batch->payload->send_initial_metadata.send_initial_metadata,
- &calld->te_trailers, GRPC_MDELEM_TE_TRAILERS, GRPC_BATCH_TE);
+ &calld->te_trailers, GRPC_MDELEM_TE_TRAILERS, GRPC_BATCH_TE);
if (error != GRPC_ERROR_NONE) goto done;
error = grpc_metadata_batch_add_tail(
batch->payload->send_initial_metadata.send_initial_metadata,
- &calld->content_type, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC,
- GRPC_BATCH_CONTENT_TYPE);
+ &calld->content_type, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC,
+ GRPC_BATCH_CONTENT_TYPE);
if (error != GRPC_ERROR_NONE) goto done;
error = grpc_metadata_batch_add_tail(
batch->payload->send_initial_metadata.send_initial_metadata,
- &calld->user_agent, GRPC_MDELEM_REF(channeld->user_agent),
- GRPC_BATCH_USER_AGENT);
+ &calld->user_agent, GRPC_MDELEM_REF(channeld->user_agent),
+ GRPC_BATCH_USER_AGENT);
if (error != GRPC_ERROR_NONE) goto done;
}
@@ -475,16 +475,16 @@ done:
}
/* Constructor for call_data */
-static grpc_error* http_client_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* args) {
+static grpc_error* http_client_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* args) {
new (elem->call_data) call_data(elem, *args);
return GRPC_ERROR_NONE;
}
/* Destructor for call_data */
-static void http_client_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void http_client_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
}
@@ -526,8 +526,8 @@ static size_t max_payload_size_from_args(const grpc_channel_args* args) {
return kMaxPayloadSizeForGet;
}
-static grpc_core::ManagedMemorySlice user_agent_from_args(
- const grpc_channel_args* args, const char* transport_name) {
+static grpc_core::ManagedMemorySlice user_agent_from_args(
+ const grpc_channel_args* args, const char* transport_name) {
std::vector<TString> user_agent_fields;
for (size_t i = 0; args && i < args->num_args; i++) {
@@ -561,8 +561,8 @@ static grpc_core::ManagedMemorySlice user_agent_from_args(
}
/* Constructor for channel_data */
-static grpc_error* http_client_init_channel_elem(
- grpc_channel_element* elem, grpc_channel_element_args* args) {
+static grpc_error* http_client_init_channel_elem(
+ grpc_channel_element* elem, grpc_channel_element_args* args) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
GPR_ASSERT(!args->is_last);
GPR_ASSERT(args->optional_transport != nullptr);
@@ -577,20 +577,20 @@ static grpc_error* http_client_init_channel_elem(
}
/* Destructor for channel data */
-static void http_client_destroy_channel_elem(grpc_channel_element* elem) {
+static void http_client_destroy_channel_elem(grpc_channel_element* elem) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
GRPC_MDELEM_UNREF(chand->user_agent);
}
const grpc_channel_filter grpc_http_client_filter = {
- http_client_start_transport_stream_op_batch,
+ http_client_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- http_client_init_call_elem,
+ http_client_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- http_client_destroy_call_elem,
+ http_client_destroy_call_elem,
sizeof(channel_data),
- http_client_init_channel_elem,
- http_client_destroy_channel_elem,
+ http_client_init_channel_elem,
+ http_client_destroy_channel_elem,
grpc_channel_next_get_info,
"http-client"};
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.h b/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.h
index a2f16ddbfb..2ce05629a6 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.h
@@ -25,7 +25,7 @@
/* Processes metadata on the client side for HTTP2 transports */
extern const grpc_channel_filter grpc_http_client_filter;
-/* Channel arg to determine maximum size of payload eligible for GET request */
+/* Channel arg to determine maximum size of payload eligible for GET request */
#define GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET "grpc.max_payload_size_for_get"
#endif /* GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_HTTP_CLIENT_FILTER_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc
index 2c3cae6adb..610a5d2a19 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc
@@ -40,15 +40,15 @@ namespace {
struct call_data {
grpc_linked_mdelem authority_storage;
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
};
struct channel_data {
- grpc_core::ManagedMemorySlice default_authority;
+ grpc_core::ManagedMemorySlice default_authority;
grpc_mdelem default_authority_mdelem;
};
-void client_authority_start_transport_stream_op_batch(
+void client_authority_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
call_data* calld = static_cast<call_data*>(elem->call_data);
@@ -60,7 +60,7 @@ void client_authority_start_transport_stream_op_batch(
grpc_error* error = grpc_metadata_batch_add_head(
batch->payload->send_initial_metadata.send_initial_metadata,
&calld->authority_storage,
- GRPC_MDELEM_REF(chand->default_authority_mdelem), GRPC_BATCH_AUTHORITY);
+ GRPC_MDELEM_REF(chand->default_authority_mdelem), GRPC_BATCH_AUTHORITY);
if (error != GRPC_ERROR_NONE) {
grpc_transport_stream_op_batch_finish_with_failure(batch, error,
calld->call_combiner);
@@ -72,21 +72,21 @@ void client_authority_start_transport_stream_op_batch(
}
/* Constructor for call_data */
-grpc_error* client_authority_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* args) {
+grpc_error* client_authority_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* args) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->call_combiner = args->call_combiner;
return GRPC_ERROR_NONE;
}
/* Destructor for call_data */
-void client_authority_destroy_call_elem(
- grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {}
+void client_authority_destroy_call_elem(
+ grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {}
/* Constructor for channel_data */
-grpc_error* client_authority_init_channel_elem(
- grpc_channel_element* elem, grpc_channel_element_args* args) {
+grpc_error* client_authority_init_channel_elem(
+ grpc_channel_element* elem, grpc_channel_element_args* args) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
const grpc_arg* default_authority_arg =
grpc_channel_args_find(args->channel_args, GRPC_ARG_DEFAULT_AUTHORITY);
@@ -102,7 +102,7 @@ grpc_error* client_authority_init_channel_elem(
"GRPC_ARG_DEFAULT_AUTHORITY channel arg. must be a string");
}
chand->default_authority =
- grpc_core::ManagedMemorySlice(default_authority_str);
+ grpc_core::ManagedMemorySlice(default_authority_str);
chand->default_authority_mdelem = grpc_mdelem_create(
GRPC_MDSTR_AUTHORITY, chand->default_authority, nullptr);
GPR_ASSERT(!args->is_last);
@@ -110,7 +110,7 @@ grpc_error* client_authority_init_channel_elem(
}
/* Destructor for channel data */
-void client_authority_destroy_channel_elem(grpc_channel_element* elem) {
+void client_authority_destroy_channel_elem(grpc_channel_element* elem) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
grpc_slice_unref_internal(chand->default_authority);
GRPC_MDELEM_UNREF(chand->default_authority_mdelem);
@@ -118,15 +118,15 @@ void client_authority_destroy_channel_elem(grpc_channel_element* elem) {
} // namespace
const grpc_channel_filter grpc_client_authority_filter = {
- client_authority_start_transport_stream_op_batch,
+ client_authority_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- client_authority_init_call_elem,
+ client_authority_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- client_authority_destroy_call_elem,
+ client_authority_destroy_call_elem,
sizeof(channel_data),
- client_authority_init_channel_elem,
- client_authority_destroy_channel_elem,
+ client_authority_init_channel_elem,
+ client_authority_destroy_channel_elem,
grpc_channel_next_get_info,
"authority"};
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc
index 53f6e2b80d..ef5a141b41 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc
@@ -31,7 +31,7 @@
#include "src/core/ext/filters/http/message_compress/message_compress_filter.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/compression/algorithm_metadata.h"
-#include "src/core/lib/compression/compression_args.h"
+#include "src/core/lib/compression/compression_args.h"
#include "src/core/lib/compression/compression_internal.h"
#include "src/core/lib/compression/message_compress.h"
#include "src/core/lib/gpr/string.h"
@@ -43,7 +43,7 @@
#include "src/core/lib/transport/static_metadata.h"
namespace {
-
+
class ChannelData {
public:
explicit ChannelData(grpc_channel_element_args* args) {
@@ -90,13 +90,13 @@ class ChannelData {
}
private:
- /** The default, channel-level, compression algorithm */
+ /** The default, channel-level, compression algorithm */
grpc_compression_algorithm default_compression_algorithm_;
- /** Bitset of enabled compression algorithms */
+ /** Bitset of enabled compression algorithms */
uint32_t enabled_compression_algorithms_bitset_;
- /** Bitset of enabled message compression algorithms */
+ /** Bitset of enabled message compression algorithms */
uint32_t enabled_message_compression_algorithms_bitset_;
- /** Bitset of enabled stream compression algorithms */
+ /** Bitset of enabled stream compression algorithms */
uint32_t enabled_stream_compression_algorithms_bitset_;
};
@@ -105,14 +105,14 @@ class CallData {
CallData(grpc_call_element* elem, const grpc_call_element_args& args)
: call_combiner_(args.call_combiner) {
ChannelData* channeld = static_cast<ChannelData*>(elem->channel_data);
- // The call's message compression algorithm is set to channel's default
- // setting. It can be overridden later by initial metadata.
+ // The call's message compression algorithm is set to channel's default
+ // setting. It can be overridden later by initial metadata.
if (GPR_LIKELY(GPR_BITGET(channeld->enabled_compression_algorithms_bitset(),
channeld->default_compression_algorithm()))) {
message_compression_algorithm_ =
- grpc_compression_algorithm_to_message_compression_algorithm(
+ grpc_compression_algorithm_to_message_compression_algorithm(
channeld->default_compression_algorithm());
- }
+ }
GRPC_CLOSURE_INIT(&start_send_message_batch_in_call_combiner_,
StartSendMessageBatch, elem, grpc_schedule_on_exec_ctx);
}
@@ -120,7 +120,7 @@ class CallData {
~CallData() {
if (state_initialized_) {
grpc_slice_buffer_destroy_internal(&slices_);
- }
+ }
GRPC_ERROR_UNREF(cancel_error_);
}
@@ -152,12 +152,12 @@ class CallData {
grpc_error* cancel_error_ = GRPC_ERROR_NONE;
grpc_transport_stream_op_batch* send_message_batch_ = nullptr;
bool seen_initial_metadata_ = false;
- /* Set to true, if the fields below are initialized. */
+ /* Set to true, if the fields below are initialized. */
bool state_initialized_ = false;
grpc_closure start_send_message_batch_in_call_combiner_;
- /* The fields below are only initialized when we compress the payload.
- * Keep them at the bottom of the struct, so they don't pollute the
- * cache-lines. */
+ /* The fields below are only initialized when we compress the payload.
+ * Keep them at the bottom of the struct, so they don't pollute the
+ * cache-lines. */
grpc_linked_mdelem message_compression_algorithm_storage_;
grpc_linked_mdelem stream_compression_algorithm_storage_;
grpc_linked_mdelem accept_encoding_storage_;
@@ -172,54 +172,54 @@ class CallData {
grpc_closure on_send_message_next_done_;
};
-// Returns true if we should skip message compression for the current message.
+// Returns true if we should skip message compression for the current message.
bool CallData::SkipMessageCompression() {
- // If the flags of this message indicate that it shouldn't be compressed, we
- // skip message compression.
- uint32_t flags =
+ // If the flags of this message indicate that it shouldn't be compressed, we
+ // skip message compression.
+ uint32_t flags =
send_message_batch_->payload->send_message.send_message->flags();
if (flags & (GRPC_WRITE_NO_COMPRESS | GRPC_WRITE_INTERNAL_COMPRESS)) {
return true;
}
- // If this call doesn't have any message compression algorithm set, skip
- // message compression.
+ // If this call doesn't have any message compression algorithm set, skip
+ // message compression.
return message_compression_algorithm_ == GRPC_MESSAGE_COMPRESS_NONE;
-}
-
-// Determines the compression algorithm from the initial metadata and the
-// channel's default setting.
+}
+
+// Determines the compression algorithm from the initial metadata and the
+// channel's default setting.
grpc_compression_algorithm FindCompressionAlgorithm(
grpc_metadata_batch* initial_metadata, ChannelData* channeld) {
- if (initial_metadata->idx.named.grpc_internal_encoding_request == nullptr) {
+ if (initial_metadata->idx.named.grpc_internal_encoding_request == nullptr) {
return channeld->default_compression_algorithm();
}
- grpc_compression_algorithm compression_algorithm;
- // Parse the compression algorithm from the initial metadata.
- grpc_mdelem md =
- initial_metadata->idx.named.grpc_internal_encoding_request->md;
- GPR_ASSERT(grpc_compression_algorithm_parse(GRPC_MDVALUE(md),
- &compression_algorithm));
- // Remove this metadata since it's an internal one (i.e., it won't be
- // transmitted out).
- grpc_metadata_batch_remove(initial_metadata,
- GRPC_BATCH_GRPC_INTERNAL_ENCODING_REQUEST);
- // Check if that algorithm is enabled. Note that GRPC_COMPRESS_NONE is always
- // enabled.
- // TODO(juanlishen): Maybe use channel default or abort() if the algorithm
- // from the initial metadata is disabled.
+ grpc_compression_algorithm compression_algorithm;
+ // Parse the compression algorithm from the initial metadata.
+ grpc_mdelem md =
+ initial_metadata->idx.named.grpc_internal_encoding_request->md;
+ GPR_ASSERT(grpc_compression_algorithm_parse(GRPC_MDVALUE(md),
+ &compression_algorithm));
+ // Remove this metadata since it's an internal one (i.e., it won't be
+ // transmitted out).
+ grpc_metadata_batch_remove(initial_metadata,
+ GRPC_BATCH_GRPC_INTERNAL_ENCODING_REQUEST);
+ // Check if that algorithm is enabled. Note that GRPC_COMPRESS_NONE is always
+ // enabled.
+ // TODO(juanlishen): Maybe use channel default or abort() if the algorithm
+ // from the initial metadata is disabled.
if (GPR_LIKELY(GPR_BITGET(channeld->enabled_compression_algorithms_bitset(),
- compression_algorithm))) {
- return compression_algorithm;
- }
- const char* algorithm_name;
- GPR_ASSERT(
- grpc_compression_algorithm_name(compression_algorithm, &algorithm_name));
- gpr_log(GPR_ERROR,
- "Invalid compression algorithm from initial metadata: '%s' "
- "(previously disabled). "
- "Will not compress.",
- algorithm_name);
- return GRPC_COMPRESS_NONE;
+ compression_algorithm))) {
+ return compression_algorithm;
+ }
+ const char* algorithm_name;
+ GPR_ASSERT(
+ grpc_compression_algorithm_name(compression_algorithm, &algorithm_name));
+ gpr_log(GPR_ERROR,
+ "Invalid compression algorithm from initial metadata: '%s' "
+ "(previously disabled). "
+ "Will not compress.",
+ algorithm_name);
+ return GRPC_COMPRESS_NONE;
}
void CallData::InitializeState(grpc_call_element* elem) {
@@ -227,56 +227,56 @@ void CallData::InitializeState(grpc_call_element* elem) {
state_initialized_ = true;
grpc_slice_buffer_init(&slices_);
GRPC_CLOSURE_INIT(&send_message_on_complete_, SendMessageOnComplete, this,
- grpc_schedule_on_exec_ctx);
+ grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&on_send_message_next_done_, OnSendMessageNextDone, elem,
- grpc_schedule_on_exec_ctx);
-}
-
+ grpc_schedule_on_exec_ctx);
+}
+
grpc_error* CallData::ProcessSendInitialMetadata(
- grpc_call_element* elem, grpc_metadata_batch* initial_metadata) {
+ grpc_call_element* elem, grpc_metadata_batch* initial_metadata) {
ChannelData* channeld = static_cast<ChannelData*>(elem->channel_data);
- // Find the compression algorithm.
- grpc_compression_algorithm compression_algorithm =
+ // Find the compression algorithm.
+ grpc_compression_algorithm compression_algorithm =
FindCompressionAlgorithm(initial_metadata, channeld);
- // Note that at most one of the following algorithms can be set.
+ // Note that at most one of the following algorithms can be set.
message_compression_algorithm_ =
- grpc_compression_algorithm_to_message_compression_algorithm(
- compression_algorithm);
+ grpc_compression_algorithm_to_message_compression_algorithm(
+ compression_algorithm);
grpc_stream_compression_algorithm stream_compression_algorithm =
- grpc_compression_algorithm_to_stream_compression_algorithm(
- compression_algorithm);
- // Hint compression algorithm.
+ grpc_compression_algorithm_to_stream_compression_algorithm(
+ compression_algorithm);
+ // Hint compression algorithm.
grpc_error* error = GRPC_ERROR_NONE;
if (message_compression_algorithm_ != GRPC_MESSAGE_COMPRESS_NONE) {
InitializeState(elem);
error = grpc_metadata_batch_add_tail(
initial_metadata, &message_compression_algorithm_storage_,
- grpc_message_compression_encoding_mdelem(
+ grpc_message_compression_encoding_mdelem(
message_compression_algorithm_),
- GRPC_BATCH_GRPC_ENCODING);
- } else if (stream_compression_algorithm != GRPC_STREAM_COMPRESS_NONE) {
+ GRPC_BATCH_GRPC_ENCODING);
+ } else if (stream_compression_algorithm != GRPC_STREAM_COMPRESS_NONE) {
InitializeState(elem);
- error = grpc_metadata_batch_add_tail(
+ error = grpc_metadata_batch_add_tail(
initial_metadata, &stream_compression_algorithm_storage_,
- grpc_stream_compression_encoding_mdelem(stream_compression_algorithm),
- GRPC_BATCH_CONTENT_ENCODING);
+ grpc_stream_compression_encoding_mdelem(stream_compression_algorithm),
+ GRPC_BATCH_CONTENT_ENCODING);
}
if (error != GRPC_ERROR_NONE) return error;
- // Convey supported compression algorithms.
+ // Convey supported compression algorithms.
error = grpc_metadata_batch_add_tail(
initial_metadata, &accept_encoding_storage_,
GRPC_MDELEM_ACCEPT_ENCODING_FOR_ALGORITHMS(
channeld->enabled_message_compression_algorithms_bitset()),
- GRPC_BATCH_GRPC_ACCEPT_ENCODING);
+ GRPC_BATCH_GRPC_ACCEPT_ENCODING);
if (error != GRPC_ERROR_NONE) return error;
- // Do not overwrite accept-encoding header if it already presents (e.g., added
- // by some proxy).
+ // Do not overwrite accept-encoding header if it already presents (e.g., added
+ // by some proxy).
if (!initial_metadata->idx.named.accept_encoding) {
error = grpc_metadata_batch_add_tail(
initial_metadata, &accept_stream_encoding_storage_,
GRPC_MDELEM_ACCEPT_STREAM_ENCODING_FOR_ALGORITHMS(
channeld->enabled_stream_compression_algorithms_bitset()),
- GRPC_BATCH_ACCEPT_ENCODING);
+ GRPC_BATCH_ACCEPT_ENCODING);
}
return error;
}
@@ -284,9 +284,9 @@ grpc_error* CallData::ProcessSendInitialMetadata(
void CallData::SendMessageOnComplete(void* calld_arg, grpc_error* error) {
CallData* calld = static_cast<CallData*>(calld_arg);
grpc_slice_buffer_reset_and_unref_internal(&calld->slices_);
- grpc_core::Closure::Run(DEBUG_LOCATION,
+ grpc_core::Closure::Run(DEBUG_LOCATION,
calld->original_send_message_on_complete_,
- GRPC_ERROR_REF(error));
+ GRPC_ERROR_REF(error));
}
void CallData::SendMessageBatchContinue(grpc_call_element* elem) {
@@ -299,7 +299,7 @@ void CallData::SendMessageBatchContinue(grpc_call_element* elem) {
void CallData::FinishSendMessage(grpc_call_element* elem) {
GPR_DEBUG_ASSERT(message_compression_algorithm_ !=
- GRPC_MESSAGE_COMPRESS_NONE);
+ GRPC_MESSAGE_COMPRESS_NONE);
// Compress the data if appropriate.
grpc_slice_buffer tmp;
grpc_slice_buffer_init(&tmp);
@@ -308,7 +308,7 @@ void CallData::FinishSendMessage(grpc_call_element* elem) {
bool did_compress =
grpc_msg_compress(message_compression_algorithm_, &slices_, &tmp);
if (did_compress) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
const char* algo_name;
const size_t before_size = slices_.length;
const size_t after_size = tmp.length;
@@ -324,7 +324,7 @@ void CallData::FinishSendMessage(grpc_call_element* elem) {
grpc_slice_buffer_swap(&slices_, &tmp);
send_flags |= GRPC_WRITE_INTERNAL_COMPRESS;
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
const char* algo_name;
GPR_ASSERT(grpc_message_compression_algorithm_name(
message_compression_algorithm_, &algo_name));
@@ -378,8 +378,8 @@ void CallData::ContinueReadingSendMessage(grpc_call_element* elem) {
if (slices_.length ==
send_message_batch_->payload->send_message.send_message->length()) {
FinishSendMessage(elem);
- return;
- }
+ return;
+ }
while (send_message_batch_->payload->send_message.send_message->Next(
~static_cast<size_t>(0), &on_send_message_next_done_)) {
grpc_error* error = PullSliceFromSendMessage();
@@ -459,7 +459,7 @@ void CallData::CompressStartTransportStreamOpBatch(
if (batch->send_initial_metadata) {
GPR_ASSERT(!seen_initial_metadata_);
grpc_error* error = ProcessSendInitialMetadata(
- elem, batch->payload->send_initial_metadata.send_initial_metadata);
+ elem, batch->payload->send_initial_metadata.send_initial_metadata);
if (error != GRPC_ERROR_NONE) {
grpc_transport_stream_op_batch_finish_with_failure(batch, error,
call_combiner_);
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc
index 62dc76fb6c..46456f79a9 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc
@@ -61,7 +61,7 @@ struct call_data {
}
}
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
// Outgoing headers to add to send_initial_metadata.
grpc_linked_mdelem status;
@@ -99,7 +99,7 @@ struct channel_data {
} // namespace
-static grpc_error* hs_filter_outgoing_metadata(grpc_metadata_batch* b) {
+static grpc_error* hs_filter_outgoing_metadata(grpc_metadata_batch* b) {
if (b->idx.named.grpc_message != nullptr) {
grpc_slice pct_encoded_msg = grpc_percent_encode_slice(
GRPC_MDVALUE(b->idx.named.grpc_message->md),
@@ -123,32 +123,32 @@ static void hs_add_error(const char* error_name, grpc_error** cumulative,
*cumulative = grpc_error_add_child(*cumulative, new_err);
}
-// Metadata equality within this filter leverages the fact that the sender was
-// likely using the gRPC chttp2 transport, in which case the encoder would emit
-// indexed values, in which case the local hpack parser would intern the
-// relevant metadata, allowing a simple pointer comparison.
-//
-// That said, if the header was transmitted sans indexing/encoding, we still
-// need to do the right thing.
-//
-// Assumptions:
-// 1) The keys for a and b_static must match
-// 2) b_static must be a statically allocated metadata object.
-// 3) It is assumed that the remote end is indexing, but not necessary.
-// TODO(arjunroy): Revisit this method when grpc_mdelem is strongly typed.
-static bool md_strict_equal(grpc_mdelem a, grpc_mdelem b_static) {
- // Hpack encoder on the remote side should emit indexed values, in which case
- // hpack parser on this end should pick up interned values, in which case the
- // pointer comparison alone is enough.
- //
- if (GPR_LIKELY(GRPC_MDELEM_IS_INTERNED(a))) {
- return a.payload == b_static.payload;
- } else {
- return grpc_slice_eq_static_interned(GRPC_MDVALUE(a),
- GRPC_MDVALUE(b_static));
- }
-}
-
+// Metadata equality within this filter leverages the fact that the sender was
+// likely using the gRPC chttp2 transport, in which case the encoder would emit
+// indexed values, in which case the local hpack parser would intern the
+// relevant metadata, allowing a simple pointer comparison.
+//
+// That said, if the header was transmitted sans indexing/encoding, we still
+// need to do the right thing.
+//
+// Assumptions:
+// 1) The keys for a and b_static must match
+// 2) b_static must be a statically allocated metadata object.
+// 3) It is assumed that the remote end is indexing, but not necessary.
+// TODO(arjunroy): Revisit this method when grpc_mdelem is strongly typed.
+static bool md_strict_equal(grpc_mdelem a, grpc_mdelem b_static) {
+ // Hpack encoder on the remote side should emit indexed values, in which case
+ // hpack parser on this end should pick up interned values, in which case the
+ // pointer comparison alone is enough.
+ //
+ if (GPR_LIKELY(GRPC_MDELEM_IS_INTERNED(a))) {
+ return a.payload == b_static.payload;
+ } else {
+ return grpc_slice_eq_static_interned(GRPC_MDVALUE(a),
+ GRPC_MDVALUE(b_static));
+ }
+}
+
static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
grpc_metadata_batch* b) {
call_data* calld = static_cast<call_data*>(elem->call_data);
@@ -156,18 +156,18 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
static const char* error_name = "Failed processing incoming headers";
if (b->idx.named.method != nullptr) {
- if (md_strict_equal(b->idx.named.method->md, GRPC_MDELEM_METHOD_POST)) {
+ if (md_strict_equal(b->idx.named.method->md, GRPC_MDELEM_METHOD_POST)) {
*calld->recv_initial_metadata_flags &=
~(GRPC_INITIAL_METADATA_CACHEABLE_REQUEST |
GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST);
- } else if (md_strict_equal(b->idx.named.method->md,
- GRPC_MDELEM_METHOD_PUT)) {
+ } else if (md_strict_equal(b->idx.named.method->md,
+ GRPC_MDELEM_METHOD_PUT)) {
*calld->recv_initial_metadata_flags &=
~GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
*calld->recv_initial_metadata_flags |=
GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
- } else if (md_strict_equal(b->idx.named.method->md,
- GRPC_MDELEM_METHOD_GET)) {
+ } else if (md_strict_equal(b->idx.named.method->md,
+ GRPC_MDELEM_METHOD_GET)) {
*calld->recv_initial_metadata_flags |=
GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
*calld->recv_initial_metadata_flags &=
@@ -178,7 +178,7 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->idx.named.method->md));
}
- grpc_metadata_batch_remove(b, GRPC_BATCH_METHOD);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_METHOD);
} else {
hs_add_error(
error_name, &error,
@@ -188,14 +188,14 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
}
if (b->idx.named.te != nullptr) {
- if (!grpc_mdelem_static_value_eq(b->idx.named.te->md,
- GRPC_MDELEM_TE_TRAILERS)) {
+ if (!grpc_mdelem_static_value_eq(b->idx.named.te->md,
+ GRPC_MDELEM_TE_TRAILERS)) {
hs_add_error(error_name, &error,
grpc_attach_md_to_error(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->idx.named.te->md));
}
- grpc_metadata_batch_remove(b, GRPC_BATCH_TE);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_TE);
} else {
hs_add_error(error_name, &error,
grpc_error_set_str(
@@ -204,16 +204,16 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
}
if (b->idx.named.scheme != nullptr) {
- if (!md_strict_equal(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTP) &&
- !md_strict_equal(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTPS) &&
- !grpc_mdelem_static_value_eq(b->idx.named.scheme->md,
- GRPC_MDELEM_SCHEME_GRPC)) {
+ if (!md_strict_equal(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTP) &&
+ !md_strict_equal(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTPS) &&
+ !grpc_mdelem_static_value_eq(b->idx.named.scheme->md,
+ GRPC_MDELEM_SCHEME_GRPC)) {
hs_add_error(error_name, &error,
grpc_attach_md_to_error(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->idx.named.scheme->md));
}
- grpc_metadata_batch_remove(b, GRPC_BATCH_SCHEME);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_SCHEME);
} else {
hs_add_error(
error_name, &error,
@@ -223,9 +223,9 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
}
if (b->idx.named.content_type != nullptr) {
- if (!grpc_mdelem_static_value_eq(
- b->idx.named.content_type->md,
- GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) {
+ if (!grpc_mdelem_static_value_eq(
+ b->idx.named.content_type->md,
+ GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) {
if (grpc_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md),
EXPECTED_CONTENT_TYPE,
EXPECTED_CONTENT_TYPE_LENGTH) &&
@@ -249,7 +249,7 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
gpr_free(val);
}
}
- grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_TYPE);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_TYPE);
}
if (b->idx.named.path == nullptr) {
@@ -304,13 +304,13 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
grpc_linked_mdelem* el = b->idx.named.host;
grpc_mdelem md = GRPC_MDELEM_REF(el->md);
grpc_metadata_batch_remove(b, el);
- hs_add_error(
- error_name, &error,
- grpc_metadata_batch_add_head(
- b, el,
- grpc_mdelem_from_slices(GRPC_MDSTR_AUTHORITY,
- grpc_slice_ref_internal(GRPC_MDVALUE(md))),
- GRPC_BATCH_AUTHORITY));
+ hs_add_error(
+ error_name, &error,
+ grpc_metadata_batch_add_head(
+ b, el,
+ grpc_mdelem_from_slices(GRPC_MDSTR_AUTHORITY,
+ grpc_slice_ref_internal(GRPC_MDVALUE(md))),
+ GRPC_BATCH_AUTHORITY));
GRPC_MDELEM_UNREF(md);
}
@@ -324,7 +324,7 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
if (!chand->surface_user_agent && b->idx.named.user_agent != nullptr) {
- grpc_metadata_batch_remove(b, GRPC_BATCH_USER_AGENT);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_USER_AGENT);
}
return error;
@@ -363,8 +363,8 @@ static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err) {
"resuming hs_recv_trailing_metadata_ready from "
"hs_recv_initial_metadata_ready");
}
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_recv_initial_metadata_ready, err);
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_recv_initial_metadata_ready, err);
}
static void hs_recv_message_ready(void* user_data, grpc_error* err) {
@@ -379,8 +379,8 @@ static void hs_recv_message_ready(void* user_data, grpc_error* err) {
calld->recv_message->reset(calld->read_stream.get());
calld->have_read_stream = false;
}
- grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_message_ready,
- GRPC_ERROR_REF(err));
+ grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_message_ready,
+ GRPC_ERROR_REF(err));
} else {
// We have not yet seen the recv_initial_metadata callback, so we
// need to wait to see if this is a GET request.
@@ -406,8 +406,8 @@ static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err) {
err = grpc_error_add_child(
GRPC_ERROR_REF(err),
GRPC_ERROR_REF(calld->recv_initial_metadata_ready_error));
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_recv_trailing_metadata_ready, err);
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_recv_trailing_metadata_ready, err);
}
static grpc_error* hs_mutate_op(grpc_call_element* elem,
@@ -418,20 +418,20 @@ static grpc_error* hs_mutate_op(grpc_call_element* elem,
if (op->send_initial_metadata) {
grpc_error* error = GRPC_ERROR_NONE;
static const char* error_name = "Failed sending initial metadata";
- hs_add_error(
- error_name, &error,
- grpc_metadata_batch_add_head(
- op->payload->send_initial_metadata.send_initial_metadata,
- &calld->status, GRPC_MDELEM_STATUS_200, GRPC_BATCH_STATUS));
+ hs_add_error(
+ error_name, &error,
+ grpc_metadata_batch_add_head(
+ op->payload->send_initial_metadata.send_initial_metadata,
+ &calld->status, GRPC_MDELEM_STATUS_200, GRPC_BATCH_STATUS));
hs_add_error(error_name, &error,
grpc_metadata_batch_add_tail(
op->payload->send_initial_metadata.send_initial_metadata,
&calld->content_type,
- GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC,
- GRPC_BATCH_CONTENT_TYPE));
- hs_add_error(error_name, &error,
- hs_filter_outgoing_metadata(
- op->payload->send_initial_metadata.send_initial_metadata));
+ GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC,
+ GRPC_BATCH_CONTENT_TYPE));
+ hs_add_error(error_name, &error,
+ hs_filter_outgoing_metadata(
+ op->payload->send_initial_metadata.send_initial_metadata));
if (error != GRPC_ERROR_NONE) return error;
}
@@ -464,7 +464,7 @@ static grpc_error* hs_mutate_op(grpc_call_element* elem,
if (op->send_trailing_metadata) {
grpc_error* error = hs_filter_outgoing_metadata(
- op->payload->send_trailing_metadata.send_trailing_metadata);
+ op->payload->send_trailing_metadata.send_trailing_metadata);
if (error != GRPC_ERROR_NONE) return error;
}
@@ -493,8 +493,8 @@ static grpc_error* hs_init_call_elem(grpc_call_element* elem,
/* Destructor for call_data */
static void hs_destroy_call_elem(grpc_call_element* elem,
- const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+ const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
}
@@ -512,7 +512,7 @@ static grpc_error* hs_init_channel_elem(grpc_channel_element* elem,
}
/* Destructor for channel data */
-static void hs_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
+static void hs_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
const grpc_channel_filter grpc_http_server_filter = {
hs_start_transport_stream_op_batch,
diff --git a/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc b/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc
index c57efd6d1c..9892a47a57 100644
--- a/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc
@@ -29,9 +29,9 @@
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/transport/http2_errors.h"
-/* If these settings change, make sure that we are not sending a GOAWAY for
- * inproc transport, since a GOAWAY to inproc ends up destroying the transport.
- */
+/* If these settings change, make sure that we are not sending a GOAWAY for
+ * inproc transport, since a GOAWAY to inproc ends up destroying the transport.
+ */
#define DEFAULT_MAX_CONNECTION_AGE_MS INT_MAX
#define DEFAULT_MAX_CONNECTION_AGE_GRACE_MS INT_MAX
#define DEFAULT_MAX_CONNECTION_IDLE_MS INT_MAX
@@ -50,7 +50,7 @@
namespace {
struct channel_data {
- /* The channel stack to which we take refs for pending callbacks. */
+ /* The channel stack to which we take refs for pending callbacks. */
grpc_channel_stack* channel_stack;
/* Guards access to max_age_timer, max_age_timer_pending, max_age_grace_timer
and max_age_grace_timer_pending */
@@ -121,8 +121,8 @@ struct channel_data {
MAX_IDLE_STATE_SEEN_ENTER_IDLE: The state after the timer is set and the at
least one call has arrived after the timer is set, BUT the channel
- currently has 0 active calls. If the timer is fired in this state, we will
- reschudle it.
+ currently has 0 active calls. If the timer is fired in this state, we will
+ reschudle it.
max_idle_timer will not be cancelled (unless the channel is shutting down).
If the timer callback is called when the max_idle_timer is valid (i.e.
@@ -206,7 +206,7 @@ static void decrease_call_count(channel_data* chand) {
}
}
-static void start_max_idle_timer_after_init(void* arg, grpc_error* /*error*/) {
+static void start_max_idle_timer_after_init(void* arg, grpc_error* /*error*/) {
channel_data* chand = static_cast<channel_data*>(arg);
/* Decrease call_count. If there are no active calls at this time,
max_idle_timer will start here. If the number of active calls is not 0,
@@ -216,49 +216,49 @@ static void start_max_idle_timer_after_init(void* arg, grpc_error* /*error*/) {
"max_age start_max_idle_timer_after_init");
}
-namespace grpc_core {
-
-class ConnectivityWatcher : public AsyncConnectivityStateWatcherInterface {
- public:
- explicit ConnectivityWatcher(channel_data* chand) : chand_(chand) {
- GRPC_CHANNEL_STACK_REF(chand_->channel_stack, "max_age conn_watch");
- }
-
- ~ConnectivityWatcher() {
- GRPC_CHANNEL_STACK_UNREF(chand_->channel_stack, "max_age conn_watch");
- }
-
- private:
+namespace grpc_core {
+
+class ConnectivityWatcher : public AsyncConnectivityStateWatcherInterface {
+ public:
+ explicit ConnectivityWatcher(channel_data* chand) : chand_(chand) {
+ GRPC_CHANNEL_STACK_REF(chand_->channel_stack, "max_age conn_watch");
+ }
+
+ ~ConnectivityWatcher() {
+ GRPC_CHANNEL_STACK_UNREF(chand_->channel_stack, "max_age conn_watch");
+ }
+
+ private:
void OnConnectivityStateChange(grpc_connectivity_state new_state,
const y_absl::Status& /* status */) override {
- if (new_state != GRPC_CHANNEL_SHUTDOWN) return;
- {
- MutexLock lock(&chand_->max_age_timer_mu);
- if (chand_->max_age_timer_pending) {
- grpc_timer_cancel(&chand_->max_age_timer);
- chand_->max_age_timer_pending = false;
- }
- if (chand_->max_age_grace_timer_pending) {
- grpc_timer_cancel(&chand_->max_age_grace_timer);
- chand_->max_age_grace_timer_pending = false;
- }
- }
- /* If there are no active calls, this increasement will cancel
- max_idle_timer, and prevent max_idle_timer from being started in the
- future. */
- increase_call_count(chand_);
- if (gpr_atm_acq_load(&chand_->idle_state) ==
- MAX_IDLE_STATE_SEEN_EXIT_IDLE) {
- grpc_timer_cancel(&chand_->max_idle_timer);
- }
- }
-
- channel_data* chand_;
-};
-
-} // namespace grpc_core
-
-static void start_max_age_timer_after_init(void* arg, grpc_error* /*error*/) {
+ if (new_state != GRPC_CHANNEL_SHUTDOWN) return;
+ {
+ MutexLock lock(&chand_->max_age_timer_mu);
+ if (chand_->max_age_timer_pending) {
+ grpc_timer_cancel(&chand_->max_age_timer);
+ chand_->max_age_timer_pending = false;
+ }
+ if (chand_->max_age_grace_timer_pending) {
+ grpc_timer_cancel(&chand_->max_age_grace_timer);
+ chand_->max_age_grace_timer_pending = false;
+ }
+ }
+ /* If there are no active calls, this increasement will cancel
+ max_idle_timer, and prevent max_idle_timer from being started in the
+ future. */
+ increase_call_count(chand_);
+ if (gpr_atm_acq_load(&chand_->idle_state) ==
+ MAX_IDLE_STATE_SEEN_EXIT_IDLE) {
+ grpc_timer_cancel(&chand_->max_idle_timer);
+ }
+ }
+
+ channel_data* chand_;
+};
+
+} // namespace grpc_core
+
+static void start_max_age_timer_after_init(void* arg, grpc_error* /*error*/) {
channel_data* chand = static_cast<channel_data*>(arg);
gpr_mu_lock(&chand->max_age_timer_mu);
chand->max_age_timer_pending = true;
@@ -268,15 +268,15 @@ static void start_max_age_timer_after_init(void* arg, grpc_error* /*error*/) {
&chand->close_max_age_channel);
gpr_mu_unlock(&chand->max_age_timer_mu);
grpc_transport_op* op = grpc_make_transport_op(nullptr);
- op->start_connectivity_watch.reset(new grpc_core::ConnectivityWatcher(chand));
- op->start_connectivity_watch_state = GRPC_CHANNEL_IDLE;
+ op->start_connectivity_watch.reset(new grpc_core::ConnectivityWatcher(chand));
+ op->start_connectivity_watch_state = GRPC_CHANNEL_IDLE;
grpc_channel_next_op(grpc_channel_stack_element(chand->channel_stack, 0), op);
GRPC_CHANNEL_STACK_UNREF(chand->channel_stack,
"max_age start_max_age_timer_after_init");
}
static void start_max_age_grace_timer_after_goaway_op(void* arg,
- grpc_error* /*error*/) {
+ grpc_error* /*error*/) {
channel_data* chand = static_cast<channel_data*>(arg);
gpr_mu_lock(&chand->max_age_timer_mu);
chand->max_age_grace_timer_pending = true;
@@ -407,24 +407,24 @@ add_random_max_connection_age_jitter_and_convert_to_grpc_millis(int value) {
}
/* Constructor for call_data. */
-static grpc_error* max_age_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* /*args*/) {
+static grpc_error* max_age_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* /*args*/) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
increase_call_count(chand);
return GRPC_ERROR_NONE;
}
/* Destructor for call_data. */
-static void max_age_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void max_age_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
decrease_call_count(chand);
}
/* Constructor for channel_data. */
-static grpc_error* max_age_init_channel_elem(grpc_channel_element* elem,
- grpc_channel_element_args* args) {
+static grpc_error* max_age_init_channel_elem(grpc_channel_element* elem,
+ grpc_channel_element_args* args) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
gpr_mu_init(&chand->max_age_timer_mu);
chand->max_age_timer_pending = false;
@@ -492,9 +492,9 @@ static grpc_error* max_age_init_channel_elem(grpc_channel_element* elem,
initialization is done. */
GRPC_CHANNEL_STACK_REF(chand->channel_stack,
"max_age start_max_age_timer_after_init");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- &chand->start_max_age_timer_after_init,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ &chand->start_max_age_timer_after_init,
+ GRPC_ERROR_NONE);
}
/* Initialize the number of calls as 1, so that the max_idle_timer will not
@@ -503,34 +503,34 @@ static grpc_error* max_age_init_channel_elem(grpc_channel_element* elem,
if (chand->max_connection_idle != GRPC_MILLIS_INF_FUTURE) {
GRPC_CHANNEL_STACK_REF(chand->channel_stack,
"max_age start_max_idle_timer_after_init");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- &chand->start_max_idle_timer_after_init,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ &chand->start_max_idle_timer_after_init,
+ GRPC_ERROR_NONE);
}
return GRPC_ERROR_NONE;
}
/* Destructor for channel_data. */
-static void max_age_destroy_channel_elem(grpc_channel_element* elem) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- gpr_mu_destroy(&chand->max_age_timer_mu);
-}
+static void max_age_destroy_channel_elem(grpc_channel_element* elem) {
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ gpr_mu_destroy(&chand->max_age_timer_mu);
+}
const grpc_channel_filter grpc_max_age_filter = {
grpc_call_next_op,
grpc_channel_next_op,
0, /* sizeof_call_data */
- max_age_init_call_elem,
+ max_age_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- max_age_destroy_call_elem,
+ max_age_destroy_call_elem,
sizeof(channel_data),
- max_age_init_channel_elem,
- max_age_destroy_channel_elem,
+ max_age_init_channel_elem,
+ max_age_destroy_channel_elem,
grpc_channel_next_get_info,
"max_age"};
static bool maybe_add_max_age_filter(grpc_channel_stack_builder* builder,
- void* /*arg*/) {
+ void* /*arg*/) {
const grpc_channel_args* channel_args =
grpc_channel_stack_builder_get_channel_arguments(builder);
bool enable =
diff --git a/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc b/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc
index 944479ac3b..3c61fe0dc3 100644
--- a/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc
@@ -27,24 +27,24 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/ext/filters/client_channel/service_config_call_data.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack_builder.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel_init.h"
-static void recv_message_ready(void* user_data, grpc_error* error);
-static void recv_trailing_metadata_ready(void* user_data, grpc_error* error);
+static void recv_message_ready(void* user_data, grpc_error* error);
+static void recv_trailing_metadata_ready(void* user_data, grpc_error* error);
namespace grpc_core {
-
+
namespace {
-size_t g_message_size_parser_index;
-} // namespace
+size_t g_message_size_parser_index;
+} // namespace
//
// MessageSizeParsedConfig
@@ -68,7 +68,7 @@ const MessageSizeParsedConfig* MessageSizeParsedConfig::GetFromCallContext(
std::unique_ptr<ServiceConfigParser::ParsedConfig>
MessageSizeParser::ParsePerMethodParams(const grpc_channel_args* /*args*/,
const Json& json, grpc_error** error) {
- GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
+ GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
std::vector<grpc_error*> error_list;
// Max request size.
int max_request_message_bytes = -1;
@@ -82,7 +82,7 @@ MessageSizeParser::ParsePerMethodParams(const grpc_channel_args* /*args*/,
max_request_message_bytes =
gpr_parse_nonnegative_int(it->second.string_value().c_str());
if (max_request_message_bytes == -1) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:maxRequestMessageBytes error:should be non-negative"));
}
}
@@ -99,25 +99,25 @@ MessageSizeParser::ParsePerMethodParams(const grpc_channel_args* /*args*/,
max_response_message_bytes =
gpr_parse_nonnegative_int(it->second.string_value().c_str());
if (max_response_message_bytes == -1) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:maxResponseMessageBytes error:should be non-negative"));
}
}
}
- if (!error_list.empty()) {
- *error = GRPC_ERROR_CREATE_FROM_VECTOR("Message size parser", &error_list);
- return nullptr;
- }
+ if (!error_list.empty()) {
+ *error = GRPC_ERROR_CREATE_FROM_VECTOR("Message size parser", &error_list);
+ return nullptr;
+ }
return y_absl::make_unique<MessageSizeParsedConfig>(max_request_message_bytes,
max_response_message_bytes);
}
-void MessageSizeParser::Register() {
+void MessageSizeParser::Register() {
g_message_size_parser_index = ServiceConfigParser::RegisterParser(
y_absl::make_unique<MessageSizeParser>());
-}
-
-size_t MessageSizeParser::ParserIndex() { return g_message_size_parser_index; }
+}
+
+size_t MessageSizeParser::ParserIndex() { return g_message_size_parser_index; }
int GetMaxRecvSizeFromChannelArgs(const grpc_channel_args* args) {
if (grpc_channel_args_want_minimal_stack(args)) return -1;
@@ -137,7 +137,7 @@ int GetMaxSendSizeFromChannelArgs(const grpc_channel_args* args) {
namespace {
struct channel_data {
- grpc_core::MessageSizeParsedConfig::message_size_limits limits;
+ grpc_core::MessageSizeParsedConfig::message_size_limits limits;
};
struct call_data {
@@ -155,24 +155,24 @@ struct call_data {
// size to the receive limit.
const grpc_core::MessageSizeParsedConfig* limits =
grpc_core::MessageSizeParsedConfig::GetFromCallContext(args.context);
- if (limits != nullptr) {
- if (limits->limits().max_send_size >= 0 &&
- (limits->limits().max_send_size < this->limits.max_send_size ||
- this->limits.max_send_size < 0)) {
- this->limits.max_send_size = limits->limits().max_send_size;
- }
- if (limits->limits().max_recv_size >= 0 &&
- (limits->limits().max_recv_size < this->limits.max_recv_size ||
- this->limits.max_recv_size < 0)) {
- this->limits.max_recv_size = limits->limits().max_recv_size;
- }
- }
+ if (limits != nullptr) {
+ if (limits->limits().max_send_size >= 0 &&
+ (limits->limits().max_send_size < this->limits.max_send_size ||
+ this->limits.max_send_size < 0)) {
+ this->limits.max_send_size = limits->limits().max_send_size;
+ }
+ if (limits->limits().max_recv_size >= 0 &&
+ (limits->limits().max_recv_size < this->limits.max_recv_size ||
+ this->limits.max_recv_size < 0)) {
+ this->limits.max_recv_size = limits->limits().max_recv_size;
+ }
+ }
}
~call_data() { GRPC_ERROR_UNREF(error); }
- grpc_core::CallCombiner* call_combiner;
- grpc_core::MessageSizeParsedConfig::message_size_limits limits;
+ grpc_core::CallCombiner* call_combiner;
+ grpc_core::MessageSizeParsedConfig::message_size_limits limits;
// Receive closures are chained: we inject this closure as the
// recv_message_ready up-call on transport_stream_op, and remember to
// call our next_recv_message_ready member after handling it.
@@ -228,7 +228,7 @@ static void recv_message_ready(void* user_data, grpc_error* error) {
calld->recv_trailing_metadata_error,
"continue recv_trailing_metadata_ready");
}
- grpc_core::Closure::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::Closure::Run(DEBUG_LOCATION, closure, error);
}
// Callback invoked on completion of recv_trailing_metadata
@@ -247,12 +247,12 @@ static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) {
error =
grpc_error_add_child(GRPC_ERROR_REF(error), GRPC_ERROR_REF(calld->error));
// Invoke the next callback.
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_recv_trailing_metadata_ready, error);
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_recv_trailing_metadata_ready, error);
}
// Start transport stream op.
-static void message_size_start_transport_stream_op_batch(
+static void message_size_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
call_data* calld = static_cast<call_data*>(elem->call_data);
// Check max send message size.
@@ -291,89 +291,89 @@ static void message_size_start_transport_stream_op_batch(
}
// Constructor for call_data.
-static grpc_error* message_size_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* args) {
+static grpc_error* message_size_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* args) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
new (elem->call_data) call_data(elem, *chand, *args);
return GRPC_ERROR_NONE;
}
// Destructor for call_data.
-static void message_size_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void message_size_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
call_data* calld = (call_data*)elem->call_data;
calld->~call_data();
}
-grpc_core::MessageSizeParsedConfig::message_size_limits get_message_size_limits(
+grpc_core::MessageSizeParsedConfig::message_size_limits get_message_size_limits(
const grpc_channel_args* channel_args) {
- grpc_core::MessageSizeParsedConfig::message_size_limits lim;
+ grpc_core::MessageSizeParsedConfig::message_size_limits lim;
lim.max_send_size = grpc_core::GetMaxSendSizeFromChannelArgs(channel_args);
lim.max_recv_size = grpc_core::GetMaxRecvSizeFromChannelArgs(channel_args);
return lim;
}
// Constructor for channel_data.
-static grpc_error* message_size_init_channel_elem(
- grpc_channel_element* elem, grpc_channel_element_args* args) {
+static grpc_error* message_size_init_channel_elem(
+ grpc_channel_element* elem, grpc_channel_element_args* args) {
GPR_ASSERT(!args->is_last);
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- new (chand) channel_data();
+ new (chand) channel_data();
chand->limits = get_message_size_limits(args->channel_args);
return GRPC_ERROR_NONE;
}
// Destructor for channel_data.
-static void message_size_destroy_channel_elem(grpc_channel_element* elem) {
+static void message_size_destroy_channel_elem(grpc_channel_element* elem) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- chand->~channel_data();
+ chand->~channel_data();
}
const grpc_channel_filter grpc_message_size_filter = {
- message_size_start_transport_stream_op_batch,
+ message_size_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- message_size_init_call_elem,
+ message_size_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- message_size_destroy_call_elem,
+ message_size_destroy_call_elem,
sizeof(channel_data),
- message_size_init_channel_elem,
- message_size_destroy_channel_elem,
+ message_size_init_channel_elem,
+ message_size_destroy_channel_elem,
grpc_channel_next_get_info,
"message_size"};
-// Used for GRPC_CLIENT_SUBCHANNEL
-static bool maybe_add_message_size_filter_subchannel(
- grpc_channel_stack_builder* builder, void* /*arg*/) {
- const grpc_channel_args* channel_args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- if (grpc_channel_args_want_minimal_stack(channel_args)) {
- return true;
- }
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_message_size_filter, nullptr, nullptr);
-}
-
-// Used for GRPC_CLIENT_DIRECT_CHANNEL and GRPC_SERVER_CHANNEL. Adds the filter
-// only if message size limits or service config is specified.
+// Used for GRPC_CLIENT_SUBCHANNEL
+static bool maybe_add_message_size_filter_subchannel(
+ grpc_channel_stack_builder* builder, void* /*arg*/) {
+ const grpc_channel_args* channel_args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ if (grpc_channel_args_want_minimal_stack(channel_args)) {
+ return true;
+ }
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_message_size_filter, nullptr, nullptr);
+}
+
+// Used for GRPC_CLIENT_DIRECT_CHANNEL and GRPC_SERVER_CHANNEL. Adds the filter
+// only if message size limits or service config is specified.
static bool maybe_add_message_size_filter(grpc_channel_stack_builder* builder,
- void* /*arg*/) {
+ void* /*arg*/) {
const grpc_channel_args* channel_args =
grpc_channel_stack_builder_get_channel_arguments(builder);
if (grpc_channel_args_want_minimal_stack(channel_args)) {
return true;
}
bool enable = false;
- grpc_core::MessageSizeParsedConfig::message_size_limits lim =
- get_message_size_limits(channel_args);
+ grpc_core::MessageSizeParsedConfig::message_size_limits lim =
+ get_message_size_limits(channel_args);
if (lim.max_send_size != -1 || lim.max_recv_size != -1) {
enable = true;
}
const grpc_arg* a =
grpc_channel_args_find(channel_args, GRPC_ARG_SERVICE_CONFIG);
- const char* svc_cfg_str = grpc_channel_arg_get_string(a);
- if (svc_cfg_str != nullptr) {
+ const char* svc_cfg_str = grpc_channel_arg_get_string(a);
+ if (svc_cfg_str != nullptr) {
enable = true;
}
if (enable) {
@@ -385,16 +385,16 @@ static bool maybe_add_message_size_filter(grpc_channel_stack_builder* builder,
}
void grpc_message_size_filter_init(void) {
- grpc_channel_init_register_stage(
- GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_message_size_filter_subchannel, nullptr);
+ grpc_channel_init_register_stage(
+ GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_message_size_filter_subchannel, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
maybe_add_message_size_filter, nullptr);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
maybe_add_message_size_filter, nullptr);
- grpc_core::MessageSizeParser::Register();
+ grpc_core::MessageSizeParser::Register();
}
void grpc_message_size_filter_shutdown(void) {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.h b/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.h
index 0583a78926..ff405ff606 100644
--- a/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.h
@@ -24,43 +24,43 @@
extern const grpc_channel_filter grpc_message_size_filter;
-namespace grpc_core {
-
+namespace grpc_core {
+
class MessageSizeParsedConfig : public ServiceConfigParser::ParsedConfig {
- public:
- struct message_size_limits {
- int max_send_size;
- int max_recv_size;
- };
-
- MessageSizeParsedConfig(int max_send_size, int max_recv_size) {
- limits_.max_send_size = max_send_size;
- limits_.max_recv_size = max_recv_size;
- }
-
- const message_size_limits& limits() const { return limits_; }
-
+ public:
+ struct message_size_limits {
+ int max_send_size;
+ int max_recv_size;
+ };
+
+ MessageSizeParsedConfig(int max_send_size, int max_recv_size) {
+ limits_.max_send_size = max_send_size;
+ limits_.max_recv_size = max_recv_size;
+ }
+
+ const message_size_limits& limits() const { return limits_; }
+
static const MessageSizeParsedConfig* GetFromCallContext(
const grpc_call_context_element* context);
- private:
- message_size_limits limits_;
-};
-
+ private:
+ message_size_limits limits_;
+};
+
class MessageSizeParser : public ServiceConfigParser::Parser {
- public:
+ public:
std::unique_ptr<ServiceConfigParser::ParsedConfig> ParsePerMethodParams(
const grpc_channel_args* /*args*/, const Json& json,
grpc_error** error) override;
-
- static void Register();
-
- static size_t ParserIndex();
-};
-
+
+ static void Register();
+
+ static size_t ParserIndex();
+};
+
int GetMaxRecvSizeFromChannelArgs(const grpc_channel_args* args);
int GetMaxSendSizeFromChannelArgs(const grpc_channel_args* args);
-} // namespace grpc_core
-
+} // namespace grpc_core
+
#endif /* GRPC_CORE_EXT_FILTERS_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc
index 7f9a4fcaf8..f9def4cd55 100644
--- a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc
@@ -70,13 +70,13 @@ static void recv_initial_metadata_ready(void* user_data, grpc_error* error) {
}
// Invoke the next callback.
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->next_recv_initial_metadata_ready,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->next_recv_initial_metadata_ready,
+ GRPC_ERROR_REF(error));
}
// Start transport stream op.
-static void cronet_compression_start_transport_stream_op_batch(
+static void cronet_compression_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
call_data* calld = static_cast<call_data*>(elem->call_data);
@@ -105,8 +105,8 @@ static void cronet_compression_start_transport_stream_op_batch(
}
// Constructor for call_data.
-static grpc_error* cronet_compression_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* /*args*/) {
+static grpc_error* cronet_compression_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* /*args*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->next_recv_initial_metadata_ready = nullptr;
calld->workaround_active = false;
@@ -117,19 +117,19 @@ static grpc_error* cronet_compression_init_call_elem(
}
// Destructor for call_data.
-static void cronet_compression_destroy_call_elem(
- grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {}
+static void cronet_compression_destroy_call_elem(
+ grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {}
// Constructor for channel_data.
-static grpc_error* cronet_compression_init_channel_elem(
- grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) {
+static grpc_error* cronet_compression_init_channel_elem(
+ grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) {
return GRPC_ERROR_NONE;
}
// Destructor for channel_data.
-static void cronet_compression_destroy_channel_elem(
- grpc_channel_element* /*elem*/) {}
+static void cronet_compression_destroy_channel_elem(
+ grpc_channel_element* /*elem*/) {}
// Parse the user agent
static bool parse_user_agent(grpc_mdelem md) {
@@ -171,20 +171,20 @@ static bool parse_user_agent(grpc_mdelem md) {
}
const grpc_channel_filter grpc_workaround_cronet_compression_filter = {
- cronet_compression_start_transport_stream_op_batch,
+ cronet_compression_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- cronet_compression_init_call_elem,
+ cronet_compression_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- cronet_compression_destroy_call_elem,
+ cronet_compression_destroy_call_elem,
0,
- cronet_compression_init_channel_elem,
- cronet_compression_destroy_channel_elem,
+ cronet_compression_init_channel_elem,
+ cronet_compression_destroy_channel_elem,
grpc_channel_next_get_info,
"workaround_cronet_compression"};
static bool register_workaround_cronet_compression(
- grpc_channel_stack_builder* builder, void* /*arg*/) {
+ grpc_channel_stack_builder* builder, void* /*arg*/) {
const grpc_channel_args* channel_args =
grpc_channel_stack_builder_get_channel_arguments(builder);
const grpc_arg* a = grpc_channel_args_find(
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.h
index e2ffe4e405..4223ecdb56 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.h
@@ -23,7 +23,7 @@
#include <string.h>
-/* Returns 1 if the version is supported, 0 otherwise. */
+/* Returns 1 if the version is supported, 0 otherwise. */
int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size);
/* Returns the number of protocol versions to advertise */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.cc
index 3408ed9267..db3653e8c4 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.cc
@@ -38,95 +38,95 @@
#include "src/core/lib/iomgr/tcp_client.h"
#include "src/core/lib/slice/slice_internal.h"
-namespace grpc_core {
+namespace grpc_core {
-Chttp2Connector::Chttp2Connector() {
- GRPC_CLOSURE_INIT(&connected_, Connected, this, grpc_schedule_on_exec_ctx);
-}
+Chttp2Connector::Chttp2Connector() {
+ GRPC_CLOSURE_INIT(&connected_, Connected, this, grpc_schedule_on_exec_ctx);
+}
-Chttp2Connector::~Chttp2Connector() {
- if (endpoint_ != nullptr) grpc_endpoint_destroy(endpoint_);
+Chttp2Connector::~Chttp2Connector() {
+ if (endpoint_ != nullptr) grpc_endpoint_destroy(endpoint_);
}
-void Chttp2Connector::Connect(const Args& args, Result* result,
- grpc_closure* notify) {
- grpc_resolved_address addr;
- Subchannel::GetAddressFromSubchannelAddressArg(args.channel_args, &addr);
- grpc_endpoint** ep;
- {
- MutexLock lock(&mu_);
- GPR_ASSERT(notify_ == nullptr);
- args_ = args;
- result_ = result;
- notify_ = notify;
- GPR_ASSERT(!connecting_);
- connecting_ = true;
- GPR_ASSERT(endpoint_ == nullptr);
- ep = &endpoint_;
+void Chttp2Connector::Connect(const Args& args, Result* result,
+ grpc_closure* notify) {
+ grpc_resolved_address addr;
+ Subchannel::GetAddressFromSubchannelAddressArg(args.channel_args, &addr);
+ grpc_endpoint** ep;
+ {
+ MutexLock lock(&mu_);
+ GPR_ASSERT(notify_ == nullptr);
+ args_ = args;
+ result_ = result;
+ notify_ = notify;
+ GPR_ASSERT(!connecting_);
+ connecting_ = true;
+ GPR_ASSERT(endpoint_ == nullptr);
+ ep = &endpoint_;
}
- // In some implementations, the closure can be flushed before
- // grpc_tcp_client_connect() returns, and since the closure requires access
- // to mu_, this can result in a deadlock (see
- // https://github.com/grpc/grpc/issues/16427 for details).
- // grpc_tcp_client_connect() will fill endpoint_ with proper contents, and we
- // make sure that we still exist at that point by taking a ref.
- Ref().release(); // Ref held by callback.
- grpc_tcp_client_connect(&connected_, ep, args.interested_parties,
- args.channel_args, &addr, args.deadline);
+ // In some implementations, the closure can be flushed before
+ // grpc_tcp_client_connect() returns, and since the closure requires access
+ // to mu_, this can result in a deadlock (see
+ // https://github.com/grpc/grpc/issues/16427 for details).
+ // grpc_tcp_client_connect() will fill endpoint_ with proper contents, and we
+ // make sure that we still exist at that point by taking a ref.
+ Ref().release(); // Ref held by callback.
+ grpc_tcp_client_connect(&connected_, ep, args.interested_parties,
+ args.channel_args, &addr, args.deadline);
}
-void Chttp2Connector::Shutdown(grpc_error* error) {
- MutexLock lock(&mu_);
- shutdown_ = true;
- if (handshake_mgr_ != nullptr) {
- handshake_mgr_->Shutdown(GRPC_ERROR_REF(error));
+void Chttp2Connector::Shutdown(grpc_error* error) {
+ MutexLock lock(&mu_);
+ shutdown_ = true;
+ if (handshake_mgr_ != nullptr) {
+ handshake_mgr_->Shutdown(GRPC_ERROR_REF(error));
}
// If handshaking is not yet in progress, shutdown the endpoint.
// Otherwise, the handshaker will do this for us.
- if (!connecting_ && endpoint_ != nullptr) {
- grpc_endpoint_shutdown(endpoint_, GRPC_ERROR_REF(error));
+ if (!connecting_ && endpoint_ != nullptr) {
+ grpc_endpoint_shutdown(endpoint_, GRPC_ERROR_REF(error));
}
- GRPC_ERROR_UNREF(error);
+ GRPC_ERROR_UNREF(error);
}
-void Chttp2Connector::Connected(void* arg, grpc_error* error) {
- Chttp2Connector* self = static_cast<Chttp2Connector*>(arg);
- bool unref = false;
- {
- MutexLock lock(&self->mu_);
- GPR_ASSERT(self->connecting_);
- self->connecting_ = false;
- if (error != GRPC_ERROR_NONE || self->shutdown_) {
- if (error == GRPC_ERROR_NONE) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("connector shutdown");
- } else {
- error = GRPC_ERROR_REF(error);
- }
- if (self->endpoint_ != nullptr) {
- grpc_endpoint_shutdown(self->endpoint_, GRPC_ERROR_REF(error));
- }
- self->result_->Reset();
- grpc_closure* notify = self->notify_;
- self->notify_ = nullptr;
- ExecCtx::Run(DEBUG_LOCATION, notify, error);
- unref = true;
+void Chttp2Connector::Connected(void* arg, grpc_error* error) {
+ Chttp2Connector* self = static_cast<Chttp2Connector*>(arg);
+ bool unref = false;
+ {
+ MutexLock lock(&self->mu_);
+ GPR_ASSERT(self->connecting_);
+ self->connecting_ = false;
+ if (error != GRPC_ERROR_NONE || self->shutdown_) {
+ if (error == GRPC_ERROR_NONE) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("connector shutdown");
+ } else {
+ error = GRPC_ERROR_REF(error);
+ }
+ if (self->endpoint_ != nullptr) {
+ grpc_endpoint_shutdown(self->endpoint_, GRPC_ERROR_REF(error));
+ }
+ self->result_->Reset();
+ grpc_closure* notify = self->notify_;
+ self->notify_ = nullptr;
+ ExecCtx::Run(DEBUG_LOCATION, notify, error);
+ unref = true;
} else {
- GPR_ASSERT(self->endpoint_ != nullptr);
- self->StartHandshakeLocked();
+ GPR_ASSERT(self->endpoint_ != nullptr);
+ self->StartHandshakeLocked();
}
}
- if (unref) self->Unref();
+ if (unref) self->Unref();
}
-void Chttp2Connector::StartHandshakeLocked() {
- handshake_mgr_ = MakeRefCounted<HandshakeManager>();
- HandshakerRegistry::AddHandshakers(HANDSHAKER_CLIENT, args_.channel_args,
- args_.interested_parties,
- handshake_mgr_.get());
- grpc_endpoint_add_to_pollset_set(endpoint_, args_.interested_parties);
- handshake_mgr_->DoHandshake(endpoint_, args_.channel_args, args_.deadline,
- nullptr /* acceptor */, OnHandshakeDone, this);
- endpoint_ = nullptr; // Endpoint handed off to handshake manager.
+void Chttp2Connector::StartHandshakeLocked() {
+ handshake_mgr_ = MakeRefCounted<HandshakeManager>();
+ HandshakerRegistry::AddHandshakers(HANDSHAKER_CLIENT, args_.channel_args,
+ args_.interested_parties,
+ handshake_mgr_.get());
+ grpc_endpoint_add_to_pollset_set(endpoint_, args_.interested_parties);
+ handshake_mgr_->DoHandshake(endpoint_, args_.channel_args, args_.deadline,
+ nullptr /* acceptor */, OnHandshakeDone, this);
+ endpoint_ = nullptr; // Endpoint handed off to handshake manager.
}
namespace {
@@ -138,60 +138,60 @@ void NullThenSchedClosure(const DebugLocation& location, grpc_closure** closure,
}
} // namespace
-void Chttp2Connector::OnHandshakeDone(void* arg, grpc_error* error) {
- auto* args = static_cast<HandshakerArgs*>(arg);
- Chttp2Connector* self = static_cast<Chttp2Connector*>(args->user_data);
- {
- MutexLock lock(&self->mu_);
- if (error != GRPC_ERROR_NONE || self->shutdown_) {
- if (error == GRPC_ERROR_NONE) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("connector shutdown");
- // We were shut down after handshaking completed successfully, so
- // destroy the endpoint here.
- if (args->endpoint != nullptr) {
- // TODO(ctiller): It is currently necessary to shutdown endpoints
- // before destroying them, even if we know that there are no
- // pending read/write callbacks. This should be fixed, at which
- // point this can be removed.
- grpc_endpoint_shutdown(args->endpoint, GRPC_ERROR_REF(error));
- grpc_endpoint_destroy(args->endpoint);
- grpc_channel_args_destroy(args->args);
- grpc_slice_buffer_destroy_internal(args->read_buffer);
- gpr_free(args->read_buffer);
- }
- } else {
- error = GRPC_ERROR_REF(error);
- }
- self->result_->Reset();
+void Chttp2Connector::OnHandshakeDone(void* arg, grpc_error* error) {
+ auto* args = static_cast<HandshakerArgs*>(arg);
+ Chttp2Connector* self = static_cast<Chttp2Connector*>(args->user_data);
+ {
+ MutexLock lock(&self->mu_);
+ if (error != GRPC_ERROR_NONE || self->shutdown_) {
+ if (error == GRPC_ERROR_NONE) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("connector shutdown");
+ // We were shut down after handshaking completed successfully, so
+ // destroy the endpoint here.
+ if (args->endpoint != nullptr) {
+ // TODO(ctiller): It is currently necessary to shutdown endpoints
+ // before destroying them, even if we know that there are no
+ // pending read/write callbacks. This should be fixed, at which
+ // point this can be removed.
+ grpc_endpoint_shutdown(args->endpoint, GRPC_ERROR_REF(error));
+ grpc_endpoint_destroy(args->endpoint);
+ grpc_channel_args_destroy(args->args);
+ grpc_slice_buffer_destroy_internal(args->read_buffer);
+ gpr_free(args->read_buffer);
+ }
+ } else {
+ error = GRPC_ERROR_REF(error);
+ }
+ self->result_->Reset();
NullThenSchedClosure(DEBUG_LOCATION, &self->notify_, error);
- } else if (args->endpoint != nullptr) {
- self->result_->transport =
- grpc_create_chttp2_transport(args->args, args->endpoint, true);
- self->result_->socket_node =
- grpc_chttp2_transport_get_socket_node(self->result_->transport);
+ } else if (args->endpoint != nullptr) {
+ self->result_->transport =
+ grpc_create_chttp2_transport(args->args, args->endpoint, true);
+ self->result_->socket_node =
+ grpc_chttp2_transport_get_socket_node(self->result_->transport);
self->result_->channel_args = args->args;
- GPR_ASSERT(self->result_->transport != nullptr);
+ GPR_ASSERT(self->result_->transport != nullptr);
self->endpoint_ = args->endpoint;
self->Ref().release(); // Ref held by OnReceiveSettings()
GRPC_CLOSURE_INIT(&self->on_receive_settings_, OnReceiveSettings, self,
grpc_schedule_on_exec_ctx);
self->Ref().release(); // Ref held by OnTimeout()
- grpc_chttp2_transport_start_reading(self->result_->transport,
+ grpc_chttp2_transport_start_reading(self->result_->transport,
args->read_buffer,
&self->on_receive_settings_);
GRPC_CLOSURE_INIT(&self->on_timeout_, OnTimeout, self,
grpc_schedule_on_exec_ctx);
grpc_timer_init(&self->timer_, self->args_.deadline, &self->on_timeout_);
} else {
- // If the handshaking succeeded but there is no endpoint, then the
- // handshaker may have handed off the connection to some external
- // code. Just verify that exit_early flag is set.
- GPR_DEBUG_ASSERT(args->exit_early);
+ // If the handshaking succeeded but there is no endpoint, then the
+ // handshaker may have handed off the connection to some external
+ // code. Just verify that exit_early flag is set.
+ GPR_DEBUG_ASSERT(args->exit_early);
NullThenSchedClosure(DEBUG_LOCATION, &self->notify_, error);
}
- self->handshake_mgr_.reset();
+ self->handshake_mgr_.reset();
}
- self->Unref();
+ self->Unref();
}
void Chttp2Connector::OnReceiveSettings(void* arg, grpc_error* error) {
@@ -259,4 +259,4 @@ void Chttp2Connector::MaybeNotify(grpc_error* error) {
}
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h
index 322cbc2eba..6f764d1251 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h
@@ -22,26 +22,26 @@
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/connector.h"
-#include "src/core/lib/channel/handshaker.h"
-#include "src/core/lib/channel/handshaker_registry.h"
+#include "src/core/lib/channel/handshaker.h"
+#include "src/core/lib/channel/handshaker_registry.h"
-namespace grpc_core {
+namespace grpc_core {
-class Chttp2Connector : public SubchannelConnector {
- public:
- Chttp2Connector();
- ~Chttp2Connector();
-
- void Connect(const Args& args, Result* result, grpc_closure* notify) override;
- void Shutdown(grpc_error* error) override;
-
- private:
- static void Connected(void* arg, grpc_error* error);
- void StartHandshakeLocked();
- static void OnHandshakeDone(void* arg, grpc_error* error);
+class Chttp2Connector : public SubchannelConnector {
+ public:
+ Chttp2Connector();
+ ~Chttp2Connector();
+
+ void Connect(const Args& args, Result* result, grpc_closure* notify) override;
+ void Shutdown(grpc_error* error) override;
+
+ private:
+ static void Connected(void* arg, grpc_error* error);
+ void StartHandshakeLocked();
+ static void OnHandshakeDone(void* arg, grpc_error* error);
static void OnReceiveSettings(void* arg, grpc_error* error);
static void OnTimeout(void* arg, grpc_error* error);
-
+
// We cannot invoke notify_ until both OnTimeout() and OnReceiveSettings()
// have been called since that is an indicator to the upper layer that we are
// done with the connection attempt. So, the notification process is broken
@@ -53,23 +53,23 @@ class Chttp2Connector : public SubchannelConnector {
// connector is waiting on the SETTINGS frame.
void MaybeNotify(grpc_error* error);
- Mutex mu_;
- Args args_;
- Result* result_ = nullptr;
- grpc_closure* notify_ = nullptr;
- bool shutdown_ = false;
- bool connecting_ = false;
- // Holds the endpoint when first created before being handed off to
+ Mutex mu_;
+ Args args_;
+ Result* result_ = nullptr;
+ grpc_closure* notify_ = nullptr;
+ bool shutdown_ = false;
+ bool connecting_ = false;
+ // Holds the endpoint when first created before being handed off to
// the handshake manager, and then again after handshake is done.
- grpc_endpoint* endpoint_ = nullptr;
- grpc_closure connected_;
+ grpc_endpoint* endpoint_ = nullptr;
+ grpc_closure connected_;
grpc_closure on_receive_settings_;
grpc_timer timer_;
grpc_closure on_timeout_;
y_absl::optional<grpc_error*> notify_error_;
- RefCountedPtr<HandshakeManager> handshake_mgr_;
-};
-
-} // namespace grpc_core
-
+ RefCountedPtr<HandshakeManager> handshake_mgr_;
+};
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_CHTTP2_CONNECTOR_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create.cc
index 189ed7d1ce..26607a7971 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create.cc
@@ -33,30 +33,30 @@
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/channel.h"
-namespace grpc_core {
-
-class Chttp2InsecureClientChannelFactory : public ClientChannelFactory {
- public:
- Subchannel* CreateSubchannel(const grpc_channel_args* args) override {
- grpc_channel_args* new_args =
- grpc_default_authority_add_if_not_present(args);
- Subchannel* s =
- Subchannel::Create(MakeOrphanable<Chttp2Connector>(), new_args);
- grpc_channel_args_destroy(new_args);
- return s;
- }
-};
-
-namespace {
-
-grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args) {
+namespace grpc_core {
+
+class Chttp2InsecureClientChannelFactory : public ClientChannelFactory {
+ public:
+ Subchannel* CreateSubchannel(const grpc_channel_args* args) override {
+ grpc_channel_args* new_args =
+ grpc_default_authority_add_if_not_present(args);
+ Subchannel* s =
+ Subchannel::Create(MakeOrphanable<Chttp2Connector>(), new_args);
+ grpc_channel_args_destroy(new_args);
+ return s;
+ }
+};
+
+namespace {
+
+grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args) {
if (target == nullptr) {
gpr_log(GPR_ERROR, "cannot create channel with NULL target name");
return nullptr;
}
// Add channel arg containing the server URI.
grpc_core::UniquePtr<char> canonical_target =
- ResolverRegistry::AddDefaultPrefixIfNeeded(target);
+ ResolverRegistry::AddDefaultPrefixIfNeeded(target);
grpc_arg arg = grpc_channel_arg_string_create(
const_cast<char*>(GRPC_ARG_SERVER_URI), canonical_target.get());
const char* to_remove[] = {GRPC_ARG_SERVER_URI};
@@ -68,21 +68,21 @@ grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args) {
return channel;
}
-} // namespace
-
-} // namespace grpc_core
-
-namespace {
-
-grpc_core::Chttp2InsecureClientChannelFactory* g_factory;
-gpr_once g_factory_once = GPR_ONCE_INIT;
-
-void FactoryInit() {
- g_factory = new grpc_core::Chttp2InsecureClientChannelFactory();
-}
-
-} // namespace
-
+} // namespace
+
+} // namespace grpc_core
+
+namespace {
+
+grpc_core::Chttp2InsecureClientChannelFactory* g_factory;
+gpr_once g_factory_once = GPR_ONCE_INIT;
+
+void FactoryInit() {
+ g_factory = new grpc_core::Chttp2InsecureClientChannelFactory();
+}
+
+} // namespace
+
/* Create a client channel:
Asynchronously: - resolve target
- connect to it (trying alternatives as presented)
@@ -96,13 +96,13 @@ grpc_channel* grpc_insecure_channel_create(const char* target,
(target, args, reserved));
GPR_ASSERT(reserved == nullptr);
// Add channel arg containing the client channel factory.
- gpr_once_init(&g_factory_once, FactoryInit);
- grpc_arg arg = grpc_core::ClientChannelFactory::CreateChannelArg(g_factory);
- const char* arg_to_remove = arg.key;
- grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
- args, &arg_to_remove, 1, &arg, 1);
+ gpr_once_init(&g_factory_once, FactoryInit);
+ grpc_arg arg = grpc_core::ClientChannelFactory::CreateChannelArg(g_factory);
+ const char* arg_to_remove = arg.key;
+ grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
+ args, &arg_to_remove, 1, &arg, 1);
// Create channel.
- grpc_channel* channel = grpc_core::CreateChannel(target, new_args);
+ grpc_channel* channel = grpc_core::CreateChannel(target, new_args);
// Clean up.
grpc_channel_args_destroy(new_args);
return channel != nullptr ? channel
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc
index 93dadf3645..7b8b099758 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc
@@ -39,104 +39,104 @@
#include "src/core/lib/transport/authority_override.h"
#include "src/core/lib/uri/uri_parser.h"
-namespace grpc_core {
-
-class Chttp2SecureClientChannelFactory : public ClientChannelFactory {
- public:
- Subchannel* CreateSubchannel(const grpc_channel_args* args) override {
- grpc_channel_args* new_args = GetSecureNamingChannelArgs(args);
- if (new_args == nullptr) {
- gpr_log(GPR_ERROR,
- "Failed to create channel args during subchannel creation.");
- return nullptr;
- }
- Subchannel* s =
- Subchannel::Create(MakeOrphanable<Chttp2Connector>(), new_args);
- grpc_channel_args_destroy(new_args);
- return s;
- }
-
- private:
- static grpc_channel_args* GetSecureNamingChannelArgs(
- const grpc_channel_args* args) {
- grpc_channel_credentials* channel_credentials =
- grpc_channel_credentials_find_in_args(args);
- if (channel_credentials == nullptr) {
- gpr_log(GPR_ERROR,
- "Can't create subchannel: channel credentials missing for secure "
- "channel.");
- return nullptr;
- }
- // Make sure security connector does not already exist in args.
- if (grpc_security_connector_find_in_args(args) != nullptr) {
- gpr_log(GPR_ERROR,
- "Can't create subchannel: security connector already present in "
- "channel args.");
- return nullptr;
+namespace grpc_core {
+
+class Chttp2SecureClientChannelFactory : public ClientChannelFactory {
+ public:
+ Subchannel* CreateSubchannel(const grpc_channel_args* args) override {
+ grpc_channel_args* new_args = GetSecureNamingChannelArgs(args);
+ if (new_args == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Failed to create channel args during subchannel creation.");
+ return nullptr;
+ }
+ Subchannel* s =
+ Subchannel::Create(MakeOrphanable<Chttp2Connector>(), new_args);
+ grpc_channel_args_destroy(new_args);
+ return s;
+ }
+
+ private:
+ static grpc_channel_args* GetSecureNamingChannelArgs(
+ const grpc_channel_args* args) {
+ grpc_channel_credentials* channel_credentials =
+ grpc_channel_credentials_find_in_args(args);
+ if (channel_credentials == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Can't create subchannel: channel credentials missing for secure "
+ "channel.");
+ return nullptr;
}
+ // Make sure security connector does not already exist in args.
+ if (grpc_security_connector_find_in_args(args) != nullptr) {
+ gpr_log(GPR_ERROR,
+ "Can't create subchannel: security connector already present in "
+ "channel args.");
+ return nullptr;
+ }
// Find the authority to use in the security connector.
// First, check the authority override channel arg.
// Otherwise, get it from the server name used to construct the
// channel.
grpc_core::UniquePtr<char> authority(
gpr_strdup(FindAuthorityOverrideInArgs(args)));
- if (authority == nullptr) {
+ if (authority == nullptr) {
const char* server_uri_str =
grpc_channel_args_find_string(args, GRPC_ARG_SERVER_URI);
GPR_ASSERT(server_uri_str != nullptr);
- authority = ResolverRegistry::GetDefaultAuthority(server_uri_str);
- }
- grpc_arg args_to_add[2];
- size_t num_args_to_add = 0;
- if (grpc_channel_args_find(args, GRPC_ARG_DEFAULT_AUTHORITY) == nullptr) {
- // If the channel args don't already contain GRPC_ARG_DEFAULT_AUTHORITY,
- // add the arg, setting it to the value just obtained.
- args_to_add[num_args_to_add++] = grpc_channel_arg_string_create(
- const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), authority.get());
- }
- grpc_channel_args* args_with_authority =
- grpc_channel_args_copy_and_add(args, args_to_add, num_args_to_add);
- // Create the security connector using the credentials and target name.
- grpc_channel_args* new_args_from_connector = nullptr;
- RefCountedPtr<grpc_channel_security_connector>
- subchannel_security_connector =
- channel_credentials->create_security_connector(
- /*call_creds=*/nullptr, authority.get(), args_with_authority,
- &new_args_from_connector);
- if (subchannel_security_connector == nullptr) {
- gpr_log(GPR_ERROR,
- "Failed to create secure subchannel for secure name '%s'",
- authority.get());
- grpc_channel_args_destroy(args_with_authority);
- return nullptr;
- }
- grpc_arg new_security_connector_arg =
- grpc_security_connector_to_arg(subchannel_security_connector.get());
- grpc_channel_args* new_args = grpc_channel_args_copy_and_add(
- new_args_from_connector != nullptr ? new_args_from_connector
- : args_with_authority,
- &new_security_connector_arg, 1);
- subchannel_security_connector.reset(DEBUG_LOCATION, "lb_channel_create");
- if (new_args_from_connector != nullptr) {
- grpc_channel_args_destroy(new_args_from_connector);
- }
+ authority = ResolverRegistry::GetDefaultAuthority(server_uri_str);
+ }
+ grpc_arg args_to_add[2];
+ size_t num_args_to_add = 0;
+ if (grpc_channel_args_find(args, GRPC_ARG_DEFAULT_AUTHORITY) == nullptr) {
+ // If the channel args don't already contain GRPC_ARG_DEFAULT_AUTHORITY,
+ // add the arg, setting it to the value just obtained.
+ args_to_add[num_args_to_add++] = grpc_channel_arg_string_create(
+ const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), authority.get());
+ }
+ grpc_channel_args* args_with_authority =
+ grpc_channel_args_copy_and_add(args, args_to_add, num_args_to_add);
+ // Create the security connector using the credentials and target name.
+ grpc_channel_args* new_args_from_connector = nullptr;
+ RefCountedPtr<grpc_channel_security_connector>
+ subchannel_security_connector =
+ channel_credentials->create_security_connector(
+ /*call_creds=*/nullptr, authority.get(), args_with_authority,
+ &new_args_from_connector);
+ if (subchannel_security_connector == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Failed to create secure subchannel for secure name '%s'",
+ authority.get());
+ grpc_channel_args_destroy(args_with_authority);
+ return nullptr;
+ }
+ grpc_arg new_security_connector_arg =
+ grpc_security_connector_to_arg(subchannel_security_connector.get());
+ grpc_channel_args* new_args = grpc_channel_args_copy_and_add(
+ new_args_from_connector != nullptr ? new_args_from_connector
+ : args_with_authority,
+ &new_security_connector_arg, 1);
+ subchannel_security_connector.reset(DEBUG_LOCATION, "lb_channel_create");
+ if (new_args_from_connector != nullptr) {
+ grpc_channel_args_destroy(new_args_from_connector);
+ }
grpc_channel_args_destroy(args_with_authority);
- return new_args;
+ return new_args;
}
-};
+};
-namespace {
+namespace {
-grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args) {
+grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args) {
if (target == nullptr) {
gpr_log(GPR_ERROR, "cannot create channel with NULL target name");
return nullptr;
}
// Add channel arg containing the server URI.
grpc_core::UniquePtr<char> canonical_target =
- ResolverRegistry::AddDefaultPrefixIfNeeded(target);
- grpc_arg arg = grpc_channel_arg_string_create(
- const_cast<char*>(GRPC_ARG_SERVER_URI), canonical_target.get());
+ ResolverRegistry::AddDefaultPrefixIfNeeded(target);
+ grpc_arg arg = grpc_channel_arg_string_create(
+ const_cast<char*>(GRPC_ARG_SERVER_URI), canonical_target.get());
const char* to_remove[] = {GRPC_ARG_SERVER_URI};
grpc_channel_args* new_args =
grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1);
@@ -146,21 +146,21 @@ grpc_channel* CreateChannel(const char* target, const grpc_channel_args* args) {
return channel;
}
-} // namespace
-
-} // namespace grpc_core
-
-namespace {
-
-grpc_core::Chttp2SecureClientChannelFactory* g_factory;
-gpr_once g_factory_once = GPR_ONCE_INIT;
-
-void FactoryInit() {
- g_factory = new grpc_core::Chttp2SecureClientChannelFactory();
-}
-
-} // namespace
-
+} // namespace
+
+} // namespace grpc_core
+
+namespace {
+
+grpc_core::Chttp2SecureClientChannelFactory* g_factory;
+gpr_once g_factory_once = GPR_ONCE_INIT;
+
+void FactoryInit() {
+ g_factory = new grpc_core::Chttp2SecureClientChannelFactory();
+}
+
+} // namespace
+
// Create a secure client channel:
// Asynchronously: - resolve target
// - connect to it (trying alternatives as presented)
@@ -179,17 +179,17 @@ grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds,
if (creds != nullptr) {
// Add channel args containing the client channel factory and channel
// credentials.
- gpr_once_init(&g_factory_once, FactoryInit);
- grpc_arg channel_factory_arg =
- grpc_core::ClientChannelFactory::CreateChannelArg(g_factory);
- grpc_arg args_to_add[] = {channel_factory_arg,
- grpc_channel_credentials_to_arg(creds)};
- const char* arg_to_remove = channel_factory_arg.key;
- grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
- args, &arg_to_remove, 1, args_to_add, GPR_ARRAY_SIZE(args_to_add));
+ gpr_once_init(&g_factory_once, FactoryInit);
+ grpc_arg channel_factory_arg =
+ grpc_core::ClientChannelFactory::CreateChannelArg(g_factory);
+ grpc_arg args_to_add[] = {channel_factory_arg,
+ grpc_channel_credentials_to_arg(creds)};
+ const char* arg_to_remove = channel_factory_arg.key;
+ grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
+ args, &arg_to_remove, 1, args_to_add, GPR_ARRAY_SIZE(args_to_add));
new_args = creds->update_arguments(new_args);
// Create channel.
- channel = grpc_core::CreateChannel(target, new_args);
+ channel = grpc_core::CreateChannel(target, new_args);
// Clean up.
grpc_channel_args_destroy(new_args);
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc
index 94cf61310b..ec34617e62 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc
@@ -28,8 +28,8 @@
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/grpc.h>
-#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/grpc.h>
+#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
@@ -464,18 +464,18 @@ void Chttp2ServerListener::Orphan() {
}
} // namespace
-
+
//
// Chttp2ServerAddPort()
//
-
+
grpc_error* Chttp2ServerAddPort(Server* server, const char* addr,
grpc_channel_args* args, int* port_num) {
if (strncmp(addr, "external:", 9) == 0) {
return grpc_core::Chttp2ServerListener::CreateWithAcceptor(server, addr,
args);
- }
+ }
return grpc_core::Chttp2ServerListener::Create(server, addr, args, port_num);
-}
-
+}
+
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc
index 249035d7e8..72f8bfe52d 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc
@@ -51,7 +51,7 @@ static uint8_t decode_table[] = {
static const uint8_t tail_xtra[4] = {0, 0, 1, 2};
-static bool input_is_valid(const uint8_t* input_ptr, size_t length) {
+static bool input_is_valid(const uint8_t* input_ptr, size_t length) {
size_t i;
for (i = 0; i < length; ++i) {
@@ -158,7 +158,7 @@ bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx) {
return true;
}
-grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input) {
+grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input) {
size_t input_length = GRPC_SLICE_LENGTH(input);
size_t output_length = input_length / 4 * 3;
struct grpc_base64_decode_context ctx;
@@ -174,7 +174,7 @@ grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input) {
}
if (input_length > 0) {
- const uint8_t* input_end = GRPC_SLICE_END_PTR(input);
+ const uint8_t* input_end = GRPC_SLICE_END_PTR(input);
if (*(--input_end) == '=') {
output_length--;
if (*(--input_end) == '=') {
@@ -202,7 +202,7 @@ grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input) {
return output;
}
-grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input,
+grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input,
size_t output_length) {
size_t input_length = GRPC_SLICE_LENGTH(input);
grpc_slice output = GRPC_SLICE_MALLOC(output_length);
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h
index 1cbca033a1..f2bb06dace 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h
@@ -26,8 +26,8 @@
struct grpc_base64_decode_context {
/* input/output: */
- const uint8_t* input_cur;
- const uint8_t* input_end;
+ const uint8_t* input_cur;
+ const uint8_t* input_end;
uint8_t* output_cur;
uint8_t* output_end;
/* Indicate if the decoder should handle the tail of input data*/
@@ -42,12 +42,12 @@ bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx);
/* base64 decode a slice with pad chars. Returns a new slice, does not take
ownership of the input. Returns an empty slice if decoding is failed. */
-grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input);
+grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input);
/* base64 decode a slice without pad chars, data length is needed. Returns a new
slice, does not take ownership of the input. Returns an empty slice if
decoding is failed. */
-grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input,
+grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input,
size_t output_length);
/* Infer the length of decoded data from encoded data. */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.cc
index ba39bbdbe3..0bfa736fd3 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.cc
@@ -47,13 +47,13 @@ static const b64_huff_sym huff_alphabet[64] = {
static const uint8_t tail_xtra[3] = {0, 2, 3};
-grpc_slice grpc_chttp2_base64_encode(const grpc_slice& input) {
+grpc_slice grpc_chttp2_base64_encode(const grpc_slice& input) {
size_t input_length = GRPC_SLICE_LENGTH(input);
size_t input_triplets = input_length / 3;
size_t tail_case = input_length % 3;
size_t output_length = input_triplets * 4 + tail_xtra[tail_case];
grpc_slice output = GRPC_SLICE_MALLOC(output_length);
- const uint8_t* in = GRPC_SLICE_START_PTR(input);
+ const uint8_t* in = GRPC_SLICE_START_PTR(input);
char* out = reinterpret_cast<char*> GRPC_SLICE_START_PTR(output);
size_t i;
@@ -91,9 +91,9 @@ grpc_slice grpc_chttp2_base64_encode(const grpc_slice& input) {
return output;
}
-grpc_slice grpc_chttp2_huffman_compress(const grpc_slice& input) {
+grpc_slice grpc_chttp2_huffman_compress(const grpc_slice& input) {
size_t nbits;
- const uint8_t* in;
+ const uint8_t* in;
uint8_t* out;
grpc_slice output;
uint32_t temp = 0;
@@ -164,8 +164,8 @@ static void enc_add1(huff_out* out, uint8_t a) {
enc_flush_some(out);
}
-grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(
- const grpc_slice& input) {
+grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(
+ const grpc_slice& input) {
size_t input_length = GRPC_SLICE_LENGTH(input);
size_t input_triplets = input_length / 3;
size_t tail_case = input_length % 3;
@@ -173,7 +173,7 @@ grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(
size_t max_output_bits = 11 * output_syms;
size_t max_output_length = max_output_bits / 8 + (max_output_bits % 8 != 0);
grpc_slice output = GRPC_SLICE_MALLOC(max_output_length);
- const uint8_t* in = GRPC_SLICE_START_PTR(input);
+ const uint8_t* in = GRPC_SLICE_START_PTR(input);
uint8_t* start_out = GRPC_SLICE_START_PTR(output);
huff_out out;
size_t i;
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h
index 4f7ee67bd3..da97555b57 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h
@@ -25,18 +25,18 @@
/* base64 encode a slice. Returns a new slice, does not take ownership of the
input */
-grpc_slice grpc_chttp2_base64_encode(const grpc_slice& input);
+grpc_slice grpc_chttp2_base64_encode(const grpc_slice& input);
/* Compress a slice with the static huffman encoder detailed in the hpack
standard. Returns a new slice, does not take ownership of the input */
-grpc_slice grpc_chttp2_huffman_compress(const grpc_slice& input);
+grpc_slice grpc_chttp2_huffman_compress(const grpc_slice& input);
/* equivalent to:
grpc_slice x = grpc_chttp2_base64_encode(input);
grpc_slice y = grpc_chttp2_huffman_compress(x);
grpc_slice_unref_internal( x);
return y; */
-grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(
- const grpc_slice& input);
+grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(
+ const grpc_slice& input);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_ENCODER_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc
index ac13d73d3b..5019568eb0 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc
@@ -20,18 +20,18 @@
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/transport/metadata.h"
-GPR_GLOBAL_CONFIG_DEFINE_BOOL(
- grpc_experimental_disable_flow_control, false,
- "If set, flow control will be effectively disabled. Max out all values and "
- "assume the remote peer does the same. Thus we can ignore any flow control "
- "bookkeeping, error checking, and decision making");
-
+GPR_GLOBAL_CONFIG_DEFINE_BOOL(
+ grpc_experimental_disable_flow_control, false,
+ "If set, flow control will be effectively disabled. Max out all values and "
+ "assume the remote peer does the same. Thus we can ignore any flow control "
+ "bookkeeping, error checking, and decision making");
+
void grpc_chttp2_plugin_init(void) {
- g_flow_control_enabled =
- !GPR_GLOBAL_CONFIG_GET(grpc_experimental_disable_flow_control);
+ g_flow_control_enabled =
+ !GPR_GLOBAL_CONFIG_GET(grpc_experimental_disable_flow_control);
}
void grpc_chttp2_plugin_shutdown(void) {}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc
index 180ca62543..c009a97b6b 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc
@@ -74,8 +74,8 @@
#define DEFAULT_MAX_PINGS_BETWEEN_DATA 2
#define DEFAULT_MAX_PING_STRIKES 2
-#define DEFAULT_MAX_PENDING_INDUCED_FRAMES 10000
-
+#define DEFAULT_MAX_PENDING_INDUCED_FRAMES 10000
+
static int g_default_client_keepalive_time_ms =
DEFAULT_CLIENT_KEEPALIVE_TIME_MS;
static int g_default_client_keepalive_timeout_ms =
@@ -105,14 +105,14 @@ grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount(false,
// forward declarations of various callbacks that we'll build closures around
static void write_action_begin_locked(void* t, grpc_error* error);
static void write_action(void* t, grpc_error* error);
-static void write_action_end(void* t, grpc_error* error);
+static void write_action_end(void* t, grpc_error* error);
static void write_action_end_locked(void* t, grpc_error* error);
-static void read_action(void* t, grpc_error* error);
+static void read_action(void* t, grpc_error* error);
static void read_action_locked(void* t, grpc_error* error);
-static void continue_read_action_locked(grpc_chttp2_transport* t);
+static void continue_read_action_locked(grpc_chttp2_transport* t);
-static void complete_fetch(void* gs, grpc_error* error);
+static void complete_fetch(void* gs, grpc_error* error);
static void complete_fetch_locked(void* gs, grpc_error* error);
// Set a transport level setting, and push it to our peer
static void queue_setting_update(grpc_chttp2_transport* t,
@@ -127,10 +127,10 @@ static void maybe_start_some_streams(grpc_chttp2_transport* t);
static void connectivity_state_set(grpc_chttp2_transport* t,
grpc_connectivity_state state,
const y_absl::Status& status,
- const char* reason);
+ const char* reason);
-static void benign_reclaimer(void* t, grpc_error* error);
-static void destructive_reclaimer(void* t, grpc_error* error);
+static void benign_reclaimer(void* t, grpc_error* error);
+static void destructive_reclaimer(void* t, grpc_error* error);
static void benign_reclaimer_locked(void* t, grpc_error* error);
static void destructive_reclaimer_locked(void* t, grpc_error* error);
@@ -140,11 +140,11 @@ static void post_destructive_reclaimer(grpc_chttp2_transport* t);
static void close_transport_locked(grpc_chttp2_transport* t, grpc_error* error);
static void end_all_the_calls(grpc_chttp2_transport* t, grpc_error* error);
-static void start_bdp_ping(void* tp, grpc_error* error);
-static void finish_bdp_ping(void* tp, grpc_error* error);
+static void start_bdp_ping(void* tp, grpc_error* error);
+static void finish_bdp_ping(void* tp, grpc_error* error);
static void start_bdp_ping_locked(void* tp, grpc_error* error);
static void finish_bdp_ping_locked(void* tp, grpc_error* error);
-static void next_bdp_ping_timer_expired(void* tp, grpc_error* error);
+static void next_bdp_ping_timer_expired(void* tp, grpc_error* error);
static void next_bdp_ping_timer_expired_locked(void* tp, grpc_error* error);
static void cancel_pings(grpc_chttp2_transport* t, grpc_error* error);
@@ -154,13 +154,13 @@ static void send_ping_locked(grpc_chttp2_transport* t,
static void retry_initiate_ping_locked(void* tp, grpc_error* error);
// keepalive-relevant functions
-static void init_keepalive_ping(void* arg, grpc_error* error);
+static void init_keepalive_ping(void* arg, grpc_error* error);
static void init_keepalive_ping_locked(void* arg, grpc_error* error);
-static void start_keepalive_ping(void* arg, grpc_error* error);
-static void finish_keepalive_ping(void* arg, grpc_error* error);
+static void start_keepalive_ping(void* arg, grpc_error* error);
+static void finish_keepalive_ping(void* arg, grpc_error* error);
static void start_keepalive_ping_locked(void* arg, grpc_error* error);
static void finish_keepalive_ping_locked(void* arg, grpc_error* error);
-static void keepalive_watchdog_fired(void* arg, grpc_error* error);
+static void keepalive_watchdog_fired(void* arg, grpc_error* error);
static void keepalive_watchdog_fired_locked(void* arg, grpc_error* error);
static void reset_byte_stream(void* arg, grpc_error* error);
@@ -320,7 +320,7 @@ static bool read_channel_args(grpc_chttp2_transport* t,
grpc_channel_arg_get_integer(&channel_args->args[i], {0, 0, 1}));
} else if (0 == strcmp(channel_args->args[i].key,
GRPC_ARG_OPTIMIZATION_TARGET)) {
- gpr_log(GPR_INFO, "GRPC_ARG_OPTIMIZATION_TARGET is deprecated");
+ gpr_log(GPR_INFO, "GRPC_ARG_OPTIMIZATION_TARGET is deprecated");
} else if (0 ==
strcmp(channel_args->args[i].key, GRPC_ARG_ENABLE_CHANNELZ)) {
channelz_enabled = grpc_channel_arg_get_bool(
@@ -419,8 +419,8 @@ static void init_keepalive_pings_if_enabled(grpc_chttp2_transport* t) {
if (t->keepalive_time != GRPC_MILLIS_INF_FUTURE) {
t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING;
GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping");
- GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
+ grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->keepalive_ping_timer,
grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
&t->init_keepalive_ping_locked);
@@ -439,8 +439,8 @@ grpc_chttp2_transport::grpc_chttp2_transport(
peer_string(grpc_endpoint_get_peer(ep)),
resource_user(resource_user),
combiner(grpc_combiner_create()),
- state_tracker(is_client ? "client_transport" : "server_transport",
- GRPC_CHANNEL_READY),
+ state_tracker(is_client ? "client_transport" : "server_transport",
+ GRPC_CHANNEL_READY),
is_client(is_client),
next_stream_id(is_client ? 1 : 2),
deframe_state(is_client ? GRPC_DTS_FH_0 : GRPC_DTS_CLIENT_PREFIX_0) {
@@ -519,7 +519,7 @@ grpc_chttp2_transport::grpc_chttp2_transport(
post_benign_reclaimer(this);
}
-static void destroy_transport_locked(void* tp, grpc_error* /*error*/) {
+static void destroy_transport_locked(void* tp, grpc_error* /*error*/) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
t->destroying = 1;
close_transport_locked(
@@ -532,8 +532,8 @@ static void destroy_transport_locked(void* tp, grpc_error* /*error*/) {
static void destroy_transport(grpc_transport* gt) {
grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
- t->combiner->Run(GRPC_CLOSURE_CREATE(destroy_transport_locked, t, nullptr),
- GRPC_ERROR_NONE);
+ t->combiner->Run(GRPC_CLOSURE_CREATE(destroy_transport_locked, t, nullptr),
+ GRPC_ERROR_NONE);
}
static void close_transport_locked(grpc_chttp2_transport* t,
@@ -588,7 +588,7 @@ static void close_transport_locked(grpc_chttp2_transport* t,
grpc_endpoint_shutdown(t->ep, GRPC_ERROR_REF(error));
}
if (t->notify_on_receive_settings != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, t->notify_on_receive_settings,
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, t->notify_on_receive_settings,
GRPC_ERROR_REF(error));
t->notify_on_receive_settings = nullptr;
}
@@ -611,23 +611,23 @@ void grpc_chttp2_stream_unref(grpc_chttp2_stream* s) {
}
#endif
-grpc_chttp2_stream::Reffer::Reffer(grpc_chttp2_stream* s) {
+grpc_chttp2_stream::Reffer::Reffer(grpc_chttp2_stream* s) {
// We reserve one 'active stream' that's dropped when the stream is
// read-closed. The others are for Chttp2IncomingByteStreams that are
// actively reading
- GRPC_CHTTP2_STREAM_REF(s, "chttp2");
- GRPC_CHTTP2_REF_TRANSPORT(s->t, "stream");
-}
-
-grpc_chttp2_stream::grpc_chttp2_stream(grpc_chttp2_transport* t,
- grpc_stream_refcount* refcount,
- const void* server_data,
- grpc_core::Arena* arena)
- : t(t),
- refcount(refcount),
- reffer(this),
- metadata_buffer{grpc_chttp2_incoming_metadata_buffer(arena),
- grpc_chttp2_incoming_metadata_buffer(arena)} {
+ GRPC_CHTTP2_STREAM_REF(s, "chttp2");
+ GRPC_CHTTP2_REF_TRANSPORT(s->t, "stream");
+}
+
+grpc_chttp2_stream::grpc_chttp2_stream(grpc_chttp2_transport* t,
+ grpc_stream_refcount* refcount,
+ const void* server_data,
+ grpc_core::Arena* arena)
+ : t(t),
+ refcount(refcount),
+ reffer(this),
+ metadata_buffer{grpc_chttp2_incoming_metadata_buffer(arena),
+ grpc_chttp2_incoming_metadata_buffer(arena)} {
if (server_data) {
id = static_cast<uint32_t>((uintptr_t)server_data);
*t->accepting_stream = this;
@@ -646,7 +646,7 @@ grpc_chttp2_stream::grpc_chttp2_stream(grpc_chttp2_transport* t,
grpc_slice_buffer_init(&frame_storage);
grpc_slice_buffer_init(&unprocessed_incoming_frames_buffer);
grpc_slice_buffer_init(&flow_controlled_buffer);
- GRPC_CLOSURE_INIT(&reset_byte_stream, ::reset_byte_stream, this, nullptr);
+ GRPC_CLOSURE_INIT(&reset_byte_stream, ::reset_byte_stream, this, nullptr);
}
grpc_chttp2_stream::~grpc_chttp2_stream() {
@@ -665,13 +665,13 @@ grpc_chttp2_stream::~grpc_chttp2_stream() {
grpc_slice_buffer_destroy_internal(&unprocessed_incoming_frames_buffer);
grpc_slice_buffer_destroy_internal(&frame_storage);
- if (stream_compression_method != GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) {
- grpc_slice_buffer_destroy_internal(&compressed_data_buffer);
- }
- if (stream_decompression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
- grpc_slice_buffer_destroy_internal(&decompressed_data_buffer);
- }
+ if (stream_compression_method != GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) {
+ grpc_slice_buffer_destroy_internal(&compressed_data_buffer);
+ }
+ if (stream_decompression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
+ grpc_slice_buffer_destroy_internal(&decompressed_data_buffer);
+ }
for (int i = 0; i < STREAM_LIST_COUNT; i++) {
if (GPR_UNLIKELY(included[i])) {
@@ -699,19 +699,19 @@ grpc_chttp2_stream::~grpc_chttp2_stream() {
}
GRPC_CHTTP2_UNREF_TRANSPORT(t, "stream");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, destroy_stream_arg, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, destroy_stream_arg, GRPC_ERROR_NONE);
}
static int init_stream(grpc_transport* gt, grpc_stream* gs,
grpc_stream_refcount* refcount, const void* server_data,
- grpc_core::Arena* arena) {
+ grpc_core::Arena* arena) {
GPR_TIMER_SCOPE("init_stream", 0);
grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
new (gs) grpc_chttp2_stream(t, refcount, server_data, arena);
return 0;
}
-static void destroy_stream_locked(void* sp, grpc_error* /*error*/) {
+static void destroy_stream_locked(void* sp, grpc_error* /*error*/) {
GPR_TIMER_SCOPE("destroy_stream", 0);
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp);
s->~grpc_chttp2_stream();
@@ -722,28 +722,28 @@ static void destroy_stream(grpc_transport* gt, grpc_stream* gs,
GPR_TIMER_SCOPE("destroy_stream", 0);
grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
grpc_chttp2_stream* s = reinterpret_cast<grpc_chttp2_stream*>(gs);
- if (s->stream_compression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS &&
- s->stream_compression_ctx != nullptr) {
+ if (s->stream_compression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS &&
+ s->stream_compression_ctx != nullptr) {
grpc_stream_compression_context_destroy(s->stream_compression_ctx);
s->stream_compression_ctx = nullptr;
}
- if (s->stream_decompression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS &&
- s->stream_decompression_ctx != nullptr) {
+ if (s->stream_decompression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS &&
+ s->stream_decompression_ctx != nullptr) {
grpc_stream_compression_context_destroy(s->stream_decompression_ctx);
s->stream_decompression_ctx = nullptr;
}
s->destroy_stream_arg = then_schedule_closure;
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&s->destroy_stream, destroy_stream_locked, s, nullptr),
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&s->destroy_stream, destroy_stream_locked, s, nullptr),
GRPC_ERROR_NONE);
}
grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
uint32_t id) {
- if (t->accept_stream_cb == nullptr) {
+ if (t->accept_stream_cb == nullptr) {
return nullptr;
}
// Don't accept the stream if memory quota doesn't allow. Note that we should
@@ -753,16 +753,16 @@ grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
!grpc_resource_user_safe_alloc(t->resource_user,
GRPC_RESOURCE_QUOTA_CALL_SIZE)) {
gpr_log(GPR_ERROR, "Memory exhausted, rejecting the stream.");
- grpc_chttp2_add_rst_stream_to_next_write(t, id, GRPC_HTTP2_REFUSED_STREAM,
- nullptr);
+ grpc_chttp2_add_rst_stream_to_next_write(t, id, GRPC_HTTP2_REFUSED_STREAM,
+ nullptr);
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM);
return nullptr;
}
grpc_chttp2_stream* accepting = nullptr;
GPR_ASSERT(t->accepting_stream == nullptr);
t->accepting_stream = &accepting;
- t->accept_stream_cb(t->accept_stream_cb_user_data, &t->base,
- (void*)static_cast<uintptr_t>(id));
+ t->accept_stream_cb(t->accept_stream_cb_user_data, &t->base,
+ (void*)static_cast<uintptr_t>(id));
t->accepting_stream = nullptr;
return accepting;
}
@@ -785,10 +785,10 @@ static const char* write_state_name(grpc_chttp2_write_state st) {
static void set_write_state(grpc_chttp2_transport* t,
grpc_chttp2_write_state st, const char* reason) {
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_INFO, "W:%p %s [%s] state %s -> %s [%s]", t,
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_INFO, "W:%p %s [%s] state %s -> %s [%s]", t,
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str(),
- write_state_name(t->write_state), write_state_name(st), reason));
+ write_state_name(t->write_state), write_state_name(st), reason));
t->write_state = st;
// If the state is being reset back to idle, it means a write was just
// finished. Make sure all the run_after_write closures are scheduled.
@@ -797,7 +797,7 @@ static void set_write_state(grpc_chttp2_transport* t,
// to be closed after all writes finish (for example, if we received a go-away
// from peer while we had some pending writes)
if (st == GRPC_CHTTP2_WRITE_STATE_IDLE) {
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &t->run_after_write);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &t->run_after_write);
if (t->close_transport_on_writes_finished != nullptr) {
grpc_error* err = t->close_transport_on_writes_finished;
t->close_transport_on_writes_finished = nullptr;
@@ -901,9 +901,9 @@ void grpc_chttp2_initiate_write(grpc_chttp2_transport* t,
// Also, 'write_action_begin_locked' only gathers the bytes into outbuf.
// It does not call the endpoint to write the bytes. That is done by the
// 'write_action' (which is scheduled by 'write_action_begin_locked')
- t->combiner->FinallyRun(
+ t->combiner->FinallyRun(
GRPC_CLOSURE_INIT(&t->write_action_begin_locked,
- write_action_begin_locked, t, nullptr),
+ write_action_begin_locked, t, nullptr),
GRPC_ERROR_NONE);
break;
case GRPC_CHTTP2_WRITE_STATE_WRITING:
@@ -923,15 +923,15 @@ void grpc_chttp2_mark_stream_writable(grpc_chttp2_transport* t,
}
}
-static const char* begin_writing_desc(bool partial) {
- if (partial) {
- return "begin partial write in background";
- } else {
- return "begin write in current thread";
+static const char* begin_writing_desc(bool partial) {
+ if (partial) {
+ return "begin partial write in background";
+ } else {
+ return "begin write in current thread";
}
}
-static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) {
+static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) {
GPR_TIMER_SCOPE("write_action_begin_locked", 0);
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(gt);
GPR_ASSERT(t->write_state != GRPC_CHTTP2_WRITE_STATE_IDLE);
@@ -945,23 +945,23 @@ static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) {
if (r.partial) {
GRPC_STATS_INC_HTTP2_PARTIAL_WRITES();
}
- set_write_state(t,
- r.partial ? GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE
- : GRPC_CHTTP2_WRITE_STATE_WRITING,
- begin_writing_desc(r.partial));
- write_action(t, GRPC_ERROR_NONE);
- if (t->reading_paused_on_pending_induced_frames) {
- GPR_ASSERT(t->num_pending_induced_frames == 0);
+ set_write_state(t,
+ r.partial ? GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE
+ : GRPC_CHTTP2_WRITE_STATE_WRITING,
+ begin_writing_desc(r.partial));
+ write_action(t, GRPC_ERROR_NONE);
+ if (t->reading_paused_on_pending_induced_frames) {
+ GPR_ASSERT(t->num_pending_induced_frames == 0);
// We had paused reading, because we had many induced frames (SETTINGS
// ACK, PINGS ACK and RST_STREAMS) pending in t->qbuf. Now that we have
// been able to flush qbuf, we can resume reading.
- GRPC_CHTTP2_IF_TRACING(gpr_log(
- GPR_INFO,
- "transport %p : Resuming reading after being paused due to too "
- "many unwritten SETTINGS ACK, PINGS ACK and RST_STREAM frames",
- t));
- t->reading_paused_on_pending_induced_frames = false;
- continue_read_action_locked(t);
+ GRPC_CHTTP2_IF_TRACING(gpr_log(
+ GPR_INFO,
+ "transport %p : Resuming reading after being paused due to too "
+ "many unwritten SETTINGS ACK, PINGS ACK and RST_STREAM frames",
+ t));
+ t->reading_paused_on_pending_induced_frames = false;
+ continue_read_action_locked(t);
}
} else {
GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN();
@@ -970,40 +970,40 @@ static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) {
}
}
-static void write_action(void* gt, grpc_error* /*error*/) {
+static void write_action(void* gt, grpc_error* /*error*/) {
GPR_TIMER_SCOPE("write_action", 0);
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(gt);
void* cl = t->cl;
t->cl = nullptr;
grpc_endpoint_write(
t->ep, &t->outbuf,
- GRPC_CLOSURE_INIT(&t->write_action_end_locked, write_action_end, t,
- grpc_schedule_on_exec_ctx),
+ GRPC_CLOSURE_INIT(&t->write_action_end_locked, write_action_end, t,
+ grpc_schedule_on_exec_ctx),
cl);
}
-static void write_action_end(void* tp, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->write_action_end_locked,
- write_action_end_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void write_action_end(void* tp, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->write_action_end_locked,
+ write_action_end_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
// Callback from the grpc_endpoint after bytes have been written by calling
// sendmsg
static void write_action_end_locked(void* tp, grpc_error* error) {
GPR_TIMER_SCOPE("terminate_writing_with_lock", 0);
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- bool closed = false;
+ bool closed = false;
if (error != GRPC_ERROR_NONE) {
close_transport_locked(t, GRPC_ERROR_REF(error));
- closed = true;
+ closed = true;
}
if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED) {
t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SENT;
- closed = true;
+ closed = true;
if (grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
close_transport_locked(
t, GRPC_ERROR_CREATE_FROM_STATIC_STRING("goaway sent"));
@@ -1021,17 +1021,17 @@ static void write_action_end_locked(void* tp, grpc_error* error) {
GPR_TIMER_MARK("state=writing_stale_no_poller", 0);
set_write_state(t, GRPC_CHTTP2_WRITE_STATE_WRITING, "continue writing");
GRPC_CHTTP2_REF_TRANSPORT(t, "writing");
- // If the transport is closed, we will retry writing on the endpoint
- // and next write may contain part of the currently serialized frames.
- // So, we should only call the run_after_write callbacks when the next
- // write finishes, or the callbacks will be invoked when the stream is
- // closed.
- if (!closed) {
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &t->run_after_write);
- }
- t->combiner->FinallyRun(
+ // If the transport is closed, we will retry writing on the endpoint
+ // and next write may contain part of the currently serialized frames.
+ // So, we should only call the run_after_write callbacks when the next
+ // write finishes, or the callbacks will be invoked when the stream is
+ // closed.
+ if (!closed) {
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &t->run_after_write);
+ }
+ t->combiner->FinallyRun(
GRPC_CLOSURE_INIT(&t->write_action_begin_locked,
- write_action_begin_locked, t, nullptr),
+ write_action_begin_locked, t, nullptr),
GRPC_ERROR_NONE);
break;
}
@@ -1059,29 +1059,29 @@ static void queue_setting_update(grpc_chttp2_transport* t,
void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
uint32_t goaway_error,
- uint32_t last_stream_id,
- const grpc_slice& goaway_text) {
+ uint32_t last_stream_id,
+ const grpc_slice& goaway_text) {
// Discard the error from a previous goaway frame (if any)
if (t->goaway_error != GRPC_ERROR_NONE) {
GRPC_ERROR_UNREF(t->goaway_error);
}
t->goaway_error = grpc_error_set_str(
grpc_error_set_int(
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("GOAWAY received"),
- GRPC_ERROR_INT_HTTP2_ERROR, static_cast<intptr_t>(goaway_error)),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE),
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("GOAWAY received"),
+ GRPC_ERROR_INT_HTTP2_ERROR, static_cast<intptr_t>(goaway_error)),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE),
GRPC_ERROR_STR_RAW_BYTES, goaway_text);
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_INFO, "transport %p got goaway with last stream id %d", t,
- last_stream_id));
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_INFO, "transport %p got goaway with last stream id %d", t,
+ last_stream_id));
// We want to log this irrespective of whether http tracing is enabled if we
// received a GOAWAY with a non NO_ERROR code.
- if (goaway_error != GRPC_HTTP2_NO_ERROR) {
+ if (goaway_error != GRPC_HTTP2_NO_ERROR) {
gpr_log(GPR_INFO, "%s: Got goaway [%d] err=%s", t->peer_string.c_str(),
- goaway_error, grpc_error_string(t->goaway_error));
- }
+ goaway_error, grpc_error_string(t->goaway_error));
+ }
y_absl::Status status = grpc_error_to_absl_status(t->goaway_error);
// When a client receives a GOAWAY with error code ENHANCE_YOUR_CALM and debug
// data equal to "too_many_pings", it should log the occurrence at a log level
@@ -1113,16 +1113,16 @@ void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
static void maybe_start_some_streams(grpc_chttp2_transport* t) {
grpc_chttp2_stream* s;
// cancel out streams that haven't yet started if we have received a GOAWAY
- if (t->goaway_error != GRPC_ERROR_NONE) {
- while (grpc_chttp2_list_pop_waiting_for_concurrency(t, &s)) {
- grpc_chttp2_cancel_stream(
- t, s,
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("GOAWAY received"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- }
- return;
- }
+ if (t->goaway_error != GRPC_ERROR_NONE) {
+ while (grpc_chttp2_list_pop_waiting_for_concurrency(t, &s)) {
+ grpc_chttp2_cancel_stream(
+ t, s,
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("GOAWAY received"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+ }
+ return;
+ }
// start streams where we have free grpc_chttp2_stream ids and free
// * concurrency
while (t->next_stream_id <= MAX_CLIENT_STREAM_ID &&
@@ -1132,19 +1132,19 @@ static void maybe_start_some_streams(grpc_chttp2_transport* t) {
grpc_chttp2_list_pop_waiting_for_concurrency(t, &s)) {
// safe since we can't (legally) be parsing this stream yet
GRPC_CHTTP2_IF_TRACING(gpr_log(
- GPR_INFO,
- "HTTP:%s: Transport %p allocating new grpc_chttp2_stream %p to id %d",
- t->is_client ? "CLI" : "SVR", t, s, t->next_stream_id));
+ GPR_INFO,
+ "HTTP:%s: Transport %p allocating new grpc_chttp2_stream %p to id %d",
+ t->is_client ? "CLI" : "SVR", t, s, t->next_stream_id));
GPR_ASSERT(s->id == 0);
s->id = t->next_stream_id;
t->next_stream_id += 2;
if (t->next_stream_id >= MAX_CLIENT_STREAM_ID) {
- connectivity_state_set(t, GRPC_CHANNEL_TRANSIENT_FAILURE,
+ connectivity_state_set(t, GRPC_CHANNEL_TRANSIENT_FAILURE,
y_absl::Status(y_absl::StatusCode::kUnavailable,
"Transport Stream IDs exhausted"),
- "no_more_stream_ids");
+ "no_more_stream_ids");
}
grpc_chttp2_stream_map_add(&t->stream_map, s->id, s);
@@ -1153,14 +1153,14 @@ static void maybe_start_some_streams(grpc_chttp2_transport* t) {
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM);
}
// cancel out streams that will never be started
- if (t->next_stream_id >= MAX_CLIENT_STREAM_ID) {
- while (grpc_chttp2_list_pop_waiting_for_concurrency(t, &s)) {
- grpc_chttp2_cancel_stream(
- t, s,
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Stream IDs exhausted"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- }
+ if (t->next_stream_id >= MAX_CLIENT_STREAM_ID) {
+ while (grpc_chttp2_list_pop_waiting_for_concurrency(t, &s)) {
+ grpc_chttp2_cancel_stream(
+ t, s,
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Stream IDs exhausted"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+ }
}
}
@@ -1177,14 +1177,14 @@ static grpc_closure* add_closure_barrier(grpc_closure* closure) {
return closure;
}
-static void null_then_sched_closure(grpc_closure** closure) {
+static void null_then_sched_closure(grpc_closure** closure) {
grpc_closure* c = *closure;
*closure = nullptr;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, c, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, c, GRPC_ERROR_NONE);
}
void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
- grpc_chttp2_stream* /*s*/,
+ grpc_chttp2_stream* /*s*/,
grpc_closure** pclosure,
grpc_error* error, const char* desc) {
grpc_closure* closure = *pclosure;
@@ -1194,7 +1194,7 @@ void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
return;
}
closure->next_data.scratch -= CLOSURE_BARRIER_FIRST_REF_BIT;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
const char* errstr = grpc_error_string(error);
gpr_log(
GPR_INFO,
@@ -1221,10 +1221,10 @@ void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
if (closure->next_data.scratch < CLOSURE_BARRIER_FIRST_REF_BIT) {
if ((t->write_state == GRPC_CHTTP2_WRITE_STATE_IDLE) ||
!(closure->next_data.scratch & CLOSURE_BARRIER_MAY_COVER_WRITE)) {
- // Using GRPC_CLOSURE_SCHED instead of GRPC_CLOSURE_RUN to avoid running
- // closures earlier than when it is safe to do so.
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure,
- closure->error_data.error);
+ // Using GRPC_CLOSURE_SCHED instead of GRPC_CLOSURE_RUN to avoid running
+ // closures earlier than when it is safe to do so.
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure,
+ closure->error_data.error);
} else {
grpc_closure_list_append(&t->run_after_write, closure,
closure->error_data.error);
@@ -1234,8 +1234,8 @@ void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
static bool contains_non_ok_status(grpc_metadata_batch* batch) {
if (batch->idx.named.grpc_status != nullptr) {
- return !grpc_mdelem_static_value_eq(batch->idx.named.grpc_status->md,
- GRPC_MDELEM_GRPC_STATUS_0);
+ return !grpc_mdelem_static_value_eq(batch->idx.named.grpc_status->md,
+ GRPC_MDELEM_GRPC_STATUS_0);
}
return false;
}
@@ -1290,10 +1290,10 @@ static void continue_fetching_send_locked(grpc_chttp2_transport* t,
}
s->fetching_send_message.reset();
return; /* early out */
- } else if (s->fetching_send_message->Next(
- UINT32_MAX, GRPC_CLOSURE_INIT(&s->complete_fetch_locked,
- ::complete_fetch, s,
- grpc_schedule_on_exec_ctx))) {
+ } else if (s->fetching_send_message->Next(
+ UINT32_MAX, GRPC_CLOSURE_INIT(&s->complete_fetch_locked,
+ ::complete_fetch, s,
+ grpc_schedule_on_exec_ctx))) {
grpc_error* error = s->fetching_send_message->Pull(&s->fetching_slice);
if (error != GRPC_ERROR_NONE) {
s->fetching_send_message.reset();
@@ -1305,13 +1305,13 @@ static void continue_fetching_send_locked(grpc_chttp2_transport* t,
}
}
-static void complete_fetch(void* gs, grpc_error* error) {
- grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(gs);
- s->t->combiner->Run(GRPC_CLOSURE_INIT(&s->complete_fetch_locked,
- ::complete_fetch_locked, s, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void complete_fetch(void* gs, grpc_error* error) {
+ grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(gs);
+ s->t->combiner->Run(GRPC_CLOSURE_INIT(&s->complete_fetch_locked,
+ ::complete_fetch_locked, s, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void complete_fetch_locked(void* gs, grpc_error* error) {
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(gs);
grpc_chttp2_transport* t = s->t;
@@ -1342,7 +1342,7 @@ static void log_metadata(const grpc_metadata_batch* md_batch, uint32_t id,
}
static void perform_stream_op_locked(void* stream_op,
- grpc_error* /*error_ignored*/) {
+ grpc_error* /*error_ignored*/) {
GPR_TIMER_SCOPE("perform_stream_op_locked", 0);
grpc_transport_stream_op_batch* op =
@@ -1356,7 +1356,7 @@ static void perform_stream_op_locked(void* stream_op,
s->context = op->payload->context;
s->traced = op->is_traced;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "perform_stream_op_locked: %s; on_complete = %p",
grpc_transport_stream_op_batch_string(op).c_str(), op->on_complete);
if (op->send_initial_metadata) {
@@ -1370,12 +1370,12 @@ static void perform_stream_op_locked(void* stream_op,
}
grpc_closure* on_complete = op->on_complete;
- // on_complete will be null if and only if there are no send ops in the batch.
- if (on_complete != nullptr) {
- // This batch has send ops. Use final_data as a barrier until enqueue time;
- // the initial counter is dropped at the end of this function.
- on_complete->next_data.scratch = CLOSURE_BARRIER_FIRST_REF_BIT;
- on_complete->error_data.error = GRPC_ERROR_NONE;
+ // on_complete will be null if and only if there are no send ops in the batch.
+ if (on_complete != nullptr) {
+ // This batch has send ops. Use final_data as a barrier until enqueue time;
+ // the initial counter is dropped at the end of this function.
+ on_complete->next_data.scratch = CLOSURE_BARRIER_FIRST_REF_BIT;
+ on_complete->error_data.error = GRPC_ERROR_NONE;
}
if (op->cancel_stream) {
@@ -1401,12 +1401,12 @@ static void perform_stream_op_locked(void* stream_op,
true, &s->stream_compression_method) == 0) {
s->stream_compression_method = GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS;
}
- if (s->stream_compression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) {
- s->uncompressed_data_size = 0;
- s->stream_compression_ctx = nullptr;
- grpc_slice_buffer_init(&s->compressed_data_buffer);
- }
+ if (s->stream_compression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) {
+ s->uncompressed_data_size = 0;
+ s->stream_compression_ctx = nullptr;
+ grpc_slice_buffer_init(&s->compressed_data_buffer);
+ }
s->send_initial_metadata_finished = add_closure_barrier(on_complete);
s->send_initial_metadata =
op_payload->send_initial_metadata.send_initial_metadata;
@@ -1463,13 +1463,13 @@ static void perform_stream_op_locked(void* stream_op,
on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE;
s->fetching_send_message_finished = add_closure_barrier(op->on_complete);
if (s->write_closed) {
- op->payload->send_message.stream_write_closed = true;
- // We should NOT return an error here, so as to avoid a cancel OP being
- // started. The surface layer will notice that the stream has been closed
- // for writes and fail the send message op.
+ op->payload->send_message.stream_write_closed = true;
+ // We should NOT return an error here, so as to avoid a cancel OP being
+ // started. The surface layer will notice that the stream has been closed
+ // for writes and fail the send message op.
op->payload->send_message.send_message.reset();
grpc_chttp2_complete_closure_step(
- t, s, &s->fetching_send_message_finished, GRPC_ERROR_NONE,
+ t, s, &s->fetching_send_message_finished, GRPC_ERROR_NONE,
"fetching_send_message_finished");
} else {
GPR_ASSERT(s->fetching_send_message == nullptr);
@@ -1587,10 +1587,10 @@ static void perform_stream_op_locked(void* stream_op,
grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
}
- if (on_complete != nullptr) {
- grpc_chttp2_complete_closure_step(t, s, &on_complete, GRPC_ERROR_NONE,
- "op->on_complete");
- }
+ if (on_complete != nullptr) {
+ grpc_chttp2_complete_closure_step(t, s, &on_complete, GRPC_ERROR_NONE,
+ "op->on_complete");
+ }
GRPC_CHTTP2_STREAM_UNREF(s, "perform_stream_op");
}
@@ -1614,16 +1614,16 @@ static void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
}
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "perform_stream_op[s=%p]: %s", s,
grpc_transport_stream_op_batch_string(op).c_str());
}
GRPC_CHTTP2_STREAM_REF(s, "perform_stream_op");
op->handler_private.extra_arg = gs;
- t->combiner->Run(GRPC_CLOSURE_INIT(&op->handler_private.closure,
- perform_stream_op_locked, op, nullptr),
- GRPC_ERROR_NONE);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&op->handler_private.closure,
+ perform_stream_op_locked, op, nullptr),
+ GRPC_ERROR_NONE);
}
static void cancel_pings(grpc_chttp2_transport* t, grpc_error* error) {
@@ -1633,7 +1633,7 @@ static void cancel_pings(grpc_chttp2_transport* t, grpc_error* error) {
GPR_ASSERT(error != GRPC_ERROR_NONE);
for (size_t j = 0; j < GRPC_CHTTP2_PCL_COUNT; j++) {
grpc_closure_list_fail_all(&pq->lists[j], GRPC_ERROR_REF(error));
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &pq->lists[j]);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &pq->lists[j]);
}
GRPC_ERROR_UNREF(error);
}
@@ -1641,10 +1641,10 @@ static void cancel_pings(grpc_chttp2_transport* t, grpc_error* error) {
static void send_ping_locked(grpc_chttp2_transport* t,
grpc_closure* on_initiate, grpc_closure* on_ack) {
if (t->closed_with_error != GRPC_ERROR_NONE) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_initiate,
- GRPC_ERROR_REF(t->closed_with_error));
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_ack,
- GRPC_ERROR_REF(t->closed_with_error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_initiate,
+ GRPC_ERROR_REF(t->closed_with_error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_ack,
+ GRPC_ERROR_REF(t->closed_with_error));
return;
}
grpc_chttp2_ping_queue* pq = &t->ping_queue;
@@ -1659,47 +1659,47 @@ static void send_ping_locked(grpc_chttp2_transport* t,
// instead of waiting for that ping to complete and then starting a new ping.
static void send_keepalive_ping_locked(grpc_chttp2_transport* t) {
if (t->closed_with_error != GRPC_ERROR_NONE) {
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked,
- start_keepalive_ping_locked, t, nullptr),
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked,
+ start_keepalive_ping_locked, t, nullptr),
GRPC_ERROR_REF(t->closed_with_error));
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
- finish_keepalive_ping_locked, t, nullptr),
- GRPC_ERROR_REF(t->closed_with_error));
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
+ finish_keepalive_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(t->closed_with_error));
return;
}
grpc_chttp2_ping_queue* pq = &t->ping_queue;
if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_INFLIGHT])) {
// There is a ping in flight. Add yourself to the inflight closure list.
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked,
- start_keepalive_ping_locked, t, nullptr),
- GRPC_ERROR_REF(t->closed_with_error));
- grpc_closure_list_append(
- &pq->lists[GRPC_CHTTP2_PCL_INFLIGHT],
- GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
- finish_keepalive_ping, t, grpc_schedule_on_exec_ctx),
- GRPC_ERROR_NONE);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked,
+ start_keepalive_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(t->closed_with_error));
+ grpc_closure_list_append(
+ &pq->lists[GRPC_CHTTP2_PCL_INFLIGHT],
+ GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
+ finish_keepalive_ping, t, grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_NONE);
return;
}
- grpc_closure_list_append(
- &pq->lists[GRPC_CHTTP2_PCL_INITIATE],
- GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked, start_keepalive_ping,
- t, grpc_schedule_on_exec_ctx),
- GRPC_ERROR_NONE);
- grpc_closure_list_append(
- &pq->lists[GRPC_CHTTP2_PCL_NEXT],
- GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked, finish_keepalive_ping,
- t, grpc_schedule_on_exec_ctx),
- GRPC_ERROR_NONE);
-}
-
-void grpc_chttp2_retry_initiate_ping(void* tp, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->retry_initiate_ping_locked,
- retry_initiate_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+ grpc_closure_list_append(
+ &pq->lists[GRPC_CHTTP2_PCL_INITIATE],
+ GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked, start_keepalive_ping,
+ t, grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_NONE);
+ grpc_closure_list_append(
+ &pq->lists[GRPC_CHTTP2_PCL_NEXT],
+ GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked, finish_keepalive_ping,
+ t, grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_NONE);
+}
+
+void grpc_chttp2_retry_initiate_ping(void* tp, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->retry_initiate_ping_locked,
+ retry_initiate_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void retry_initiate_ping_locked(void* tp, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
t->ping_state.is_delayed_ping_timer_set = false;
@@ -1716,8 +1716,8 @@ void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id) {
t->peer_string.c_str(), id);
return;
}
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION,
- &pq->lists[GRPC_CHTTP2_PCL_INFLIGHT]);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION,
+ &pq->lists[GRPC_CHTTP2_PCL_INFLIGHT]);
if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_NEXT])) {
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS);
}
@@ -1764,7 +1764,7 @@ void grpc_chttp2_reset_ping_clock(grpc_chttp2_transport* t) {
}
static void perform_transport_op_locked(void* stream_op,
- grpc_error* /*error_ignored*/) {
+ grpc_error* /*error_ignored*/) {
grpc_transport_op* op = static_cast<grpc_transport_op*>(stream_op);
grpc_chttp2_transport* t =
static_cast<grpc_chttp2_transport*>(op->handler_private.extra_arg);
@@ -1774,8 +1774,8 @@ static void perform_transport_op_locked(void* stream_op,
}
if (op->set_accept_stream) {
- t->accept_stream_cb = op->set_accept_stream_fn;
- t->accept_stream_cb_user_data = op->set_accept_stream_user_data;
+ t->accept_stream_cb = op->set_accept_stream_fn;
+ t->accept_stream_cb_user_data = op->set_accept_stream_user_data;
}
if (op->bind_pollset) {
@@ -1791,42 +1791,42 @@ static void perform_transport_op_locked(void* stream_op,
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING);
}
- if (op->start_connectivity_watch != nullptr) {
- t->state_tracker.AddWatcher(op->start_connectivity_watch_state,
- std::move(op->start_connectivity_watch));
- }
- if (op->stop_connectivity_watch != nullptr) {
- t->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
+ if (op->start_connectivity_watch != nullptr) {
+ t->state_tracker.AddWatcher(op->start_connectivity_watch_state,
+ std::move(op->start_connectivity_watch));
}
+ if (op->stop_connectivity_watch != nullptr) {
+ t->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
+ }
if (op->disconnect_with_error != GRPC_ERROR_NONE) {
close_transport_locked(t, op->disconnect_with_error);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
GRPC_CHTTP2_UNREF_TRANSPORT(t, "transport_op");
}
static void perform_transport_op(grpc_transport* gt, grpc_transport_op* op) {
grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "perform_transport_op[t=%p]: %s", t,
grpc_transport_op_string(op).c_str());
}
op->handler_private.extra_arg = gt;
GRPC_CHTTP2_REF_TRANSPORT(t, "transport_op");
- t->combiner->Run(GRPC_CLOSURE_INIT(&op->handler_private.closure,
- perform_transport_op_locked, op, nullptr),
- GRPC_ERROR_NONE);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&op->handler_private.closure,
+ perform_transport_op_locked, op, nullptr),
+ GRPC_ERROR_NONE);
}
//
// INPUT PROCESSING - GENERAL
//
-void grpc_chttp2_maybe_complete_recv_initial_metadata(
- grpc_chttp2_transport* /*t*/, grpc_chttp2_stream* s) {
+void grpc_chttp2_maybe_complete_recv_initial_metadata(
+ grpc_chttp2_transport* /*t*/, grpc_chttp2_stream* s) {
if (s->recv_initial_metadata_ready != nullptr &&
s->published_metadata[0] != GRPC_METADATA_NOT_PUBLISHED) {
if (s->seen_error) {
@@ -1838,11 +1838,11 @@ void grpc_chttp2_maybe_complete_recv_initial_metadata(
}
grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[0],
s->recv_initial_metadata);
- null_then_sched_closure(&s->recv_initial_metadata_ready);
+ null_then_sched_closure(&s->recv_initial_metadata_ready);
}
}
-void grpc_chttp2_maybe_complete_recv_message(grpc_chttp2_transport* /*t*/,
+void grpc_chttp2_maybe_complete_recv_message(grpc_chttp2_transport* /*t*/,
grpc_chttp2_stream* s) {
grpc_error* error = GRPC_ERROR_NONE;
if (s->recv_message_ready != nullptr) {
@@ -1918,10 +1918,10 @@ void grpc_chttp2_maybe_complete_recv_message(grpc_chttp2_transport* /*t*/,
s->unprocessed_incoming_frames_buffer_cached_length =
s->unprocessed_incoming_frames_buffer.length;
if (error == GRPC_ERROR_NONE && *s->recv_message != nullptr) {
- null_then_sched_closure(&s->recv_message_ready);
+ null_then_sched_closure(&s->recv_message_ready);
} else if (s->published_metadata[1] != GRPC_METADATA_NOT_PUBLISHED) {
*s->recv_message = nullptr;
- null_then_sched_closure(&s->recv_message_ready);
+ null_then_sched_closure(&s->recv_message_ready);
}
GRPC_ERROR_UNREF(error);
}
@@ -1945,41 +1945,41 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
!s->seen_error && s->recv_trailing_metadata_finished != nullptr) {
// Maybe some SYNC_FLUSH data is left in frame_storage. Consume them and
// maybe decompress the next 5 bytes in the stream.
- if (s->stream_decompression_method ==
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
- grpc_slice_buffer_move_first(
- &s->frame_storage,
- GPR_MIN(s->frame_storage.length, GRPC_HEADER_SIZE_IN_BYTES),
+ if (s->stream_decompression_method ==
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
+ grpc_slice_buffer_move_first(
+ &s->frame_storage,
+ GPR_MIN(s->frame_storage.length, GRPC_HEADER_SIZE_IN_BYTES),
&s->unprocessed_incoming_frames_buffer);
if (s->unprocessed_incoming_frames_buffer.length > 0) {
s->unprocessed_incoming_frames_decompressed = true;
pending_data = true;
}
- } else {
- bool end_of_context;
- if (!s->stream_decompression_ctx) {
- s->stream_decompression_ctx = grpc_stream_compression_context_create(
- s->stream_decompression_method);
- }
- if (!grpc_stream_decompress(
- s->stream_decompression_ctx, &s->frame_storage,
- &s->unprocessed_incoming_frames_buffer, nullptr,
- GRPC_HEADER_SIZE_IN_BYTES, &end_of_context)) {
- grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
- grpc_slice_buffer_reset_and_unref_internal(
- &s->unprocessed_incoming_frames_buffer);
- s->seen_error = true;
- } else {
- if (s->unprocessed_incoming_frames_buffer.length > 0) {
- s->unprocessed_incoming_frames_decompressed = true;
- pending_data = true;
- }
- if (end_of_context) {
- grpc_stream_compression_context_destroy(
- s->stream_decompression_ctx);
- s->stream_decompression_ctx = nullptr;
- }
+ } else {
+ bool end_of_context;
+ if (!s->stream_decompression_ctx) {
+ s->stream_decompression_ctx = grpc_stream_compression_context_create(
+ s->stream_decompression_method);
}
+ if (!grpc_stream_decompress(
+ s->stream_decompression_ctx, &s->frame_storage,
+ &s->unprocessed_incoming_frames_buffer, nullptr,
+ GRPC_HEADER_SIZE_IN_BYTES, &end_of_context)) {
+ grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
+ grpc_slice_buffer_reset_and_unref_internal(
+ &s->unprocessed_incoming_frames_buffer);
+ s->seen_error = true;
+ } else {
+ if (s->unprocessed_incoming_frames_buffer.length > 0) {
+ s->unprocessed_incoming_frames_decompressed = true;
+ pending_data = true;
+ }
+ if (end_of_context) {
+ grpc_stream_compression_context_destroy(
+ s->stream_decompression_ctx);
+ s->stream_decompression_ctx = nullptr;
+ }
+ }
}
}
if (s->read_closed && s->frame_storage.length == 0 && !pending_data &&
@@ -1988,7 +1988,7 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
s->collecting_stats = nullptr;
grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[1],
s->recv_trailing_metadata);
- null_then_sched_closure(&s->recv_trailing_metadata_finished);
+ null_then_sched_closure(&s->recv_trailing_metadata_finished);
}
}
}
@@ -1997,7 +1997,7 @@ static void remove_stream(grpc_chttp2_transport* t, uint32_t id,
grpc_error* error) {
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(
grpc_chttp2_stream_map_delete(&t->stream_map, id));
- GPR_DEBUG_ASSERT(s);
+ GPR_DEBUG_ASSERT(s);
if (t->incoming_stream == s) {
t->incoming_stream = nullptr;
grpc_chttp2_parsing_become_skip_parser(t);
@@ -2049,8 +2049,8 @@ void grpc_chttp2_cancel_stream(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
grpc_http2_error_code http_error;
grpc_error_get_status(due_to_error, s->deadline, nullptr, nullptr,
&http_error, nullptr);
- grpc_chttp2_add_rst_stream_to_next_write(
- t, s->id, static_cast<uint32_t>(http_error), &s->stats.outgoing);
+ grpc_chttp2_add_rst_stream_to_next_write(
+ t, s->id, static_cast<uint32_t>(http_error), &s->stats.outgoing);
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM);
}
}
@@ -2083,7 +2083,7 @@ void grpc_chttp2_fake_status(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
&s->metadata_buffer[1],
grpc_mdelem_from_slices(
GRPC_MDSTR_GRPC_STATUS,
- grpc_core::UnmanagedMemorySlice(status_string))));
+ grpc_core::UnmanagedMemorySlice(status_string))));
if (!GRPC_SLICE_IS_EMPTY(slice)) {
GRPC_LOG_IF_ERROR(
"add_status_message",
@@ -2202,7 +2202,7 @@ void grpc_chttp2_mark_stream_closed(grpc_chttp2_transport* t,
if (closed_read) {
for (int i = 0; i < 2; i++) {
if (s->published_metadata[i] == GRPC_METADATA_NOT_PUBLISHED) {
- s->published_metadata[i] = GRPC_METADATA_PUBLISHED_AT_CLOSE;
+ s->published_metadata[i] = GRPC_METADATA_PUBLISHED_AT_CLOSE;
}
}
grpc_chttp2_maybe_complete_recv_initial_metadata(t, s);
@@ -2366,8 +2366,8 @@ static void close_from_api(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
grpc_slice_buffer_add(&t->qbuf, message_pfx);
grpc_slice_buffer_add(&t->qbuf, grpc_slice_ref_internal(slice));
grpc_chttp2_reset_ping_clock(t);
- grpc_chttp2_add_rst_stream_to_next_write(t, s->id, GRPC_HTTP2_NO_ERROR,
- &s->stats.outgoing);
+ grpc_chttp2_add_rst_stream_to_next_write(t, s->id, GRPC_HTTP2_NO_ERROR,
+ &s->stats.outgoing);
grpc_chttp2_mark_stream_closed(t, s, 1, 1, error);
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API);
@@ -2378,20 +2378,20 @@ struct cancel_stream_cb_args {
grpc_chttp2_transport* t;
};
-static void cancel_stream_cb(void* user_data, uint32_t /*key*/, void* stream) {
+static void cancel_stream_cb(void* user_data, uint32_t /*key*/, void* stream) {
cancel_stream_cb_args* args = static_cast<cancel_stream_cb_args*>(user_data);
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(stream);
grpc_chttp2_cancel_stream(args->t, s, GRPC_ERROR_REF(args->error));
}
static void end_all_the_calls(grpc_chttp2_transport* t, grpc_error* error) {
- intptr_t http2_error;
- // If there is no explicit grpc or HTTP/2 error, set to UNAVAILABLE on server.
- if (!t->is_client && !grpc_error_has_clear_grpc_status(error) &&
- !grpc_error_get_int(error, GRPC_ERROR_INT_HTTP2_ERROR, &http2_error)) {
- error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE);
- }
+ intptr_t http2_error;
+ // If there is no explicit grpc or HTTP/2 error, set to UNAVAILABLE on server.
+ if (!t->is_client && !grpc_error_has_clear_grpc_status(error) &&
+ !grpc_error_get_int(error, GRPC_ERROR_INT_HTTP2_ERROR, &http2_error)) {
+ error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE);
+ }
cancel_stream_cb_args args = {error, t};
grpc_chttp2_stream_map_for_each(&t->stream_map, cancel_stream_cb, &args);
GRPC_ERROR_UNREF(error);
@@ -2467,13 +2467,13 @@ static grpc_error* try_http_parsing(grpc_chttp2_transport* t) {
return error;
}
-static void read_action(void* tp, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&t->read_action_locked, read_action_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void read_action(void* tp, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&t->read_action_locked, read_action_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void read_action_locked(void* tp, grpc_error* error) {
GPR_TIMER_SCOPE("reading_action_locked", 0);
@@ -2547,16 +2547,16 @@ static void read_action_locked(void* tp, grpc_error* error) {
grpc_slice_buffer_reset_and_unref_internal(&t->read_buffer);
if (keep_reading) {
- if (t->num_pending_induced_frames >= DEFAULT_MAX_PENDING_INDUCED_FRAMES) {
- t->reading_paused_on_pending_induced_frames = true;
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_INFO,
- "transport %p : Pausing reading due to too "
- "many unwritten SETTINGS ACK and RST_STREAM frames",
- t));
- } else {
- continue_read_action_locked(t);
- }
+ if (t->num_pending_induced_frames >= DEFAULT_MAX_PENDING_INDUCED_FRAMES) {
+ t->reading_paused_on_pending_induced_frames = true;
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_INFO,
+ "transport %p : Pausing reading due to too "
+ "many unwritten SETTINGS ACK and RST_STREAM frames",
+ t));
+ } else {
+ continue_read_action_locked(t);
+ }
} else {
GRPC_CHTTP2_UNREF_TRANSPORT(t, "reading_action");
}
@@ -2564,98 +2564,98 @@ static void read_action_locked(void* tp, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
-static void continue_read_action_locked(grpc_chttp2_transport* t) {
- const bool urgent = t->goaway_error != GRPC_ERROR_NONE;
- GRPC_CLOSURE_INIT(&t->read_action_locked, read_action, t,
- grpc_schedule_on_exec_ctx);
- grpc_endpoint_read(t->ep, &t->read_buffer, &t->read_action_locked, urgent);
- grpc_chttp2_act_on_flowctl_action(t->flow_control->MakeAction(), t, nullptr);
-}
-
+static void continue_read_action_locked(grpc_chttp2_transport* t) {
+ const bool urgent = t->goaway_error != GRPC_ERROR_NONE;
+ GRPC_CLOSURE_INIT(&t->read_action_locked, read_action, t,
+ grpc_schedule_on_exec_ctx);
+ grpc_endpoint_read(t->ep, &t->read_buffer, &t->read_action_locked, urgent);
+ grpc_chttp2_act_on_flowctl_action(t->flow_control->MakeAction(), t, nullptr);
+}
+
// t is reffed prior to calling the first time, and once the callback chain
// that kicks off finishes, it's unreffed
void schedule_bdp_ping_locked(grpc_chttp2_transport* t) {
t->flow_control->bdp_estimator()->SchedulePing();
- send_ping_locked(
- t,
- GRPC_CLOSURE_INIT(&t->start_bdp_ping_locked, start_bdp_ping, t,
- grpc_schedule_on_exec_ctx),
- GRPC_CLOSURE_INIT(&t->finish_bdp_ping_locked, finish_bdp_ping, t,
- grpc_schedule_on_exec_ctx));
+ send_ping_locked(
+ t,
+ GRPC_CLOSURE_INIT(&t->start_bdp_ping_locked, start_bdp_ping, t,
+ grpc_schedule_on_exec_ctx),
+ GRPC_CLOSURE_INIT(&t->finish_bdp_ping_locked, finish_bdp_ping, t,
+ grpc_schedule_on_exec_ctx));
// TODO(yashykt): Enabling this causes internal b/168345569. Re-enable once
// fixed.
// grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_BDP_PING);
}
-static void start_bdp_ping(void* tp, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_bdp_ping_locked,
- start_bdp_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void start_bdp_ping(void* tp, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_bdp_ping_locked,
+ start_bdp_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void start_bdp_ping_locked(void* tp, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "%s: Start BDP ping err=%s", t->peer_string.c_str(),
grpc_error_string(error));
}
- if (error != GRPC_ERROR_NONE || t->closed_with_error != GRPC_ERROR_NONE) {
- return;
- }
+ if (error != GRPC_ERROR_NONE || t->closed_with_error != GRPC_ERROR_NONE) {
+ return;
+ }
// Reset the keepalive ping timer
if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING) {
grpc_timer_cancel(&t->keepalive_ping_timer);
}
t->flow_control->bdp_estimator()->StartPing();
- t->bdp_ping_started = true;
-}
-
-static void finish_bdp_ping(void* tp, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->finish_bdp_ping_locked,
- finish_bdp_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
+ t->bdp_ping_started = true;
}
+static void finish_bdp_ping(void* tp, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->finish_bdp_ping_locked,
+ finish_bdp_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void finish_bdp_ping_locked(void* tp, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "%s: Complete BDP ping err=%s", t->peer_string.c_str(),
grpc_error_string(error));
}
- if (error != GRPC_ERROR_NONE || t->closed_with_error != GRPC_ERROR_NONE) {
+ if (error != GRPC_ERROR_NONE || t->closed_with_error != GRPC_ERROR_NONE) {
GRPC_CHTTP2_UNREF_TRANSPORT(t, "bdp_ping");
return;
}
- if (!t->bdp_ping_started) {
+ if (!t->bdp_ping_started) {
// start_bdp_ping_locked has not been run yet. Schedule
// finish_bdp_ping_locked to be run later.
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->finish_bdp_ping_locked,
- finish_bdp_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
- return;
- }
- t->bdp_ping_started = false;
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->finish_bdp_ping_locked,
+ finish_bdp_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+ return;
+ }
+ t->bdp_ping_started = false;
grpc_millis next_ping = t->flow_control->bdp_estimator()->CompletePing();
grpc_chttp2_act_on_flowctl_action(t->flow_control->PeriodicUpdate(), t,
nullptr);
GPR_ASSERT(!t->have_next_bdp_ping_timer);
t->have_next_bdp_ping_timer = true;
- GRPC_CLOSURE_INIT(&t->next_bdp_ping_timer_expired_locked,
- next_bdp_ping_timer_expired, t, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->next_bdp_ping_timer_expired_locked,
+ next_bdp_ping_timer_expired, t, grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->next_bdp_ping_timer, next_ping,
&t->next_bdp_ping_timer_expired_locked);
}
-static void next_bdp_ping_timer_expired(void* tp, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&t->next_bdp_ping_timer_expired_locked,
- next_bdp_ping_timer_expired_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void next_bdp_ping_timer_expired(void* tp, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&t->next_bdp_ping_timer_expired_locked,
+ next_bdp_ping_timer_expired_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void next_bdp_ping_timer_expired_locked(void* tp, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
GPR_ASSERT(t->have_next_bdp_ping_timer);
@@ -2704,7 +2704,7 @@ void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args,
const bool value = static_cast<uint32_t>(grpc_channel_arg_get_integer(
&args->args[i],
{is_client ? g_default_client_keepalive_permit_without_calls
- : g_default_server_keepalive_permit_without_calls,
+ : g_default_server_keepalive_permit_without_calls,
0, 1}));
if (is_client) {
g_default_client_keepalive_permit_without_calls = value;
@@ -2740,13 +2740,13 @@ void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args,
}
}
-static void init_keepalive_ping(void* arg, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked,
- init_keepalive_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void init_keepalive_ping(void* arg, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked,
+ init_keepalive_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void init_keepalive_ping_locked(void* arg, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
GPR_ASSERT(t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING);
@@ -2762,8 +2762,8 @@ static void init_keepalive_ping_locked(void* arg, grpc_error* error) {
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING);
} else {
GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping");
- GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
+ grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->keepalive_ping_timer,
grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
&t->init_keepalive_ping_locked);
@@ -2771,8 +2771,8 @@ static void init_keepalive_ping_locked(void* arg, grpc_error* error) {
} else if (error == GRPC_ERROR_CANCELLED) {
// The keepalive ping timer may be cancelled by bdp
GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping");
- GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
+ grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->keepalive_ping_timer,
grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
&t->init_keepalive_ping_locked);
@@ -2780,13 +2780,13 @@ static void init_keepalive_ping_locked(void* arg, grpc_error* error) {
GRPC_CHTTP2_UNREF_TRANSPORT(t, "init keepalive ping");
}
-static void start_keepalive_ping(void* arg, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked,
- start_keepalive_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void start_keepalive_ping(void* arg, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked,
+ start_keepalive_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void start_keepalive_ping_locked(void* arg, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
if (error != GRPC_ERROR_NONE) {
@@ -2800,21 +2800,21 @@ static void start_keepalive_ping_locked(void* arg, grpc_error* error) {
gpr_log(GPR_INFO, "%s: Start keepalive ping", t->peer_string.c_str());
}
GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive watchdog");
- GRPC_CLOSURE_INIT(&t->keepalive_watchdog_fired_locked,
- keepalive_watchdog_fired, t, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->keepalive_watchdog_fired_locked,
+ keepalive_watchdog_fired, t, grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->keepalive_watchdog_timer,
grpc_core::ExecCtx::Get()->Now() + t->keepalive_timeout,
&t->keepalive_watchdog_fired_locked);
- t->keepalive_ping_started = true;
-}
-
-static void finish_keepalive_ping(void* arg, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
- finish_keepalive_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
+ t->keepalive_ping_started = true;
}
+static void finish_keepalive_ping(void* arg, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
+ finish_keepalive_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void finish_keepalive_ping_locked(void* arg, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_PINGING) {
@@ -2823,21 +2823,21 @@ static void finish_keepalive_ping_locked(void* arg, grpc_error* error) {
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
gpr_log(GPR_INFO, "%s: Finish keepalive ping", t->peer_string.c_str());
}
- if (!t->keepalive_ping_started) {
+ if (!t->keepalive_ping_started) {
// start_keepalive_ping_locked has not run yet. Reschedule
// finish_keepalive_ping_locked for it to be run later.
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
- finish_keepalive_ping_locked, t, nullptr),
- GRPC_ERROR_REF(error));
- return;
- }
- t->keepalive_ping_started = false;
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
+ finish_keepalive_ping_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+ return;
+ }
+ t->keepalive_ping_started = false;
t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING;
grpc_timer_cancel(&t->keepalive_watchdog_timer);
GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping");
- GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t,
+ grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->keepalive_ping_timer,
grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
&t->init_keepalive_ping_locked);
@@ -2846,14 +2846,14 @@ static void finish_keepalive_ping_locked(void* arg, grpc_error* error) {
GRPC_CHTTP2_UNREF_TRANSPORT(t, "keepalive ping end");
}
-static void keepalive_watchdog_fired(void* arg, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&t->keepalive_watchdog_fired_locked,
- keepalive_watchdog_fired_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void keepalive_watchdog_fired(void* arg, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&t->keepalive_watchdog_fired_locked,
+ keepalive_watchdog_fired_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void keepalive_watchdog_fired_locked(void* arg, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_PINGING) {
@@ -2885,9 +2885,9 @@ static void keepalive_watchdog_fired_locked(void* arg, grpc_error* error) {
static void connectivity_state_set(grpc_chttp2_transport* t,
grpc_connectivity_state state,
const y_absl::Status& status,
- const char* reason) {
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_INFO, "transport %p set connectivity_state=%d", t, state));
+ const char* reason) {
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_INFO, "transport %p set connectivity_state=%d", t, state));
t->state_tracker.SetState(state, status, reason);
}
@@ -2895,13 +2895,13 @@ static void connectivity_state_set(grpc_chttp2_transport* t,
// POLLSET STUFF
//
-static void set_pollset(grpc_transport* gt, grpc_stream* /*gs*/,
+static void set_pollset(grpc_transport* gt, grpc_stream* /*gs*/,
grpc_pollset* pollset) {
grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
grpc_endpoint_add_to_pollset(t->ep, pollset);
}
-static void set_pollset_set(grpc_transport* gt, grpc_stream* /*gs*/,
+static void set_pollset_set(grpc_transport* gt, grpc_stream* /*gs*/,
grpc_pollset_set* pollset_set) {
grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
grpc_endpoint_add_to_pollset_set(t->ep, pollset_set);
@@ -2919,7 +2919,7 @@ static void reset_byte_stream(void* arg, grpc_error* error) {
grpc_chttp2_maybe_complete_recv_trailing_metadata(s->t, s);
} else {
GPR_ASSERT(error != GRPC_ERROR_NONE);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->on_next, GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->on_next, GRPC_ERROR_REF(error));
s->on_next = nullptr;
GRPC_ERROR_UNREF(s->byte_stream_error);
s->byte_stream_error = GRPC_ERROR_NONE;
@@ -2943,7 +2943,7 @@ Chttp2IncomingByteStream::Chttp2IncomingByteStream(
}
void Chttp2IncomingByteStream::OrphanLocked(void* arg,
- grpc_error* /*error_ignored*/) {
+ grpc_error* /*error_ignored*/) {
Chttp2IncomingByteStream* bs = static_cast<Chttp2IncomingByteStream*>(arg);
grpc_chttp2_stream* s = bs->stream_;
grpc_chttp2_transport* t = s->t;
@@ -2955,14 +2955,14 @@ void Chttp2IncomingByteStream::OrphanLocked(void* arg,
void Chttp2IncomingByteStream::Orphan() {
GPR_TIMER_SCOPE("incoming_byte_stream_destroy", 0);
- transport_->combiner->Run(
+ transport_->combiner->Run(
GRPC_CLOSURE_INIT(&destroy_action_,
- &Chttp2IncomingByteStream::OrphanLocked, this, nullptr),
+ &Chttp2IncomingByteStream::OrphanLocked, this, nullptr),
GRPC_ERROR_NONE);
}
void Chttp2IncomingByteStream::NextLocked(void* arg,
- grpc_error* /*error_ignored*/) {
+ grpc_error* /*error_ignored*/) {
Chttp2IncomingByteStream* bs = static_cast<Chttp2IncomingByteStream*>(arg);
grpc_chttp2_transport* t = bs->transport_;
grpc_chttp2_stream* s = bs->stream_;
@@ -2977,11 +2977,11 @@ void Chttp2IncomingByteStream::NextLocked(void* arg,
grpc_slice_buffer_swap(&s->frame_storage,
&s->unprocessed_incoming_frames_buffer);
s->unprocessed_incoming_frames_decompressed = false;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, bs->next_action_.on_complete,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, bs->next_action_.on_complete,
+ GRPC_ERROR_NONE);
} else if (s->byte_stream_error != GRPC_ERROR_NONE) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, bs->next_action_.on_complete,
- GRPC_ERROR_REF(s->byte_stream_error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, bs->next_action_.on_complete,
+ GRPC_ERROR_REF(s->byte_stream_error));
if (s->data_parser.parsing_frame != nullptr) {
s->data_parser.parsing_frame->Unref();
s->data_parser.parsing_frame = nullptr;
@@ -2990,8 +2990,8 @@ void Chttp2IncomingByteStream::NextLocked(void* arg,
if (bs->remaining_bytes_ != 0) {
s->byte_stream_error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Truncated message", &s->read_closed_error, 1);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, bs->next_action_.on_complete,
- GRPC_ERROR_REF(s->byte_stream_error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, bs->next_action_.on_complete,
+ GRPC_ERROR_REF(s->byte_stream_error));
if (s->data_parser.parsing_frame != nullptr) {
s->data_parser.parsing_frame->Unref();
s->data_parser.parsing_frame = nullptr;
@@ -3015,17 +3015,17 @@ bool Chttp2IncomingByteStream::Next(size_t max_size_hint,
Ref();
next_action_.max_size_hint = max_size_hint;
next_action_.on_complete = on_complete;
- transport_->combiner->Run(
+ transport_->combiner->Run(
GRPC_CLOSURE_INIT(&next_action_.closure,
- &Chttp2IncomingByteStream::NextLocked, this, nullptr),
+ &Chttp2IncomingByteStream::NextLocked, this, nullptr),
GRPC_ERROR_NONE);
return false;
}
}
void Chttp2IncomingByteStream::MaybeCreateStreamDecompressionCtx() {
- GPR_DEBUG_ASSERT(stream_->stream_decompression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS);
+ GPR_DEBUG_ASSERT(stream_->stream_decompression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS);
if (!stream_->stream_decompression_ctx) {
stream_->stream_decompression_ctx = grpc_stream_compression_context_create(
stream_->stream_decompression_method);
@@ -3036,9 +3036,9 @@ grpc_error* Chttp2IncomingByteStream::Pull(grpc_slice* slice) {
GPR_TIMER_SCOPE("incoming_byte_stream_pull", 0);
grpc_error* error;
if (stream_->unprocessed_incoming_frames_buffer.length > 0) {
- if (!stream_->unprocessed_incoming_frames_decompressed &&
- stream_->stream_decompression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
+ if (!stream_->unprocessed_incoming_frames_decompressed &&
+ stream_->stream_decompression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
bool end_of_context;
MaybeCreateStreamDecompressionCtx();
if (!grpc_stream_decompress(stream_->stream_decompression_ctx,
@@ -3070,8 +3070,8 @@ grpc_error* Chttp2IncomingByteStream::Pull(grpc_slice* slice) {
}
} else {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
- stream_->t->combiner->Run(&stream_->reset_byte_stream,
- GRPC_ERROR_REF(error));
+ stream_->t->combiner->Run(&stream_->reset_byte_stream,
+ GRPC_ERROR_REF(error));
return error;
}
return GRPC_ERROR_NONE;
@@ -3079,21 +3079,21 @@ grpc_error* Chttp2IncomingByteStream::Pull(grpc_slice* slice) {
void Chttp2IncomingByteStream::PublishError(grpc_error* error) {
GPR_ASSERT(error != GRPC_ERROR_NONE);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, stream_->on_next,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, stream_->on_next,
+ GRPC_ERROR_REF(error));
stream_->on_next = nullptr;
GRPC_ERROR_UNREF(stream_->byte_stream_error);
stream_->byte_stream_error = GRPC_ERROR_REF(error);
grpc_chttp2_cancel_stream(transport_, stream_, GRPC_ERROR_REF(error));
}
-grpc_error* Chttp2IncomingByteStream::Push(const grpc_slice& slice,
+grpc_error* Chttp2IncomingByteStream::Push(const grpc_slice& slice,
grpc_slice* slice_out) {
if (remaining_bytes_ < GRPC_SLICE_LENGTH(slice)) {
grpc_error* error =
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many bytes in stream");
- transport_->combiner->Run(&stream_->reset_byte_stream,
- GRPC_ERROR_REF(error));
+ transport_->combiner->Run(&stream_->reset_byte_stream,
+ GRPC_ERROR_REF(error));
grpc_slice_unref_internal(slice);
return error;
} else {
@@ -3113,8 +3113,8 @@ grpc_error* Chttp2IncomingByteStream::Finished(grpc_error* error,
}
}
if (error != GRPC_ERROR_NONE && reset_on_error) {
- transport_->combiner->Run(&stream_->reset_byte_stream,
- GRPC_ERROR_REF(error));
+ transport_->combiner->Run(&stream_->reset_byte_stream,
+ GRPC_ERROR_REF(error));
}
Unref();
return error;
@@ -3134,8 +3134,8 @@ static void post_benign_reclaimer(grpc_chttp2_transport* t) {
if (!t->benign_reclaimer_registered) {
t->benign_reclaimer_registered = true;
GRPC_CHTTP2_REF_TRANSPORT(t, "benign_reclaimer");
- GRPC_CLOSURE_INIT(&t->benign_reclaimer_locked, benign_reclaimer, t,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->benign_reclaimer_locked, benign_reclaimer, t,
+ grpc_schedule_on_exec_ctx);
grpc_resource_user_post_reclaimer(grpc_endpoint_get_resource_user(t->ep),
false, &t->benign_reclaimer_locked);
}
@@ -3145,27 +3145,27 @@ static void post_destructive_reclaimer(grpc_chttp2_transport* t) {
if (!t->destructive_reclaimer_registered) {
t->destructive_reclaimer_registered = true;
GRPC_CHTTP2_REF_TRANSPORT(t, "destructive_reclaimer");
- GRPC_CLOSURE_INIT(&t->destructive_reclaimer_locked, destructive_reclaimer,
- t, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->destructive_reclaimer_locked, destructive_reclaimer,
+ t, grpc_schedule_on_exec_ctx);
grpc_resource_user_post_reclaimer(grpc_endpoint_get_resource_user(t->ep),
true, &t->destructive_reclaimer_locked);
}
}
-static void benign_reclaimer(void* arg, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->benign_reclaimer_locked,
- benign_reclaimer_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void benign_reclaimer(void* arg, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->benign_reclaimer_locked,
+ benign_reclaimer_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void benign_reclaimer_locked(void* arg, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
if (error == GRPC_ERROR_NONE &&
grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
// Channel with no active streams: send a goaway to try and make it
// disconnect cleanly
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "HTTP2: %s - send goaway to free memory",
t->peer_string.c_str());
}
@@ -3173,8 +3173,8 @@ static void benign_reclaimer_locked(void* arg, grpc_error* error) {
grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Buffers full"),
GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_ENHANCE_YOUR_CALM));
- } else if (error == GRPC_ERROR_NONE &&
- GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ } else if (error == GRPC_ERROR_NONE &&
+ GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO,
"HTTP2: %s - skip benign reclamation, there are still %" PRIdPTR
" streams",
@@ -3189,13 +3189,13 @@ static void benign_reclaimer_locked(void* arg, grpc_error* error) {
GRPC_CHTTP2_UNREF_TRANSPORT(t, "benign_reclaimer");
}
-static void destructive_reclaimer(void* arg, grpc_error* error) {
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
- t->combiner->Run(GRPC_CLOSURE_INIT(&t->destructive_reclaimer_locked,
- destructive_reclaimer_locked, t, nullptr),
- GRPC_ERROR_REF(error));
-}
-
+static void destructive_reclaimer(void* arg, grpc_error* error) {
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
+ t->combiner->Run(GRPC_CLOSURE_INIT(&t->destructive_reclaimer_locked,
+ destructive_reclaimer_locked, t, nullptr),
+ GRPC_ERROR_REF(error));
+}
+
static void destructive_reclaimer_locked(void* arg, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg);
size_t n = grpc_chttp2_stream_map_size(&t->stream_map);
@@ -3203,7 +3203,7 @@ static void destructive_reclaimer_locked(void* arg, grpc_error* error) {
if (error == GRPC_ERROR_NONE && n > 0) {
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(
grpc_chttp2_stream_map_rand(&t->stream_map));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "HTTP2: %s - abandon stream id %d",
t->peer_string.c_str(), s->id);
}
@@ -3307,8 +3307,8 @@ grpc_chttp2_transport_get_socket_node(grpc_transport* transport) {
grpc_transport* grpc_create_chttp2_transport(
const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client,
grpc_resource_user* resource_user) {
- auto t =
- new grpc_chttp2_transport(channel_args, ep, is_client, resource_user);
+ auto t =
+ new grpc_chttp2_transport(channel_args, ep, is_client, resource_user);
return &t->base;
}
@@ -3324,7 +3324,7 @@ void grpc_chttp2_transport_start_reading(
gpr_free(read_buffer);
}
t->notify_on_receive_settings = notify_on_receive_settings;
- t->combiner->Run(
- GRPC_CLOSURE_INIT(&t->read_action_locked, read_action_locked, t, nullptr),
- GRPC_ERROR_NONE);
+ t->combiner->Run(
+ GRPC_CLOSURE_INIT(&t->read_action_locked, read_action_locked, t, nullptr),
+ GRPC_ERROR_NONE);
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h
index b04630bbe2..0f1c1dfb31 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h
@@ -30,7 +30,7 @@ extern grpc_core::TraceFlag grpc_http_trace;
extern grpc_core::TraceFlag grpc_keepalive_trace;
extern grpc_core::TraceFlag grpc_trace_http2_stream_state;
extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount;
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser;
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser;
extern bool g_flow_control_enabled;
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc
index a0473ea822..dae54e566e 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc
@@ -33,7 +33,7 @@ void ContextList::Append(ContextList** head, grpc_chttp2_stream* s) {
return;
}
/* Create a new element in the list and add it at the front */
- ContextList* elem = new ContextList();
+ ContextList* elem = new ContextList();
elem->trace_context_ = get_copied_context_fn_g(s->context);
elem->byte_offset_ = s->byte_counter;
elem->next_ = *head;
@@ -46,14 +46,14 @@ void ContextList::Execute(void* arg, grpc_core::Timestamps* ts,
ContextList* to_be_freed;
while (head != nullptr) {
if (write_timestamps_callback_g) {
- if (ts) {
- ts->byte_offset = static_cast<uint32_t>(head->byte_offset_);
- }
+ if (ts) {
+ ts->byte_offset = static_cast<uint32_t>(head->byte_offset_);
+ }
write_timestamps_callback_g(head->trace_context_, ts, error);
}
to_be_freed = head;
head = head->next_;
- delete to_be_freed;
+ delete to_be_freed;
}
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc
index fd76c4b3d9..cf4317c409 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc
@@ -192,7 +192,7 @@ TransportFlowControl::TransportFlowControl(const grpc_chttp2_transport* t,
uint32_t TransportFlowControl::MaybeSendUpdate(bool writing_anyway) {
FlowControlTrace trace("t updt sent", this, nullptr);
const uint32_t target_announced_window =
- static_cast<uint32_t>(target_window());
+ static_cast<uint32_t>(target_window());
if ((writing_anyway || announced_window_ <= target_announced_window / 2) &&
announced_window_ != target_announced_window) {
const uint32_t announce = static_cast<uint32_t> GPR_CLAMP(
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.h
index a55ab82efb..367d4de6be 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.h
@@ -126,7 +126,7 @@ class FlowControlTrace {
StreamFlowControl* sfc);
void Finish();
- const bool enabled_ = GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace);
+ const bool enabled_ = GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace);
TransportFlowControl* tfc_;
StreamFlowControl* sfc_;
@@ -206,14 +206,14 @@ class TransportFlowControlDisabled final : public TransportFlowControlBase {
bool flow_control_enabled() const override { return false; }
// Never do anything.
- uint32_t MaybeSendUpdate(bool /* writing_anyway */) override { return 0; }
+ uint32_t MaybeSendUpdate(bool /* writing_anyway */) override { return 0; }
FlowControlAction MakeAction() override { return FlowControlAction(); }
FlowControlAction PeriodicUpdate() override { return FlowControlAction(); }
- void StreamSentData(int64_t /* size */) override {}
- grpc_error* RecvData(int64_t /* incoming_frame_size */) override {
+ void StreamSentData(int64_t /* size */) override {}
+ grpc_error* RecvData(int64_t /* incoming_frame_size */) override {
return GRPC_ERROR_NONE;
}
- void RecvUpdate(uint32_t /* size */) override {}
+ void RecvUpdate(uint32_t /* size */) override {}
};
// Implementation of flow control that abides to HTTP/2 spec and attempts
@@ -340,9 +340,9 @@ class StreamFlowControlBase {
virtual ~StreamFlowControlBase() {}
// Updates an action using the protected members.
- virtual FlowControlAction UpdateAction(FlowControlAction /* action */) {
- abort();
- }
+ virtual FlowControlAction UpdateAction(FlowControlAction /* action */) {
+ abort();
+ }
// Using the protected members, returns an Action for this stream to be
// taken by the tranport.
@@ -363,8 +363,8 @@ class StreamFlowControlBase {
// Bookkeeping for when a call pulls bytes out of the transport. At this
// point we consider the data 'used' and can thus let out peer know we are
// ready for more data.
- virtual void IncomingByteStreamUpdate(size_t /* max_size_hint */,
- size_t /* have_already */) {
+ virtual void IncomingByteStreamUpdate(size_t /* max_size_hint */,
+ size_t /* have_already */) {
abort();
}
@@ -394,14 +394,14 @@ class StreamFlowControlDisabled : public StreamFlowControlBase {
return action;
}
FlowControlAction MakeAction() override { return FlowControlAction(); }
- void SentData(int64_t /* outgoing_frame_size */) override {}
- grpc_error* RecvData(int64_t /* incoming_frame_size */) override {
+ void SentData(int64_t /* outgoing_frame_size */) override {}
+ grpc_error* RecvData(int64_t /* incoming_frame_size */) override {
return GRPC_ERROR_NONE;
}
uint32_t MaybeSendUpdate() override { return 0; }
- void RecvUpdate(uint32_t /* size */) override {}
- void IncomingByteStreamUpdate(size_t /* max_size_hint */,
- size_t /* have_already */) override {}
+ void RecvUpdate(uint32_t /* size */) override {}
+ void IncomingByteStreamUpdate(size_t /* max_size_hint */,
+ size_t /* have_already */) override {}
};
// Implementation of flow control that abides to HTTP/2 spec and attempts
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc
index 6869bdb006..73627cd7eb 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc
@@ -41,9 +41,9 @@ grpc_chttp2_data_parser::~grpc_chttp2_data_parser() {
GRPC_ERROR_UNREF(error);
}
-grpc_error* grpc_chttp2_data_parser_begin_frame(
- grpc_chttp2_data_parser* /*parser*/, uint8_t flags, uint32_t stream_id,
- grpc_chttp2_stream* s) {
+grpc_error* grpc_chttp2_data_parser_begin_frame(
+ grpc_chttp2_data_parser* /*parser*/, uint8_t flags, uint32_t stream_id,
+ grpc_chttp2_stream* s) {
if (flags & ~GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
return grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
@@ -101,21 +101,21 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
uint8_t* end = nullptr;
uint8_t* cur = nullptr;
- grpc_slice* slice = grpc_slice_buffer_peek_first(slices);
- beg = GRPC_SLICE_START_PTR(*slice);
- end = GRPC_SLICE_END_PTR(*slice);
+ grpc_slice* slice = grpc_slice_buffer_peek_first(slices);
+ beg = GRPC_SLICE_START_PTR(*slice);
+ end = GRPC_SLICE_END_PTR(*slice);
cur = beg;
uint32_t message_flags;
if (cur == end) {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
continue;
}
switch (p->state) {
case GRPC_CHTTP2_DATA_ERROR:
p->state = GRPC_CHTTP2_DATA_ERROR;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return GRPC_ERROR_REF(p->error);
case GRPC_CHTTP2_DATA_FH_0:
s->stats.incoming.framing_bytes++;
@@ -133,19 +133,19 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
.c_str());
p->error = grpc_error_set_int(p->error, GRPC_ERROR_INT_STREAM_ID,
static_cast<intptr_t>(s->id));
- p->error = grpc_error_set_str(
- p->error, GRPC_ERROR_STR_RAW_BYTES,
- grpc_slice_from_moved_string(grpc_core::UniquePtr<char>(
- grpc_dump_slice(*slice, GPR_DUMP_HEX | GPR_DUMP_ASCII))));
+ p->error = grpc_error_set_str(
+ p->error, GRPC_ERROR_STR_RAW_BYTES,
+ grpc_slice_from_moved_string(grpc_core::UniquePtr<char>(
+ grpc_dump_slice(*slice, GPR_DUMP_HEX | GPR_DUMP_ASCII))));
p->error =
grpc_error_set_int(p->error, GRPC_ERROR_INT_OFFSET, cur - beg);
p->state = GRPC_CHTTP2_DATA_ERROR;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return GRPC_ERROR_REF(p->error);
}
if (++cur == end) {
p->state = GRPC_CHTTP2_DATA_FH_1;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
continue;
}
/* fallthrough */
@@ -154,7 +154,7 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
p->frame_size = (static_cast<uint32_t>(*cur)) << 24;
if (++cur == end) {
p->state = GRPC_CHTTP2_DATA_FH_2;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
continue;
}
/* fallthrough */
@@ -163,7 +163,7 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
p->frame_size |= (static_cast<uint32_t>(*cur)) << 16;
if (++cur == end) {
p->state = GRPC_CHTTP2_DATA_FH_3;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
continue;
}
/* fallthrough */
@@ -172,7 +172,7 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
p->frame_size |= (static_cast<uint32_t>(*cur)) << 8;
if (++cur == end) {
p->state = GRPC_CHTTP2_DATA_FH_4;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
continue;
}
/* fallthrough */
@@ -190,7 +190,7 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
if (p->is_frame_compressed) {
message_flags |= GRPC_WRITE_INTERNAL_COMPRESS;
}
- p->parsing_frame = new grpc_core::Chttp2IncomingByteStream(
+ p->parsing_frame = new grpc_core::Chttp2IncomingByteStream(
t, s, p->frame_size, message_flags);
stream_out->reset(p->parsing_frame);
if (p->parsing_frame->remaining_bytes() == 0) {
@@ -200,17 +200,17 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
}
s->pending_byte_stream = true;
if (cur != end) {
- grpc_slice_buffer_sub_first(slices, static_cast<size_t>(cur - beg),
- static_cast<size_t>(end - beg));
- } else {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_sub_first(slices, static_cast<size_t>(cur - beg),
+ static_cast<size_t>(end - beg));
+ } else {
+ grpc_slice_buffer_remove_first(slices);
}
return GRPC_ERROR_NONE;
case GRPC_CHTTP2_DATA_FRAME: {
GPR_ASSERT(p->parsing_frame != nullptr);
GPR_ASSERT(slice_out != nullptr);
if (cur == end) {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
continue;
}
uint32_t remaining = static_cast<uint32_t>(end - cur);
@@ -218,32 +218,32 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
s->stats.incoming.data_bytes += remaining;
if (GRPC_ERROR_NONE !=
(error = p->parsing_frame->Push(
- grpc_slice_sub(*slice, static_cast<size_t>(cur - beg),
+ grpc_slice_sub(*slice, static_cast<size_t>(cur - beg),
static_cast<size_t>(end - beg)),
slice_out))) {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return error;
}
if (GRPC_ERROR_NONE !=
(error = p->parsing_frame->Finished(GRPC_ERROR_NONE, true))) {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return error;
}
p->parsing_frame = nullptr;
p->state = GRPC_CHTTP2_DATA_FH_0;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return GRPC_ERROR_NONE;
} else if (remaining < p->frame_size) {
s->stats.incoming.data_bytes += remaining;
if (GRPC_ERROR_NONE !=
(error = p->parsing_frame->Push(
- grpc_slice_sub(*slice, static_cast<size_t>(cur - beg),
+ grpc_slice_sub(*slice, static_cast<size_t>(cur - beg),
static_cast<size_t>(end - beg)),
slice_out))) {
return error;
}
p->frame_size -= remaining;
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return GRPC_ERROR_NONE;
} else {
GPR_ASSERT(remaining > p->frame_size);
@@ -251,22 +251,22 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
if (GRPC_ERROR_NONE !=
p->parsing_frame->Push(
grpc_slice_sub(
- *slice, static_cast<size_t>(cur - beg),
+ *slice, static_cast<size_t>(cur - beg),
static_cast<size_t>(cur + p->frame_size - beg)),
slice_out)) {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return error;
}
if (GRPC_ERROR_NONE !=
(error = p->parsing_frame->Finished(GRPC_ERROR_NONE, true))) {
- grpc_slice_buffer_remove_first(slices);
+ grpc_slice_buffer_remove_first(slices);
return error;
}
p->parsing_frame = nullptr;
p->state = GRPC_CHTTP2_DATA_FH_0;
cur += p->frame_size;
- grpc_slice_buffer_sub_first(slices, static_cast<size_t>(cur - beg),
- static_cast<size_t>(end - beg));
+ grpc_slice_buffer_sub_first(slices, static_cast<size_t>(cur - beg),
+ static_cast<size_t>(end - beg));
return GRPC_ERROR_NONE;
}
}
@@ -275,11 +275,11 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
return GRPC_ERROR_NONE;
}
-grpc_error* grpc_chttp2_data_parser_parse(void* /*parser*/,
+grpc_error* grpc_chttp2_data_parser_parse(void* /*parser*/,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last) {
+ const grpc_slice& slice,
+ int is_last) {
if (!s->pending_byte_stream) {
grpc_slice_ref_internal(slice);
grpc_slice_buffer_add(&s->frame_storage, slice);
@@ -288,7 +288,7 @@ grpc_error* grpc_chttp2_data_parser_parse(void* /*parser*/,
GPR_ASSERT(s->frame_storage.length == 0);
grpc_slice_ref_internal(slice);
grpc_slice_buffer_add(&s->unprocessed_incoming_frames_buffer, slice);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->on_next, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->on_next, GRPC_ERROR_NONE);
s->on_next = nullptr;
s->unprocessed_incoming_frames_decompressed = false;
} else {
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h
index ec3890098e..e757ff1e7d 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h
@@ -67,7 +67,7 @@ grpc_error* grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser* parser,
grpc_error* grpc_chttp2_data_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice, int is_last);
+ const grpc_slice& slice, int is_last);
void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf,
uint32_t write_bytes, int is_eof,
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc
index 79a8a03dc7..b07c082dbe 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc
@@ -38,7 +38,7 @@ void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p) {
grpc_error* grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser* p,
uint32_t length,
- uint8_t /*flags*/) {
+ uint8_t /*flags*/) {
if (length < 8) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("goaway frame too short (%d bytes)", length).c_str());
@@ -54,12 +54,12 @@ grpc_error* grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser* p,
grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
grpc_chttp2_transport* t,
- grpc_chttp2_stream* /*s*/,
- const grpc_slice& slice,
- int is_last) {
- const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
- const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
- const uint8_t* cur = beg;
+ grpc_chttp2_stream* /*s*/,
+ const grpc_slice& slice,
+ int is_last) {
+ const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* cur = beg;
grpc_chttp2_goaway_parser* p =
static_cast<grpc_chttp2_goaway_parser*>(parser);
@@ -137,7 +137,7 @@ grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
p->state = GRPC_CHTTP2_GOAWAY_DEBUG;
if (is_last) {
grpc_chttp2_add_incoming_goaway(
- t, p->error_code, p->last_stream_id,
+ t, p->error_code, p->last_stream_id,
grpc_slice_new(p->debug_data, p->debug_length, gpr_free));
p->debug_data = nullptr;
}
@@ -148,7 +148,7 @@ grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
}
void grpc_chttp2_goaway_append(uint32_t last_stream_id, uint32_t error_code,
- const grpc_slice& debug_data,
+ const grpc_slice& debug_data,
grpc_slice_buffer* slice_buffer) {
grpc_slice header = GRPC_SLICE_MALLOC(9 + 4 + 4);
uint8_t* p = GRPC_SLICE_START_PTR(header);
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h
index df6274d628..3a7d18e2a5 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h
@@ -52,11 +52,11 @@ grpc_error* grpc_chttp2_goaway_parser_begin_frame(
grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last);
+ const grpc_slice& slice,
+ int is_last);
void grpc_chttp2_goaway_append(uint32_t last_stream_id, uint32_t error_code,
- const grpc_slice& debug_data,
+ const grpc_slice& debug_data,
grpc_slice_buffer* slice_buffer);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_GOAWAY_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc
index ae152099ba..ed32597809 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc
@@ -71,12 +71,12 @@ grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
grpc_error* grpc_chttp2_ping_parser_parse(void* parser,
grpc_chttp2_transport* t,
- grpc_chttp2_stream* /*s*/,
- const grpc_slice& slice,
- int is_last) {
- const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
- const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
- const uint8_t* cur = beg;
+ grpc_chttp2_stream* /*s*/,
+ const grpc_slice& slice,
+ int is_last) {
+ const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* cur = beg;
grpc_chttp2_ping_parser* p = static_cast<grpc_chttp2_ping_parser*>(parser);
while (p->byte != 8 && cur != end) {
@@ -117,7 +117,7 @@ grpc_error* grpc_chttp2_ping_parser_parse(void* parser,
t->ping_acks = static_cast<uint64_t*>(gpr_realloc(
t->ping_acks, t->ping_ack_capacity * sizeof(*t->ping_acks)));
}
- t->num_pending_induced_frames++;
+ t->num_pending_induced_frames++;
t->ping_acks[t->ping_ack_count++] = p->opaque_8bytes;
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE);
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.h
index e356bf43f0..44fb6b8335 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.h
@@ -36,7 +36,7 @@ grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
grpc_error* grpc_chttp2_ping_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice, int is_last);
+ const grpc_slice& slice, int is_last);
/* Test-only function for disabling ping ack */
void grpc_set_disable_ping_ack(bool disable_ping_ack);
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc
index 5113329991..b01302fe8e 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc
@@ -28,7 +28,7 @@
#include <grpc/support/log.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/transport/http2_errors.h"
grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code,
@@ -60,14 +60,14 @@ grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code,
return slice;
}
-void grpc_chttp2_add_rst_stream_to_next_write(
- grpc_chttp2_transport* t, uint32_t id, uint32_t code,
- grpc_transport_one_way_stats* stats) {
- t->num_pending_induced_frames++;
- grpc_slice_buffer_add(&t->qbuf,
- grpc_chttp2_rst_stream_create(id, code, stats));
-}
-
+void grpc_chttp2_add_rst_stream_to_next_write(
+ grpc_chttp2_transport* t, uint32_t id, uint32_t code,
+ grpc_transport_one_way_stats* stats) {
+ t->num_pending_induced_frames++;
+ grpc_slice_buffer_add(&t->qbuf,
+ grpc_chttp2_rst_stream_create(id, code, stats));
+}
+
grpc_error* grpc_chttp2_rst_stream_parser_begin_frame(
grpc_chttp2_rst_stream_parser* parser, uint32_t length, uint8_t flags) {
if (length != 4) {
@@ -83,11 +83,11 @@ grpc_error* grpc_chttp2_rst_stream_parser_begin_frame(
grpc_error* grpc_chttp2_rst_stream_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last) {
- const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
- const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
- const uint8_t* cur = beg;
+ const grpc_slice& slice,
+ int is_last) {
+ const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* cur = beg;
grpc_chttp2_rst_stream_parser* p =
static_cast<grpc_chttp2_rst_stream_parser*>(parser);
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h
index e324ee2cfc..3c52ae5f2f 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h
@@ -32,19 +32,19 @@ struct grpc_chttp2_rst_stream_parser {
grpc_slice grpc_chttp2_rst_stream_create(uint32_t stream_id, uint32_t code,
grpc_transport_one_way_stats* stats);
-// Adds RST_STREAM frame to t->qbuf (buffer for the next write). Should be
-// called when we want to add RST_STREAM and we are not in
-// write_action_begin_locked.
-void grpc_chttp2_add_rst_stream_to_next_write(
- grpc_chttp2_transport* t, uint32_t id, uint32_t code,
- grpc_transport_one_way_stats* stats);
-
+// Adds RST_STREAM frame to t->qbuf (buffer for the next write). Should be
+// called when we want to add RST_STREAM and we are not in
+// write_action_begin_locked.
+void grpc_chttp2_add_rst_stream_to_next_write(
+ grpc_chttp2_transport* t, uint32_t id, uint32_t code,
+ grpc_transport_one_way_stats* stats);
+
grpc_error* grpc_chttp2_rst_stream_parser_begin_frame(
grpc_chttp2_rst_stream_parser* parser, uint32_t length, uint8_t flags);
grpc_error* grpc_chttp2_rst_stream_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last);
+ const grpc_slice& slice,
+ int is_last);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_RST_STREAM_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc
index 9e9a838cc3..cc3e00ef1f 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc
@@ -111,9 +111,9 @@ grpc_error* grpc_chttp2_settings_parser_begin_frame(
}
grpc_error* grpc_chttp2_settings_parser_parse(void* p, grpc_chttp2_transport* t,
- grpc_chttp2_stream* /*s*/,
- const grpc_slice& slice,
- int is_last) {
+ grpc_chttp2_stream* /*s*/,
+ const grpc_slice& slice,
+ int is_last) {
grpc_chttp2_settings_parser* parser =
static_cast<grpc_chttp2_settings_parser*>(p);
const uint8_t* cur = GRPC_SLICE_START_PTR(slice);
@@ -132,12 +132,12 @@ grpc_error* grpc_chttp2_settings_parser_parse(void* p, grpc_chttp2_transport* t,
if (is_last) {
memcpy(parser->target_settings, parser->incoming_settings,
GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
- t->num_pending_induced_frames++;
+ t->num_pending_induced_frames++;
grpc_slice_buffer_add(&t->qbuf, grpc_chttp2_settings_ack_create());
if (t->notify_on_receive_settings != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- t->notify_on_receive_settings,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ t->notify_on_receive_settings,
+ GRPC_ERROR_NONE);
t->notify_on_receive_settings = nullptr;
}
}
@@ -218,20 +218,20 @@ grpc_error* grpc_chttp2_settings_parser_parse(void* p, grpc_chttp2_transport* t,
parser->incoming_settings[id] != parser->value) {
t->initial_window_update += static_cast<int64_t>(parser->value) -
parser->incoming_settings[id];
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
- GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
+ GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace)) {
gpr_log(GPR_INFO, "%p[%s] adding %d for initial_window change", t,
t->is_client ? "cli" : "svr",
static_cast<int>(t->initial_window_update));
}
}
parser->incoming_settings[id] = parser->value;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "CHTTP2:%s:%s: got setting %s = %d",
t->is_client ? "CLI" : "SVR", t->peer_string.c_str(),
sp->name, parser->value);
}
- } else if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ } else if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_ERROR, "CHTTP2: Ignoring unknown setting %d (value %d)",
parser->id, parser->value);
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.h
index 181471401c..59f53d315a 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.h
@@ -54,7 +54,7 @@ grpc_error* grpc_chttp2_settings_parser_begin_frame(
grpc_error* grpc_chttp2_settings_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last);
+ const grpc_slice& slice,
+ int is_last);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_SETTINGS_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc
index 20efb09b0d..ce0b11a747 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc
@@ -69,11 +69,11 @@ grpc_error* grpc_chttp2_window_update_parser_begin_frame(
grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
+ const grpc_slice& slice,
int is_last) {
- const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
- const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
- const uint8_t* cur = beg;
+ const uint8_t* const beg = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* const end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* cur = beg;
grpc_chttp2_window_update_parser* p =
static_cast<grpc_chttp2_window_update_parser*>(parser);
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h
index 340445d87a..ea8fe91d53 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h
@@ -38,7 +38,7 @@ grpc_error* grpc_chttp2_window_update_parser_begin_frame(
grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
+ const grpc_slice& slice,
int is_last);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_WINDOW_UPDATE_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc
index 4ceaec24b3..a72795cacc 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc
@@ -37,25 +37,25 @@
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/validate_metadata.h"
+#include "src/core/lib/surface/validate_metadata.h"
#include "src/core/lib/transport/metadata.h"
#include "src/core/lib/transport/static_metadata.h"
#include "src/core/lib/transport/timeout_encoding.h"
-namespace {
-/* (Maybe-cuckoo) hpack encoder hash table implementation.
-
- This hashtable implementation is a subset of a proper cuckoo hash; while we
- have fallback cells that a value can be hashed to if the first cell is full,
- we do not attempt to iteratively rearrange entries into backup cells to get
- things to fit. Instead, if both a cell and the backup cell for a value are
- occupied, the older existing entry is evicted.
-
- Note that we can disable backup-cell picking by setting
- GRPC_HPACK_ENCODER_USE_CUCKOO_HASH to 0. In that case, we simply evict an
- existing entry rather than try to use a backup. Hence, "maybe-cuckoo."
- TODO(arjunroy): Add unit tests for hashtable implementation. */
-#define GRPC_HPACK_ENCODER_USE_CUCKOO_HASH 1
+namespace {
+/* (Maybe-cuckoo) hpack encoder hash table implementation.
+
+ This hashtable implementation is a subset of a proper cuckoo hash; while we
+ have fallback cells that a value can be hashed to if the first cell is full,
+ we do not attempt to iteratively rearrange entries into backup cells to get
+ things to fit. Instead, if both a cell and the backup cell for a value are
+ occupied, the older existing entry is evicted.
+
+ Note that we can disable backup-cell picking by setting
+ GRPC_HPACK_ENCODER_USE_CUCKOO_HASH to 0. In that case, we simply evict an
+ existing entry rather than try to use a backup. Hence, "maybe-cuckoo."
+ TODO(arjunroy): Add unit tests for hashtable implementation. */
+#define GRPC_HPACK_ENCODER_USE_CUCKOO_HASH 1
#define HASH_FRAGMENT_MASK (GRPC_CHTTP2_HPACKC_NUM_VALUES - 1)
#define HASH_FRAGMENT_1(x) ((x)&HASH_FRAGMENT_MASK)
#define HASH_FRAGMENT_2(x) \
@@ -65,200 +65,200 @@ namespace {
#define HASH_FRAGMENT_4(x) \
(((x) >> (GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS * 3)) & HASH_FRAGMENT_MASK)
-/* don't consider adding anything bigger than this to the hpack table */
-constexpr size_t kMaxDecoderSpaceUsage = 512;
-constexpr size_t kDataFrameHeaderSize = 9;
-constexpr uint8_t kMaxFilterValue = 255;
-
+/* don't consider adding anything bigger than this to the hpack table */
+constexpr size_t kMaxDecoderSpaceUsage = 512;
+constexpr size_t kDataFrameHeaderSize = 9;
+constexpr uint8_t kMaxFilterValue = 255;
+
/* if the probability of this item being seen again is < 1/x then don't add
it to the table */
#define ONE_ON_ADD_PROBABILITY (GRPC_CHTTP2_HPACKC_NUM_VALUES >> 1)
-/* The hpack index we encode over the wire. Meaningful to the hpack encoder and
- parser on the remote end as well as HTTP2. *Not* the same as
- HpackEncoderSlotHash, which is only meaningful to the hpack encoder
- implementation (HpackEncoderSlotHash is used for the hashtable implementation
- when mapping from metadata to HpackEncoderIndex. */
-typedef uint32_t HpackEncoderIndex;
-/* Internal-table bookkeeping (*not* the hpack index). */
-typedef uint32_t HpackEncoderSlotHash;
-
-struct SliceRefComparator {
- typedef grpc_slice_refcount* Type;
- static grpc_slice_refcount* Null() { return nullptr; }
- static bool IsNull(const grpc_slice_refcount* sref) {
- return sref == nullptr;
- }
- static bool Equals(const grpc_slice_refcount* s1,
- const grpc_slice_refcount* s2) {
- return s1 == s2;
- }
- static void Ref(grpc_slice_refcount* sref) {
- GPR_DEBUG_ASSERT(sref != nullptr);
- sref->Ref();
- }
- static void Unref(grpc_slice_refcount* sref) {
- GPR_DEBUG_ASSERT(sref != nullptr);
- sref->Unref();
- }
-};
-
-struct MetadataComparator {
- typedef grpc_mdelem Type;
- static const grpc_mdelem Null() { return {0}; }
- static bool IsNull(const grpc_mdelem md) { return md.payload == 0; }
- static bool Equals(const grpc_mdelem md1, const grpc_mdelem md2) {
- return md1.payload == md2.payload;
- }
- static void Ref(grpc_mdelem md) {
- GPR_DEBUG_ASSERT(md.payload != 0);
- GRPC_MDELEM_REF(md);
- }
- static void Unref(grpc_mdelem md) {
- GPR_DEBUG_ASSERT(md.payload != 0);
- GRPC_MDELEM_UNREF(md);
- }
+/* The hpack index we encode over the wire. Meaningful to the hpack encoder and
+ parser on the remote end as well as HTTP2. *Not* the same as
+ HpackEncoderSlotHash, which is only meaningful to the hpack encoder
+ implementation (HpackEncoderSlotHash is used for the hashtable implementation
+ when mapping from metadata to HpackEncoderIndex. */
+typedef uint32_t HpackEncoderIndex;
+/* Internal-table bookkeeping (*not* the hpack index). */
+typedef uint32_t HpackEncoderSlotHash;
+
+struct SliceRefComparator {
+ typedef grpc_slice_refcount* Type;
+ static grpc_slice_refcount* Null() { return nullptr; }
+ static bool IsNull(const grpc_slice_refcount* sref) {
+ return sref == nullptr;
+ }
+ static bool Equals(const grpc_slice_refcount* s1,
+ const grpc_slice_refcount* s2) {
+ return s1 == s2;
+ }
+ static void Ref(grpc_slice_refcount* sref) {
+ GPR_DEBUG_ASSERT(sref != nullptr);
+ sref->Ref();
+ }
+ static void Unref(grpc_slice_refcount* sref) {
+ GPR_DEBUG_ASSERT(sref != nullptr);
+ sref->Unref();
+ }
};
-/* Index table management */
-template <typename Hashtable>
-static HpackEncoderIndex HpackIndex(const Hashtable* hashtable,
- HpackEncoderSlotHash hash_index) {
- return hashtable[hash_index].index;
-}
-
-template <typename ValueType, typename Hashtable>
-static const ValueType& GetEntry(const Hashtable* hashtable,
- HpackEncoderSlotHash hash_index) {
- return hashtable[hash_index].value;
-}
-
-template <typename Cmp, typename Hashtable>
-static bool TableEmptyAt(const Hashtable* hashtable,
- HpackEncoderSlotHash hash_index) {
- return Cmp::Equals(hashtable[hash_index].value, Cmp::Null());
-}
-
-template <typename Cmp, typename Hashtable, typename ValueType>
-static bool Matches(const Hashtable* hashtable, const ValueType& value,
- HpackEncoderSlotHash hash_index) {
- return Cmp::Equals(value, hashtable[hash_index].value);
-}
-
-template <typename Hashtable>
-static void UpdateIndex(Hashtable* hashtable, HpackEncoderSlotHash hash_index,
- HpackEncoderIndex hpack_index) {
- hashtable[hash_index].index = hpack_index;
-}
-
-template <typename Hashtable, typename ValueType>
-static void SetIndex(Hashtable* hashtable, HpackEncoderSlotHash hash_index,
- const ValueType& value, HpackEncoderIndex hpack_index) {
- hashtable[hash_index].value = value;
- UpdateIndex(hashtable, hash_index, hpack_index);
-}
-
-template <typename Cmp, typename Hashtable, typename ValueType>
-static bool GetMatchingIndex(Hashtable* hashtable, const ValueType& value,
- uint32_t value_hash, HpackEncoderIndex* index) {
- const HpackEncoderSlotHash cuckoo_first = HASH_FRAGMENT_2(value_hash);
- if (Matches<Cmp>(hashtable, value, cuckoo_first)) {
- *index = HpackIndex(hashtable, cuckoo_first);
- return true;
- }
-#if GRPC_HPACK_ENCODER_USE_CUCKOO_HASH
- const HpackEncoderSlotHash cuckoo_second = HASH_FRAGMENT_3(value_hash);
-
- if (Matches<Cmp>(hashtable, value, cuckoo_second)) {
- *index = HpackIndex(hashtable, cuckoo_second);
- return true;
- }
-#endif
- return false;
-}
-
-template <typename Cmp, typename Hashtable, typename ValueType>
-static ValueType ReplaceOlderIndex(Hashtable* hashtable, const ValueType& value,
- HpackEncoderSlotHash hash_index_a,
- HpackEncoderSlotHash hash_index_b,
- HpackEncoderIndex new_index) {
- const HpackEncoderIndex hpack_idx_a = hashtable[hash_index_a].index;
- const HpackEncoderIndex hpack_idx_b = hashtable[hash_index_b].index;
- const HpackEncoderSlotHash id =
- hpack_idx_a < hpack_idx_b ? hash_index_a : hash_index_b;
- ValueType old = GetEntry<typename Cmp::Type>(hashtable, id);
- SetIndex(hashtable, id, value, new_index);
- return old;
-}
-
-template <typename Cmp, typename Hashtable, typename ValueType>
-static void UpdateAddOrEvict(Hashtable hashtable, const ValueType& value,
- uint32_t value_hash, HpackEncoderIndex new_index) {
- const HpackEncoderSlotHash cuckoo_first = HASH_FRAGMENT_2(value_hash);
- if (Matches<Cmp>(hashtable, value, cuckoo_first)) {
- UpdateIndex(hashtable, cuckoo_first, new_index);
- return;
- }
- if (TableEmptyAt<Cmp>(hashtable, cuckoo_first)) {
- Cmp::Ref(value);
- SetIndex(hashtable, cuckoo_first, value, new_index);
- return;
- }
-#if GRPC_HPACK_ENCODER_USE_CUCKOO_HASH
- const HpackEncoderSlotHash cuckoo_second = HASH_FRAGMENT_3(value_hash);
- if (Matches<Cmp>(hashtable, value, cuckoo_second)) {
- UpdateIndex(hashtable, cuckoo_second, new_index);
- return;
- }
- Cmp::Ref(value);
- if (TableEmptyAt<Cmp>(hashtable, cuckoo_second)) {
- SetIndex(hashtable, cuckoo_second, value, new_index);
- return;
- }
- Cmp::Unref(ReplaceOlderIndex<Cmp>(hashtable, value, cuckoo_first,
- cuckoo_second, new_index));
-#else
- ValueType old = GetEntry<typename Cmp::Type>(hashtable, cuckoo_first);
- SetIndex(hashtable, cuckoo_first, value, new_index);
- Cmp::Unref(old);
-#endif
-}
-
-/* halve all counts because an element reached max */
-static void HalveFilter(uint8_t /*idx*/, uint32_t* sum, uint8_t* elems) {
- *sum = 0;
- for (int i = 0; i < GRPC_CHTTP2_HPACKC_NUM_VALUES; i++) {
- elems[i] /= 2;
- (*sum) += elems[i];
- }
-}
-
-/* increment a filter count, halve all counts if one element reaches max */
-static void IncrementFilter(uint8_t idx, uint32_t* sum, uint8_t* elems) {
- elems[idx]++;
- if (GPR_LIKELY(elems[idx] < kMaxFilterValue)) {
- (*sum)++;
- } else {
- HalveFilter(idx, sum, elems);
- }
-}
-
-static uint32_t UpdateHashtablePopularity(
- grpc_chttp2_hpack_compressor* hpack_compressor, uint32_t elem_hash) {
- const uint32_t popularity_hash = HASH_FRAGMENT_1(elem_hash);
- IncrementFilter(popularity_hash, &hpack_compressor->filter_elems_sum,
- hpack_compressor->filter_elems);
- return popularity_hash;
-}
-
-static bool CanAddToHashtable(grpc_chttp2_hpack_compressor* hpack_compressor,
- uint32_t popularity_hash) {
- const bool can_add =
- hpack_compressor->filter_elems[popularity_hash] >=
- hpack_compressor->filter_elems_sum / ONE_ON_ADD_PROBABILITY;
- return can_add;
-}
-} /* namespace */
-
+struct MetadataComparator {
+ typedef grpc_mdelem Type;
+ static const grpc_mdelem Null() { return {0}; }
+ static bool IsNull(const grpc_mdelem md) { return md.payload == 0; }
+ static bool Equals(const grpc_mdelem md1, const grpc_mdelem md2) {
+ return md1.payload == md2.payload;
+ }
+ static void Ref(grpc_mdelem md) {
+ GPR_DEBUG_ASSERT(md.payload != 0);
+ GRPC_MDELEM_REF(md);
+ }
+ static void Unref(grpc_mdelem md) {
+ GPR_DEBUG_ASSERT(md.payload != 0);
+ GRPC_MDELEM_UNREF(md);
+ }
+};
+
+/* Index table management */
+template <typename Hashtable>
+static HpackEncoderIndex HpackIndex(const Hashtable* hashtable,
+ HpackEncoderSlotHash hash_index) {
+ return hashtable[hash_index].index;
+}
+
+template <typename ValueType, typename Hashtable>
+static const ValueType& GetEntry(const Hashtable* hashtable,
+ HpackEncoderSlotHash hash_index) {
+ return hashtable[hash_index].value;
+}
+
+template <typename Cmp, typename Hashtable>
+static bool TableEmptyAt(const Hashtable* hashtable,
+ HpackEncoderSlotHash hash_index) {
+ return Cmp::Equals(hashtable[hash_index].value, Cmp::Null());
+}
+
+template <typename Cmp, typename Hashtable, typename ValueType>
+static bool Matches(const Hashtable* hashtable, const ValueType& value,
+ HpackEncoderSlotHash hash_index) {
+ return Cmp::Equals(value, hashtable[hash_index].value);
+}
+
+template <typename Hashtable>
+static void UpdateIndex(Hashtable* hashtable, HpackEncoderSlotHash hash_index,
+ HpackEncoderIndex hpack_index) {
+ hashtable[hash_index].index = hpack_index;
+}
+
+template <typename Hashtable, typename ValueType>
+static void SetIndex(Hashtable* hashtable, HpackEncoderSlotHash hash_index,
+ const ValueType& value, HpackEncoderIndex hpack_index) {
+ hashtable[hash_index].value = value;
+ UpdateIndex(hashtable, hash_index, hpack_index);
+}
+
+template <typename Cmp, typename Hashtable, typename ValueType>
+static bool GetMatchingIndex(Hashtable* hashtable, const ValueType& value,
+ uint32_t value_hash, HpackEncoderIndex* index) {
+ const HpackEncoderSlotHash cuckoo_first = HASH_FRAGMENT_2(value_hash);
+ if (Matches<Cmp>(hashtable, value, cuckoo_first)) {
+ *index = HpackIndex(hashtable, cuckoo_first);
+ return true;
+ }
+#if GRPC_HPACK_ENCODER_USE_CUCKOO_HASH
+ const HpackEncoderSlotHash cuckoo_second = HASH_FRAGMENT_3(value_hash);
+
+ if (Matches<Cmp>(hashtable, value, cuckoo_second)) {
+ *index = HpackIndex(hashtable, cuckoo_second);
+ return true;
+ }
+#endif
+ return false;
+}
+
+template <typename Cmp, typename Hashtable, typename ValueType>
+static ValueType ReplaceOlderIndex(Hashtable* hashtable, const ValueType& value,
+ HpackEncoderSlotHash hash_index_a,
+ HpackEncoderSlotHash hash_index_b,
+ HpackEncoderIndex new_index) {
+ const HpackEncoderIndex hpack_idx_a = hashtable[hash_index_a].index;
+ const HpackEncoderIndex hpack_idx_b = hashtable[hash_index_b].index;
+ const HpackEncoderSlotHash id =
+ hpack_idx_a < hpack_idx_b ? hash_index_a : hash_index_b;
+ ValueType old = GetEntry<typename Cmp::Type>(hashtable, id);
+ SetIndex(hashtable, id, value, new_index);
+ return old;
+}
+
+template <typename Cmp, typename Hashtable, typename ValueType>
+static void UpdateAddOrEvict(Hashtable hashtable, const ValueType& value,
+ uint32_t value_hash, HpackEncoderIndex new_index) {
+ const HpackEncoderSlotHash cuckoo_first = HASH_FRAGMENT_2(value_hash);
+ if (Matches<Cmp>(hashtable, value, cuckoo_first)) {
+ UpdateIndex(hashtable, cuckoo_first, new_index);
+ return;
+ }
+ if (TableEmptyAt<Cmp>(hashtable, cuckoo_first)) {
+ Cmp::Ref(value);
+ SetIndex(hashtable, cuckoo_first, value, new_index);
+ return;
+ }
+#if GRPC_HPACK_ENCODER_USE_CUCKOO_HASH
+ const HpackEncoderSlotHash cuckoo_second = HASH_FRAGMENT_3(value_hash);
+ if (Matches<Cmp>(hashtable, value, cuckoo_second)) {
+ UpdateIndex(hashtable, cuckoo_second, new_index);
+ return;
+ }
+ Cmp::Ref(value);
+ if (TableEmptyAt<Cmp>(hashtable, cuckoo_second)) {
+ SetIndex(hashtable, cuckoo_second, value, new_index);
+ return;
+ }
+ Cmp::Unref(ReplaceOlderIndex<Cmp>(hashtable, value, cuckoo_first,
+ cuckoo_second, new_index));
+#else
+ ValueType old = GetEntry<typename Cmp::Type>(hashtable, cuckoo_first);
+ SetIndex(hashtable, cuckoo_first, value, new_index);
+ Cmp::Unref(old);
+#endif
+}
+
+/* halve all counts because an element reached max */
+static void HalveFilter(uint8_t /*idx*/, uint32_t* sum, uint8_t* elems) {
+ *sum = 0;
+ for (int i = 0; i < GRPC_CHTTP2_HPACKC_NUM_VALUES; i++) {
+ elems[i] /= 2;
+ (*sum) += elems[i];
+ }
+}
+
+/* increment a filter count, halve all counts if one element reaches max */
+static void IncrementFilter(uint8_t idx, uint32_t* sum, uint8_t* elems) {
+ elems[idx]++;
+ if (GPR_LIKELY(elems[idx] < kMaxFilterValue)) {
+ (*sum)++;
+ } else {
+ HalveFilter(idx, sum, elems);
+ }
+}
+
+static uint32_t UpdateHashtablePopularity(
+ grpc_chttp2_hpack_compressor* hpack_compressor, uint32_t elem_hash) {
+ const uint32_t popularity_hash = HASH_FRAGMENT_1(elem_hash);
+ IncrementFilter(popularity_hash, &hpack_compressor->filter_elems_sum,
+ hpack_compressor->filter_elems);
+ return popularity_hash;
+}
+
+static bool CanAddToHashtable(grpc_chttp2_hpack_compressor* hpack_compressor,
+ uint32_t popularity_hash) {
+ const bool can_add =
+ hpack_compressor->filter_elems[popularity_hash] >=
+ hpack_compressor->filter_elems_sum / ONE_ON_ADD_PROBABILITY;
+ return can_add;
+}
+} /* namespace */
+
struct framer_state {
int is_first_frame;
/* number of bytes in 'output' when we started the frame - used to calculate
@@ -266,10 +266,10 @@ struct framer_state {
size_t output_length_at_start_of_frame;
/* index (in output) of the header for the current frame */
size_t header_idx;
-#ifndef NDEBUG
+#ifndef NDEBUG
/* have we seen a regular (non-colon-prefixed) header yet? */
uint8_t seen_regular_header;
-#endif
+#endif
/* output stream id */
uint32_t stream_id;
grpc_slice_buffer* output;
@@ -279,23 +279,23 @@ struct framer_state {
bool use_true_binary_metadata;
bool is_end_of_stream;
};
-/* fills p (which is expected to be kDataFrameHeaderSize bytes long)
- * with a data frame header */
+/* fills p (which is expected to be kDataFrameHeaderSize bytes long)
+ * with a data frame header */
static void fill_header(uint8_t* p, uint8_t type, uint32_t id, size_t len,
uint8_t flags) {
- /* len is the current frame size (i.e. for the frame we're finishing).
- We finish a frame if:
- 1) We called ensure_space(), (i.e. add_tiny_header_data()) and adding
- 'need_bytes' to the frame would cause us to exceed st->max_frame_size.
- 2) We called add_header_data, and adding the slice would cause us to exceed
- st->max_frame_size.
- 3) We're done encoding the header.
-
- Thus, len is always <= st->max_frame_size.
- st->max_frame_size is derived from GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE,
- which has a max allowable value of 16777215 (see chttp_transport.cc).
- Thus, the following assert can be a debug assert. */
- GPR_DEBUG_ASSERT(len < 16777316);
+ /* len is the current frame size (i.e. for the frame we're finishing).
+ We finish a frame if:
+ 1) We called ensure_space(), (i.e. add_tiny_header_data()) and adding
+ 'need_bytes' to the frame would cause us to exceed st->max_frame_size.
+ 2) We called add_header_data, and adding the slice would cause us to exceed
+ st->max_frame_size.
+ 3) We're done encoding the header.
+
+ Thus, len is always <= st->max_frame_size.
+ st->max_frame_size is derived from GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE,
+ which has a max allowable value of 16777215 (see chttp_transport.cc).
+ Thus, the following assert can be a debug assert. */
+ GPR_DEBUG_ASSERT(len < 16777316);
*p++ = static_cast<uint8_t>(len >> 16);
*p++ = static_cast<uint8_t>(len >> 8);
*p++ = static_cast<uint8_t>(len);
@@ -307,13 +307,13 @@ static void fill_header(uint8_t* p, uint8_t type, uint32_t id, size_t len,
*p++ = static_cast<uint8_t>(id);
}
-static size_t current_frame_size(framer_state* st) {
- const size_t frame_size =
- st->output->length - st->output_length_at_start_of_frame;
- GPR_DEBUG_ASSERT(frame_size <= st->max_frame_size);
- return frame_size;
-}
-
+static size_t current_frame_size(framer_state* st) {
+ const size_t frame_size =
+ st->output->length - st->output_length_at_start_of_frame;
+ GPR_DEBUG_ASSERT(frame_size <= st->max_frame_size);
+ return frame_size;
+}
+
/* finish a frame - fill in the previously reserved header */
static void finish_frame(framer_state* st, int is_header_boundary) {
uint8_t type = 0xff;
@@ -338,17 +338,17 @@ static void finish_frame(framer_state* st, int is_header_boundary) {
is_header_boundary ? GRPC_CHTTP2_DATA_FLAG_END_HEADERS : 0);
fill_header(GRPC_SLICE_START_PTR(st->output->slices[st->header_idx]), type,
st->stream_id, current_frame_size(st), flags);
- st->stats->framing_bytes += kDataFrameHeaderSize;
+ st->stats->framing_bytes += kDataFrameHeaderSize;
st->is_first_frame = 0;
}
/* begin a new frame: reserve off header space, remember how many bytes we'd
output before beginning */
static void begin_frame(framer_state* st) {
- grpc_slice reserved;
- reserved.refcount = nullptr;
- reserved.data.inlined.length = kDataFrameHeaderSize;
- st->header_idx = grpc_slice_buffer_add_indexed(st->output, reserved);
+ grpc_slice reserved;
+ reserved.refcount = nullptr;
+ reserved.data.inlined.length = kDataFrameHeaderSize;
+ st->header_idx = grpc_slice_buffer_add_indexed(st->output, reserved);
st->output_length_at_start_of_frame = st->output->length;
}
@@ -356,7 +356,7 @@ static void begin_frame(framer_state* st) {
space to add at least about_to_add bytes -- finishes the current frame if
needed */
static void ensure_space(framer_state* st, size_t need_bytes) {
- if (GPR_LIKELY(current_frame_size(st) + need_bytes <= st->max_frame_size)) {
+ if (GPR_LIKELY(current_frame_size(st) + need_bytes <= st->max_frame_size)) {
return;
}
finish_frame(st, 0);
@@ -367,7 +367,7 @@ static void add_header_data(framer_state* st, grpc_slice slice) {
size_t len = GRPC_SLICE_LENGTH(slice);
size_t remaining;
if (len == 0) return;
- remaining = st->max_frame_size - current_frame_size(st);
+ remaining = st->max_frame_size - current_frame_size(st);
if (len <= remaining) {
st->stats->header_bytes += len;
grpc_slice_buffer_add(st->output, slice);
@@ -404,9 +404,9 @@ static void evict_entry(grpc_chttp2_hpack_compressor* c) {
static uint32_t prepare_space_for_new_elem(grpc_chttp2_hpack_compressor* c,
size_t elem_size) {
uint32_t new_index = c->tail_remote_index + c->table_elems + 1;
- GPR_DEBUG_ASSERT(elem_size < 65536);
+ GPR_DEBUG_ASSERT(elem_size < 65536);
- // TODO(arjunroy): Re-examine semantics
+ // TODO(arjunroy): Re-examine semantics
if (elem_size > c->max_table_size) {
while (c->table_size > 0) {
evict_entry(c);
@@ -431,170 +431,170 @@ static uint32_t prepare_space_for_new_elem(grpc_chttp2_hpack_compressor* c,
// Add a key to the dynamic table. Both key and value will be added to table at
// the decoder.
-static void AddKeyWithIndex(grpc_chttp2_hpack_compressor* c,
- grpc_slice_refcount* key_ref, uint32_t new_index,
- uint32_t key_hash) {
- UpdateAddOrEvict<SliceRefComparator>(c->key_table.entries, key_ref, key_hash,
- new_index);
+static void AddKeyWithIndex(grpc_chttp2_hpack_compressor* c,
+ grpc_slice_refcount* key_ref, uint32_t new_index,
+ uint32_t key_hash) {
+ UpdateAddOrEvict<SliceRefComparator>(c->key_table.entries, key_ref, key_hash,
+ new_index);
}
/* add an element to the decoder table */
-static void AddElemWithIndex(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
- uint32_t new_index, uint32_t elem_hash,
- uint32_t key_hash) {
- GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(elem));
- UpdateAddOrEvict<MetadataComparator>(c->elem_table.entries, elem, elem_hash,
- new_index);
- AddKeyWithIndex(c, GRPC_MDKEY(elem).refcount, new_index, key_hash);
+static void AddElemWithIndex(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
+ uint32_t new_index, uint32_t elem_hash,
+ uint32_t key_hash) {
+ GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(elem));
+ UpdateAddOrEvict<MetadataComparator>(c->elem_table.entries, elem, elem_hash,
+ new_index);
+ AddKeyWithIndex(c, GRPC_MDKEY(elem).refcount, new_index, key_hash);
}
static void add_elem(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
- size_t elem_size, uint32_t elem_hash, uint32_t key_hash) {
+ size_t elem_size, uint32_t elem_hash, uint32_t key_hash) {
uint32_t new_index = prepare_space_for_new_elem(c, elem_size);
- if (new_index != 0) {
- AddElemWithIndex(c, elem, new_index, elem_hash, key_hash);
- }
+ if (new_index != 0) {
+ AddElemWithIndex(c, elem, new_index, elem_hash, key_hash);
+ }
}
static void add_key(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
- size_t elem_size, uint32_t key_hash) {
+ size_t elem_size, uint32_t key_hash) {
uint32_t new_index = prepare_space_for_new_elem(c, elem_size);
- if (new_index != 0) {
- AddKeyWithIndex(c, GRPC_MDKEY(elem).refcount, new_index, key_hash);
- }
+ if (new_index != 0) {
+ AddKeyWithIndex(c, GRPC_MDKEY(elem).refcount, new_index, key_hash);
+ }
}
-static void emit_indexed(grpc_chttp2_hpack_compressor* /*c*/,
- uint32_t elem_index, framer_state* st) {
+static void emit_indexed(grpc_chttp2_hpack_compressor* /*c*/,
+ uint32_t elem_index, framer_state* st) {
GRPC_STATS_INC_HPACK_SEND_INDEXED();
uint32_t len = GRPC_CHTTP2_VARINT_LENGTH(elem_index, 1);
GRPC_CHTTP2_WRITE_VARINT(elem_index, 1, 0x80, add_tiny_header_data(st, len),
len);
}
-struct wire_value {
- wire_value(uint8_t huffman_prefix, bool insert_null_before_wire_value,
- const grpc_slice& slice)
- : data(slice),
- huffman_prefix(huffman_prefix),
- insert_null_before_wire_value(insert_null_before_wire_value),
- length(GRPC_SLICE_LENGTH(slice) +
- (insert_null_before_wire_value ? 1 : 0)) {}
- // While wire_value is const from the POV of hpack encoder code, actually
- // adding it to a slice buffer will possibly split the slice.
- const grpc_slice data;
- const uint8_t huffman_prefix;
- const bool insert_null_before_wire_value;
- const size_t length;
-};
-
-template <bool mdkey_definitely_interned>
+struct wire_value {
+ wire_value(uint8_t huffman_prefix, bool insert_null_before_wire_value,
+ const grpc_slice& slice)
+ : data(slice),
+ huffman_prefix(huffman_prefix),
+ insert_null_before_wire_value(insert_null_before_wire_value),
+ length(GRPC_SLICE_LENGTH(slice) +
+ (insert_null_before_wire_value ? 1 : 0)) {}
+ // While wire_value is const from the POV of hpack encoder code, actually
+ // adding it to a slice buffer will possibly split the slice.
+ const grpc_slice data;
+ const uint8_t huffman_prefix;
+ const bool insert_null_before_wire_value;
+ const size_t length;
+};
+
+template <bool mdkey_definitely_interned>
static wire_value get_wire_value(grpc_mdelem elem, bool true_binary_enabled) {
- const bool is_bin_hdr =
- mdkey_definitely_interned
- ? grpc_is_refcounted_slice_binary_header(GRPC_MDKEY(elem))
- : grpc_is_binary_header_internal(GRPC_MDKEY(elem));
- const grpc_slice& value = GRPC_MDVALUE(elem);
- if (is_bin_hdr) {
+ const bool is_bin_hdr =
+ mdkey_definitely_interned
+ ? grpc_is_refcounted_slice_binary_header(GRPC_MDKEY(elem))
+ : grpc_is_binary_header_internal(GRPC_MDKEY(elem));
+ const grpc_slice& value = GRPC_MDVALUE(elem);
+ if (is_bin_hdr) {
if (true_binary_enabled) {
GRPC_STATS_INC_HPACK_SEND_BINARY();
- return wire_value(0x00, true, grpc_slice_ref_internal(value));
+ return wire_value(0x00, true, grpc_slice_ref_internal(value));
} else {
GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64();
- return wire_value(0x80, false,
- grpc_chttp2_base64_encode_and_huffman_compress(value));
+ return wire_value(0x80, false,
+ grpc_chttp2_base64_encode_and_huffman_compress(value));
}
} else {
/* TODO(ctiller): opportunistically compress non-binary headers */
GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED();
- return wire_value(0x00, false, grpc_slice_ref_internal(value));
- }
-}
-
-static uint32_t wire_value_length(const wire_value& v) {
- GPR_DEBUG_ASSERT(v.length <= UINT32_MAX);
- return static_cast<uint32_t>(v.length);
-}
-
-namespace {
-enum class EmitLitHdrType { INC_IDX, NO_IDX };
-
-enum class EmitLitHdrVType { INC_IDX_V, NO_IDX_V };
-} // namespace
-
-template <EmitLitHdrType type>
-static void emit_lithdr(grpc_chttp2_hpack_compressor* /*c*/, uint32_t key_index,
- grpc_mdelem elem, framer_state* st) {
- switch (type) {
- case EmitLitHdrType::INC_IDX:
- GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX();
- break;
- case EmitLitHdrType::NO_IDX:
- GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX();
- break;
- }
- const uint32_t len_pfx = type == EmitLitHdrType::INC_IDX
- ? GRPC_CHTTP2_VARINT_LENGTH(key_index, 2)
- : GRPC_CHTTP2_VARINT_LENGTH(key_index, 4);
- const wire_value value =
- get_wire_value<true>(elem, st->use_true_binary_metadata);
- const uint32_t len_val = wire_value_length(value);
- const uint32_t len_val_len = GRPC_CHTTP2_VARINT_LENGTH(len_val, 1);
- GPR_DEBUG_ASSERT(len_pfx + len_val_len < GRPC_SLICE_INLINED_SIZE);
- uint8_t* data = add_tiny_header_data(
- st,
- len_pfx + len_val_len + (value.insert_null_before_wire_value ? 1 : 0));
- switch (type) {
- case EmitLitHdrType::INC_IDX:
- GRPC_CHTTP2_WRITE_VARINT(key_index, 2, 0x40, data, len_pfx);
- break;
- case EmitLitHdrType::NO_IDX:
- GRPC_CHTTP2_WRITE_VARINT(key_index, 4, 0x00, data, len_pfx);
- break;
- }
- GRPC_CHTTP2_WRITE_VARINT(len_val, 1, value.huffman_prefix, &data[len_pfx],
- len_val_len);
- if (value.insert_null_before_wire_value) {
- data[len_pfx + len_val_len] = 0;
- }
- add_header_data(st, value.data);
-}
-
-template <EmitLitHdrVType type>
-static void emit_lithdr_v(grpc_chttp2_hpack_compressor* /*c*/, grpc_mdelem elem,
- framer_state* st) {
- switch (type) {
- case EmitLitHdrVType::INC_IDX_V:
- GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V();
- break;
- case EmitLitHdrVType::NO_IDX_V:
- GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V();
- break;
- }
+ return wire_value(0x00, false, grpc_slice_ref_internal(value));
+ }
+}
+
+static uint32_t wire_value_length(const wire_value& v) {
+ GPR_DEBUG_ASSERT(v.length <= UINT32_MAX);
+ return static_cast<uint32_t>(v.length);
+}
+
+namespace {
+enum class EmitLitHdrType { INC_IDX, NO_IDX };
+
+enum class EmitLitHdrVType { INC_IDX_V, NO_IDX_V };
+} // namespace
+
+template <EmitLitHdrType type>
+static void emit_lithdr(grpc_chttp2_hpack_compressor* /*c*/, uint32_t key_index,
+ grpc_mdelem elem, framer_state* st) {
+ switch (type) {
+ case EmitLitHdrType::INC_IDX:
+ GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX();
+ break;
+ case EmitLitHdrType::NO_IDX:
+ GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX();
+ break;
+ }
+ const uint32_t len_pfx = type == EmitLitHdrType::INC_IDX
+ ? GRPC_CHTTP2_VARINT_LENGTH(key_index, 2)
+ : GRPC_CHTTP2_VARINT_LENGTH(key_index, 4);
+ const wire_value value =
+ get_wire_value<true>(elem, st->use_true_binary_metadata);
+ const uint32_t len_val = wire_value_length(value);
+ const uint32_t len_val_len = GRPC_CHTTP2_VARINT_LENGTH(len_val, 1);
+ GPR_DEBUG_ASSERT(len_pfx + len_val_len < GRPC_SLICE_INLINED_SIZE);
+ uint8_t* data = add_tiny_header_data(
+ st,
+ len_pfx + len_val_len + (value.insert_null_before_wire_value ? 1 : 0));
+ switch (type) {
+ case EmitLitHdrType::INC_IDX:
+ GRPC_CHTTP2_WRITE_VARINT(key_index, 2, 0x40, data, len_pfx);
+ break;
+ case EmitLitHdrType::NO_IDX:
+ GRPC_CHTTP2_WRITE_VARINT(key_index, 4, 0x00, data, len_pfx);
+ break;
+ }
+ GRPC_CHTTP2_WRITE_VARINT(len_val, 1, value.huffman_prefix, &data[len_pfx],
+ len_val_len);
+ if (value.insert_null_before_wire_value) {
+ data[len_pfx + len_val_len] = 0;
+ }
+ add_header_data(st, value.data);
+}
+
+template <EmitLitHdrVType type>
+static void emit_lithdr_v(grpc_chttp2_hpack_compressor* /*c*/, grpc_mdelem elem,
+ framer_state* st) {
+ switch (type) {
+ case EmitLitHdrVType::INC_IDX_V:
+ GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V();
+ break;
+ case EmitLitHdrVType::NO_IDX_V:
+ GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V();
+ break;
+ }
GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED();
- const uint32_t len_key =
- static_cast<uint32_t>(GRPC_SLICE_LENGTH(GRPC_MDKEY(elem)));
- const wire_value value =
- type == EmitLitHdrVType::INC_IDX_V
- ? get_wire_value<true>(elem, st->use_true_binary_metadata)
- : get_wire_value<false>(elem, st->use_true_binary_metadata);
- const uint32_t len_val = wire_value_length(value);
- const uint32_t len_key_len = GRPC_CHTTP2_VARINT_LENGTH(len_key, 1);
- const uint32_t len_val_len = GRPC_CHTTP2_VARINT_LENGTH(len_val, 1);
- GPR_DEBUG_ASSERT(len_key <= UINT32_MAX);
- GPR_DEBUG_ASSERT(1 + len_key_len < GRPC_SLICE_INLINED_SIZE);
- uint8_t* key_buf = add_tiny_header_data(st, 1 + len_key_len);
- key_buf[0] = type == EmitLitHdrVType::INC_IDX_V ? 0x40 : 0x00;
- GRPC_CHTTP2_WRITE_VARINT(len_key, 1, 0x00, &key_buf[1], len_key_len);
+ const uint32_t len_key =
+ static_cast<uint32_t>(GRPC_SLICE_LENGTH(GRPC_MDKEY(elem)));
+ const wire_value value =
+ type == EmitLitHdrVType::INC_IDX_V
+ ? get_wire_value<true>(elem, st->use_true_binary_metadata)
+ : get_wire_value<false>(elem, st->use_true_binary_metadata);
+ const uint32_t len_val = wire_value_length(value);
+ const uint32_t len_key_len = GRPC_CHTTP2_VARINT_LENGTH(len_key, 1);
+ const uint32_t len_val_len = GRPC_CHTTP2_VARINT_LENGTH(len_val, 1);
+ GPR_DEBUG_ASSERT(len_key <= UINT32_MAX);
+ GPR_DEBUG_ASSERT(1 + len_key_len < GRPC_SLICE_INLINED_SIZE);
+ uint8_t* key_buf = add_tiny_header_data(st, 1 + len_key_len);
+ key_buf[0] = type == EmitLitHdrVType::INC_IDX_V ? 0x40 : 0x00;
+ GRPC_CHTTP2_WRITE_VARINT(len_key, 1, 0x00, &key_buf[1], len_key_len);
add_header_data(st, grpc_slice_ref_internal(GRPC_MDKEY(elem)));
- uint8_t* value_buf = add_tiny_header_data(
- st, len_val_len + (value.insert_null_before_wire_value ? 1 : 0));
- GRPC_CHTTP2_WRITE_VARINT(len_val, 1, value.huffman_prefix, value_buf,
- len_val_len);
- if (value.insert_null_before_wire_value) {
- value_buf[len_val_len] = 0;
- }
- add_header_data(st, value.data);
+ uint8_t* value_buf = add_tiny_header_data(
+ st, len_val_len + (value.insert_null_before_wire_value ? 1 : 0));
+ GRPC_CHTTP2_WRITE_VARINT(len_val, 1, value.huffman_prefix, value_buf,
+ len_val_len);
+ if (value.insert_null_before_wire_value) {
+ value_buf[len_val_len] = 0;
+ }
+ add_header_data(st, value.data);
}
static void emit_advertise_table_size_change(grpc_chttp2_hpack_compressor* c,
@@ -605,139 +605,139 @@ static void emit_advertise_table_size_change(grpc_chttp2_hpack_compressor* c,
c->advertise_table_size_change = 0;
}
-static void GPR_ATTRIBUTE_NOINLINE hpack_enc_log(grpc_mdelem elem) {
- char* k = grpc_slice_to_c_string(GRPC_MDKEY(elem));
- char* v = nullptr;
- if (grpc_is_binary_header_internal(GRPC_MDKEY(elem))) {
- v = grpc_dump_slice(GRPC_MDVALUE(elem), GPR_DUMP_HEX);
- } else {
- v = grpc_slice_to_c_string(GRPC_MDVALUE(elem));
- }
- gpr_log(
- GPR_INFO,
- "Encode: '%s: %s', elem_interned=%d [%d], k_interned=%d, v_interned=%d",
- k, v, GRPC_MDELEM_IS_INTERNED(elem), GRPC_MDELEM_STORAGE(elem),
- grpc_slice_is_interned(GRPC_MDKEY(elem)),
- grpc_slice_is_interned(GRPC_MDVALUE(elem)));
- gpr_free(k);
- gpr_free(v);
-}
-
+static void GPR_ATTRIBUTE_NOINLINE hpack_enc_log(grpc_mdelem elem) {
+ char* k = grpc_slice_to_c_string(GRPC_MDKEY(elem));
+ char* v = nullptr;
+ if (grpc_is_binary_header_internal(GRPC_MDKEY(elem))) {
+ v = grpc_dump_slice(GRPC_MDVALUE(elem), GPR_DUMP_HEX);
+ } else {
+ v = grpc_slice_to_c_string(GRPC_MDVALUE(elem));
+ }
+ gpr_log(
+ GPR_INFO,
+ "Encode: '%s: %s', elem_interned=%d [%d], k_interned=%d, v_interned=%d",
+ k, v, GRPC_MDELEM_IS_INTERNED(elem), GRPC_MDELEM_STORAGE(elem),
+ grpc_slice_is_interned(GRPC_MDKEY(elem)),
+ grpc_slice_is_interned(GRPC_MDVALUE(elem)));
+ gpr_free(k);
+ gpr_free(v);
+}
+
static uint32_t dynidx(grpc_chttp2_hpack_compressor* c, uint32_t elem_index) {
return 1 + GRPC_CHTTP2_LAST_STATIC_ENTRY + c->tail_remote_index +
c->table_elems - elem_index;
}
-struct EmitIndexedStatus {
- EmitIndexedStatus() = default;
- EmitIndexedStatus(uint32_t elem_hash, bool emitted, bool can_add)
- : elem_hash(elem_hash), emitted(emitted), can_add(can_add) {}
- const uint32_t elem_hash = 0;
- const bool emitted = false;
- const bool can_add = false;
-};
-
-static EmitIndexedStatus maybe_emit_indexed(grpc_chttp2_hpack_compressor* c,
- grpc_mdelem elem,
- framer_state* st) {
- const uint32_t elem_hash =
- GRPC_MDELEM_STORAGE(elem) == GRPC_MDELEM_STORAGE_INTERNED
- ? reinterpret_cast<grpc_core::InternedMetadata*>(
- GRPC_MDELEM_DATA(elem))
- ->hash()
- : reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(elem))
- ->hash();
- /* Update filter to see if we can perhaps add this elem. */
- const uint32_t popularity_hash = UpdateHashtablePopularity(c, elem_hash);
- /* is this elem currently in the decoders table? */
- HpackEncoderIndex indices_key;
- if (GetMatchingIndex<MetadataComparator>(c->elem_table.entries, elem,
- elem_hash, &indices_key) &&
- indices_key > c->tail_remote_index) {
- emit_indexed(c, dynidx(c, indices_key), st);
- return EmitIndexedStatus(elem_hash, true, false);
- }
- /* Didn't hit either cuckoo index, so no emit. */
- return EmitIndexedStatus(elem_hash, false,
- CanAddToHashtable(c, popularity_hash));
-}
-
-static void emit_maybe_add(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
- framer_state* st, uint32_t indices_key,
- bool should_add_elem, size_t decoder_space_usage,
- uint32_t elem_hash, uint32_t key_hash) {
- if (should_add_elem) {
- emit_lithdr<EmitLitHdrType::INC_IDX>(c, dynidx(c, indices_key), elem, st);
- add_elem(c, elem, decoder_space_usage, elem_hash, key_hash);
- } else {
- emit_lithdr<EmitLitHdrType::NO_IDX>(c, dynidx(c, indices_key), elem, st);
- }
-}
-
+struct EmitIndexedStatus {
+ EmitIndexedStatus() = default;
+ EmitIndexedStatus(uint32_t elem_hash, bool emitted, bool can_add)
+ : elem_hash(elem_hash), emitted(emitted), can_add(can_add) {}
+ const uint32_t elem_hash = 0;
+ const bool emitted = false;
+ const bool can_add = false;
+};
+
+static EmitIndexedStatus maybe_emit_indexed(grpc_chttp2_hpack_compressor* c,
+ grpc_mdelem elem,
+ framer_state* st) {
+ const uint32_t elem_hash =
+ GRPC_MDELEM_STORAGE(elem) == GRPC_MDELEM_STORAGE_INTERNED
+ ? reinterpret_cast<grpc_core::InternedMetadata*>(
+ GRPC_MDELEM_DATA(elem))
+ ->hash()
+ : reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(elem))
+ ->hash();
+ /* Update filter to see if we can perhaps add this elem. */
+ const uint32_t popularity_hash = UpdateHashtablePopularity(c, elem_hash);
+ /* is this elem currently in the decoders table? */
+ HpackEncoderIndex indices_key;
+ if (GetMatchingIndex<MetadataComparator>(c->elem_table.entries, elem,
+ elem_hash, &indices_key) &&
+ indices_key > c->tail_remote_index) {
+ emit_indexed(c, dynidx(c, indices_key), st);
+ return EmitIndexedStatus(elem_hash, true, false);
+ }
+ /* Didn't hit either cuckoo index, so no emit. */
+ return EmitIndexedStatus(elem_hash, false,
+ CanAddToHashtable(c, popularity_hash));
+}
+
+static void emit_maybe_add(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
+ framer_state* st, uint32_t indices_key,
+ bool should_add_elem, size_t decoder_space_usage,
+ uint32_t elem_hash, uint32_t key_hash) {
+ if (should_add_elem) {
+ emit_lithdr<EmitLitHdrType::INC_IDX>(c, dynidx(c, indices_key), elem, st);
+ add_elem(c, elem, decoder_space_usage, elem_hash, key_hash);
+ } else {
+ emit_lithdr<EmitLitHdrType::NO_IDX>(c, dynidx(c, indices_key), elem, st);
+ }
+}
+
/* encode an mdelem */
static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
framer_state* st) {
- const grpc_slice& elem_key = GRPC_MDKEY(elem);
- /* User-provided key len validated in grpc_validate_header_key_is_legal(). */
- GPR_DEBUG_ASSERT(GRPC_SLICE_LENGTH(elem_key) > 0);
- /* Header ordering: all reserved headers (prefixed with ':') must precede
- * regular headers. This can be a debug assert, since:
- * 1) User cannot give us ':' headers (grpc_validate_header_key_is_legal()).
- * 2) grpc filters/core should be checked during debug builds. */
-#ifndef NDEBUG
- if (GRPC_SLICE_START_PTR(elem_key)[0] != ':') { /* regular header */
+ const grpc_slice& elem_key = GRPC_MDKEY(elem);
+ /* User-provided key len validated in grpc_validate_header_key_is_legal(). */
+ GPR_DEBUG_ASSERT(GRPC_SLICE_LENGTH(elem_key) > 0);
+ /* Header ordering: all reserved headers (prefixed with ':') must precede
+ * regular headers. This can be a debug assert, since:
+ * 1) User cannot give us ':' headers (grpc_validate_header_key_is_legal()).
+ * 2) grpc filters/core should be checked during debug builds. */
+#ifndef NDEBUG
+ if (GRPC_SLICE_START_PTR(elem_key)[0] != ':') { /* regular header */
st->seen_regular_header = 1;
} else {
- GPR_DEBUG_ASSERT(
+ GPR_DEBUG_ASSERT(
st->seen_regular_header == 0 &&
"Reserved header (colon-prefixed) happening after regular ones.");
}
-#endif
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
- hpack_enc_log(elem);
+#endif
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ hpack_enc_log(elem);
}
- const bool elem_interned = GRPC_MDELEM_IS_INTERNED(elem);
- const bool key_interned = elem_interned || grpc_slice_is_interned(elem_key);
- /* Key is not interned, emit literals. */
+ const bool elem_interned = GRPC_MDELEM_IS_INTERNED(elem);
+ const bool key_interned = elem_interned || grpc_slice_is_interned(elem_key);
+ /* Key is not interned, emit literals. */
if (!key_interned) {
- emit_lithdr_v<EmitLitHdrVType::NO_IDX_V>(c, elem, st);
+ emit_lithdr_v<EmitLitHdrVType::NO_IDX_V>(c, elem, st);
return;
}
- /* Interned metadata => maybe already indexed. */
- const EmitIndexedStatus ret =
- elem_interned ? maybe_emit_indexed(c, elem, st) : EmitIndexedStatus();
- if (ret.emitted) {
- return;
+ /* Interned metadata => maybe already indexed. */
+ const EmitIndexedStatus ret =
+ elem_interned ? maybe_emit_indexed(c, elem, st) : EmitIndexedStatus();
+ if (ret.emitted) {
+ return;
}
/* should this elem be in the table? */
const size_t decoder_space_usage =
grpc_chttp2_get_size_in_hpack_table(elem, st->use_true_binary_metadata);
- const bool decoder_space_available =
- decoder_space_usage < kMaxDecoderSpaceUsage;
- const bool should_add_elem =
- elem_interned && decoder_space_available && ret.can_add;
- const uint32_t elem_hash = ret.elem_hash;
+ const bool decoder_space_available =
+ decoder_space_usage < kMaxDecoderSpaceUsage;
+ const bool should_add_elem =
+ elem_interned && decoder_space_available && ret.can_add;
+ const uint32_t elem_hash = ret.elem_hash;
/* no hits for the elem... maybe there's a key? */
- const uint32_t key_hash = elem_key.refcount->Hash(elem_key);
- HpackEncoderIndex indices_key;
- if (GetMatchingIndex<SliceRefComparator>(
- c->key_table.entries, elem_key.refcount, key_hash, &indices_key) &&
+ const uint32_t key_hash = elem_key.refcount->Hash(elem_key);
+ HpackEncoderIndex indices_key;
+ if (GetMatchingIndex<SliceRefComparator>(
+ c->key_table.entries, elem_key.refcount, key_hash, &indices_key) &&
indices_key > c->tail_remote_index) {
- emit_maybe_add(c, elem, st, indices_key, should_add_elem,
- decoder_space_usage, elem_hash, key_hash);
+ emit_maybe_add(c, elem, st, indices_key, should_add_elem,
+ decoder_space_usage, elem_hash, key_hash);
return;
}
/* no elem, key in the table... fall back to literal emission */
- const bool should_add_key = !elem_interned && decoder_space_available;
+ const bool should_add_key = !elem_interned && decoder_space_available;
if (should_add_elem || should_add_key) {
- emit_lithdr_v<EmitLitHdrVType::INC_IDX_V>(c, elem, st);
+ emit_lithdr_v<EmitLitHdrVType::INC_IDX_V>(c, elem, st);
} else {
- emit_lithdr_v<EmitLitHdrVType::NO_IDX_V>(c, elem, st);
+ emit_lithdr_v<EmitLitHdrVType::NO_IDX_V>(c, elem, st);
}
if (should_add_elem) {
- add_elem(c, elem, decoder_space_usage, elem_hash, key_hash);
+ add_elem(c, elem, decoder_space_usage, elem_hash, key_hash);
} else if (should_add_key) {
- add_key(c, elem, decoder_space_usage, key_hash);
+ add_key(c, elem, decoder_space_usage, key_hash);
}
}
@@ -750,8 +750,8 @@ static void deadline_enc(grpc_chttp2_hpack_compressor* c, grpc_millis deadline,
grpc_mdelem mdelem;
grpc_http2_encode_timeout(deadline - grpc_core::ExecCtx::Get()->Now(),
timeout_str);
- mdelem = grpc_mdelem_from_slices(
- GRPC_MDSTR_GRPC_TIMEOUT, grpc_core::UnmanagedMemorySlice(timeout_str));
+ mdelem = grpc_mdelem_from_slices(
+ GRPC_MDSTR_GRPC_TIMEOUT, grpc_core::UnmanagedMemorySlice(timeout_str));
hpack_enc(c, mdelem, st);
GRPC_MDELEM_UNREF(mdelem);
}
@@ -764,18 +764,18 @@ void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c) {
c->cap_table_elems = elems_for_bytes(c->max_table_size);
c->max_table_elems = c->cap_table_elems;
c->max_usable_size = GRPC_CHTTP2_HPACKC_INITIAL_TABLE_SIZE;
- const size_t alloc_size = sizeof(*c->table_elem_size) * c->cap_table_elems;
- c->table_elem_size = static_cast<uint16_t*>(gpr_malloc(alloc_size));
- memset(c->table_elem_size, 0, alloc_size);
+ const size_t alloc_size = sizeof(*c->table_elem_size) * c->cap_table_elems;
+ c->table_elem_size = static_cast<uint16_t*>(gpr_malloc(alloc_size));
+ memset(c->table_elem_size, 0, alloc_size);
}
void grpc_chttp2_hpack_compressor_destroy(grpc_chttp2_hpack_compressor* c) {
- for (int i = 0; i < GRPC_CHTTP2_HPACKC_NUM_VALUES; i++) {
- auto* const key = GetEntry<grpc_slice_refcount*>(c->key_table.entries, i);
- if (key != nullptr) {
- key->Unref();
+ for (int i = 0; i < GRPC_CHTTP2_HPACKC_NUM_VALUES; i++) {
+ auto* const key = GetEntry<grpc_slice_refcount*>(c->key_table.entries, i);
+ if (key != nullptr) {
+ key->Unref();
}
- GRPC_MDELEM_UNREF(GetEntry<grpc_mdelem>(c->elem_table.entries, i));
+ GRPC_MDELEM_UNREF(GetEntry<grpc_mdelem>(c->elem_table.entries, i));
}
gpr_free(c->table_elem_size);
}
@@ -826,7 +826,7 @@ void grpc_chttp2_hpack_compressor_set_max_table_size(
}
}
c->advertise_table_size_change = 1;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "set max table size from encoder to %d", max_table_size);
}
}
@@ -837,16 +837,16 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
grpc_metadata_batch* metadata,
const grpc_encode_header_options* options,
grpc_slice_buffer* outbuf) {
- /* grpc_chttp2_encode_header is called by FlushInitial/TrailingMetadata in
- writing.cc. Specifically, on streams returned by NextStream(), which
- returns streams from the list GRPC_CHTTP2_LIST_WRITABLE. The only way to be
- added to the list is via grpc_chttp2_list_add_writable_stream(), which
- validates that stream_id is not 0. So, this can be a debug assert. */
- GPR_DEBUG_ASSERT(options->stream_id != 0);
+ /* grpc_chttp2_encode_header is called by FlushInitial/TrailingMetadata in
+ writing.cc. Specifically, on streams returned by NextStream(), which
+ returns streams from the list GRPC_CHTTP2_LIST_WRITABLE. The only way to be
+ added to the list is via grpc_chttp2_list_add_writable_stream(), which
+ validates that stream_id is not 0. So, this can be a debug assert. */
+ GPR_DEBUG_ASSERT(options->stream_id != 0);
framer_state st;
-#ifndef NDEBUG
+#ifndef NDEBUG
st.seen_regular_header = 0;
-#endif
+#endif
st.stream_id = options->stream_id;
st.output = outbuf;
st.is_first_frame = 1;
@@ -865,28 +865,28 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
}
for (size_t i = 0; i < extra_headers_size; ++i) {
grpc_mdelem md = *extra_headers[i];
- const bool is_static =
- GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_STATIC;
- uintptr_t static_index;
- if (is_static &&
- (static_index =
- reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(md))
- ->StaticIndex()) < GRPC_CHTTP2_LAST_STATIC_ENTRY) {
- emit_indexed(c, static_cast<uint32_t>(static_index + 1), &st);
+ const bool is_static =
+ GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_STATIC;
+ uintptr_t static_index;
+ if (is_static &&
+ (static_index =
+ reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(md))
+ ->StaticIndex()) < GRPC_CHTTP2_LAST_STATIC_ENTRY) {
+ emit_indexed(c, static_cast<uint32_t>(static_index + 1), &st);
} else {
hpack_enc(c, md, &st);
}
}
grpc_metadata_batch_assert_ok(metadata);
for (grpc_linked_mdelem* l = metadata->list.head; l; l = l->next) {
- const bool is_static =
- GRPC_MDELEM_STORAGE(l->md) == GRPC_MDELEM_STORAGE_STATIC;
- uintptr_t static_index;
- if (is_static &&
- (static_index = reinterpret_cast<grpc_core::StaticMetadata*>(
- GRPC_MDELEM_DATA(l->md))
- ->StaticIndex()) < GRPC_CHTTP2_LAST_STATIC_ENTRY) {
- emit_indexed(c, static_cast<uint32_t>(static_index + 1), &st);
+ const bool is_static =
+ GRPC_MDELEM_STORAGE(l->md) == GRPC_MDELEM_STORAGE_STATIC;
+ uintptr_t static_index;
+ if (is_static &&
+ (static_index = reinterpret_cast<grpc_core::StaticMetadata*>(
+ GRPC_MDELEM_DATA(l->md))
+ ->StaticIndex()) < GRPC_CHTTP2_LAST_STATIC_ENTRY) {
+ emit_indexed(c, static_cast<uint32_t>(static_index + 1), &st);
} else {
hpack_enc(c, l->md, &st);
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h
index 5093f80ae2..77c65369af 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h
@@ -38,7 +38,7 @@
extern grpc_core::TraceFlag grpc_http_trace;
-struct grpc_chttp2_hpack_compressor {
+struct grpc_chttp2_hpack_compressor {
uint32_t max_table_size;
uint32_t max_table_elems;
uint32_t cap_table_elems;
@@ -49,39 +49,39 @@ struct grpc_chttp2_hpack_compressor {
uint32_t tail_remote_index;
uint32_t table_size;
uint32_t table_elems;
- uint16_t* table_elem_size;
- /** if non-zero, advertise to the decoder that we'll start using a table
- of this size */
- uint8_t advertise_table_size_change;
+ uint16_t* table_elem_size;
+ /** if non-zero, advertise to the decoder that we'll start using a table
+ of this size */
+ uint8_t advertise_table_size_change;
/* filter tables for elems: this tables provides an approximate
popularity count for particular hashes, and are used to determine whether
a new literal should be added to the compression table or not.
They track a single integer that counts how often a particular value has
been seen. When that count reaches max (255), all values are halved. */
- uint32_t filter_elems_sum;
+ uint32_t filter_elems_sum;
uint8_t filter_elems[GRPC_CHTTP2_HPACKC_NUM_VALUES];
/* entry tables for keys & elems: these tables track values that have been
seen and *may* be in the decompressor table */
- struct {
- struct {
- grpc_mdelem value;
- uint32_t index;
- } entries[GRPC_CHTTP2_HPACKC_NUM_VALUES];
- } elem_table; /* Metadata table management */
- struct {
- struct {
- /* Only store the slice refcount - we do not need the byte buffer or
- length of the slice since we only need to store a mapping between the
- identity of the slice and the corresponding HPACK index. Since the
- slice *must* be static or interned, the refcount is sufficient to
- establish identity. */
- grpc_slice_refcount* value;
- uint32_t index;
- } entries[GRPC_CHTTP2_HPACKC_NUM_VALUES];
- } key_table; /* Key table management */
-};
+ struct {
+ struct {
+ grpc_mdelem value;
+ uint32_t index;
+ } entries[GRPC_CHTTP2_HPACKC_NUM_VALUES];
+ } elem_table; /* Metadata table management */
+ struct {
+ struct {
+ /* Only store the slice refcount - we do not need the byte buffer or
+ length of the slice since we only need to store a mapping between the
+ identity of the slice and the corresponding HPACK index. Since the
+ slice *must* be static or interned, the refcount is sufficient to
+ establish identity. */
+ grpc_slice_refcount* value;
+ uint32_t index;
+ } entries[GRPC_CHTTP2_HPACKC_NUM_VALUES];
+ } key_table; /* Key table management */
+};
void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c);
void grpc_chttp2_hpack_compressor_destroy(grpc_chttp2_hpack_compressor* c);
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc
index a325439ad5..e9f01fe4fc 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc
@@ -37,12 +37,12 @@
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/validate_metadata.h"
+#include "src/core/lib/surface/validate_metadata.h"
#include "src/core/lib/transport/http2_errors.h"
-grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser(
- false, "chttp2_hpack_parser");
-
+grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser(
+ false, "chttp2_hpack_parser");
+
typedef enum {
NOT_BINARY,
BINARY_BEGIN,
@@ -627,65 +627,65 @@ static const uint8_t inverse_base64[256] = {
255,
};
-static void GPR_ATTRIBUTE_NOINLINE on_hdr_log(grpc_mdelem md) {
- char* k = grpc_slice_to_c_string(GRPC_MDKEY(md));
- char* v = nullptr;
- if (grpc_is_binary_header_internal(GRPC_MDKEY(md))) {
- v = grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX);
- } else {
- v = grpc_slice_to_c_string(GRPC_MDVALUE(md));
- }
- gpr_log(
- GPR_INFO,
- "Decode: '%s: %s', elem_interned=%d [%d], k_interned=%d, v_interned=%d",
- k, v, GRPC_MDELEM_IS_INTERNED(md), GRPC_MDELEM_STORAGE(md),
- grpc_slice_is_interned(GRPC_MDKEY(md)),
- grpc_slice_is_interned(GRPC_MDVALUE(md)));
- gpr_free(k);
- gpr_free(v);
-}
-
+static void GPR_ATTRIBUTE_NOINLINE on_hdr_log(grpc_mdelem md) {
+ char* k = grpc_slice_to_c_string(GRPC_MDKEY(md));
+ char* v = nullptr;
+ if (grpc_is_binary_header_internal(GRPC_MDKEY(md))) {
+ v = grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX);
+ } else {
+ v = grpc_slice_to_c_string(GRPC_MDVALUE(md));
+ }
+ gpr_log(
+ GPR_INFO,
+ "Decode: '%s: %s', elem_interned=%d [%d], k_interned=%d, v_interned=%d",
+ k, v, GRPC_MDELEM_IS_INTERNED(md), GRPC_MDELEM_STORAGE(md),
+ grpc_slice_is_interned(GRPC_MDKEY(md)),
+ grpc_slice_is_interned(GRPC_MDVALUE(md)));
+ gpr_free(k);
+ gpr_free(v);
+}
+
/* emission helpers */
-template <bool do_add>
-static grpc_error* on_hdr(grpc_chttp2_hpack_parser* p, grpc_mdelem md) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_chttp2_hpack_parser)) {
- on_hdr_log(md);
+template <bool do_add>
+static grpc_error* on_hdr(grpc_chttp2_hpack_parser* p, grpc_mdelem md) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_chttp2_hpack_parser)) {
+ on_hdr_log(md);
}
- if (do_add) {
- GPR_DEBUG_ASSERT(GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_INTERNED ||
- GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_STATIC);
+ if (do_add) {
+ GPR_DEBUG_ASSERT(GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_INTERNED ||
+ GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_STATIC);
grpc_error* err = grpc_chttp2_hptbl_add(&p->table, md);
- if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) return err;
+ if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) return err;
}
- return p->on_header(p->on_header_user_data, md);
-}
-
-static grpc_core::UnmanagedMemorySlice take_string_extern(
- grpc_chttp2_hpack_parser* /*p*/, grpc_chttp2_hpack_parser_string* str) {
- grpc_core::UnmanagedMemorySlice s;
- if (!str->copied) {
- GPR_DEBUG_ASSERT(!grpc_slice_is_interned(str->data.referenced));
- s = static_cast<grpc_core::UnmanagedMemorySlice&>(str->data.referenced);
- str->copied = true;
- str->data.referenced = grpc_core::UnmanagedMemorySlice();
- } else {
- s = grpc_core::UnmanagedMemorySlice(str->data.copied.str,
- str->data.copied.length);
+ return p->on_header(p->on_header_user_data, md);
+}
+
+static grpc_core::UnmanagedMemorySlice take_string_extern(
+ grpc_chttp2_hpack_parser* /*p*/, grpc_chttp2_hpack_parser_string* str) {
+ grpc_core::UnmanagedMemorySlice s;
+ if (!str->copied) {
+ GPR_DEBUG_ASSERT(!grpc_slice_is_interned(str->data.referenced));
+ s = static_cast<grpc_core::UnmanagedMemorySlice&>(str->data.referenced);
+ str->copied = true;
+ str->data.referenced = grpc_core::UnmanagedMemorySlice();
+ } else {
+ s = grpc_core::UnmanagedMemorySlice(str->data.copied.str,
+ str->data.copied.length);
}
- str->data.copied.length = 0;
- return s;
+ str->data.copied.length = 0;
+ return s;
}
-static grpc_core::ManagedMemorySlice take_string_intern(
- grpc_chttp2_hpack_parser* /*p*/, grpc_chttp2_hpack_parser_string* str) {
- grpc_core::ManagedMemorySlice s;
+static grpc_core::ManagedMemorySlice take_string_intern(
+ grpc_chttp2_hpack_parser* /*p*/, grpc_chttp2_hpack_parser_string* str) {
+ grpc_core::ManagedMemorySlice s;
if (!str->copied) {
- s = grpc_core::ManagedMemorySlice(&str->data.referenced);
- grpc_slice_unref_internal(str->data.referenced);
+ s = grpc_core::ManagedMemorySlice(&str->data.referenced);
+ grpc_slice_unref_internal(str->data.referenced);
str->copied = true;
str->data.referenced = grpc_empty_slice();
} else {
- s = grpc_core::ManagedMemorySlice(str->data.copied.str,
+ s = grpc_core::ManagedMemorySlice(str->data.copied.str,
str->data.copied.length);
}
str->data.copied.length = 0;
@@ -762,26 +762,26 @@ static grpc_error* parse_stream_dep0(grpc_chttp2_hpack_parser* p,
return parse_stream_dep1(p, cur + 1, end);
}
-static grpc_error* GPR_ATTRIBUTE_NOINLINE
-on_invalid_hpack_idx(grpc_chttp2_hpack_parser* p) {
- return grpc_error_set_int(
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Invalid HPACK index received"),
- GRPC_ERROR_INT_INDEX, static_cast<intptr_t>(p->index)),
- GRPC_ERROR_INT_SIZE, static_cast<intptr_t>(p->table.num_ents));
-}
-
+static grpc_error* GPR_ATTRIBUTE_NOINLINE
+on_invalid_hpack_idx(grpc_chttp2_hpack_parser* p) {
+ return grpc_error_set_int(
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Invalid HPACK index received"),
+ GRPC_ERROR_INT_INDEX, static_cast<intptr_t>(p->index)),
+ GRPC_ERROR_INT_SIZE, static_cast<intptr_t>(p->table.num_ents));
+}
+
/* emit an indexed field; jumps to begin the next field on completion */
static grpc_error* finish_indexed_field(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
- grpc_mdelem md = grpc_chttp2_hptbl_lookup<true>(&p->table, p->index);
- if (GPR_UNLIKELY(GRPC_MDISNULL(md))) {
- return on_invalid_hpack_idx(p);
+ grpc_mdelem md = grpc_chttp2_hptbl_lookup<true>(&p->table, p->index);
+ if (GPR_UNLIKELY(GRPC_MDISNULL(md))) {
+ return on_invalid_hpack_idx(p);
}
GRPC_STATS_INC_HPACK_RECV_INDEXED();
- grpc_error* err = on_hdr<false>(p, md);
- if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) return err;
+ grpc_error* err = on_hdr<false>(p, md);
+ if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) return err;
return parse_begin(p, cur, end);
}
@@ -790,7 +790,7 @@ static grpc_error* parse_indexed_field(grpc_chttp2_hpack_parser* p,
const uint8_t* cur, const uint8_t* end) {
p->dynamic_table_update_allowed = 0;
p->index = (*cur) & 0x7f;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
return finish_indexed_field(p, cur + 1, end);
}
@@ -803,41 +803,41 @@ static grpc_error* parse_indexed_field_x(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = 0x7f;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
p->parsing.value = &p->index;
return parse_value0(p, cur + 1, end);
}
-/* When finishing with a header, get the cached md element for this index.
- This is set in parse_value_string(). We ensure (in debug mode) that the
- cached metadata corresponds with the index we are examining. */
-static grpc_mdelem get_precomputed_md_for_idx(grpc_chttp2_hpack_parser* p) {
- GPR_DEBUG_ASSERT(p->md_for_index.payload != 0);
- GPR_DEBUG_ASSERT(static_cast<int64_t>(p->index) == p->precomputed_md_index);
- grpc_mdelem md = p->md_for_index;
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(md)); /* handled in string parsing */
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
-#ifndef NDEBUG
- p->precomputed_md_index = -1;
-#endif
- return md;
-}
-
-static const grpc_core::ManagedMemorySlice& get_indexed_key(grpc_mdelem md) {
- GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(md));
- return static_cast<const grpc_core::ManagedMemorySlice&>(
- grpc_slice_ref_internal(GRPC_MDKEY(md)));
-}
-
+/* When finishing with a header, get the cached md element for this index.
+ This is set in parse_value_string(). We ensure (in debug mode) that the
+ cached metadata corresponds with the index we are examining. */
+static grpc_mdelem get_precomputed_md_for_idx(grpc_chttp2_hpack_parser* p) {
+ GPR_DEBUG_ASSERT(p->md_for_index.payload != 0);
+ GPR_DEBUG_ASSERT(static_cast<int64_t>(p->index) == p->precomputed_md_index);
+ grpc_mdelem md = p->md_for_index;
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(md)); /* handled in string parsing */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+#ifndef NDEBUG
+ p->precomputed_md_index = -1;
+#endif
+ return md;
+}
+
+static const grpc_core::ManagedMemorySlice& get_indexed_key(grpc_mdelem md) {
+ GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(md));
+ return static_cast<const grpc_core::ManagedMemorySlice&>(
+ grpc_slice_ref_internal(GRPC_MDKEY(md)));
+}
+
/* finish a literal header with incremental indexing */
static grpc_error* finish_lithdr_incidx(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX();
- grpc_mdelem md = get_precomputed_md_for_idx(p);
- grpc_error* err = on_hdr<true>(
- p, grpc_mdelem_from_slices(get_indexed_key(md),
- take_string_intern(p, &p->value)));
+ grpc_mdelem md = get_precomputed_md_for_idx(p);
+ grpc_error* err = on_hdr<true>(
+ p, grpc_mdelem_from_slices(get_indexed_key(md),
+ take_string_intern(p, &p->value)));
if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
return parse_begin(p, cur, end);
}
@@ -847,9 +847,9 @@ static grpc_error* finish_lithdr_incidx_v(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX_V();
- grpc_error* err = on_hdr<true>(
- p, grpc_mdelem_from_slices(take_string_intern(p, &p->key),
- take_string_intern(p, &p->value)));
+ grpc_error* err = on_hdr<true>(
+ p, grpc_mdelem_from_slices(take_string_intern(p, &p->key),
+ take_string_intern(p, &p->value)));
if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
return parse_begin(p, cur, end);
}
@@ -862,7 +862,7 @@ static grpc_error* parse_lithdr_incidx(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = (*cur) & 0x3f;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
return parse_string_prefix(p, cur + 1, end);
}
@@ -876,7 +876,7 @@ static grpc_error* parse_lithdr_incidx_x(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = 0x3f;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
p->parsing.value = &p->index;
return parse_value0(p, cur + 1, end);
}
@@ -898,10 +898,10 @@ static grpc_error* finish_lithdr_notidx(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX();
- grpc_mdelem md = get_precomputed_md_for_idx(p);
- grpc_error* err = on_hdr<false>(
- p, grpc_mdelem_from_slices(get_indexed_key(md),
- take_string_extern(p, &p->value)));
+ grpc_mdelem md = get_precomputed_md_for_idx(p);
+ grpc_error* err = on_hdr<false>(
+ p, grpc_mdelem_from_slices(get_indexed_key(md),
+ take_string_extern(p, &p->value)));
if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
return parse_begin(p, cur, end);
}
@@ -911,9 +911,9 @@ static grpc_error* finish_lithdr_notidx_v(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX_V();
- grpc_error* err = on_hdr<false>(
- p, grpc_mdelem_from_slices(take_string_intern(p, &p->key),
- take_string_extern(p, &p->value)));
+ grpc_error* err = on_hdr<false>(
+ p, grpc_mdelem_from_slices(take_string_intern(p, &p->key),
+ take_string_extern(p, &p->value)));
if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
return parse_begin(p, cur, end);
}
@@ -926,7 +926,7 @@ static grpc_error* parse_lithdr_notidx(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = (*cur) & 0xf;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
return parse_string_prefix(p, cur + 1, end);
}
@@ -940,7 +940,7 @@ static grpc_error* parse_lithdr_notidx_x(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = 0xf;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
p->parsing.value = &p->index;
return parse_value0(p, cur + 1, end);
}
@@ -962,10 +962,10 @@ static grpc_error* finish_lithdr_nvridx(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX();
- grpc_mdelem md = get_precomputed_md_for_idx(p);
- grpc_error* err = on_hdr<false>(
- p, grpc_mdelem_from_slices(get_indexed_key(md),
- take_string_extern(p, &p->value)));
+ grpc_mdelem md = get_precomputed_md_for_idx(p);
+ grpc_error* err = on_hdr<false>(
+ p, grpc_mdelem_from_slices(get_indexed_key(md),
+ take_string_extern(p, &p->value)));
if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
return parse_begin(p, cur, end);
}
@@ -975,9 +975,9 @@ static grpc_error* finish_lithdr_nvridx_v(grpc_chttp2_hpack_parser* p,
const uint8_t* cur,
const uint8_t* end) {
GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX_V();
- grpc_error* err = on_hdr<false>(
- p, grpc_mdelem_from_slices(take_string_intern(p, &p->key),
- take_string_extern(p, &p->value)));
+ grpc_error* err = on_hdr<false>(
+ p, grpc_mdelem_from_slices(take_string_intern(p, &p->key),
+ take_string_extern(p, &p->value)));
if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
return parse_begin(p, cur, end);
}
@@ -990,7 +990,7 @@ static grpc_error* parse_lithdr_nvridx(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = (*cur) & 0xf;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
return parse_string_prefix(p, cur + 1, end);
}
@@ -1004,7 +1004,7 @@ static grpc_error* parse_lithdr_nvridx_x(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed = 0;
p->next_state = and_then;
p->index = 0xf;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
p->parsing.value = &p->index;
return parse_value0(p, cur + 1, end);
}
@@ -1024,7 +1024,7 @@ static grpc_error* parse_lithdr_nvridx_v(grpc_chttp2_hpack_parser* p,
/* finish parsing a max table size change */
static grpc_error* finish_max_tbl_size(grpc_chttp2_hpack_parser* p,
const uint8_t* cur, const uint8_t* end) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_chttp2_hpack_parser)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_chttp2_hpack_parser)) {
gpr_log(GPR_INFO, "MAX TABLE SIZE: %d", p->index);
}
grpc_error* err =
@@ -1044,7 +1044,7 @@ static grpc_error* parse_max_tbl_size(grpc_chttp2_hpack_parser* p,
}
p->dynamic_table_update_allowed--;
p->index = (*cur) & 0x1f;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
return finish_max_tbl_size(p, cur + 1, end);
}
@@ -1063,15 +1063,15 @@ static grpc_error* parse_max_tbl_size_x(grpc_chttp2_hpack_parser* p,
p->dynamic_table_update_allowed--;
p->next_state = and_then;
p->index = 0x1f;
- p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
+ p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
p->parsing.value = &p->index;
return parse_value0(p, cur + 1, end);
}
/* a parse error: jam the parse state into parse_error, and return error */
-static grpc_error* parse_error(grpc_chttp2_hpack_parser* p,
- const uint8_t* /*cur*/, const uint8_t* /*end*/,
- grpc_error* err) {
+static grpc_error* parse_error(grpc_chttp2_hpack_parser* p,
+ const uint8_t* /*cur*/, const uint8_t* /*end*/,
+ grpc_error* err) {
GPR_ASSERT(err != GRPC_ERROR_NONE);
if (p->last_error == GRPC_ERROR_NONE) {
p->last_error = GRPC_ERROR_REF(err);
@@ -1081,8 +1081,8 @@ static grpc_error* parse_error(grpc_chttp2_hpack_parser* p,
}
static grpc_error* still_parse_error(grpc_chttp2_hpack_parser* p,
- const uint8_t* /*cur*/,
- const uint8_t* /*end*/) {
+ const uint8_t* /*cur*/,
+ const uint8_t* /*end*/) {
return GRPC_ERROR_REF(p->last_error);
}
@@ -1480,7 +1480,7 @@ static grpc_error* begin_parse_string(grpc_chttp2_hpack_parser* p,
uint8_t binary,
grpc_chttp2_hpack_parser_string* str) {
if (!p->huff && binary == NOT_BINARY &&
- static_cast<uint32_t>(end - cur) >= p->strlen &&
+ static_cast<uint32_t>(end - cur) >= p->strlen &&
p->current_slice_refcount != nullptr) {
GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED();
str->copied = false;
@@ -1522,50 +1522,50 @@ static grpc_error* parse_key_string(grpc_chttp2_hpack_parser* p,
/* check if a key represents a binary header or not */
static bool is_binary_literal_header(grpc_chttp2_hpack_parser* p) {
- /* We know that either argument here is a reference counter slice.
- * 1. If it is a grpc_core::StaticSlice, the refcount is set to kNoopRefcount.
- * 2. If it's p->key.data.referenced, then p->key.copied was set to false,
- * which occurs in begin_parse_string() - where the refcount is set to
- * p->current_slice_refcount, which is not null. */
- return grpc_is_refcounted_slice_binary_header(
- p->key.copied ? grpc_core::ExternallyManagedSlice(
- p->key.data.copied.str, p->key.data.copied.length)
+ /* We know that either argument here is a reference counter slice.
+ * 1. If it is a grpc_core::StaticSlice, the refcount is set to kNoopRefcount.
+ * 2. If it's p->key.data.referenced, then p->key.copied was set to false,
+ * which occurs in begin_parse_string() - where the refcount is set to
+ * p->current_slice_refcount, which is not null. */
+ return grpc_is_refcounted_slice_binary_header(
+ p->key.copied ? grpc_core::ExternallyManagedSlice(
+ p->key.data.copied.str, p->key.data.copied.length)
: p->key.data.referenced);
}
-/* Cache the metadata for the given index during initial parsing. This avoids a
- pointless recomputation of the metadata when finishing a header. We read the
- cached value in get_precomputed_md_for_idx(). */
-static void set_precomputed_md_idx(grpc_chttp2_hpack_parser* p,
- grpc_mdelem md) {
- GPR_DEBUG_ASSERT(p->md_for_index.payload == 0);
- GPR_DEBUG_ASSERT(p->precomputed_md_index == -1);
- p->md_for_index = md;
-#ifndef NDEBUG
- p->precomputed_md_index = p->index;
-#endif
-}
-
-/* Determines if a metadata element key associated with the current parser index
- is a binary indexed header during string parsing. We'll need to revisit this
- metadata when we're done parsing, so we cache the metadata for this index
- here using set_precomputed_md_idx(). */
+/* Cache the metadata for the given index during initial parsing. This avoids a
+ pointless recomputation of the metadata when finishing a header. We read the
+ cached value in get_precomputed_md_for_idx(). */
+static void set_precomputed_md_idx(grpc_chttp2_hpack_parser* p,
+ grpc_mdelem md) {
+ GPR_DEBUG_ASSERT(p->md_for_index.payload == 0);
+ GPR_DEBUG_ASSERT(p->precomputed_md_index == -1);
+ p->md_for_index = md;
+#ifndef NDEBUG
+ p->precomputed_md_index = p->index;
+#endif
+}
+
+/* Determines if a metadata element key associated with the current parser index
+ is a binary indexed header during string parsing. We'll need to revisit this
+ metadata when we're done parsing, so we cache the metadata for this index
+ here using set_precomputed_md_idx(). */
static grpc_error* is_binary_indexed_header(grpc_chttp2_hpack_parser* p,
bool* is) {
grpc_mdelem elem = grpc_chttp2_hptbl_lookup(&p->table, p->index);
- if (GPR_UNLIKELY(GRPC_MDISNULL(elem))) {
- return on_invalid_hpack_idx(p);
+ if (GPR_UNLIKELY(GRPC_MDISNULL(elem))) {
+ return on_invalid_hpack_idx(p);
}
- /* We know that GRPC_MDKEY(elem) points to a reference counted slice since:
- * 1. elem was a result of grpc_chttp2_hptbl_lookup
- * 2. An item in this table is either static (see entries with
- * index < GRPC_CHTTP2_LAST_STATIC_ENTRY or added via
- * grpc_chttp2_hptbl_add).
- * 3. If added via grpc_chttp2_hptbl_add, the entry is either static or
- * interned.
- * 4. Both static and interned element slices have non-null refcounts. */
- *is = grpc_is_refcounted_slice_binary_header(GRPC_MDKEY(elem));
- set_precomputed_md_idx(p, elem);
+ /* We know that GRPC_MDKEY(elem) points to a reference counted slice since:
+ * 1. elem was a result of grpc_chttp2_hptbl_lookup
+ * 2. An item in this table is either static (see entries with
+ * index < GRPC_CHTTP2_LAST_STATIC_ENTRY or added via
+ * grpc_chttp2_hptbl_add).
+ * 3. If added via grpc_chttp2_hptbl_add, the entry is either static or
+ * interned.
+ * 4. Both static and interned element slices have non-null refcounts. */
+ *is = grpc_is_refcounted_slice_binary_header(GRPC_MDKEY(elem));
+ set_precomputed_md_idx(p, elem);
return GRPC_ERROR_NONE;
}
@@ -1590,17 +1590,17 @@ static grpc_error* parse_value_string_with_literal_key(
return parse_value_string(p, cur, end, is_binary_literal_header(p));
}
-/* "Uninitialized" header parser to save us a branch in on_hdr(). */
-static grpc_error* on_header_uninitialized(void* /*user_data*/,
- grpc_mdelem md) {
- GRPC_MDELEM_UNREF(md);
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("on_header callback not set");
-}
-
+/* "Uninitialized" header parser to save us a branch in on_hdr(). */
+static grpc_error* on_header_uninitialized(void* /*user_data*/,
+ grpc_mdelem md) {
+ GRPC_MDELEM_UNREF(md);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("on_header callback not set");
+}
+
/* PUBLIC INTERFACE */
void grpc_chttp2_hpack_parser_init(grpc_chttp2_hpack_parser* p) {
- p->on_header = on_header_uninitialized;
+ p->on_header = on_header_uninitialized;
p->on_header_user_data = nullptr;
p->state = parse_begin;
p->key.data.referenced = grpc_empty_slice();
@@ -1611,18 +1611,18 @@ void grpc_chttp2_hpack_parser_init(grpc_chttp2_hpack_parser* p) {
p->value.data.copied.str = nullptr;
p->value.data.copied.capacity = 0;
p->value.data.copied.length = 0;
- /* Cached metadata for the current index the parser is handling. This is set
- to 0 initially, invalidated when the index changes, and invalidated when it
- is read (by get_precomputed_md_for_idx()). It is set during string parsing,
- by set_precomputed_md_idx() - which is called by parse_value_string().
- The goal here is to avoid recomputing the metadata for the index when
- finishing with a header as well as the initial parse. */
- p->md_for_index.payload = 0;
-#ifndef NDEBUG
- /* In debug mode, this ensures that the cached metadata we're reading is in
- * fact correct for the index we are examining. */
- p->precomputed_md_index = -1;
-#endif
+ /* Cached metadata for the current index the parser is handling. This is set
+ to 0 initially, invalidated when the index changes, and invalidated when it
+ is read (by get_precomputed_md_for_idx()). It is set during string parsing,
+ by set_precomputed_md_idx() - which is called by parse_value_string().
+ The goal here is to avoid recomputing the metadata for the index when
+ finishing with a header as well as the initial parse. */
+ p->md_for_index.payload = 0;
+#ifndef NDEBUG
+ /* In debug mode, this ensures that the cached metadata we're reading is in
+ * fact correct for the index we are examining. */
+ p->precomputed_md_index = -1;
+#endif
p->dynamic_table_update_allowed = 2;
p->last_error = GRPC_ERROR_NONE;
}
@@ -1642,16 +1642,16 @@ void grpc_chttp2_hpack_parser_destroy(grpc_chttp2_hpack_parser* p) {
}
grpc_error* grpc_chttp2_hpack_parser_parse(grpc_chttp2_hpack_parser* p,
- const grpc_slice& slice) {
+ const grpc_slice& slice) {
/* max number of bytes to parse at a time... limits call stack depth on
* compilers without TCO */
#define MAX_PARSE_LENGTH 1024
p->current_slice_refcount = slice.refcount;
- const uint8_t* start = GRPC_SLICE_START_PTR(slice);
- const uint8_t* end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* start = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* end = GRPC_SLICE_END_PTR(slice);
grpc_error* error = GRPC_ERROR_NONE;
while (start != end && error == GRPC_ERROR_NONE) {
- const uint8_t* target = start + GPR_MIN(MAX_PARSE_LENGTH, end - start);
+ const uint8_t* target = start + GPR_MIN(MAX_PARSE_LENGTH, end - start);
error = p->state(p, start, target);
start = target;
}
@@ -1665,19 +1665,19 @@ static const maybe_complete_func_type maybe_complete_funcs[] = {
grpc_chttp2_maybe_complete_recv_initial_metadata,
grpc_chttp2_maybe_complete_recv_trailing_metadata};
-static void force_client_rst_stream(void* sp, grpc_error* /*error*/) {
+static void force_client_rst_stream(void* sp, grpc_error* /*error*/) {
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp);
grpc_chttp2_transport* t = s->t;
if (!s->write_closed) {
- grpc_chttp2_add_rst_stream_to_next_write(t, s->id, GRPC_HTTP2_NO_ERROR,
- &s->stats.outgoing);
+ grpc_chttp2_add_rst_stream_to_next_write(t, s->id, GRPC_HTTP2_NO_ERROR,
+ &s->stats.outgoing);
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM);
grpc_chttp2_mark_stream_closed(t, s, true, true, GRPC_ERROR_NONE);
}
GRPC_CHTTP2_STREAM_UNREF(s, "final_rst");
}
-static void parse_stream_compression_md(grpc_chttp2_transport* /*t*/,
+static void parse_stream_compression_md(grpc_chttp2_transport* /*t*/,
grpc_chttp2_stream* s,
grpc_metadata_batch* initial_metadata) {
if (initial_metadata->idx.named.content_encoding == nullptr ||
@@ -1687,19 +1687,19 @@ static void parse_stream_compression_md(grpc_chttp2_transport* /*t*/,
s->stream_decompression_method =
GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
}
-
- if (s->stream_decompression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
- s->stream_decompression_ctx = nullptr;
- grpc_slice_buffer_init(&s->decompressed_data_buffer);
- }
+
+ if (s->stream_decompression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
+ s->stream_decompression_ctx = nullptr;
+ grpc_slice_buffer_init(&s->decompressed_data_buffer);
+ }
}
grpc_error* grpc_chttp2_header_parser_parse(void* hpack_parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last) {
+ const grpc_slice& slice,
+ int is_last) {
GPR_TIMER_SCOPE("grpc_chttp2_header_parser_parse", 0);
grpc_chttp2_hpack_parser* parser =
static_cast<grpc_chttp2_hpack_parser*>(hpack_parser);
@@ -1740,14 +1740,14 @@ grpc_error* grpc_chttp2_header_parser_parse(void* hpack_parser,
however -- it might be that we receive a RST_STREAM following this
and can avoid the extra write */
GRPC_CHTTP2_STREAM_REF(s, "final_rst");
- t->combiner->FinallyRun(
- GRPC_CLOSURE_CREATE(force_client_rst_stream, s, nullptr),
+ t->combiner->FinallyRun(
+ GRPC_CLOSURE_CREATE(force_client_rst_stream, s, nullptr),
GRPC_ERROR_NONE);
}
grpc_chttp2_mark_stream_closed(t, s, true, false, GRPC_ERROR_NONE);
}
}
- parser->on_header = on_header_uninitialized;
+ parser->on_header = on_header_uninitialized;
parser->on_header_user_data = nullptr;
parser->is_boundary = 0xde;
parser->is_eof = 0xde;
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h
index 1b859c4d7c..7c26998df8 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h
@@ -45,7 +45,7 @@ struct grpc_chttp2_hpack_parser_string {
};
struct grpc_chttp2_hpack_parser {
/* user specified callback for each header output */
- grpc_error* (*on_header)(void* user_data, grpc_mdelem md);
+ grpc_error* (*on_header)(void* user_data, grpc_mdelem md);
void* on_header_user_data;
grpc_error* last_error;
@@ -68,14 +68,14 @@ struct grpc_chttp2_hpack_parser {
grpc_chttp2_hpack_parser_string value;
/* parsed index */
uint32_t index;
- /* When we parse a value string, we determine the metadata element for a
- specific index, which we need again when we're finishing up with that
- header. To avoid calculating the metadata element for that index a second
- time at that stage, we cache (and invalidate) the element here. */
- grpc_mdelem md_for_index;
-#ifndef NDEBUG
- int64_t precomputed_md_index;
-#endif
+ /* When we parse a value string, we determine the metadata element for a
+ specific index, which we need again when we're finishing up with that
+ header. To avoid calculating the metadata element for that index a second
+ time at that stage, we cache (and invalidate) the element here. */
+ grpc_mdelem md_for_index;
+#ifndef NDEBUG
+ int64_t precomputed_md_index;
+#endif
/* length of source bytes for the currently parsing string */
uint32_t strlen;
/* number of source bytes read for the currently parsing string */
@@ -104,14 +104,14 @@ void grpc_chttp2_hpack_parser_destroy(grpc_chttp2_hpack_parser* p);
void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser* p);
grpc_error* grpc_chttp2_hpack_parser_parse(grpc_chttp2_hpack_parser* p,
- const grpc_slice& slice);
+ const grpc_slice& slice);
/* wraps grpc_chttp2_hpack_parser_parse to provide a frame level parser for
the transport */
grpc_error* grpc_chttp2_header_parser_parse(void* hpack_parser,
grpc_chttp2_transport* t,
grpc_chttp2_stream* s,
- const grpc_slice& slice,
- int is_last);
+ const grpc_slice& slice,
+ int is_last);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_PARSER_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc
index 812d17cb45..18afcafa26 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc
@@ -30,8 +30,8 @@
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/murmur_hash.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/validate_metadata.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/validate_metadata.h"
#include "src/core/lib/transport/static_metadata.h"
extern grpc_core::TraceFlag grpc_http_trace;
@@ -42,37 +42,37 @@ void grpc_chttp2_hptbl_destroy(grpc_chttp2_hptbl* tbl) {
GRPC_MDELEM_UNREF(tbl->ents[(tbl->first_ent + i) % tbl->cap_entries]);
}
gpr_free(tbl->ents);
- tbl->ents = nullptr;
+ tbl->ents = nullptr;
}
-template <bool take_ref>
-static grpc_mdelem lookup_dynamic_index(const grpc_chttp2_hptbl* tbl,
- uint32_t tbl_index) {
- /* Not static - find the value in the list of valid entries */
+template <bool take_ref>
+static grpc_mdelem lookup_dynamic_index(const grpc_chttp2_hptbl* tbl,
+ uint32_t tbl_index) {
+ /* Not static - find the value in the list of valid entries */
tbl_index -= (GRPC_CHTTP2_LAST_STATIC_ENTRY + 1);
if (tbl_index < tbl->num_ents) {
uint32_t offset =
(tbl->num_ents - 1u - tbl_index + tbl->first_ent) % tbl->cap_entries;
- grpc_mdelem md = tbl->ents[offset];
- if (take_ref) {
- GRPC_MDELEM_REF(md);
- }
- return md;
+ grpc_mdelem md = tbl->ents[offset];
+ if (take_ref) {
+ GRPC_MDELEM_REF(md);
+ }
+ return md;
}
/* Invalid entry: return error */
return GRPC_MDNULL;
}
-grpc_mdelem grpc_chttp2_hptbl_lookup_dynamic_index(const grpc_chttp2_hptbl* tbl,
- uint32_t tbl_index) {
- return lookup_dynamic_index<false>(tbl, tbl_index);
-}
-
-grpc_mdelem grpc_chttp2_hptbl_lookup_ref_dynamic_index(
- const grpc_chttp2_hptbl* tbl, uint32_t tbl_index) {
- return lookup_dynamic_index<true>(tbl, tbl_index);
-}
-
+grpc_mdelem grpc_chttp2_hptbl_lookup_dynamic_index(const grpc_chttp2_hptbl* tbl,
+ uint32_t tbl_index) {
+ return lookup_dynamic_index<false>(tbl, tbl_index);
+}
+
+grpc_mdelem grpc_chttp2_hptbl_lookup_ref_dynamic_index(
+ const grpc_chttp2_hptbl* tbl, uint32_t tbl_index) {
+ return lookup_dynamic_index<true>(tbl, tbl_index);
+}
+
/* Evict one element from the table */
static void evict1(grpc_chttp2_hptbl* tbl) {
grpc_mdelem first_ent = tbl->ents[tbl->first_ent];
@@ -105,7 +105,7 @@ void grpc_chttp2_hptbl_set_max_bytes(grpc_chttp2_hptbl* tbl,
if (tbl->max_bytes == max_bytes) {
return;
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "Update hpack parser max size to %d", max_bytes);
}
while (tbl->mem_used > max_bytes) {
@@ -126,14 +126,14 @@ grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_chttp2_hptbl* tbl,
tbl->max_bytes)
.c_str());
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "Update hpack parser table size to %d", bytes);
}
while (tbl->mem_used > bytes) {
evict1(tbl);
}
tbl->current_table_bytes = bytes;
- tbl->max_entries = grpc_chttp2_hptbl::entries_for_bytes(bytes);
+ tbl->max_entries = grpc_chttp2_hptbl::entries_for_bytes(bytes);
if (tbl->max_entries > tbl->cap_entries) {
rebuild_ents(tbl, GPR_MAX(tbl->max_entries, 2 * tbl->cap_entries));
} else if (tbl->max_entries < tbl->cap_entries / 3) {
@@ -200,7 +200,7 @@ grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find(
/* See if the string is in the static table */
for (i = 0; i < GRPC_CHTTP2_LAST_STATIC_ENTRY; i++) {
- grpc_mdelem ent = grpc_static_mdelem_manifested()[i];
+ grpc_mdelem ent = grpc_static_mdelem_manifested()[i];
if (!grpc_slice_eq(GRPC_MDKEY(md), GRPC_MDKEY(ent))) continue;
r.index = i + 1u;
r.has_value = grpc_slice_eq(GRPC_MDVALUE(md), GRPC_MDVALUE(ent));
@@ -228,11 +228,11 @@ static size_t get_base64_encoded_size(size_t raw_length) {
size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem,
bool use_true_binary_metadata) {
- const uint8_t* key_buf = GRPC_SLICE_START_PTR(GRPC_MDKEY(elem));
- size_t key_len = GRPC_SLICE_LENGTH(GRPC_MDKEY(elem));
- size_t overhead_and_key = 32 + key_len;
+ const uint8_t* key_buf = GRPC_SLICE_START_PTR(GRPC_MDKEY(elem));
+ size_t key_len = GRPC_SLICE_LENGTH(GRPC_MDKEY(elem));
+ size_t overhead_and_key = 32 + key_len;
size_t value_len = GRPC_SLICE_LENGTH(GRPC_MDVALUE(elem));
- if (grpc_key_is_binary_header(key_buf, key_len)) {
+ if (grpc_key_is_binary_header(key_buf, key_len)) {
return overhead_and_key + (use_true_binary_metadata
? value_len + 1
: get_base64_encoded_size(value_len));
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h
index 34c3dceda7..d7906189fc 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h
@@ -22,10 +22,10 @@
#include <grpc/support/port_platform.h>
#include <grpc/slice.h>
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/transport/metadata.h"
-#include "src/core/lib/transport/static_metadata.h"
+#include "src/core/lib/transport/static_metadata.h"
/* HPACK header table */
@@ -47,44 +47,44 @@
#endif
/* hpack decoder table */
-struct grpc_chttp2_hptbl {
- static uint32_t entries_for_bytes(uint32_t bytes) {
- return (bytes + GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD - 1) /
- GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
- }
- static constexpr uint32_t kInitialCapacity =
- (GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE + GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD -
- 1) /
- GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
-
- grpc_chttp2_hptbl() {
- GPR_DEBUG_ASSERT(!ents);
- constexpr uint32_t AllocSize = sizeof(*ents) * kInitialCapacity;
- ents = static_cast<grpc_mdelem*>(gpr_malloc(AllocSize));
- memset(ents, 0, AllocSize);
- }
-
+struct grpc_chttp2_hptbl {
+ static uint32_t entries_for_bytes(uint32_t bytes) {
+ return (bytes + GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD - 1) /
+ GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
+ }
+ static constexpr uint32_t kInitialCapacity =
+ (GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE + GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD -
+ 1) /
+ GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
+
+ grpc_chttp2_hptbl() {
+ GPR_DEBUG_ASSERT(!ents);
+ constexpr uint32_t AllocSize = sizeof(*ents) * kInitialCapacity;
+ ents = static_cast<grpc_mdelem*>(gpr_malloc(AllocSize));
+ memset(ents, 0, AllocSize);
+ }
+
/* the first used entry in ents */
- uint32_t first_ent = 0;
+ uint32_t first_ent = 0;
/* how many entries are in the table */
- uint32_t num_ents = 0;
+ uint32_t num_ents = 0;
/* the amount of memory used by the table, according to the hpack algorithm */
- uint32_t mem_used = 0;
+ uint32_t mem_used = 0;
/* the max memory allowed to be used by the table, according to the hpack
algorithm */
- uint32_t max_bytes = GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE;
+ uint32_t max_bytes = GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE;
/* the currently agreed size of the table, according to the hpack algorithm */
- uint32_t current_table_bytes = GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE;
+ uint32_t current_table_bytes = GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE;
/* Maximum number of entries we could possibly fit in the table, given defined
overheads */
- uint32_t max_entries = kInitialCapacity;
+ uint32_t max_entries = kInitialCapacity;
/* Number of entries allocated in ents */
- uint32_t cap_entries = kInitialCapacity;
+ uint32_t cap_entries = kInitialCapacity;
/* a circular buffer of headers - this is stored in the opposite order to
what hpack specifies, in order to simplify table management a little...
meaning lookups need to SUBTRACT from the end position */
- grpc_mdelem* ents = nullptr;
-};
+ grpc_mdelem* ents = nullptr;
+};
void grpc_chttp2_hptbl_destroy(grpc_chttp2_hptbl* tbl);
void grpc_chttp2_hptbl_set_max_bytes(grpc_chttp2_hptbl* tbl,
@@ -93,29 +93,29 @@ grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_chttp2_hptbl* tbl,
uint32_t bytes);
/* lookup a table entry based on its hpack index */
-grpc_mdelem grpc_chttp2_hptbl_lookup_dynamic_index(const grpc_chttp2_hptbl* tbl,
- uint32_t tbl_index);
-grpc_mdelem grpc_chttp2_hptbl_lookup_ref_dynamic_index(
- const grpc_chttp2_hptbl* tbl, uint32_t tbl_index);
-template <bool take_ref = false>
-inline grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl* tbl,
- uint32_t index) {
- /* Static table comes first, just return an entry from it.
- NB: This imposes the constraint that the first
- GRPC_CHTTP2_LAST_STATIC_ENTRY entries in the core static metadata table
- must follow the hpack standard. If that changes, we *must* not rely on
- reading the core static metadata table here; at that point we'd need our
- own singleton static metadata in the correct order. */
- if (index <= GRPC_CHTTP2_LAST_STATIC_ENTRY) {
- return grpc_static_mdelem_manifested()[index - 1];
- } else {
- if (take_ref) {
- return grpc_chttp2_hptbl_lookup_ref_dynamic_index(tbl, index);
- } else {
- return grpc_chttp2_hptbl_lookup_dynamic_index(tbl, index);
- }
- }
-}
+grpc_mdelem grpc_chttp2_hptbl_lookup_dynamic_index(const grpc_chttp2_hptbl* tbl,
+ uint32_t tbl_index);
+grpc_mdelem grpc_chttp2_hptbl_lookup_ref_dynamic_index(
+ const grpc_chttp2_hptbl* tbl, uint32_t tbl_index);
+template <bool take_ref = false>
+inline grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl* tbl,
+ uint32_t index) {
+ /* Static table comes first, just return an entry from it.
+ NB: This imposes the constraint that the first
+ GRPC_CHTTP2_LAST_STATIC_ENTRY entries in the core static metadata table
+ must follow the hpack standard. If that changes, we *must* not rely on
+ reading the core static metadata table here; at that point we'd need our
+ own singleton static metadata in the correct order. */
+ if (index <= GRPC_CHTTP2_LAST_STATIC_ENTRY) {
+ return grpc_static_mdelem_manifested()[index - 1];
+ } else {
+ if (take_ref) {
+ return grpc_chttp2_hptbl_lookup_ref_dynamic_index(tbl, index);
+ } else {
+ return grpc_chttp2_hptbl_lookup_dynamic_index(tbl, index);
+ }
+ }
+}
/* add a table entry to the index */
grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl,
grpc_mdelem md) GRPC_MUST_USE_RESULT;
@@ -126,15 +126,15 @@ size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem,
/* Returns the static hpack table index that corresponds to /a elem. Returns 0
if /a elem is not statically stored or if it is not in the static hpack
table */
-inline uintptr_t grpc_chttp2_get_static_hpack_table_index(grpc_mdelem md) {
- uintptr_t index =
- reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(md)) -
- grpc_static_mdelem_table();
- if (index < GRPC_CHTTP2_LAST_STATIC_ENTRY) {
- return index + 1; // Hpack static metadata element indices start at 1
- }
- return 0;
-}
+inline uintptr_t grpc_chttp2_get_static_hpack_table_index(grpc_mdelem md) {
+ uintptr_t index =
+ reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(md)) -
+ grpc_static_mdelem_table();
+ if (index < GRPC_CHTTP2_LAST_STATIC_ENTRY) {
+ return index + 1; // Hpack static metadata element indices start at 1
+ }
+ return 0;
+}
/* Find a key/value pair in the table... returns the index in the table of the
most similar entry, or 0 if the value was not found */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc
index d04630d726..79325277e4 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc
@@ -30,16 +30,16 @@
grpc_error* grpc_chttp2_incoming_metadata_buffer_add(
grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) {
buffer->size += GRPC_MDELEM_LENGTH(elem);
- grpc_linked_mdelem* storage;
- if (buffer->count < buffer->kPreallocatedMDElem) {
- storage = &buffer->preallocated_mdelems[buffer->count];
- buffer->count++;
- } else {
- storage = static_cast<grpc_linked_mdelem*>(
- buffer->arena->Alloc(sizeof(grpc_linked_mdelem)));
- }
- storage->md = elem;
- return grpc_metadata_batch_link_tail(&buffer->batch, storage);
+ grpc_linked_mdelem* storage;
+ if (buffer->count < buffer->kPreallocatedMDElem) {
+ storage = &buffer->preallocated_mdelems[buffer->count];
+ buffer->count++;
+ } else {
+ storage = static_cast<grpc_linked_mdelem*>(
+ buffer->arena->Alloc(sizeof(grpc_linked_mdelem)));
+ }
+ storage->md = elem;
+ return grpc_metadata_batch_link_tail(&buffer->batch, storage);
}
grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add(
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h
index b63caa1ae2..4dd627a59a 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h
@@ -24,8 +24,8 @@
#include "src/core/lib/transport/transport.h"
struct grpc_chttp2_incoming_metadata_buffer {
- explicit grpc_chttp2_incoming_metadata_buffer(grpc_core::Arena* arena)
- : arena(arena) {
+ explicit grpc_chttp2_incoming_metadata_buffer(grpc_core::Arena* arena)
+ : arena(arena) {
grpc_metadata_batch_init(&batch);
batch.deadline = GRPC_MILLIS_INF_FUTURE;
}
@@ -33,13 +33,13 @@ struct grpc_chttp2_incoming_metadata_buffer {
grpc_metadata_batch_destroy(&batch);
}
- static constexpr size_t kPreallocatedMDElem = 10;
-
- grpc_core::Arena* arena;
- size_t size = 0; // total size of metadata.
- size_t count = 0; // minimum of count of metadata and kPreallocatedMDElem.
- // These preallocated mdelems are used while count < kPreallocatedMDElem.
- grpc_linked_mdelem preallocated_mdelems[kPreallocatedMDElem];
+ static constexpr size_t kPreallocatedMDElem = 10;
+
+ grpc_core::Arena* arena;
+ size_t size = 0; // total size of metadata.
+ size_t count = 0; // minimum of count of metadata and kPreallocatedMDElem.
+ // These preallocated mdelems are used while count < kPreallocatedMDElem.
+ grpc_linked_mdelem preallocated_mdelems[kPreallocatedMDElem];
grpc_metadata_batch batch;
};
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h
index 2f028c08f3..0fcd8e7545 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h
@@ -224,27 +224,27 @@ class Chttp2IncomingByteStream : public ByteStream {
// TODO(roth): When I converted this class to C++, I wanted to make it
// inherit from RefCounted or InternallyRefCounted instead of continuing
// to use its own custom ref-counting code. However, that would require
- // using multiple inheritance, which sucks in general. And to make matters
+ // using multiple inheritance, which sucks in general. And to make matters
// worse, it causes problems with our New<> and Delete<> wrappers.
// Specifically, unless RefCounted is first in the list of parent classes,
// it will see a different value of the address of the object than the one
// we actually allocated, in which case gpr_free() will be called on a
// different address than the one we got from gpr_malloc(), thus causing a
// crash. Given the fragility of depending on that, as well as a desire to
- // avoid multiple inheritance in general, I've decided to leave this
+ // avoid multiple inheritance in general, I've decided to leave this
// alone for now. We can revisit this once we're able to link against
// libc++, at which point we can eliminate New<> and Delete<> and
// switch to std::shared_ptr<>.
void Ref() { refs_.Ref(); }
void Unref() {
- if (GPR_UNLIKELY(refs_.Unref())) {
- delete this;
+ if (GPR_UNLIKELY(refs_.Unref())) {
+ delete this;
}
}
void PublishError(grpc_error* error);
- grpc_error* Push(const grpc_slice& slice, grpc_slice* slice_out);
+ grpc_error* Push(const grpc_slice& slice, grpc_slice* slice_out);
grpc_error* Finished(grpc_error* error, bool reset_on_error);
@@ -299,7 +299,7 @@ struct grpc_chttp2_transport {
grpc_resource_user* resource_user;
- grpc_core::Combiner* combiner;
+ grpc_core::Combiner* combiner;
grpc_closure* notify_on_receive_settings = nullptr;
@@ -334,13 +334,13 @@ struct grpc_chttp2_transport {
publish the accepted server stream */
grpc_chttp2_stream** accepting_stream = nullptr;
- /* accept stream callback */
- void (*accept_stream_cb)(void* user_data, grpc_transport* transport,
- const void* server_data);
- void* accept_stream_cb_user_data;
+ /* accept stream callback */
+ void (*accept_stream_cb)(void* user_data, grpc_transport* transport,
+ const void* server_data);
+ void* accept_stream_cb_user_data;
- /** connectivity tracking */
- grpc_core::ConnectivityStateTracker state_tracker;
+ /** connectivity tracking */
+ grpc_core::ConnectivityStateTracker state_tracker;
/** data to write now */
grpc_slice_buffer outbuf;
@@ -429,8 +429,8 @@ struct grpc_chttp2_transport {
void* parser_data = nullptr;
grpc_chttp2_stream* incoming_stream = nullptr;
grpc_error* (*parser)(void* parser_user_data, grpc_chttp2_transport* t,
- grpc_chttp2_stream* s, const grpc_slice& slice,
- int is_last);
+ grpc_chttp2_stream* s, const grpc_slice& slice,
+ int is_last);
grpc_chttp2_write_cb* write_cb_pool = nullptr;
@@ -460,8 +460,8 @@ struct grpc_chttp2_transport {
/* next bdp ping timer */
bool have_next_bdp_ping_timer = false;
- /** If start_bdp_ping_locked has been called */
- bool bdp_ping_started = false;
+ /** If start_bdp_ping_locked has been called */
+ bool bdp_ping_started = false;
grpc_timer next_bdp_ping_timer;
/* keep-alive ping support */
@@ -483,43 +483,43 @@ struct grpc_chttp2_transport {
grpc_millis keepalive_timeout;
/** if keepalive pings are allowed when there's no outstanding streams */
bool keepalive_permit_without_calls = false;
- /** If start_keepalive_ping_locked has been called */
- bool keepalive_ping_started = false;
+ /** If start_keepalive_ping_locked has been called */
+ bool keepalive_ping_started = false;
/** keep-alive state machine state */
grpc_chttp2_keepalive_state keepalive_state;
grpc_core::ContextList* cl = nullptr;
grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> channelz_socket;
uint32_t num_messages_in_next_write = 0;
- /** The number of pending induced frames (SETTINGS_ACK, PINGS_ACK and
- * RST_STREAM) in the outgoing buffer (t->qbuf). If this number goes beyond
- * DEFAULT_MAX_PENDING_INDUCED_FRAMES, we pause reading new frames. We would
- * only continue reading when we are able to write to the socket again,
- * thereby reducing the number of induced frames. */
- uint32_t num_pending_induced_frames = 0;
- bool reading_paused_on_pending_induced_frames = false;
+ /** The number of pending induced frames (SETTINGS_ACK, PINGS_ACK and
+ * RST_STREAM) in the outgoing buffer (t->qbuf). If this number goes beyond
+ * DEFAULT_MAX_PENDING_INDUCED_FRAMES, we pause reading new frames. We would
+ * only continue reading when we are able to write to the socket again,
+ * thereby reducing the number of induced frames. */
+ uint32_t num_pending_induced_frames = 0;
+ bool reading_paused_on_pending_induced_frames = false;
};
typedef enum {
GRPC_METADATA_NOT_PUBLISHED,
GRPC_METADATA_SYNTHESIZED_FROM_FAKE,
GRPC_METADATA_PUBLISHED_FROM_WIRE,
- GRPC_METADATA_PUBLISHED_AT_CLOSE
+ GRPC_METADATA_PUBLISHED_AT_CLOSE
} grpc_published_metadata_method;
struct grpc_chttp2_stream {
grpc_chttp2_stream(grpc_chttp2_transport* t, grpc_stream_refcount* refcount,
- const void* server_data, grpc_core::Arena* arena);
+ const void* server_data, grpc_core::Arena* arena);
~grpc_chttp2_stream();
void* context;
grpc_chttp2_transport* t;
grpc_stream_refcount* refcount;
- // Reffer is a 0-len structure, simply reffing `t` and `refcount` in its ctor
- // before initializing the rest of the stream, to avoid cache misses. This
- // field MUST be right after `t` and `refcount`.
- struct Reffer {
- explicit Reffer(grpc_chttp2_stream* s);
- } reffer;
+ // Reffer is a 0-len structure, simply reffing `t` and `refcount` in its ctor
+ // before initializing the rest of the stream, to avoid cache misses. This
+ // field MUST be right after `t` and `refcount`.
+ struct Reffer {
+ explicit Reffer(grpc_chttp2_stream* s);
+ } reffer;
grpc_closure destroy_stream;
grpc_closure* destroy_stream_arg;
@@ -599,10 +599,10 @@ struct grpc_chttp2_stream {
// application threads are allowed to modify
// unprocessed_incoming_frames_buffer
size_t unprocessed_incoming_frames_buffer_cached_length = 0;
- /* Accessed only by transport thread when stream->pending_byte_stream == false
- * Accessed only by application thread when stream->pending_byte_stream ==
- * true */
- grpc_slice_buffer unprocessed_incoming_frames_buffer;
+ /* Accessed only by transport thread when stream->pending_byte_stream == false
+ * Accessed only by application thread when stream->pending_byte_stream ==
+ * true */
+ grpc_slice_buffer unprocessed_incoming_frames_buffer;
grpc_closure reset_byte_stream;
grpc_error* byte_stream_error = GRPC_ERROR_NONE; /* protected by t combiner */
bool received_last_frame = false; /* protected by t combiner */
@@ -642,7 +642,7 @@ struct grpc_chttp2_stream {
GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS;
/* Stream decompression method to be used. */
grpc_stream_compression_method stream_decompression_method =
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
/** Whether bytes stored in unprocessed_incoming_byte_stream is decompressed
*/
@@ -653,22 +653,22 @@ struct grpc_chttp2_stream {
size_t decompressed_header_bytes = 0;
/** Byte counter for number of bytes written */
size_t byte_counter = 0;
-
- /** Amount of uncompressed bytes sent out when compressed_data_buffer is
- * emptied */
- size_t uncompressed_data_size;
- /** Stream compression compress context */
- grpc_stream_compression_context* stream_compression_ctx;
- /** Buffer storing data that is compressed but not sent */
- grpc_slice_buffer compressed_data_buffer;
-
- /** Stream compression decompress context */
- grpc_stream_compression_context* stream_decompression_ctx;
- /** Temporary buffer storing decompressed data.
- * Initialized, used, and destroyed only when stream uses (non-identity)
- * compression.
- */
- grpc_slice_buffer decompressed_data_buffer;
+
+ /** Amount of uncompressed bytes sent out when compressed_data_buffer is
+ * emptied */
+ size_t uncompressed_data_size;
+ /** Stream compression compress context */
+ grpc_stream_compression_context* stream_compression_ctx;
+ /** Buffer storing data that is compressed but not sent */
+ grpc_slice_buffer compressed_data_buffer;
+
+ /** Stream compression decompress context */
+ grpc_stream_compression_context* stream_decompression_ctx;
+ /** Temporary buffer storing decompressed data.
+ * Initialized, used, and destroyed only when stream uses (non-identity)
+ * compression.
+ */
+ grpc_slice_buffer decompressed_data_buffer;
};
/** Transport writing call flow:
@@ -701,7 +701,7 @@ void grpc_chttp2_end_write(grpc_chttp2_transport* t, grpc_error* error);
/** Process one slice of incoming data; return 1 if the connection is still
viable after reading, or 0 if the connection should be torn down */
grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
- const grpc_slice& slice);
+ const grpc_slice& slice);
bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t,
grpc_chttp2_stream* s);
@@ -753,18 +753,18 @@ void grpc_chttp2_act_on_flowctl_action(
/********* End of Flow Control ***************/
-inline grpc_chttp2_stream* grpc_chttp2_parsing_lookup_stream(
- grpc_chttp2_transport* t, uint32_t id) {
- return static_cast<grpc_chttp2_stream*>(
- grpc_chttp2_stream_map_find(&t->stream_map, id));
-}
+inline grpc_chttp2_stream* grpc_chttp2_parsing_lookup_stream(
+ grpc_chttp2_transport* t, uint32_t id) {
+ return static_cast<grpc_chttp2_stream*>(
+ grpc_chttp2_stream_map_find(&t->stream_map, id));
+}
grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
uint32_t id);
void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
uint32_t goaway_error,
- uint32_t last_stream_id,
- const grpc_slice& goaway_text);
+ uint32_t last_stream_id,
+ const grpc_slice& goaway_text);
void grpc_chttp2_parsing_become_skip_parser(grpc_chttp2_transport* t);
@@ -783,12 +783,12 @@ void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
// extern grpc_core::TraceFlag grpc_http_trace;
// extern grpc_core::TraceFlag grpc_flowctl_trace;
-#define GRPC_CHTTP2_IF_TRACING(stmt) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) { \
- (stmt); \
- } \
- } while (0)
+#define GRPC_CHTTP2_IF_TRACING(stmt) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) { \
+ (stmt); \
+ } \
+ } while (0)
void grpc_chttp2_fake_status(grpc_chttp2_transport* t,
grpc_chttp2_stream* stream, grpc_error* error);
@@ -821,7 +821,7 @@ inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t,
const char* reason, const char* file,
int line) {
if (t->refs.Unref(grpc_core::DebugLocation(file, line), reason)) {
- delete t;
+ delete t;
}
}
inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t,
@@ -834,7 +834,7 @@ inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t,
#define GRPC_CHTTP2_UNREF_TRANSPORT(t, r) grpc_chttp2_unref_transport(t)
inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t) {
if (t->refs.Unref()) {
- delete t;
+ delete t;
}
}
inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t) {
@@ -879,8 +879,8 @@ void grpc_chttp2_fail_pending_writes(grpc_chttp2_transport* t,
void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args,
bool is_client);
-void grpc_chttp2_retry_initiate_ping(void* tp, grpc_error* error);
-
+void grpc_chttp2_retry_initiate_ping(void* tp, grpc_error* error);
+
void schedule_bdp_ping_locked(grpc_chttp2_transport* t);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_INTERNAL_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc
index 741d72041b..2f480eb940 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc
@@ -30,7 +30,7 @@
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/slice/slice_utils.h"
#include "src/core/lib/transport/http2_errors.h"
#include "src/core/lib/transport/static_metadata.h"
#include "src/core/lib/transport/status_conversion.h"
@@ -48,14 +48,14 @@ static grpc_error* init_goaway_parser(grpc_chttp2_transport* t);
static grpc_error* init_skip_frame_parser(grpc_chttp2_transport* t,
int is_header);
-static grpc_error* parse_frame_slice(grpc_chttp2_transport* t,
- const grpc_slice& slice, int is_last);
+static grpc_error* parse_frame_slice(grpc_chttp2_transport* t,
+ const grpc_slice& slice, int is_last);
grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
- const grpc_slice& slice) {
- const uint8_t* beg = GRPC_SLICE_START_PTR(slice);
- const uint8_t* end = GRPC_SLICE_END_PTR(slice);
- const uint8_t* cur = beg;
+ const grpc_slice& slice) {
+ const uint8_t* beg = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* cur = beg;
grpc_error* err;
if (cur == end) return GRPC_ERROR_NONE;
@@ -107,7 +107,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
/* fallthrough */
dts_fh_0:
case GRPC_DTS_FH_0:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_frame_size = (static_cast<uint32_t>(*cur)) << 16;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_1;
@@ -115,7 +115,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_1:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_frame_size |= (static_cast<uint32_t>(*cur)) << 8;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_2;
@@ -123,7 +123,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_2:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_frame_size |= *cur;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_3;
@@ -131,7 +131,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_3:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_frame_type = *cur;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_4;
@@ -139,7 +139,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_4:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_frame_flags = *cur;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_5;
@@ -147,7 +147,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_5:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_stream_id = ((static_cast<uint32_t>(*cur)) & 0x7f) << 24;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_6;
@@ -155,7 +155,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_6:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 16;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_7;
@@ -163,7 +163,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_7:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 8;
if (++cur == end) {
t->deframe_state = GRPC_DTS_FH_8;
@@ -171,7 +171,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FH_8:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
t->incoming_stream_id |= (static_cast<uint32_t>(*cur));
t->deframe_state = GRPC_DTS_FRAME;
err = init_frame_parser(t);
@@ -205,7 +205,7 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
}
/* fallthrough */
case GRPC_DTS_FRAME:
- GPR_DEBUG_ASSERT(cur < end);
+ GPR_DEBUG_ASSERT(cur < end);
if (static_cast<uint32_t>(end - cur) == t->incoming_frame_size) {
err = parse_frame_slice(
t,
@@ -295,23 +295,23 @@ static grpc_error* init_frame_parser(grpc_chttp2_transport* t) {
case GRPC_CHTTP2_FRAME_GOAWAY:
return init_goaway_parser(t);
default:
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_ERROR, "Unknown frame type %02x", t->incoming_frame_type);
}
return init_skip_frame_parser(t, 0);
}
}
-static grpc_error* skip_parser(void* /*parser*/, grpc_chttp2_transport* /*t*/,
- grpc_chttp2_stream* /*s*/,
- const grpc_slice& /*slice*/, int /*is_last*/) {
+static grpc_error* skip_parser(void* /*parser*/, grpc_chttp2_transport* /*t*/,
+ grpc_chttp2_stream* /*s*/,
+ const grpc_slice& /*slice*/, int /*is_last*/) {
return GRPC_ERROR_NONE;
}
-static grpc_error* skip_header(void* /*tp*/, grpc_mdelem md) {
- GRPC_MDELEM_UNREF(md);
- return GRPC_ERROR_NONE;
-}
+static grpc_error* skip_header(void* /*tp*/, grpc_mdelem md) {
+ GRPC_MDELEM_UNREF(md);
+ return GRPC_ERROR_NONE;
+}
static grpc_error* init_skip_frame_parser(grpc_chttp2_transport* t,
int is_header) {
@@ -385,9 +385,9 @@ error_handler:
if (s != nullptr) {
grpc_chttp2_mark_stream_closed(t, s, true, false, err);
}
- grpc_chttp2_add_rst_stream_to_next_write(t, t->incoming_stream_id,
- GRPC_HTTP2_PROTOCOL_ERROR,
- &s->stats.outgoing);
+ grpc_chttp2_add_rst_stream_to_next_write(t, t->incoming_stream_id,
+ GRPC_HTTP2_PROTOCOL_ERROR,
+ &s->stats.outgoing);
return init_skip_frame_parser(t, 0);
} else {
return err;
@@ -396,123 +396,123 @@ error_handler:
static void free_timeout(void* p) { gpr_free(p); }
-static bool md_key_cmp(grpc_mdelem md, const grpc_slice& reference) {
- GPR_DEBUG_ASSERT(grpc_slice_is_interned(GRPC_MDKEY(md)));
- return GRPC_MDKEY(md).refcount == reference.refcount;
-}
-
-static void GPR_ATTRIBUTE_NOINLINE on_initial_header_log(
- grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_mdelem md) {
- char* key = grpc_slice_to_c_string(GRPC_MDKEY(md));
- char* value =
- grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII);
- gpr_log(GPR_INFO, "HTTP:%d:HDR:%s: %s: %s", s->id,
- t->is_client ? "CLI" : "SVR", key, value);
- gpr_free(key);
- gpr_free(value);
-}
-
-static grpc_error* GPR_ATTRIBUTE_NOINLINE handle_timeout(grpc_chttp2_stream* s,
- grpc_mdelem md) {
- grpc_millis* cached_timeout =
- static_cast<grpc_millis*>(grpc_mdelem_get_user_data(md, free_timeout));
- grpc_millis timeout;
- if (cached_timeout != nullptr) {
- timeout = *cached_timeout;
- } else {
- if (GPR_UNLIKELY(!grpc_http2_decode_timeout(GRPC_MDVALUE(md), &timeout))) {
- char* val = grpc_slice_to_c_string(GRPC_MDVALUE(md));
- gpr_log(GPR_ERROR, "Ignoring bad timeout value '%s'", val);
- gpr_free(val);
- timeout = GRPC_MILLIS_INF_FUTURE;
- }
- if (GRPC_MDELEM_IS_INTERNED(md)) {
- /* store the result */
- cached_timeout =
- static_cast<grpc_millis*>(gpr_malloc(sizeof(grpc_millis)));
- *cached_timeout = timeout;
- grpc_mdelem_set_user_data(md, free_timeout, cached_timeout);
- }
- }
- if (timeout != GRPC_MILLIS_INF_FUTURE) {
- grpc_chttp2_incoming_metadata_buffer_set_deadline(
- &s->metadata_buffer[0], grpc_core::ExecCtx::Get()->Now() + timeout);
- }
- GRPC_MDELEM_UNREF(md);
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* GPR_ATTRIBUTE_NOINLINE handle_metadata_size_limit_exceeded(
- grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_mdelem md,
- size_t new_size, size_t metadata_size_limit) {
- gpr_log(GPR_DEBUG,
- "received initial metadata size exceeds limit (%" PRIuPTR
+static bool md_key_cmp(grpc_mdelem md, const grpc_slice& reference) {
+ GPR_DEBUG_ASSERT(grpc_slice_is_interned(GRPC_MDKEY(md)));
+ return GRPC_MDKEY(md).refcount == reference.refcount;
+}
+
+static void GPR_ATTRIBUTE_NOINLINE on_initial_header_log(
+ grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_mdelem md) {
+ char* key = grpc_slice_to_c_string(GRPC_MDKEY(md));
+ char* value =
+ grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII);
+ gpr_log(GPR_INFO, "HTTP:%d:HDR:%s: %s: %s", s->id,
+ t->is_client ? "CLI" : "SVR", key, value);
+ gpr_free(key);
+ gpr_free(value);
+}
+
+static grpc_error* GPR_ATTRIBUTE_NOINLINE handle_timeout(grpc_chttp2_stream* s,
+ grpc_mdelem md) {
+ grpc_millis* cached_timeout =
+ static_cast<grpc_millis*>(grpc_mdelem_get_user_data(md, free_timeout));
+ grpc_millis timeout;
+ if (cached_timeout != nullptr) {
+ timeout = *cached_timeout;
+ } else {
+ if (GPR_UNLIKELY(!grpc_http2_decode_timeout(GRPC_MDVALUE(md), &timeout))) {
+ char* val = grpc_slice_to_c_string(GRPC_MDVALUE(md));
+ gpr_log(GPR_ERROR, "Ignoring bad timeout value '%s'", val);
+ gpr_free(val);
+ timeout = GRPC_MILLIS_INF_FUTURE;
+ }
+ if (GRPC_MDELEM_IS_INTERNED(md)) {
+ /* store the result */
+ cached_timeout =
+ static_cast<grpc_millis*>(gpr_malloc(sizeof(grpc_millis)));
+ *cached_timeout = timeout;
+ grpc_mdelem_set_user_data(md, free_timeout, cached_timeout);
+ }
+ }
+ if (timeout != GRPC_MILLIS_INF_FUTURE) {
+ grpc_chttp2_incoming_metadata_buffer_set_deadline(
+ &s->metadata_buffer[0], grpc_core::ExecCtx::Get()->Now() + timeout);
+ }
+ GRPC_MDELEM_UNREF(md);
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* GPR_ATTRIBUTE_NOINLINE handle_metadata_size_limit_exceeded(
+ grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_mdelem md,
+ size_t new_size, size_t metadata_size_limit) {
+ gpr_log(GPR_DEBUG,
+ "received initial metadata size exceeds limit (%" PRIuPTR
" vs. %" PRIuPTR
"). GRPC_ARG_MAX_METADATA_SIZE can be set to increase this limit.",
- new_size, metadata_size_limit);
- grpc_chttp2_cancel_stream(
- t, s,
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "received initial metadata size exceeds limit"),
- GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_RESOURCE_EXHAUSTED));
- grpc_chttp2_parsing_become_skip_parser(t);
- s->seen_error = true;
- GRPC_MDELEM_UNREF(md);
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* GPR_ATTRIBUTE_NOINLINE
-handle_metadata_add_failure(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_mdelem md, grpc_error* error) {
- grpc_chttp2_cancel_stream(t, s, error);
- grpc_chttp2_parsing_become_skip_parser(t);
- s->seen_error = true;
- GRPC_MDELEM_UNREF(md);
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* on_initial_header(void* tp, grpc_mdelem md) {
+ new_size, metadata_size_limit);
+ grpc_chttp2_cancel_stream(
+ t, s,
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "received initial metadata size exceeds limit"),
+ GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_RESOURCE_EXHAUSTED));
+ grpc_chttp2_parsing_become_skip_parser(t);
+ s->seen_error = true;
+ GRPC_MDELEM_UNREF(md);
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* GPR_ATTRIBUTE_NOINLINE
+handle_metadata_add_failure(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_mdelem md, grpc_error* error) {
+ grpc_chttp2_cancel_stream(t, s, error);
+ grpc_chttp2_parsing_become_skip_parser(t);
+ s->seen_error = true;
+ GRPC_MDELEM_UNREF(md);
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* on_initial_header(void* tp, grpc_mdelem md) {
GPR_TIMER_SCOPE("on_initial_header", 0);
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
grpc_chttp2_stream* s = t->incoming_stream;
- GPR_DEBUG_ASSERT(s != nullptr);
+ GPR_DEBUG_ASSERT(s != nullptr);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
- on_initial_header_log(t, s, md);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ on_initial_header_log(t, s, md);
}
if (md_key_cmp(md, GRPC_MDSTR_GRPC_TIMEOUT)) {
- return handle_timeout(s, md);
+ return handle_timeout(s, md);
}
const size_t new_size = s->metadata_buffer[0].size + GRPC_MDELEM_LENGTH(md);
const size_t metadata_size_limit =
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE];
- if (GPR_UNLIKELY(new_size > metadata_size_limit)) {
- return handle_metadata_size_limit_exceeded(t, s, md, new_size,
- metadata_size_limit);
+ if (GPR_UNLIKELY(new_size > metadata_size_limit)) {
+ return handle_metadata_size_limit_exceeded(t, s, md, new_size,
+ metadata_size_limit);
} else {
grpc_error* error =
grpc_chttp2_incoming_metadata_buffer_add(&s->metadata_buffer[0], md);
- if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
- return handle_metadata_add_failure(t, s, md, error);
+ if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
+ return handle_metadata_add_failure(t, s, md, error);
}
}
- // Not timeout-related metadata, and no error occurred.
- return GRPC_ERROR_NONE;
+ // Not timeout-related metadata, and no error occurred.
+ return GRPC_ERROR_NONE;
}
-static grpc_error* on_trailing_header(void* tp, grpc_mdelem md) {
+static grpc_error* on_trailing_header(void* tp, grpc_mdelem md) {
GPR_TIMER_SCOPE("on_trailing_header", 0);
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
grpc_chttp2_stream* s = t->incoming_stream;
- GPR_DEBUG_ASSERT(s != nullptr);
+ GPR_DEBUG_ASSERT(s != nullptr);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
char* key = grpc_slice_to_c_string(GRPC_MDKEY(md));
char* value =
grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII);
@@ -553,7 +553,7 @@ static grpc_error* on_trailing_header(void* tp, grpc_mdelem md) {
GRPC_MDELEM_UNREF(md);
}
}
- return GRPC_ERROR_NONE;
+ return GRPC_ERROR_NONE;
}
static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t,
@@ -633,7 +633,7 @@ static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t,
} else {
t->incoming_stream = s;
}
- GPR_DEBUG_ASSERT(s != nullptr);
+ GPR_DEBUG_ASSERT(s != nullptr);
s->stats.incoming.framing_bytes += 9;
if (GPR_UNLIKELY(s->read_closed)) {
GRPC_CHTTP2_IF_TRACING(gpr_log(
@@ -754,24 +754,24 @@ static grpc_error* init_settings_frame_parser(grpc_chttp2_transport* t) {
return GRPC_ERROR_NONE;
}
-static grpc_error* parse_frame_slice(grpc_chttp2_transport* t,
- const grpc_slice& slice, int is_last) {
+static grpc_error* parse_frame_slice(grpc_chttp2_transport* t,
+ const grpc_slice& slice, int is_last) {
grpc_chttp2_stream* s = t->incoming_stream;
grpc_error* err = t->parser(t->parser_data, t, s, slice, is_last);
intptr_t unused;
if (GPR_LIKELY(err == GRPC_ERROR_NONE)) {
return err;
} else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
const char* msg = grpc_error_string(err);
gpr_log(GPR_ERROR, "%s", msg);
}
grpc_chttp2_parsing_become_skip_parser(t);
if (s) {
s->forced_close_error = err;
- grpc_chttp2_add_rst_stream_to_next_write(t, t->incoming_stream_id,
- GRPC_HTTP2_PROTOCOL_ERROR,
- &s->stats.outgoing);
+ grpc_chttp2_add_rst_stream_to_next_write(t, t->incoming_stream_id,
+ GRPC_HTTP2_PROTOCOL_ERROR,
+ &s->stats.outgoing);
} else {
GRPC_ERROR_UNREF(err);
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_lists.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_lists.cc
index db79899ded..a1f17748ab 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_lists.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_lists.cc
@@ -67,7 +67,7 @@ static bool stream_list_pop(grpc_chttp2_transport* t,
s->included[id] = 0;
}
*stream = s;
- if (s && GRPC_TRACE_FLAG_ENABLED(grpc_trace_http2_stream_state)) {
+ if (s && GRPC_TRACE_FLAG_ENABLED(grpc_trace_http2_stream_state)) {
gpr_log(GPR_INFO, "%p[%d][%s]: pop from %s", t, s->id,
t->is_client ? "cli" : "svr", stream_list_id_string(id));
}
@@ -89,7 +89,7 @@ static void stream_list_remove(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
} else {
t->lists[id].tail = s->links[id].prev;
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_http2_stream_state)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_http2_stream_state)) {
gpr_log(GPR_INFO, "%p[%d][%s]: remove from %s", t, s->id,
t->is_client ? "cli" : "svr", stream_list_id_string(id));
}
@@ -121,7 +121,7 @@ static void stream_list_add_tail(grpc_chttp2_transport* t,
}
t->lists[id].tail = s;
s->included[id] = 1;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_http2_stream_state)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_http2_stream_state)) {
gpr_log(GPR_INFO, "%p[%d][%s]: add to %s", t, s->id,
t->is_client ? "cli" : "svr", stream_list_id_string(id));
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.cc
index 647214b94a..8c65906312 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.cc
@@ -27,7 +27,7 @@
void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map,
size_t initial_capacity) {
- GPR_DEBUG_ASSERT(initial_capacity > 1);
+ GPR_DEBUG_ASSERT(initial_capacity > 1);
map->keys =
static_cast<uint32_t*>(gpr_malloc(sizeof(uint32_t) * initial_capacity));
map->values =
@@ -63,17 +63,17 @@ void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
uint32_t* keys = map->keys;
void** values = map->values;
- // The first assertion ensures that the table is monotonically increasing.
+ // The first assertion ensures that the table is monotonically increasing.
GPR_ASSERT(count == 0 || keys[count - 1] < key);
- GPR_DEBUG_ASSERT(value);
- // Asserting that the key is not already in the map can be a debug assertion.
- // Why: we're already checking that the map elements are monotonically
- // increasing. If we re-add a key, i.e. if the key is already present, then
- // either it is the most recently added key in the map (in which case the
- // first assertion fails due to key == last_key) or there is a more recently
- // added (larger) key at the end of the map: in which case the first assertion
- // still fails due to key < last_key.
- GPR_DEBUG_ASSERT(grpc_chttp2_stream_map_find(map, key) == nullptr);
+ GPR_DEBUG_ASSERT(value);
+ // Asserting that the key is not already in the map can be a debug assertion.
+ // Why: we're already checking that the map elements are monotonically
+ // increasing. If we re-add a key, i.e. if the key is already present, then
+ // either it is the most recently added key in the map (in which case the
+ // first assertion fails due to key == last_key) or there is a more recently
+ // added (larger) key at the end of the map: in which case the first assertion
+ // still fails due to key < last_key.
+ GPR_DEBUG_ASSERT(grpc_chttp2_stream_map_find(map, key) == nullptr);
if (count == capacity) {
if (map->free > capacity / 4) {
@@ -82,7 +82,7 @@ void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
} else {
/* resize when less than 25% of the table is free, because compaction
won't help much */
- map->capacity = capacity = 2 * capacity;
+ map->capacity = capacity = 2 * capacity;
map->keys = keys = static_cast<uint32_t*>(
gpr_realloc(keys, capacity * sizeof(uint32_t)));
map->values = values =
@@ -95,7 +95,7 @@ void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
map->count = count + 1;
}
-template <bool strict_find>
+template <bool strict_find>
static void** find(grpc_chttp2_stream_map* map, uint32_t key) {
size_t min_idx = 0;
size_t max_idx = map->count;
@@ -104,8 +104,8 @@ static void** find(grpc_chttp2_stream_map* map, uint32_t key) {
void** values = map->values;
uint32_t mid_key;
- GPR_DEBUG_ASSERT(!strict_find || max_idx > 0);
- if (!strict_find && max_idx == 0) return nullptr;
+ GPR_DEBUG_ASSERT(!strict_find || max_idx > 0);
+ if (!strict_find && max_idx == 0) return nullptr;
while (min_idx < max_idx) {
/* find the midpoint, avoiding overflow */
@@ -122,28 +122,28 @@ static void** find(grpc_chttp2_stream_map* map, uint32_t key) {
}
}
- GPR_DEBUG_ASSERT(!strict_find);
+ GPR_DEBUG_ASSERT(!strict_find);
return nullptr;
}
void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key) {
- void** pvalue = find<true>(map, key);
- GPR_DEBUG_ASSERT(pvalue != nullptr);
- void* out = *pvalue;
- GPR_DEBUG_ASSERT(out != nullptr);
- *pvalue = nullptr;
- map->free++;
- /* recognize complete emptyness and ensure we can skip
- defragmentation later */
- if (map->free == map->count) {
- map->free = map->count = 0;
+ void** pvalue = find<true>(map, key);
+ GPR_DEBUG_ASSERT(pvalue != nullptr);
+ void* out = *pvalue;
+ GPR_DEBUG_ASSERT(out != nullptr);
+ *pvalue = nullptr;
+ map->free++;
+ /* recognize complete emptyness and ensure we can skip
+ defragmentation later */
+ if (map->free == map->count) {
+ map->free = map->count = 0;
}
- GPR_DEBUG_ASSERT(grpc_chttp2_stream_map_find(map, key) == nullptr);
+ GPR_DEBUG_ASSERT(grpc_chttp2_stream_map_find(map, key) == nullptr);
return out;
}
void* grpc_chttp2_stream_map_find(grpc_chttp2_stream_map* map, uint32_t key) {
- void** pvalue = find<false>(map, key);
+ void** pvalue = find<false>(map, key);
return pvalue != nullptr ? *pvalue : nullptr;
}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc
index f8e21e8e15..890abf482e 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc
@@ -26,7 +26,7 @@
#include <grpc/support/log.h>
-#include "src/core/lib/compression/stream_compression.h"
+#include "src/core/lib/compression/stream_compression.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_internal.h"
@@ -54,7 +54,7 @@ static void maybe_initiate_ping(grpc_chttp2_transport* t) {
}
if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_INFLIGHT])) {
/* ping already in-flight: wait */
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
gpr_log(GPR_INFO, "%s: Ping delayed [%s]: already pinging",
@@ -65,7 +65,7 @@ static void maybe_initiate_ping(grpc_chttp2_transport* t) {
if (t->ping_state.pings_before_data_required == 0 &&
t->ping_policy.max_pings_without_data != 0) {
/* need to receive something of substance before sending a ping again */
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
gpr_log(GPR_INFO, "%s: Ping delayed [%s]: too many recent pings: %d/%d",
@@ -89,7 +89,7 @@ static void maybe_initiate_ping(grpc_chttp2_transport* t) {
if (next_allowed_ping > now) {
/* not enough elapsed time between successive pings */
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
gpr_log(GPR_INFO,
@@ -102,9 +102,9 @@ static void maybe_initiate_ping(grpc_chttp2_transport* t) {
if (!t->ping_state.is_delayed_ping_timer_set) {
t->ping_state.is_delayed_ping_timer_set = true;
GRPC_CHTTP2_REF_TRANSPORT(t, "retry_initiate_ping_locked");
- GRPC_CLOSURE_INIT(&t->retry_initiate_ping_locked,
- grpc_chttp2_retry_initiate_ping, t,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&t->retry_initiate_ping_locked,
+ grpc_chttp2_retry_initiate_ping, t,
+ grpc_schedule_on_exec_ctx);
grpc_timer_init(&t->ping_state.delayed_ping_timer, next_allowed_ping,
&t->retry_initiate_ping_locked);
}
@@ -113,18 +113,18 @@ static void maybe_initiate_ping(grpc_chttp2_transport* t) {
pq->inflight_id = t->ping_ctr;
t->ping_ctr++;
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION,
- &pq->lists[GRPC_CHTTP2_PCL_INITIATE]);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION,
+ &pq->lists[GRPC_CHTTP2_PCL_INITIATE]);
grpc_closure_list_move(&pq->lists[GRPC_CHTTP2_PCL_NEXT],
&pq->lists[GRPC_CHTTP2_PCL_INFLIGHT]);
grpc_slice_buffer_add(&t->outbuf,
grpc_chttp2_ping_create(false, pq->inflight_id));
GRPC_STATS_INC_HTTP2_PINGS_SENT();
t->ping_state.last_ping_sent_time = now;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
- gpr_log(GPR_INFO, "%s: Ping sent [%s]: %d/%d",
+ gpr_log(GPR_INFO, "%s: Ping sent [%s]: %d/%d",
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str(),
t->ping_state.pings_before_data_required,
t->ping_policy.max_pings_without_data);
@@ -156,7 +156,7 @@ static bool update_list(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
const char* staller) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace)) {
gpr_log(
GPR_DEBUG,
"%s:%p stream %d moved to stalled list by %s. This is FULLY expected "
@@ -167,11 +167,11 @@ static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
":s_win=%d:s_delta=%" PRId64 "]",
t->peer_string.c_str(), t, s->id, staller,
s->flow_controlled_buffer.length,
- s->stream_compression_method ==
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
- ? 0
- : s->compressed_data_buffer.length,
- s->flow_controlled_bytes_flowed,
+ s->stream_compression_method ==
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
+ ? 0
+ : s->compressed_data_buffer.length,
+ s->flow_controlled_bytes_flowed,
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE],
t->flow_control->remote_window(),
@@ -185,7 +185,7 @@ static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
}
/* How many bytes would we like to put on the wire during a single syscall */
-static uint32_t target_write_size(grpc_chttp2_transport* /*t*/) {
+static uint32_t target_write_size(grpc_chttp2_transport* /*t*/) {
return 1024 * 1024;
}
@@ -231,7 +231,7 @@ class WriteContext {
void FlushQueuedBuffers() {
/* simple writes are queued to qbuf, and flushed here */
grpc_slice_buffer_move_into(&t_->qbuf, &t_->outbuf);
- t_->num_pending_induced_frames = 0;
+ t_->num_pending_induced_frames = 0;
GPR_ASSERT(t_->qbuf.count == 0);
}
@@ -267,7 +267,7 @@ class WriteContext {
while (grpc_chttp2_list_pop_stalled_by_transport(t_, &s)) {
if (t_->closed_with_error == GRPC_ERROR_NONE &&
grpc_chttp2_list_add_writable_stream(t_, s)) {
- if (!s->refcount->refs.RefIfNonZero()) {
+ if (!s->refcount->refs.RefIfNonZero()) {
grpc_chttp2_list_remove_writable_stream(t_, s);
}
}
@@ -338,23 +338,23 @@ class DataSendContext {
bool AnyOutgoing() const { return max_outgoing() > 0; }
- void FlushUncompressedBytes() {
- uint32_t send_bytes = static_cast<uint32_t> GPR_MIN(
- max_outgoing(), s_->flow_controlled_buffer.length);
- is_last_frame_ = send_bytes == s_->flow_controlled_buffer.length &&
- s_->fetching_send_message == nullptr &&
- s_->send_trailing_metadata != nullptr &&
- grpc_metadata_batch_is_empty(s_->send_trailing_metadata);
- grpc_chttp2_encode_data(s_->id, &s_->flow_controlled_buffer, send_bytes,
- is_last_frame_, &s_->stats.outgoing, &t_->outbuf);
- s_->flow_control->SentData(send_bytes);
- s_->sending_bytes += send_bytes;
- }
-
+ void FlushUncompressedBytes() {
+ uint32_t send_bytes = static_cast<uint32_t> GPR_MIN(
+ max_outgoing(), s_->flow_controlled_buffer.length);
+ is_last_frame_ = send_bytes == s_->flow_controlled_buffer.length &&
+ s_->fetching_send_message == nullptr &&
+ s_->send_trailing_metadata != nullptr &&
+ grpc_metadata_batch_is_empty(s_->send_trailing_metadata);
+ grpc_chttp2_encode_data(s_->id, &s_->flow_controlled_buffer, send_bytes,
+ is_last_frame_, &s_->stats.outgoing, &t_->outbuf);
+ s_->flow_control->SentData(send_bytes);
+ s_->sending_bytes += send_bytes;
+ }
+
void FlushCompressedBytes() {
- GPR_DEBUG_ASSERT(s_->stream_compression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS);
-
+ GPR_DEBUG_ASSERT(s_->stream_compression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS);
+
uint32_t send_bytes = static_cast<uint32_t> GPR_MIN(
max_outgoing(), s_->compressed_data_buffer.length);
bool is_last_data_frame =
@@ -389,9 +389,9 @@ class DataSendContext {
}
void CompressMoreBytes() {
- GPR_DEBUG_ASSERT(s_->stream_compression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS);
-
+ GPR_DEBUG_ASSERT(s_->stream_compression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS);
+
if (s_->stream_compression_ctx == nullptr) {
s_->stream_compression_ctx =
grpc_stream_compression_context_create(s_->stream_compression_method);
@@ -449,7 +449,7 @@ class StreamWriteContext {
// https://github.com/grpc/proposal/blob/master/A6-client-retries.md#when-retries-are-valid
if (!t_->is_client && s_->fetching_send_message == nullptr &&
s_->flow_controlled_buffer.length == 0 &&
- compressed_data_buffer_len() == 0 &&
+ compressed_data_buffer_len() == 0 &&
s_->send_trailing_metadata != nullptr &&
is_default_initial_metadata(s_->send_initial_metadata)) {
ConvertInitialMetadataToTrailingMetadata();
@@ -479,12 +479,12 @@ class StreamWriteContext {
}
size_t compressed_data_buffer_len() {
- return s_->stream_compression_method ==
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
- ? 0
- : s_->compressed_data_buffer.length;
- }
-
+ return s_->stream_compression_method ==
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
+ ? 0
+ : s_->compressed_data_buffer.length;
+ }
+
void FlushWindowUpdates() {
/* send any window updates */
const uint32_t stream_announce = s_->flow_control->MaybeSendUpdate();
@@ -501,7 +501,7 @@ class StreamWriteContext {
if (!s_->sent_initial_metadata) return;
if (s_->flow_controlled_buffer.length == 0 &&
- compressed_data_buffer_len() == 0) {
+ compressed_data_buffer_len() == 0) {
return; // early out: nothing to do
}
@@ -518,22 +518,22 @@ class StreamWriteContext {
return; // early out: nothing to do
}
- if (s_->stream_compression_method ==
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) {
- while (s_->flow_controlled_buffer.length > 0 &&
- data_send_context.max_outgoing() > 0) {
- data_send_context.FlushUncompressedBytes();
- }
- } else {
- while ((s_->flow_controlled_buffer.length > 0 ||
- s_->compressed_data_buffer.length > 0) &&
- data_send_context.max_outgoing() > 0) {
- if (s_->compressed_data_buffer.length > 0) {
- data_send_context.FlushCompressedBytes();
- } else {
- data_send_context.CompressMoreBytes();
- }
+ if (s_->stream_compression_method ==
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) {
+ while (s_->flow_controlled_buffer.length > 0 &&
+ data_send_context.max_outgoing() > 0) {
+ data_send_context.FlushUncompressedBytes();
}
+ } else {
+ while ((s_->flow_controlled_buffer.length > 0 ||
+ s_->compressed_data_buffer.length > 0) &&
+ data_send_context.max_outgoing() > 0) {
+ if (s_->compressed_data_buffer.length > 0) {
+ data_send_context.FlushCompressedBytes();
+ } else {
+ data_send_context.CompressMoreBytes();
+ }
+ }
}
grpc_chttp2_reset_ping_clock(t_);
if (data_send_context.is_last_frame()) {
@@ -542,7 +542,7 @@ class StreamWriteContext {
data_send_context.CallCallbacks();
stream_became_writable_ = true;
if (s_->flow_controlled_buffer.length > 0 ||
- compressed_data_buffer_len() > 0) {
+ compressed_data_buffer_len() > 0) {
GRPC_CHTTP2_STREAM_REF(s_, "chttp2_writing:fork");
grpc_chttp2_list_add_writable_stream(t_, s_);
}
@@ -555,7 +555,7 @@ class StreamWriteContext {
if (s_->send_trailing_metadata == nullptr) return;
if (s_->fetching_send_message != nullptr) return;
if (s_->flow_controlled_buffer.length != 0) return;
- if (compressed_data_buffer_len() != 0) return;
+ if (compressed_data_buffer_len() != 0) return;
GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "sending trailing_metadata"));
if (grpc_metadata_batch_is_empty(s_->send_trailing_metadata)) {
diff --git a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc
index 728831f364..1e529c998f 100644
--- a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc
@@ -35,11 +35,11 @@
#include "src/core/lib/transport/error_utils.h"
#include "src/core/lib/transport/transport_impl.h"
-#define INPROC_LOG(...) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) { \
- gpr_log(__VA_ARGS__); \
- } \
+#define INPROC_LOG(...) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) { \
+ gpr_log(__VA_ARGS__); \
+ } \
} while (0)
namespace {
@@ -67,8 +67,8 @@ struct shared_mu {
gpr_ref_init(&refs, 2);
}
- ~shared_mu() { gpr_mu_destroy(&mu); }
-
+ ~shared_mu() { gpr_mu_destroy(&mu); }
+
gpr_mu mu;
gpr_refcount refs;
};
@@ -76,10 +76,10 @@ struct shared_mu {
struct inproc_transport {
inproc_transport(const grpc_transport_vtable* vtable, shared_mu* mu,
bool is_client)
- : mu(mu),
- is_client(is_client),
- state_tracker(is_client ? "inproc_client" : "inproc_server",
- GRPC_CHANNEL_READY) {
+ : mu(mu),
+ is_client(is_client),
+ state_tracker(is_client ? "inproc_client" : "inproc_server",
+ GRPC_CHANNEL_READY) {
base.vtable = vtable;
// Start each side of transport with 2 refs since they each have a ref
// to the other
@@ -88,7 +88,7 @@ struct inproc_transport {
~inproc_transport() {
if (gpr_unref(&mu->refs)) {
- mu->~shared_mu();
+ mu->~shared_mu();
gpr_free(mu);
}
}
@@ -112,7 +112,7 @@ struct inproc_transport {
shared_mu* mu;
gpr_refcount refs;
bool is_client;
- grpc_core::ConnectivityStateTracker state_tracker;
+ grpc_core::ConnectivityStateTracker state_tracker;
void (*accept_stream_cb)(void* user_data, grpc_transport* transport,
const void* server_data);
void* accept_stream_data;
@@ -123,7 +123,7 @@ struct inproc_transport {
struct inproc_stream {
inproc_stream(inproc_transport* t, grpc_stream_refcount* refcount,
- const void* server_data, grpc_core::Arena* arena)
+ const void* server_data, grpc_core::Arena* arena)
: t(t), refs(refcount), arena(arena) {
// Ref this stream right now for ctor and list.
ref("inproc_init_stream:init");
@@ -245,7 +245,7 @@ struct inproc_stream {
bool write_buffer_other_side_closed = false; // on hold
grpc_stream_refcount* refs;
- grpc_core::Arena* arena;
+ grpc_core::Arena* arena;
grpc_transport_stream_op_batch* send_message_op = nullptr;
grpc_transport_stream_op_batch* send_trailing_md_op = nullptr;
@@ -296,7 +296,7 @@ grpc_error* fill_in_metadata(inproc_stream* s,
const grpc_metadata_batch* metadata,
uint32_t flags, grpc_metadata_batch* out_md,
uint32_t* outflags, bool* markfilled) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) {
log_metadata(metadata, s->t->is_client, outflags != nullptr);
}
@@ -309,8 +309,8 @@ grpc_error* fill_in_metadata(inproc_stream* s,
grpc_error* error = GRPC_ERROR_NONE;
for (grpc_linked_mdelem* elem = metadata->list.head;
(elem != nullptr) && (error == GRPC_ERROR_NONE); elem = elem->next) {
- grpc_linked_mdelem* nelem =
- static_cast<grpc_linked_mdelem*>(s->arena->Alloc(sizeof(*nelem)));
+ grpc_linked_mdelem* nelem =
+ static_cast<grpc_linked_mdelem*>(s->arena->Alloc(sizeof(*nelem)));
nelem->md =
grpc_mdelem_from_slices(grpc_slice_intern(GRPC_MDKEY(elem->md)),
grpc_slice_intern(GRPC_MDVALUE(elem->md)));
@@ -322,7 +322,7 @@ grpc_error* fill_in_metadata(inproc_stream* s,
int init_stream(grpc_transport* gt, grpc_stream* gs,
grpc_stream_refcount* refcount, const void* server_data,
- grpc_core::Arena* arena) {
+ grpc_core::Arena* arena) {
INPROC_LOG(GPR_INFO, "init_stream %p %p %p", gt, gs, server_data);
inproc_transport* t = reinterpret_cast<inproc_transport*>(gt);
new (gs) inproc_stream(t, refcount, server_data, arena);
@@ -388,8 +388,8 @@ void complete_if_batch_end_locked(inproc_stream* s, grpc_error* error,
if ((is_sm + is_stm + is_rim + is_rm + is_rtm) == 1) {
INPROC_LOG(GPR_INFO, "%s %p %p %p", msg, s, op, error);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_complete,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_complete,
+ GRPC_ERROR_REF(error));
}
}
@@ -436,13 +436,13 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) {
// since it expects that as well as no error yet
grpc_metadata_batch fake_md;
grpc_metadata_batch_init(&fake_md);
- grpc_linked_mdelem* path_md =
- static_cast<grpc_linked_mdelem*>(s->arena->Alloc(sizeof(*path_md)));
+ grpc_linked_mdelem* path_md =
+ static_cast<grpc_linked_mdelem*>(s->arena->Alloc(sizeof(*path_md)));
path_md->md = grpc_mdelem_from_slices(g_fake_path_key, g_fake_path_value);
GPR_ASSERT(grpc_metadata_batch_link_tail(&fake_md, path_md) ==
GRPC_ERROR_NONE);
- grpc_linked_mdelem* auth_md =
- static_cast<grpc_linked_mdelem*>(s->arena->Alloc(sizeof(*auth_md)));
+ grpc_linked_mdelem* auth_md =
+ static_cast<grpc_linked_mdelem*>(s->arena->Alloc(sizeof(*auth_md)));
auth_md->md = grpc_mdelem_from_slices(g_fake_auth_key, g_fake_auth_value);
GPR_ASSERT(grpc_metadata_batch_link_tail(&fake_md, auth_md) ==
GRPC_ERROR_NONE);
@@ -469,11 +469,11 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) {
INPROC_LOG(GPR_INFO,
"fail_helper %p scheduling initial-metadata-ready %p %p", s,
error, err);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- s->recv_initial_md_op->payload->recv_initial_metadata
- .recv_initial_metadata_ready,
- err);
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ s->recv_initial_md_op->payload->recv_initial_metadata
+ .recv_initial_metadata_ready,
+ err);
// Last use of err so no need to REF and then UNREF it
complete_if_batch_end_locked(
@@ -484,8 +484,8 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) {
if (s->recv_message_op) {
INPROC_LOG(GPR_INFO, "fail_helper %p scheduling message-ready %p", s,
error);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
s->recv_message_op->payload->recv_message.recv_message_ready,
GRPC_ERROR_REF(error));
complete_if_batch_end_locked(
@@ -509,11 +509,11 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) {
if (s->recv_trailing_md_op) {
INPROC_LOG(GPR_INFO, "fail_helper %p scheduling trailing-metadata-ready %p",
s, error);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- s->recv_trailing_md_op->payload->recv_trailing_metadata
- .recv_trailing_metadata_ready,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ s->recv_trailing_md_op->payload->recv_trailing_metadata
+ .recv_trailing_metadata_ready,
+ GRPC_ERROR_REF(error));
INPROC_LOG(GPR_INFO, "fail_helper %p scheduling trailing-md-on-complete %p",
s, error);
complete_if_batch_end_locked(
@@ -567,8 +567,8 @@ void message_transfer_locked(inproc_stream* sender, inproc_stream* receiver) {
receiver->recv_stream.get());
INPROC_LOG(GPR_INFO, "message_transfer_locked %p scheduling message-ready",
receiver);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
receiver->recv_message_op->payload->recv_message.recv_message_ready,
GRPC_ERROR_NONE);
complete_if_batch_end_locked(
@@ -657,16 +657,16 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
if (!s->t->is_client && s->trailing_md_recvd && s->recv_trailing_md_op) {
INPROC_LOG(GPR_INFO,
"op_state_machine %p scheduling trailing-metadata-ready", s);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
s->recv_trailing_md_op->payload->recv_trailing_metadata
.recv_trailing_metadata_ready,
GRPC_ERROR_NONE);
INPROC_LOG(GPR_INFO,
"op_state_machine %p scheduling trailing-md-on-complete", s);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- s->recv_trailing_md_op->on_complete,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ s->recv_trailing_md_op->on_complete,
+ GRPC_ERROR_NONE);
s->recv_trailing_md_op = nullptr;
needs_close = true;
}
@@ -711,11 +711,11 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
INPROC_LOG(GPR_INFO,
"op_state_machine %p scheduling initial-metadata-ready %p", s,
new_err);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- s->recv_initial_md_op->payload->recv_initial_metadata
- .recv_initial_metadata_ready,
- GRPC_ERROR_REF(new_err));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ s->recv_initial_md_op->payload->recv_initial_metadata
+ .recv_initial_metadata_ready,
+ GRPC_ERROR_REF(new_err));
complete_if_batch_end_locked(
s, new_err, s->recv_initial_md_op,
"op_state_machine scheduling recv-initial-metadata-on-complete");
@@ -763,8 +763,8 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
// satisfied
*s->recv_message_op->payload->recv_message.recv_message = nullptr;
INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
s->recv_message_op->payload->recv_message.recv_message_ready,
GRPC_ERROR_NONE);
complete_if_batch_end_locked(
@@ -802,14 +802,14 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
INPROC_LOG(GPR_INFO,
"op_state_machine %p scheduling trailing-md-on-complete %p",
s, new_err);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
s->recv_trailing_md_op->payload->recv_trailing_metadata
.recv_trailing_metadata_ready,
GRPC_ERROR_REF(new_err));
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- s->recv_trailing_md_op->on_complete,
- GRPC_ERROR_REF(new_err));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ s->recv_trailing_md_op->on_complete,
+ GRPC_ERROR_REF(new_err));
s->recv_trailing_md_op = nullptr;
needs_close = s->trailing_md_sent;
} else {
@@ -850,8 +850,8 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
// recv_message_op
INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s);
*s->recv_message_op->payload->recv_message.recv_message = nullptr;
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
s->recv_message_op->payload->recv_message.recv_message_ready,
GRPC_ERROR_NONE);
complete_if_batch_end_locked(
@@ -923,11 +923,11 @@ bool cancel_stream_locked(inproc_stream* s, grpc_error* error) {
// couldn't complete that because we hadn't yet sent out trailing
// md, now's the chance
if (!s->t->is_client && s->trailing_md_recvd && s->recv_trailing_md_op) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- s->recv_trailing_md_op->payload->recv_trailing_metadata
- .recv_trailing_metadata_ready,
- GRPC_ERROR_REF(s->cancel_self_error));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ s->recv_trailing_md_op->payload->recv_trailing_metadata
+ .recv_trailing_metadata_ready,
+ GRPC_ERROR_REF(s->cancel_self_error));
complete_if_batch_end_locked(
s, s->cancel_self_error, s->recv_trailing_md_op,
"cancel_stream scheduling trailing-md-on-complete");
@@ -942,7 +942,7 @@ bool cancel_stream_locked(inproc_stream* s, grpc_error* error) {
return ret;
}
-void do_nothing(void* /*arg*/, grpc_error* /*error*/) {}
+void do_nothing(void* /*arg*/, grpc_error* /*error*/) {}
void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
grpc_transport_stream_op_batch* op) {
@@ -951,7 +951,7 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
gpr_mu* mu = &s->t->mu->mu; // save aside in case s gets closed
gpr_mu_lock(mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) {
if (op->send_initial_metadata) {
log_metadata(op->payload->send_initial_metadata.send_initial_metadata,
s->t->is_client, true);
@@ -1071,11 +1071,11 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
}
} else {
if (error != GRPC_ERROR_NONE) {
- // Consume any send message that was sent here but that we are not pushing
- // to the other side
- if (op->send_message) {
- op->payload->send_message.send_message.reset();
- }
+ // Consume any send message that was sent here but that we are not pushing
+ // to the other side
+ if (op->send_message) {
+ op->payload->send_message.send_message.reset();
+ }
// Schedule op's closures that we didn't push to op state machine
if (op->recv_initial_metadata) {
if (op->payload->recv_initial_metadata.trailing_metadata_available !=
@@ -1091,8 +1091,8 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
GPR_INFO,
"perform_stream_op error %p scheduling initial-metadata-ready %p",
s, error);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
op->payload->recv_initial_metadata.recv_initial_metadata_ready,
GRPC_ERROR_REF(error));
}
@@ -1101,24 +1101,24 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
GPR_INFO,
"perform_stream_op error %p scheduling recv message-ready %p", s,
error);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- op->payload->recv_message.recv_message_ready,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ op->payload->recv_message.recv_message_ready,
+ GRPC_ERROR_REF(error));
}
if (op->recv_trailing_metadata) {
INPROC_LOG(
GPR_INFO,
"perform_stream_op error %p scheduling trailing-metadata-ready %p",
s, error);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready,
GRPC_ERROR_REF(error));
}
}
INPROC_LOG(GPR_INFO, "perform_stream_op %p scheduling on_complete %p", s,
error);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_complete, GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_complete, GRPC_ERROR_REF(error));
}
gpr_mu_unlock(mu);
GRPC_ERROR_UNREF(error);
@@ -1146,19 +1146,19 @@ void perform_transport_op(grpc_transport* gt, grpc_transport_op* op) {
inproc_transport* t = reinterpret_cast<inproc_transport*>(gt);
INPROC_LOG(GPR_INFO, "perform_transport_op %p %p", t, op);
gpr_mu_lock(&t->mu->mu);
- if (op->start_connectivity_watch != nullptr) {
- t->state_tracker.AddWatcher(op->start_connectivity_watch_state,
- std::move(op->start_connectivity_watch));
- }
- if (op->stop_connectivity_watch != nullptr) {
- t->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
+ if (op->start_connectivity_watch != nullptr) {
+ t->state_tracker.AddWatcher(op->start_connectivity_watch_state,
+ std::move(op->start_connectivity_watch));
}
+ if (op->stop_connectivity_watch != nullptr) {
+ t->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
+ }
if (op->set_accept_stream) {
t->accept_stream_cb = op->set_accept_stream_fn;
t->accept_stream_data = op->set_accept_stream_user_data;
}
if (op->on_consumed) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
}
bool do_close = false;
@@ -1204,17 +1204,17 @@ void destroy_transport(grpc_transport* gt) {
* INTEGRATION GLUE
*/
-void set_pollset(grpc_transport* /*gt*/, grpc_stream* /*gs*/,
- grpc_pollset* /*pollset*/) {
+void set_pollset(grpc_transport* /*gt*/, grpc_stream* /*gs*/,
+ grpc_pollset* /*pollset*/) {
// Nothing to do here
}
-void set_pollset_set(grpc_transport* /*gt*/, grpc_stream* /*gs*/,
- grpc_pollset_set* /*pollset_set*/) {
+void set_pollset_set(grpc_transport* /*gt*/, grpc_stream* /*gs*/,
+ grpc_pollset_set* /*pollset_set*/) {
// Nothing to do here
}
-grpc_endpoint* get_endpoint(grpc_transport* /*t*/) { return nullptr; }
+grpc_endpoint* get_endpoint(grpc_transport* /*t*/) { return nullptr; }
const grpc_transport_vtable inproc_vtable = {
sizeof(inproc_stream), "inproc", init_stream,
@@ -1226,9 +1226,9 @@ const grpc_transport_vtable inproc_vtable = {
* Main inproc transport functions
*/
void inproc_transports_create(grpc_transport** server_transport,
- const grpc_channel_args* /*server_args*/,
+ const grpc_channel_args* /*server_args*/,
grpc_transport** client_transport,
- const grpc_channel_args* /*client_args*/) {
+ const grpc_channel_args* /*client_args*/) {
INPROC_LOG(GPR_INFO, "inproc_transports_create");
shared_mu* mu = new (gpr_malloc(sizeof(*mu))) shared_mu();
inproc_transport* st = new (gpr_malloc(sizeof(*st)))
@@ -1247,7 +1247,7 @@ void inproc_transports_create(grpc_transport** server_transport,
*/
void grpc_inproc_transport_init(void) {
grpc_core::ExecCtx exec_ctx;
- g_empty_slice = grpc_core::ExternallyManagedSlice();
+ g_empty_slice = grpc_core::ExternallyManagedSlice();
grpc_slice key_tmp = grpc_slice_from_static_string(":path");
g_fake_path_key = grpc_slice_intern(key_tmp);
@@ -1264,19 +1264,19 @@ void grpc_inproc_transport_init(void) {
grpc_channel* grpc_inproc_channel_create(grpc_server* server,
grpc_channel_args* args,
- void* /*reserved*/) {
+ void* /*reserved*/) {
GRPC_API_TRACE("grpc_inproc_channel_create(server=%p, args=%p)", 2,
(server, args));
grpc_core::ExecCtx exec_ctx;
- // Remove max_connection_idle and max_connection_age channel arguments since
- // those do not apply to inproc transports.
- const char* args_to_remove[] = {GRPC_ARG_MAX_CONNECTION_IDLE_MS,
- GRPC_ARG_MAX_CONNECTION_AGE_MS};
- const grpc_channel_args* server_args = grpc_channel_args_copy_and_remove(
+ // Remove max_connection_idle and max_connection_age channel arguments since
+ // those do not apply to inproc transports.
+ const char* args_to_remove[] = {GRPC_ARG_MAX_CONNECTION_IDLE_MS,
+ GRPC_ARG_MAX_CONNECTION_AGE_MS};
+ const grpc_channel_args* server_args = grpc_channel_args_copy_and_remove(
server->core_server->channel_args(), args_to_remove,
- GPR_ARRAY_SIZE(args_to_remove));
+ GPR_ARRAY_SIZE(args_to_remove));
// Add a default authority channel argument for the client
grpc_arg default_authority_arg;
@@ -1298,7 +1298,7 @@ grpc_channel* grpc_inproc_channel_create(grpc_server* server,
"inproc", client_args, GRPC_CLIENT_DIRECT_CHANNEL, client_transport);
// Free up created channel args
- grpc_channel_args_destroy(server_args);
+ grpc_channel_args_destroy(server_args);
grpc_channel_args_destroy(client_args);
// Now finish scheduled operations
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.c
index a1385cc3e7..60f689e84e 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.c
@@ -1,18 +1,18 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/api/annotations.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/api/annotations.upb.h"
-#include "google/api/http.upb.h"
-#include "google/protobuf/descriptor.upb.h"
-
-#include "upb/port_def.inc"
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/api/annotations.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/api/annotations.upb.h"
+#include "google/api/http.upb.h"
+#include "google/protobuf/descriptor.upb.h"
+
+#include "upb/port_def.inc"
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.h
index ea05f2597a..2112f04ca3 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/annotations.upb.h
@@ -1,29 +1,29 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/api/annotations.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_API_ANNOTATIONS_PROTO_UPB_H_
-#define GOOGLE_API_ANNOTATIONS_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_API_ANNOTATIONS_PROTO_UPB_H_ */
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/api/annotations.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_API_ANNOTATIONS_PROTO_UPB_H_
+#define GOOGLE_API_ANNOTATIONS_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_API_ANNOTATIONS_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.c
index 8ad07dcd9f..dde95db297 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.c
@@ -1,66 +1,66 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/api/http.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/api/http.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const google_api_Http_submsgs[1] = {
- &google_api_HttpRule_msginit,
-};
-
-static const upb_msglayout_field google_api_Http__fields[2] = {
- {1, UPB_SIZE(4, 8), 0, 0, 11, 3},
- {2, UPB_SIZE(0, 0), 0, 0, 8, 1},
-};
-
-const upb_msglayout google_api_Http_msginit = {
- &google_api_Http_submsgs[0],
- &google_api_Http__fields[0],
- UPB_SIZE(8, 16), 2, false,
-};
-
-static const upb_msglayout *const google_api_HttpRule_submsgs[2] = {
- &google_api_CustomHttpPattern_msginit,
- &google_api_HttpRule_msginit,
-};
-
-static const upb_msglayout_field google_api_HttpRule__fields[10] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
- {3, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
- {4, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
- {5, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
- {6, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
- {7, UPB_SIZE(8, 16), 0, 0, 9, 1},
- {8, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 11, 1},
- {11, UPB_SIZE(24, 48), 0, 1, 11, 3},
- {12, UPB_SIZE(16, 32), 0, 0, 9, 1},
-};
-
-const upb_msglayout google_api_HttpRule_msginit = {
- &google_api_HttpRule_submsgs[0],
- &google_api_HttpRule__fields[0],
- UPB_SIZE(40, 80), 10, false,
-};
-
-static const upb_msglayout_field google_api_CustomHttpPattern__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 16), 0, 0, 9, 1},
-};
-
-const upb_msglayout google_api_CustomHttpPattern_msginit = {
- NULL,
- &google_api_CustomHttpPattern__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/api/http.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/api/http.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const google_api_Http_submsgs[1] = {
+ &google_api_HttpRule_msginit,
+};
+
+static const upb_msglayout_field google_api_Http__fields[2] = {
+ {1, UPB_SIZE(4, 8), 0, 0, 11, 3},
+ {2, UPB_SIZE(0, 0), 0, 0, 8, 1},
+};
+
+const upb_msglayout google_api_Http_msginit = {
+ &google_api_Http_submsgs[0],
+ &google_api_Http__fields[0],
+ UPB_SIZE(8, 16), 2, false,
+};
+
+static const upb_msglayout *const google_api_HttpRule_submsgs[2] = {
+ &google_api_CustomHttpPattern_msginit,
+ &google_api_HttpRule_msginit,
+};
+
+static const upb_msglayout_field google_api_HttpRule__fields[10] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
+ {3, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
+ {4, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
+ {5, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
+ {6, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 9, 1},
+ {7, UPB_SIZE(8, 16), 0, 0, 9, 1},
+ {8, UPB_SIZE(28, 56), UPB_SIZE(-37, -73), 0, 11, 1},
+ {11, UPB_SIZE(24, 48), 0, 1, 11, 3},
+ {12, UPB_SIZE(16, 32), 0, 0, 9, 1},
+};
+
+const upb_msglayout google_api_HttpRule_msginit = {
+ &google_api_HttpRule_submsgs[0],
+ &google_api_HttpRule__fields[0],
+ UPB_SIZE(40, 80), 10, false,
+};
+
+static const upb_msglayout_field google_api_CustomHttpPattern__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 16), 0, 0, 9, 1},
+};
+
+const upb_msglayout google_api_CustomHttpPattern_msginit = {
+ NULL,
+ &google_api_CustomHttpPattern__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.h
index 9012b9f748..baa4be24d8 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/api/http.upb.h
@@ -1,191 +1,191 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/api/http.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_API_HTTP_PROTO_UPB_H_
-#define GOOGLE_API_HTTP_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_api_Http;
-struct google_api_HttpRule;
-struct google_api_CustomHttpPattern;
-typedef struct google_api_Http google_api_Http;
-typedef struct google_api_HttpRule google_api_HttpRule;
-typedef struct google_api_CustomHttpPattern google_api_CustomHttpPattern;
-extern const upb_msglayout google_api_Http_msginit;
-extern const upb_msglayout google_api_HttpRule_msginit;
-extern const upb_msglayout google_api_CustomHttpPattern_msginit;
-
-
-/* google.api.Http */
-
-UPB_INLINE google_api_Http *google_api_Http_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/api/http.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_API_HTTP_PROTO_UPB_H_
+#define GOOGLE_API_HTTP_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_api_Http;
+struct google_api_HttpRule;
+struct google_api_CustomHttpPattern;
+typedef struct google_api_Http google_api_Http;
+typedef struct google_api_HttpRule google_api_HttpRule;
+typedef struct google_api_CustomHttpPattern google_api_CustomHttpPattern;
+extern const upb_msglayout google_api_Http_msginit;
+extern const upb_msglayout google_api_HttpRule_msginit;
+extern const upb_msglayout google_api_CustomHttpPattern_msginit;
+
+
+/* google.api.Http */
+
+UPB_INLINE google_api_Http *google_api_Http_new(upb_arena *arena) {
return (google_api_Http *)_upb_msg_new(&google_api_Http_msginit, arena);
-}
-UPB_INLINE google_api_Http *google_api_Http_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_api_Http *ret = google_api_Http_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_api_Http_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_api_Http_serialize(const google_api_Http *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_api_Http_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_api_Http *google_api_Http_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_api_Http *ret = google_api_Http_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_api_Http_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_api_Http_serialize(const google_api_Http *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_api_Http_msginit, arena, len);
+}
+
UPB_INLINE bool google_api_Http_has_rules(const google_api_Http *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
-UPB_INLINE const google_api_HttpRule* const* google_api_Http_rules(const google_api_Http *msg, size_t *len) { return (const google_api_HttpRule* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
+UPB_INLINE const google_api_HttpRule* const* google_api_Http_rules(const google_api_Http *msg, size_t *len) { return (const google_api_HttpRule* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE bool google_api_Http_fully_decode_reserved_expansion(const google_api_Http *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), bool); }
-
-UPB_INLINE google_api_HttpRule** google_api_Http_mutable_rules(google_api_Http *msg, size_t *len) {
- return (google_api_HttpRule**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
-}
-UPB_INLINE google_api_HttpRule** google_api_Http_resize_rules(google_api_Http *msg, size_t len, upb_arena *arena) {
+
+UPB_INLINE google_api_HttpRule** google_api_Http_mutable_rules(google_api_Http *msg, size_t *len) {
+ return (google_api_HttpRule**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
+}
+UPB_INLINE google_api_HttpRule** google_api_Http_resize_rules(google_api_Http *msg, size_t len, upb_arena *arena) {
return (google_api_HttpRule**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_api_HttpRule* google_api_Http_add_rules(google_api_Http *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_api_HttpRule* google_api_Http_add_rules(google_api_Http *msg, upb_arena *arena) {
struct google_api_HttpRule* sub = (struct google_api_HttpRule*)_upb_msg_new(&google_api_HttpRule_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_api_Http_set_fully_decode_reserved_expansion(google_api_Http *msg, bool value) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_api_Http_set_fully_decode_reserved_expansion(google_api_Http *msg, bool value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), bool) = value;
-}
-
-/* google.api.HttpRule */
-
-UPB_INLINE google_api_HttpRule *google_api_HttpRule_new(upb_arena *arena) {
+}
+
+/* google.api.HttpRule */
+
+UPB_INLINE google_api_HttpRule *google_api_HttpRule_new(upb_arena *arena) {
return (google_api_HttpRule *)_upb_msg_new(&google_api_HttpRule_msginit, arena);
-}
-UPB_INLINE google_api_HttpRule *google_api_HttpRule_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_api_HttpRule *ret = google_api_HttpRule_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_api_HttpRule_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_api_HttpRule_serialize(const google_api_HttpRule *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_api_HttpRule_msginit, arena, len);
-}
-
-typedef enum {
- google_api_HttpRule_pattern_get = 2,
- google_api_HttpRule_pattern_put = 3,
- google_api_HttpRule_pattern_post = 4,
- google_api_HttpRule_pattern_delete = 5,
- google_api_HttpRule_pattern_patch = 6,
- google_api_HttpRule_pattern_custom = 8,
- google_api_HttpRule_pattern_NOT_SET = 0
-} google_api_HttpRule_pattern_oneofcases;
+}
+UPB_INLINE google_api_HttpRule *google_api_HttpRule_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_api_HttpRule *ret = google_api_HttpRule_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_api_HttpRule_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_api_HttpRule_serialize(const google_api_HttpRule *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_api_HttpRule_msginit, arena, len);
+}
+
+typedef enum {
+ google_api_HttpRule_pattern_get = 2,
+ google_api_HttpRule_pattern_put = 3,
+ google_api_HttpRule_pattern_post = 4,
+ google_api_HttpRule_pattern_delete = 5,
+ google_api_HttpRule_pattern_patch = 6,
+ google_api_HttpRule_pattern_custom = 8,
+ google_api_HttpRule_pattern_NOT_SET = 0
+} google_api_HttpRule_pattern_oneofcases;
UPB_INLINE google_api_HttpRule_pattern_oneofcases google_api_HttpRule_pattern_case(const google_api_HttpRule* msg) { return (google_api_HttpRule_pattern_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(36, 72), int32_t); }
-
+
UPB_INLINE upb_strview google_api_HttpRule_selector(const google_api_HttpRule *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
UPB_INLINE bool google_api_HttpRule_has_get(const google_api_HttpRule *msg) { return _upb_getoneofcase(msg, UPB_SIZE(36, 72)) == 2; }
-UPB_INLINE upb_strview google_api_HttpRule_get(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 2, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview google_api_HttpRule_get(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 2, upb_strview_make("", strlen(""))); }
UPB_INLINE bool google_api_HttpRule_has_put(const google_api_HttpRule *msg) { return _upb_getoneofcase(msg, UPB_SIZE(36, 72)) == 3; }
-UPB_INLINE upb_strview google_api_HttpRule_put(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 3, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview google_api_HttpRule_put(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 3, upb_strview_make("", strlen(""))); }
UPB_INLINE bool google_api_HttpRule_has_post(const google_api_HttpRule *msg) { return _upb_getoneofcase(msg, UPB_SIZE(36, 72)) == 4; }
-UPB_INLINE upb_strview google_api_HttpRule_post(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 4, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview google_api_HttpRule_post(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 4, upb_strview_make("", strlen(""))); }
UPB_INLINE bool google_api_HttpRule_has_delete(const google_api_HttpRule *msg) { return _upb_getoneofcase(msg, UPB_SIZE(36, 72)) == 5; }
-UPB_INLINE upb_strview google_api_HttpRule_delete(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 5, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview google_api_HttpRule_delete(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 5, upb_strview_make("", strlen(""))); }
UPB_INLINE bool google_api_HttpRule_has_patch(const google_api_HttpRule *msg) { return _upb_getoneofcase(msg, UPB_SIZE(36, 72)) == 6; }
-UPB_INLINE upb_strview google_api_HttpRule_patch(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 6, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview google_api_HttpRule_patch(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 6, upb_strview_make("", strlen(""))); }
UPB_INLINE upb_strview google_api_HttpRule_body(const google_api_HttpRule *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), upb_strview); }
UPB_INLINE bool google_api_HttpRule_has_custom(const google_api_HttpRule *msg) { return _upb_getoneofcase(msg, UPB_SIZE(36, 72)) == 8; }
-UPB_INLINE const google_api_CustomHttpPattern* google_api_HttpRule_custom(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, const google_api_CustomHttpPattern*, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 8, NULL); }
+UPB_INLINE const google_api_CustomHttpPattern* google_api_HttpRule_custom(const google_api_HttpRule *msg) { return UPB_READ_ONEOF(msg, const google_api_CustomHttpPattern*, UPB_SIZE(28, 56), UPB_SIZE(36, 72), 8, NULL); }
UPB_INLINE bool google_api_HttpRule_has_additional_bindings(const google_api_HttpRule *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(24, 48)); }
-UPB_INLINE const google_api_HttpRule* const* google_api_HttpRule_additional_bindings(const google_api_HttpRule *msg, size_t *len) { return (const google_api_HttpRule* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+UPB_INLINE const google_api_HttpRule* const* google_api_HttpRule_additional_bindings(const google_api_HttpRule *msg, size_t *len) { return (const google_api_HttpRule* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE upb_strview google_api_HttpRule_response_body(const google_api_HttpRule *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 32), upb_strview); }
-
-UPB_INLINE void google_api_HttpRule_set_selector(google_api_HttpRule *msg, upb_strview value) {
+
+UPB_INLINE void google_api_HttpRule_set_selector(google_api_HttpRule *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-UPB_INLINE void google_api_HttpRule_set_get(google_api_HttpRule *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 2);
-}
-UPB_INLINE void google_api_HttpRule_set_put(google_api_HttpRule *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 3);
-}
-UPB_INLINE void google_api_HttpRule_set_post(google_api_HttpRule *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 4);
-}
-UPB_INLINE void google_api_HttpRule_set_delete(google_api_HttpRule *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 5);
-}
-UPB_INLINE void google_api_HttpRule_set_patch(google_api_HttpRule *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 6);
-}
-UPB_INLINE void google_api_HttpRule_set_body(google_api_HttpRule *msg, upb_strview value) {
+}
+UPB_INLINE void google_api_HttpRule_set_get(google_api_HttpRule *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 2);
+}
+UPB_INLINE void google_api_HttpRule_set_put(google_api_HttpRule *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 3);
+}
+UPB_INLINE void google_api_HttpRule_set_post(google_api_HttpRule *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 4);
+}
+UPB_INLINE void google_api_HttpRule_set_delete(google_api_HttpRule *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 5);
+}
+UPB_INLINE void google_api_HttpRule_set_patch(google_api_HttpRule *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 6);
+}
+UPB_INLINE void google_api_HttpRule_set_body(google_api_HttpRule *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), upb_strview) = value;
-}
-UPB_INLINE void google_api_HttpRule_set_custom(google_api_HttpRule *msg, google_api_CustomHttpPattern* value) {
- UPB_WRITE_ONEOF(msg, google_api_CustomHttpPattern*, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 8);
-}
-UPB_INLINE struct google_api_CustomHttpPattern* google_api_HttpRule_mutable_custom(google_api_HttpRule *msg, upb_arena *arena) {
- struct google_api_CustomHttpPattern* sub = (struct google_api_CustomHttpPattern*)google_api_HttpRule_custom(msg);
- if (sub == NULL) {
+}
+UPB_INLINE void google_api_HttpRule_set_custom(google_api_HttpRule *msg, google_api_CustomHttpPattern* value) {
+ UPB_WRITE_ONEOF(msg, google_api_CustomHttpPattern*, UPB_SIZE(28, 56), value, UPB_SIZE(36, 72), 8);
+}
+UPB_INLINE struct google_api_CustomHttpPattern* google_api_HttpRule_mutable_custom(google_api_HttpRule *msg, upb_arena *arena) {
+ struct google_api_CustomHttpPattern* sub = (struct google_api_CustomHttpPattern*)google_api_HttpRule_custom(msg);
+ if (sub == NULL) {
sub = (struct google_api_CustomHttpPattern*)_upb_msg_new(&google_api_CustomHttpPattern_msginit, arena);
- if (!sub) return NULL;
- google_api_HttpRule_set_custom(msg, sub);
- }
- return sub;
-}
-UPB_INLINE google_api_HttpRule** google_api_HttpRule_mutable_additional_bindings(google_api_HttpRule *msg, size_t *len) {
- return (google_api_HttpRule**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
-}
-UPB_INLINE google_api_HttpRule** google_api_HttpRule_resize_additional_bindings(google_api_HttpRule *msg, size_t len, upb_arena *arena) {
+ if (!sub) return NULL;
+ google_api_HttpRule_set_custom(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE google_api_HttpRule** google_api_HttpRule_mutable_additional_bindings(google_api_HttpRule *msg, size_t *len) {
+ return (google_api_HttpRule**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
+}
+UPB_INLINE google_api_HttpRule** google_api_HttpRule_resize_additional_bindings(google_api_HttpRule *msg, size_t len, upb_arena *arena) {
return (google_api_HttpRule**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_api_HttpRule* google_api_HttpRule_add_additional_bindings(google_api_HttpRule *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_api_HttpRule* google_api_HttpRule_add_additional_bindings(google_api_HttpRule *msg, upb_arena *arena) {
struct google_api_HttpRule* sub = (struct google_api_HttpRule*)_upb_msg_new(&google_api_HttpRule_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_api_HttpRule_set_response_body(google_api_HttpRule *msg, upb_strview value) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_api_HttpRule_set_response_body(google_api_HttpRule *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 32), upb_strview) = value;
-}
-
-/* google.api.CustomHttpPattern */
-
-UPB_INLINE google_api_CustomHttpPattern *google_api_CustomHttpPattern_new(upb_arena *arena) {
+}
+
+/* google.api.CustomHttpPattern */
+
+UPB_INLINE google_api_CustomHttpPattern *google_api_CustomHttpPattern_new(upb_arena *arena) {
return (google_api_CustomHttpPattern *)_upb_msg_new(&google_api_CustomHttpPattern_msginit, arena);
-}
-UPB_INLINE google_api_CustomHttpPattern *google_api_CustomHttpPattern_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_api_CustomHttpPattern *ret = google_api_CustomHttpPattern_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_api_CustomHttpPattern_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_api_CustomHttpPattern_serialize(const google_api_CustomHttpPattern *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_api_CustomHttpPattern_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_api_CustomHttpPattern *google_api_CustomHttpPattern_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_api_CustomHttpPattern *ret = google_api_CustomHttpPattern_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_api_CustomHttpPattern_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_api_CustomHttpPattern_serialize(const google_api_CustomHttpPattern *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_api_CustomHttpPattern_msginit, arena, len);
+}
+
UPB_INLINE upb_strview google_api_CustomHttpPattern_kind(const google_api_CustomHttpPattern *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
UPB_INLINE upb_strview google_api_CustomHttpPattern_path(const google_api_CustomHttpPattern *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), upb_strview); }
-
-UPB_INLINE void google_api_CustomHttpPattern_set_kind(google_api_CustomHttpPattern *msg, upb_strview value) {
+
+UPB_INLINE void google_api_CustomHttpPattern_set_kind(google_api_CustomHttpPattern *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-UPB_INLINE void google_api_CustomHttpPattern_set_path(google_api_CustomHttpPattern *msg, upb_strview value) {
+}
+UPB_INLINE void google_api_CustomHttpPattern_set_path(google_api_CustomHttpPattern *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), upb_strview) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_API_HTTP_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_API_HTTP_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.c
index 14badf797c..941b65485a 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.c
@@ -1,27 +1,27 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/any.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/any.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout_field google_protobuf_Any__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 16), 0, 0, 12, 1},
-};
-
-const upb_msglayout google_protobuf_Any_msginit = {
- NULL,
- &google_protobuf_Any__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/any.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/any.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout_field google_protobuf_Any__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 16), 0, 0, 12, 1},
+};
+
+const upb_msglayout google_protobuf_Any_msginit = {
+ NULL,
+ &google_protobuf_Any__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.h
index bf8394e732..7f54a810eb 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/any.upb.h
@@ -1,57 +1,57 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/any.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_ANY_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_ANY_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_Any;
-typedef struct google_protobuf_Any google_protobuf_Any;
-extern const upb_msglayout google_protobuf_Any_msginit;
-
-
-/* google.protobuf.Any */
-
-UPB_INLINE google_protobuf_Any *google_protobuf_Any_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/any.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_ANY_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_ANY_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_Any;
+typedef struct google_protobuf_Any google_protobuf_Any;
+extern const upb_msglayout google_protobuf_Any_msginit;
+
+
+/* google.protobuf.Any */
+
+UPB_INLINE google_protobuf_Any *google_protobuf_Any_new(upb_arena *arena) {
return (google_protobuf_Any *)_upb_msg_new(&google_protobuf_Any_msginit, arena);
-}
-UPB_INLINE google_protobuf_Any *google_protobuf_Any_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Any *ret = google_protobuf_Any_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Any_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Any_serialize(const google_protobuf_Any *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Any_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_Any *google_protobuf_Any_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Any *ret = google_protobuf_Any_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Any_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Any_serialize(const google_protobuf_Any *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Any_msginit, arena, len);
+}
+
UPB_INLINE upb_strview google_protobuf_Any_type_url(const google_protobuf_Any *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
UPB_INLINE upb_strview google_protobuf_Any_value(const google_protobuf_Any *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), upb_strview); }
-
-UPB_INLINE void google_protobuf_Any_set_type_url(google_protobuf_Any *msg, upb_strview value) {
+
+UPB_INLINE void google_protobuf_Any_set_type_url(google_protobuf_Any *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_Any_set_value(google_protobuf_Any *msg, upb_strview value) {
+}
+UPB_INLINE void google_protobuf_Any_set_value(google_protobuf_Any *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), upb_strview) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_ANY_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_ANY_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.c
index 44cd3ae2ce..6bd0e9e0d1 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.c
@@ -1,486 +1,486 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/descriptor.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/descriptor.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
- &google_protobuf_FileDescriptorProto_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
- &google_protobuf_FileDescriptorSet_submsgs[0],
- &google_protobuf_FileDescriptorSet__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
- &google_protobuf_DescriptorProto_msginit,
- &google_protobuf_EnumDescriptorProto_msginit,
- &google_protobuf_FieldDescriptorProto_msginit,
- &google_protobuf_FileOptions_msginit,
- &google_protobuf_ServiceDescriptorProto_msginit,
- &google_protobuf_SourceCodeInfo_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/descriptor.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/descriptor.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const google_protobuf_FileDescriptorSet_submsgs[1] = {
+ &google_protobuf_FileDescriptorProto_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_FileDescriptorSet__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_FileDescriptorSet_msginit = {
+ &google_protobuf_FileDescriptorSet_submsgs[0],
+ &google_protobuf_FileDescriptorSet__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout *const google_protobuf_FileDescriptorProto_submsgs[6] = {
+ &google_protobuf_DescriptorProto_msginit,
+ &google_protobuf_EnumDescriptorProto_msginit,
+ &google_protobuf_FieldDescriptorProto_msginit,
+ &google_protobuf_FileOptions_msginit,
+ &google_protobuf_ServiceDescriptorProto_msginit,
+ &google_protobuf_SourceCodeInfo_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_FileDescriptorProto__fields[12] = {
{1, UPB_SIZE(4, 8), 1, 0, 12, 1},
{2, UPB_SIZE(12, 24), 2, 0, 12, 1},
{3, UPB_SIZE(36, 72), 0, 0, 12, 3},
- {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
- {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
- {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
- {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
- {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
- {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
- {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
- {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
+ {4, UPB_SIZE(40, 80), 0, 0, 11, 3},
+ {5, UPB_SIZE(44, 88), 0, 1, 11, 3},
+ {6, UPB_SIZE(48, 96), 0, 4, 11, 3},
+ {7, UPB_SIZE(52, 104), 0, 2, 11, 3},
+ {8, UPB_SIZE(28, 56), 4, 3, 11, 1},
+ {9, UPB_SIZE(32, 64), 5, 5, 11, 1},
+ {10, UPB_SIZE(56, 112), 0, 0, 5, 3},
+ {11, UPB_SIZE(60, 120), 0, 0, 5, 3},
{12, UPB_SIZE(20, 40), 3, 0, 12, 1},
-};
-
-const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
- &google_protobuf_FileDescriptorProto_submsgs[0],
- &google_protobuf_FileDescriptorProto__fields[0],
- UPB_SIZE(64, 128), 12, false,
-};
-
-static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
- &google_protobuf_DescriptorProto_msginit,
- &google_protobuf_DescriptorProto_ExtensionRange_msginit,
- &google_protobuf_DescriptorProto_ReservedRange_msginit,
- &google_protobuf_EnumDescriptorProto_msginit,
- &google_protobuf_FieldDescriptorProto_msginit,
- &google_protobuf_MessageOptions_msginit,
- &google_protobuf_OneofDescriptorProto_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
+};
+
+const upb_msglayout google_protobuf_FileDescriptorProto_msginit = {
+ &google_protobuf_FileDescriptorProto_submsgs[0],
+ &google_protobuf_FileDescriptorProto__fields[0],
+ UPB_SIZE(64, 128), 12, false,
+};
+
+static const upb_msglayout *const google_protobuf_DescriptorProto_submsgs[8] = {
+ &google_protobuf_DescriptorProto_msginit,
+ &google_protobuf_DescriptorProto_ExtensionRange_msginit,
+ &google_protobuf_DescriptorProto_ReservedRange_msginit,
+ &google_protobuf_EnumDescriptorProto_msginit,
+ &google_protobuf_FieldDescriptorProto_msginit,
+ &google_protobuf_MessageOptions_msginit,
+ &google_protobuf_OneofDescriptorProto_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_DescriptorProto__fields[10] = {
{1, UPB_SIZE(4, 8), 1, 0, 12, 1},
- {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
- {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
- {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
- {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
- {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
- {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
- {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
- {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
+ {2, UPB_SIZE(16, 32), 0, 4, 11, 3},
+ {3, UPB_SIZE(20, 40), 0, 0, 11, 3},
+ {4, UPB_SIZE(24, 48), 0, 3, 11, 3},
+ {5, UPB_SIZE(28, 56), 0, 1, 11, 3},
+ {6, UPB_SIZE(32, 64), 0, 4, 11, 3},
+ {7, UPB_SIZE(12, 24), 2, 5, 11, 1},
+ {8, UPB_SIZE(36, 72), 0, 6, 11, 3},
+ {9, UPB_SIZE(40, 80), 0, 2, 11, 3},
{10, UPB_SIZE(44, 88), 0, 0, 12, 3},
-};
-
-const upb_msglayout google_protobuf_DescriptorProto_msginit = {
- &google_protobuf_DescriptorProto_submsgs[0],
- &google_protobuf_DescriptorProto__fields[0],
- UPB_SIZE(48, 96), 10, false,
-};
-
-static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
- &google_protobuf_ExtensionRangeOptions_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
- {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
- {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
-};
-
-const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
- &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
- &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
- UPB_SIZE(16, 24), 3, false,
-};
-
-static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
- {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
-};
-
-const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
- NULL,
- &google_protobuf_DescriptorProto_ReservedRange__fields[0],
- UPB_SIZE(12, 12), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
- {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
- &google_protobuf_ExtensionRangeOptions_submsgs[0],
- &google_protobuf_ExtensionRangeOptions__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
- &google_protobuf_FieldOptions_msginit,
-};
-
+};
+
+const upb_msglayout google_protobuf_DescriptorProto_msginit = {
+ &google_protobuf_DescriptorProto_submsgs[0],
+ &google_protobuf_DescriptorProto__fields[0],
+ UPB_SIZE(48, 96), 10, false,
+};
+
+static const upb_msglayout *const google_protobuf_DescriptorProto_ExtensionRange_submsgs[1] = {
+ &google_protobuf_ExtensionRangeOptions_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_DescriptorProto_ExtensionRange__fields[3] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
+ {3, UPB_SIZE(12, 16), 3, 0, 11, 1},
+};
+
+const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit = {
+ &google_protobuf_DescriptorProto_ExtensionRange_submsgs[0],
+ &google_protobuf_DescriptorProto_ExtensionRange__fields[0],
+ UPB_SIZE(16, 24), 3, false,
+};
+
+static const upb_msglayout_field google_protobuf_DescriptorProto_ReservedRange__fields[2] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
+};
+
+const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit = {
+ NULL,
+ &google_protobuf_DescriptorProto_ReservedRange__fields[0],
+ UPB_SIZE(12, 12), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_ExtensionRangeOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_ExtensionRangeOptions__fields[1] = {
+ {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit = {
+ &google_protobuf_ExtensionRangeOptions_submsgs[0],
+ &google_protobuf_ExtensionRangeOptions__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout *const google_protobuf_FieldDescriptorProto_submsgs[1] = {
+ &google_protobuf_FieldOptions_msginit,
+};
+
static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[11] = {
{1, UPB_SIZE(36, 40), 6, 0, 12, 1},
{2, UPB_SIZE(44, 56), 7, 0, 12, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
- {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
- {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 5, 1},
+ {4, UPB_SIZE(8, 8), 1, 0, 14, 1},
+ {5, UPB_SIZE(16, 16), 2, 0, 14, 1},
{6, UPB_SIZE(52, 72), 8, 0, 12, 1},
{7, UPB_SIZE(60, 88), 9, 0, 12, 1},
{8, UPB_SIZE(76, 120), 11, 0, 11, 1},
- {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
+ {9, UPB_SIZE(28, 28), 4, 0, 5, 1},
{10, UPB_SIZE(68, 104), 10, 0, 12, 1},
{17, UPB_SIZE(32, 32), 5, 0, 8, 1},
-};
-
-const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
- &google_protobuf_FieldDescriptorProto_submsgs[0],
- &google_protobuf_FieldDescriptorProto__fields[0],
+};
+
+const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
+ &google_protobuf_FieldDescriptorProto_submsgs[0],
+ &google_protobuf_FieldDescriptorProto__fields[0],
UPB_SIZE(80, 128), 11, false,
-};
-
-static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
- &google_protobuf_OneofOptions_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
+};
+
+static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
+ &google_protobuf_OneofOptions_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_OneofDescriptorProto__fields[2] = {
{1, UPB_SIZE(4, 8), 1, 0, 12, 1},
- {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
-};
-
-const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
- &google_protobuf_OneofDescriptorProto_submsgs[0],
- &google_protobuf_OneofDescriptorProto__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
- &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
- &google_protobuf_EnumOptions_msginit,
- &google_protobuf_EnumValueDescriptorProto_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
+ {2, UPB_SIZE(12, 24), 2, 0, 11, 1},
+};
+
+const upb_msglayout google_protobuf_OneofDescriptorProto_msginit = {
+ &google_protobuf_OneofDescriptorProto_submsgs[0],
+ &google_protobuf_OneofDescriptorProto__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_EnumDescriptorProto_submsgs[3] = {
+ &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit,
+ &google_protobuf_EnumOptions_msginit,
+ &google_protobuf_EnumValueDescriptorProto_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_EnumDescriptorProto__fields[5] = {
{1, UPB_SIZE(4, 8), 1, 0, 12, 1},
- {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
- {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
- {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
+ {2, UPB_SIZE(16, 32), 0, 2, 11, 3},
+ {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
+ {4, UPB_SIZE(20, 40), 0, 0, 11, 3},
{5, UPB_SIZE(24, 48), 0, 0, 12, 3},
-};
-
-const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
- &google_protobuf_EnumDescriptorProto_submsgs[0],
- &google_protobuf_EnumDescriptorProto__fields[0],
- UPB_SIZE(32, 64), 5, false,
-};
-
-static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
- {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
-};
-
-const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
- NULL,
- &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
- UPB_SIZE(12, 12), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
- &google_protobuf_EnumValueOptions_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
+};
+
+const upb_msglayout google_protobuf_EnumDescriptorProto_msginit = {
+ &google_protobuf_EnumDescriptorProto_submsgs[0],
+ &google_protobuf_EnumDescriptorProto__fields[0],
+ UPB_SIZE(32, 64), 5, false,
+};
+
+static const upb_msglayout_field google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[2] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
+};
+
+const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit = {
+ NULL,
+ &google_protobuf_EnumDescriptorProto_EnumReservedRange__fields[0],
+ UPB_SIZE(12, 12), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_EnumValueDescriptorProto_submsgs[1] = {
+ &google_protobuf_EnumValueOptions_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_EnumValueDescriptorProto__fields[3] = {
{1, UPB_SIZE(8, 8), 2, 0, 12, 1},
- {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
-};
-
-const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
- &google_protobuf_EnumValueDescriptorProto_submsgs[0],
- &google_protobuf_EnumValueDescriptorProto__fields[0],
- UPB_SIZE(24, 32), 3, false,
-};
-
-static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
- &google_protobuf_MethodDescriptorProto_msginit,
- &google_protobuf_ServiceOptions_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
+ {2, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {3, UPB_SIZE(16, 24), 3, 0, 11, 1},
+};
+
+const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit = {
+ &google_protobuf_EnumValueDescriptorProto_submsgs[0],
+ &google_protobuf_EnumValueDescriptorProto__fields[0],
+ UPB_SIZE(24, 32), 3, false,
+};
+
+static const upb_msglayout *const google_protobuf_ServiceDescriptorProto_submsgs[2] = {
+ &google_protobuf_MethodDescriptorProto_msginit,
+ &google_protobuf_ServiceOptions_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_ServiceDescriptorProto__fields[3] = {
{1, UPB_SIZE(4, 8), 1, 0, 12, 1},
- {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
- {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
-};
-
-const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
- &google_protobuf_ServiceDescriptorProto_submsgs[0],
- &google_protobuf_ServiceDescriptorProto__fields[0],
- UPB_SIZE(24, 48), 3, false,
-};
-
-static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
- &google_protobuf_MethodOptions_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
+ {2, UPB_SIZE(16, 32), 0, 0, 11, 3},
+ {3, UPB_SIZE(12, 24), 2, 1, 11, 1},
+};
+
+const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit = {
+ &google_protobuf_ServiceDescriptorProto_submsgs[0],
+ &google_protobuf_ServiceDescriptorProto__fields[0],
+ UPB_SIZE(24, 48), 3, false,
+};
+
+static const upb_msglayout *const google_protobuf_MethodDescriptorProto_submsgs[1] = {
+ &google_protobuf_MethodOptions_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_MethodDescriptorProto__fields[6] = {
{1, UPB_SIZE(4, 8), 3, 0, 12, 1},
{2, UPB_SIZE(12, 24), 4, 0, 12, 1},
{3, UPB_SIZE(20, 40), 5, 0, 12, 1},
- {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
- {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
-};
-
-const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
- &google_protobuf_MethodDescriptorProto_submsgs[0],
- &google_protobuf_MethodDescriptorProto__fields[0],
- UPB_SIZE(32, 64), 6, false,
-};
-
-static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
+ {4, UPB_SIZE(28, 56), 6, 0, 11, 1},
+ {5, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {6, UPB_SIZE(2, 2), 2, 0, 8, 1},
+};
+
+const upb_msglayout google_protobuf_MethodDescriptorProto_msginit = {
+ &google_protobuf_MethodDescriptorProto_submsgs[0],
+ &google_protobuf_MethodDescriptorProto__fields[0],
+ UPB_SIZE(32, 64), 6, false,
+};
+
+static const upb_msglayout *const google_protobuf_FileOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_FileOptions__fields[21] = {
{1, UPB_SIZE(28, 32), 11, 0, 12, 1},
{8, UPB_SIZE(36, 48), 12, 0, 12, 1},
- {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
- {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
+ {9, UPB_SIZE(8, 8), 1, 0, 14, 1},
+ {10, UPB_SIZE(16, 16), 2, 0, 8, 1},
{11, UPB_SIZE(44, 64), 13, 0, 12, 1},
- {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
- {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
- {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
- {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
- {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
- {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
- {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
+ {16, UPB_SIZE(17, 17), 3, 0, 8, 1},
+ {17, UPB_SIZE(18, 18), 4, 0, 8, 1},
+ {18, UPB_SIZE(19, 19), 5, 0, 8, 1},
+ {20, UPB_SIZE(20, 20), 6, 0, 8, 1},
+ {23, UPB_SIZE(21, 21), 7, 0, 8, 1},
+ {27, UPB_SIZE(22, 22), 8, 0, 8, 1},
+ {31, UPB_SIZE(23, 23), 9, 0, 8, 1},
{36, UPB_SIZE(52, 80), 14, 0, 12, 1},
{37, UPB_SIZE(60, 96), 15, 0, 12, 1},
{39, UPB_SIZE(68, 112), 16, 0, 12, 1},
{40, UPB_SIZE(76, 128), 17, 0, 12, 1},
{41, UPB_SIZE(84, 144), 18, 0, 12, 1},
- {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
+ {42, UPB_SIZE(24, 24), 10, 0, 8, 1},
{44, UPB_SIZE(92, 160), 19, 0, 12, 1},
{45, UPB_SIZE(100, 176), 20, 0, 12, 1},
- {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_FileOptions_msginit = {
- &google_protobuf_FileOptions_submsgs[0],
- &google_protobuf_FileOptions__fields[0],
- UPB_SIZE(112, 208), 21, false,
-};
-
-static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
- {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
- {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
- {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
- {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_MessageOptions_msginit = {
- &google_protobuf_MessageOptions_submsgs[0],
- &google_protobuf_MessageOptions__fields[0],
- UPB_SIZE(12, 16), 5, false,
-};
-
-static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
- {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
- {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
- {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
- {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
- {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
- {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_FieldOptions_msginit = {
- &google_protobuf_FieldOptions_submsgs[0],
- &google_protobuf_FieldOptions__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
- {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_OneofOptions_msginit = {
- &google_protobuf_OneofOptions_submsgs[0],
- &google_protobuf_OneofOptions__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
- {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
- {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_EnumOptions_msginit = {
- &google_protobuf_EnumOptions_submsgs[0],
- &google_protobuf_EnumOptions__fields[0],
- UPB_SIZE(8, 16), 3, false,
-};
-
-static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
- {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
- &google_protobuf_EnumValueOptions_submsgs[0],
- &google_protobuf_EnumValueOptions__fields[0],
- UPB_SIZE(8, 16), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
- {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_ServiceOptions_msginit = {
- &google_protobuf_ServiceOptions_submsgs[0],
- &google_protobuf_ServiceOptions__fields[0],
- UPB_SIZE(8, 16), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
- &google_protobuf_UninterpretedOption_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
- {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
- {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
- {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_MethodOptions_msginit = {
- &google_protobuf_MethodOptions_submsgs[0],
- &google_protobuf_MethodOptions__fields[0],
- UPB_SIZE(24, 32), 3, false,
-};
-
-static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
- &google_protobuf_UninterpretedOption_NamePart_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
- {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
+ {999, UPB_SIZE(108, 192), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_FileOptions_msginit = {
+ &google_protobuf_FileOptions_submsgs[0],
+ &google_protobuf_FileOptions__fields[0],
+ UPB_SIZE(112, 208), 21, false,
+};
+
+static const upb_msglayout *const google_protobuf_MessageOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_MessageOptions__fields[5] = {
+ {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
+ {3, UPB_SIZE(3, 3), 3, 0, 8, 1},
+ {7, UPB_SIZE(4, 4), 4, 0, 8, 1},
+ {999, UPB_SIZE(8, 8), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_MessageOptions_msginit = {
+ &google_protobuf_MessageOptions_submsgs[0],
+ &google_protobuf_MessageOptions__fields[0],
+ UPB_SIZE(12, 16), 5, false,
+};
+
+static const upb_msglayout *const google_protobuf_FieldOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_FieldOptions__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 14, 1},
+ {2, UPB_SIZE(24, 24), 3, 0, 8, 1},
+ {3, UPB_SIZE(25, 25), 4, 0, 8, 1},
+ {5, UPB_SIZE(26, 26), 5, 0, 8, 1},
+ {6, UPB_SIZE(16, 16), 2, 0, 14, 1},
+ {10, UPB_SIZE(27, 27), 6, 0, 8, 1},
+ {999, UPB_SIZE(28, 32), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_FieldOptions_msginit = {
+ &google_protobuf_FieldOptions_submsgs[0],
+ &google_protobuf_FieldOptions__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout *const google_protobuf_OneofOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_OneofOptions__fields[1] = {
+ {999, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_OneofOptions_msginit = {
+ &google_protobuf_OneofOptions_submsgs[0],
+ &google_protobuf_OneofOptions__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout *const google_protobuf_EnumOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_EnumOptions__fields[3] = {
+ {2, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {3, UPB_SIZE(2, 2), 2, 0, 8, 1},
+ {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_EnumOptions_msginit = {
+ &google_protobuf_EnumOptions_submsgs[0],
+ &google_protobuf_EnumOptions__fields[0],
+ UPB_SIZE(8, 16), 3, false,
+};
+
+static const upb_msglayout *const google_protobuf_EnumValueOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_EnumValueOptions__fields[2] = {
+ {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_EnumValueOptions_msginit = {
+ &google_protobuf_EnumValueOptions_submsgs[0],
+ &google_protobuf_EnumValueOptions__fields[0],
+ UPB_SIZE(8, 16), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_ServiceOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_ServiceOptions__fields[2] = {
+ {33, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {999, UPB_SIZE(4, 8), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_ServiceOptions_msginit = {
+ &google_protobuf_ServiceOptions_submsgs[0],
+ &google_protobuf_ServiceOptions__fields[0],
+ UPB_SIZE(8, 16), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_MethodOptions_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_MethodOptions__fields[3] = {
+ {33, UPB_SIZE(16, 16), 2, 0, 8, 1},
+ {34, UPB_SIZE(8, 8), 1, 0, 14, 1},
+ {999, UPB_SIZE(20, 24), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_MethodOptions_msginit = {
+ &google_protobuf_MethodOptions_submsgs[0],
+ &google_protobuf_MethodOptions__fields[0],
+ UPB_SIZE(24, 32), 3, false,
+};
+
+static const upb_msglayout *const google_protobuf_UninterpretedOption_submsgs[1] = {
+ &google_protobuf_UninterpretedOption_NamePart_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_UninterpretedOption__fields[7] = {
+ {2, UPB_SIZE(56, 80), 0, 0, 11, 3},
{3, UPB_SIZE(32, 32), 4, 0, 12, 1},
- {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
- {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
- {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
- {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
+ {4, UPB_SIZE(8, 8), 1, 0, 4, 1},
+ {5, UPB_SIZE(16, 16), 2, 0, 3, 1},
+ {6, UPB_SIZE(24, 24), 3, 0, 1, 1},
+ {7, UPB_SIZE(40, 48), 5, 0, 12, 1},
{8, UPB_SIZE(48, 64), 6, 0, 12, 1},
-};
-
-const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
- &google_protobuf_UninterpretedOption_submsgs[0],
- &google_protobuf_UninterpretedOption__fields[0],
- UPB_SIZE(64, 96), 7, false,
-};
-
-static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
+};
+
+const upb_msglayout google_protobuf_UninterpretedOption_msginit = {
+ &google_protobuf_UninterpretedOption_submsgs[0],
+ &google_protobuf_UninterpretedOption__fields[0],
+ UPB_SIZE(64, 96), 7, false,
+};
+
+static const upb_msglayout_field google_protobuf_UninterpretedOption_NamePart__fields[2] = {
{1, UPB_SIZE(4, 8), 2, 0, 12, 2},
- {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
-};
-
-const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
- NULL,
- &google_protobuf_UninterpretedOption_NamePart__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
- &google_protobuf_SourceCodeInfo_Location_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
- &google_protobuf_SourceCodeInfo_submsgs[0],
- &google_protobuf_SourceCodeInfo__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
+ {2, UPB_SIZE(1, 1), 1, 0, 8, 2},
+};
+
+const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit = {
+ NULL,
+ &google_protobuf_UninterpretedOption_NamePart__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_SourceCodeInfo_submsgs[1] = {
+ &google_protobuf_SourceCodeInfo_Location_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_SourceCodeInfo__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_SourceCodeInfo_msginit = {
+ &google_protobuf_SourceCodeInfo_submsgs[0],
+ &google_protobuf_SourceCodeInfo__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
{1, UPB_SIZE(20, 40), 0, 0, 5, _UPB_LABEL_PACKED},
{2, UPB_SIZE(24, 48), 0, 0, 5, _UPB_LABEL_PACKED},
{3, UPB_SIZE(4, 8), 1, 0, 12, 1},
{4, UPB_SIZE(12, 24), 2, 0, 12, 1},
{6, UPB_SIZE(28, 56), 0, 0, 12, 3},
-};
-
-const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
- NULL,
- &google_protobuf_SourceCodeInfo_Location__fields[0],
- UPB_SIZE(32, 64), 5, false,
-};
-
-static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
- &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
- &google_protobuf_GeneratedCodeInfo_submsgs[0],
- &google_protobuf_GeneratedCodeInfo__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
+};
+
+const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit = {
+ NULL,
+ &google_protobuf_SourceCodeInfo_Location__fields[0],
+ UPB_SIZE(32, 64), 5, false,
+};
+
+static const upb_msglayout *const google_protobuf_GeneratedCodeInfo_submsgs[1] = {
+ &google_protobuf_GeneratedCodeInfo_Annotation_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_GeneratedCodeInfo__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit = {
+ &google_protobuf_GeneratedCodeInfo_submsgs[0],
+ &google_protobuf_GeneratedCodeInfo__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
{1, UPB_SIZE(20, 32), 0, 0, 5, _UPB_LABEL_PACKED},
{2, UPB_SIZE(12, 16), 3, 0, 12, 1},
- {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
-};
-
-const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
- NULL,
- &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
- UPB_SIZE(24, 48), 4, false,
-};
-
-#include "upb/port_undef.inc"
-
+ {3, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {4, UPB_SIZE(8, 8), 2, 0, 5, 1},
+};
+
+const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit = {
+ NULL,
+ &google_protobuf_GeneratedCodeInfo_Annotation__fields[0],
+ UPB_SIZE(24, 48), 4, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h
index 64701a0cf2..b47554755f 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h
@@ -1,615 +1,615 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/descriptor.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_FileDescriptorSet;
-struct google_protobuf_FileDescriptorProto;
-struct google_protobuf_DescriptorProto;
-struct google_protobuf_DescriptorProto_ExtensionRange;
-struct google_protobuf_DescriptorProto_ReservedRange;
-struct google_protobuf_ExtensionRangeOptions;
-struct google_protobuf_FieldDescriptorProto;
-struct google_protobuf_OneofDescriptorProto;
-struct google_protobuf_EnumDescriptorProto;
-struct google_protobuf_EnumDescriptorProto_EnumReservedRange;
-struct google_protobuf_EnumValueDescriptorProto;
-struct google_protobuf_ServiceDescriptorProto;
-struct google_protobuf_MethodDescriptorProto;
-struct google_protobuf_FileOptions;
-struct google_protobuf_MessageOptions;
-struct google_protobuf_FieldOptions;
-struct google_protobuf_OneofOptions;
-struct google_protobuf_EnumOptions;
-struct google_protobuf_EnumValueOptions;
-struct google_protobuf_ServiceOptions;
-struct google_protobuf_MethodOptions;
-struct google_protobuf_UninterpretedOption;
-struct google_protobuf_UninterpretedOption_NamePart;
-struct google_protobuf_SourceCodeInfo;
-struct google_protobuf_SourceCodeInfo_Location;
-struct google_protobuf_GeneratedCodeInfo;
-struct google_protobuf_GeneratedCodeInfo_Annotation;
-typedef struct google_protobuf_FileDescriptorSet google_protobuf_FileDescriptorSet;
-typedef struct google_protobuf_FileDescriptorProto google_protobuf_FileDescriptorProto;
-typedef struct google_protobuf_DescriptorProto google_protobuf_DescriptorProto;
-typedef struct google_protobuf_DescriptorProto_ExtensionRange google_protobuf_DescriptorProto_ExtensionRange;
-typedef struct google_protobuf_DescriptorProto_ReservedRange google_protobuf_DescriptorProto_ReservedRange;
-typedef struct google_protobuf_ExtensionRangeOptions google_protobuf_ExtensionRangeOptions;
-typedef struct google_protobuf_FieldDescriptorProto google_protobuf_FieldDescriptorProto;
-typedef struct google_protobuf_OneofDescriptorProto google_protobuf_OneofDescriptorProto;
-typedef struct google_protobuf_EnumDescriptorProto google_protobuf_EnumDescriptorProto;
-typedef struct google_protobuf_EnumDescriptorProto_EnumReservedRange google_protobuf_EnumDescriptorProto_EnumReservedRange;
-typedef struct google_protobuf_EnumValueDescriptorProto google_protobuf_EnumValueDescriptorProto;
-typedef struct google_protobuf_ServiceDescriptorProto google_protobuf_ServiceDescriptorProto;
-typedef struct google_protobuf_MethodDescriptorProto google_protobuf_MethodDescriptorProto;
-typedef struct google_protobuf_FileOptions google_protobuf_FileOptions;
-typedef struct google_protobuf_MessageOptions google_protobuf_MessageOptions;
-typedef struct google_protobuf_FieldOptions google_protobuf_FieldOptions;
-typedef struct google_protobuf_OneofOptions google_protobuf_OneofOptions;
-typedef struct google_protobuf_EnumOptions google_protobuf_EnumOptions;
-typedef struct google_protobuf_EnumValueOptions google_protobuf_EnumValueOptions;
-typedef struct google_protobuf_ServiceOptions google_protobuf_ServiceOptions;
-typedef struct google_protobuf_MethodOptions google_protobuf_MethodOptions;
-typedef struct google_protobuf_UninterpretedOption google_protobuf_UninterpretedOption;
-typedef struct google_protobuf_UninterpretedOption_NamePart google_protobuf_UninterpretedOption_NamePart;
-typedef struct google_protobuf_SourceCodeInfo google_protobuf_SourceCodeInfo;
-typedef struct google_protobuf_SourceCodeInfo_Location google_protobuf_SourceCodeInfo_Location;
-typedef struct google_protobuf_GeneratedCodeInfo google_protobuf_GeneratedCodeInfo;
-typedef struct google_protobuf_GeneratedCodeInfo_Annotation google_protobuf_GeneratedCodeInfo_Annotation;
-extern const upb_msglayout google_protobuf_FileDescriptorSet_msginit;
-extern const upb_msglayout google_protobuf_FileDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_DescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit;
-extern const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit;
-extern const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit;
-extern const upb_msglayout google_protobuf_FieldDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_OneofDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_EnumDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit;
-extern const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_MethodDescriptorProto_msginit;
-extern const upb_msglayout google_protobuf_FileOptions_msginit;
-extern const upb_msglayout google_protobuf_MessageOptions_msginit;
-extern const upb_msglayout google_protobuf_FieldOptions_msginit;
-extern const upb_msglayout google_protobuf_OneofOptions_msginit;
-extern const upb_msglayout google_protobuf_EnumOptions_msginit;
-extern const upb_msglayout google_protobuf_EnumValueOptions_msginit;
-extern const upb_msglayout google_protobuf_ServiceOptions_msginit;
-extern const upb_msglayout google_protobuf_MethodOptions_msginit;
-extern const upb_msglayout google_protobuf_UninterpretedOption_msginit;
-extern const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit;
-extern const upb_msglayout google_protobuf_SourceCodeInfo_msginit;
-extern const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit;
-extern const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit;
-extern const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit;
-
-typedef enum {
- google_protobuf_FieldDescriptorProto_LABEL_OPTIONAL = 1,
- google_protobuf_FieldDescriptorProto_LABEL_REQUIRED = 2,
- google_protobuf_FieldDescriptorProto_LABEL_REPEATED = 3
-} google_protobuf_FieldDescriptorProto_Label;
-
-typedef enum {
- google_protobuf_FieldDescriptorProto_TYPE_DOUBLE = 1,
- google_protobuf_FieldDescriptorProto_TYPE_FLOAT = 2,
- google_protobuf_FieldDescriptorProto_TYPE_INT64 = 3,
- google_protobuf_FieldDescriptorProto_TYPE_UINT64 = 4,
- google_protobuf_FieldDescriptorProto_TYPE_INT32 = 5,
- google_protobuf_FieldDescriptorProto_TYPE_FIXED64 = 6,
- google_protobuf_FieldDescriptorProto_TYPE_FIXED32 = 7,
- google_protobuf_FieldDescriptorProto_TYPE_BOOL = 8,
- google_protobuf_FieldDescriptorProto_TYPE_STRING = 9,
- google_protobuf_FieldDescriptorProto_TYPE_GROUP = 10,
- google_protobuf_FieldDescriptorProto_TYPE_MESSAGE = 11,
- google_protobuf_FieldDescriptorProto_TYPE_BYTES = 12,
- google_protobuf_FieldDescriptorProto_TYPE_UINT32 = 13,
- google_protobuf_FieldDescriptorProto_TYPE_ENUM = 14,
- google_protobuf_FieldDescriptorProto_TYPE_SFIXED32 = 15,
- google_protobuf_FieldDescriptorProto_TYPE_SFIXED64 = 16,
- google_protobuf_FieldDescriptorProto_TYPE_SINT32 = 17,
- google_protobuf_FieldDescriptorProto_TYPE_SINT64 = 18
-} google_protobuf_FieldDescriptorProto_Type;
-
-typedef enum {
- google_protobuf_FieldOptions_STRING = 0,
- google_protobuf_FieldOptions_CORD = 1,
- google_protobuf_FieldOptions_STRING_PIECE = 2
-} google_protobuf_FieldOptions_CType;
-
-typedef enum {
- google_protobuf_FieldOptions_JS_NORMAL = 0,
- google_protobuf_FieldOptions_JS_STRING = 1,
- google_protobuf_FieldOptions_JS_NUMBER = 2
-} google_protobuf_FieldOptions_JSType;
-
-typedef enum {
- google_protobuf_FileOptions_SPEED = 1,
- google_protobuf_FileOptions_CODE_SIZE = 2,
- google_protobuf_FileOptions_LITE_RUNTIME = 3
-} google_protobuf_FileOptions_OptimizeMode;
-
-typedef enum {
- google_protobuf_MethodOptions_IDEMPOTENCY_UNKNOWN = 0,
- google_protobuf_MethodOptions_NO_SIDE_EFFECTS = 1,
- google_protobuf_MethodOptions_IDEMPOTENT = 2
-} google_protobuf_MethodOptions_IdempotencyLevel;
-
-
-/* google.protobuf.FileDescriptorSet */
-
-UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/descriptor.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_FileDescriptorSet;
+struct google_protobuf_FileDescriptorProto;
+struct google_protobuf_DescriptorProto;
+struct google_protobuf_DescriptorProto_ExtensionRange;
+struct google_protobuf_DescriptorProto_ReservedRange;
+struct google_protobuf_ExtensionRangeOptions;
+struct google_protobuf_FieldDescriptorProto;
+struct google_protobuf_OneofDescriptorProto;
+struct google_protobuf_EnumDescriptorProto;
+struct google_protobuf_EnumDescriptorProto_EnumReservedRange;
+struct google_protobuf_EnumValueDescriptorProto;
+struct google_protobuf_ServiceDescriptorProto;
+struct google_protobuf_MethodDescriptorProto;
+struct google_protobuf_FileOptions;
+struct google_protobuf_MessageOptions;
+struct google_protobuf_FieldOptions;
+struct google_protobuf_OneofOptions;
+struct google_protobuf_EnumOptions;
+struct google_protobuf_EnumValueOptions;
+struct google_protobuf_ServiceOptions;
+struct google_protobuf_MethodOptions;
+struct google_protobuf_UninterpretedOption;
+struct google_protobuf_UninterpretedOption_NamePart;
+struct google_protobuf_SourceCodeInfo;
+struct google_protobuf_SourceCodeInfo_Location;
+struct google_protobuf_GeneratedCodeInfo;
+struct google_protobuf_GeneratedCodeInfo_Annotation;
+typedef struct google_protobuf_FileDescriptorSet google_protobuf_FileDescriptorSet;
+typedef struct google_protobuf_FileDescriptorProto google_protobuf_FileDescriptorProto;
+typedef struct google_protobuf_DescriptorProto google_protobuf_DescriptorProto;
+typedef struct google_protobuf_DescriptorProto_ExtensionRange google_protobuf_DescriptorProto_ExtensionRange;
+typedef struct google_protobuf_DescriptorProto_ReservedRange google_protobuf_DescriptorProto_ReservedRange;
+typedef struct google_protobuf_ExtensionRangeOptions google_protobuf_ExtensionRangeOptions;
+typedef struct google_protobuf_FieldDescriptorProto google_protobuf_FieldDescriptorProto;
+typedef struct google_protobuf_OneofDescriptorProto google_protobuf_OneofDescriptorProto;
+typedef struct google_protobuf_EnumDescriptorProto google_protobuf_EnumDescriptorProto;
+typedef struct google_protobuf_EnumDescriptorProto_EnumReservedRange google_protobuf_EnumDescriptorProto_EnumReservedRange;
+typedef struct google_protobuf_EnumValueDescriptorProto google_protobuf_EnumValueDescriptorProto;
+typedef struct google_protobuf_ServiceDescriptorProto google_protobuf_ServiceDescriptorProto;
+typedef struct google_protobuf_MethodDescriptorProto google_protobuf_MethodDescriptorProto;
+typedef struct google_protobuf_FileOptions google_protobuf_FileOptions;
+typedef struct google_protobuf_MessageOptions google_protobuf_MessageOptions;
+typedef struct google_protobuf_FieldOptions google_protobuf_FieldOptions;
+typedef struct google_protobuf_OneofOptions google_protobuf_OneofOptions;
+typedef struct google_protobuf_EnumOptions google_protobuf_EnumOptions;
+typedef struct google_protobuf_EnumValueOptions google_protobuf_EnumValueOptions;
+typedef struct google_protobuf_ServiceOptions google_protobuf_ServiceOptions;
+typedef struct google_protobuf_MethodOptions google_protobuf_MethodOptions;
+typedef struct google_protobuf_UninterpretedOption google_protobuf_UninterpretedOption;
+typedef struct google_protobuf_UninterpretedOption_NamePart google_protobuf_UninterpretedOption_NamePart;
+typedef struct google_protobuf_SourceCodeInfo google_protobuf_SourceCodeInfo;
+typedef struct google_protobuf_SourceCodeInfo_Location google_protobuf_SourceCodeInfo_Location;
+typedef struct google_protobuf_GeneratedCodeInfo google_protobuf_GeneratedCodeInfo;
+typedef struct google_protobuf_GeneratedCodeInfo_Annotation google_protobuf_GeneratedCodeInfo_Annotation;
+extern const upb_msglayout google_protobuf_FileDescriptorSet_msginit;
+extern const upb_msglayout google_protobuf_FileDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_DescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_DescriptorProto_ExtensionRange_msginit;
+extern const upb_msglayout google_protobuf_DescriptorProto_ReservedRange_msginit;
+extern const upb_msglayout google_protobuf_ExtensionRangeOptions_msginit;
+extern const upb_msglayout google_protobuf_FieldDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_OneofDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_EnumDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit;
+extern const upb_msglayout google_protobuf_EnumValueDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_ServiceDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_MethodDescriptorProto_msginit;
+extern const upb_msglayout google_protobuf_FileOptions_msginit;
+extern const upb_msglayout google_protobuf_MessageOptions_msginit;
+extern const upb_msglayout google_protobuf_FieldOptions_msginit;
+extern const upb_msglayout google_protobuf_OneofOptions_msginit;
+extern const upb_msglayout google_protobuf_EnumOptions_msginit;
+extern const upb_msglayout google_protobuf_EnumValueOptions_msginit;
+extern const upb_msglayout google_protobuf_ServiceOptions_msginit;
+extern const upb_msglayout google_protobuf_MethodOptions_msginit;
+extern const upb_msglayout google_protobuf_UninterpretedOption_msginit;
+extern const upb_msglayout google_protobuf_UninterpretedOption_NamePart_msginit;
+extern const upb_msglayout google_protobuf_SourceCodeInfo_msginit;
+extern const upb_msglayout google_protobuf_SourceCodeInfo_Location_msginit;
+extern const upb_msglayout google_protobuf_GeneratedCodeInfo_msginit;
+extern const upb_msglayout google_protobuf_GeneratedCodeInfo_Annotation_msginit;
+
+typedef enum {
+ google_protobuf_FieldDescriptorProto_LABEL_OPTIONAL = 1,
+ google_protobuf_FieldDescriptorProto_LABEL_REQUIRED = 2,
+ google_protobuf_FieldDescriptorProto_LABEL_REPEATED = 3
+} google_protobuf_FieldDescriptorProto_Label;
+
+typedef enum {
+ google_protobuf_FieldDescriptorProto_TYPE_DOUBLE = 1,
+ google_protobuf_FieldDescriptorProto_TYPE_FLOAT = 2,
+ google_protobuf_FieldDescriptorProto_TYPE_INT64 = 3,
+ google_protobuf_FieldDescriptorProto_TYPE_UINT64 = 4,
+ google_protobuf_FieldDescriptorProto_TYPE_INT32 = 5,
+ google_protobuf_FieldDescriptorProto_TYPE_FIXED64 = 6,
+ google_protobuf_FieldDescriptorProto_TYPE_FIXED32 = 7,
+ google_protobuf_FieldDescriptorProto_TYPE_BOOL = 8,
+ google_protobuf_FieldDescriptorProto_TYPE_STRING = 9,
+ google_protobuf_FieldDescriptorProto_TYPE_GROUP = 10,
+ google_protobuf_FieldDescriptorProto_TYPE_MESSAGE = 11,
+ google_protobuf_FieldDescriptorProto_TYPE_BYTES = 12,
+ google_protobuf_FieldDescriptorProto_TYPE_UINT32 = 13,
+ google_protobuf_FieldDescriptorProto_TYPE_ENUM = 14,
+ google_protobuf_FieldDescriptorProto_TYPE_SFIXED32 = 15,
+ google_protobuf_FieldDescriptorProto_TYPE_SFIXED64 = 16,
+ google_protobuf_FieldDescriptorProto_TYPE_SINT32 = 17,
+ google_protobuf_FieldDescriptorProto_TYPE_SINT64 = 18
+} google_protobuf_FieldDescriptorProto_Type;
+
+typedef enum {
+ google_protobuf_FieldOptions_STRING = 0,
+ google_protobuf_FieldOptions_CORD = 1,
+ google_protobuf_FieldOptions_STRING_PIECE = 2
+} google_protobuf_FieldOptions_CType;
+
+typedef enum {
+ google_protobuf_FieldOptions_JS_NORMAL = 0,
+ google_protobuf_FieldOptions_JS_STRING = 1,
+ google_protobuf_FieldOptions_JS_NUMBER = 2
+} google_protobuf_FieldOptions_JSType;
+
+typedef enum {
+ google_protobuf_FileOptions_SPEED = 1,
+ google_protobuf_FileOptions_CODE_SIZE = 2,
+ google_protobuf_FileOptions_LITE_RUNTIME = 3
+} google_protobuf_FileOptions_OptimizeMode;
+
+typedef enum {
+ google_protobuf_MethodOptions_IDEMPOTENCY_UNKNOWN = 0,
+ google_protobuf_MethodOptions_NO_SIDE_EFFECTS = 1,
+ google_protobuf_MethodOptions_IDEMPOTENT = 2
+} google_protobuf_MethodOptions_IdempotencyLevel;
+
+
+/* google.protobuf.FileDescriptorSet */
+
+UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_new(upb_arena *arena) {
return (google_protobuf_FileDescriptorSet *)_upb_msg_new(&google_protobuf_FileDescriptorSet_msginit, arena);
-}
-UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_FileDescriptorSet *ret = google_protobuf_FileDescriptorSet_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_FileDescriptorSet_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_FileDescriptorSet_serialize(const google_protobuf_FileDescriptorSet *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_FileDescriptorSet_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_FileDescriptorSet *ret = google_protobuf_FileDescriptorSet_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_FileDescriptorSet_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_FileDescriptorSet_serialize(const google_protobuf_FileDescriptorSet *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_FileDescriptorSet_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_FileDescriptorSet_has_file(const google_protobuf_FileDescriptorSet *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const google_protobuf_FileDescriptorProto* const* google_protobuf_FileDescriptorSet_file(const google_protobuf_FileDescriptorSet *msg, size_t *len) { return (const google_protobuf_FileDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_mutable_file(google_protobuf_FileDescriptorSet *msg, size_t *len) {
- return (google_protobuf_FileDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_resize_file(google_protobuf_FileDescriptorSet *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const google_protobuf_FileDescriptorProto* const* google_protobuf_FileDescriptorSet_file(const google_protobuf_FileDescriptorSet *msg, size_t *len) { return (const google_protobuf_FileDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_mutable_file(google_protobuf_FileDescriptorSet *msg, size_t *len) {
+ return (google_protobuf_FileDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_resize_file(google_protobuf_FileDescriptorSet *msg, size_t len, upb_arena *arena) {
return (google_protobuf_FileDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_FileDescriptorProto* google_protobuf_FileDescriptorSet_add_file(google_protobuf_FileDescriptorSet *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_FileDescriptorProto* google_protobuf_FileDescriptorSet_add_file(google_protobuf_FileDescriptorSet *msg, upb_arena *arena) {
struct google_protobuf_FileDescriptorProto* sub = (struct google_protobuf_FileDescriptorProto*)_upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.FileDescriptorProto */
-
-UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.FileDescriptorProto */
+
+UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_FileDescriptorProto *)_upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_FileDescriptorProto *ret = google_protobuf_FileDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_FileDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_FileDescriptorProto_serialize(const google_protobuf_FileDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_FileDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_FileDescriptorProto *ret = google_protobuf_FileDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_FileDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_FileDescriptorProto_serialize(const google_protobuf_FileDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_FileDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_name(const google_protobuf_FileDescriptorProto *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_package(const google_protobuf_FileDescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
-UPB_INLINE upb_strview const* google_protobuf_FileDescriptorProto_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
+UPB_INLINE upb_strview const* google_protobuf_FileDescriptorProto_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_message_type(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 80)); }
-UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_FileDescriptorProto_message_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
+UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_FileDescriptorProto_message_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_enum_type(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(44, 88)); }
-UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_FileDescriptorProto_enum_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
+UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_FileDescriptorProto_enum_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_service(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(48, 96)); }
-UPB_INLINE const google_protobuf_ServiceDescriptorProto* const* google_protobuf_FileDescriptorProto_service(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_ServiceDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(48, 96), len); }
+UPB_INLINE const google_protobuf_ServiceDescriptorProto* const* google_protobuf_FileDescriptorProto_service(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_ServiceDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(48, 96), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_extension(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(52, 104)); }
-UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_FileDescriptorProto_extension(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(52, 104), len); }
+UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_FileDescriptorProto_extension(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(52, 104), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_options(const google_protobuf_FileDescriptorProto *msg) { return _upb_hasbit(msg, 4); }
UPB_INLINE const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 56), const google_protobuf_FileOptions*); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 64), const google_protobuf_SourceCodeInfo*); }
-UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_public_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(56, 112), len); }
-UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_weak_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(60, 120), len); }
+UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_public_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(56, 112), len); }
+UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_weak_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(60, 120), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_syntax(const google_protobuf_FileDescriptorProto *msg) { return _upb_hasbit(msg, 3); }
UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview); }
-
-UPB_INLINE void google_protobuf_FileDescriptorProto_set_name(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void google_protobuf_FileDescriptorProto_set_name(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileDescriptorProto_set_package(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_FileDescriptorProto_set_package(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
-}
-UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_mutable_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
-}
-UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_resize_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_mutable_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
+}
+UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_resize_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool google_protobuf_FileDescriptorProto_add_dependency(google_protobuf_FileDescriptorProto *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_FileDescriptorProto_add_dependency(google_protobuf_FileDescriptorProto *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(36, 72), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_mutable_message_type(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
-}
-UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_resize_message_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_mutable_message_type(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
+}
+UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_resize_message_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_FileDescriptorProto_add_message_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_FileDescriptorProto_add_message_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_FileDescriptorProto_mutable_enum_type(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_FileDescriptorProto_resize_enum_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_FileDescriptorProto_mutable_enum_type(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_FileDescriptorProto_resize_enum_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_FileDescriptorProto_add_enum_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_FileDescriptorProto_add_enum_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(44, 88), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_ServiceDescriptorProto** google_protobuf_FileDescriptorProto_mutable_service(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (google_protobuf_ServiceDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 96), len);
-}
-UPB_INLINE google_protobuf_ServiceDescriptorProto** google_protobuf_FileDescriptorProto_resize_service(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(44, 88), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_ServiceDescriptorProto** google_protobuf_FileDescriptorProto_mutable_service(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_ServiceDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 96), len);
+}
+UPB_INLINE google_protobuf_ServiceDescriptorProto** google_protobuf_FileDescriptorProto_resize_service(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_ServiceDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(48, 96), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_ServiceDescriptorProto* google_protobuf_FileDescriptorProto_add_service(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_ServiceDescriptorProto* google_protobuf_FileDescriptorProto_add_service(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_ServiceDescriptorProto* sub = (struct google_protobuf_ServiceDescriptorProto*)_upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(48, 96), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_FileDescriptorProto_mutable_extension(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 104), len);
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_FileDescriptorProto_resize_extension(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(48, 96), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_FileDescriptorProto_mutable_extension(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 104), len);
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_FileDescriptorProto_resize_extension(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(52, 104), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_FileDescriptorProto_add_extension(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_FileDescriptorProto_add_extension(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(52, 104), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_protobuf_FileDescriptorProto_set_options(google_protobuf_FileDescriptorProto *msg, google_protobuf_FileOptions* value) {
- _upb_sethas(msg, 4);
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(52, 104), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_protobuf_FileDescriptorProto_set_options(google_protobuf_FileDescriptorProto *msg, google_protobuf_FileOptions* value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(28, 56), google_protobuf_FileOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_mutable_options(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FileOptions* sub = (struct google_protobuf_FileOptions*)google_protobuf_FileDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_mutable_options(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_FileOptions* sub = (struct google_protobuf_FileOptions*)google_protobuf_FileDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_FileOptions*)_upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_FileDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void google_protobuf_FileDescriptorProto_set_source_code_info(google_protobuf_FileDescriptorProto *msg, google_protobuf_SourceCodeInfo* value) {
- _upb_sethas(msg, 5);
+ if (!sub) return NULL;
+ google_protobuf_FileDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void google_protobuf_FileDescriptorProto_set_source_code_info(google_protobuf_FileDescriptorProto *msg, google_protobuf_SourceCodeInfo* value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(32, 64), google_protobuf_SourceCodeInfo*) = value;
-}
-UPB_INLINE struct google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_mutable_source_code_info(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_SourceCodeInfo* sub = (struct google_protobuf_SourceCodeInfo*)google_protobuf_FileDescriptorProto_source_code_info(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_mutable_source_code_info(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_SourceCodeInfo* sub = (struct google_protobuf_SourceCodeInfo*)google_protobuf_FileDescriptorProto_source_code_info(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_SourceCodeInfo*)_upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_FileDescriptorProto_set_source_code_info(msg, sub);
- }
- return sub;
-}
-UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_mutable_public_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 112), len);
-}
-UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_public_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_FileDescriptorProto_set_source_code_info(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_mutable_public_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 112), len);
+}
+UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_public_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(56, 112), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool google_protobuf_FileDescriptorProto_add_public_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_FileDescriptorProto_add_public_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(56, 112), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_mutable_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(60, 120), len);
-}
-UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_mutable_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(60, 120), len);
+}
+UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(60, 120), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool google_protobuf_FileDescriptorProto_add_weak_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_FileDescriptorProto_add_weak_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(60, 120), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE void google_protobuf_FileDescriptorProto_set_syntax(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_FileDescriptorProto_set_syntax(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview) = value;
-}
-
-/* google.protobuf.DescriptorProto */
-
-UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_new(upb_arena *arena) {
+}
+
+/* google.protobuf.DescriptorProto */
+
+UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_new(upb_arena *arena) {
return (google_protobuf_DescriptorProto *)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_DescriptorProto *ret = google_protobuf_DescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_DescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_DescriptorProto_serialize(const google_protobuf_DescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_DescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_DescriptorProto *ret = google_protobuf_DescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_DescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_DescriptorProto_serialize(const google_protobuf_DescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_DescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_DescriptorProto_has_name(const google_protobuf_DescriptorProto *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE upb_strview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_field(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
-UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_field(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
+UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_field(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_nested_type(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
-UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_DescriptorProto_nested_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
+UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_DescriptorProto_nested_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_enum_type(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(24, 48)); }
-UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_DescriptorProto_enum_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_DescriptorProto_enum_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_extension_range(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 56)); }
-UPB_INLINE const google_protobuf_DescriptorProto_ExtensionRange* const* google_protobuf_DescriptorProto_extension_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ExtensionRange* const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
+UPB_INLINE const google_protobuf_DescriptorProto_ExtensionRange* const* google_protobuf_DescriptorProto_extension_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ExtensionRange* const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_extension(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(32, 64)); }
-UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_extension(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(32, 64), len); }
+UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_extension(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(32, 64), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_options(const google_protobuf_DescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_MessageOptions*); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_oneof_decl(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(36, 72)); }
-UPB_INLINE const google_protobuf_OneofDescriptorProto* const* google_protobuf_DescriptorProto_oneof_decl(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_OneofDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
+UPB_INLINE const google_protobuf_OneofDescriptorProto* const* google_protobuf_DescriptorProto_oneof_decl(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_OneofDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_reserved_range(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 80)); }
-UPB_INLINE const google_protobuf_DescriptorProto_ReservedRange* const* google_protobuf_DescriptorProto_reserved_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
-UPB_INLINE upb_strview const* google_protobuf_DescriptorProto_reserved_name(const google_protobuf_DescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
-
-UPB_INLINE void google_protobuf_DescriptorProto_set_name(google_protobuf_DescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_DescriptorProto_ReservedRange* const* google_protobuf_DescriptorProto_reserved_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
+UPB_INLINE upb_strview const* google_protobuf_DescriptorProto_reserved_name(const google_protobuf_DescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
+
+UPB_INLINE void google_protobuf_DescriptorProto_set_name(google_protobuf_DescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_mutable_field(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_field(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_mutable_field(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_field(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_field(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_field(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_DescriptorProto_mutable_nested_type(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
-}
-UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_DescriptorProto_resize_nested_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_DescriptorProto_mutable_nested_type(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
+}
+UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_DescriptorProto_resize_nested_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_DescriptorProto_add_nested_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_DescriptorProto_add_nested_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_DescriptorProto_mutable_enum_type(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_DescriptorProto_resize_enum_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_DescriptorProto_mutable_enum_type(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_DescriptorProto_resize_enum_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_DescriptorProto_add_enum_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_DescriptorProto_add_enum_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange** google_protobuf_DescriptorProto_mutable_extension_range(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
-}
-UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange** google_protobuf_DescriptorProto_resize_extension_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange** google_protobuf_DescriptorProto_mutable_extension_range(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
+}
+UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange** google_protobuf_DescriptorProto_resize_extension_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_DescriptorProto_ExtensionRange* google_protobuf_DescriptorProto_add_extension_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_DescriptorProto_ExtensionRange* google_protobuf_DescriptorProto_add_extension_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_DescriptorProto_ExtensionRange* sub = (struct google_protobuf_DescriptorProto_ExtensionRange*)_upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(28, 56), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_mutable_extension(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(32, 64), len);
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_extension(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(28, 56), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_mutable_extension(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(32, 64), len);
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_extension(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(32, 64), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_extension(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_extension(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(32, 64), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_protobuf_DescriptorProto_set_options(google_protobuf_DescriptorProto *msg, google_protobuf_MessageOptions* value) {
- _upb_sethas(msg, 2);
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(32, 64), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_protobuf_DescriptorProto_set_options(google_protobuf_DescriptorProto *msg, google_protobuf_MessageOptions* value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_MessageOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_MessageOptions* google_protobuf_DescriptorProto_mutable_options(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_MessageOptions* sub = (struct google_protobuf_MessageOptions*)google_protobuf_DescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_MessageOptions* google_protobuf_DescriptorProto_mutable_options(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_MessageOptions* sub = (struct google_protobuf_MessageOptions*)google_protobuf_DescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_MessageOptions*)_upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_DescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-UPB_INLINE google_protobuf_OneofDescriptorProto** google_protobuf_DescriptorProto_mutable_oneof_decl(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_OneofDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
-}
-UPB_INLINE google_protobuf_OneofDescriptorProto** google_protobuf_DescriptorProto_resize_oneof_decl(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_DescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE google_protobuf_OneofDescriptorProto** google_protobuf_DescriptorProto_mutable_oneof_decl(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_OneofDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
+}
+UPB_INLINE google_protobuf_OneofDescriptorProto** google_protobuf_DescriptorProto_resize_oneof_decl(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_OneofDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_OneofDescriptorProto* google_protobuf_DescriptorProto_add_oneof_decl(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_OneofDescriptorProto* google_protobuf_DescriptorProto_add_oneof_decl(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_OneofDescriptorProto* sub = (struct google_protobuf_OneofDescriptorProto*)_upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(36, 72), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE google_protobuf_DescriptorProto_ReservedRange** google_protobuf_DescriptorProto_mutable_reserved_range(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
-}
-UPB_INLINE google_protobuf_DescriptorProto_ReservedRange** google_protobuf_DescriptorProto_resize_reserved_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(36, 72), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE google_protobuf_DescriptorProto_ReservedRange** google_protobuf_DescriptorProto_mutable_reserved_range(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
+}
+UPB_INLINE google_protobuf_DescriptorProto_ReservedRange** google_protobuf_DescriptorProto_resize_reserved_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_DescriptorProto_ReservedRange* google_protobuf_DescriptorProto_add_reserved_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_DescriptorProto_ReservedRange* google_protobuf_DescriptorProto_add_reserved_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_DescriptorProto_ReservedRange* sub = (struct google_protobuf_DescriptorProto_ReservedRange*)_upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE upb_strview* google_protobuf_DescriptorProto_mutable_reserved_name(google_protobuf_DescriptorProto *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
-}
-UPB_INLINE upb_strview* google_protobuf_DescriptorProto_resize_reserved_name(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE upb_strview* google_protobuf_DescriptorProto_mutable_reserved_name(google_protobuf_DescriptorProto *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
+}
+UPB_INLINE upb_strview* google_protobuf_DescriptorProto_resize_reserved_name(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool google_protobuf_DescriptorProto_add_reserved_name(google_protobuf_DescriptorProto *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_DescriptorProto_add_reserved_name(google_protobuf_DescriptorProto *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(44, 88), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-
-/* google.protobuf.DescriptorProto.ExtensionRange */
-
-UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_new(upb_arena *arena) {
+}
+
+/* google.protobuf.DescriptorProto.ExtensionRange */
+
+UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_new(upb_arena *arena) {
return (google_protobuf_DescriptorProto_ExtensionRange *)_upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
-}
-UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_DescriptorProto_ExtensionRange *ret = google_protobuf_DescriptorProto_ExtensionRange_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_DescriptorProto_ExtensionRange_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_DescriptorProto_ExtensionRange_serialize(const google_protobuf_DescriptorProto_ExtensionRange *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_DescriptorProto_ExtensionRange_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_DescriptorProto_ExtensionRange *ret = google_protobuf_DescriptorProto_ExtensionRange_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_DescriptorProto_ExtensionRange_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_DescriptorProto_ExtensionRange_serialize(const google_protobuf_DescriptorProto_ExtensionRange *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_DescriptorProto_ExtensionRange_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_hasbit(msg, 3); }
UPB_INLINE const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), const google_protobuf_ExtensionRangeOptions*); }
-
-UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_start(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_start(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_end(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_end(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_options(google_protobuf_DescriptorProto_ExtensionRange *msg, google_protobuf_ExtensionRangeOptions* value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_options(google_protobuf_DescriptorProto_ExtensionRange *msg, google_protobuf_ExtensionRangeOptions* value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 16), google_protobuf_ExtensionRangeOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_mutable_options(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_arena *arena) {
- struct google_protobuf_ExtensionRangeOptions* sub = (struct google_protobuf_ExtensionRangeOptions*)google_protobuf_DescriptorProto_ExtensionRange_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_mutable_options(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_arena *arena) {
+ struct google_protobuf_ExtensionRangeOptions* sub = (struct google_protobuf_ExtensionRangeOptions*)google_protobuf_DescriptorProto_ExtensionRange_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_ExtensionRangeOptions*)_upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_DescriptorProto_ExtensionRange_set_options(msg, sub);
- }
- return sub;
-}
-
-/* google.protobuf.DescriptorProto.ReservedRange */
-
-UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_DescriptorProto_ExtensionRange_set_options(msg, sub);
+ }
+ return sub;
+}
+
+/* google.protobuf.DescriptorProto.ReservedRange */
+
+UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_new(upb_arena *arena) {
return (google_protobuf_DescriptorProto_ReservedRange *)_upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
-}
-UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_DescriptorProto_ReservedRange *ret = google_protobuf_DescriptorProto_ReservedRange_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_DescriptorProto_ReservedRange_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_DescriptorProto_ReservedRange_serialize(const google_protobuf_DescriptorProto_ReservedRange *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_DescriptorProto_ReservedRange_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_DescriptorProto_ReservedRange *ret = google_protobuf_DescriptorProto_ReservedRange_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_DescriptorProto_ReservedRange_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_DescriptorProto_ReservedRange_serialize(const google_protobuf_DescriptorProto_ReservedRange *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_DescriptorProto_ReservedRange_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_DescriptorProto_ReservedRange_has_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ReservedRange_has_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
-
-UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_start(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_start(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_end(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_end(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-
-/* google.protobuf.ExtensionRangeOptions */
-
-UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_new(upb_arena *arena) {
+}
+
+/* google.protobuf.ExtensionRangeOptions */
+
+UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_new(upb_arena *arena) {
return (google_protobuf_ExtensionRangeOptions *)_upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_ExtensionRangeOptions *ret = google_protobuf_ExtensionRangeOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_ExtensionRangeOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_ExtensionRangeOptions_serialize(const google_protobuf_ExtensionRangeOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_ExtensionRangeOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_ExtensionRangeOptions *ret = google_protobuf_ExtensionRangeOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_ExtensionRangeOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_ExtensionRangeOptions_serialize(const google_protobuf_ExtensionRangeOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_ExtensionRangeOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_ExtensionRangeOptions_has_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ExtensionRangeOptions_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_mutable_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_resize_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ExtensionRangeOptions_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_mutable_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_resize_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ExtensionRangeOptions_add_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ExtensionRangeOptions_add_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.FieldDescriptorProto */
-
-UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.FieldDescriptorProto */
+
+UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_FieldDescriptorProto *)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_FieldDescriptorProto *ret = google_protobuf_FieldDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_FieldDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_FieldDescriptorProto_serialize(const google_protobuf_FieldDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_FieldDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_FieldDescriptorProto *ret = google_protobuf_FieldDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_FieldDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_FieldDescriptorProto_serialize(const google_protobuf_FieldDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_FieldDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_hasbit(msg, 6); }
UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(36, 40), upb_strview); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_extendee(const google_protobuf_FieldDescriptorProto *msg) { return _upb_hasbit(msg, 7); }
@@ -632,313 +632,313 @@ UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_json_name(const google_
UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(68, 104), upb_strview); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_proto3_optional(const google_protobuf_FieldDescriptorProto *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_proto3_optional(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), bool); }
-
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
+
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(36, 40), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_extendee(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_extendee(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 7);
*UPB_PTR_AT(msg, UPB_SIZE(44, 56), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_number(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_number(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_label(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_label(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 8);
*UPB_PTR_AT(msg, UPB_SIZE(52, 72), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_default_value(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_default_value(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 9);
*UPB_PTR_AT(msg, UPB_SIZE(60, 88), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_options(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldOptions* value) {
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_options(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldOptions* value) {
_upb_sethas(msg, 11);
*UPB_PTR_AT(msg, UPB_SIZE(76, 120), google_protobuf_FieldOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_mutable_options(google_protobuf_FieldDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldOptions* sub = (struct google_protobuf_FieldOptions*)google_protobuf_FieldDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_mutable_options(google_protobuf_FieldDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_FieldOptions* sub = (struct google_protobuf_FieldOptions*)google_protobuf_FieldDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_FieldOptions*)_upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_FieldDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_oneof_index(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
- _upb_sethas(msg, 4);
+ if (!sub) return NULL;
+ google_protobuf_FieldDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_oneof_index(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(28, 28), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FieldDescriptorProto_set_json_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_json_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 10);
*UPB_PTR_AT(msg, UPB_SIZE(68, 104), upb_strview) = value;
-}
+}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_proto3_optional(google_protobuf_FieldDescriptorProto *msg, bool value) {
_upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), bool) = value;
}
-
-/* google.protobuf.OneofDescriptorProto */
-
-UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_new(upb_arena *arena) {
+
+/* google.protobuf.OneofDescriptorProto */
+
+UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_OneofDescriptorProto *)_upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_OneofDescriptorProto *ret = google_protobuf_OneofDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_OneofDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_OneofDescriptorProto_serialize(const google_protobuf_OneofDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_OneofDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_OneofDescriptorProto *ret = google_protobuf_OneofDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_OneofDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_OneofDescriptorProto_serialize(const google_protobuf_OneofDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_OneofDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_OneofDescriptorProto_has_name(const google_protobuf_OneofDescriptorProto *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE upb_strview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_OneofDescriptorProto_has_options(const google_protobuf_OneofDescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_OneofOptions*); }
-
-UPB_INLINE void google_protobuf_OneofDescriptorProto_set_name(google_protobuf_OneofDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void google_protobuf_OneofDescriptorProto_set_name(google_protobuf_OneofDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_OneofDescriptorProto_set_options(google_protobuf_OneofDescriptorProto *msg, google_protobuf_OneofOptions* value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_OneofDescriptorProto_set_options(google_protobuf_OneofDescriptorProto *msg, google_protobuf_OneofOptions* value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_OneofOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_mutable_options(google_protobuf_OneofDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_OneofOptions* sub = (struct google_protobuf_OneofOptions*)google_protobuf_OneofDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_mutable_options(google_protobuf_OneofDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_OneofOptions* sub = (struct google_protobuf_OneofOptions*)google_protobuf_OneofDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_OneofOptions*)_upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_OneofDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-
-/* google.protobuf.EnumDescriptorProto */
-
-UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_OneofDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+
+/* google.protobuf.EnumDescriptorProto */
+
+UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_EnumDescriptorProto *)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_EnumDescriptorProto *ret = google_protobuf_EnumDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_EnumDescriptorProto_serialize(const google_protobuf_EnumDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_EnumDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_EnumDescriptorProto *ret = google_protobuf_EnumDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_EnumDescriptorProto_serialize(const google_protobuf_EnumDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_EnumDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_name(const google_protobuf_EnumDescriptorProto *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE upb_strview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_value(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
-UPB_INLINE const google_protobuf_EnumValueDescriptorProto* const* google_protobuf_EnumDescriptorProto_value(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumValueDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
+UPB_INLINE const google_protobuf_EnumValueDescriptorProto* const* google_protobuf_EnumDescriptorProto_value(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumValueDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_options(const google_protobuf_EnumDescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_EnumOptions*); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_reserved_range(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
-UPB_INLINE const google_protobuf_EnumDescriptorProto_EnumReservedRange* const* google_protobuf_EnumDescriptorProto_reserved_range(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto_EnumReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
-UPB_INLINE upb_strview const* google_protobuf_EnumDescriptorProto_reserved_name(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
-
-UPB_INLINE void google_protobuf_EnumDescriptorProto_set_name(google_protobuf_EnumDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_EnumDescriptorProto_EnumReservedRange* const* google_protobuf_EnumDescriptorProto_reserved_range(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto_EnumReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
+UPB_INLINE upb_strview const* google_protobuf_EnumDescriptorProto_reserved_name(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+
+UPB_INLINE void google_protobuf_EnumDescriptorProto_set_name(google_protobuf_EnumDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_mutable_value(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
- return (google_protobuf_EnumValueDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
-}
-UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_resize_value(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_mutable_value(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_EnumValueDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
+}
+UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_resize_value(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_EnumValueDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_EnumValueDescriptorProto* google_protobuf_EnumDescriptorProto_add_value(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_EnumValueDescriptorProto* google_protobuf_EnumDescriptorProto_add_value(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumValueDescriptorProto* sub = (struct google_protobuf_EnumValueDescriptorProto*)_upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_protobuf_EnumDescriptorProto_set_options(google_protobuf_EnumDescriptorProto *msg, google_protobuf_EnumOptions* value) {
- _upb_sethas(msg, 2);
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_protobuf_EnumDescriptorProto_set_options(google_protobuf_EnumDescriptorProto *msg, google_protobuf_EnumOptions* value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_EnumOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_mutable_options(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumOptions* sub = (struct google_protobuf_EnumOptions*)google_protobuf_EnumDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_mutable_options(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_EnumOptions* sub = (struct google_protobuf_EnumOptions*)google_protobuf_EnumDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_EnumOptions*)_upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_EnumDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange** google_protobuf_EnumDescriptorProto_mutable_reserved_range(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
- return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange** google_protobuf_EnumDescriptorProto_resize_reserved_range(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_EnumDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange** google_protobuf_EnumDescriptorProto_mutable_reserved_range(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange** google_protobuf_EnumDescriptorProto_resize_reserved_range(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_EnumDescriptorProto_EnumReservedRange* google_protobuf_EnumDescriptorProto_add_reserved_range(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_EnumDescriptorProto_EnumReservedRange* google_protobuf_EnumDescriptorProto_add_reserved_range(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumDescriptorProto_EnumReservedRange* sub = (struct google_protobuf_EnumDescriptorProto_EnumReservedRange*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE upb_strview* google_protobuf_EnumDescriptorProto_mutable_reserved_name(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
-}
-UPB_INLINE upb_strview* google_protobuf_EnumDescriptorProto_resize_reserved_name(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE upb_strview* google_protobuf_EnumDescriptorProto_mutable_reserved_name(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
+}
+UPB_INLINE upb_strview* google_protobuf_EnumDescriptorProto_resize_reserved_name(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool google_protobuf_EnumDescriptorProto_add_reserved_name(google_protobuf_EnumDescriptorProto *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_EnumDescriptorProto_add_reserved_name(google_protobuf_EnumDescriptorProto *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-
-/* google.protobuf.EnumDescriptorProto.EnumReservedRange */
-
-UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_new(upb_arena *arena) {
+}
+
+/* google.protobuf.EnumDescriptorProto.EnumReservedRange */
+
+UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_new(upb_arena *arena) {
return (google_protobuf_EnumDescriptorProto_EnumReservedRange *)_upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
-}
-UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_EnumDescriptorProto_EnumReservedRange *ret = google_protobuf_EnumDescriptorProto_EnumReservedRange_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_EnumDescriptorProto_EnumReservedRange_serialize(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_EnumDescriptorProto_EnumReservedRange *ret = google_protobuf_EnumDescriptorProto_EnumReservedRange_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_EnumDescriptorProto_EnumReservedRange_serialize(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_EnumDescriptorProto_EnumReservedRange_has_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_EnumReservedRange_has_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
-
-UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_start(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_start(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_end(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_end(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-
-/* google.protobuf.EnumValueDescriptorProto */
-
-UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_new(upb_arena *arena) {
+}
+
+/* google.protobuf.EnumValueDescriptorProto */
+
+UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_EnumValueDescriptorProto *)_upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_EnumValueDescriptorProto *ret = google_protobuf_EnumValueDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumValueDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_EnumValueDescriptorProto_serialize(const google_protobuf_EnumValueDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_EnumValueDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_EnumValueDescriptorProto *ret = google_protobuf_EnumValueDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumValueDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_EnumValueDescriptorProto_serialize(const google_protobuf_EnumValueDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_EnumValueDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_name(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE upb_strview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_number(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_options(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_hasbit(msg, 3); }
UPB_INLINE const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 24), const google_protobuf_EnumValueOptions*); }
-
-UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_name(google_protobuf_EnumValueDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 2);
+
+UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_name(google_protobuf_EnumValueDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_number(google_protobuf_EnumValueDescriptorProto *msg, int32_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_number(google_protobuf_EnumValueDescriptorProto *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_options(google_protobuf_EnumValueDescriptorProto *msg, google_protobuf_EnumValueOptions* value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_options(google_protobuf_EnumValueDescriptorProto *msg, google_protobuf_EnumValueOptions* value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(16, 24), google_protobuf_EnumValueOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_mutable_options(google_protobuf_EnumValueDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumValueOptions* sub = (struct google_protobuf_EnumValueOptions*)google_protobuf_EnumValueDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_mutable_options(google_protobuf_EnumValueDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_EnumValueOptions* sub = (struct google_protobuf_EnumValueOptions*)google_protobuf_EnumValueDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_EnumValueOptions*)_upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_EnumValueDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-
-/* google.protobuf.ServiceDescriptorProto */
-
-UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_EnumValueDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+
+/* google.protobuf.ServiceDescriptorProto */
+
+UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_ServiceDescriptorProto *)_upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_ServiceDescriptorProto *ret = google_protobuf_ServiceDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_ServiceDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_ServiceDescriptorProto_serialize(const google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_ServiceDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_ServiceDescriptorProto *ret = google_protobuf_ServiceDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_ServiceDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_ServiceDescriptorProto_serialize(const google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_ServiceDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_name(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE upb_strview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_method(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
-UPB_INLINE const google_protobuf_MethodDescriptorProto* const* google_protobuf_ServiceDescriptorProto_method(const google_protobuf_ServiceDescriptorProto *msg, size_t *len) { return (const google_protobuf_MethodDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
+UPB_INLINE const google_protobuf_MethodDescriptorProto* const* google_protobuf_ServiceDescriptorProto_method(const google_protobuf_ServiceDescriptorProto *msg, size_t *len) { return (const google_protobuf_MethodDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_options(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_ServiceOptions*); }
-
-UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_name(google_protobuf_ServiceDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_name(google_protobuf_ServiceDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_mutable_method(google_protobuf_ServiceDescriptorProto *msg, size_t *len) {
- return (google_protobuf_MethodDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
-}
-UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_resize_method(google_protobuf_ServiceDescriptorProto *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_mutable_method(google_protobuf_ServiceDescriptorProto *msg, size_t *len) {
+ return (google_protobuf_MethodDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
+}
+UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_resize_method(google_protobuf_ServiceDescriptorProto *msg, size_t len, upb_arena *arena) {
return (google_protobuf_MethodDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_MethodDescriptorProto* google_protobuf_ServiceDescriptorProto_add_method(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_MethodDescriptorProto* google_protobuf_ServiceDescriptorProto_add_method(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_MethodDescriptorProto* sub = (struct google_protobuf_MethodDescriptorProto*)_upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_options(google_protobuf_ServiceDescriptorProto *msg, google_protobuf_ServiceOptions* value) {
- _upb_sethas(msg, 2);
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_options(google_protobuf_ServiceDescriptorProto *msg, google_protobuf_ServiceOptions* value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_ServiceOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_mutable_options(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_ServiceOptions* sub = (struct google_protobuf_ServiceOptions*)google_protobuf_ServiceDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_mutable_options(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_ServiceOptions* sub = (struct google_protobuf_ServiceOptions*)google_protobuf_ServiceDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_ServiceOptions*)_upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_ServiceDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-
-/* google.protobuf.MethodDescriptorProto */
-
-UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_ServiceDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+
+/* google.protobuf.MethodDescriptorProto */
+
+UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_new(upb_arena *arena) {
return (google_protobuf_MethodDescriptorProto *)_upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
-}
-UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_MethodDescriptorProto *ret = google_protobuf_MethodDescriptorProto_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_MethodDescriptorProto_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_MethodDescriptorProto_serialize(const google_protobuf_MethodDescriptorProto *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_MethodDescriptorProto_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_MethodDescriptorProto *ret = google_protobuf_MethodDescriptorProto_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_MethodDescriptorProto_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_MethodDescriptorProto_serialize(const google_protobuf_MethodDescriptorProto *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_MethodDescriptorProto_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_name(const google_protobuf_MethodDescriptorProto *msg) { return _upb_hasbit(msg, 3); }
UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_input_type(const google_protobuf_MethodDescriptorProto *msg) { return _upb_hasbit(msg, 4); }
@@ -951,55 +951,55 @@ UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_client_streaming(const
UPB_INLINE bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
-
-UPB_INLINE void google_protobuf_MethodDescriptorProto_set_name(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 3);
+
+UPB_INLINE void google_protobuf_MethodDescriptorProto_set_name(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_MethodDescriptorProto_set_input_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void google_protobuf_MethodDescriptorProto_set_input_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_MethodDescriptorProto_set_output_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void google_protobuf_MethodDescriptorProto_set_output_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_MethodDescriptorProto_set_options(google_protobuf_MethodDescriptorProto *msg, google_protobuf_MethodOptions* value) {
- _upb_sethas(msg, 6);
+}
+UPB_INLINE void google_protobuf_MethodDescriptorProto_set_options(google_protobuf_MethodDescriptorProto *msg, google_protobuf_MethodOptions* value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(28, 56), google_protobuf_MethodOptions*) = value;
-}
-UPB_INLINE struct google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_mutable_options(google_protobuf_MethodDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_MethodOptions* sub = (struct google_protobuf_MethodOptions*)google_protobuf_MethodDescriptorProto_options(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_mutable_options(google_protobuf_MethodDescriptorProto *msg, upb_arena *arena) {
+ struct google_protobuf_MethodOptions* sub = (struct google_protobuf_MethodOptions*)google_protobuf_MethodDescriptorProto_options(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_MethodOptions*)_upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_MethodDescriptorProto_set_options(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void google_protobuf_MethodDescriptorProto_set_client_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
- _upb_sethas(msg, 1);
+ if (!sub) return NULL;
+ google_protobuf_MethodDescriptorProto_set_options(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void google_protobuf_MethodDescriptorProto_set_client_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE void google_protobuf_MethodDescriptorProto_set_server_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_MethodDescriptorProto_set_server_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
-}
-
-/* google.protobuf.FileOptions */
-
-UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_new(upb_arena *arena) {
+}
+
+/* google.protobuf.FileOptions */
+
+UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_new(upb_arena *arena) {
return (google_protobuf_FileOptions *)_upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_FileOptions *ret = google_protobuf_FileOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_FileOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_FileOptions_serialize(const google_protobuf_FileOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_FileOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_FileOptions *ret = google_protobuf_FileOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_FileOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_FileOptions_serialize(const google_protobuf_FileOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_FileOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_FileOptions_has_java_package(const google_protobuf_FileOptions *msg) { return _upb_hasbit(msg, 11); }
UPB_INLINE upb_strview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 32), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_outer_classname(const google_protobuf_FileOptions *msg) { return _upb_hasbit(msg, 12); }
@@ -1041,116 +1041,116 @@ UPB_INLINE upb_strview google_protobuf_FileOptions_php_metadata_namespace(const
UPB_INLINE bool google_protobuf_FileOptions_has_ruby_package(const google_protobuf_FileOptions *msg) { return _upb_hasbit(msg, 20); }
UPB_INLINE upb_strview google_protobuf_FileOptions_ruby_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(100, 176), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_uninterpreted_option(const google_protobuf_FileOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(108, 192)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FileOptions_uninterpreted_option(const google_protobuf_FileOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(108, 192), len); }
-
-UPB_INLINE void google_protobuf_FileOptions_set_java_package(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 11);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FileOptions_uninterpreted_option(const google_protobuf_FileOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(108, 192), len); }
+
+UPB_INLINE void google_protobuf_FileOptions_set_java_package(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 11);
*UPB_PTR_AT(msg, UPB_SIZE(28, 32), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_java_outer_classname(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 12);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_java_outer_classname(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 12);
*UPB_PTR_AT(msg, UPB_SIZE(36, 48), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_optimize_for(google_protobuf_FileOptions *msg, int32_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_optimize_for(google_protobuf_FileOptions *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_java_multiple_files(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_java_multiple_files(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_go_package(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 13);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_go_package(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 13);
*UPB_PTR_AT(msg, UPB_SIZE(44, 64), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_cc_generic_services(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_cc_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(17, 17), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_java_generic_services(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_java_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(18, 18), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_py_generic_services(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_py_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(19, 19), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_java_generate_equals_and_hash(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 6);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_java_generate_equals_and_hash(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_deprecated(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 7);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_deprecated(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 7);
*UPB_PTR_AT(msg, UPB_SIZE(21, 21), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_java_string_check_utf8(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 8);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_java_string_check_utf8(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 8);
*UPB_PTR_AT(msg, UPB_SIZE(22, 22), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_cc_enable_arenas(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 9);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_cc_enable_arenas(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 9);
*UPB_PTR_AT(msg, UPB_SIZE(23, 23), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_objc_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 14);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_objc_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 14);
*UPB_PTR_AT(msg, UPB_SIZE(52, 80), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_csharp_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 15);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_csharp_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 15);
*UPB_PTR_AT(msg, UPB_SIZE(60, 96), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_swift_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 16);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_swift_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 16);
*UPB_PTR_AT(msg, UPB_SIZE(68, 112), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_php_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 17);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_php_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 17);
*UPB_PTR_AT(msg, UPB_SIZE(76, 128), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_php_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 18);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_php_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 18);
*UPB_PTR_AT(msg, UPB_SIZE(84, 144), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_php_generic_services(google_protobuf_FileOptions *msg, bool value) {
- _upb_sethas(msg, 10);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_php_generic_services(google_protobuf_FileOptions *msg, bool value) {
+ _upb_sethas(msg, 10);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_php_metadata_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 19);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_php_metadata_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 19);
*UPB_PTR_AT(msg, UPB_SIZE(92, 160), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_FileOptions_set_ruby_package(google_protobuf_FileOptions *msg, upb_strview value) {
- _upb_sethas(msg, 20);
+}
+UPB_INLINE void google_protobuf_FileOptions_set_ruby_package(google_protobuf_FileOptions *msg, upb_strview value) {
+ _upb_sethas(msg, 20);
*UPB_PTR_AT(msg, UPB_SIZE(100, 176), upb_strview) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_mutable_uninterpreted_option(google_protobuf_FileOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(108, 192), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_resize_uninterpreted_option(google_protobuf_FileOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_mutable_uninterpreted_option(google_protobuf_FileOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(108, 192), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_resize_uninterpreted_option(google_protobuf_FileOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(108, 192), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FileOptions_add_uninterpreted_option(google_protobuf_FileOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FileOptions_add_uninterpreted_option(google_protobuf_FileOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(108, 192), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.MessageOptions */
-
-UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(108, 192), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.MessageOptions */
+
+UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_new(upb_arena *arena) {
return (google_protobuf_MessageOptions *)_upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_MessageOptions *ret = google_protobuf_MessageOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_MessageOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_MessageOptions_serialize(const google_protobuf_MessageOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_MessageOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_MessageOptions *ret = google_protobuf_MessageOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_MessageOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_MessageOptions_serialize(const google_protobuf_MessageOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_MessageOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_MessageOptions_has_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return _upb_hasbit(msg, 2); }
@@ -1160,52 +1160,52 @@ UPB_INLINE bool google_protobuf_MessageOptions_deprecated(const google_protobuf_
UPB_INLINE bool google_protobuf_MessageOptions_has_map_entry(const google_protobuf_MessageOptions *msg) { return _upb_hasbit(msg, 4); }
UPB_INLINE bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_uninterpreted_option(const google_protobuf_MessageOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 8)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MessageOptions_uninterpreted_option(const google_protobuf_MessageOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(8, 8), len); }
-
-UPB_INLINE void google_protobuf_MessageOptions_set_message_set_wire_format(google_protobuf_MessageOptions *msg, bool value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MessageOptions_uninterpreted_option(const google_protobuf_MessageOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(8, 8), len); }
+
+UPB_INLINE void google_protobuf_MessageOptions_set_message_set_wire_format(google_protobuf_MessageOptions *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE void google_protobuf_MessageOptions_set_no_standard_descriptor_accessor(google_protobuf_MessageOptions *msg, bool value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_MessageOptions_set_no_standard_descriptor_accessor(google_protobuf_MessageOptions *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
-}
-UPB_INLINE void google_protobuf_MessageOptions_set_deprecated(google_protobuf_MessageOptions *msg, bool value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_MessageOptions_set_deprecated(google_protobuf_MessageOptions *msg, bool value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(3, 3), bool) = value;
-}
-UPB_INLINE void google_protobuf_MessageOptions_set_map_entry(google_protobuf_MessageOptions *msg, bool value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void google_protobuf_MessageOptions_set_map_entry(google_protobuf_MessageOptions *msg, bool value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_mutable_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 8), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_resize_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_mutable_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 8), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_resize_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(8, 8), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MessageOptions_add_uninterpreted_option(google_protobuf_MessageOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MessageOptions_add_uninterpreted_option(google_protobuf_MessageOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(8, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.FieldOptions */
-
-UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(8, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.FieldOptions */
+
+UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_new(upb_arena *arena) {
return (google_protobuf_FieldOptions *)_upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_FieldOptions *ret = google_protobuf_FieldOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_FieldOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_FieldOptions_serialize(const google_protobuf_FieldOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_FieldOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_FieldOptions *ret = google_protobuf_FieldOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_FieldOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_FieldOptions_serialize(const google_protobuf_FieldOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_FieldOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_FieldOptions_has_ctype(const google_protobuf_FieldOptions *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FieldOptions_has_packed(const google_protobuf_FieldOptions *msg) { return _upb_hasbit(msg, 3); }
@@ -1219,253 +1219,253 @@ UPB_INLINE int32_t google_protobuf_FieldOptions_jstype(const google_protobuf_Fie
UPB_INLINE bool google_protobuf_FieldOptions_has_weak(const google_protobuf_FieldOptions *msg) { return _upb_hasbit(msg, 6); }
UPB_INLINE bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(27, 27), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_uninterpreted_option(const google_protobuf_FieldOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 32)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FieldOptions_uninterpreted_option(const google_protobuf_FieldOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void google_protobuf_FieldOptions_set_ctype(google_protobuf_FieldOptions *msg, int32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FieldOptions_uninterpreted_option(const google_protobuf_FieldOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void google_protobuf_FieldOptions_set_ctype(google_protobuf_FieldOptions *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FieldOptions_set_packed(google_protobuf_FieldOptions *msg, bool value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_FieldOptions_set_packed(google_protobuf_FieldOptions *msg, bool value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
-}
-UPB_INLINE void google_protobuf_FieldOptions_set_deprecated(google_protobuf_FieldOptions *msg, bool value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void google_protobuf_FieldOptions_set_deprecated(google_protobuf_FieldOptions *msg, bool value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(25, 25), bool) = value;
-}
-UPB_INLINE void google_protobuf_FieldOptions_set_lazy(google_protobuf_FieldOptions *msg, bool value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void google_protobuf_FieldOptions_set_lazy(google_protobuf_FieldOptions *msg, bool value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(26, 26), bool) = value;
-}
-UPB_INLINE void google_protobuf_FieldOptions_set_jstype(google_protobuf_FieldOptions *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_FieldOptions_set_jstype(google_protobuf_FieldOptions *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_FieldOptions_set_weak(google_protobuf_FieldOptions *msg, bool value) {
- _upb_sethas(msg, 6);
+}
+UPB_INLINE void google_protobuf_FieldOptions_set_weak(google_protobuf_FieldOptions *msg, bool value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(27, 27), bool) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_mutable_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_resize_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_mutable_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_resize_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FieldOptions_add_uninterpreted_option(google_protobuf_FieldOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FieldOptions_add_uninterpreted_option(google_protobuf_FieldOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(28, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.OneofOptions */
-
-UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(28, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.OneofOptions */
+
+UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_new(upb_arena *arena) {
return (google_protobuf_OneofOptions *)_upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_OneofOptions *ret = google_protobuf_OneofOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_OneofOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_OneofOptions_serialize(const google_protobuf_OneofOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_OneofOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_OneofOptions *ret = google_protobuf_OneofOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_OneofOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_OneofOptions_serialize(const google_protobuf_OneofOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_OneofOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_OneofOptions_has_uninterpreted_option(const google_protobuf_OneofOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_OneofOptions_uninterpreted_option(const google_protobuf_OneofOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_mutable_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_resize_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_OneofOptions_uninterpreted_option(const google_protobuf_OneofOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_mutable_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_resize_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_OneofOptions_add_uninterpreted_option(google_protobuf_OneofOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_OneofOptions_add_uninterpreted_option(google_protobuf_OneofOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.EnumOptions */
-
-UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.EnumOptions */
+
+UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_new(upb_arena *arena) {
return (google_protobuf_EnumOptions *)_upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_EnumOptions *ret = google_protobuf_EnumOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_EnumOptions_serialize(const google_protobuf_EnumOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_EnumOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_EnumOptions *ret = google_protobuf_EnumOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_EnumOptions_serialize(const google_protobuf_EnumOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_EnumOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_EnumOptions_has_allow_alias(const google_protobuf_EnumOptions *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_EnumOptions_has_deprecated(const google_protobuf_EnumOptions *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
UPB_INLINE bool google_protobuf_EnumOptions_has_uninterpreted_option(const google_protobuf_EnumOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumOptions_uninterpreted_option(const google_protobuf_EnumOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
-
-UPB_INLINE void google_protobuf_EnumOptions_set_allow_alias(google_protobuf_EnumOptions *msg, bool value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumOptions_uninterpreted_option(const google_protobuf_EnumOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
+
+UPB_INLINE void google_protobuf_EnumOptions_set_allow_alias(google_protobuf_EnumOptions *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE void google_protobuf_EnumOptions_set_deprecated(google_protobuf_EnumOptions *msg, bool value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_EnumOptions_set_deprecated(google_protobuf_EnumOptions *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_mutable_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_resize_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_mutable_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_resize_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumOptions_add_uninterpreted_option(google_protobuf_EnumOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumOptions_add_uninterpreted_option(google_protobuf_EnumOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.EnumValueOptions */
-
-UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.EnumValueOptions */
+
+UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_new(upb_arena *arena) {
return (google_protobuf_EnumValueOptions *)_upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_EnumValueOptions *ret = google_protobuf_EnumValueOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumValueOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_EnumValueOptions_serialize(const google_protobuf_EnumValueOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_EnumValueOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_EnumValueOptions *ret = google_protobuf_EnumValueOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_EnumValueOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_EnumValueOptions_serialize(const google_protobuf_EnumValueOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_EnumValueOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_EnumValueOptions_has_deprecated(const google_protobuf_EnumValueOptions *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_EnumValueOptions_has_uninterpreted_option(const google_protobuf_EnumValueOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumValueOptions_uninterpreted_option(const google_protobuf_EnumValueOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
-
-UPB_INLINE void google_protobuf_EnumValueOptions_set_deprecated(google_protobuf_EnumValueOptions *msg, bool value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumValueOptions_uninterpreted_option(const google_protobuf_EnumValueOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
+
+UPB_INLINE void google_protobuf_EnumValueOptions_set_deprecated(google_protobuf_EnumValueOptions *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_mutable_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_resize_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_mutable_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_resize_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumValueOptions_add_uninterpreted_option(google_protobuf_EnumValueOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumValueOptions_add_uninterpreted_option(google_protobuf_EnumValueOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.ServiceOptions */
-
-UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.ServiceOptions */
+
+UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_new(upb_arena *arena) {
return (google_protobuf_ServiceOptions *)_upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_ServiceOptions *ret = google_protobuf_ServiceOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_ServiceOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_ServiceOptions_serialize(const google_protobuf_ServiceOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_ServiceOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_ServiceOptions *ret = google_protobuf_ServiceOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_ServiceOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_ServiceOptions_serialize(const google_protobuf_ServiceOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_ServiceOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_ServiceOptions_has_deprecated(const google_protobuf_ServiceOptions *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_ServiceOptions_has_uninterpreted_option(const google_protobuf_ServiceOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ServiceOptions_uninterpreted_option(const google_protobuf_ServiceOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
-
-UPB_INLINE void google_protobuf_ServiceOptions_set_deprecated(google_protobuf_ServiceOptions *msg, bool value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ServiceOptions_uninterpreted_option(const google_protobuf_ServiceOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
+
+UPB_INLINE void google_protobuf_ServiceOptions_set_deprecated(google_protobuf_ServiceOptions *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_mutable_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_resize_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_mutable_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_resize_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ServiceOptions_add_uninterpreted_option(google_protobuf_ServiceOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ServiceOptions_add_uninterpreted_option(google_protobuf_ServiceOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.MethodOptions */
-
-UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.MethodOptions */
+
+UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_new(upb_arena *arena) {
return (google_protobuf_MethodOptions *)_upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
-}
-UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_MethodOptions *ret = google_protobuf_MethodOptions_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_MethodOptions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_MethodOptions_serialize(const google_protobuf_MethodOptions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_MethodOptions_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_MethodOptions *ret = google_protobuf_MethodOptions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_MethodOptions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_MethodOptions_serialize(const google_protobuf_MethodOptions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_MethodOptions_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_MethodOptions_has_deprecated(const google_protobuf_MethodOptions *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool); }
UPB_INLINE bool google_protobuf_MethodOptions_has_idempotency_level(const google_protobuf_MethodOptions *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_MethodOptions_has_uninterpreted_option(const google_protobuf_MethodOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 24)); }
-UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MethodOptions_uninterpreted_option(const google_protobuf_MethodOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(20, 24), len); }
-
-UPB_INLINE void google_protobuf_MethodOptions_set_deprecated(google_protobuf_MethodOptions *msg, bool value) {
- _upb_sethas(msg, 2);
+UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MethodOptions_uninterpreted_option(const google_protobuf_MethodOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(20, 24), len); }
+
+UPB_INLINE void google_protobuf_MethodOptions_set_deprecated(google_protobuf_MethodOptions *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool) = value;
-}
-UPB_INLINE void google_protobuf_MethodOptions_set_idempotency_level(google_protobuf_MethodOptions *msg, int32_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_MethodOptions_set_idempotency_level(google_protobuf_MethodOptions *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_mutable_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 24), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_resize_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_mutable_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 24), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_resize_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 24), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MethodOptions_add_uninterpreted_option(google_protobuf_MethodOptions *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MethodOptions_add_uninterpreted_option(google_protobuf_MethodOptions *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(20, 24), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.UninterpretedOption */
-
-UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(20, 24), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.UninterpretedOption */
+
+UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_new(upb_arena *arena) {
return (google_protobuf_UninterpretedOption *)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
-}
-UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_UninterpretedOption *ret = google_protobuf_UninterpretedOption_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_UninterpretedOption_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_UninterpretedOption_serialize(const google_protobuf_UninterpretedOption *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_UninterpretedOption_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_UninterpretedOption *ret = google_protobuf_UninterpretedOption_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_UninterpretedOption_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_UninterpretedOption_serialize(const google_protobuf_UninterpretedOption *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_UninterpretedOption_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_UninterpretedOption_has_name(const google_protobuf_UninterpretedOption *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(56, 80)); }
-UPB_INLINE const google_protobuf_UninterpretedOption_NamePart* const* google_protobuf_UninterpretedOption_name(const google_protobuf_UninterpretedOption *msg, size_t *len) { return (const google_protobuf_UninterpretedOption_NamePart* const*)_upb_array_accessor(msg, UPB_SIZE(56, 80), len); }
+UPB_INLINE const google_protobuf_UninterpretedOption_NamePart* const* google_protobuf_UninterpretedOption_name(const google_protobuf_UninterpretedOption *msg, size_t *len) { return (const google_protobuf_UninterpretedOption_NamePart* const*)_upb_array_accessor(msg, UPB_SIZE(56, 80), len); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_identifier_value(const google_protobuf_UninterpretedOption *msg) { return _upb_hasbit(msg, 4); }
UPB_INLINE upb_strview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return _upb_hasbit(msg, 1); }
@@ -1478,245 +1478,245 @@ UPB_INLINE bool google_protobuf_UninterpretedOption_has_string_value(const googl
UPB_INLINE upb_strview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return _upb_hasbit(msg, 6); }
UPB_INLINE upb_strview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview); }
-
-UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_mutable_name(google_protobuf_UninterpretedOption *msg, size_t *len) {
- return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 80), len);
-}
-UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_resize_name(google_protobuf_UninterpretedOption *msg, size_t len, upb_arena *arena) {
+
+UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_mutable_name(google_protobuf_UninterpretedOption *msg, size_t *len) {
+ return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 80), len);
+}
+UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_resize_name(google_protobuf_UninterpretedOption *msg, size_t len, upb_arena *arena) {
return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_resize_accessor(msg, UPB_SIZE(56, 80), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_UninterpretedOption_NamePart* google_protobuf_UninterpretedOption_add_name(google_protobuf_UninterpretedOption *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_UninterpretedOption_NamePart* google_protobuf_UninterpretedOption_add_name(google_protobuf_UninterpretedOption *msg, upb_arena *arena) {
struct google_protobuf_UninterpretedOption_NamePart* sub = (struct google_protobuf_UninterpretedOption_NamePart*)_upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(56, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_set_identifier_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
- _upb_sethas(msg, 4);
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(56, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_set_identifier_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_set_positive_int_value(google_protobuf_UninterpretedOption *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_set_positive_int_value(google_protobuf_UninterpretedOption *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_set_negative_int_value(google_protobuf_UninterpretedOption *msg, int64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_set_negative_int_value(google_protobuf_UninterpretedOption *msg, int64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_set_double_value(google_protobuf_UninterpretedOption *msg, double value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_set_double_value(google_protobuf_UninterpretedOption *msg, double value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), double) = value;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_set_string_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_set_string_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_set_aggregate_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
- _upb_sethas(msg, 6);
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_set_aggregate_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview) = value;
-}
-
-/* google.protobuf.UninterpretedOption.NamePart */
-
-UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_new(upb_arena *arena) {
+}
+
+/* google.protobuf.UninterpretedOption.NamePart */
+
+UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_new(upb_arena *arena) {
return (google_protobuf_UninterpretedOption_NamePart *)_upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
-}
-UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_UninterpretedOption_NamePart *ret = google_protobuf_UninterpretedOption_NamePart_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_UninterpretedOption_NamePart_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_UninterpretedOption_NamePart_serialize(const google_protobuf_UninterpretedOption_NamePart *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_UninterpretedOption_NamePart_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_UninterpretedOption_NamePart *ret = google_protobuf_UninterpretedOption_NamePart_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_UninterpretedOption_NamePart_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_UninterpretedOption_NamePart_serialize(const google_protobuf_UninterpretedOption_NamePart *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_UninterpretedOption_NamePart_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_has_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE upb_strview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_has_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
-
-UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_name_part(google_protobuf_UninterpretedOption_NamePart *msg, upb_strview value) {
- _upb_sethas(msg, 2);
+
+UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_name_part(google_protobuf_UninterpretedOption_NamePart *msg, upb_strview value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_is_extension(google_protobuf_UninterpretedOption_NamePart *msg, bool value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_is_extension(google_protobuf_UninterpretedOption_NamePart *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-
-/* google.protobuf.SourceCodeInfo */
-
-UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_new(upb_arena *arena) {
+}
+
+/* google.protobuf.SourceCodeInfo */
+
+UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_new(upb_arena *arena) {
return (google_protobuf_SourceCodeInfo *)_upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
-}
-UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_SourceCodeInfo *ret = google_protobuf_SourceCodeInfo_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_SourceCodeInfo_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_SourceCodeInfo_serialize(const google_protobuf_SourceCodeInfo *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_SourceCodeInfo_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_SourceCodeInfo *ret = google_protobuf_SourceCodeInfo_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_SourceCodeInfo_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_SourceCodeInfo_serialize(const google_protobuf_SourceCodeInfo *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_SourceCodeInfo_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_SourceCodeInfo_has_location(const google_protobuf_SourceCodeInfo *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const google_protobuf_SourceCodeInfo_Location* const* google_protobuf_SourceCodeInfo_location(const google_protobuf_SourceCodeInfo *msg, size_t *len) { return (const google_protobuf_SourceCodeInfo_Location* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_mutable_location(google_protobuf_SourceCodeInfo *msg, size_t *len) {
- return (google_protobuf_SourceCodeInfo_Location**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_resize_location(google_protobuf_SourceCodeInfo *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const google_protobuf_SourceCodeInfo_Location* const* google_protobuf_SourceCodeInfo_location(const google_protobuf_SourceCodeInfo *msg, size_t *len) { return (const google_protobuf_SourceCodeInfo_Location* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_mutable_location(google_protobuf_SourceCodeInfo *msg, size_t *len) {
+ return (google_protobuf_SourceCodeInfo_Location**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_resize_location(google_protobuf_SourceCodeInfo *msg, size_t len, upb_arena *arena) {
return (google_protobuf_SourceCodeInfo_Location**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_SourceCodeInfo_Location* google_protobuf_SourceCodeInfo_add_location(google_protobuf_SourceCodeInfo *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_SourceCodeInfo_Location* google_protobuf_SourceCodeInfo_add_location(google_protobuf_SourceCodeInfo *msg, upb_arena *arena) {
struct google_protobuf_SourceCodeInfo_Location* sub = (struct google_protobuf_SourceCodeInfo_Location*)_upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.SourceCodeInfo.Location */
-
-UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.SourceCodeInfo.Location */
+
+UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_new(upb_arena *arena) {
return (google_protobuf_SourceCodeInfo_Location *)_upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
-}
-UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_SourceCodeInfo_Location *ret = google_protobuf_SourceCodeInfo_Location_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_SourceCodeInfo_Location_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_SourceCodeInfo_Location_serialize(const google_protobuf_SourceCodeInfo_Location *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_SourceCodeInfo_Location_msginit, arena, len);
-}
-
-UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_path(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
-UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_span(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+}
+UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_SourceCodeInfo_Location *ret = google_protobuf_SourceCodeInfo_Location_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_SourceCodeInfo_Location_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_SourceCodeInfo_Location_serialize(const google_protobuf_SourceCodeInfo_Location *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_SourceCodeInfo_Location_msginit, arena, len);
+}
+
+UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_path(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
+UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_span(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_has_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_has_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
-UPB_INLINE upb_strview const* google_protobuf_SourceCodeInfo_Location_leading_detached_comments(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
-
-UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_path(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
-}
-UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_path(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
+UPB_INLINE upb_strview const* google_protobuf_SourceCodeInfo_Location_leading_detached_comments(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
+
+UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_path(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
+}
+UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_path(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_path(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_path(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(20, 40), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_span(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
-}
-UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_span(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_span(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
+}
+UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_span(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_span(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_span(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_leading_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_leading_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_trailing_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_trailing_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
-}
-UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_mutable_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
-}
-UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_resize_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_mutable_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
+}
+UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_resize_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 56), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-
-/* google.protobuf.GeneratedCodeInfo */
-
-UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_new(upb_arena *arena) {
+}
+
+/* google.protobuf.GeneratedCodeInfo */
+
+UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_new(upb_arena *arena) {
return (google_protobuf_GeneratedCodeInfo *)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_msginit, arena);
-}
-UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_GeneratedCodeInfo *ret = google_protobuf_GeneratedCodeInfo_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_GeneratedCodeInfo_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_GeneratedCodeInfo_serialize(const google_protobuf_GeneratedCodeInfo *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_GeneratedCodeInfo *ret = google_protobuf_GeneratedCodeInfo_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_GeneratedCodeInfo_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_GeneratedCodeInfo_serialize(const google_protobuf_GeneratedCodeInfo *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_has_annotation(const google_protobuf_GeneratedCodeInfo *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const google_protobuf_GeneratedCodeInfo_Annotation* const* google_protobuf_GeneratedCodeInfo_annotation(const google_protobuf_GeneratedCodeInfo *msg, size_t *len) { return (const google_protobuf_GeneratedCodeInfo_Annotation* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_mutable_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t *len) {
- return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_resize_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const google_protobuf_GeneratedCodeInfo_Annotation* const* google_protobuf_GeneratedCodeInfo_annotation(const google_protobuf_GeneratedCodeInfo *msg, size_t *len) { return (const google_protobuf_GeneratedCodeInfo_Annotation* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_mutable_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t *len) {
+ return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_resize_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t len, upb_arena *arena) {
return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_GeneratedCodeInfo_Annotation* google_protobuf_GeneratedCodeInfo_add_annotation(google_protobuf_GeneratedCodeInfo *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_GeneratedCodeInfo_Annotation* google_protobuf_GeneratedCodeInfo_add_annotation(google_protobuf_GeneratedCodeInfo *msg, upb_arena *arena) {
struct google_protobuf_GeneratedCodeInfo_Annotation* sub = (struct google_protobuf_GeneratedCodeInfo_Annotation*)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* google.protobuf.GeneratedCodeInfo.Annotation */
-
-UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* google.protobuf.GeneratedCodeInfo.Annotation */
+
+UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_new(upb_arena *arena) {
return (google_protobuf_GeneratedCodeInfo_Annotation *)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
-}
-UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_GeneratedCodeInfo_Annotation *ret = google_protobuf_GeneratedCodeInfo_Annotation_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_GeneratedCodeInfo_Annotation_serialize(const google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena, len);
-}
-
-UPB_INLINE int32_t const* google_protobuf_GeneratedCodeInfo_Annotation_path(const google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 32), len); }
+}
+UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_GeneratedCodeInfo_Annotation *ret = google_protobuf_GeneratedCodeInfo_Annotation_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_GeneratedCodeInfo_Annotation_serialize(const google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena, len);
+}
+
+UPB_INLINE int32_t const* google_protobuf_GeneratedCodeInfo_Annotation_path(const google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 32), len); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_hasbit(msg, 3); }
UPB_INLINE upb_strview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
-
-UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_mutable_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 32), len);
-}
-UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_resize_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t len, upb_arena *arena) {
+
+UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_mutable_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 32), len);
+}
+UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_resize_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 32), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_add_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_add_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(20, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_source_file(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_strview value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_source_file(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_strview value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview) = value;
-}
-UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_begin(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_begin(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_end(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_end(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.c
index 7384c06cf2..768b19721f 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.c
@@ -1,27 +1,27 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/duration.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/duration.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout_field google_protobuf_Duration__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 3, 1},
- {2, UPB_SIZE(8, 8), 0, 0, 5, 1},
-};
-
-const upb_msglayout google_protobuf_Duration_msginit = {
- NULL,
- &google_protobuf_Duration__fields[0],
- UPB_SIZE(16, 16), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/duration.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/duration.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout_field google_protobuf_Duration__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 3, 1},
+ {2, UPB_SIZE(8, 8), 0, 0, 5, 1},
+};
+
+const upb_msglayout google_protobuf_Duration_msginit = {
+ NULL,
+ &google_protobuf_Duration__fields[0],
+ UPB_SIZE(16, 16), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.h
index f3fa03591c..d04dccaf0d 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.h
@@ -1,57 +1,57 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/duration.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_DURATION_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_DURATION_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_Duration;
-typedef struct google_protobuf_Duration google_protobuf_Duration;
-extern const upb_msglayout google_protobuf_Duration_msginit;
-
-
-/* google.protobuf.Duration */
-
-UPB_INLINE google_protobuf_Duration *google_protobuf_Duration_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/duration.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_DURATION_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_DURATION_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_Duration;
+typedef struct google_protobuf_Duration google_protobuf_Duration;
+extern const upb_msglayout google_protobuf_Duration_msginit;
+
+
+/* google.protobuf.Duration */
+
+UPB_INLINE google_protobuf_Duration *google_protobuf_Duration_new(upb_arena *arena) {
return (google_protobuf_Duration *)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
-}
-UPB_INLINE google_protobuf_Duration *google_protobuf_Duration_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Duration *ret = google_protobuf_Duration_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Duration_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Duration_serialize(const google_protobuf_Duration *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Duration_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_Duration *google_protobuf_Duration_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Duration *ret = google_protobuf_Duration_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Duration_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Duration_serialize(const google_protobuf_Duration *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Duration_msginit, arena, len);
+}
+
UPB_INLINE int64_t google_protobuf_Duration_seconds(const google_protobuf_Duration *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t); }
UPB_INLINE int32_t google_protobuf_Duration_nanos(const google_protobuf_Duration *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
-
-UPB_INLINE void google_protobuf_Duration_set_seconds(google_protobuf_Duration *msg, int64_t value) {
+
+UPB_INLINE void google_protobuf_Duration_set_seconds(google_protobuf_Duration *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t) = value;
-}
-UPB_INLINE void google_protobuf_Duration_set_nanos(google_protobuf_Duration *msg, int32_t value) {
+}
+UPB_INLINE void google_protobuf_Duration_set_nanos(google_protobuf_Duration *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_DURATION_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_DURATION_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.c
index 51ac7ed26c..0b872f2eac 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.c
@@ -1,22 +1,22 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/empty.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/empty.upb.h"
-
-#include "upb/port_def.inc"
-
-const upb_msglayout google_protobuf_Empty_msginit = {
- NULL,
- NULL,
- UPB_SIZE(0, 0), 0, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/empty.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/empty.upb.h"
+
+#include "upb/port_def.inc"
+
+const upb_msglayout google_protobuf_Empty_msginit = {
+ NULL,
+ NULL,
+ UPB_SIZE(0, 0), 0, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.h
index a7471dcd08..bf61dc9dd5 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.h
@@ -1,49 +1,49 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/empty.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_EMPTY_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_EMPTY_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_Empty;
-typedef struct google_protobuf_Empty google_protobuf_Empty;
-extern const upb_msglayout google_protobuf_Empty_msginit;
-
-
-/* google.protobuf.Empty */
-
-UPB_INLINE google_protobuf_Empty *google_protobuf_Empty_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/empty.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_EMPTY_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_EMPTY_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_Empty;
+typedef struct google_protobuf_Empty google_protobuf_Empty;
+extern const upb_msglayout google_protobuf_Empty_msginit;
+
+
+/* google.protobuf.Empty */
+
+UPB_INLINE google_protobuf_Empty *google_protobuf_Empty_new(upb_arena *arena) {
return (google_protobuf_Empty *)_upb_msg_new(&google_protobuf_Empty_msginit, arena);
-}
-UPB_INLINE google_protobuf_Empty *google_protobuf_Empty_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Empty *ret = google_protobuf_Empty_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Empty_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Empty_serialize(const google_protobuf_Empty *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Empty_msginit, arena, len);
-}
-
-
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_EMPTY_PROTO_UPB_H_ */
+}
+UPB_INLINE google_protobuf_Empty *google_protobuf_Empty_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Empty *ret = google_protobuf_Empty_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Empty_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Empty_serialize(const google_protobuf_Empty *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Empty_msginit, arena, len);
+}
+
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_EMPTY_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.c
index a0d20a4fae..bfe4ed8c80 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.c
@@ -1,79 +1,79 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/struct.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/struct.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const google_protobuf_Struct_submsgs[1] = {
- &google_protobuf_Struct_FieldsEntry_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_Struct__fields[1] = {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/struct.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/struct.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const google_protobuf_Struct_submsgs[1] = {
+ &google_protobuf_Struct_FieldsEntry_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_Struct__fields[1] = {
{1, UPB_SIZE(0, 0), 0, 0, 11, _UPB_LABEL_MAP},
-};
-
-const upb_msglayout google_protobuf_Struct_msginit = {
- &google_protobuf_Struct_submsgs[0],
- &google_protobuf_Struct__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout *const google_protobuf_Struct_FieldsEntry_submsgs[1] = {
- &google_protobuf_Value_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_Struct_FieldsEntry__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 16), 0, 0, 11, 1},
-};
-
-const upb_msglayout google_protobuf_Struct_FieldsEntry_msginit = {
- &google_protobuf_Struct_FieldsEntry_submsgs[0],
- &google_protobuf_Struct_FieldsEntry__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const google_protobuf_Value_submsgs[2] = {
- &google_protobuf_ListValue_msginit,
- &google_protobuf_Struct_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_Value__fields[6] = {
- {1, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 14, 1},
- {2, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 1, 1},
- {3, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 9, 1},
- {4, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 8, 1},
- {5, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 1, 11, 1},
- {6, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 11, 1},
-};
-
-const upb_msglayout google_protobuf_Value_msginit = {
- &google_protobuf_Value_submsgs[0],
- &google_protobuf_Value__fields[0],
- UPB_SIZE(16, 32), 6, false,
-};
-
-static const upb_msglayout *const google_protobuf_ListValue_submsgs[1] = {
- &google_protobuf_Value_msginit,
-};
-
-static const upb_msglayout_field google_protobuf_ListValue__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_protobuf_ListValue_msginit = {
- &google_protobuf_ListValue_submsgs[0],
- &google_protobuf_ListValue__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-#include "upb/port_undef.inc"
-
+};
+
+const upb_msglayout google_protobuf_Struct_msginit = {
+ &google_protobuf_Struct_submsgs[0],
+ &google_protobuf_Struct__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout *const google_protobuf_Struct_FieldsEntry_submsgs[1] = {
+ &google_protobuf_Value_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_Struct_FieldsEntry__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 16), 0, 0, 11, 1},
+};
+
+const upb_msglayout google_protobuf_Struct_FieldsEntry_msginit = {
+ &google_protobuf_Struct_FieldsEntry_submsgs[0],
+ &google_protobuf_Struct_FieldsEntry__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const google_protobuf_Value_submsgs[2] = {
+ &google_protobuf_ListValue_msginit,
+ &google_protobuf_Struct_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_Value__fields[6] = {
+ {1, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 14, 1},
+ {2, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 1, 1},
+ {3, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 9, 1},
+ {4, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 8, 1},
+ {5, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 1, 11, 1},
+ {6, UPB_SIZE(0, 0), UPB_SIZE(-9, -17), 0, 11, 1},
+};
+
+const upb_msglayout google_protobuf_Value_msginit = {
+ &google_protobuf_Value_submsgs[0],
+ &google_protobuf_Value__fields[0],
+ UPB_SIZE(16, 32), 6, false,
+};
+
+static const upb_msglayout *const google_protobuf_ListValue_submsgs[1] = {
+ &google_protobuf_Value_msginit,
+};
+
+static const upb_msglayout_field google_protobuf_ListValue__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_protobuf_ListValue_msginit = {
+ &google_protobuf_ListValue_submsgs[0],
+ &google_protobuf_ListValue__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.h
index b25201d323..084fda4dad 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.h
@@ -1,194 +1,194 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/struct.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_STRUCT_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_STRUCT_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_Struct;
-struct google_protobuf_Struct_FieldsEntry;
-struct google_protobuf_Value;
-struct google_protobuf_ListValue;
-typedef struct google_protobuf_Struct google_protobuf_Struct;
-typedef struct google_protobuf_Struct_FieldsEntry google_protobuf_Struct_FieldsEntry;
-typedef struct google_protobuf_Value google_protobuf_Value;
-typedef struct google_protobuf_ListValue google_protobuf_ListValue;
-extern const upb_msglayout google_protobuf_Struct_msginit;
-extern const upb_msglayout google_protobuf_Struct_FieldsEntry_msginit;
-extern const upb_msglayout google_protobuf_Value_msginit;
-extern const upb_msglayout google_protobuf_ListValue_msginit;
-
-typedef enum {
- google_protobuf_NULL_VALUE = 0
-} google_protobuf_NullValue;
-
-
-/* google.protobuf.Struct */
-
-UPB_INLINE google_protobuf_Struct *google_protobuf_Struct_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/struct.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_STRUCT_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_STRUCT_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_Struct;
+struct google_protobuf_Struct_FieldsEntry;
+struct google_protobuf_Value;
+struct google_protobuf_ListValue;
+typedef struct google_protobuf_Struct google_protobuf_Struct;
+typedef struct google_protobuf_Struct_FieldsEntry google_protobuf_Struct_FieldsEntry;
+typedef struct google_protobuf_Value google_protobuf_Value;
+typedef struct google_protobuf_ListValue google_protobuf_ListValue;
+extern const upb_msglayout google_protobuf_Struct_msginit;
+extern const upb_msglayout google_protobuf_Struct_FieldsEntry_msginit;
+extern const upb_msglayout google_protobuf_Value_msginit;
+extern const upb_msglayout google_protobuf_ListValue_msginit;
+
+typedef enum {
+ google_protobuf_NULL_VALUE = 0
+} google_protobuf_NullValue;
+
+
+/* google.protobuf.Struct */
+
+UPB_INLINE google_protobuf_Struct *google_protobuf_Struct_new(upb_arena *arena) {
return (google_protobuf_Struct *)_upb_msg_new(&google_protobuf_Struct_msginit, arena);
-}
-UPB_INLINE google_protobuf_Struct *google_protobuf_Struct_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Struct *ret = google_protobuf_Struct_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Struct_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Struct_serialize(const google_protobuf_Struct *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Struct_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_Struct *google_protobuf_Struct_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Struct *ret = google_protobuf_Struct_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Struct_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Struct_serialize(const google_protobuf_Struct *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Struct_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_Struct_has_fields(const google_protobuf_Struct *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE size_t google_protobuf_Struct_fields_size(const google_protobuf_Struct *msg) {return _upb_msg_map_size(msg, UPB_SIZE(0, 0)); }
UPB_INLINE bool google_protobuf_Struct_fields_get(const google_protobuf_Struct *msg, upb_strview key, google_protobuf_Value* *val) { return _upb_msg_map_get(msg, UPB_SIZE(0, 0), &key, 0, val, sizeof(*val)); }
UPB_INLINE const google_protobuf_Struct_FieldsEntry* google_protobuf_Struct_fields_next(const google_protobuf_Struct *msg, size_t* iter) { return (const google_protobuf_Struct_FieldsEntry*)_upb_msg_map_next(msg, UPB_SIZE(0, 0), iter); }
-
+
UPB_INLINE void google_protobuf_Struct_fields_clear(google_protobuf_Struct *msg) { _upb_msg_map_clear(msg, UPB_SIZE(0, 0)); }
UPB_INLINE bool google_protobuf_Struct_fields_set(google_protobuf_Struct *msg, upb_strview key, google_protobuf_Value* val, upb_arena *a) { return _upb_msg_map_set(msg, UPB_SIZE(0, 0), &key, 0, &val, sizeof(val), a); }
UPB_INLINE bool google_protobuf_Struct_fields_delete(google_protobuf_Struct *msg, upb_strview key) { return _upb_msg_map_delete(msg, UPB_SIZE(0, 0), &key, 0); }
UPB_INLINE google_protobuf_Struct_FieldsEntry* google_protobuf_Struct_fields_nextmutable(google_protobuf_Struct *msg, size_t* iter) { return (google_protobuf_Struct_FieldsEntry*)_upb_msg_map_next(msg, UPB_SIZE(0, 0), iter); }
-
-/* google.protobuf.Struct.FieldsEntry */
-
+
+/* google.protobuf.Struct.FieldsEntry */
+
UPB_INLINE upb_strview google_protobuf_Struct_FieldsEntry_key(const google_protobuf_Struct_FieldsEntry *msg) {
upb_strview ret;
_upb_msg_map_key(msg, &ret, 0);
return ret;
-}
+}
UPB_INLINE bool google_protobuf_Struct_FieldsEntry_has_value(const google_protobuf_Struct_FieldsEntry *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 16)); }
UPB_INLINE const google_protobuf_Value* google_protobuf_Struct_FieldsEntry_value(const google_protobuf_Struct_FieldsEntry *msg) {
google_protobuf_Value* ret;
_upb_msg_map_value(msg, &ret, sizeof(ret));
return ret;
-}
-
-UPB_INLINE void google_protobuf_Struct_FieldsEntry_set_value(google_protobuf_Struct_FieldsEntry *msg, google_protobuf_Value* value) {
+}
+
+UPB_INLINE void google_protobuf_Struct_FieldsEntry_set_value(google_protobuf_Struct_FieldsEntry *msg, google_protobuf_Value* value) {
_upb_msg_map_set_value(msg, &value, sizeof(google_protobuf_Value*));
-}
-
-/* google.protobuf.Value */
-
-UPB_INLINE google_protobuf_Value *google_protobuf_Value_new(upb_arena *arena) {
+}
+
+/* google.protobuf.Value */
+
+UPB_INLINE google_protobuf_Value *google_protobuf_Value_new(upb_arena *arena) {
return (google_protobuf_Value *)_upb_msg_new(&google_protobuf_Value_msginit, arena);
-}
-UPB_INLINE google_protobuf_Value *google_protobuf_Value_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Value *ret = google_protobuf_Value_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Value_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Value_serialize(const google_protobuf_Value *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Value_msginit, arena, len);
-}
-
-typedef enum {
- google_protobuf_Value_kind_null_value = 1,
- google_protobuf_Value_kind_number_value = 2,
- google_protobuf_Value_kind_string_value = 3,
- google_protobuf_Value_kind_bool_value = 4,
- google_protobuf_Value_kind_struct_value = 5,
- google_protobuf_Value_kind_list_value = 6,
- google_protobuf_Value_kind_NOT_SET = 0
-} google_protobuf_Value_kind_oneofcases;
+}
+UPB_INLINE google_protobuf_Value *google_protobuf_Value_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Value *ret = google_protobuf_Value_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Value_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Value_serialize(const google_protobuf_Value *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Value_msginit, arena, len);
+}
+
+typedef enum {
+ google_protobuf_Value_kind_null_value = 1,
+ google_protobuf_Value_kind_number_value = 2,
+ google_protobuf_Value_kind_string_value = 3,
+ google_protobuf_Value_kind_bool_value = 4,
+ google_protobuf_Value_kind_struct_value = 5,
+ google_protobuf_Value_kind_list_value = 6,
+ google_protobuf_Value_kind_NOT_SET = 0
+} google_protobuf_Value_kind_oneofcases;
UPB_INLINE google_protobuf_Value_kind_oneofcases google_protobuf_Value_kind_case(const google_protobuf_Value* msg) { return (google_protobuf_Value_kind_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(8, 16), int32_t); }
-
+
UPB_INLINE bool google_protobuf_Value_has_null_value(const google_protobuf_Value *msg) { return _upb_getoneofcase(msg, UPB_SIZE(8, 16)) == 1; }
UPB_INLINE int32_t google_protobuf_Value_null_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, int32_t, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 1, 0); }
UPB_INLINE bool google_protobuf_Value_has_number_value(const google_protobuf_Value *msg) { return _upb_getoneofcase(msg, UPB_SIZE(8, 16)) == 2; }
-UPB_INLINE double google_protobuf_Value_number_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, double, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 2, 0); }
+UPB_INLINE double google_protobuf_Value_number_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, double, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 2, 0); }
UPB_INLINE bool google_protobuf_Value_has_string_value(const google_protobuf_Value *msg) { return _upb_getoneofcase(msg, UPB_SIZE(8, 16)) == 3; }
-UPB_INLINE upb_strview google_protobuf_Value_string_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 3, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview google_protobuf_Value_string_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 3, upb_strview_make("", strlen(""))); }
UPB_INLINE bool google_protobuf_Value_has_bool_value(const google_protobuf_Value *msg) { return _upb_getoneofcase(msg, UPB_SIZE(8, 16)) == 4; }
-UPB_INLINE bool google_protobuf_Value_bool_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 4, false); }
+UPB_INLINE bool google_protobuf_Value_bool_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 4, false); }
UPB_INLINE bool google_protobuf_Value_has_struct_value(const google_protobuf_Value *msg) { return _upb_getoneofcase(msg, UPB_SIZE(8, 16)) == 5; }
-UPB_INLINE const google_protobuf_Struct* google_protobuf_Value_struct_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, const google_protobuf_Struct*, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 5, NULL); }
+UPB_INLINE const google_protobuf_Struct* google_protobuf_Value_struct_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, const google_protobuf_Struct*, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 5, NULL); }
UPB_INLINE bool google_protobuf_Value_has_list_value(const google_protobuf_Value *msg) { return _upb_getoneofcase(msg, UPB_SIZE(8, 16)) == 6; }
-UPB_INLINE const google_protobuf_ListValue* google_protobuf_Value_list_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, const google_protobuf_ListValue*, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 6, NULL); }
-
-UPB_INLINE void google_protobuf_Value_set_null_value(google_protobuf_Value *msg, int32_t value) {
- UPB_WRITE_ONEOF(msg, int32_t, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 1);
-}
-UPB_INLINE void google_protobuf_Value_set_number_value(google_protobuf_Value *msg, double value) {
- UPB_WRITE_ONEOF(msg, double, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 2);
-}
-UPB_INLINE void google_protobuf_Value_set_string_value(google_protobuf_Value *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 3);
-}
-UPB_INLINE void google_protobuf_Value_set_bool_value(google_protobuf_Value *msg, bool value) {
- UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 4);
-}
-UPB_INLINE void google_protobuf_Value_set_struct_value(google_protobuf_Value *msg, google_protobuf_Struct* value) {
- UPB_WRITE_ONEOF(msg, google_protobuf_Struct*, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 5);
-}
-UPB_INLINE struct google_protobuf_Struct* google_protobuf_Value_mutable_struct_value(google_protobuf_Value *msg, upb_arena *arena) {
- struct google_protobuf_Struct* sub = (struct google_protobuf_Struct*)google_protobuf_Value_struct_value(msg);
- if (sub == NULL) {
+UPB_INLINE const google_protobuf_ListValue* google_protobuf_Value_list_value(const google_protobuf_Value *msg) { return UPB_READ_ONEOF(msg, const google_protobuf_ListValue*, UPB_SIZE(0, 0), UPB_SIZE(8, 16), 6, NULL); }
+
+UPB_INLINE void google_protobuf_Value_set_null_value(google_protobuf_Value *msg, int32_t value) {
+ UPB_WRITE_ONEOF(msg, int32_t, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 1);
+}
+UPB_INLINE void google_protobuf_Value_set_number_value(google_protobuf_Value *msg, double value) {
+ UPB_WRITE_ONEOF(msg, double, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 2);
+}
+UPB_INLINE void google_protobuf_Value_set_string_value(google_protobuf_Value *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 3);
+}
+UPB_INLINE void google_protobuf_Value_set_bool_value(google_protobuf_Value *msg, bool value) {
+ UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 4);
+}
+UPB_INLINE void google_protobuf_Value_set_struct_value(google_protobuf_Value *msg, google_protobuf_Struct* value) {
+ UPB_WRITE_ONEOF(msg, google_protobuf_Struct*, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 5);
+}
+UPB_INLINE struct google_protobuf_Struct* google_protobuf_Value_mutable_struct_value(google_protobuf_Value *msg, upb_arena *arena) {
+ struct google_protobuf_Struct* sub = (struct google_protobuf_Struct*)google_protobuf_Value_struct_value(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Struct*)_upb_msg_new(&google_protobuf_Struct_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_Value_set_struct_value(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void google_protobuf_Value_set_list_value(google_protobuf_Value *msg, google_protobuf_ListValue* value) {
- UPB_WRITE_ONEOF(msg, google_protobuf_ListValue*, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 6);
-}
-UPB_INLINE struct google_protobuf_ListValue* google_protobuf_Value_mutable_list_value(google_protobuf_Value *msg, upb_arena *arena) {
- struct google_protobuf_ListValue* sub = (struct google_protobuf_ListValue*)google_protobuf_Value_list_value(msg);
- if (sub == NULL) {
+ if (!sub) return NULL;
+ google_protobuf_Value_set_struct_value(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void google_protobuf_Value_set_list_value(google_protobuf_Value *msg, google_protobuf_ListValue* value) {
+ UPB_WRITE_ONEOF(msg, google_protobuf_ListValue*, UPB_SIZE(0, 0), value, UPB_SIZE(8, 16), 6);
+}
+UPB_INLINE struct google_protobuf_ListValue* google_protobuf_Value_mutable_list_value(google_protobuf_Value *msg, upb_arena *arena) {
+ struct google_protobuf_ListValue* sub = (struct google_protobuf_ListValue*)google_protobuf_Value_list_value(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_ListValue*)_upb_msg_new(&google_protobuf_ListValue_msginit, arena);
- if (!sub) return NULL;
- google_protobuf_Value_set_list_value(msg, sub);
- }
- return sub;
-}
-
-/* google.protobuf.ListValue */
-
-UPB_INLINE google_protobuf_ListValue *google_protobuf_ListValue_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ google_protobuf_Value_set_list_value(msg, sub);
+ }
+ return sub;
+}
+
+/* google.protobuf.ListValue */
+
+UPB_INLINE google_protobuf_ListValue *google_protobuf_ListValue_new(upb_arena *arena) {
return (google_protobuf_ListValue *)_upb_msg_new(&google_protobuf_ListValue_msginit, arena);
-}
-UPB_INLINE google_protobuf_ListValue *google_protobuf_ListValue_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_ListValue *ret = google_protobuf_ListValue_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_ListValue_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_ListValue_serialize(const google_protobuf_ListValue *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_ListValue_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_ListValue *google_protobuf_ListValue_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_ListValue *ret = google_protobuf_ListValue_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_ListValue_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_ListValue_serialize(const google_protobuf_ListValue *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_ListValue_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_ListValue_has_values(const google_protobuf_ListValue *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const google_protobuf_Value* const* google_protobuf_ListValue_values(const google_protobuf_ListValue *msg, size_t *len) { return (const google_protobuf_Value* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE google_protobuf_Value** google_protobuf_ListValue_mutable_values(google_protobuf_ListValue *msg, size_t *len) {
- return (google_protobuf_Value**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE google_protobuf_Value** google_protobuf_ListValue_resize_values(google_protobuf_ListValue *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const google_protobuf_Value* const* google_protobuf_ListValue_values(const google_protobuf_ListValue *msg, size_t *len) { return (const google_protobuf_Value* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE google_protobuf_Value** google_protobuf_ListValue_mutable_values(google_protobuf_ListValue *msg, size_t *len) {
+ return (google_protobuf_Value**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE google_protobuf_Value** google_protobuf_ListValue_resize_values(google_protobuf_ListValue *msg, size_t len, upb_arena *arena) {
return (google_protobuf_Value**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_Value* google_protobuf_ListValue_add_values(google_protobuf_ListValue *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_Value* google_protobuf_ListValue_add_values(google_protobuf_ListValue *msg, upb_arena *arena) {
struct google_protobuf_Value* sub = (struct google_protobuf_Value*)_upb_msg_new(&google_protobuf_Value_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_STRUCT_PROTO_UPB_H_ */
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_STRUCT_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.c
index edc7af5f36..e5043c5495 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.c
@@ -1,27 +1,27 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/timestamp.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/timestamp.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout_field google_protobuf_Timestamp__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 3, 1},
- {2, UPB_SIZE(8, 8), 0, 0, 5, 1},
-};
-
-const upb_msglayout google_protobuf_Timestamp_msginit = {
- NULL,
- &google_protobuf_Timestamp__fields[0],
- UPB_SIZE(16, 16), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/timestamp.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/timestamp.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout_field google_protobuf_Timestamp__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 3, 1},
+ {2, UPB_SIZE(8, 8), 0, 0, 5, 1},
+};
+
+const upb_msglayout google_protobuf_Timestamp_msginit = {
+ NULL,
+ &google_protobuf_Timestamp__fields[0],
+ UPB_SIZE(16, 16), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h
index f5166de4d5..9b690ce4be 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h
@@ -1,57 +1,57 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/timestamp.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_TIMESTAMP_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_TIMESTAMP_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_Timestamp;
-typedef struct google_protobuf_Timestamp google_protobuf_Timestamp;
-extern const upb_msglayout google_protobuf_Timestamp_msginit;
-
-
-/* google.protobuf.Timestamp */
-
-UPB_INLINE google_protobuf_Timestamp *google_protobuf_Timestamp_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/timestamp.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_TIMESTAMP_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_TIMESTAMP_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_Timestamp;
+typedef struct google_protobuf_Timestamp google_protobuf_Timestamp;
+extern const upb_msglayout google_protobuf_Timestamp_msginit;
+
+
+/* google.protobuf.Timestamp */
+
+UPB_INLINE google_protobuf_Timestamp *google_protobuf_Timestamp_new(upb_arena *arena) {
return (google_protobuf_Timestamp *)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
-}
-UPB_INLINE google_protobuf_Timestamp *google_protobuf_Timestamp_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Timestamp *ret = google_protobuf_Timestamp_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Timestamp_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Timestamp_serialize(const google_protobuf_Timestamp *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Timestamp_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_Timestamp *google_protobuf_Timestamp_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Timestamp *ret = google_protobuf_Timestamp_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Timestamp_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Timestamp_serialize(const google_protobuf_Timestamp *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Timestamp_msginit, arena, len);
+}
+
UPB_INLINE int64_t google_protobuf_Timestamp_seconds(const google_protobuf_Timestamp *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t); }
UPB_INLINE int32_t google_protobuf_Timestamp_nanos(const google_protobuf_Timestamp *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
-
-UPB_INLINE void google_protobuf_Timestamp_set_seconds(google_protobuf_Timestamp *msg, int64_t value) {
+
+UPB_INLINE void google_protobuf_Timestamp_set_seconds(google_protobuf_Timestamp *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t) = value;
-}
-UPB_INLINE void google_protobuf_Timestamp_set_nanos(google_protobuf_Timestamp *msg, int32_t value) {
+}
+UPB_INLINE void google_protobuf_Timestamp_set_nanos(google_protobuf_Timestamp *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_TIMESTAMP_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_TIMESTAMP_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.c
index 1b93ef437a..060225679d 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.c
@@ -1,106 +1,106 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/wrappers.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/protobuf/wrappers.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout_field google_protobuf_DoubleValue__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 1, 1},
-};
-
-const upb_msglayout google_protobuf_DoubleValue_msginit = {
- NULL,
- &google_protobuf_DoubleValue__fields[0],
- UPB_SIZE(8, 8), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_FloatValue__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 2, 1},
-};
-
-const upb_msglayout google_protobuf_FloatValue_msginit = {
- NULL,
- &google_protobuf_FloatValue__fields[0],
- UPB_SIZE(4, 4), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_Int64Value__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 3, 1},
-};
-
-const upb_msglayout google_protobuf_Int64Value_msginit = {
- NULL,
- &google_protobuf_Int64Value__fields[0],
- UPB_SIZE(8, 8), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_UInt64Value__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 4, 1},
-};
-
-const upb_msglayout google_protobuf_UInt64Value_msginit = {
- NULL,
- &google_protobuf_UInt64Value__fields[0],
- UPB_SIZE(8, 8), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_Int32Value__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 5, 1},
-};
-
-const upb_msglayout google_protobuf_Int32Value_msginit = {
- NULL,
- &google_protobuf_Int32Value__fields[0],
- UPB_SIZE(4, 4), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_UInt32Value__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 13, 1},
-};
-
-const upb_msglayout google_protobuf_UInt32Value_msginit = {
- NULL,
- &google_protobuf_UInt32Value__fields[0],
- UPB_SIZE(4, 4), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_BoolValue__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 8, 1},
-};
-
-const upb_msglayout google_protobuf_BoolValue_msginit = {
- NULL,
- &google_protobuf_BoolValue__fields[0],
- UPB_SIZE(1, 1), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_StringValue__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
-};
-
-const upb_msglayout google_protobuf_StringValue_msginit = {
- NULL,
- &google_protobuf_StringValue__fields[0],
- UPB_SIZE(8, 16), 1, false,
-};
-
-static const upb_msglayout_field google_protobuf_BytesValue__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 12, 1},
-};
-
-const upb_msglayout google_protobuf_BytesValue_msginit = {
- NULL,
- &google_protobuf_BytesValue__fields[0],
- UPB_SIZE(8, 16), 1, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/wrappers.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/protobuf/wrappers.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout_field google_protobuf_DoubleValue__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 1, 1},
+};
+
+const upb_msglayout google_protobuf_DoubleValue_msginit = {
+ NULL,
+ &google_protobuf_DoubleValue__fields[0],
+ UPB_SIZE(8, 8), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_FloatValue__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 2, 1},
+};
+
+const upb_msglayout google_protobuf_FloatValue_msginit = {
+ NULL,
+ &google_protobuf_FloatValue__fields[0],
+ UPB_SIZE(4, 4), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_Int64Value__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 3, 1},
+};
+
+const upb_msglayout google_protobuf_Int64Value_msginit = {
+ NULL,
+ &google_protobuf_Int64Value__fields[0],
+ UPB_SIZE(8, 8), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_UInt64Value__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 4, 1},
+};
+
+const upb_msglayout google_protobuf_UInt64Value_msginit = {
+ NULL,
+ &google_protobuf_UInt64Value__fields[0],
+ UPB_SIZE(8, 8), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_Int32Value__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 5, 1},
+};
+
+const upb_msglayout google_protobuf_Int32Value_msginit = {
+ NULL,
+ &google_protobuf_Int32Value__fields[0],
+ UPB_SIZE(4, 4), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_UInt32Value__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 13, 1},
+};
+
+const upb_msglayout google_protobuf_UInt32Value_msginit = {
+ NULL,
+ &google_protobuf_UInt32Value__fields[0],
+ UPB_SIZE(4, 4), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_BoolValue__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 8, 1},
+};
+
+const upb_msglayout google_protobuf_BoolValue_msginit = {
+ NULL,
+ &google_protobuf_BoolValue__fields[0],
+ UPB_SIZE(1, 1), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_StringValue__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+};
+
+const upb_msglayout google_protobuf_StringValue_msginit = {
+ NULL,
+ &google_protobuf_StringValue__fields[0],
+ UPB_SIZE(8, 16), 1, false,
+};
+
+static const upb_msglayout_field google_protobuf_BytesValue__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 12, 1},
+};
+
+const upb_msglayout google_protobuf_BytesValue_msginit = {
+ NULL,
+ &google_protobuf_BytesValue__fields[0],
+ UPB_SIZE(8, 16), 1, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h
index 761eeebdd6..72c754f1ae 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h
@@ -1,237 +1,237 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/wrappers.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_PROTOBUF_WRAPPERS_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_WRAPPERS_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_protobuf_DoubleValue;
-struct google_protobuf_FloatValue;
-struct google_protobuf_Int64Value;
-struct google_protobuf_UInt64Value;
-struct google_protobuf_Int32Value;
-struct google_protobuf_UInt32Value;
-struct google_protobuf_BoolValue;
-struct google_protobuf_StringValue;
-struct google_protobuf_BytesValue;
-typedef struct google_protobuf_DoubleValue google_protobuf_DoubleValue;
-typedef struct google_protobuf_FloatValue google_protobuf_FloatValue;
-typedef struct google_protobuf_Int64Value google_protobuf_Int64Value;
-typedef struct google_protobuf_UInt64Value google_protobuf_UInt64Value;
-typedef struct google_protobuf_Int32Value google_protobuf_Int32Value;
-typedef struct google_protobuf_UInt32Value google_protobuf_UInt32Value;
-typedef struct google_protobuf_BoolValue google_protobuf_BoolValue;
-typedef struct google_protobuf_StringValue google_protobuf_StringValue;
-typedef struct google_protobuf_BytesValue google_protobuf_BytesValue;
-extern const upb_msglayout google_protobuf_DoubleValue_msginit;
-extern const upb_msglayout google_protobuf_FloatValue_msginit;
-extern const upb_msglayout google_protobuf_Int64Value_msginit;
-extern const upb_msglayout google_protobuf_UInt64Value_msginit;
-extern const upb_msglayout google_protobuf_Int32Value_msginit;
-extern const upb_msglayout google_protobuf_UInt32Value_msginit;
-extern const upb_msglayout google_protobuf_BoolValue_msginit;
-extern const upb_msglayout google_protobuf_StringValue_msginit;
-extern const upb_msglayout google_protobuf_BytesValue_msginit;
-
-
-/* google.protobuf.DoubleValue */
-
-UPB_INLINE google_protobuf_DoubleValue *google_protobuf_DoubleValue_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/wrappers.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_WRAPPERS_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_WRAPPERS_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_protobuf_DoubleValue;
+struct google_protobuf_FloatValue;
+struct google_protobuf_Int64Value;
+struct google_protobuf_UInt64Value;
+struct google_protobuf_Int32Value;
+struct google_protobuf_UInt32Value;
+struct google_protobuf_BoolValue;
+struct google_protobuf_StringValue;
+struct google_protobuf_BytesValue;
+typedef struct google_protobuf_DoubleValue google_protobuf_DoubleValue;
+typedef struct google_protobuf_FloatValue google_protobuf_FloatValue;
+typedef struct google_protobuf_Int64Value google_protobuf_Int64Value;
+typedef struct google_protobuf_UInt64Value google_protobuf_UInt64Value;
+typedef struct google_protobuf_Int32Value google_protobuf_Int32Value;
+typedef struct google_protobuf_UInt32Value google_protobuf_UInt32Value;
+typedef struct google_protobuf_BoolValue google_protobuf_BoolValue;
+typedef struct google_protobuf_StringValue google_protobuf_StringValue;
+typedef struct google_protobuf_BytesValue google_protobuf_BytesValue;
+extern const upb_msglayout google_protobuf_DoubleValue_msginit;
+extern const upb_msglayout google_protobuf_FloatValue_msginit;
+extern const upb_msglayout google_protobuf_Int64Value_msginit;
+extern const upb_msglayout google_protobuf_UInt64Value_msginit;
+extern const upb_msglayout google_protobuf_Int32Value_msginit;
+extern const upb_msglayout google_protobuf_UInt32Value_msginit;
+extern const upb_msglayout google_protobuf_BoolValue_msginit;
+extern const upb_msglayout google_protobuf_StringValue_msginit;
+extern const upb_msglayout google_protobuf_BytesValue_msginit;
+
+
+/* google.protobuf.DoubleValue */
+
+UPB_INLINE google_protobuf_DoubleValue *google_protobuf_DoubleValue_new(upb_arena *arena) {
return (google_protobuf_DoubleValue *)_upb_msg_new(&google_protobuf_DoubleValue_msginit, arena);
-}
-UPB_INLINE google_protobuf_DoubleValue *google_protobuf_DoubleValue_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_DoubleValue *ret = google_protobuf_DoubleValue_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_DoubleValue_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_DoubleValue_serialize(const google_protobuf_DoubleValue *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_DoubleValue_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_DoubleValue *google_protobuf_DoubleValue_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_DoubleValue *ret = google_protobuf_DoubleValue_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_DoubleValue_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_DoubleValue_serialize(const google_protobuf_DoubleValue *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_DoubleValue_msginit, arena, len);
+}
+
UPB_INLINE double google_protobuf_DoubleValue_value(const google_protobuf_DoubleValue *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), double); }
-
-UPB_INLINE void google_protobuf_DoubleValue_set_value(google_protobuf_DoubleValue *msg, double value) {
+
+UPB_INLINE void google_protobuf_DoubleValue_set_value(google_protobuf_DoubleValue *msg, double value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), double) = value;
-}
-
-/* google.protobuf.FloatValue */
-
-UPB_INLINE google_protobuf_FloatValue *google_protobuf_FloatValue_new(upb_arena *arena) {
+}
+
+/* google.protobuf.FloatValue */
+
+UPB_INLINE google_protobuf_FloatValue *google_protobuf_FloatValue_new(upb_arena *arena) {
return (google_protobuf_FloatValue *)_upb_msg_new(&google_protobuf_FloatValue_msginit, arena);
-}
-UPB_INLINE google_protobuf_FloatValue *google_protobuf_FloatValue_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_FloatValue *ret = google_protobuf_FloatValue_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_FloatValue_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_FloatValue_serialize(const google_protobuf_FloatValue *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_FloatValue_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_FloatValue *google_protobuf_FloatValue_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_FloatValue *ret = google_protobuf_FloatValue_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_FloatValue_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_FloatValue_serialize(const google_protobuf_FloatValue *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_FloatValue_msginit, arena, len);
+}
+
UPB_INLINE float google_protobuf_FloatValue_value(const google_protobuf_FloatValue *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), float); }
-
-UPB_INLINE void google_protobuf_FloatValue_set_value(google_protobuf_FloatValue *msg, float value) {
+
+UPB_INLINE void google_protobuf_FloatValue_set_value(google_protobuf_FloatValue *msg, float value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), float) = value;
-}
-
-/* google.protobuf.Int64Value */
-
-UPB_INLINE google_protobuf_Int64Value *google_protobuf_Int64Value_new(upb_arena *arena) {
+}
+
+/* google.protobuf.Int64Value */
+
+UPB_INLINE google_protobuf_Int64Value *google_protobuf_Int64Value_new(upb_arena *arena) {
return (google_protobuf_Int64Value *)_upb_msg_new(&google_protobuf_Int64Value_msginit, arena);
-}
-UPB_INLINE google_protobuf_Int64Value *google_protobuf_Int64Value_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Int64Value *ret = google_protobuf_Int64Value_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Int64Value_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Int64Value_serialize(const google_protobuf_Int64Value *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Int64Value_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_Int64Value *google_protobuf_Int64Value_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Int64Value *ret = google_protobuf_Int64Value_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Int64Value_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Int64Value_serialize(const google_protobuf_Int64Value *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Int64Value_msginit, arena, len);
+}
+
UPB_INLINE int64_t google_protobuf_Int64Value_value(const google_protobuf_Int64Value *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t); }
-
-UPB_INLINE void google_protobuf_Int64Value_set_value(google_protobuf_Int64Value *msg, int64_t value) {
+
+UPB_INLINE void google_protobuf_Int64Value_set_value(google_protobuf_Int64Value *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t) = value;
-}
-
-/* google.protobuf.UInt64Value */
-
-UPB_INLINE google_protobuf_UInt64Value *google_protobuf_UInt64Value_new(upb_arena *arena) {
+}
+
+/* google.protobuf.UInt64Value */
+
+UPB_INLINE google_protobuf_UInt64Value *google_protobuf_UInt64Value_new(upb_arena *arena) {
return (google_protobuf_UInt64Value *)_upb_msg_new(&google_protobuf_UInt64Value_msginit, arena);
-}
-UPB_INLINE google_protobuf_UInt64Value *google_protobuf_UInt64Value_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_UInt64Value *ret = google_protobuf_UInt64Value_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_UInt64Value_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_UInt64Value_serialize(const google_protobuf_UInt64Value *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_UInt64Value_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_UInt64Value *google_protobuf_UInt64Value_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_UInt64Value *ret = google_protobuf_UInt64Value_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_UInt64Value_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_UInt64Value_serialize(const google_protobuf_UInt64Value *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_UInt64Value_msginit, arena, len);
+}
+
UPB_INLINE uint64_t google_protobuf_UInt64Value_value(const google_protobuf_UInt64Value *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint64_t); }
-
-UPB_INLINE void google_protobuf_UInt64Value_set_value(google_protobuf_UInt64Value *msg, uint64_t value) {
+
+UPB_INLINE void google_protobuf_UInt64Value_set_value(google_protobuf_UInt64Value *msg, uint64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint64_t) = value;
-}
-
-/* google.protobuf.Int32Value */
-
-UPB_INLINE google_protobuf_Int32Value *google_protobuf_Int32Value_new(upb_arena *arena) {
+}
+
+/* google.protobuf.Int32Value */
+
+UPB_INLINE google_protobuf_Int32Value *google_protobuf_Int32Value_new(upb_arena *arena) {
return (google_protobuf_Int32Value *)_upb_msg_new(&google_protobuf_Int32Value_msginit, arena);
-}
-UPB_INLINE google_protobuf_Int32Value *google_protobuf_Int32Value_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_Int32Value *ret = google_protobuf_Int32Value_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_Int32Value_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_Int32Value_serialize(const google_protobuf_Int32Value *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_Int32Value_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_Int32Value *google_protobuf_Int32Value_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_Int32Value *ret = google_protobuf_Int32Value_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_Int32Value_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_Int32Value_serialize(const google_protobuf_Int32Value *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_Int32Value_msginit, arena, len);
+}
+
UPB_INLINE int32_t google_protobuf_Int32Value_value(const google_protobuf_Int32Value *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
-
-UPB_INLINE void google_protobuf_Int32Value_set_value(google_protobuf_Int32Value *msg, int32_t value) {
+
+UPB_INLINE void google_protobuf_Int32Value_set_value(google_protobuf_Int32Value *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-
-/* google.protobuf.UInt32Value */
-
-UPB_INLINE google_protobuf_UInt32Value *google_protobuf_UInt32Value_new(upb_arena *arena) {
+}
+
+/* google.protobuf.UInt32Value */
+
+UPB_INLINE google_protobuf_UInt32Value *google_protobuf_UInt32Value_new(upb_arena *arena) {
return (google_protobuf_UInt32Value *)_upb_msg_new(&google_protobuf_UInt32Value_msginit, arena);
-}
-UPB_INLINE google_protobuf_UInt32Value *google_protobuf_UInt32Value_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_UInt32Value *ret = google_protobuf_UInt32Value_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_UInt32Value_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_UInt32Value_serialize(const google_protobuf_UInt32Value *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_UInt32Value_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_UInt32Value *google_protobuf_UInt32Value_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_UInt32Value *ret = google_protobuf_UInt32Value_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_UInt32Value_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_UInt32Value_serialize(const google_protobuf_UInt32Value *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_UInt32Value_msginit, arena, len);
+}
+
UPB_INLINE uint32_t google_protobuf_UInt32Value_value(const google_protobuf_UInt32Value *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t); }
-
-UPB_INLINE void google_protobuf_UInt32Value_set_value(google_protobuf_UInt32Value *msg, uint32_t value) {
+
+UPB_INLINE void google_protobuf_UInt32Value_set_value(google_protobuf_UInt32Value *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
-}
-
-/* google.protobuf.BoolValue */
-
-UPB_INLINE google_protobuf_BoolValue *google_protobuf_BoolValue_new(upb_arena *arena) {
+}
+
+/* google.protobuf.BoolValue */
+
+UPB_INLINE google_protobuf_BoolValue *google_protobuf_BoolValue_new(upb_arena *arena) {
return (google_protobuf_BoolValue *)_upb_msg_new(&google_protobuf_BoolValue_msginit, arena);
-}
-UPB_INLINE google_protobuf_BoolValue *google_protobuf_BoolValue_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_BoolValue *ret = google_protobuf_BoolValue_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_BoolValue_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_BoolValue_serialize(const google_protobuf_BoolValue *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_BoolValue_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_BoolValue *google_protobuf_BoolValue_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_BoolValue *ret = google_protobuf_BoolValue_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_BoolValue_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_BoolValue_serialize(const google_protobuf_BoolValue *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_BoolValue_msginit, arena, len);
+}
+
UPB_INLINE bool google_protobuf_BoolValue_value(const google_protobuf_BoolValue *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), bool); }
-
-UPB_INLINE void google_protobuf_BoolValue_set_value(google_protobuf_BoolValue *msg, bool value) {
+
+UPB_INLINE void google_protobuf_BoolValue_set_value(google_protobuf_BoolValue *msg, bool value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), bool) = value;
-}
-
-/* google.protobuf.StringValue */
-
-UPB_INLINE google_protobuf_StringValue *google_protobuf_StringValue_new(upb_arena *arena) {
+}
+
+/* google.protobuf.StringValue */
+
+UPB_INLINE google_protobuf_StringValue *google_protobuf_StringValue_new(upb_arena *arena) {
return (google_protobuf_StringValue *)_upb_msg_new(&google_protobuf_StringValue_msginit, arena);
-}
-UPB_INLINE google_protobuf_StringValue *google_protobuf_StringValue_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_StringValue *ret = google_protobuf_StringValue_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_StringValue_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_StringValue_serialize(const google_protobuf_StringValue *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_StringValue_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_StringValue *google_protobuf_StringValue_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_StringValue *ret = google_protobuf_StringValue_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_StringValue_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_StringValue_serialize(const google_protobuf_StringValue *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_StringValue_msginit, arena, len);
+}
+
UPB_INLINE upb_strview google_protobuf_StringValue_value(const google_protobuf_StringValue *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
-
-UPB_INLINE void google_protobuf_StringValue_set_value(google_protobuf_StringValue *msg, upb_strview value) {
+
+UPB_INLINE void google_protobuf_StringValue_set_value(google_protobuf_StringValue *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-
-/* google.protobuf.BytesValue */
-
-UPB_INLINE google_protobuf_BytesValue *google_protobuf_BytesValue_new(upb_arena *arena) {
+}
+
+/* google.protobuf.BytesValue */
+
+UPB_INLINE google_protobuf_BytesValue *google_protobuf_BytesValue_new(upb_arena *arena) {
return (google_protobuf_BytesValue *)_upb_msg_new(&google_protobuf_BytesValue_msginit, arena);
-}
-UPB_INLINE google_protobuf_BytesValue *google_protobuf_BytesValue_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_protobuf_BytesValue *ret = google_protobuf_BytesValue_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_protobuf_BytesValue_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_protobuf_BytesValue_serialize(const google_protobuf_BytesValue *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_protobuf_BytesValue_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_protobuf_BytesValue *google_protobuf_BytesValue_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_protobuf_BytesValue *ret = google_protobuf_BytesValue_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_protobuf_BytesValue_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_protobuf_BytesValue_serialize(const google_protobuf_BytesValue *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_protobuf_BytesValue_msginit, arena, len);
+}
+
UPB_INLINE upb_strview google_protobuf_BytesValue_value(const google_protobuf_BytesValue *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
-
-UPB_INLINE void google_protobuf_BytesValue_set_value(google_protobuf_BytesValue *msg, upb_strview value) {
+
+UPB_INLINE void google_protobuf_BytesValue_set_value(google_protobuf_BytesValue *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_PROTOBUF_WRAPPERS_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_PROTOBUF_WRAPPERS_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.c
index 25ac146174..9a9e6f0753 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.c
@@ -1,33 +1,33 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/rpc/status.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "google/rpc/status.upb.h"
-#include "google/protobuf/any.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const google_rpc_Status_submsgs[1] = {
- &google_protobuf_Any_msginit,
-};
-
-static const upb_msglayout_field google_rpc_Status__fields[3] = {
- {1, UPB_SIZE(0, 0), 0, 0, 5, 1},
- {2, UPB_SIZE(4, 8), 0, 0, 9, 1},
- {3, UPB_SIZE(12, 24), 0, 0, 11, 3},
-};
-
-const upb_msglayout google_rpc_Status_msginit = {
- &google_rpc_Status_submsgs[0],
- &google_rpc_Status__fields[0],
- UPB_SIZE(16, 32), 3, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/rpc/status.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "google/rpc/status.upb.h"
+#include "google/protobuf/any.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const google_rpc_Status_submsgs[1] = {
+ &google_protobuf_Any_msginit,
+};
+
+static const upb_msglayout_field google_rpc_Status__fields[3] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 5, 1},
+ {2, UPB_SIZE(4, 8), 0, 0, 9, 1},
+ {3, UPB_SIZE(12, 24), 0, 0, 11, 3},
+};
+
+const upb_msglayout google_rpc_Status_msginit = {
+ &google_rpc_Status_submsgs[0],
+ &google_rpc_Status__fields[0],
+ UPB_SIZE(16, 32), 3, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.h
index 2c5fb02f7d..675615adcf 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/google/rpc/status.upb.h
@@ -1,74 +1,74 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/rpc/status.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef GOOGLE_RPC_STATUS_PROTO_UPB_H_
-#define GOOGLE_RPC_STATUS_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct google_rpc_Status;
-typedef struct google_rpc_Status google_rpc_Status;
-extern const upb_msglayout google_rpc_Status_msginit;
-struct google_protobuf_Any;
-extern const upb_msglayout google_protobuf_Any_msginit;
-
-
-/* google.rpc.Status */
-
-UPB_INLINE google_rpc_Status *google_rpc_Status_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/rpc/status.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_RPC_STATUS_PROTO_UPB_H_
+#define GOOGLE_RPC_STATUS_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct google_rpc_Status;
+typedef struct google_rpc_Status google_rpc_Status;
+extern const upb_msglayout google_rpc_Status_msginit;
+struct google_protobuf_Any;
+extern const upb_msglayout google_protobuf_Any_msginit;
+
+
+/* google.rpc.Status */
+
+UPB_INLINE google_rpc_Status *google_rpc_Status_new(upb_arena *arena) {
return (google_rpc_Status *)_upb_msg_new(&google_rpc_Status_msginit, arena);
-}
-UPB_INLINE google_rpc_Status *google_rpc_Status_parse(const char *buf, size_t size,
- upb_arena *arena) {
- google_rpc_Status *ret = google_rpc_Status_new(arena);
- return (ret && upb_decode(buf, size, ret, &google_rpc_Status_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *google_rpc_Status_serialize(const google_rpc_Status *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &google_rpc_Status_msginit, arena, len);
-}
-
+}
+UPB_INLINE google_rpc_Status *google_rpc_Status_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ google_rpc_Status *ret = google_rpc_Status_new(arena);
+ return (ret && upb_decode(buf, size, ret, &google_rpc_Status_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *google_rpc_Status_serialize(const google_rpc_Status *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &google_rpc_Status_msginit, arena, len);
+}
+
UPB_INLINE int32_t google_rpc_Status_code(const google_rpc_Status *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
UPB_INLINE upb_strview google_rpc_Status_message(const google_rpc_Status *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_rpc_Status_has_details(const google_rpc_Status *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(12, 24)); }
-UPB_INLINE const struct google_protobuf_Any* const* google_rpc_Status_details(const google_rpc_Status *msg, size_t *len) { return (const struct google_protobuf_Any* const*)_upb_array_accessor(msg, UPB_SIZE(12, 24), len); }
-
-UPB_INLINE void google_rpc_Status_set_code(google_rpc_Status *msg, int32_t value) {
+UPB_INLINE const struct google_protobuf_Any* const* google_rpc_Status_details(const google_rpc_Status *msg, size_t *len) { return (const struct google_protobuf_Any* const*)_upb_array_accessor(msg, UPB_SIZE(12, 24), len); }
+
+UPB_INLINE void google_rpc_Status_set_code(google_rpc_Status *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-UPB_INLINE void google_rpc_Status_set_message(google_rpc_Status *msg, upb_strview value) {
+}
+UPB_INLINE void google_rpc_Status_set_message(google_rpc_Status *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE struct google_protobuf_Any** google_rpc_Status_mutable_details(google_rpc_Status *msg, size_t *len) {
- return (struct google_protobuf_Any**)_upb_array_mutable_accessor(msg, UPB_SIZE(12, 24), len);
-}
-UPB_INLINE struct google_protobuf_Any** google_rpc_Status_resize_details(google_rpc_Status *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_Any** google_rpc_Status_mutable_details(google_rpc_Status *msg, size_t *len) {
+ return (struct google_protobuf_Any**)_upb_array_mutable_accessor(msg, UPB_SIZE(12, 24), len);
+}
+UPB_INLINE struct google_protobuf_Any** google_rpc_Status_resize_details(google_rpc_Status *msg, size_t len, upb_arena *arena) {
return (struct google_protobuf_Any**)_upb_array_resize_accessor(msg, UPB_SIZE(12, 24), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_Any* google_rpc_Status_add_details(google_rpc_Status *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_Any* google_rpc_Status_add_details(google_rpc_Status *msg, upb_arena *arena) {
struct google_protobuf_Any* sub = (struct google_protobuf_Any*)_upb_msg_new(&google_protobuf_Any_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(12, 24), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* GOOGLE_RPC_STATUS_PROTO_UPB_H_ */
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(12, 24), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* GOOGLE_RPC_STATUS_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c
index 6c917ad9f2..0eccb13985 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c
@@ -1,49 +1,49 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/gcp/altscontext.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "src/proto/grpc/gcp/altscontext.upb.h"
-#include "src/proto/grpc/gcp/transport_security_common.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const grpc_gcp_AltsContext_submsgs[2] = {
- &grpc_gcp_AltsContext_PeerAttributesEntry_msginit,
- &grpc_gcp_RpcProtocolVersions_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_AltsContext__fields[7] = {
- {1, UPB_SIZE(8, 8), 0, 0, 9, 1},
- {2, UPB_SIZE(16, 24), 0, 0, 9, 1},
- {3, UPB_SIZE(0, 0), 0, 0, 14, 1},
- {4, UPB_SIZE(24, 40), 0, 0, 9, 1},
- {5, UPB_SIZE(32, 56), 0, 0, 9, 1},
- {6, UPB_SIZE(40, 72), 0, 1, 11, 1},
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/gcp/altscontext.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "src/proto/grpc/gcp/altscontext.upb.h"
+#include "src/proto/grpc/gcp/transport_security_common.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const grpc_gcp_AltsContext_submsgs[2] = {
+ &grpc_gcp_AltsContext_PeerAttributesEntry_msginit,
+ &grpc_gcp_RpcProtocolVersions_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_AltsContext__fields[7] = {
+ {1, UPB_SIZE(8, 8), 0, 0, 9, 1},
+ {2, UPB_SIZE(16, 24), 0, 0, 9, 1},
+ {3, UPB_SIZE(0, 0), 0, 0, 14, 1},
+ {4, UPB_SIZE(24, 40), 0, 0, 9, 1},
+ {5, UPB_SIZE(32, 56), 0, 0, 9, 1},
+ {6, UPB_SIZE(40, 72), 0, 1, 11, 1},
{7, UPB_SIZE(44, 80), 0, 0, 11, _UPB_LABEL_MAP},
-};
-
-const upb_msglayout grpc_gcp_AltsContext_msginit = {
- &grpc_gcp_AltsContext_submsgs[0],
- &grpc_gcp_AltsContext__fields[0],
- UPB_SIZE(48, 96), 7, false,
-};
-
-static const upb_msglayout_field grpc_gcp_AltsContext_PeerAttributesEntry__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 16), 0, 0, 9, 1},
-};
-
-const upb_msglayout grpc_gcp_AltsContext_PeerAttributesEntry_msginit = {
- NULL,
- &grpc_gcp_AltsContext_PeerAttributesEntry__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+};
+
+const upb_msglayout grpc_gcp_AltsContext_msginit = {
+ &grpc_gcp_AltsContext_submsgs[0],
+ &grpc_gcp_AltsContext__fields[0],
+ UPB_SIZE(48, 96), 7, false,
+};
+
+static const upb_msglayout_field grpc_gcp_AltsContext_PeerAttributesEntry__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 16), 0, 0, 9, 1},
+};
+
+const upb_msglayout grpc_gcp_AltsContext_PeerAttributesEntry_msginit = {
+ NULL,
+ &grpc_gcp_AltsContext_PeerAttributesEntry__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h
index 33c1b2f160..263eecf66c 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h
@@ -1,48 +1,48 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/gcp/altscontext.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef SRC_PROTO_GRPC_GCP_ALTSCONTEXT_PROTO_UPB_H_
-#define SRC_PROTO_GRPC_GCP_ALTSCONTEXT_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct grpc_gcp_AltsContext;
-struct grpc_gcp_AltsContext_PeerAttributesEntry;
-typedef struct grpc_gcp_AltsContext grpc_gcp_AltsContext;
-typedef struct grpc_gcp_AltsContext_PeerAttributesEntry grpc_gcp_AltsContext_PeerAttributesEntry;
-extern const upb_msglayout grpc_gcp_AltsContext_msginit;
-extern const upb_msglayout grpc_gcp_AltsContext_PeerAttributesEntry_msginit;
-struct grpc_gcp_RpcProtocolVersions;
-extern const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit;
-
-
-/* grpc.gcp.AltsContext */
-
-UPB_INLINE grpc_gcp_AltsContext *grpc_gcp_AltsContext_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/gcp/altscontext.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef SRC_PROTO_GRPC_GCP_ALTSCONTEXT_PROTO_UPB_H_
+#define SRC_PROTO_GRPC_GCP_ALTSCONTEXT_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct grpc_gcp_AltsContext;
+struct grpc_gcp_AltsContext_PeerAttributesEntry;
+typedef struct grpc_gcp_AltsContext grpc_gcp_AltsContext;
+typedef struct grpc_gcp_AltsContext_PeerAttributesEntry grpc_gcp_AltsContext_PeerAttributesEntry;
+extern const upb_msglayout grpc_gcp_AltsContext_msginit;
+extern const upb_msglayout grpc_gcp_AltsContext_PeerAttributesEntry_msginit;
+struct grpc_gcp_RpcProtocolVersions;
+extern const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit;
+
+
+/* grpc.gcp.AltsContext */
+
+UPB_INLINE grpc_gcp_AltsContext *grpc_gcp_AltsContext_new(upb_arena *arena) {
return (grpc_gcp_AltsContext *)_upb_msg_new(&grpc_gcp_AltsContext_msginit, arena);
-}
-UPB_INLINE grpc_gcp_AltsContext *grpc_gcp_AltsContext_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_AltsContext *ret = grpc_gcp_AltsContext_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_AltsContext_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_AltsContext_serialize(const grpc_gcp_AltsContext *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_AltsContext_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_AltsContext *grpc_gcp_AltsContext_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_AltsContext *ret = grpc_gcp_AltsContext_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_AltsContext_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_AltsContext_serialize(const grpc_gcp_AltsContext *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_AltsContext_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_gcp_AltsContext_application_protocol(const grpc_gcp_AltsContext *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE upb_strview grpc_gcp_AltsContext_record_protocol(const grpc_gcp_AltsContext *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 24), upb_strview); }
UPB_INLINE int32_t grpc_gcp_AltsContext_security_level(const grpc_gcp_AltsContext *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
@@ -54,60 +54,60 @@ UPB_INLINE bool grpc_gcp_AltsContext_has_peer_attributes(const grpc_gcp_AltsCont
UPB_INLINE size_t grpc_gcp_AltsContext_peer_attributes_size(const grpc_gcp_AltsContext *msg) {return _upb_msg_map_size(msg, UPB_SIZE(44, 80)); }
UPB_INLINE bool grpc_gcp_AltsContext_peer_attributes_get(const grpc_gcp_AltsContext *msg, upb_strview key, upb_strview *val) { return _upb_msg_map_get(msg, UPB_SIZE(44, 80), &key, 0, val, 0); }
UPB_INLINE const grpc_gcp_AltsContext_PeerAttributesEntry* grpc_gcp_AltsContext_peer_attributes_next(const grpc_gcp_AltsContext *msg, size_t* iter) { return (const grpc_gcp_AltsContext_PeerAttributesEntry*)_upb_msg_map_next(msg, UPB_SIZE(44, 80), iter); }
-
-UPB_INLINE void grpc_gcp_AltsContext_set_application_protocol(grpc_gcp_AltsContext *msg, upb_strview value) {
+
+UPB_INLINE void grpc_gcp_AltsContext_set_application_protocol(grpc_gcp_AltsContext *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_AltsContext_set_record_protocol(grpc_gcp_AltsContext *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_gcp_AltsContext_set_record_protocol(grpc_gcp_AltsContext *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 24), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_AltsContext_set_security_level(grpc_gcp_AltsContext *msg, int32_t value) {
+}
+UPB_INLINE void grpc_gcp_AltsContext_set_security_level(grpc_gcp_AltsContext *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-UPB_INLINE void grpc_gcp_AltsContext_set_peer_service_account(grpc_gcp_AltsContext *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_gcp_AltsContext_set_peer_service_account(grpc_gcp_AltsContext *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(24, 40), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_AltsContext_set_local_service_account(grpc_gcp_AltsContext *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_gcp_AltsContext_set_local_service_account(grpc_gcp_AltsContext *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(32, 56), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_AltsContext_set_peer_rpc_versions(grpc_gcp_AltsContext *msg, struct grpc_gcp_RpcProtocolVersions* value) {
+}
+UPB_INLINE void grpc_gcp_AltsContext_set_peer_rpc_versions(grpc_gcp_AltsContext *msg, struct grpc_gcp_RpcProtocolVersions* value) {
*UPB_PTR_AT(msg, UPB_SIZE(40, 72), struct grpc_gcp_RpcProtocolVersions*) = value;
-}
-UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_AltsContext_mutable_peer_rpc_versions(grpc_gcp_AltsContext *msg, upb_arena *arena) {
- struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_AltsContext_peer_rpc_versions(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_AltsContext_mutable_peer_rpc_versions(grpc_gcp_AltsContext *msg, upb_arena *arena) {
+ struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_AltsContext_peer_rpc_versions(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_RpcProtocolVersions*)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_AltsContext_set_peer_rpc_versions(msg, sub);
- }
- return sub;
-}
+ if (!sub) return NULL;
+ grpc_gcp_AltsContext_set_peer_rpc_versions(msg, sub);
+ }
+ return sub;
+}
UPB_INLINE void grpc_gcp_AltsContext_peer_attributes_clear(grpc_gcp_AltsContext *msg) { _upb_msg_map_clear(msg, UPB_SIZE(44, 80)); }
UPB_INLINE bool grpc_gcp_AltsContext_peer_attributes_set(grpc_gcp_AltsContext *msg, upb_strview key, upb_strview val, upb_arena *a) { return _upb_msg_map_set(msg, UPB_SIZE(44, 80), &key, 0, &val, 0, a); }
UPB_INLINE bool grpc_gcp_AltsContext_peer_attributes_delete(grpc_gcp_AltsContext *msg, upb_strview key) { return _upb_msg_map_delete(msg, UPB_SIZE(44, 80), &key, 0); }
UPB_INLINE grpc_gcp_AltsContext_PeerAttributesEntry* grpc_gcp_AltsContext_peer_attributes_nextmutable(grpc_gcp_AltsContext *msg, size_t* iter) { return (grpc_gcp_AltsContext_PeerAttributesEntry*)_upb_msg_map_next(msg, UPB_SIZE(44, 80), iter); }
-
-/* grpc.gcp.AltsContext.PeerAttributesEntry */
-
+
+/* grpc.gcp.AltsContext.PeerAttributesEntry */
+
UPB_INLINE upb_strview grpc_gcp_AltsContext_PeerAttributesEntry_key(const grpc_gcp_AltsContext_PeerAttributesEntry *msg) {
upb_strview ret;
_upb_msg_map_key(msg, &ret, 0);
return ret;
-}
+}
UPB_INLINE upb_strview grpc_gcp_AltsContext_PeerAttributesEntry_value(const grpc_gcp_AltsContext_PeerAttributesEntry *msg) {
upb_strview ret;
_upb_msg_map_value(msg, &ret, 0);
return ret;
-}
-
-UPB_INLINE void grpc_gcp_AltsContext_PeerAttributesEntry_set_value(grpc_gcp_AltsContext_PeerAttributesEntry *msg, upb_strview value) {
+}
+
+UPB_INLINE void grpc_gcp_AltsContext_PeerAttributesEntry_set_value(grpc_gcp_AltsContext_PeerAttributesEntry *msg, upb_strview value) {
_upb_msg_map_set_value(msg, &value, 0);
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* SRC_PROTO_GRPC_GCP_ALTSCONTEXT_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* SRC_PROTO_GRPC_GCP_ALTSCONTEXT_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c
index 036b66fdce..d852fd6954 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c
@@ -1,65 +1,65 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/gcp/handshaker.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "src/proto/grpc/gcp/handshaker.upb.h"
-#include "src/proto/grpc/gcp/transport_security_common.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout_field grpc_gcp_Endpoint__fields[3] = {
- {1, UPB_SIZE(12, 16), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 8), 0, 0, 5, 1},
- {3, UPB_SIZE(0, 0), 0, 0, 14, 1},
-};
-
-const upb_msglayout grpc_gcp_Endpoint_msginit = {
- NULL,
- &grpc_gcp_Endpoint__fields[0],
- UPB_SIZE(24, 32), 3, false,
-};
-
-static const upb_msglayout *const grpc_gcp_Identity_submsgs[1] = {
- &grpc_gcp_Identity_AttributesEntry_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_Identity__fields[3] = {
- {1, UPB_SIZE(4, 8), UPB_SIZE(-13, -25), 0, 9, 1},
- {2, UPB_SIZE(4, 8), UPB_SIZE(-13, -25), 0, 9, 1},
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/gcp/handshaker.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "src/proto/grpc/gcp/handshaker.upb.h"
+#include "src/proto/grpc/gcp/transport_security_common.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout_field grpc_gcp_Endpoint__fields[3] = {
+ {1, UPB_SIZE(12, 16), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 8), 0, 0, 5, 1},
+ {3, UPB_SIZE(0, 0), 0, 0, 14, 1},
+};
+
+const upb_msglayout grpc_gcp_Endpoint_msginit = {
+ NULL,
+ &grpc_gcp_Endpoint__fields[0],
+ UPB_SIZE(24, 32), 3, false,
+};
+
+static const upb_msglayout *const grpc_gcp_Identity_submsgs[1] = {
+ &grpc_gcp_Identity_AttributesEntry_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_Identity__fields[3] = {
+ {1, UPB_SIZE(4, 8), UPB_SIZE(-13, -25), 0, 9, 1},
+ {2, UPB_SIZE(4, 8), UPB_SIZE(-13, -25), 0, 9, 1},
{3, UPB_SIZE(0, 0), 0, 0, 11, _UPB_LABEL_MAP},
-};
-
-const upb_msglayout grpc_gcp_Identity_msginit = {
- &grpc_gcp_Identity_submsgs[0],
- &grpc_gcp_Identity__fields[0],
- UPB_SIZE(16, 32), 3, false,
-};
-
-static const upb_msglayout_field grpc_gcp_Identity_AttributesEntry__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 16), 0, 0, 9, 1},
-};
-
-const upb_msglayout grpc_gcp_Identity_AttributesEntry_msginit = {
- NULL,
- &grpc_gcp_Identity_AttributesEntry__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const grpc_gcp_StartClientHandshakeReq_submsgs[5] = {
- &grpc_gcp_Endpoint_msginit,
- &grpc_gcp_Identity_msginit,
- &grpc_gcp_RpcProtocolVersions_msginit,
-};
-
+};
+
+const upb_msglayout grpc_gcp_Identity_msginit = {
+ &grpc_gcp_Identity_submsgs[0],
+ &grpc_gcp_Identity__fields[0],
+ UPB_SIZE(16, 32), 3, false,
+};
+
+static const upb_msglayout_field grpc_gcp_Identity_AttributesEntry__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 16), 0, 0, 9, 1},
+};
+
+const upb_msglayout grpc_gcp_Identity_AttributesEntry_msginit = {
+ NULL,
+ &grpc_gcp_Identity_AttributesEntry__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const grpc_gcp_StartClientHandshakeReq_submsgs[5] = {
+ &grpc_gcp_Endpoint_msginit,
+ &grpc_gcp_Identity_msginit,
+ &grpc_gcp_RpcProtocolVersions_msginit,
+};
+
static const upb_msglayout_field grpc_gcp_StartClientHandshakeReq__fields[10] = {
- {1, UPB_SIZE(0, 0), 0, 0, 14, 1},
+ {1, UPB_SIZE(0, 0), 0, 0, 14, 1},
{2, UPB_SIZE(36, 64), 0, 0, 9, 3},
{3, UPB_SIZE(40, 72), 0, 0, 9, 3},
{4, UPB_SIZE(44, 80), 0, 1, 11, 3},
@@ -69,35 +69,35 @@ static const upb_msglayout_field grpc_gcp_StartClientHandshakeReq__fields[10] =
{8, UPB_SIZE(12, 16), 0, 0, 9, 1},
{9, UPB_SIZE(32, 56), 0, 2, 11, 1},
{10, UPB_SIZE(8, 8), 0, 0, 13, 1},
-};
-
-const upb_msglayout grpc_gcp_StartClientHandshakeReq_msginit = {
- &grpc_gcp_StartClientHandshakeReq_submsgs[0],
- &grpc_gcp_StartClientHandshakeReq__fields[0],
+};
+
+const upb_msglayout grpc_gcp_StartClientHandshakeReq_msginit = {
+ &grpc_gcp_StartClientHandshakeReq_submsgs[0],
+ &grpc_gcp_StartClientHandshakeReq__fields[0],
UPB_SIZE(48, 96), 10, false,
-};
-
-static const upb_msglayout *const grpc_gcp_ServerHandshakeParameters_submsgs[1] = {
- &grpc_gcp_Identity_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_ServerHandshakeParameters__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 3},
- {2, UPB_SIZE(4, 8), 0, 0, 11, 3},
-};
-
-const upb_msglayout grpc_gcp_ServerHandshakeParameters_msginit = {
- &grpc_gcp_ServerHandshakeParameters_submsgs[0],
- &grpc_gcp_ServerHandshakeParameters__fields[0],
- UPB_SIZE(8, 16), 2, false,
-};
-
-static const upb_msglayout *const grpc_gcp_StartServerHandshakeReq_submsgs[4] = {
- &grpc_gcp_Endpoint_msginit,
- &grpc_gcp_RpcProtocolVersions_msginit,
- &grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_msginit,
-};
-
+};
+
+static const upb_msglayout *const grpc_gcp_ServerHandshakeParameters_submsgs[1] = {
+ &grpc_gcp_Identity_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_ServerHandshakeParameters__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 3},
+ {2, UPB_SIZE(4, 8), 0, 0, 11, 3},
+};
+
+const upb_msglayout grpc_gcp_ServerHandshakeParameters_msginit = {
+ &grpc_gcp_ServerHandshakeParameters_submsgs[0],
+ &grpc_gcp_ServerHandshakeParameters__fields[0],
+ UPB_SIZE(8, 16), 2, false,
+};
+
+static const upb_msglayout *const grpc_gcp_StartServerHandshakeReq_submsgs[4] = {
+ &grpc_gcp_Endpoint_msginit,
+ &grpc_gcp_RpcProtocolVersions_msginit,
+ &grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_msginit,
+};
+
static const upb_msglayout_field grpc_gcp_StartServerHandshakeReq__fields[7] = {
{1, UPB_SIZE(24, 48), 0, 0, 9, 3},
{2, UPB_SIZE(28, 56), 0, 2, 11, _UPB_LABEL_MAP},
@@ -106,62 +106,62 @@ static const upb_msglayout_field grpc_gcp_StartServerHandshakeReq__fields[7] = {
{5, UPB_SIZE(16, 32), 0, 0, 11, 1},
{6, UPB_SIZE(20, 40), 0, 1, 11, 1},
{7, UPB_SIZE(0, 0), 0, 0, 13, 1},
-};
-
-const upb_msglayout grpc_gcp_StartServerHandshakeReq_msginit = {
- &grpc_gcp_StartServerHandshakeReq_submsgs[0],
- &grpc_gcp_StartServerHandshakeReq__fields[0],
+};
+
+const upb_msglayout grpc_gcp_StartServerHandshakeReq_msginit = {
+ &grpc_gcp_StartServerHandshakeReq_submsgs[0],
+ &grpc_gcp_StartServerHandshakeReq__fields[0],
UPB_SIZE(32, 64), 7, false,
-};
-
-static const upb_msglayout *const grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_submsgs[1] = {
- &grpc_gcp_ServerHandshakeParameters_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 5, 1},
+};
+
+static const upb_msglayout *const grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_submsgs[1] = {
+ &grpc_gcp_ServerHandshakeParameters_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 5, 1},
{2, UPB_SIZE(8, 16), 0, 0, 11, 1},
-};
-
-const upb_msglayout grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_msginit = {
- &grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_submsgs[0],
- &grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry__fields[0],
+};
+
+const upb_msglayout grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_msginit = {
+ &grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_submsgs[0],
+ &grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry__fields[0],
UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout_field grpc_gcp_NextHandshakeMessageReq__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 12, 1},
-};
-
-const upb_msglayout grpc_gcp_NextHandshakeMessageReq_msginit = {
- NULL,
- &grpc_gcp_NextHandshakeMessageReq__fields[0],
- UPB_SIZE(8, 16), 1, false,
-};
-
-static const upb_msglayout *const grpc_gcp_HandshakerReq_submsgs[3] = {
- &grpc_gcp_NextHandshakeMessageReq_msginit,
- &grpc_gcp_StartClientHandshakeReq_msginit,
- &grpc_gcp_StartServerHandshakeReq_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_HandshakerReq__fields[3] = {
- {1, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
- {2, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 2, 11, 1},
- {3, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 11, 1},
-};
-
-const upb_msglayout grpc_gcp_HandshakerReq_msginit = {
- &grpc_gcp_HandshakerReq_submsgs[0],
- &grpc_gcp_HandshakerReq__fields[0],
- UPB_SIZE(8, 16), 3, false,
-};
-
-static const upb_msglayout *const grpc_gcp_HandshakerResult_submsgs[3] = {
- &grpc_gcp_Identity_msginit,
- &grpc_gcp_RpcProtocolVersions_msginit,
-};
-
+};
+
+static const upb_msglayout_field grpc_gcp_NextHandshakeMessageReq__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 12, 1},
+};
+
+const upb_msglayout grpc_gcp_NextHandshakeMessageReq_msginit = {
+ NULL,
+ &grpc_gcp_NextHandshakeMessageReq__fields[0],
+ UPB_SIZE(8, 16), 1, false,
+};
+
+static const upb_msglayout *const grpc_gcp_HandshakerReq_submsgs[3] = {
+ &grpc_gcp_NextHandshakeMessageReq_msginit,
+ &grpc_gcp_StartClientHandshakeReq_msginit,
+ &grpc_gcp_StartServerHandshakeReq_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_HandshakerReq__fields[3] = {
+ {1, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
+ {2, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 2, 11, 1},
+ {3, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 11, 1},
+};
+
+const upb_msglayout grpc_gcp_HandshakerReq_msginit = {
+ &grpc_gcp_HandshakerReq_submsgs[0],
+ &grpc_gcp_HandshakerReq__fields[0],
+ UPB_SIZE(8, 16), 3, false,
+};
+
+static const upb_msglayout *const grpc_gcp_HandshakerResult_submsgs[3] = {
+ &grpc_gcp_Identity_msginit,
+ &grpc_gcp_RpcProtocolVersions_msginit,
+};
+
static const upb_msglayout_field grpc_gcp_HandshakerResult__fields[8] = {
{1, UPB_SIZE(8, 8), 0, 0, 9, 1},
{2, UPB_SIZE(16, 24), 0, 0, 9, 1},
@@ -171,42 +171,42 @@ static const upb_msglayout_field grpc_gcp_HandshakerResult__fields[8] = {
{6, UPB_SIZE(4, 4), 0, 0, 8, 1},
{7, UPB_SIZE(40, 72), 0, 1, 11, 1},
{8, UPB_SIZE(0, 0), 0, 0, 13, 1},
-};
-
-const upb_msglayout grpc_gcp_HandshakerResult_msginit = {
- &grpc_gcp_HandshakerResult_submsgs[0],
- &grpc_gcp_HandshakerResult__fields[0],
+};
+
+const upb_msglayout grpc_gcp_HandshakerResult_msginit = {
+ &grpc_gcp_HandshakerResult_submsgs[0],
+ &grpc_gcp_HandshakerResult__fields[0],
UPB_SIZE(48, 80), 8, false,
-};
-
-static const upb_msglayout_field grpc_gcp_HandshakerStatus__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 13, 1},
- {2, UPB_SIZE(4, 8), 0, 0, 9, 1},
-};
-
-const upb_msglayout grpc_gcp_HandshakerStatus_msginit = {
- NULL,
- &grpc_gcp_HandshakerStatus__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const grpc_gcp_HandshakerResp_submsgs[2] = {
- &grpc_gcp_HandshakerResult_msginit,
- &grpc_gcp_HandshakerStatus_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_HandshakerResp__fields[4] = {
- {1, UPB_SIZE(4, 8), 0, 0, 12, 1},
- {2, UPB_SIZE(0, 0), 0, 0, 13, 1},
- {3, UPB_SIZE(12, 24), 0, 0, 11, 1},
- {4, UPB_SIZE(16, 32), 0, 1, 11, 1},
-};
-
-const upb_msglayout grpc_gcp_HandshakerResp_msginit = {
- &grpc_gcp_HandshakerResp_submsgs[0],
- &grpc_gcp_HandshakerResp__fields[0],
- UPB_SIZE(24, 48), 4, false,
-};
-
-#include "upb/port_undef.inc"
-
+};
+
+static const upb_msglayout_field grpc_gcp_HandshakerStatus__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 13, 1},
+ {2, UPB_SIZE(4, 8), 0, 0, 9, 1},
+};
+
+const upb_msglayout grpc_gcp_HandshakerStatus_msginit = {
+ NULL,
+ &grpc_gcp_HandshakerStatus__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const grpc_gcp_HandshakerResp_submsgs[2] = {
+ &grpc_gcp_HandshakerResult_msginit,
+ &grpc_gcp_HandshakerStatus_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_HandshakerResp__fields[4] = {
+ {1, UPB_SIZE(4, 8), 0, 0, 12, 1},
+ {2, UPB_SIZE(0, 0), 0, 0, 13, 1},
+ {3, UPB_SIZE(12, 24), 0, 0, 11, 1},
+ {4, UPB_SIZE(16, 32), 0, 1, 11, 1},
+};
+
+const upb_msglayout grpc_gcp_HandshakerResp_msginit = {
+ &grpc_gcp_HandshakerResp_submsgs[0],
+ &grpc_gcp_HandshakerResp__fields[0],
+ UPB_SIZE(24, 48), 4, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h
index 323f3cdbc6..dc6ad8c787 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h
@@ -1,176 +1,176 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/gcp/handshaker.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef SRC_PROTO_GRPC_GCP_HANDSHAKER_PROTO_UPB_H_
-#define SRC_PROTO_GRPC_GCP_HANDSHAKER_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct grpc_gcp_Endpoint;
-struct grpc_gcp_Identity;
-struct grpc_gcp_Identity_AttributesEntry;
-struct grpc_gcp_StartClientHandshakeReq;
-struct grpc_gcp_ServerHandshakeParameters;
-struct grpc_gcp_StartServerHandshakeReq;
-struct grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry;
-struct grpc_gcp_NextHandshakeMessageReq;
-struct grpc_gcp_HandshakerReq;
-struct grpc_gcp_HandshakerResult;
-struct grpc_gcp_HandshakerStatus;
-struct grpc_gcp_HandshakerResp;
-typedef struct grpc_gcp_Endpoint grpc_gcp_Endpoint;
-typedef struct grpc_gcp_Identity grpc_gcp_Identity;
-typedef struct grpc_gcp_Identity_AttributesEntry grpc_gcp_Identity_AttributesEntry;
-typedef struct grpc_gcp_StartClientHandshakeReq grpc_gcp_StartClientHandshakeReq;
-typedef struct grpc_gcp_ServerHandshakeParameters grpc_gcp_ServerHandshakeParameters;
-typedef struct grpc_gcp_StartServerHandshakeReq grpc_gcp_StartServerHandshakeReq;
-typedef struct grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry;
-typedef struct grpc_gcp_NextHandshakeMessageReq grpc_gcp_NextHandshakeMessageReq;
-typedef struct grpc_gcp_HandshakerReq grpc_gcp_HandshakerReq;
-typedef struct grpc_gcp_HandshakerResult grpc_gcp_HandshakerResult;
-typedef struct grpc_gcp_HandshakerStatus grpc_gcp_HandshakerStatus;
-typedef struct grpc_gcp_HandshakerResp grpc_gcp_HandshakerResp;
-extern const upb_msglayout grpc_gcp_Endpoint_msginit;
-extern const upb_msglayout grpc_gcp_Identity_msginit;
-extern const upb_msglayout grpc_gcp_Identity_AttributesEntry_msginit;
-extern const upb_msglayout grpc_gcp_StartClientHandshakeReq_msginit;
-extern const upb_msglayout grpc_gcp_ServerHandshakeParameters_msginit;
-extern const upb_msglayout grpc_gcp_StartServerHandshakeReq_msginit;
-extern const upb_msglayout grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_msginit;
-extern const upb_msglayout grpc_gcp_NextHandshakeMessageReq_msginit;
-extern const upb_msglayout grpc_gcp_HandshakerReq_msginit;
-extern const upb_msglayout grpc_gcp_HandshakerResult_msginit;
-extern const upb_msglayout grpc_gcp_HandshakerStatus_msginit;
-extern const upb_msglayout grpc_gcp_HandshakerResp_msginit;
-struct grpc_gcp_RpcProtocolVersions;
-extern const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit;
-
-typedef enum {
- grpc_gcp_HANDSHAKE_PROTOCOL_UNSPECIFIED = 0,
- grpc_gcp_TLS = 1,
- grpc_gcp_ALTS = 2
-} grpc_gcp_HandshakeProtocol;
-
-typedef enum {
- grpc_gcp_NETWORK_PROTOCOL_UNSPECIFIED = 0,
- grpc_gcp_TCP = 1,
- grpc_gcp_UDP = 2
-} grpc_gcp_NetworkProtocol;
-
-
-/* grpc.gcp.Endpoint */
-
-UPB_INLINE grpc_gcp_Endpoint *grpc_gcp_Endpoint_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/gcp/handshaker.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef SRC_PROTO_GRPC_GCP_HANDSHAKER_PROTO_UPB_H_
+#define SRC_PROTO_GRPC_GCP_HANDSHAKER_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct grpc_gcp_Endpoint;
+struct grpc_gcp_Identity;
+struct grpc_gcp_Identity_AttributesEntry;
+struct grpc_gcp_StartClientHandshakeReq;
+struct grpc_gcp_ServerHandshakeParameters;
+struct grpc_gcp_StartServerHandshakeReq;
+struct grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry;
+struct grpc_gcp_NextHandshakeMessageReq;
+struct grpc_gcp_HandshakerReq;
+struct grpc_gcp_HandshakerResult;
+struct grpc_gcp_HandshakerStatus;
+struct grpc_gcp_HandshakerResp;
+typedef struct grpc_gcp_Endpoint grpc_gcp_Endpoint;
+typedef struct grpc_gcp_Identity grpc_gcp_Identity;
+typedef struct grpc_gcp_Identity_AttributesEntry grpc_gcp_Identity_AttributesEntry;
+typedef struct grpc_gcp_StartClientHandshakeReq grpc_gcp_StartClientHandshakeReq;
+typedef struct grpc_gcp_ServerHandshakeParameters grpc_gcp_ServerHandshakeParameters;
+typedef struct grpc_gcp_StartServerHandshakeReq grpc_gcp_StartServerHandshakeReq;
+typedef struct grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry;
+typedef struct grpc_gcp_NextHandshakeMessageReq grpc_gcp_NextHandshakeMessageReq;
+typedef struct grpc_gcp_HandshakerReq grpc_gcp_HandshakerReq;
+typedef struct grpc_gcp_HandshakerResult grpc_gcp_HandshakerResult;
+typedef struct grpc_gcp_HandshakerStatus grpc_gcp_HandshakerStatus;
+typedef struct grpc_gcp_HandshakerResp grpc_gcp_HandshakerResp;
+extern const upb_msglayout grpc_gcp_Endpoint_msginit;
+extern const upb_msglayout grpc_gcp_Identity_msginit;
+extern const upb_msglayout grpc_gcp_Identity_AttributesEntry_msginit;
+extern const upb_msglayout grpc_gcp_StartClientHandshakeReq_msginit;
+extern const upb_msglayout grpc_gcp_ServerHandshakeParameters_msginit;
+extern const upb_msglayout grpc_gcp_StartServerHandshakeReq_msginit;
+extern const upb_msglayout grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_msginit;
+extern const upb_msglayout grpc_gcp_NextHandshakeMessageReq_msginit;
+extern const upb_msglayout grpc_gcp_HandshakerReq_msginit;
+extern const upb_msglayout grpc_gcp_HandshakerResult_msginit;
+extern const upb_msglayout grpc_gcp_HandshakerStatus_msginit;
+extern const upb_msglayout grpc_gcp_HandshakerResp_msginit;
+struct grpc_gcp_RpcProtocolVersions;
+extern const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit;
+
+typedef enum {
+ grpc_gcp_HANDSHAKE_PROTOCOL_UNSPECIFIED = 0,
+ grpc_gcp_TLS = 1,
+ grpc_gcp_ALTS = 2
+} grpc_gcp_HandshakeProtocol;
+
+typedef enum {
+ grpc_gcp_NETWORK_PROTOCOL_UNSPECIFIED = 0,
+ grpc_gcp_TCP = 1,
+ grpc_gcp_UDP = 2
+} grpc_gcp_NetworkProtocol;
+
+
+/* grpc.gcp.Endpoint */
+
+UPB_INLINE grpc_gcp_Endpoint *grpc_gcp_Endpoint_new(upb_arena *arena) {
return (grpc_gcp_Endpoint *)_upb_msg_new(&grpc_gcp_Endpoint_msginit, arena);
-}
-UPB_INLINE grpc_gcp_Endpoint *grpc_gcp_Endpoint_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_Endpoint *ret = grpc_gcp_Endpoint_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_Endpoint_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_Endpoint_serialize(const grpc_gcp_Endpoint *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_Endpoint_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_Endpoint *grpc_gcp_Endpoint_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_Endpoint *ret = grpc_gcp_Endpoint_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_Endpoint_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_Endpoint_serialize(const grpc_gcp_Endpoint *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_Endpoint_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_gcp_Endpoint_ip_address(const grpc_gcp_Endpoint *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview); }
UPB_INLINE int32_t grpc_gcp_Endpoint_port(const grpc_gcp_Endpoint *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE int32_t grpc_gcp_Endpoint_protocol(const grpc_gcp_Endpoint *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
-
-UPB_INLINE void grpc_gcp_Endpoint_set_ip_address(grpc_gcp_Endpoint *msg, upb_strview value) {
+
+UPB_INLINE void grpc_gcp_Endpoint_set_ip_address(grpc_gcp_Endpoint *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_Endpoint_set_port(grpc_gcp_Endpoint *msg, int32_t value) {
+}
+UPB_INLINE void grpc_gcp_Endpoint_set_port(grpc_gcp_Endpoint *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void grpc_gcp_Endpoint_set_protocol(grpc_gcp_Endpoint *msg, int32_t value) {
+}
+UPB_INLINE void grpc_gcp_Endpoint_set_protocol(grpc_gcp_Endpoint *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-
-/* grpc.gcp.Identity */
-
-UPB_INLINE grpc_gcp_Identity *grpc_gcp_Identity_new(upb_arena *arena) {
+}
+
+/* grpc.gcp.Identity */
+
+UPB_INLINE grpc_gcp_Identity *grpc_gcp_Identity_new(upb_arena *arena) {
return (grpc_gcp_Identity *)_upb_msg_new(&grpc_gcp_Identity_msginit, arena);
-}
-UPB_INLINE grpc_gcp_Identity *grpc_gcp_Identity_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_Identity *ret = grpc_gcp_Identity_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_Identity_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_Identity_serialize(const grpc_gcp_Identity *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_Identity_msginit, arena, len);
-}
-
-typedef enum {
- grpc_gcp_Identity_identity_oneof_service_account = 1,
- grpc_gcp_Identity_identity_oneof_hostname = 2,
- grpc_gcp_Identity_identity_oneof_NOT_SET = 0
-} grpc_gcp_Identity_identity_oneof_oneofcases;
+}
+UPB_INLINE grpc_gcp_Identity *grpc_gcp_Identity_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_Identity *ret = grpc_gcp_Identity_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_Identity_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_Identity_serialize(const grpc_gcp_Identity *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_Identity_msginit, arena, len);
+}
+
+typedef enum {
+ grpc_gcp_Identity_identity_oneof_service_account = 1,
+ grpc_gcp_Identity_identity_oneof_hostname = 2,
+ grpc_gcp_Identity_identity_oneof_NOT_SET = 0
+} grpc_gcp_Identity_identity_oneof_oneofcases;
UPB_INLINE grpc_gcp_Identity_identity_oneof_oneofcases grpc_gcp_Identity_identity_oneof_case(const grpc_gcp_Identity* msg) { return (grpc_gcp_Identity_identity_oneof_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(12, 24), int32_t); }
-
+
UPB_INLINE bool grpc_gcp_Identity_has_service_account(const grpc_gcp_Identity *msg) { return _upb_getoneofcase(msg, UPB_SIZE(12, 24)) == 1; }
-UPB_INLINE upb_strview grpc_gcp_Identity_service_account(const grpc_gcp_Identity *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), UPB_SIZE(12, 24), 1, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview grpc_gcp_Identity_service_account(const grpc_gcp_Identity *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), UPB_SIZE(12, 24), 1, upb_strview_make("", strlen(""))); }
UPB_INLINE bool grpc_gcp_Identity_has_hostname(const grpc_gcp_Identity *msg) { return _upb_getoneofcase(msg, UPB_SIZE(12, 24)) == 2; }
-UPB_INLINE upb_strview grpc_gcp_Identity_hostname(const grpc_gcp_Identity *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), UPB_SIZE(12, 24), 2, upb_strview_make("", strlen(""))); }
+UPB_INLINE upb_strview grpc_gcp_Identity_hostname(const grpc_gcp_Identity *msg) { return UPB_READ_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), UPB_SIZE(12, 24), 2, upb_strview_make("", strlen(""))); }
UPB_INLINE bool grpc_gcp_Identity_has_attributes(const grpc_gcp_Identity *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE size_t grpc_gcp_Identity_attributes_size(const grpc_gcp_Identity *msg) {return _upb_msg_map_size(msg, UPB_SIZE(0, 0)); }
UPB_INLINE bool grpc_gcp_Identity_attributes_get(const grpc_gcp_Identity *msg, upb_strview key, upb_strview *val) { return _upb_msg_map_get(msg, UPB_SIZE(0, 0), &key, 0, val, 0); }
UPB_INLINE const grpc_gcp_Identity_AttributesEntry* grpc_gcp_Identity_attributes_next(const grpc_gcp_Identity *msg, size_t* iter) { return (const grpc_gcp_Identity_AttributesEntry*)_upb_msg_map_next(msg, UPB_SIZE(0, 0), iter); }
-
-UPB_INLINE void grpc_gcp_Identity_set_service_account(grpc_gcp_Identity *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), value, UPB_SIZE(12, 24), 1);
-}
-UPB_INLINE void grpc_gcp_Identity_set_hostname(grpc_gcp_Identity *msg, upb_strview value) {
- UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), value, UPB_SIZE(12, 24), 2);
-}
+
+UPB_INLINE void grpc_gcp_Identity_set_service_account(grpc_gcp_Identity *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), value, UPB_SIZE(12, 24), 1);
+}
+UPB_INLINE void grpc_gcp_Identity_set_hostname(grpc_gcp_Identity *msg, upb_strview value) {
+ UPB_WRITE_ONEOF(msg, upb_strview, UPB_SIZE(4, 8), value, UPB_SIZE(12, 24), 2);
+}
UPB_INLINE void grpc_gcp_Identity_attributes_clear(grpc_gcp_Identity *msg) { _upb_msg_map_clear(msg, UPB_SIZE(0, 0)); }
UPB_INLINE bool grpc_gcp_Identity_attributes_set(grpc_gcp_Identity *msg, upb_strview key, upb_strview val, upb_arena *a) { return _upb_msg_map_set(msg, UPB_SIZE(0, 0), &key, 0, &val, 0, a); }
UPB_INLINE bool grpc_gcp_Identity_attributes_delete(grpc_gcp_Identity *msg, upb_strview key) { return _upb_msg_map_delete(msg, UPB_SIZE(0, 0), &key, 0); }
UPB_INLINE grpc_gcp_Identity_AttributesEntry* grpc_gcp_Identity_attributes_nextmutable(grpc_gcp_Identity *msg, size_t* iter) { return (grpc_gcp_Identity_AttributesEntry*)_upb_msg_map_next(msg, UPB_SIZE(0, 0), iter); }
-
-/* grpc.gcp.Identity.AttributesEntry */
-
+
+/* grpc.gcp.Identity.AttributesEntry */
+
UPB_INLINE upb_strview grpc_gcp_Identity_AttributesEntry_key(const grpc_gcp_Identity_AttributesEntry *msg) {
upb_strview ret;
_upb_msg_map_key(msg, &ret, 0);
return ret;
-}
+}
UPB_INLINE upb_strview grpc_gcp_Identity_AttributesEntry_value(const grpc_gcp_Identity_AttributesEntry *msg) {
upb_strview ret;
_upb_msg_map_value(msg, &ret, 0);
return ret;
-}
-
-UPB_INLINE void grpc_gcp_Identity_AttributesEntry_set_value(grpc_gcp_Identity_AttributesEntry *msg, upb_strview value) {
+}
+
+UPB_INLINE void grpc_gcp_Identity_AttributesEntry_set_value(grpc_gcp_Identity_AttributesEntry *msg, upb_strview value) {
_upb_msg_map_set_value(msg, &value, 0);
-}
-
-/* grpc.gcp.StartClientHandshakeReq */
-
-UPB_INLINE grpc_gcp_StartClientHandshakeReq *grpc_gcp_StartClientHandshakeReq_new(upb_arena *arena) {
+}
+
+/* grpc.gcp.StartClientHandshakeReq */
+
+UPB_INLINE grpc_gcp_StartClientHandshakeReq *grpc_gcp_StartClientHandshakeReq_new(upb_arena *arena) {
return (grpc_gcp_StartClientHandshakeReq *)_upb_msg_new(&grpc_gcp_StartClientHandshakeReq_msginit, arena);
-}
-UPB_INLINE grpc_gcp_StartClientHandshakeReq *grpc_gcp_StartClientHandshakeReq_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_StartClientHandshakeReq *ret = grpc_gcp_StartClientHandshakeReq_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_StartClientHandshakeReq_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_StartClientHandshakeReq_serialize(const grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_StartClientHandshakeReq_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_StartClientHandshakeReq *grpc_gcp_StartClientHandshakeReq_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_StartClientHandshakeReq *ret = grpc_gcp_StartClientHandshakeReq_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_StartClientHandshakeReq_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_StartClientHandshakeReq_serialize(const grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_StartClientHandshakeReq_msginit, arena, len);
+}
+
UPB_INLINE int32_t grpc_gcp_StartClientHandshakeReq_handshake_security_protocol(const grpc_gcp_StartClientHandshakeReq *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
UPB_INLINE upb_strview const* grpc_gcp_StartClientHandshakeReq_application_protocols(const grpc_gcp_StartClientHandshakeReq *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(36, 64), len); }
UPB_INLINE upb_strview const* grpc_gcp_StartClientHandshakeReq_record_protocols(const grpc_gcp_StartClientHandshakeReq *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(40, 72), len); }
@@ -186,154 +186,154 @@ UPB_INLINE upb_strview grpc_gcp_StartClientHandshakeReq_target_name(const grpc_g
UPB_INLINE bool grpc_gcp_StartClientHandshakeReq_has_rpc_versions(const grpc_gcp_StartClientHandshakeReq *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(32, 56)); }
UPB_INLINE const struct grpc_gcp_RpcProtocolVersions* grpc_gcp_StartClientHandshakeReq_rpc_versions(const grpc_gcp_StartClientHandshakeReq *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 56), const struct grpc_gcp_RpcProtocolVersions*); }
UPB_INLINE uint32_t grpc_gcp_StartClientHandshakeReq_max_frame_size(const grpc_gcp_StartClientHandshakeReq *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint32_t); }
-
-UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_handshake_security_protocol(grpc_gcp_StartClientHandshakeReq *msg, int32_t value) {
+
+UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_handshake_security_protocol(grpc_gcp_StartClientHandshakeReq *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_mutable_application_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t *len) {
+}
+UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_mutable_application_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 64), len);
-}
-UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_resize_application_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_resize_application_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(36, 64), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool grpc_gcp_StartClientHandshakeReq_add_application_protocols(grpc_gcp_StartClientHandshakeReq *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool grpc_gcp_StartClientHandshakeReq_add_application_protocols(grpc_gcp_StartClientHandshakeReq *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(36, 64), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_mutable_record_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t *len) {
+}
+UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_mutable_record_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 72), len);
-}
-UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_resize_record_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* grpc_gcp_StartClientHandshakeReq_resize_record_protocols(grpc_gcp_StartClientHandshakeReq *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(40, 72), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool grpc_gcp_StartClientHandshakeReq_add_record_protocols(grpc_gcp_StartClientHandshakeReq *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool grpc_gcp_StartClientHandshakeReq_add_record_protocols(grpc_gcp_StartClientHandshakeReq *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(40, 72), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE grpc_gcp_Identity** grpc_gcp_StartClientHandshakeReq_mutable_target_identities(grpc_gcp_StartClientHandshakeReq *msg, size_t *len) {
+}
+UPB_INLINE grpc_gcp_Identity** grpc_gcp_StartClientHandshakeReq_mutable_target_identities(grpc_gcp_StartClientHandshakeReq *msg, size_t *len) {
return (grpc_gcp_Identity**)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 80), len);
-}
-UPB_INLINE grpc_gcp_Identity** grpc_gcp_StartClientHandshakeReq_resize_target_identities(grpc_gcp_StartClientHandshakeReq *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE grpc_gcp_Identity** grpc_gcp_StartClientHandshakeReq_resize_target_identities(grpc_gcp_StartClientHandshakeReq *msg, size_t len, upb_arena *arena) {
return (grpc_gcp_Identity**)_upb_array_resize_accessor(msg, UPB_SIZE(44, 80), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_StartClientHandshakeReq_add_target_identities(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
+}
+UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_StartClientHandshakeReq_add_target_identities(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)_upb_msg_new(&grpc_gcp_Identity_msginit, arena);
- bool ok = _upb_array_append_accessor(
+ bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(44, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_local_identity(grpc_gcp_StartClientHandshakeReq *msg, grpc_gcp_Identity* value) {
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_local_identity(grpc_gcp_StartClientHandshakeReq *msg, grpc_gcp_Identity* value) {
*UPB_PTR_AT(msg, UPB_SIZE(20, 32), grpc_gcp_Identity*) = value;
-}
-UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_StartClientHandshakeReq_mutable_local_identity(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)grpc_gcp_StartClientHandshakeReq_local_identity(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_StartClientHandshakeReq_mutable_local_identity(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)grpc_gcp_StartClientHandshakeReq_local_identity(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Identity*)_upb_msg_new(&grpc_gcp_Identity_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartClientHandshakeReq_set_local_identity(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_local_endpoint(grpc_gcp_StartClientHandshakeReq *msg, grpc_gcp_Endpoint* value) {
+ if (!sub) return NULL;
+ grpc_gcp_StartClientHandshakeReq_set_local_identity(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_local_endpoint(grpc_gcp_StartClientHandshakeReq *msg, grpc_gcp_Endpoint* value) {
*UPB_PTR_AT(msg, UPB_SIZE(24, 40), grpc_gcp_Endpoint*) = value;
-}
-UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartClientHandshakeReq_mutable_local_endpoint(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartClientHandshakeReq_local_endpoint(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartClientHandshakeReq_mutable_local_endpoint(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartClientHandshakeReq_local_endpoint(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Endpoint*)_upb_msg_new(&grpc_gcp_Endpoint_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartClientHandshakeReq_set_local_endpoint(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_remote_endpoint(grpc_gcp_StartClientHandshakeReq *msg, grpc_gcp_Endpoint* value) {
+ if (!sub) return NULL;
+ grpc_gcp_StartClientHandshakeReq_set_local_endpoint(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_remote_endpoint(grpc_gcp_StartClientHandshakeReq *msg, grpc_gcp_Endpoint* value) {
*UPB_PTR_AT(msg, UPB_SIZE(28, 48), grpc_gcp_Endpoint*) = value;
-}
-UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartClientHandshakeReq_mutable_remote_endpoint(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartClientHandshakeReq_remote_endpoint(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartClientHandshakeReq_mutable_remote_endpoint(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartClientHandshakeReq_remote_endpoint(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Endpoint*)_upb_msg_new(&grpc_gcp_Endpoint_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartClientHandshakeReq_set_remote_endpoint(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_target_name(grpc_gcp_StartClientHandshakeReq *msg, upb_strview value) {
+ if (!sub) return NULL;
+ grpc_gcp_StartClientHandshakeReq_set_remote_endpoint(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_target_name(grpc_gcp_StartClientHandshakeReq *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_rpc_versions(grpc_gcp_StartClientHandshakeReq *msg, struct grpc_gcp_RpcProtocolVersions* value) {
+}
+UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_rpc_versions(grpc_gcp_StartClientHandshakeReq *msg, struct grpc_gcp_RpcProtocolVersions* value) {
*UPB_PTR_AT(msg, UPB_SIZE(32, 56), struct grpc_gcp_RpcProtocolVersions*) = value;
-}
-UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_StartClientHandshakeReq_mutable_rpc_versions(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_StartClientHandshakeReq_rpc_versions(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_StartClientHandshakeReq_mutable_rpc_versions(grpc_gcp_StartClientHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_StartClientHandshakeReq_rpc_versions(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_RpcProtocolVersions*)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartClientHandshakeReq_set_rpc_versions(msg, sub);
- }
- return sub;
-}
+ if (!sub) return NULL;
+ grpc_gcp_StartClientHandshakeReq_set_rpc_versions(msg, sub);
+ }
+ return sub;
+}
UPB_INLINE void grpc_gcp_StartClientHandshakeReq_set_max_frame_size(grpc_gcp_StartClientHandshakeReq *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint32_t) = value;
}
-
-/* grpc.gcp.ServerHandshakeParameters */
-
-UPB_INLINE grpc_gcp_ServerHandshakeParameters *grpc_gcp_ServerHandshakeParameters_new(upb_arena *arena) {
+
+/* grpc.gcp.ServerHandshakeParameters */
+
+UPB_INLINE grpc_gcp_ServerHandshakeParameters *grpc_gcp_ServerHandshakeParameters_new(upb_arena *arena) {
return (grpc_gcp_ServerHandshakeParameters *)_upb_msg_new(&grpc_gcp_ServerHandshakeParameters_msginit, arena);
-}
-UPB_INLINE grpc_gcp_ServerHandshakeParameters *grpc_gcp_ServerHandshakeParameters_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_ServerHandshakeParameters *ret = grpc_gcp_ServerHandshakeParameters_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_ServerHandshakeParameters_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_ServerHandshakeParameters_serialize(const grpc_gcp_ServerHandshakeParameters *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_ServerHandshakeParameters_msginit, arena, len);
-}
-
-UPB_INLINE upb_strview const* grpc_gcp_ServerHandshakeParameters_record_protocols(const grpc_gcp_ServerHandshakeParameters *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+}
+UPB_INLINE grpc_gcp_ServerHandshakeParameters *grpc_gcp_ServerHandshakeParameters_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_ServerHandshakeParameters *ret = grpc_gcp_ServerHandshakeParameters_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_ServerHandshakeParameters_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_ServerHandshakeParameters_serialize(const grpc_gcp_ServerHandshakeParameters *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_ServerHandshakeParameters_msginit, arena, len);
+}
+
+UPB_INLINE upb_strview const* grpc_gcp_ServerHandshakeParameters_record_protocols(const grpc_gcp_ServerHandshakeParameters *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE bool grpc_gcp_ServerHandshakeParameters_has_local_identities(const grpc_gcp_ServerHandshakeParameters *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
-UPB_INLINE const grpc_gcp_Identity* const* grpc_gcp_ServerHandshakeParameters_local_identities(const grpc_gcp_ServerHandshakeParameters *msg, size_t *len) { return (const grpc_gcp_Identity* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
-
-UPB_INLINE upb_strview* grpc_gcp_ServerHandshakeParameters_mutable_record_protocols(grpc_gcp_ServerHandshakeParameters *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE upb_strview* grpc_gcp_ServerHandshakeParameters_resize_record_protocols(grpc_gcp_ServerHandshakeParameters *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const grpc_gcp_Identity* const* grpc_gcp_ServerHandshakeParameters_local_identities(const grpc_gcp_ServerHandshakeParameters *msg, size_t *len) { return (const grpc_gcp_Identity* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
+
+UPB_INLINE upb_strview* grpc_gcp_ServerHandshakeParameters_mutable_record_protocols(grpc_gcp_ServerHandshakeParameters *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE upb_strview* grpc_gcp_ServerHandshakeParameters_resize_record_protocols(grpc_gcp_ServerHandshakeParameters *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool grpc_gcp_ServerHandshakeParameters_add_record_protocols(grpc_gcp_ServerHandshakeParameters *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool grpc_gcp_ServerHandshakeParameters_add_record_protocols(grpc_gcp_ServerHandshakeParameters *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(0, 0), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE grpc_gcp_Identity** grpc_gcp_ServerHandshakeParameters_mutable_local_identities(grpc_gcp_ServerHandshakeParameters *msg, size_t *len) {
- return (grpc_gcp_Identity**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
-}
-UPB_INLINE grpc_gcp_Identity** grpc_gcp_ServerHandshakeParameters_resize_local_identities(grpc_gcp_ServerHandshakeParameters *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE grpc_gcp_Identity** grpc_gcp_ServerHandshakeParameters_mutable_local_identities(grpc_gcp_ServerHandshakeParameters *msg, size_t *len) {
+ return (grpc_gcp_Identity**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
+}
+UPB_INLINE grpc_gcp_Identity** grpc_gcp_ServerHandshakeParameters_resize_local_identities(grpc_gcp_ServerHandshakeParameters *msg, size_t len, upb_arena *arena) {
return (grpc_gcp_Identity**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_ServerHandshakeParameters_add_local_identities(grpc_gcp_ServerHandshakeParameters *msg, upb_arena *arena) {
+}
+UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_ServerHandshakeParameters_add_local_identities(grpc_gcp_ServerHandshakeParameters *msg, upb_arena *arena) {
struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)_upb_msg_new(&grpc_gcp_Identity_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* grpc.gcp.StartServerHandshakeReq */
-
-UPB_INLINE grpc_gcp_StartServerHandshakeReq *grpc_gcp_StartServerHandshakeReq_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* grpc.gcp.StartServerHandshakeReq */
+
+UPB_INLINE grpc_gcp_StartServerHandshakeReq *grpc_gcp_StartServerHandshakeReq_new(upb_arena *arena) {
return (grpc_gcp_StartServerHandshakeReq *)_upb_msg_new(&grpc_gcp_StartServerHandshakeReq_msginit, arena);
-}
-UPB_INLINE grpc_gcp_StartServerHandshakeReq *grpc_gcp_StartServerHandshakeReq_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_StartServerHandshakeReq *ret = grpc_gcp_StartServerHandshakeReq_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_StartServerHandshakeReq_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_StartServerHandshakeReq_serialize(const grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_StartServerHandshakeReq_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_StartServerHandshakeReq *grpc_gcp_StartServerHandshakeReq_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_StartServerHandshakeReq *ret = grpc_gcp_StartServerHandshakeReq_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_StartServerHandshakeReq_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_StartServerHandshakeReq_serialize(const grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_StartServerHandshakeReq_msginit, arena, len);
+}
+
UPB_INLINE upb_strview const* grpc_gcp_StartServerHandshakeReq_application_protocols(const grpc_gcp_StartServerHandshakeReq *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_has_handshake_parameters(const grpc_gcp_StartServerHandshakeReq *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 56)); }
UPB_INLINE size_t grpc_gcp_StartServerHandshakeReq_handshake_parameters_size(const grpc_gcp_StartServerHandshakeReq *msg) {return _upb_msg_map_size(msg, UPB_SIZE(28, 56)); }
@@ -347,182 +347,182 @@ UPB_INLINE const grpc_gcp_Endpoint* grpc_gcp_StartServerHandshakeReq_remote_endp
UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_has_rpc_versions(const grpc_gcp_StartServerHandshakeReq *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
UPB_INLINE const struct grpc_gcp_RpcProtocolVersions* grpc_gcp_StartServerHandshakeReq_rpc_versions(const grpc_gcp_StartServerHandshakeReq *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), const struct grpc_gcp_RpcProtocolVersions*); }
UPB_INLINE uint32_t grpc_gcp_StartServerHandshakeReq_max_frame_size(const grpc_gcp_StartServerHandshakeReq *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t); }
-
-UPB_INLINE upb_strview* grpc_gcp_StartServerHandshakeReq_mutable_application_protocols(grpc_gcp_StartServerHandshakeReq *msg, size_t *len) {
+
+UPB_INLINE upb_strview* grpc_gcp_StartServerHandshakeReq_mutable_application_protocols(grpc_gcp_StartServerHandshakeReq *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
-}
-UPB_INLINE upb_strview* grpc_gcp_StartServerHandshakeReq_resize_application_protocols(grpc_gcp_StartServerHandshakeReq *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* grpc_gcp_StartServerHandshakeReq_resize_application_protocols(grpc_gcp_StartServerHandshakeReq *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_add_application_protocols(grpc_gcp_StartServerHandshakeReq *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_add_application_protocols(grpc_gcp_StartServerHandshakeReq *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
+}
UPB_INLINE void grpc_gcp_StartServerHandshakeReq_handshake_parameters_clear(grpc_gcp_StartServerHandshakeReq *msg) { _upb_msg_map_clear(msg, UPB_SIZE(28, 56)); }
UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_handshake_parameters_set(grpc_gcp_StartServerHandshakeReq *msg, int32_t key, grpc_gcp_ServerHandshakeParameters* val, upb_arena *a) { return _upb_msg_map_set(msg, UPB_SIZE(28, 56), &key, sizeof(key), &val, sizeof(val), a); }
UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_handshake_parameters_delete(grpc_gcp_StartServerHandshakeReq *msg, int32_t key) { return _upb_msg_map_delete(msg, UPB_SIZE(28, 56), &key, sizeof(key)); }
UPB_INLINE grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry* grpc_gcp_StartServerHandshakeReq_handshake_parameters_nextmutable(grpc_gcp_StartServerHandshakeReq *msg, size_t* iter) { return (grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry*)_upb_msg_map_next(msg, UPB_SIZE(28, 56), iter); }
-UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_in_bytes(grpc_gcp_StartServerHandshakeReq *msg, upb_strview value) {
+UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_in_bytes(grpc_gcp_StartServerHandshakeReq *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_local_endpoint(grpc_gcp_StartServerHandshakeReq *msg, grpc_gcp_Endpoint* value) {
+}
+UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_local_endpoint(grpc_gcp_StartServerHandshakeReq *msg, grpc_gcp_Endpoint* value) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), grpc_gcp_Endpoint*) = value;
-}
-UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartServerHandshakeReq_mutable_local_endpoint(grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartServerHandshakeReq_local_endpoint(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartServerHandshakeReq_mutable_local_endpoint(grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartServerHandshakeReq_local_endpoint(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Endpoint*)_upb_msg_new(&grpc_gcp_Endpoint_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartServerHandshakeReq_set_local_endpoint(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_remote_endpoint(grpc_gcp_StartServerHandshakeReq *msg, grpc_gcp_Endpoint* value) {
+ if (!sub) return NULL;
+ grpc_gcp_StartServerHandshakeReq_set_local_endpoint(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_remote_endpoint(grpc_gcp_StartServerHandshakeReq *msg, grpc_gcp_Endpoint* value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 32), grpc_gcp_Endpoint*) = value;
-}
-UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartServerHandshakeReq_mutable_remote_endpoint(grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartServerHandshakeReq_remote_endpoint(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Endpoint* grpc_gcp_StartServerHandshakeReq_mutable_remote_endpoint(grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_Endpoint* sub = (struct grpc_gcp_Endpoint*)grpc_gcp_StartServerHandshakeReq_remote_endpoint(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Endpoint*)_upb_msg_new(&grpc_gcp_Endpoint_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartServerHandshakeReq_set_remote_endpoint(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_rpc_versions(grpc_gcp_StartServerHandshakeReq *msg, struct grpc_gcp_RpcProtocolVersions* value) {
+ if (!sub) return NULL;
+ grpc_gcp_StartServerHandshakeReq_set_remote_endpoint(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_rpc_versions(grpc_gcp_StartServerHandshakeReq *msg, struct grpc_gcp_RpcProtocolVersions* value) {
*UPB_PTR_AT(msg, UPB_SIZE(20, 40), struct grpc_gcp_RpcProtocolVersions*) = value;
-}
-UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_StartServerHandshakeReq_mutable_rpc_versions(grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena) {
- struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_StartServerHandshakeReq_rpc_versions(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_StartServerHandshakeReq_mutable_rpc_versions(grpc_gcp_StartServerHandshakeReq *msg, upb_arena *arena) {
+ struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_StartServerHandshakeReq_rpc_versions(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_RpcProtocolVersions*)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_StartServerHandshakeReq_set_rpc_versions(msg, sub);
- }
- return sub;
-}
+ if (!sub) return NULL;
+ grpc_gcp_StartServerHandshakeReq_set_rpc_versions(msg, sub);
+ }
+ return sub;
+}
UPB_INLINE void grpc_gcp_StartServerHandshakeReq_set_max_frame_size(grpc_gcp_StartServerHandshakeReq *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
}
-
-/* grpc.gcp.StartServerHandshakeReq.HandshakeParametersEntry */
-
+
+/* grpc.gcp.StartServerHandshakeReq.HandshakeParametersEntry */
+
UPB_INLINE int32_t grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_key(const grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry *msg) {
int32_t ret;
_upb_msg_map_key(msg, &ret, sizeof(ret));
return ret;
-}
+}
UPB_INLINE bool grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_has_value(const grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 16)); }
UPB_INLINE const grpc_gcp_ServerHandshakeParameters* grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_value(const grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry *msg) {
grpc_gcp_ServerHandshakeParameters* ret;
_upb_msg_map_value(msg, &ret, sizeof(ret));
return ret;
-}
-
-UPB_INLINE void grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_set_value(grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry *msg, grpc_gcp_ServerHandshakeParameters* value) {
+}
+
+UPB_INLINE void grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_set_value(grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry *msg, grpc_gcp_ServerHandshakeParameters* value) {
_upb_msg_map_set_value(msg, &value, sizeof(grpc_gcp_ServerHandshakeParameters*));
-}
-
-/* grpc.gcp.NextHandshakeMessageReq */
-
-UPB_INLINE grpc_gcp_NextHandshakeMessageReq *grpc_gcp_NextHandshakeMessageReq_new(upb_arena *arena) {
+}
+
+/* grpc.gcp.NextHandshakeMessageReq */
+
+UPB_INLINE grpc_gcp_NextHandshakeMessageReq *grpc_gcp_NextHandshakeMessageReq_new(upb_arena *arena) {
return (grpc_gcp_NextHandshakeMessageReq *)_upb_msg_new(&grpc_gcp_NextHandshakeMessageReq_msginit, arena);
-}
-UPB_INLINE grpc_gcp_NextHandshakeMessageReq *grpc_gcp_NextHandshakeMessageReq_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_NextHandshakeMessageReq *ret = grpc_gcp_NextHandshakeMessageReq_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_NextHandshakeMessageReq_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_NextHandshakeMessageReq_serialize(const grpc_gcp_NextHandshakeMessageReq *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_NextHandshakeMessageReq_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_NextHandshakeMessageReq *grpc_gcp_NextHandshakeMessageReq_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_NextHandshakeMessageReq *ret = grpc_gcp_NextHandshakeMessageReq_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_NextHandshakeMessageReq_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_NextHandshakeMessageReq_serialize(const grpc_gcp_NextHandshakeMessageReq *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_NextHandshakeMessageReq_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_gcp_NextHandshakeMessageReq_in_bytes(const grpc_gcp_NextHandshakeMessageReq *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
-
-UPB_INLINE void grpc_gcp_NextHandshakeMessageReq_set_in_bytes(grpc_gcp_NextHandshakeMessageReq *msg, upb_strview value) {
+
+UPB_INLINE void grpc_gcp_NextHandshakeMessageReq_set_in_bytes(grpc_gcp_NextHandshakeMessageReq *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-
-/* grpc.gcp.HandshakerReq */
-
-UPB_INLINE grpc_gcp_HandshakerReq *grpc_gcp_HandshakerReq_new(upb_arena *arena) {
+}
+
+/* grpc.gcp.HandshakerReq */
+
+UPB_INLINE grpc_gcp_HandshakerReq *grpc_gcp_HandshakerReq_new(upb_arena *arena) {
return (grpc_gcp_HandshakerReq *)_upb_msg_new(&grpc_gcp_HandshakerReq_msginit, arena);
-}
-UPB_INLINE grpc_gcp_HandshakerReq *grpc_gcp_HandshakerReq_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_HandshakerReq *ret = grpc_gcp_HandshakerReq_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerReq_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_HandshakerReq_serialize(const grpc_gcp_HandshakerReq *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_HandshakerReq_msginit, arena, len);
-}
-
-typedef enum {
- grpc_gcp_HandshakerReq_req_oneof_client_start = 1,
- grpc_gcp_HandshakerReq_req_oneof_server_start = 2,
- grpc_gcp_HandshakerReq_req_oneof_next = 3,
- grpc_gcp_HandshakerReq_req_oneof_NOT_SET = 0
-} grpc_gcp_HandshakerReq_req_oneof_oneofcases;
+}
+UPB_INLINE grpc_gcp_HandshakerReq *grpc_gcp_HandshakerReq_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_HandshakerReq *ret = grpc_gcp_HandshakerReq_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerReq_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_HandshakerReq_serialize(const grpc_gcp_HandshakerReq *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_HandshakerReq_msginit, arena, len);
+}
+
+typedef enum {
+ grpc_gcp_HandshakerReq_req_oneof_client_start = 1,
+ grpc_gcp_HandshakerReq_req_oneof_server_start = 2,
+ grpc_gcp_HandshakerReq_req_oneof_next = 3,
+ grpc_gcp_HandshakerReq_req_oneof_NOT_SET = 0
+} grpc_gcp_HandshakerReq_req_oneof_oneofcases;
UPB_INLINE grpc_gcp_HandshakerReq_req_oneof_oneofcases grpc_gcp_HandshakerReq_req_oneof_case(const grpc_gcp_HandshakerReq* msg) { return (grpc_gcp_HandshakerReq_req_oneof_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(4, 8), int32_t); }
-
+
UPB_INLINE bool grpc_gcp_HandshakerReq_has_client_start(const grpc_gcp_HandshakerReq *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 1; }
-UPB_INLINE const grpc_gcp_StartClientHandshakeReq* grpc_gcp_HandshakerReq_client_start(const grpc_gcp_HandshakerReq *msg) { return UPB_READ_ONEOF(msg, const grpc_gcp_StartClientHandshakeReq*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 1, NULL); }
+UPB_INLINE const grpc_gcp_StartClientHandshakeReq* grpc_gcp_HandshakerReq_client_start(const grpc_gcp_HandshakerReq *msg) { return UPB_READ_ONEOF(msg, const grpc_gcp_StartClientHandshakeReq*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 1, NULL); }
UPB_INLINE bool grpc_gcp_HandshakerReq_has_server_start(const grpc_gcp_HandshakerReq *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 2; }
-UPB_INLINE const grpc_gcp_StartServerHandshakeReq* grpc_gcp_HandshakerReq_server_start(const grpc_gcp_HandshakerReq *msg) { return UPB_READ_ONEOF(msg, const grpc_gcp_StartServerHandshakeReq*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 2, NULL); }
+UPB_INLINE const grpc_gcp_StartServerHandshakeReq* grpc_gcp_HandshakerReq_server_start(const grpc_gcp_HandshakerReq *msg) { return UPB_READ_ONEOF(msg, const grpc_gcp_StartServerHandshakeReq*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 2, NULL); }
UPB_INLINE bool grpc_gcp_HandshakerReq_has_next(const grpc_gcp_HandshakerReq *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 3; }
-UPB_INLINE const grpc_gcp_NextHandshakeMessageReq* grpc_gcp_HandshakerReq_next(const grpc_gcp_HandshakerReq *msg) { return UPB_READ_ONEOF(msg, const grpc_gcp_NextHandshakeMessageReq*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 3, NULL); }
-
-UPB_INLINE void grpc_gcp_HandshakerReq_set_client_start(grpc_gcp_HandshakerReq *msg, grpc_gcp_StartClientHandshakeReq* value) {
- UPB_WRITE_ONEOF(msg, grpc_gcp_StartClientHandshakeReq*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 1);
-}
-UPB_INLINE struct grpc_gcp_StartClientHandshakeReq* grpc_gcp_HandshakerReq_mutable_client_start(grpc_gcp_HandshakerReq *msg, upb_arena *arena) {
- struct grpc_gcp_StartClientHandshakeReq* sub = (struct grpc_gcp_StartClientHandshakeReq*)grpc_gcp_HandshakerReq_client_start(msg);
- if (sub == NULL) {
+UPB_INLINE const grpc_gcp_NextHandshakeMessageReq* grpc_gcp_HandshakerReq_next(const grpc_gcp_HandshakerReq *msg) { return UPB_READ_ONEOF(msg, const grpc_gcp_NextHandshakeMessageReq*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 3, NULL); }
+
+UPB_INLINE void grpc_gcp_HandshakerReq_set_client_start(grpc_gcp_HandshakerReq *msg, grpc_gcp_StartClientHandshakeReq* value) {
+ UPB_WRITE_ONEOF(msg, grpc_gcp_StartClientHandshakeReq*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 1);
+}
+UPB_INLINE struct grpc_gcp_StartClientHandshakeReq* grpc_gcp_HandshakerReq_mutable_client_start(grpc_gcp_HandshakerReq *msg, upb_arena *arena) {
+ struct grpc_gcp_StartClientHandshakeReq* sub = (struct grpc_gcp_StartClientHandshakeReq*)grpc_gcp_HandshakerReq_client_start(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_StartClientHandshakeReq*)_upb_msg_new(&grpc_gcp_StartClientHandshakeReq_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerReq_set_client_start(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_HandshakerReq_set_server_start(grpc_gcp_HandshakerReq *msg, grpc_gcp_StartServerHandshakeReq* value) {
- UPB_WRITE_ONEOF(msg, grpc_gcp_StartServerHandshakeReq*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 2);
-}
-UPB_INLINE struct grpc_gcp_StartServerHandshakeReq* grpc_gcp_HandshakerReq_mutable_server_start(grpc_gcp_HandshakerReq *msg, upb_arena *arena) {
- struct grpc_gcp_StartServerHandshakeReq* sub = (struct grpc_gcp_StartServerHandshakeReq*)grpc_gcp_HandshakerReq_server_start(msg);
- if (sub == NULL) {
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerReq_set_client_start(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_HandshakerReq_set_server_start(grpc_gcp_HandshakerReq *msg, grpc_gcp_StartServerHandshakeReq* value) {
+ UPB_WRITE_ONEOF(msg, grpc_gcp_StartServerHandshakeReq*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 2);
+}
+UPB_INLINE struct grpc_gcp_StartServerHandshakeReq* grpc_gcp_HandshakerReq_mutable_server_start(grpc_gcp_HandshakerReq *msg, upb_arena *arena) {
+ struct grpc_gcp_StartServerHandshakeReq* sub = (struct grpc_gcp_StartServerHandshakeReq*)grpc_gcp_HandshakerReq_server_start(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_StartServerHandshakeReq*)_upb_msg_new(&grpc_gcp_StartServerHandshakeReq_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerReq_set_server_start(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_HandshakerReq_set_next(grpc_gcp_HandshakerReq *msg, grpc_gcp_NextHandshakeMessageReq* value) {
- UPB_WRITE_ONEOF(msg, grpc_gcp_NextHandshakeMessageReq*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 3);
-}
-UPB_INLINE struct grpc_gcp_NextHandshakeMessageReq* grpc_gcp_HandshakerReq_mutable_next(grpc_gcp_HandshakerReq *msg, upb_arena *arena) {
- struct grpc_gcp_NextHandshakeMessageReq* sub = (struct grpc_gcp_NextHandshakeMessageReq*)grpc_gcp_HandshakerReq_next(msg);
- if (sub == NULL) {
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerReq_set_server_start(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_HandshakerReq_set_next(grpc_gcp_HandshakerReq *msg, grpc_gcp_NextHandshakeMessageReq* value) {
+ UPB_WRITE_ONEOF(msg, grpc_gcp_NextHandshakeMessageReq*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 3);
+}
+UPB_INLINE struct grpc_gcp_NextHandshakeMessageReq* grpc_gcp_HandshakerReq_mutable_next(grpc_gcp_HandshakerReq *msg, upb_arena *arena) {
+ struct grpc_gcp_NextHandshakeMessageReq* sub = (struct grpc_gcp_NextHandshakeMessageReq*)grpc_gcp_HandshakerReq_next(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_NextHandshakeMessageReq*)_upb_msg_new(&grpc_gcp_NextHandshakeMessageReq_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerReq_set_next(msg, sub);
- }
- return sub;
-}
-
-/* grpc.gcp.HandshakerResult */
-
-UPB_INLINE grpc_gcp_HandshakerResult *grpc_gcp_HandshakerResult_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerReq_set_next(msg, sub);
+ }
+ return sub;
+}
+
+/* grpc.gcp.HandshakerResult */
+
+UPB_INLINE grpc_gcp_HandshakerResult *grpc_gcp_HandshakerResult_new(upb_arena *arena) {
return (grpc_gcp_HandshakerResult *)_upb_msg_new(&grpc_gcp_HandshakerResult_msginit, arena);
-}
-UPB_INLINE grpc_gcp_HandshakerResult *grpc_gcp_HandshakerResult_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_HandshakerResult *ret = grpc_gcp_HandshakerResult_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerResult_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_HandshakerResult_serialize(const grpc_gcp_HandshakerResult *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_HandshakerResult_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_HandshakerResult *grpc_gcp_HandshakerResult_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_HandshakerResult *ret = grpc_gcp_HandshakerResult_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerResult_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_HandshakerResult_serialize(const grpc_gcp_HandshakerResult *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_HandshakerResult_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_gcp_HandshakerResult_application_protocol(const grpc_gcp_HandshakerResult *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE upb_strview grpc_gcp_HandshakerResult_record_protocol(const grpc_gcp_HandshakerResult *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 24), upb_strview); }
UPB_INLINE upb_strview grpc_gcp_HandshakerResult_key_data(const grpc_gcp_HandshakerResult *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 40), upb_strview); }
@@ -534,139 +534,139 @@ UPB_INLINE bool grpc_gcp_HandshakerResult_keep_channel_open(const grpc_gcp_Hands
UPB_INLINE bool grpc_gcp_HandshakerResult_has_peer_rpc_versions(const grpc_gcp_HandshakerResult *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 72)); }
UPB_INLINE const struct grpc_gcp_RpcProtocolVersions* grpc_gcp_HandshakerResult_peer_rpc_versions(const grpc_gcp_HandshakerResult *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 72), const struct grpc_gcp_RpcProtocolVersions*); }
UPB_INLINE uint32_t grpc_gcp_HandshakerResult_max_frame_size(const grpc_gcp_HandshakerResult *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t); }
-
-UPB_INLINE void grpc_gcp_HandshakerResult_set_application_protocol(grpc_gcp_HandshakerResult *msg, upb_strview value) {
+
+UPB_INLINE void grpc_gcp_HandshakerResult_set_application_protocol(grpc_gcp_HandshakerResult *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerResult_set_record_protocol(grpc_gcp_HandshakerResult *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerResult_set_record_protocol(grpc_gcp_HandshakerResult *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 24), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerResult_set_key_data(grpc_gcp_HandshakerResult *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerResult_set_key_data(grpc_gcp_HandshakerResult *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(24, 40), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerResult_set_peer_identity(grpc_gcp_HandshakerResult *msg, grpc_gcp_Identity* value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerResult_set_peer_identity(grpc_gcp_HandshakerResult *msg, grpc_gcp_Identity* value) {
*UPB_PTR_AT(msg, UPB_SIZE(32, 56), grpc_gcp_Identity*) = value;
-}
-UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_HandshakerResult_mutable_peer_identity(grpc_gcp_HandshakerResult *msg, upb_arena *arena) {
- struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)grpc_gcp_HandshakerResult_peer_identity(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_HandshakerResult_mutable_peer_identity(grpc_gcp_HandshakerResult *msg, upb_arena *arena) {
+ struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)grpc_gcp_HandshakerResult_peer_identity(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Identity*)_upb_msg_new(&grpc_gcp_Identity_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerResult_set_peer_identity(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_HandshakerResult_set_local_identity(grpc_gcp_HandshakerResult *msg, grpc_gcp_Identity* value) {
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerResult_set_peer_identity(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_HandshakerResult_set_local_identity(grpc_gcp_HandshakerResult *msg, grpc_gcp_Identity* value) {
*UPB_PTR_AT(msg, UPB_SIZE(36, 64), grpc_gcp_Identity*) = value;
-}
-UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_HandshakerResult_mutable_local_identity(grpc_gcp_HandshakerResult *msg, upb_arena *arena) {
- struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)grpc_gcp_HandshakerResult_local_identity(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_Identity* grpc_gcp_HandshakerResult_mutable_local_identity(grpc_gcp_HandshakerResult *msg, upb_arena *arena) {
+ struct grpc_gcp_Identity* sub = (struct grpc_gcp_Identity*)grpc_gcp_HandshakerResult_local_identity(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_Identity*)_upb_msg_new(&grpc_gcp_Identity_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerResult_set_local_identity(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_HandshakerResult_set_keep_channel_open(grpc_gcp_HandshakerResult *msg, bool value) {
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerResult_set_local_identity(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_HandshakerResult_set_keep_channel_open(grpc_gcp_HandshakerResult *msg, bool value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerResult_set_peer_rpc_versions(grpc_gcp_HandshakerResult *msg, struct grpc_gcp_RpcProtocolVersions* value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerResult_set_peer_rpc_versions(grpc_gcp_HandshakerResult *msg, struct grpc_gcp_RpcProtocolVersions* value) {
*UPB_PTR_AT(msg, UPB_SIZE(40, 72), struct grpc_gcp_RpcProtocolVersions*) = value;
-}
-UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_HandshakerResult_mutable_peer_rpc_versions(grpc_gcp_HandshakerResult *msg, upb_arena *arena) {
- struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_HandshakerResult_peer_rpc_versions(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_RpcProtocolVersions* grpc_gcp_HandshakerResult_mutable_peer_rpc_versions(grpc_gcp_HandshakerResult *msg, upb_arena *arena) {
+ struct grpc_gcp_RpcProtocolVersions* sub = (struct grpc_gcp_RpcProtocolVersions*)grpc_gcp_HandshakerResult_peer_rpc_versions(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_RpcProtocolVersions*)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerResult_set_peer_rpc_versions(msg, sub);
- }
- return sub;
-}
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerResult_set_peer_rpc_versions(msg, sub);
+ }
+ return sub;
+}
UPB_INLINE void grpc_gcp_HandshakerResult_set_max_frame_size(grpc_gcp_HandshakerResult *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
}
-
-/* grpc.gcp.HandshakerStatus */
-
-UPB_INLINE grpc_gcp_HandshakerStatus *grpc_gcp_HandshakerStatus_new(upb_arena *arena) {
+
+/* grpc.gcp.HandshakerStatus */
+
+UPB_INLINE grpc_gcp_HandshakerStatus *grpc_gcp_HandshakerStatus_new(upb_arena *arena) {
return (grpc_gcp_HandshakerStatus *)_upb_msg_new(&grpc_gcp_HandshakerStatus_msginit, arena);
-}
-UPB_INLINE grpc_gcp_HandshakerStatus *grpc_gcp_HandshakerStatus_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_HandshakerStatus *ret = grpc_gcp_HandshakerStatus_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerStatus_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_HandshakerStatus_serialize(const grpc_gcp_HandshakerStatus *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_HandshakerStatus_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_HandshakerStatus *grpc_gcp_HandshakerStatus_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_HandshakerStatus *ret = grpc_gcp_HandshakerStatus_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerStatus_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_HandshakerStatus_serialize(const grpc_gcp_HandshakerStatus *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_HandshakerStatus_msginit, arena, len);
+}
+
UPB_INLINE uint32_t grpc_gcp_HandshakerStatus_code(const grpc_gcp_HandshakerStatus *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t); }
UPB_INLINE upb_strview grpc_gcp_HandshakerStatus_details(const grpc_gcp_HandshakerStatus *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
-
-UPB_INLINE void grpc_gcp_HandshakerStatus_set_code(grpc_gcp_HandshakerStatus *msg, uint32_t value) {
+
+UPB_INLINE void grpc_gcp_HandshakerStatus_set_code(grpc_gcp_HandshakerStatus *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerStatus_set_details(grpc_gcp_HandshakerStatus *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerStatus_set_details(grpc_gcp_HandshakerStatus *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-
-/* grpc.gcp.HandshakerResp */
-
-UPB_INLINE grpc_gcp_HandshakerResp *grpc_gcp_HandshakerResp_new(upb_arena *arena) {
+}
+
+/* grpc.gcp.HandshakerResp */
+
+UPB_INLINE grpc_gcp_HandshakerResp *grpc_gcp_HandshakerResp_new(upb_arena *arena) {
return (grpc_gcp_HandshakerResp *)_upb_msg_new(&grpc_gcp_HandshakerResp_msginit, arena);
-}
-UPB_INLINE grpc_gcp_HandshakerResp *grpc_gcp_HandshakerResp_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_HandshakerResp *ret = grpc_gcp_HandshakerResp_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerResp_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_HandshakerResp_serialize(const grpc_gcp_HandshakerResp *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_HandshakerResp_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_HandshakerResp *grpc_gcp_HandshakerResp_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_HandshakerResp *ret = grpc_gcp_HandshakerResp_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_HandshakerResp_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_HandshakerResp_serialize(const grpc_gcp_HandshakerResp *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_HandshakerResp_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_gcp_HandshakerResp_out_frames(const grpc_gcp_HandshakerResp *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE uint32_t grpc_gcp_HandshakerResp_bytes_consumed(const grpc_gcp_HandshakerResp *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t); }
UPB_INLINE bool grpc_gcp_HandshakerResp_has_result(const grpc_gcp_HandshakerResp *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(12, 24)); }
UPB_INLINE const grpc_gcp_HandshakerResult* grpc_gcp_HandshakerResp_result(const grpc_gcp_HandshakerResp *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const grpc_gcp_HandshakerResult*); }
UPB_INLINE bool grpc_gcp_HandshakerResp_has_status(const grpc_gcp_HandshakerResp *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const grpc_gcp_HandshakerStatus* grpc_gcp_HandshakerResp_status(const grpc_gcp_HandshakerResp *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 32), const grpc_gcp_HandshakerStatus*); }
-
-UPB_INLINE void grpc_gcp_HandshakerResp_set_out_frames(grpc_gcp_HandshakerResp *msg, upb_strview value) {
+
+UPB_INLINE void grpc_gcp_HandshakerResp_set_out_frames(grpc_gcp_HandshakerResp *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerResp_set_bytes_consumed(grpc_gcp_HandshakerResp *msg, uint32_t value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerResp_set_bytes_consumed(grpc_gcp_HandshakerResp *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
-}
-UPB_INLINE void grpc_gcp_HandshakerResp_set_result(grpc_gcp_HandshakerResp *msg, grpc_gcp_HandshakerResult* value) {
+}
+UPB_INLINE void grpc_gcp_HandshakerResp_set_result(grpc_gcp_HandshakerResp *msg, grpc_gcp_HandshakerResult* value) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), grpc_gcp_HandshakerResult*) = value;
-}
-UPB_INLINE struct grpc_gcp_HandshakerResult* grpc_gcp_HandshakerResp_mutable_result(grpc_gcp_HandshakerResp *msg, upb_arena *arena) {
- struct grpc_gcp_HandshakerResult* sub = (struct grpc_gcp_HandshakerResult*)grpc_gcp_HandshakerResp_result(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_HandshakerResult* grpc_gcp_HandshakerResp_mutable_result(grpc_gcp_HandshakerResp *msg, upb_arena *arena) {
+ struct grpc_gcp_HandshakerResult* sub = (struct grpc_gcp_HandshakerResult*)grpc_gcp_HandshakerResp_result(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_HandshakerResult*)_upb_msg_new(&grpc_gcp_HandshakerResult_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerResp_set_result(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_HandshakerResp_set_status(grpc_gcp_HandshakerResp *msg, grpc_gcp_HandshakerStatus* value) {
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerResp_set_result(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_HandshakerResp_set_status(grpc_gcp_HandshakerResp *msg, grpc_gcp_HandshakerStatus* value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 32), grpc_gcp_HandshakerStatus*) = value;
-}
-UPB_INLINE struct grpc_gcp_HandshakerStatus* grpc_gcp_HandshakerResp_mutable_status(grpc_gcp_HandshakerResp *msg, upb_arena *arena) {
- struct grpc_gcp_HandshakerStatus* sub = (struct grpc_gcp_HandshakerStatus*)grpc_gcp_HandshakerResp_status(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_HandshakerStatus* grpc_gcp_HandshakerResp_mutable_status(grpc_gcp_HandshakerResp *msg, upb_arena *arena) {
+ struct grpc_gcp_HandshakerStatus* sub = (struct grpc_gcp_HandshakerStatus*)grpc_gcp_HandshakerResp_status(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_HandshakerStatus*)_upb_msg_new(&grpc_gcp_HandshakerStatus_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_HandshakerResp_set_status(msg, sub);
- }
- return sub;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* SRC_PROTO_GRPC_GCP_HANDSHAKER_PROTO_UPB_H_ */
+ if (!sub) return NULL;
+ grpc_gcp_HandshakerResp_set_status(msg, sub);
+ }
+ return sub;
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* SRC_PROTO_GRPC_GCP_HANDSHAKER_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c
index 9b6303458e..9f50149044 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c
@@ -1,42 +1,42 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/gcp/transport_security_common.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "src/proto/grpc/gcp/transport_security_common.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const grpc_gcp_RpcProtocolVersions_submsgs[2] = {
- &grpc_gcp_RpcProtocolVersions_Version_msginit,
-};
-
-static const upb_msglayout_field grpc_gcp_RpcProtocolVersions__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 11, 1},
- {2, UPB_SIZE(4, 8), 0, 0, 11, 1},
-};
-
-const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit = {
- &grpc_gcp_RpcProtocolVersions_submsgs[0],
- &grpc_gcp_RpcProtocolVersions__fields[0],
- UPB_SIZE(8, 16), 2, false,
-};
-
-static const upb_msglayout_field grpc_gcp_RpcProtocolVersions_Version__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 13, 1},
- {2, UPB_SIZE(4, 4), 0, 0, 13, 1},
-};
-
-const upb_msglayout grpc_gcp_RpcProtocolVersions_Version_msginit = {
- NULL,
- &grpc_gcp_RpcProtocolVersions_Version__fields[0],
- UPB_SIZE(8, 8), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/gcp/transport_security_common.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "src/proto/grpc/gcp/transport_security_common.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const grpc_gcp_RpcProtocolVersions_submsgs[2] = {
+ &grpc_gcp_RpcProtocolVersions_Version_msginit,
+};
+
+static const upb_msglayout_field grpc_gcp_RpcProtocolVersions__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 11, 1},
+ {2, UPB_SIZE(4, 8), 0, 0, 11, 1},
+};
+
+const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit = {
+ &grpc_gcp_RpcProtocolVersions_submsgs[0],
+ &grpc_gcp_RpcProtocolVersions__fields[0],
+ UPB_SIZE(8, 16), 2, false,
+};
+
+static const upb_msglayout_field grpc_gcp_RpcProtocolVersions_Version__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 13, 1},
+ {2, UPB_SIZE(4, 4), 0, 0, 13, 1},
+};
+
+const upb_msglayout grpc_gcp_RpcProtocolVersions_Version_msginit = {
+ NULL,
+ &grpc_gcp_RpcProtocolVersions_Version__fields[0],
+ UPB_SIZE(8, 8), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h
index 5296398813..6e33b3a7d3 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h
@@ -1,110 +1,110 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/gcp/transport_security_common.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_
-#define SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct grpc_gcp_RpcProtocolVersions;
-struct grpc_gcp_RpcProtocolVersions_Version;
-typedef struct grpc_gcp_RpcProtocolVersions grpc_gcp_RpcProtocolVersions;
-typedef struct grpc_gcp_RpcProtocolVersions_Version grpc_gcp_RpcProtocolVersions_Version;
-extern const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit;
-extern const upb_msglayout grpc_gcp_RpcProtocolVersions_Version_msginit;
-
-typedef enum {
- grpc_gcp_SECURITY_NONE = 0,
- grpc_gcp_INTEGRITY_ONLY = 1,
- grpc_gcp_INTEGRITY_AND_PRIVACY = 2
-} grpc_gcp_SecurityLevel;
-
-
-/* grpc.gcp.RpcProtocolVersions */
-
-UPB_INLINE grpc_gcp_RpcProtocolVersions *grpc_gcp_RpcProtocolVersions_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/gcp/transport_security_common.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_
+#define SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct grpc_gcp_RpcProtocolVersions;
+struct grpc_gcp_RpcProtocolVersions_Version;
+typedef struct grpc_gcp_RpcProtocolVersions grpc_gcp_RpcProtocolVersions;
+typedef struct grpc_gcp_RpcProtocolVersions_Version grpc_gcp_RpcProtocolVersions_Version;
+extern const upb_msglayout grpc_gcp_RpcProtocolVersions_msginit;
+extern const upb_msglayout grpc_gcp_RpcProtocolVersions_Version_msginit;
+
+typedef enum {
+ grpc_gcp_SECURITY_NONE = 0,
+ grpc_gcp_INTEGRITY_ONLY = 1,
+ grpc_gcp_INTEGRITY_AND_PRIVACY = 2
+} grpc_gcp_SecurityLevel;
+
+
+/* grpc.gcp.RpcProtocolVersions */
+
+UPB_INLINE grpc_gcp_RpcProtocolVersions *grpc_gcp_RpcProtocolVersions_new(upb_arena *arena) {
return (grpc_gcp_RpcProtocolVersions *)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_msginit, arena);
-}
-UPB_INLINE grpc_gcp_RpcProtocolVersions *grpc_gcp_RpcProtocolVersions_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_RpcProtocolVersions *ret = grpc_gcp_RpcProtocolVersions_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_RpcProtocolVersions_serialize(const grpc_gcp_RpcProtocolVersions *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_RpcProtocolVersions_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_RpcProtocolVersions *grpc_gcp_RpcProtocolVersions_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_RpcProtocolVersions *ret = grpc_gcp_RpcProtocolVersions_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_RpcProtocolVersions_serialize(const grpc_gcp_RpcProtocolVersions *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_RpcProtocolVersions_msginit, arena, len);
+}
+
UPB_INLINE bool grpc_gcp_RpcProtocolVersions_has_max_rpc_version(const grpc_gcp_RpcProtocolVersions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_max_rpc_version(const grpc_gcp_RpcProtocolVersions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), const grpc_gcp_RpcProtocolVersions_Version*); }
UPB_INLINE bool grpc_gcp_RpcProtocolVersions_has_min_rpc_version(const grpc_gcp_RpcProtocolVersions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_min_rpc_version(const grpc_gcp_RpcProtocolVersions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const grpc_gcp_RpcProtocolVersions_Version*); }
-
-UPB_INLINE void grpc_gcp_RpcProtocolVersions_set_max_rpc_version(grpc_gcp_RpcProtocolVersions *msg, grpc_gcp_RpcProtocolVersions_Version* value) {
+
+UPB_INLINE void grpc_gcp_RpcProtocolVersions_set_max_rpc_version(grpc_gcp_RpcProtocolVersions *msg, grpc_gcp_RpcProtocolVersions_Version* value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), grpc_gcp_RpcProtocolVersions_Version*) = value;
-}
-UPB_INLINE struct grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_mutable_max_rpc_version(grpc_gcp_RpcProtocolVersions *msg, upb_arena *arena) {
- struct grpc_gcp_RpcProtocolVersions_Version* sub = (struct grpc_gcp_RpcProtocolVersions_Version*)grpc_gcp_RpcProtocolVersions_max_rpc_version(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_mutable_max_rpc_version(grpc_gcp_RpcProtocolVersions *msg, upb_arena *arena) {
+ struct grpc_gcp_RpcProtocolVersions_Version* sub = (struct grpc_gcp_RpcProtocolVersions_Version*)grpc_gcp_RpcProtocolVersions_max_rpc_version(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_RpcProtocolVersions_Version*)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_Version_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_RpcProtocolVersions_set_max_rpc_version(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_gcp_RpcProtocolVersions_set_min_rpc_version(grpc_gcp_RpcProtocolVersions *msg, grpc_gcp_RpcProtocolVersions_Version* value) {
+ if (!sub) return NULL;
+ grpc_gcp_RpcProtocolVersions_set_max_rpc_version(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_gcp_RpcProtocolVersions_set_min_rpc_version(grpc_gcp_RpcProtocolVersions *msg, grpc_gcp_RpcProtocolVersions_Version* value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), grpc_gcp_RpcProtocolVersions_Version*) = value;
-}
-UPB_INLINE struct grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_mutable_min_rpc_version(grpc_gcp_RpcProtocolVersions *msg, upb_arena *arena) {
- struct grpc_gcp_RpcProtocolVersions_Version* sub = (struct grpc_gcp_RpcProtocolVersions_Version*)grpc_gcp_RpcProtocolVersions_min_rpc_version(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct grpc_gcp_RpcProtocolVersions_Version* grpc_gcp_RpcProtocolVersions_mutable_min_rpc_version(grpc_gcp_RpcProtocolVersions *msg, upb_arena *arena) {
+ struct grpc_gcp_RpcProtocolVersions_Version* sub = (struct grpc_gcp_RpcProtocolVersions_Version*)grpc_gcp_RpcProtocolVersions_min_rpc_version(msg);
+ if (sub == NULL) {
sub = (struct grpc_gcp_RpcProtocolVersions_Version*)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_Version_msginit, arena);
- if (!sub) return NULL;
- grpc_gcp_RpcProtocolVersions_set_min_rpc_version(msg, sub);
- }
- return sub;
-}
-
-/* grpc.gcp.RpcProtocolVersions.Version */
-
-UPB_INLINE grpc_gcp_RpcProtocolVersions_Version *grpc_gcp_RpcProtocolVersions_Version_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ grpc_gcp_RpcProtocolVersions_set_min_rpc_version(msg, sub);
+ }
+ return sub;
+}
+
+/* grpc.gcp.RpcProtocolVersions.Version */
+
+UPB_INLINE grpc_gcp_RpcProtocolVersions_Version *grpc_gcp_RpcProtocolVersions_Version_new(upb_arena *arena) {
return (grpc_gcp_RpcProtocolVersions_Version *)_upb_msg_new(&grpc_gcp_RpcProtocolVersions_Version_msginit, arena);
-}
-UPB_INLINE grpc_gcp_RpcProtocolVersions_Version *grpc_gcp_RpcProtocolVersions_Version_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_gcp_RpcProtocolVersions_Version *ret = grpc_gcp_RpcProtocolVersions_Version_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_Version_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_gcp_RpcProtocolVersions_Version_serialize(const grpc_gcp_RpcProtocolVersions_Version *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_gcp_RpcProtocolVersions_Version_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_gcp_RpcProtocolVersions_Version *grpc_gcp_RpcProtocolVersions_Version_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_gcp_RpcProtocolVersions_Version *ret = grpc_gcp_RpcProtocolVersions_Version_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_gcp_RpcProtocolVersions_Version_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_gcp_RpcProtocolVersions_Version_serialize(const grpc_gcp_RpcProtocolVersions_Version *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_gcp_RpcProtocolVersions_Version_msginit, arena, len);
+}
+
UPB_INLINE uint32_t grpc_gcp_RpcProtocolVersions_Version_major(const grpc_gcp_RpcProtocolVersions_Version *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t); }
UPB_INLINE uint32_t grpc_gcp_RpcProtocolVersions_Version_minor(const grpc_gcp_RpcProtocolVersions_Version *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t); }
-
-UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_set_major(grpc_gcp_RpcProtocolVersions_Version *msg, uint32_t value) {
+
+UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_set_major(grpc_gcp_RpcProtocolVersions_Version *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), uint32_t) = value;
-}
-UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_set_minor(grpc_gcp_RpcProtocolVersions_Version *msg, uint32_t value) {
+}
+UPB_INLINE void grpc_gcp_RpcProtocolVersions_Version_set_minor(grpc_gcp_RpcProtocolVersions_Version *msg, uint32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* SRC_PROTO_GRPC_GCP_TRANSPORT_SECURITY_COMMON_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c
index 8a3359bb76..5f2f19de46 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c
@@ -1,36 +1,36 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/health/v1/health.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "src/proto/grpc/health/v1/health.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout_field grpc_health_v1_HealthCheckRequest__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
-};
-
-const upb_msglayout grpc_health_v1_HealthCheckRequest_msginit = {
- NULL,
- &grpc_health_v1_HealthCheckRequest__fields[0],
- UPB_SIZE(8, 16), 1, false,
-};
-
-static const upb_msglayout_field grpc_health_v1_HealthCheckResponse__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 14, 1},
-};
-
-const upb_msglayout grpc_health_v1_HealthCheckResponse_msginit = {
- NULL,
- &grpc_health_v1_HealthCheckResponse__fields[0],
- UPB_SIZE(8, 8), 1, false,
-};
-
-#include "upb/port_undef.inc"
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/health/v1/health.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "src/proto/grpc/health/v1/health.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout_field grpc_health_v1_HealthCheckRequest__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+};
+
+const upb_msglayout grpc_health_v1_HealthCheckRequest_msginit = {
+ NULL,
+ &grpc_health_v1_HealthCheckRequest__fields[0],
+ UPB_SIZE(8, 16), 1, false,
+};
+
+static const upb_msglayout_field grpc_health_v1_HealthCheckResponse__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 14, 1},
+};
+
+const upb_msglayout grpc_health_v1_HealthCheckResponse_msginit = {
+ NULL,
+ &grpc_health_v1_HealthCheckResponse__fields[0],
+ UPB_SIZE(8, 8), 1, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h
index d3f6471621..46811d172d 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h
@@ -1,83 +1,83 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/health/v1/health.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef SRC_PROTO_GRPC_HEALTH_V1_HEALTH_PROTO_UPB_H_
-#define SRC_PROTO_GRPC_HEALTH_V1_HEALTH_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct grpc_health_v1_HealthCheckRequest;
-struct grpc_health_v1_HealthCheckResponse;
-typedef struct grpc_health_v1_HealthCheckRequest grpc_health_v1_HealthCheckRequest;
-typedef struct grpc_health_v1_HealthCheckResponse grpc_health_v1_HealthCheckResponse;
-extern const upb_msglayout grpc_health_v1_HealthCheckRequest_msginit;
-extern const upb_msglayout grpc_health_v1_HealthCheckResponse_msginit;
-
-typedef enum {
- grpc_health_v1_HealthCheckResponse_UNKNOWN = 0,
- grpc_health_v1_HealthCheckResponse_SERVING = 1,
- grpc_health_v1_HealthCheckResponse_NOT_SERVING = 2,
- grpc_health_v1_HealthCheckResponse_SERVICE_UNKNOWN = 3
-} grpc_health_v1_HealthCheckResponse_ServingStatus;
-
-
-/* grpc.health.v1.HealthCheckRequest */
-
-UPB_INLINE grpc_health_v1_HealthCheckRequest *grpc_health_v1_HealthCheckRequest_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/health/v1/health.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef SRC_PROTO_GRPC_HEALTH_V1_HEALTH_PROTO_UPB_H_
+#define SRC_PROTO_GRPC_HEALTH_V1_HEALTH_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct grpc_health_v1_HealthCheckRequest;
+struct grpc_health_v1_HealthCheckResponse;
+typedef struct grpc_health_v1_HealthCheckRequest grpc_health_v1_HealthCheckRequest;
+typedef struct grpc_health_v1_HealthCheckResponse grpc_health_v1_HealthCheckResponse;
+extern const upb_msglayout grpc_health_v1_HealthCheckRequest_msginit;
+extern const upb_msglayout grpc_health_v1_HealthCheckResponse_msginit;
+
+typedef enum {
+ grpc_health_v1_HealthCheckResponse_UNKNOWN = 0,
+ grpc_health_v1_HealthCheckResponse_SERVING = 1,
+ grpc_health_v1_HealthCheckResponse_NOT_SERVING = 2,
+ grpc_health_v1_HealthCheckResponse_SERVICE_UNKNOWN = 3
+} grpc_health_v1_HealthCheckResponse_ServingStatus;
+
+
+/* grpc.health.v1.HealthCheckRequest */
+
+UPB_INLINE grpc_health_v1_HealthCheckRequest *grpc_health_v1_HealthCheckRequest_new(upb_arena *arena) {
return (grpc_health_v1_HealthCheckRequest *)_upb_msg_new(&grpc_health_v1_HealthCheckRequest_msginit, arena);
-}
-UPB_INLINE grpc_health_v1_HealthCheckRequest *grpc_health_v1_HealthCheckRequest_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_health_v1_HealthCheckRequest *ret = grpc_health_v1_HealthCheckRequest_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_health_v1_HealthCheckRequest_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_health_v1_HealthCheckRequest_serialize(const grpc_health_v1_HealthCheckRequest *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_health_v1_HealthCheckRequest_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_health_v1_HealthCheckRequest *grpc_health_v1_HealthCheckRequest_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_health_v1_HealthCheckRequest *ret = grpc_health_v1_HealthCheckRequest_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_health_v1_HealthCheckRequest_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_health_v1_HealthCheckRequest_serialize(const grpc_health_v1_HealthCheckRequest *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_health_v1_HealthCheckRequest_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_health_v1_HealthCheckRequest_service(const grpc_health_v1_HealthCheckRequest *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
-
-UPB_INLINE void grpc_health_v1_HealthCheckRequest_set_service(grpc_health_v1_HealthCheckRequest *msg, upb_strview value) {
+
+UPB_INLINE void grpc_health_v1_HealthCheckRequest_set_service(grpc_health_v1_HealthCheckRequest *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-
-/* grpc.health.v1.HealthCheckResponse */
-
-UPB_INLINE grpc_health_v1_HealthCheckResponse *grpc_health_v1_HealthCheckResponse_new(upb_arena *arena) {
+}
+
+/* grpc.health.v1.HealthCheckResponse */
+
+UPB_INLINE grpc_health_v1_HealthCheckResponse *grpc_health_v1_HealthCheckResponse_new(upb_arena *arena) {
return (grpc_health_v1_HealthCheckResponse *)_upb_msg_new(&grpc_health_v1_HealthCheckResponse_msginit, arena);
-}
-UPB_INLINE grpc_health_v1_HealthCheckResponse *grpc_health_v1_HealthCheckResponse_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_health_v1_HealthCheckResponse *ret = grpc_health_v1_HealthCheckResponse_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_health_v1_HealthCheckResponse_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_health_v1_HealthCheckResponse_serialize(const grpc_health_v1_HealthCheckResponse *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_health_v1_HealthCheckResponse_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_health_v1_HealthCheckResponse *grpc_health_v1_HealthCheckResponse_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_health_v1_HealthCheckResponse *ret = grpc_health_v1_HealthCheckResponse_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_health_v1_HealthCheckResponse_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_health_v1_HealthCheckResponse_serialize(const grpc_health_v1_HealthCheckResponse *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_health_v1_HealthCheckResponse_msginit, arena, len);
+}
+
UPB_INLINE int32_t grpc_health_v1_HealthCheckResponse_status(const grpc_health_v1_HealthCheckResponse *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
-
-UPB_INLINE void grpc_health_v1_HealthCheckResponse_set_status(grpc_health_v1_HealthCheckResponse *msg, int32_t value) {
+
+UPB_INLINE void grpc_health_v1_HealthCheckResponse_set_status(grpc_health_v1_HealthCheckResponse *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* SRC_PROTO_GRPC_HEALTH_V1_HEALTH_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* SRC_PROTO_GRPC_HEALTH_V1_HEALTH_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c
index 90b7cb7f62..30b967dad2 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c
@@ -1,141 +1,141 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/lb/v1/load_balancer.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "src/proto/grpc/lb/v1/load_balancer.upb.h"
-#include "google/protobuf/duration.upb.h"
-#include "google/protobuf/timestamp.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const grpc_lb_v1_LoadBalanceRequest_submsgs[2] = {
- &grpc_lb_v1_ClientStats_msginit,
- &grpc_lb_v1_InitialLoadBalanceRequest_msginit,
-};
-
-static const upb_msglayout_field grpc_lb_v1_LoadBalanceRequest__fields[2] = {
- {1, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
- {2, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 11, 1},
-};
-
-const upb_msglayout grpc_lb_v1_LoadBalanceRequest_msginit = {
- &grpc_lb_v1_LoadBalanceRequest_submsgs[0],
- &grpc_lb_v1_LoadBalanceRequest__fields[0],
- UPB_SIZE(8, 16), 2, false,
-};
-
-static const upb_msglayout_field grpc_lb_v1_InitialLoadBalanceRequest__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
-};
-
-const upb_msglayout grpc_lb_v1_InitialLoadBalanceRequest_msginit = {
- NULL,
- &grpc_lb_v1_InitialLoadBalanceRequest__fields[0],
- UPB_SIZE(8, 16), 1, false,
-};
-
-static const upb_msglayout_field grpc_lb_v1_ClientStatsPerToken__fields[2] = {
- {1, UPB_SIZE(8, 8), 0, 0, 9, 1},
- {2, UPB_SIZE(0, 0), 0, 0, 3, 1},
-};
-
-const upb_msglayout grpc_lb_v1_ClientStatsPerToken_msginit = {
- NULL,
- &grpc_lb_v1_ClientStatsPerToken__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const grpc_lb_v1_ClientStats_submsgs[2] = {
- &google_protobuf_Timestamp_msginit,
- &grpc_lb_v1_ClientStatsPerToken_msginit,
-};
-
-static const upb_msglayout_field grpc_lb_v1_ClientStats__fields[6] = {
- {1, UPB_SIZE(32, 32), 0, 0, 11, 1},
- {2, UPB_SIZE(0, 0), 0, 0, 3, 1},
- {3, UPB_SIZE(8, 8), 0, 0, 3, 1},
- {6, UPB_SIZE(16, 16), 0, 0, 3, 1},
- {7, UPB_SIZE(24, 24), 0, 0, 3, 1},
- {8, UPB_SIZE(36, 40), 0, 1, 11, 3},
-};
-
-const upb_msglayout grpc_lb_v1_ClientStats_msginit = {
- &grpc_lb_v1_ClientStats_submsgs[0],
- &grpc_lb_v1_ClientStats__fields[0],
- UPB_SIZE(40, 48), 6, false,
-};
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/lb/v1/load_balancer.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "src/proto/grpc/lb/v1/load_balancer.upb.h"
+#include "google/protobuf/duration.upb.h"
+#include "google/protobuf/timestamp.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const grpc_lb_v1_LoadBalanceRequest_submsgs[2] = {
+ &grpc_lb_v1_ClientStats_msginit,
+ &grpc_lb_v1_InitialLoadBalanceRequest_msginit,
+};
+
+static const upb_msglayout_field grpc_lb_v1_LoadBalanceRequest__fields[2] = {
+ {1, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
+ {2, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 11, 1},
+};
+
+const upb_msglayout grpc_lb_v1_LoadBalanceRequest_msginit = {
+ &grpc_lb_v1_LoadBalanceRequest_submsgs[0],
+ &grpc_lb_v1_LoadBalanceRequest__fields[0],
+ UPB_SIZE(8, 16), 2, false,
+};
+
+static const upb_msglayout_field grpc_lb_v1_InitialLoadBalanceRequest__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+};
+
+const upb_msglayout grpc_lb_v1_InitialLoadBalanceRequest_msginit = {
+ NULL,
+ &grpc_lb_v1_InitialLoadBalanceRequest__fields[0],
+ UPB_SIZE(8, 16), 1, false,
+};
+
+static const upb_msglayout_field grpc_lb_v1_ClientStatsPerToken__fields[2] = {
+ {1, UPB_SIZE(8, 8), 0, 0, 9, 1},
+ {2, UPB_SIZE(0, 0), 0, 0, 3, 1},
+};
+
+const upb_msglayout grpc_lb_v1_ClientStatsPerToken_msginit = {
+ NULL,
+ &grpc_lb_v1_ClientStatsPerToken__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const grpc_lb_v1_ClientStats_submsgs[2] = {
+ &google_protobuf_Timestamp_msginit,
+ &grpc_lb_v1_ClientStatsPerToken_msginit,
+};
+
+static const upb_msglayout_field grpc_lb_v1_ClientStats__fields[6] = {
+ {1, UPB_SIZE(32, 32), 0, 0, 11, 1},
+ {2, UPB_SIZE(0, 0), 0, 0, 3, 1},
+ {3, UPB_SIZE(8, 8), 0, 0, 3, 1},
+ {6, UPB_SIZE(16, 16), 0, 0, 3, 1},
+ {7, UPB_SIZE(24, 24), 0, 0, 3, 1},
+ {8, UPB_SIZE(36, 40), 0, 1, 11, 3},
+};
+
+const upb_msglayout grpc_lb_v1_ClientStats_msginit = {
+ &grpc_lb_v1_ClientStats_submsgs[0],
+ &grpc_lb_v1_ClientStats__fields[0],
+ UPB_SIZE(40, 48), 6, false,
+};
+
static const upb_msglayout *const grpc_lb_v1_LoadBalanceResponse_submsgs[3] = {
&grpc_lb_v1_FallbackResponse_msginit,
- &grpc_lb_v1_InitialLoadBalanceResponse_msginit,
- &grpc_lb_v1_ServerList_msginit,
-};
-
+ &grpc_lb_v1_InitialLoadBalanceResponse_msginit,
+ &grpc_lb_v1_ServerList_msginit,
+};
+
static const upb_msglayout_field grpc_lb_v1_LoadBalanceResponse__fields[3] = {
{1, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
{2, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 2, 11, 1},
{3, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 11, 1},
-};
-
-const upb_msglayout grpc_lb_v1_LoadBalanceResponse_msginit = {
- &grpc_lb_v1_LoadBalanceResponse_submsgs[0],
- &grpc_lb_v1_LoadBalanceResponse__fields[0],
+};
+
+const upb_msglayout grpc_lb_v1_LoadBalanceResponse_msginit = {
+ &grpc_lb_v1_LoadBalanceResponse_submsgs[0],
+ &grpc_lb_v1_LoadBalanceResponse__fields[0],
UPB_SIZE(8, 16), 3, false,
-};
-
-static const upb_msglayout *const grpc_lb_v1_InitialLoadBalanceResponse_submsgs[1] = {
- &google_protobuf_Duration_msginit,
-};
-
-static const upb_msglayout_field grpc_lb_v1_InitialLoadBalanceResponse__fields[2] = {
- {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
- {2, UPB_SIZE(8, 16), 0, 0, 11, 1},
-};
-
-const upb_msglayout grpc_lb_v1_InitialLoadBalanceResponse_msginit = {
- &grpc_lb_v1_InitialLoadBalanceResponse_submsgs[0],
- &grpc_lb_v1_InitialLoadBalanceResponse__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout *const grpc_lb_v1_ServerList_submsgs[1] = {
- &grpc_lb_v1_Server_msginit,
-};
-
-static const upb_msglayout_field grpc_lb_v1_ServerList__fields[1] = {
- {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
-};
-
-const upb_msglayout grpc_lb_v1_ServerList_msginit = {
- &grpc_lb_v1_ServerList_submsgs[0],
- &grpc_lb_v1_ServerList__fields[0],
- UPB_SIZE(4, 8), 1, false,
-};
-
-static const upb_msglayout_field grpc_lb_v1_Server__fields[4] = {
- {1, UPB_SIZE(8, 8), 0, 0, 12, 1},
- {2, UPB_SIZE(0, 0), 0, 0, 5, 1},
- {3, UPB_SIZE(16, 24), 0, 0, 9, 1},
- {4, UPB_SIZE(4, 4), 0, 0, 8, 1},
-};
-
-const upb_msglayout grpc_lb_v1_Server_msginit = {
- NULL,
- &grpc_lb_v1_Server__fields[0],
- UPB_SIZE(24, 48), 4, false,
-};
-
+};
+
+static const upb_msglayout *const grpc_lb_v1_InitialLoadBalanceResponse_submsgs[1] = {
+ &google_protobuf_Duration_msginit,
+};
+
+static const upb_msglayout_field grpc_lb_v1_InitialLoadBalanceResponse__fields[2] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
+ {2, UPB_SIZE(8, 16), 0, 0, 11, 1},
+};
+
+const upb_msglayout grpc_lb_v1_InitialLoadBalanceResponse_msginit = {
+ &grpc_lb_v1_InitialLoadBalanceResponse_submsgs[0],
+ &grpc_lb_v1_InitialLoadBalanceResponse__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout *const grpc_lb_v1_ServerList_submsgs[1] = {
+ &grpc_lb_v1_Server_msginit,
+};
+
+static const upb_msglayout_field grpc_lb_v1_ServerList__fields[1] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
+};
+
+const upb_msglayout grpc_lb_v1_ServerList_msginit = {
+ &grpc_lb_v1_ServerList_submsgs[0],
+ &grpc_lb_v1_ServerList__fields[0],
+ UPB_SIZE(4, 8), 1, false,
+};
+
+static const upb_msglayout_field grpc_lb_v1_Server__fields[4] = {
+ {1, UPB_SIZE(8, 8), 0, 0, 12, 1},
+ {2, UPB_SIZE(0, 0), 0, 0, 5, 1},
+ {3, UPB_SIZE(16, 24), 0, 0, 9, 1},
+ {4, UPB_SIZE(4, 4), 0, 0, 8, 1},
+};
+
+const upb_msglayout grpc_lb_v1_Server_msginit = {
+ NULL,
+ &grpc_lb_v1_Server__fields[0],
+ UPB_SIZE(24, 48), 4, false,
+};
+
const upb_msglayout grpc_lb_v1_FallbackResponse_msginit = {
NULL,
NULL,
UPB_SIZE(0, 0), 0, false,
};
-#include "upb/port_undef.inc"
-
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h
index 2ce5afca1c..ca997fb13b 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h
@@ -1,166 +1,166 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * src/proto/grpc/lb/v1/load_balancer.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef SRC_PROTO_GRPC_LB_V1_LOAD_BALANCER_PROTO_UPB_H_
-#define SRC_PROTO_GRPC_LB_V1_LOAD_BALANCER_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct grpc_lb_v1_LoadBalanceRequest;
-struct grpc_lb_v1_InitialLoadBalanceRequest;
-struct grpc_lb_v1_ClientStatsPerToken;
-struct grpc_lb_v1_ClientStats;
-struct grpc_lb_v1_LoadBalanceResponse;
-struct grpc_lb_v1_InitialLoadBalanceResponse;
-struct grpc_lb_v1_ServerList;
-struct grpc_lb_v1_Server;
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * src/proto/grpc/lb/v1/load_balancer.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef SRC_PROTO_GRPC_LB_V1_LOAD_BALANCER_PROTO_UPB_H_
+#define SRC_PROTO_GRPC_LB_V1_LOAD_BALANCER_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct grpc_lb_v1_LoadBalanceRequest;
+struct grpc_lb_v1_InitialLoadBalanceRequest;
+struct grpc_lb_v1_ClientStatsPerToken;
+struct grpc_lb_v1_ClientStats;
+struct grpc_lb_v1_LoadBalanceResponse;
+struct grpc_lb_v1_InitialLoadBalanceResponse;
+struct grpc_lb_v1_ServerList;
+struct grpc_lb_v1_Server;
struct grpc_lb_v1_FallbackResponse;
-typedef struct grpc_lb_v1_LoadBalanceRequest grpc_lb_v1_LoadBalanceRequest;
-typedef struct grpc_lb_v1_InitialLoadBalanceRequest grpc_lb_v1_InitialLoadBalanceRequest;
-typedef struct grpc_lb_v1_ClientStatsPerToken grpc_lb_v1_ClientStatsPerToken;
-typedef struct grpc_lb_v1_ClientStats grpc_lb_v1_ClientStats;
-typedef struct grpc_lb_v1_LoadBalanceResponse grpc_lb_v1_LoadBalanceResponse;
-typedef struct grpc_lb_v1_InitialLoadBalanceResponse grpc_lb_v1_InitialLoadBalanceResponse;
-typedef struct grpc_lb_v1_ServerList grpc_lb_v1_ServerList;
-typedef struct grpc_lb_v1_Server grpc_lb_v1_Server;
+typedef struct grpc_lb_v1_LoadBalanceRequest grpc_lb_v1_LoadBalanceRequest;
+typedef struct grpc_lb_v1_InitialLoadBalanceRequest grpc_lb_v1_InitialLoadBalanceRequest;
+typedef struct grpc_lb_v1_ClientStatsPerToken grpc_lb_v1_ClientStatsPerToken;
+typedef struct grpc_lb_v1_ClientStats grpc_lb_v1_ClientStats;
+typedef struct grpc_lb_v1_LoadBalanceResponse grpc_lb_v1_LoadBalanceResponse;
+typedef struct grpc_lb_v1_InitialLoadBalanceResponse grpc_lb_v1_InitialLoadBalanceResponse;
+typedef struct grpc_lb_v1_ServerList grpc_lb_v1_ServerList;
+typedef struct grpc_lb_v1_Server grpc_lb_v1_Server;
typedef struct grpc_lb_v1_FallbackResponse grpc_lb_v1_FallbackResponse;
-extern const upb_msglayout grpc_lb_v1_LoadBalanceRequest_msginit;
-extern const upb_msglayout grpc_lb_v1_InitialLoadBalanceRequest_msginit;
-extern const upb_msglayout grpc_lb_v1_ClientStatsPerToken_msginit;
-extern const upb_msglayout grpc_lb_v1_ClientStats_msginit;
-extern const upb_msglayout grpc_lb_v1_LoadBalanceResponse_msginit;
-extern const upb_msglayout grpc_lb_v1_InitialLoadBalanceResponse_msginit;
-extern const upb_msglayout grpc_lb_v1_ServerList_msginit;
-extern const upb_msglayout grpc_lb_v1_Server_msginit;
+extern const upb_msglayout grpc_lb_v1_LoadBalanceRequest_msginit;
+extern const upb_msglayout grpc_lb_v1_InitialLoadBalanceRequest_msginit;
+extern const upb_msglayout grpc_lb_v1_ClientStatsPerToken_msginit;
+extern const upb_msglayout grpc_lb_v1_ClientStats_msginit;
+extern const upb_msglayout grpc_lb_v1_LoadBalanceResponse_msginit;
+extern const upb_msglayout grpc_lb_v1_InitialLoadBalanceResponse_msginit;
+extern const upb_msglayout grpc_lb_v1_ServerList_msginit;
+extern const upb_msglayout grpc_lb_v1_Server_msginit;
extern const upb_msglayout grpc_lb_v1_FallbackResponse_msginit;
-struct google_protobuf_Duration;
-struct google_protobuf_Timestamp;
-extern const upb_msglayout google_protobuf_Duration_msginit;
-extern const upb_msglayout google_protobuf_Timestamp_msginit;
-
-
-/* grpc.lb.v1.LoadBalanceRequest */
-
-UPB_INLINE grpc_lb_v1_LoadBalanceRequest *grpc_lb_v1_LoadBalanceRequest_new(upb_arena *arena) {
+struct google_protobuf_Duration;
+struct google_protobuf_Timestamp;
+extern const upb_msglayout google_protobuf_Duration_msginit;
+extern const upb_msglayout google_protobuf_Timestamp_msginit;
+
+
+/* grpc.lb.v1.LoadBalanceRequest */
+
+UPB_INLINE grpc_lb_v1_LoadBalanceRequest *grpc_lb_v1_LoadBalanceRequest_new(upb_arena *arena) {
return (grpc_lb_v1_LoadBalanceRequest *)_upb_msg_new(&grpc_lb_v1_LoadBalanceRequest_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_LoadBalanceRequest *grpc_lb_v1_LoadBalanceRequest_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_LoadBalanceRequest *ret = grpc_lb_v1_LoadBalanceRequest_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_LoadBalanceRequest_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_LoadBalanceRequest_serialize(const grpc_lb_v1_LoadBalanceRequest *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_LoadBalanceRequest_msginit, arena, len);
-}
-
-typedef enum {
- grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_initial_request = 1,
- grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_client_stats = 2,
- grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_NOT_SET = 0
-} grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_oneofcases;
+}
+UPB_INLINE grpc_lb_v1_LoadBalanceRequest *grpc_lb_v1_LoadBalanceRequest_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_LoadBalanceRequest *ret = grpc_lb_v1_LoadBalanceRequest_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_LoadBalanceRequest_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_LoadBalanceRequest_serialize(const grpc_lb_v1_LoadBalanceRequest *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_LoadBalanceRequest_msginit, arena, len);
+}
+
+typedef enum {
+ grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_initial_request = 1,
+ grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_client_stats = 2,
+ grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_NOT_SET = 0
+} grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_oneofcases;
UPB_INLINE grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_oneofcases grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_case(const grpc_lb_v1_LoadBalanceRequest* msg) { return (grpc_lb_v1_LoadBalanceRequest_load_balance_request_type_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(4, 8), int32_t); }
-
+
UPB_INLINE bool grpc_lb_v1_LoadBalanceRequest_has_initial_request(const grpc_lb_v1_LoadBalanceRequest *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 1; }
-UPB_INLINE const grpc_lb_v1_InitialLoadBalanceRequest* grpc_lb_v1_LoadBalanceRequest_initial_request(const grpc_lb_v1_LoadBalanceRequest *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_InitialLoadBalanceRequest*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 1, NULL); }
+UPB_INLINE const grpc_lb_v1_InitialLoadBalanceRequest* grpc_lb_v1_LoadBalanceRequest_initial_request(const grpc_lb_v1_LoadBalanceRequest *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_InitialLoadBalanceRequest*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 1, NULL); }
UPB_INLINE bool grpc_lb_v1_LoadBalanceRequest_has_client_stats(const grpc_lb_v1_LoadBalanceRequest *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 2; }
-UPB_INLINE const grpc_lb_v1_ClientStats* grpc_lb_v1_LoadBalanceRequest_client_stats(const grpc_lb_v1_LoadBalanceRequest *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_ClientStats*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 2, NULL); }
-
-UPB_INLINE void grpc_lb_v1_LoadBalanceRequest_set_initial_request(grpc_lb_v1_LoadBalanceRequest *msg, grpc_lb_v1_InitialLoadBalanceRequest* value) {
- UPB_WRITE_ONEOF(msg, grpc_lb_v1_InitialLoadBalanceRequest*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 1);
-}
-UPB_INLINE struct grpc_lb_v1_InitialLoadBalanceRequest* grpc_lb_v1_LoadBalanceRequest_mutable_initial_request(grpc_lb_v1_LoadBalanceRequest *msg, upb_arena *arena) {
- struct grpc_lb_v1_InitialLoadBalanceRequest* sub = (struct grpc_lb_v1_InitialLoadBalanceRequest*)grpc_lb_v1_LoadBalanceRequest_initial_request(msg);
- if (sub == NULL) {
+UPB_INLINE const grpc_lb_v1_ClientStats* grpc_lb_v1_LoadBalanceRequest_client_stats(const grpc_lb_v1_LoadBalanceRequest *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_ClientStats*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 2, NULL); }
+
+UPB_INLINE void grpc_lb_v1_LoadBalanceRequest_set_initial_request(grpc_lb_v1_LoadBalanceRequest *msg, grpc_lb_v1_InitialLoadBalanceRequest* value) {
+ UPB_WRITE_ONEOF(msg, grpc_lb_v1_InitialLoadBalanceRequest*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 1);
+}
+UPB_INLINE struct grpc_lb_v1_InitialLoadBalanceRequest* grpc_lb_v1_LoadBalanceRequest_mutable_initial_request(grpc_lb_v1_LoadBalanceRequest *msg, upb_arena *arena) {
+ struct grpc_lb_v1_InitialLoadBalanceRequest* sub = (struct grpc_lb_v1_InitialLoadBalanceRequest*)grpc_lb_v1_LoadBalanceRequest_initial_request(msg);
+ if (sub == NULL) {
sub = (struct grpc_lb_v1_InitialLoadBalanceRequest*)_upb_msg_new(&grpc_lb_v1_InitialLoadBalanceRequest_msginit, arena);
- if (!sub) return NULL;
- grpc_lb_v1_LoadBalanceRequest_set_initial_request(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_lb_v1_LoadBalanceRequest_set_client_stats(grpc_lb_v1_LoadBalanceRequest *msg, grpc_lb_v1_ClientStats* value) {
- UPB_WRITE_ONEOF(msg, grpc_lb_v1_ClientStats*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 2);
-}
-UPB_INLINE struct grpc_lb_v1_ClientStats* grpc_lb_v1_LoadBalanceRequest_mutable_client_stats(grpc_lb_v1_LoadBalanceRequest *msg, upb_arena *arena) {
- struct grpc_lb_v1_ClientStats* sub = (struct grpc_lb_v1_ClientStats*)grpc_lb_v1_LoadBalanceRequest_client_stats(msg);
- if (sub == NULL) {
+ if (!sub) return NULL;
+ grpc_lb_v1_LoadBalanceRequest_set_initial_request(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_lb_v1_LoadBalanceRequest_set_client_stats(grpc_lb_v1_LoadBalanceRequest *msg, grpc_lb_v1_ClientStats* value) {
+ UPB_WRITE_ONEOF(msg, grpc_lb_v1_ClientStats*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 2);
+}
+UPB_INLINE struct grpc_lb_v1_ClientStats* grpc_lb_v1_LoadBalanceRequest_mutable_client_stats(grpc_lb_v1_LoadBalanceRequest *msg, upb_arena *arena) {
+ struct grpc_lb_v1_ClientStats* sub = (struct grpc_lb_v1_ClientStats*)grpc_lb_v1_LoadBalanceRequest_client_stats(msg);
+ if (sub == NULL) {
sub = (struct grpc_lb_v1_ClientStats*)_upb_msg_new(&grpc_lb_v1_ClientStats_msginit, arena);
- if (!sub) return NULL;
- grpc_lb_v1_LoadBalanceRequest_set_client_stats(msg, sub);
- }
- return sub;
-}
-
-/* grpc.lb.v1.InitialLoadBalanceRequest */
-
-UPB_INLINE grpc_lb_v1_InitialLoadBalanceRequest *grpc_lb_v1_InitialLoadBalanceRequest_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ grpc_lb_v1_LoadBalanceRequest_set_client_stats(msg, sub);
+ }
+ return sub;
+}
+
+/* grpc.lb.v1.InitialLoadBalanceRequest */
+
+UPB_INLINE grpc_lb_v1_InitialLoadBalanceRequest *grpc_lb_v1_InitialLoadBalanceRequest_new(upb_arena *arena) {
return (grpc_lb_v1_InitialLoadBalanceRequest *)_upb_msg_new(&grpc_lb_v1_InitialLoadBalanceRequest_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_InitialLoadBalanceRequest *grpc_lb_v1_InitialLoadBalanceRequest_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_InitialLoadBalanceRequest *ret = grpc_lb_v1_InitialLoadBalanceRequest_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_InitialLoadBalanceRequest_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_InitialLoadBalanceRequest_serialize(const grpc_lb_v1_InitialLoadBalanceRequest *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_InitialLoadBalanceRequest_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_lb_v1_InitialLoadBalanceRequest *grpc_lb_v1_InitialLoadBalanceRequest_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_InitialLoadBalanceRequest *ret = grpc_lb_v1_InitialLoadBalanceRequest_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_InitialLoadBalanceRequest_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_InitialLoadBalanceRequest_serialize(const grpc_lb_v1_InitialLoadBalanceRequest *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_InitialLoadBalanceRequest_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_lb_v1_InitialLoadBalanceRequest_name(const grpc_lb_v1_InitialLoadBalanceRequest *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
-
-UPB_INLINE void grpc_lb_v1_InitialLoadBalanceRequest_set_name(grpc_lb_v1_InitialLoadBalanceRequest *msg, upb_strview value) {
+
+UPB_INLINE void grpc_lb_v1_InitialLoadBalanceRequest_set_name(grpc_lb_v1_InitialLoadBalanceRequest *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-
-/* grpc.lb.v1.ClientStatsPerToken */
-
-UPB_INLINE grpc_lb_v1_ClientStatsPerToken *grpc_lb_v1_ClientStatsPerToken_new(upb_arena *arena) {
+}
+
+/* grpc.lb.v1.ClientStatsPerToken */
+
+UPB_INLINE grpc_lb_v1_ClientStatsPerToken *grpc_lb_v1_ClientStatsPerToken_new(upb_arena *arena) {
return (grpc_lb_v1_ClientStatsPerToken *)_upb_msg_new(&grpc_lb_v1_ClientStatsPerToken_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_ClientStatsPerToken *grpc_lb_v1_ClientStatsPerToken_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_ClientStatsPerToken *ret = grpc_lb_v1_ClientStatsPerToken_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_ClientStatsPerToken_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_ClientStatsPerToken_serialize(const grpc_lb_v1_ClientStatsPerToken *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_ClientStatsPerToken_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_lb_v1_ClientStatsPerToken *grpc_lb_v1_ClientStatsPerToken_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_ClientStatsPerToken *ret = grpc_lb_v1_ClientStatsPerToken_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_ClientStatsPerToken_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_ClientStatsPerToken_serialize(const grpc_lb_v1_ClientStatsPerToken *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_ClientStatsPerToken_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_lb_v1_ClientStatsPerToken_load_balance_token(const grpc_lb_v1_ClientStatsPerToken *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE int64_t grpc_lb_v1_ClientStatsPerToken_num_calls(const grpc_lb_v1_ClientStatsPerToken *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t); }
-
-UPB_INLINE void grpc_lb_v1_ClientStatsPerToken_set_load_balance_token(grpc_lb_v1_ClientStatsPerToken *msg, upb_strview value) {
+
+UPB_INLINE void grpc_lb_v1_ClientStatsPerToken_set_load_balance_token(grpc_lb_v1_ClientStatsPerToken *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
-}
-UPB_INLINE void grpc_lb_v1_ClientStatsPerToken_set_num_calls(grpc_lb_v1_ClientStatsPerToken *msg, int64_t value) {
+}
+UPB_INLINE void grpc_lb_v1_ClientStatsPerToken_set_num_calls(grpc_lb_v1_ClientStatsPerToken *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t) = value;
-}
-
-/* grpc.lb.v1.ClientStats */
-
-UPB_INLINE grpc_lb_v1_ClientStats *grpc_lb_v1_ClientStats_new(upb_arena *arena) {
+}
+
+/* grpc.lb.v1.ClientStats */
+
+UPB_INLINE grpc_lb_v1_ClientStats *grpc_lb_v1_ClientStats_new(upb_arena *arena) {
return (grpc_lb_v1_ClientStats *)_upb_msg_new(&grpc_lb_v1_ClientStats_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_ClientStats *grpc_lb_v1_ClientStats_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_ClientStats *ret = grpc_lb_v1_ClientStats_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_ClientStats_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_ClientStats_serialize(const grpc_lb_v1_ClientStats *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_ClientStats_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_lb_v1_ClientStats *grpc_lb_v1_ClientStats_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_ClientStats *ret = grpc_lb_v1_ClientStats_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_ClientStats_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_ClientStats_serialize(const grpc_lb_v1_ClientStats *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_ClientStats_msginit, arena, len);
+}
+
UPB_INLINE bool grpc_lb_v1_ClientStats_has_timestamp(const grpc_lb_v1_ClientStats *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(32, 32)); }
UPB_INLINE const struct google_protobuf_Timestamp* grpc_lb_v1_ClientStats_timestamp(const grpc_lb_v1_ClientStats *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), const struct google_protobuf_Timestamp*); }
UPB_INLINE int64_t grpc_lb_v1_ClientStats_num_calls_started(const grpc_lb_v1_ClientStats *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t); }
@@ -168,99 +168,99 @@ UPB_INLINE int64_t grpc_lb_v1_ClientStats_num_calls_finished(const grpc_lb_v1_Cl
UPB_INLINE int64_t grpc_lb_v1_ClientStats_num_calls_finished_with_client_failed_to_send(const grpc_lb_v1_ClientStats *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t); }
UPB_INLINE int64_t grpc_lb_v1_ClientStats_num_calls_finished_known_received(const grpc_lb_v1_ClientStats *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), int64_t); }
UPB_INLINE bool grpc_lb_v1_ClientStats_has_calls_finished_with_drop(const grpc_lb_v1_ClientStats *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(36, 40)); }
-UPB_INLINE const grpc_lb_v1_ClientStatsPerToken* const* grpc_lb_v1_ClientStats_calls_finished_with_drop(const grpc_lb_v1_ClientStats *msg, size_t *len) { return (const grpc_lb_v1_ClientStatsPerToken* const*)_upb_array_accessor(msg, UPB_SIZE(36, 40), len); }
-
-UPB_INLINE void grpc_lb_v1_ClientStats_set_timestamp(grpc_lb_v1_ClientStats *msg, struct google_protobuf_Timestamp* value) {
+UPB_INLINE const grpc_lb_v1_ClientStatsPerToken* const* grpc_lb_v1_ClientStats_calls_finished_with_drop(const grpc_lb_v1_ClientStats *msg, size_t *len) { return (const grpc_lb_v1_ClientStatsPerToken* const*)_upb_array_accessor(msg, UPB_SIZE(36, 40), len); }
+
+UPB_INLINE void grpc_lb_v1_ClientStats_set_timestamp(grpc_lb_v1_ClientStats *msg, struct google_protobuf_Timestamp* value) {
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), struct google_protobuf_Timestamp*) = value;
-}
-UPB_INLINE struct google_protobuf_Timestamp* grpc_lb_v1_ClientStats_mutable_timestamp(grpc_lb_v1_ClientStats *msg, upb_arena *arena) {
- struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)grpc_lb_v1_ClientStats_timestamp(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Timestamp* grpc_lb_v1_ClientStats_mutable_timestamp(grpc_lb_v1_ClientStats *msg, upb_arena *arena) {
+ struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)grpc_lb_v1_ClientStats_timestamp(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Timestamp*)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
- if (!sub) return NULL;
- grpc_lb_v1_ClientStats_set_timestamp(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_started(grpc_lb_v1_ClientStats *msg, int64_t value) {
+ if (!sub) return NULL;
+ grpc_lb_v1_ClientStats_set_timestamp(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_started(grpc_lb_v1_ClientStats *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int64_t) = value;
-}
-UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_finished(grpc_lb_v1_ClientStats *msg, int64_t value) {
+}
+UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_finished(grpc_lb_v1_ClientStats *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t) = value;
-}
-UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_finished_with_client_failed_to_send(grpc_lb_v1_ClientStats *msg, int64_t value) {
+}
+UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_finished_with_client_failed_to_send(grpc_lb_v1_ClientStats *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
-}
-UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_finished_known_received(grpc_lb_v1_ClientStats *msg, int64_t value) {
+}
+UPB_INLINE void grpc_lb_v1_ClientStats_set_num_calls_finished_known_received(grpc_lb_v1_ClientStats *msg, int64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), int64_t) = value;
-}
-UPB_INLINE grpc_lb_v1_ClientStatsPerToken** grpc_lb_v1_ClientStats_mutable_calls_finished_with_drop(grpc_lb_v1_ClientStats *msg, size_t *len) {
- return (grpc_lb_v1_ClientStatsPerToken**)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 40), len);
-}
-UPB_INLINE grpc_lb_v1_ClientStatsPerToken** grpc_lb_v1_ClientStats_resize_calls_finished_with_drop(grpc_lb_v1_ClientStats *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE grpc_lb_v1_ClientStatsPerToken** grpc_lb_v1_ClientStats_mutable_calls_finished_with_drop(grpc_lb_v1_ClientStats *msg, size_t *len) {
+ return (grpc_lb_v1_ClientStatsPerToken**)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 40), len);
+}
+UPB_INLINE grpc_lb_v1_ClientStatsPerToken** grpc_lb_v1_ClientStats_resize_calls_finished_with_drop(grpc_lb_v1_ClientStats *msg, size_t len, upb_arena *arena) {
return (grpc_lb_v1_ClientStatsPerToken**)_upb_array_resize_accessor(msg, UPB_SIZE(36, 40), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct grpc_lb_v1_ClientStatsPerToken* grpc_lb_v1_ClientStats_add_calls_finished_with_drop(grpc_lb_v1_ClientStats *msg, upb_arena *arena) {
+}
+UPB_INLINE struct grpc_lb_v1_ClientStatsPerToken* grpc_lb_v1_ClientStats_add_calls_finished_with_drop(grpc_lb_v1_ClientStats *msg, upb_arena *arena) {
struct grpc_lb_v1_ClientStatsPerToken* sub = (struct grpc_lb_v1_ClientStatsPerToken*)_upb_msg_new(&grpc_lb_v1_ClientStatsPerToken_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(36, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* grpc.lb.v1.LoadBalanceResponse */
-
-UPB_INLINE grpc_lb_v1_LoadBalanceResponse *grpc_lb_v1_LoadBalanceResponse_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(36, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* grpc.lb.v1.LoadBalanceResponse */
+
+UPB_INLINE grpc_lb_v1_LoadBalanceResponse *grpc_lb_v1_LoadBalanceResponse_new(upb_arena *arena) {
return (grpc_lb_v1_LoadBalanceResponse *)_upb_msg_new(&grpc_lb_v1_LoadBalanceResponse_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_LoadBalanceResponse *grpc_lb_v1_LoadBalanceResponse_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_LoadBalanceResponse *ret = grpc_lb_v1_LoadBalanceResponse_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_LoadBalanceResponse_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_LoadBalanceResponse_serialize(const grpc_lb_v1_LoadBalanceResponse *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_LoadBalanceResponse_msginit, arena, len);
-}
-
-typedef enum {
- grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_initial_response = 1,
- grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_server_list = 2,
+}
+UPB_INLINE grpc_lb_v1_LoadBalanceResponse *grpc_lb_v1_LoadBalanceResponse_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_LoadBalanceResponse *ret = grpc_lb_v1_LoadBalanceResponse_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_LoadBalanceResponse_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_LoadBalanceResponse_serialize(const grpc_lb_v1_LoadBalanceResponse *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_LoadBalanceResponse_msginit, arena, len);
+}
+
+typedef enum {
+ grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_initial_response = 1,
+ grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_server_list = 2,
grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_fallback_response = 3,
- grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_NOT_SET = 0
-} grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_oneofcases;
+ grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_NOT_SET = 0
+} grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_oneofcases;
UPB_INLINE grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_oneofcases grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_case(const grpc_lb_v1_LoadBalanceResponse* msg) { return (grpc_lb_v1_LoadBalanceResponse_load_balance_response_type_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(4, 8), int32_t); }
-
+
UPB_INLINE bool grpc_lb_v1_LoadBalanceResponse_has_initial_response(const grpc_lb_v1_LoadBalanceResponse *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 1; }
-UPB_INLINE const grpc_lb_v1_InitialLoadBalanceResponse* grpc_lb_v1_LoadBalanceResponse_initial_response(const grpc_lb_v1_LoadBalanceResponse *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_InitialLoadBalanceResponse*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 1, NULL); }
+UPB_INLINE const grpc_lb_v1_InitialLoadBalanceResponse* grpc_lb_v1_LoadBalanceResponse_initial_response(const grpc_lb_v1_LoadBalanceResponse *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_InitialLoadBalanceResponse*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 1, NULL); }
UPB_INLINE bool grpc_lb_v1_LoadBalanceResponse_has_server_list(const grpc_lb_v1_LoadBalanceResponse *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 2; }
-UPB_INLINE const grpc_lb_v1_ServerList* grpc_lb_v1_LoadBalanceResponse_server_list(const grpc_lb_v1_LoadBalanceResponse *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_ServerList*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 2, NULL); }
+UPB_INLINE const grpc_lb_v1_ServerList* grpc_lb_v1_LoadBalanceResponse_server_list(const grpc_lb_v1_LoadBalanceResponse *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_ServerList*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 2, NULL); }
UPB_INLINE bool grpc_lb_v1_LoadBalanceResponse_has_fallback_response(const grpc_lb_v1_LoadBalanceResponse *msg) { return _upb_getoneofcase(msg, UPB_SIZE(4, 8)) == 3; }
UPB_INLINE const grpc_lb_v1_FallbackResponse* grpc_lb_v1_LoadBalanceResponse_fallback_response(const grpc_lb_v1_LoadBalanceResponse *msg) { return UPB_READ_ONEOF(msg, const grpc_lb_v1_FallbackResponse*, UPB_SIZE(0, 0), UPB_SIZE(4, 8), 3, NULL); }
-
-UPB_INLINE void grpc_lb_v1_LoadBalanceResponse_set_initial_response(grpc_lb_v1_LoadBalanceResponse *msg, grpc_lb_v1_InitialLoadBalanceResponse* value) {
- UPB_WRITE_ONEOF(msg, grpc_lb_v1_InitialLoadBalanceResponse*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 1);
-}
-UPB_INLINE struct grpc_lb_v1_InitialLoadBalanceResponse* grpc_lb_v1_LoadBalanceResponse_mutable_initial_response(grpc_lb_v1_LoadBalanceResponse *msg, upb_arena *arena) {
- struct grpc_lb_v1_InitialLoadBalanceResponse* sub = (struct grpc_lb_v1_InitialLoadBalanceResponse*)grpc_lb_v1_LoadBalanceResponse_initial_response(msg);
- if (sub == NULL) {
+
+UPB_INLINE void grpc_lb_v1_LoadBalanceResponse_set_initial_response(grpc_lb_v1_LoadBalanceResponse *msg, grpc_lb_v1_InitialLoadBalanceResponse* value) {
+ UPB_WRITE_ONEOF(msg, grpc_lb_v1_InitialLoadBalanceResponse*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 1);
+}
+UPB_INLINE struct grpc_lb_v1_InitialLoadBalanceResponse* grpc_lb_v1_LoadBalanceResponse_mutable_initial_response(grpc_lb_v1_LoadBalanceResponse *msg, upb_arena *arena) {
+ struct grpc_lb_v1_InitialLoadBalanceResponse* sub = (struct grpc_lb_v1_InitialLoadBalanceResponse*)grpc_lb_v1_LoadBalanceResponse_initial_response(msg);
+ if (sub == NULL) {
sub = (struct grpc_lb_v1_InitialLoadBalanceResponse*)_upb_msg_new(&grpc_lb_v1_InitialLoadBalanceResponse_msginit, arena);
- if (!sub) return NULL;
- grpc_lb_v1_LoadBalanceResponse_set_initial_response(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void grpc_lb_v1_LoadBalanceResponse_set_server_list(grpc_lb_v1_LoadBalanceResponse *msg, grpc_lb_v1_ServerList* value) {
- UPB_WRITE_ONEOF(msg, grpc_lb_v1_ServerList*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 2);
-}
-UPB_INLINE struct grpc_lb_v1_ServerList* grpc_lb_v1_LoadBalanceResponse_mutable_server_list(grpc_lb_v1_LoadBalanceResponse *msg, upb_arena *arena) {
- struct grpc_lb_v1_ServerList* sub = (struct grpc_lb_v1_ServerList*)grpc_lb_v1_LoadBalanceResponse_server_list(msg);
- if (sub == NULL) {
+ if (!sub) return NULL;
+ grpc_lb_v1_LoadBalanceResponse_set_initial_response(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void grpc_lb_v1_LoadBalanceResponse_set_server_list(grpc_lb_v1_LoadBalanceResponse *msg, grpc_lb_v1_ServerList* value) {
+ UPB_WRITE_ONEOF(msg, grpc_lb_v1_ServerList*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 2);
+}
+UPB_INLINE struct grpc_lb_v1_ServerList* grpc_lb_v1_LoadBalanceResponse_mutable_server_list(grpc_lb_v1_LoadBalanceResponse *msg, upb_arena *arena) {
+ struct grpc_lb_v1_ServerList* sub = (struct grpc_lb_v1_ServerList*)grpc_lb_v1_LoadBalanceResponse_server_list(msg);
+ if (sub == NULL) {
sub = (struct grpc_lb_v1_ServerList*)_upb_msg_new(&grpc_lb_v1_ServerList_msginit, arena);
- if (!sub) return NULL;
- grpc_lb_v1_LoadBalanceResponse_set_server_list(msg, sub);
- }
- return sub;
-}
+ if (!sub) return NULL;
+ grpc_lb_v1_LoadBalanceResponse_set_server_list(msg, sub);
+ }
+ return sub;
+}
UPB_INLINE void grpc_lb_v1_LoadBalanceResponse_set_fallback_response(grpc_lb_v1_LoadBalanceResponse *msg, grpc_lb_v1_FallbackResponse* value) {
UPB_WRITE_ONEOF(msg, grpc_lb_v1_FallbackResponse*, UPB_SIZE(0, 0), value, UPB_SIZE(4, 8), 3);
}
@@ -273,104 +273,104 @@ UPB_INLINE struct grpc_lb_v1_FallbackResponse* grpc_lb_v1_LoadBalanceResponse_mu
}
return sub;
}
-
-/* grpc.lb.v1.InitialLoadBalanceResponse */
-
-UPB_INLINE grpc_lb_v1_InitialLoadBalanceResponse *grpc_lb_v1_InitialLoadBalanceResponse_new(upb_arena *arena) {
+
+/* grpc.lb.v1.InitialLoadBalanceResponse */
+
+UPB_INLINE grpc_lb_v1_InitialLoadBalanceResponse *grpc_lb_v1_InitialLoadBalanceResponse_new(upb_arena *arena) {
return (grpc_lb_v1_InitialLoadBalanceResponse *)_upb_msg_new(&grpc_lb_v1_InitialLoadBalanceResponse_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_InitialLoadBalanceResponse *grpc_lb_v1_InitialLoadBalanceResponse_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_InitialLoadBalanceResponse *ret = grpc_lb_v1_InitialLoadBalanceResponse_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_InitialLoadBalanceResponse_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_InitialLoadBalanceResponse_serialize(const grpc_lb_v1_InitialLoadBalanceResponse *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_InitialLoadBalanceResponse_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_lb_v1_InitialLoadBalanceResponse *grpc_lb_v1_InitialLoadBalanceResponse_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_InitialLoadBalanceResponse *ret = grpc_lb_v1_InitialLoadBalanceResponse_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_InitialLoadBalanceResponse_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_InitialLoadBalanceResponse_serialize(const grpc_lb_v1_InitialLoadBalanceResponse *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_InitialLoadBalanceResponse_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_lb_v1_InitialLoadBalanceResponse_load_balancer_delegate(const grpc_lb_v1_InitialLoadBalanceResponse *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
UPB_INLINE bool grpc_lb_v1_InitialLoadBalanceResponse_has_client_stats_report_interval(const grpc_lb_v1_InitialLoadBalanceResponse *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 16)); }
UPB_INLINE const struct google_protobuf_Duration* grpc_lb_v1_InitialLoadBalanceResponse_client_stats_report_interval(const grpc_lb_v1_InitialLoadBalanceResponse *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const struct google_protobuf_Duration*); }
-
-UPB_INLINE void grpc_lb_v1_InitialLoadBalanceResponse_set_load_balancer_delegate(grpc_lb_v1_InitialLoadBalanceResponse *msg, upb_strview value) {
+
+UPB_INLINE void grpc_lb_v1_InitialLoadBalanceResponse_set_load_balancer_delegate(grpc_lb_v1_InitialLoadBalanceResponse *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
-}
-UPB_INLINE void grpc_lb_v1_InitialLoadBalanceResponse_set_client_stats_report_interval(grpc_lb_v1_InitialLoadBalanceResponse *msg, struct google_protobuf_Duration* value) {
+}
+UPB_INLINE void grpc_lb_v1_InitialLoadBalanceResponse_set_client_stats_report_interval(grpc_lb_v1_InitialLoadBalanceResponse *msg, struct google_protobuf_Duration* value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* grpc_lb_v1_InitialLoadBalanceResponse_mutable_client_stats_report_interval(grpc_lb_v1_InitialLoadBalanceResponse *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)grpc_lb_v1_InitialLoadBalanceResponse_client_stats_report_interval(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* grpc_lb_v1_InitialLoadBalanceResponse_mutable_client_stats_report_interval(grpc_lb_v1_InitialLoadBalanceResponse *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)grpc_lb_v1_InitialLoadBalanceResponse_client_stats_report_interval(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- grpc_lb_v1_InitialLoadBalanceResponse_set_client_stats_report_interval(msg, sub);
- }
- return sub;
-}
-
-/* grpc.lb.v1.ServerList */
-
-UPB_INLINE grpc_lb_v1_ServerList *grpc_lb_v1_ServerList_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ grpc_lb_v1_InitialLoadBalanceResponse_set_client_stats_report_interval(msg, sub);
+ }
+ return sub;
+}
+
+/* grpc.lb.v1.ServerList */
+
+UPB_INLINE grpc_lb_v1_ServerList *grpc_lb_v1_ServerList_new(upb_arena *arena) {
return (grpc_lb_v1_ServerList *)_upb_msg_new(&grpc_lb_v1_ServerList_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_ServerList *grpc_lb_v1_ServerList_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_ServerList *ret = grpc_lb_v1_ServerList_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_ServerList_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_ServerList_serialize(const grpc_lb_v1_ServerList *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_ServerList_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_lb_v1_ServerList *grpc_lb_v1_ServerList_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_ServerList *ret = grpc_lb_v1_ServerList_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_ServerList_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_ServerList_serialize(const grpc_lb_v1_ServerList *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_ServerList_msginit, arena, len);
+}
+
UPB_INLINE bool grpc_lb_v1_ServerList_has_servers(const grpc_lb_v1_ServerList *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
-UPB_INLINE const grpc_lb_v1_Server* const* grpc_lb_v1_ServerList_servers(const grpc_lb_v1_ServerList *msg, size_t *len) { return (const grpc_lb_v1_Server* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
-
-UPB_INLINE grpc_lb_v1_Server** grpc_lb_v1_ServerList_mutable_servers(grpc_lb_v1_ServerList *msg, size_t *len) {
- return (grpc_lb_v1_Server**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
-}
-UPB_INLINE grpc_lb_v1_Server** grpc_lb_v1_ServerList_resize_servers(grpc_lb_v1_ServerList *msg, size_t len, upb_arena *arena) {
+UPB_INLINE const grpc_lb_v1_Server* const* grpc_lb_v1_ServerList_servers(const grpc_lb_v1_ServerList *msg, size_t *len) { return (const grpc_lb_v1_Server* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
+
+UPB_INLINE grpc_lb_v1_Server** grpc_lb_v1_ServerList_mutable_servers(grpc_lb_v1_ServerList *msg, size_t *len) {
+ return (grpc_lb_v1_Server**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
+}
+UPB_INLINE grpc_lb_v1_Server** grpc_lb_v1_ServerList_resize_servers(grpc_lb_v1_ServerList *msg, size_t len, upb_arena *arena) {
return (grpc_lb_v1_Server**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct grpc_lb_v1_Server* grpc_lb_v1_ServerList_add_servers(grpc_lb_v1_ServerList *msg, upb_arena *arena) {
+}
+UPB_INLINE struct grpc_lb_v1_Server* grpc_lb_v1_ServerList_add_servers(grpc_lb_v1_ServerList *msg, upb_arena *arena) {
struct grpc_lb_v1_Server* sub = (struct grpc_lb_v1_Server*)_upb_msg_new(&grpc_lb_v1_Server_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* grpc.lb.v1.Server */
-
-UPB_INLINE grpc_lb_v1_Server *grpc_lb_v1_Server_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* grpc.lb.v1.Server */
+
+UPB_INLINE grpc_lb_v1_Server *grpc_lb_v1_Server_new(upb_arena *arena) {
return (grpc_lb_v1_Server *)_upb_msg_new(&grpc_lb_v1_Server_msginit, arena);
-}
-UPB_INLINE grpc_lb_v1_Server *grpc_lb_v1_Server_parse(const char *buf, size_t size,
- upb_arena *arena) {
- grpc_lb_v1_Server *ret = grpc_lb_v1_Server_new(arena);
- return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_Server_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *grpc_lb_v1_Server_serialize(const grpc_lb_v1_Server *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &grpc_lb_v1_Server_msginit, arena, len);
-}
-
+}
+UPB_INLINE grpc_lb_v1_Server *grpc_lb_v1_Server_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ grpc_lb_v1_Server *ret = grpc_lb_v1_Server_new(arena);
+ return (ret && upb_decode(buf, size, ret, &grpc_lb_v1_Server_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *grpc_lb_v1_Server_serialize(const grpc_lb_v1_Server *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &grpc_lb_v1_Server_msginit, arena, len);
+}
+
UPB_INLINE upb_strview grpc_lb_v1_Server_ip_address(const grpc_lb_v1_Server *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE int32_t grpc_lb_v1_Server_port(const grpc_lb_v1_Server *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t); }
UPB_INLINE upb_strview grpc_lb_v1_Server_load_balance_token(const grpc_lb_v1_Server *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 24), upb_strview); }
UPB_INLINE bool grpc_lb_v1_Server_drop(const grpc_lb_v1_Server *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool); }
-
-UPB_INLINE void grpc_lb_v1_Server_set_ip_address(grpc_lb_v1_Server *msg, upb_strview value) {
+
+UPB_INLINE void grpc_lb_v1_Server_set_ip_address(grpc_lb_v1_Server *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
-}
-UPB_INLINE void grpc_lb_v1_Server_set_port(grpc_lb_v1_Server *msg, int32_t value) {
+}
+UPB_INLINE void grpc_lb_v1_Server_set_port(grpc_lb_v1_Server *msg, int32_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), int32_t) = value;
-}
-UPB_INLINE void grpc_lb_v1_Server_set_load_balance_token(grpc_lb_v1_Server *msg, upb_strview value) {
+}
+UPB_INLINE void grpc_lb_v1_Server_set_load_balance_token(grpc_lb_v1_Server *msg, upb_strview value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 24), upb_strview) = value;
-}
-UPB_INLINE void grpc_lb_v1_Server_set_drop(grpc_lb_v1_Server *msg, bool value) {
+}
+UPB_INLINE void grpc_lb_v1_Server_set_drop(grpc_lb_v1_Server *msg, bool value) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool) = value;
-}
-
+}
+
/* grpc.lb.v1.FallbackResponse */
UPB_INLINE grpc_lb_v1_FallbackResponse *grpc_lb_v1_FallbackResponse_new(upb_arena *arena) {
@@ -387,10 +387,10 @@ UPB_INLINE char *grpc_lb_v1_FallbackResponse_serialize(const grpc_lb_v1_Fallback
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* SRC_PROTO_GRPC_LB_V1_LOAD_BALANCER_PROTO_UPB_H_ */
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* SRC_PROTO_GRPC_LB_V1_LOAD_BALANCER_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c
index aa9918f024..ccb66f4e65 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c
@@ -1,58 +1,58 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * udpa/data/orca/v1/orca_load_report.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "udpa/data/orca/v1/orca_load_report.upb.h"
-#include "validate/validate.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const udpa_data_orca_v1_OrcaLoadReport_submsgs[2] = {
- &udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_msginit,
- &udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_msginit,
-};
-
-static const upb_msglayout_field udpa_data_orca_v1_OrcaLoadReport__fields[5] = {
- {1, UPB_SIZE(0, 0), 0, 0, 1, 1},
- {2, UPB_SIZE(8, 8), 0, 0, 1, 1},
- {3, UPB_SIZE(16, 16), 0, 0, 4, 1},
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * udpa/data/orca/v1/orca_load_report.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "udpa/data/orca/v1/orca_load_report.upb.h"
+#include "validate/validate.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const udpa_data_orca_v1_OrcaLoadReport_submsgs[2] = {
+ &udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_msginit,
+ &udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_msginit,
+};
+
+static const upb_msglayout_field udpa_data_orca_v1_OrcaLoadReport__fields[5] = {
+ {1, UPB_SIZE(0, 0), 0, 0, 1, 1},
+ {2, UPB_SIZE(8, 8), 0, 0, 1, 1},
+ {3, UPB_SIZE(16, 16), 0, 0, 4, 1},
{4, UPB_SIZE(24, 24), 0, 0, 11, _UPB_LABEL_MAP},
{5, UPB_SIZE(28, 32), 0, 1, 11, _UPB_LABEL_MAP},
-};
-
-const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_msginit = {
- &udpa_data_orca_v1_OrcaLoadReport_submsgs[0],
- &udpa_data_orca_v1_OrcaLoadReport__fields[0],
- UPB_SIZE(32, 40), 5, false,
-};
-
-static const upb_msglayout_field udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry__fields[2] = {
+};
+
+const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_msginit = {
+ &udpa_data_orca_v1_OrcaLoadReport_submsgs[0],
+ &udpa_data_orca_v1_OrcaLoadReport__fields[0],
+ UPB_SIZE(32, 40), 5, false,
+};
+
+static const upb_msglayout_field udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry__fields[2] = {
{1, UPB_SIZE(0, 0), 0, 0, 9, 1},
{2, UPB_SIZE(8, 16), 0, 0, 1, 1},
-};
-
-const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_msginit = {
- NULL,
- &udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-static const upb_msglayout_field udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry__fields[2] = {
+};
+
+const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_msginit = {
+ NULL,
+ &udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+static const upb_msglayout_field udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry__fields[2] = {
{1, UPB_SIZE(0, 0), 0, 0, 9, 1},
{2, UPB_SIZE(8, 16), 0, 0, 1, 1},
-};
-
-const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_msginit = {
- NULL,
- &udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry__fields[0],
- UPB_SIZE(16, 32), 2, false,
-};
-
-#include "upb/port_undef.inc"
-
+};
+
+const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_msginit = {
+ NULL,
+ &udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry__fields[0],
+ UPB_SIZE(16, 32), 2, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h
index 5c63aef12e..c548ee85d6 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h
@@ -1,49 +1,49 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * udpa/data/orca/v1/orca_load_report.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef UDPA_DATA_ORCA_V1_ORCA_LOAD_REPORT_PROTO_UPB_H_
-#define UDPA_DATA_ORCA_V1_ORCA_LOAD_REPORT_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct udpa_data_orca_v1_OrcaLoadReport;
-struct udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry;
-struct udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry;
-typedef struct udpa_data_orca_v1_OrcaLoadReport udpa_data_orca_v1_OrcaLoadReport;
-typedef struct udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry;
-typedef struct udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry;
-extern const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_msginit;
-extern const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_msginit;
-extern const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_msginit;
-
-
-/* udpa.data.orca.v1.OrcaLoadReport */
-
-UPB_INLINE udpa_data_orca_v1_OrcaLoadReport *udpa_data_orca_v1_OrcaLoadReport_new(upb_arena *arena) {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * udpa/data/orca/v1/orca_load_report.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef UDPA_DATA_ORCA_V1_ORCA_LOAD_REPORT_PROTO_UPB_H_
+#define UDPA_DATA_ORCA_V1_ORCA_LOAD_REPORT_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct udpa_data_orca_v1_OrcaLoadReport;
+struct udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry;
+struct udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry;
+typedef struct udpa_data_orca_v1_OrcaLoadReport udpa_data_orca_v1_OrcaLoadReport;
+typedef struct udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry;
+typedef struct udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry;
+extern const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_msginit;
+extern const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_msginit;
+extern const upb_msglayout udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_msginit;
+
+
+/* udpa.data.orca.v1.OrcaLoadReport */
+
+UPB_INLINE udpa_data_orca_v1_OrcaLoadReport *udpa_data_orca_v1_OrcaLoadReport_new(upb_arena *arena) {
return (udpa_data_orca_v1_OrcaLoadReport *)_upb_msg_new(&udpa_data_orca_v1_OrcaLoadReport_msginit, arena);
-}
-UPB_INLINE udpa_data_orca_v1_OrcaLoadReport *udpa_data_orca_v1_OrcaLoadReport_parse(const char *buf, size_t size,
- upb_arena *arena) {
- udpa_data_orca_v1_OrcaLoadReport *ret = udpa_data_orca_v1_OrcaLoadReport_new(arena);
- return (ret && upb_decode(buf, size, ret, &udpa_data_orca_v1_OrcaLoadReport_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *udpa_data_orca_v1_OrcaLoadReport_serialize(const udpa_data_orca_v1_OrcaLoadReport *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &udpa_data_orca_v1_OrcaLoadReport_msginit, arena, len);
-}
-
+}
+UPB_INLINE udpa_data_orca_v1_OrcaLoadReport *udpa_data_orca_v1_OrcaLoadReport_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ udpa_data_orca_v1_OrcaLoadReport *ret = udpa_data_orca_v1_OrcaLoadReport_new(arena);
+ return (ret && upb_decode(buf, size, ret, &udpa_data_orca_v1_OrcaLoadReport_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *udpa_data_orca_v1_OrcaLoadReport_serialize(const udpa_data_orca_v1_OrcaLoadReport *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &udpa_data_orca_v1_OrcaLoadReport_msginit, arena, len);
+}
+
UPB_INLINE double udpa_data_orca_v1_OrcaLoadReport_cpu_utilization(const udpa_data_orca_v1_OrcaLoadReport *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), double); }
UPB_INLINE double udpa_data_orca_v1_OrcaLoadReport_mem_utilization(const udpa_data_orca_v1_OrcaLoadReport *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), double); }
UPB_INLINE uint64_t udpa_data_orca_v1_OrcaLoadReport_rps(const udpa_data_orca_v1_OrcaLoadReport *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t); }
@@ -55,16 +55,16 @@ UPB_INLINE bool udpa_data_orca_v1_OrcaLoadReport_has_utilization(const udpa_data
UPB_INLINE size_t udpa_data_orca_v1_OrcaLoadReport_utilization_size(const udpa_data_orca_v1_OrcaLoadReport *msg) {return _upb_msg_map_size(msg, UPB_SIZE(28, 32)); }
UPB_INLINE bool udpa_data_orca_v1_OrcaLoadReport_utilization_get(const udpa_data_orca_v1_OrcaLoadReport *msg, upb_strview key, double *val) { return _upb_msg_map_get(msg, UPB_SIZE(28, 32), &key, 0, val, sizeof(*val)); }
UPB_INLINE const udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry* udpa_data_orca_v1_OrcaLoadReport_utilization_next(const udpa_data_orca_v1_OrcaLoadReport *msg, size_t* iter) { return (const udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry*)_upb_msg_map_next(msg, UPB_SIZE(28, 32), iter); }
-
-UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_set_cpu_utilization(udpa_data_orca_v1_OrcaLoadReport *msg, double value) {
+
+UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_set_cpu_utilization(udpa_data_orca_v1_OrcaLoadReport *msg, double value) {
*UPB_PTR_AT(msg, UPB_SIZE(0, 0), double) = value;
-}
-UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_set_mem_utilization(udpa_data_orca_v1_OrcaLoadReport *msg, double value) {
+}
+UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_set_mem_utilization(udpa_data_orca_v1_OrcaLoadReport *msg, double value) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), double) = value;
-}
-UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_set_rps(udpa_data_orca_v1_OrcaLoadReport *msg, uint64_t value) {
+}
+UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_set_rps(udpa_data_orca_v1_OrcaLoadReport *msg, uint64_t value) {
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
+}
UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_request_cost_clear(udpa_data_orca_v1_OrcaLoadReport *msg) { _upb_msg_map_clear(msg, UPB_SIZE(24, 24)); }
UPB_INLINE bool udpa_data_orca_v1_OrcaLoadReport_request_cost_set(udpa_data_orca_v1_OrcaLoadReport *msg, upb_strview key, double val, upb_arena *a) { return _upb_msg_map_set(msg, UPB_SIZE(24, 24), &key, 0, &val, sizeof(val), a); }
UPB_INLINE bool udpa_data_orca_v1_OrcaLoadReport_request_cost_delete(udpa_data_orca_v1_OrcaLoadReport *msg, upb_strview key) { return _upb_msg_map_delete(msg, UPB_SIZE(24, 24), &key, 0); }
@@ -73,45 +73,45 @@ UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_utilization_clear(udpa_data_orc
UPB_INLINE bool udpa_data_orca_v1_OrcaLoadReport_utilization_set(udpa_data_orca_v1_OrcaLoadReport *msg, upb_strview key, double val, upb_arena *a) { return _upb_msg_map_set(msg, UPB_SIZE(28, 32), &key, 0, &val, sizeof(val), a); }
UPB_INLINE bool udpa_data_orca_v1_OrcaLoadReport_utilization_delete(udpa_data_orca_v1_OrcaLoadReport *msg, upb_strview key) { return _upb_msg_map_delete(msg, UPB_SIZE(28, 32), &key, 0); }
UPB_INLINE udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry* udpa_data_orca_v1_OrcaLoadReport_utilization_nextmutable(udpa_data_orca_v1_OrcaLoadReport *msg, size_t* iter) { return (udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry*)_upb_msg_map_next(msg, UPB_SIZE(28, 32), iter); }
-
-/* udpa.data.orca.v1.OrcaLoadReport.RequestCostEntry */
-
+
+/* udpa.data.orca.v1.OrcaLoadReport.RequestCostEntry */
+
UPB_INLINE upb_strview udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_key(const udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry *msg) {
upb_strview ret;
_upb_msg_map_key(msg, &ret, 0);
return ret;
-}
+}
UPB_INLINE double udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_value(const udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry *msg) {
double ret;
_upb_msg_map_value(msg, &ret, sizeof(ret));
return ret;
-}
-
-UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_set_value(udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry *msg, double value) {
+}
+
+UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_set_value(udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry *msg, double value) {
_upb_msg_map_set_value(msg, &value, sizeof(double));
-}
-
-/* udpa.data.orca.v1.OrcaLoadReport.UtilizationEntry */
-
+}
+
+/* udpa.data.orca.v1.OrcaLoadReport.UtilizationEntry */
+
UPB_INLINE upb_strview udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_key(const udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry *msg) {
upb_strview ret;
_upb_msg_map_key(msg, &ret, 0);
return ret;
-}
+}
UPB_INLINE double udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_value(const udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry *msg) {
double ret;
_upb_msg_map_value(msg, &ret, sizeof(ret));
return ret;
-}
-
-UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_set_value(udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry *msg, double value) {
+}
+
+UPB_INLINE void udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_set_value(udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry *msg, double value) {
_upb_msg_map_set_value(msg, &value, sizeof(double));
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* UDPA_DATA_ORCA_V1_ORCA_LOAD_REPORT_PROTO_UPB_H_ */
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* UDPA_DATA_ORCA_V1_ORCA_LOAD_REPORT_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.c b/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.c
index 63c324368d..39ffcd5a23 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.c
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.c
@@ -1,46 +1,46 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * validate/validate.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#include <stddef.h>
-#include "upb/msg.h"
-#include "validate/validate.upb.h"
-#include "google/protobuf/descriptor.upb.h"
-#include "google/protobuf/duration.upb.h"
-#include "google/protobuf/timestamp.upb.h"
-
-#include "upb/port_def.inc"
-
-static const upb_msglayout *const validate_FieldRules_submsgs[22] = {
- &validate_AnyRules_msginit,
- &validate_BoolRules_msginit,
- &validate_BytesRules_msginit,
- &validate_DoubleRules_msginit,
- &validate_DurationRules_msginit,
- &validate_EnumRules_msginit,
- &validate_Fixed32Rules_msginit,
- &validate_Fixed64Rules_msginit,
- &validate_FloatRules_msginit,
- &validate_Int32Rules_msginit,
- &validate_Int64Rules_msginit,
- &validate_MapRules_msginit,
- &validate_MessageRules_msginit,
- &validate_RepeatedRules_msginit,
- &validate_SFixed32Rules_msginit,
- &validate_SFixed64Rules_msginit,
- &validate_SInt32Rules_msginit,
- &validate_SInt64Rules_msginit,
- &validate_StringRules_msginit,
- &validate_TimestampRules_msginit,
- &validate_UInt32Rules_msginit,
- &validate_UInt64Rules_msginit,
-};
-
-static const upb_msglayout_field validate_FieldRules__fields[22] = {
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * validate/validate.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#include <stddef.h>
+#include "upb/msg.h"
+#include "validate/validate.upb.h"
+#include "google/protobuf/descriptor.upb.h"
+#include "google/protobuf/duration.upb.h"
+#include "google/protobuf/timestamp.upb.h"
+
+#include "upb/port_def.inc"
+
+static const upb_msglayout *const validate_FieldRules_submsgs[22] = {
+ &validate_AnyRules_msginit,
+ &validate_BoolRules_msginit,
+ &validate_BytesRules_msginit,
+ &validate_DoubleRules_msginit,
+ &validate_DurationRules_msginit,
+ &validate_EnumRules_msginit,
+ &validate_Fixed32Rules_msginit,
+ &validate_Fixed64Rules_msginit,
+ &validate_FloatRules_msginit,
+ &validate_Int32Rules_msginit,
+ &validate_Int64Rules_msginit,
+ &validate_MapRules_msginit,
+ &validate_MessageRules_msginit,
+ &validate_RepeatedRules_msginit,
+ &validate_SFixed32Rules_msginit,
+ &validate_SFixed64Rules_msginit,
+ &validate_SInt32Rules_msginit,
+ &validate_SInt64Rules_msginit,
+ &validate_StringRules_msginit,
+ &validate_TimestampRules_msginit,
+ &validate_UInt32Rules_msginit,
+ &validate_UInt64Rules_msginit,
+};
+
+static const upb_msglayout_field validate_FieldRules__fields[22] = {
{1, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 8, 11, 1},
{2, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 3, 11, 1},
{3, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 9, 11, 1},
@@ -63,222 +63,222 @@ static const upb_msglayout_field validate_FieldRules__fields[22] = {
{20, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 0, 11, 1},
{21, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 4, 11, 1},
{22, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 19, 11, 1},
-};
-
-const upb_msglayout validate_FieldRules_msginit = {
- &validate_FieldRules_submsgs[0],
- &validate_FieldRules__fields[0],
+};
+
+const upb_msglayout validate_FieldRules_msginit = {
+ &validate_FieldRules_submsgs[0],
+ &validate_FieldRules__fields[0],
UPB_SIZE(16, 32), 22, false,
-};
-
-static const upb_msglayout_field validate_FloatRules__fields[7] = {
- {1, UPB_SIZE(4, 4), 1, 0, 2, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 2, 1},
- {3, UPB_SIZE(12, 12), 3, 0, 2, 1},
- {4, UPB_SIZE(16, 16), 4, 0, 2, 1},
- {5, UPB_SIZE(20, 20), 5, 0, 2, 1},
- {6, UPB_SIZE(24, 24), 0, 0, 2, 3},
- {7, UPB_SIZE(28, 32), 0, 0, 2, 3},
-};
-
-const upb_msglayout validate_FloatRules_msginit = {
- NULL,
- &validate_FloatRules__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout_field validate_DoubleRules__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 1, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 1, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 1, 1},
- {4, UPB_SIZE(32, 32), 4, 0, 1, 1},
- {5, UPB_SIZE(40, 40), 5, 0, 1, 1},
- {6, UPB_SIZE(48, 48), 0, 0, 1, 3},
- {7, UPB_SIZE(52, 56), 0, 0, 1, 3},
-};
-
-const upb_msglayout validate_DoubleRules_msginit = {
- NULL,
- &validate_DoubleRules__fields[0],
- UPB_SIZE(56, 64), 7, false,
-};
-
-static const upb_msglayout_field validate_Int32Rules__fields[7] = {
- {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
- {3, UPB_SIZE(12, 12), 3, 0, 5, 1},
- {4, UPB_SIZE(16, 16), 4, 0, 5, 1},
- {5, UPB_SIZE(20, 20), 5, 0, 5, 1},
- {6, UPB_SIZE(24, 24), 0, 0, 5, 3},
- {7, UPB_SIZE(28, 32), 0, 0, 5, 3},
-};
-
-const upb_msglayout validate_Int32Rules_msginit = {
- NULL,
- &validate_Int32Rules__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout_field validate_Int64Rules__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 3, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 3, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 3, 1},
- {4, UPB_SIZE(32, 32), 4, 0, 3, 1},
- {5, UPB_SIZE(40, 40), 5, 0, 3, 1},
- {6, UPB_SIZE(48, 48), 0, 0, 3, 3},
- {7, UPB_SIZE(52, 56), 0, 0, 3, 3},
-};
-
-const upb_msglayout validate_Int64Rules_msginit = {
- NULL,
- &validate_Int64Rules__fields[0],
- UPB_SIZE(56, 64), 7, false,
-};
-
-static const upb_msglayout_field validate_UInt32Rules__fields[7] = {
- {1, UPB_SIZE(4, 4), 1, 0, 13, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 13, 1},
- {3, UPB_SIZE(12, 12), 3, 0, 13, 1},
- {4, UPB_SIZE(16, 16), 4, 0, 13, 1},
- {5, UPB_SIZE(20, 20), 5, 0, 13, 1},
- {6, UPB_SIZE(24, 24), 0, 0, 13, 3},
- {7, UPB_SIZE(28, 32), 0, 0, 13, 3},
-};
-
-const upb_msglayout validate_UInt32Rules_msginit = {
- NULL,
- &validate_UInt32Rules__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout_field validate_UInt64Rules__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 4, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 4, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 4, 1},
- {4, UPB_SIZE(32, 32), 4, 0, 4, 1},
- {5, UPB_SIZE(40, 40), 5, 0, 4, 1},
- {6, UPB_SIZE(48, 48), 0, 0, 4, 3},
- {7, UPB_SIZE(52, 56), 0, 0, 4, 3},
-};
-
-const upb_msglayout validate_UInt64Rules_msginit = {
- NULL,
- &validate_UInt64Rules__fields[0],
- UPB_SIZE(56, 64), 7, false,
-};
-
-static const upb_msglayout_field validate_SInt32Rules__fields[7] = {
- {1, UPB_SIZE(4, 4), 1, 0, 17, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 17, 1},
- {3, UPB_SIZE(12, 12), 3, 0, 17, 1},
- {4, UPB_SIZE(16, 16), 4, 0, 17, 1},
- {5, UPB_SIZE(20, 20), 5, 0, 17, 1},
- {6, UPB_SIZE(24, 24), 0, 0, 17, 3},
- {7, UPB_SIZE(28, 32), 0, 0, 17, 3},
-};
-
-const upb_msglayout validate_SInt32Rules_msginit = {
- NULL,
- &validate_SInt32Rules__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout_field validate_SInt64Rules__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 18, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 18, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 18, 1},
- {4, UPB_SIZE(32, 32), 4, 0, 18, 1},
- {5, UPB_SIZE(40, 40), 5, 0, 18, 1},
- {6, UPB_SIZE(48, 48), 0, 0, 18, 3},
- {7, UPB_SIZE(52, 56), 0, 0, 18, 3},
-};
-
-const upb_msglayout validate_SInt64Rules_msginit = {
- NULL,
- &validate_SInt64Rules__fields[0],
- UPB_SIZE(56, 64), 7, false,
-};
-
-static const upb_msglayout_field validate_Fixed32Rules__fields[7] = {
- {1, UPB_SIZE(4, 4), 1, 0, 7, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 7, 1},
- {3, UPB_SIZE(12, 12), 3, 0, 7, 1},
- {4, UPB_SIZE(16, 16), 4, 0, 7, 1},
- {5, UPB_SIZE(20, 20), 5, 0, 7, 1},
- {6, UPB_SIZE(24, 24), 0, 0, 7, 3},
- {7, UPB_SIZE(28, 32), 0, 0, 7, 3},
-};
-
-const upb_msglayout validate_Fixed32Rules_msginit = {
- NULL,
- &validate_Fixed32Rules__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout_field validate_Fixed64Rules__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 6, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 6, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 6, 1},
- {4, UPB_SIZE(32, 32), 4, 0, 6, 1},
- {5, UPB_SIZE(40, 40), 5, 0, 6, 1},
- {6, UPB_SIZE(48, 48), 0, 0, 6, 3},
- {7, UPB_SIZE(52, 56), 0, 0, 6, 3},
-};
-
-const upb_msglayout validate_Fixed64Rules_msginit = {
- NULL,
- &validate_Fixed64Rules__fields[0],
- UPB_SIZE(56, 64), 7, false,
-};
-
-static const upb_msglayout_field validate_SFixed32Rules__fields[7] = {
- {1, UPB_SIZE(4, 4), 1, 0, 15, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 15, 1},
- {3, UPB_SIZE(12, 12), 3, 0, 15, 1},
- {4, UPB_SIZE(16, 16), 4, 0, 15, 1},
- {5, UPB_SIZE(20, 20), 5, 0, 15, 1},
- {6, UPB_SIZE(24, 24), 0, 0, 15, 3},
- {7, UPB_SIZE(28, 32), 0, 0, 15, 3},
-};
-
-const upb_msglayout validate_SFixed32Rules_msginit = {
- NULL,
- &validate_SFixed32Rules__fields[0],
- UPB_SIZE(32, 40), 7, false,
-};
-
-static const upb_msglayout_field validate_SFixed64Rules__fields[7] = {
- {1, UPB_SIZE(8, 8), 1, 0, 16, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 16, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 16, 1},
- {4, UPB_SIZE(32, 32), 4, 0, 16, 1},
- {5, UPB_SIZE(40, 40), 5, 0, 16, 1},
- {6, UPB_SIZE(48, 48), 0, 0, 16, 3},
- {7, UPB_SIZE(52, 56), 0, 0, 16, 3},
-};
-
-const upb_msglayout validate_SFixed64Rules_msginit = {
- NULL,
- &validate_SFixed64Rules__fields[0],
- UPB_SIZE(56, 64), 7, false,
-};
-
-static const upb_msglayout_field validate_BoolRules__fields[1] = {
- {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
-};
-
-const upb_msglayout validate_BoolRules_msginit = {
- NULL,
- &validate_BoolRules__fields[0],
- UPB_SIZE(2, 2), 1, false,
-};
-
+};
+
+static const upb_msglayout_field validate_FloatRules__fields[7] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 2, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 2, 1},
+ {3, UPB_SIZE(12, 12), 3, 0, 2, 1},
+ {4, UPB_SIZE(16, 16), 4, 0, 2, 1},
+ {5, UPB_SIZE(20, 20), 5, 0, 2, 1},
+ {6, UPB_SIZE(24, 24), 0, 0, 2, 3},
+ {7, UPB_SIZE(28, 32), 0, 0, 2, 3},
+};
+
+const upb_msglayout validate_FloatRules_msginit = {
+ NULL,
+ &validate_FloatRules__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout_field validate_DoubleRules__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 1, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 1, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 1, 1},
+ {4, UPB_SIZE(32, 32), 4, 0, 1, 1},
+ {5, UPB_SIZE(40, 40), 5, 0, 1, 1},
+ {6, UPB_SIZE(48, 48), 0, 0, 1, 3},
+ {7, UPB_SIZE(52, 56), 0, 0, 1, 3},
+};
+
+const upb_msglayout validate_DoubleRules_msginit = {
+ NULL,
+ &validate_DoubleRules__fields[0],
+ UPB_SIZE(56, 64), 7, false,
+};
+
+static const upb_msglayout_field validate_Int32Rules__fields[7] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 5, 1},
+ {3, UPB_SIZE(12, 12), 3, 0, 5, 1},
+ {4, UPB_SIZE(16, 16), 4, 0, 5, 1},
+ {5, UPB_SIZE(20, 20), 5, 0, 5, 1},
+ {6, UPB_SIZE(24, 24), 0, 0, 5, 3},
+ {7, UPB_SIZE(28, 32), 0, 0, 5, 3},
+};
+
+const upb_msglayout validate_Int32Rules_msginit = {
+ NULL,
+ &validate_Int32Rules__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout_field validate_Int64Rules__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 3, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 3, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 3, 1},
+ {4, UPB_SIZE(32, 32), 4, 0, 3, 1},
+ {5, UPB_SIZE(40, 40), 5, 0, 3, 1},
+ {6, UPB_SIZE(48, 48), 0, 0, 3, 3},
+ {7, UPB_SIZE(52, 56), 0, 0, 3, 3},
+};
+
+const upb_msglayout validate_Int64Rules_msginit = {
+ NULL,
+ &validate_Int64Rules__fields[0],
+ UPB_SIZE(56, 64), 7, false,
+};
+
+static const upb_msglayout_field validate_UInt32Rules__fields[7] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 13, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 13, 1},
+ {3, UPB_SIZE(12, 12), 3, 0, 13, 1},
+ {4, UPB_SIZE(16, 16), 4, 0, 13, 1},
+ {5, UPB_SIZE(20, 20), 5, 0, 13, 1},
+ {6, UPB_SIZE(24, 24), 0, 0, 13, 3},
+ {7, UPB_SIZE(28, 32), 0, 0, 13, 3},
+};
+
+const upb_msglayout validate_UInt32Rules_msginit = {
+ NULL,
+ &validate_UInt32Rules__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout_field validate_UInt64Rules__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 4, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 4, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 4, 1},
+ {4, UPB_SIZE(32, 32), 4, 0, 4, 1},
+ {5, UPB_SIZE(40, 40), 5, 0, 4, 1},
+ {6, UPB_SIZE(48, 48), 0, 0, 4, 3},
+ {7, UPB_SIZE(52, 56), 0, 0, 4, 3},
+};
+
+const upb_msglayout validate_UInt64Rules_msginit = {
+ NULL,
+ &validate_UInt64Rules__fields[0],
+ UPB_SIZE(56, 64), 7, false,
+};
+
+static const upb_msglayout_field validate_SInt32Rules__fields[7] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 17, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 17, 1},
+ {3, UPB_SIZE(12, 12), 3, 0, 17, 1},
+ {4, UPB_SIZE(16, 16), 4, 0, 17, 1},
+ {5, UPB_SIZE(20, 20), 5, 0, 17, 1},
+ {6, UPB_SIZE(24, 24), 0, 0, 17, 3},
+ {7, UPB_SIZE(28, 32), 0, 0, 17, 3},
+};
+
+const upb_msglayout validate_SInt32Rules_msginit = {
+ NULL,
+ &validate_SInt32Rules__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout_field validate_SInt64Rules__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 18, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 18, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 18, 1},
+ {4, UPB_SIZE(32, 32), 4, 0, 18, 1},
+ {5, UPB_SIZE(40, 40), 5, 0, 18, 1},
+ {6, UPB_SIZE(48, 48), 0, 0, 18, 3},
+ {7, UPB_SIZE(52, 56), 0, 0, 18, 3},
+};
+
+const upb_msglayout validate_SInt64Rules_msginit = {
+ NULL,
+ &validate_SInt64Rules__fields[0],
+ UPB_SIZE(56, 64), 7, false,
+};
+
+static const upb_msglayout_field validate_Fixed32Rules__fields[7] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 7, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 7, 1},
+ {3, UPB_SIZE(12, 12), 3, 0, 7, 1},
+ {4, UPB_SIZE(16, 16), 4, 0, 7, 1},
+ {5, UPB_SIZE(20, 20), 5, 0, 7, 1},
+ {6, UPB_SIZE(24, 24), 0, 0, 7, 3},
+ {7, UPB_SIZE(28, 32), 0, 0, 7, 3},
+};
+
+const upb_msglayout validate_Fixed32Rules_msginit = {
+ NULL,
+ &validate_Fixed32Rules__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout_field validate_Fixed64Rules__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 6, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 6, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 6, 1},
+ {4, UPB_SIZE(32, 32), 4, 0, 6, 1},
+ {5, UPB_SIZE(40, 40), 5, 0, 6, 1},
+ {6, UPB_SIZE(48, 48), 0, 0, 6, 3},
+ {7, UPB_SIZE(52, 56), 0, 0, 6, 3},
+};
+
+const upb_msglayout validate_Fixed64Rules_msginit = {
+ NULL,
+ &validate_Fixed64Rules__fields[0],
+ UPB_SIZE(56, 64), 7, false,
+};
+
+static const upb_msglayout_field validate_SFixed32Rules__fields[7] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 15, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 15, 1},
+ {3, UPB_SIZE(12, 12), 3, 0, 15, 1},
+ {4, UPB_SIZE(16, 16), 4, 0, 15, 1},
+ {5, UPB_SIZE(20, 20), 5, 0, 15, 1},
+ {6, UPB_SIZE(24, 24), 0, 0, 15, 3},
+ {7, UPB_SIZE(28, 32), 0, 0, 15, 3},
+};
+
+const upb_msglayout validate_SFixed32Rules_msginit = {
+ NULL,
+ &validate_SFixed32Rules__fields[0],
+ UPB_SIZE(32, 40), 7, false,
+};
+
+static const upb_msglayout_field validate_SFixed64Rules__fields[7] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 16, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 16, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 16, 1},
+ {4, UPB_SIZE(32, 32), 4, 0, 16, 1},
+ {5, UPB_SIZE(40, 40), 5, 0, 16, 1},
+ {6, UPB_SIZE(48, 48), 0, 0, 16, 3},
+ {7, UPB_SIZE(52, 56), 0, 0, 16, 3},
+};
+
+const upb_msglayout validate_SFixed64Rules_msginit = {
+ NULL,
+ &validate_SFixed64Rules__fields[0],
+ UPB_SIZE(56, 64), 7, false,
+};
+
+static const upb_msglayout_field validate_BoolRules__fields[1] = {
+ {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
+};
+
+const upb_msglayout validate_BoolRules_msginit = {
+ NULL,
+ &validate_BoolRules__fields[0],
+ UPB_SIZE(2, 2), 1, false,
+};
+
static const upb_msglayout_field validate_StringRules__fields[25] = {
{1, UPB_SIZE(60, 64), 8, 0, 12, 1},
- {2, UPB_SIZE(8, 8), 1, 0, 4, 1},
- {3, UPB_SIZE(16, 16), 2, 0, 4, 1},
- {4, UPB_SIZE(24, 24), 3, 0, 4, 1},
- {5, UPB_SIZE(32, 32), 4, 0, 4, 1},
+ {2, UPB_SIZE(8, 8), 1, 0, 4, 1},
+ {3, UPB_SIZE(16, 16), 2, 0, 4, 1},
+ {4, UPB_SIZE(24, 24), 3, 0, 4, 1},
+ {5, UPB_SIZE(32, 32), 4, 0, 4, 1},
{6, UPB_SIZE(68, 80), 9, 0, 12, 1},
{7, UPB_SIZE(76, 96), 10, 0, 12, 1},
{8, UPB_SIZE(84, 112), 11, 0, 12, 1},
@@ -292,157 +292,157 @@ static const upb_msglayout_field validate_StringRules__fields[25] = {
{16, UPB_SIZE(120, 176), UPB_SIZE(-129, -185), 0, 8, 1},
{17, UPB_SIZE(120, 176), UPB_SIZE(-129, -185), 0, 8, 1},
{18, UPB_SIZE(120, 176), UPB_SIZE(-129, -185), 0, 8, 1},
- {19, UPB_SIZE(40, 40), 5, 0, 4, 1},
- {20, UPB_SIZE(48, 48), 6, 0, 4, 1},
+ {19, UPB_SIZE(40, 40), 5, 0, 4, 1},
+ {20, UPB_SIZE(48, 48), 6, 0, 4, 1},
{21, UPB_SIZE(120, 176), UPB_SIZE(-129, -185), 0, 8, 1},
{22, UPB_SIZE(120, 176), UPB_SIZE(-129, -185), 0, 8, 1},
{23, UPB_SIZE(100, 144), 13, 0, 12, 1},
{24, UPB_SIZE(120, 176), UPB_SIZE(-129, -185), 0, 14, 1},
{25, UPB_SIZE(56, 56), 7, 0, 8, 1},
-};
-
-const upb_msglayout validate_StringRules_msginit = {
- NULL,
- &validate_StringRules__fields[0],
+};
+
+const upb_msglayout validate_StringRules_msginit = {
+ NULL,
+ &validate_StringRules__fields[0],
UPB_SIZE(136, 192), 25, false,
-};
-
-static const upb_msglayout_field validate_BytesRules__fields[13] = {
- {1, UPB_SIZE(32, 32), 4, 0, 12, 1},
- {2, UPB_SIZE(8, 8), 1, 0, 4, 1},
- {3, UPB_SIZE(16, 16), 2, 0, 4, 1},
+};
+
+static const upb_msglayout_field validate_BytesRules__fields[13] = {
+ {1, UPB_SIZE(32, 32), 4, 0, 12, 1},
+ {2, UPB_SIZE(8, 8), 1, 0, 4, 1},
+ {3, UPB_SIZE(16, 16), 2, 0, 4, 1},
{4, UPB_SIZE(40, 48), 5, 0, 12, 1},
- {5, UPB_SIZE(48, 64), 6, 0, 12, 1},
- {6, UPB_SIZE(56, 80), 7, 0, 12, 1},
- {7, UPB_SIZE(64, 96), 8, 0, 12, 1},
- {8, UPB_SIZE(72, 112), 0, 0, 12, 3},
- {9, UPB_SIZE(76, 120), 0, 0, 12, 3},
- {10, UPB_SIZE(80, 128), UPB_SIZE(-85, -133), 0, 8, 1},
- {11, UPB_SIZE(80, 128), UPB_SIZE(-85, -133), 0, 8, 1},
- {12, UPB_SIZE(80, 128), UPB_SIZE(-85, -133), 0, 8, 1},
- {13, UPB_SIZE(24, 24), 3, 0, 4, 1},
-};
-
-const upb_msglayout validate_BytesRules_msginit = {
- NULL,
- &validate_BytesRules__fields[0],
- UPB_SIZE(88, 144), 13, false,
-};
-
-static const upb_msglayout_field validate_EnumRules__fields[4] = {
- {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
- {2, UPB_SIZE(8, 8), 2, 0, 8, 1},
- {3, UPB_SIZE(12, 16), 0, 0, 5, 3},
- {4, UPB_SIZE(16, 24), 0, 0, 5, 3},
-};
-
-const upb_msglayout validate_EnumRules_msginit = {
- NULL,
- &validate_EnumRules__fields[0],
- UPB_SIZE(20, 32), 4, false,
-};
-
-static const upb_msglayout_field validate_MessageRules__fields[2] = {
- {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
-};
-
-const upb_msglayout validate_MessageRules_msginit = {
- NULL,
- &validate_MessageRules__fields[0],
- UPB_SIZE(3, 3), 2, false,
-};
-
-static const upb_msglayout *const validate_RepeatedRules_submsgs[1] = {
- &validate_FieldRules_msginit,
-};
-
-static const upb_msglayout_field validate_RepeatedRules__fields[4] = {
- {1, UPB_SIZE(8, 8), 1, 0, 4, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 4, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 8, 1},
- {4, UPB_SIZE(28, 32), 4, 0, 11, 1},
-};
-
-const upb_msglayout validate_RepeatedRules_msginit = {
- &validate_RepeatedRules_submsgs[0],
- &validate_RepeatedRules__fields[0],
- UPB_SIZE(32, 40), 4, false,
-};
-
-static const upb_msglayout *const validate_MapRules_submsgs[2] = {
- &validate_FieldRules_msginit,
-};
-
-static const upb_msglayout_field validate_MapRules__fields[5] = {
- {1, UPB_SIZE(8, 8), 1, 0, 4, 1},
- {2, UPB_SIZE(16, 16), 2, 0, 4, 1},
- {3, UPB_SIZE(24, 24), 3, 0, 8, 1},
- {4, UPB_SIZE(28, 32), 4, 0, 11, 1},
- {5, UPB_SIZE(32, 40), 5, 0, 11, 1},
-};
-
-const upb_msglayout validate_MapRules_msginit = {
- &validate_MapRules_submsgs[0],
- &validate_MapRules__fields[0],
- UPB_SIZE(40, 48), 5, false,
-};
-
-static const upb_msglayout_field validate_AnyRules__fields[3] = {
- {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {5, UPB_SIZE(48, 64), 6, 0, 12, 1},
+ {6, UPB_SIZE(56, 80), 7, 0, 12, 1},
+ {7, UPB_SIZE(64, 96), 8, 0, 12, 1},
+ {8, UPB_SIZE(72, 112), 0, 0, 12, 3},
+ {9, UPB_SIZE(76, 120), 0, 0, 12, 3},
+ {10, UPB_SIZE(80, 128), UPB_SIZE(-85, -133), 0, 8, 1},
+ {11, UPB_SIZE(80, 128), UPB_SIZE(-85, -133), 0, 8, 1},
+ {12, UPB_SIZE(80, 128), UPB_SIZE(-85, -133), 0, 8, 1},
+ {13, UPB_SIZE(24, 24), 3, 0, 4, 1},
+};
+
+const upb_msglayout validate_BytesRules_msginit = {
+ NULL,
+ &validate_BytesRules__fields[0],
+ UPB_SIZE(88, 144), 13, false,
+};
+
+static const upb_msglayout_field validate_EnumRules__fields[4] = {
+ {1, UPB_SIZE(4, 4), 1, 0, 5, 1},
+ {2, UPB_SIZE(8, 8), 2, 0, 8, 1},
+ {3, UPB_SIZE(12, 16), 0, 0, 5, 3},
+ {4, UPB_SIZE(16, 24), 0, 0, 5, 3},
+};
+
+const upb_msglayout validate_EnumRules_msginit = {
+ NULL,
+ &validate_EnumRules__fields[0],
+ UPB_SIZE(20, 32), 4, false,
+};
+
+static const upb_msglayout_field validate_MessageRules__fields[2] = {
+ {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {2, UPB_SIZE(2, 2), 2, 0, 8, 1},
+};
+
+const upb_msglayout validate_MessageRules_msginit = {
+ NULL,
+ &validate_MessageRules__fields[0],
+ UPB_SIZE(3, 3), 2, false,
+};
+
+static const upb_msglayout *const validate_RepeatedRules_submsgs[1] = {
+ &validate_FieldRules_msginit,
+};
+
+static const upb_msglayout_field validate_RepeatedRules__fields[4] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 4, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 4, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 8, 1},
+ {4, UPB_SIZE(28, 32), 4, 0, 11, 1},
+};
+
+const upb_msglayout validate_RepeatedRules_msginit = {
+ &validate_RepeatedRules_submsgs[0],
+ &validate_RepeatedRules__fields[0],
+ UPB_SIZE(32, 40), 4, false,
+};
+
+static const upb_msglayout *const validate_MapRules_submsgs[2] = {
+ &validate_FieldRules_msginit,
+};
+
+static const upb_msglayout_field validate_MapRules__fields[5] = {
+ {1, UPB_SIZE(8, 8), 1, 0, 4, 1},
+ {2, UPB_SIZE(16, 16), 2, 0, 4, 1},
+ {3, UPB_SIZE(24, 24), 3, 0, 8, 1},
+ {4, UPB_SIZE(28, 32), 4, 0, 11, 1},
+ {5, UPB_SIZE(32, 40), 5, 0, 11, 1},
+};
+
+const upb_msglayout validate_MapRules_msginit = {
+ &validate_MapRules_submsgs[0],
+ &validate_MapRules__fields[0],
+ UPB_SIZE(40, 48), 5, false,
+};
+
+static const upb_msglayout_field validate_AnyRules__fields[3] = {
+ {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
{2, UPB_SIZE(4, 8), 0, 0, 12, 3},
{3, UPB_SIZE(8, 16), 0, 0, 12, 3},
-};
-
-const upb_msglayout validate_AnyRules_msginit = {
- NULL,
- &validate_AnyRules__fields[0],
- UPB_SIZE(12, 24), 3, false,
-};
-
-static const upb_msglayout *const validate_DurationRules_submsgs[7] = {
- &google_protobuf_Duration_msginit,
-};
-
-static const upb_msglayout_field validate_DurationRules__fields[8] = {
- {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
- {2, UPB_SIZE(4, 8), 2, 0, 11, 1},
- {3, UPB_SIZE(8, 16), 3, 0, 11, 1},
- {4, UPB_SIZE(12, 24), 4, 0, 11, 1},
- {5, UPB_SIZE(16, 32), 5, 0, 11, 1},
- {6, UPB_SIZE(20, 40), 6, 0, 11, 1},
- {7, UPB_SIZE(24, 48), 0, 0, 11, 3},
- {8, UPB_SIZE(28, 56), 0, 0, 11, 3},
-};
-
-const upb_msglayout validate_DurationRules_msginit = {
- &validate_DurationRules_submsgs[0],
- &validate_DurationRules__fields[0],
- UPB_SIZE(32, 64), 8, false,
-};
-
-static const upb_msglayout *const validate_TimestampRules_submsgs[6] = {
- &google_protobuf_Duration_msginit,
- &google_protobuf_Timestamp_msginit,
-};
-
-static const upb_msglayout_field validate_TimestampRules__fields[9] = {
- {1, UPB_SIZE(2, 2), 1, 0, 8, 1},
- {2, UPB_SIZE(8, 8), 4, 1, 11, 1},
- {3, UPB_SIZE(12, 16), 5, 1, 11, 1},
- {4, UPB_SIZE(16, 24), 6, 1, 11, 1},
- {5, UPB_SIZE(20, 32), 7, 1, 11, 1},
- {6, UPB_SIZE(24, 40), 8, 1, 11, 1},
- {7, UPB_SIZE(3, 3), 2, 0, 8, 1},
- {8, UPB_SIZE(4, 4), 3, 0, 8, 1},
- {9, UPB_SIZE(28, 48), 9, 0, 11, 1},
-};
-
-const upb_msglayout validate_TimestampRules_msginit = {
- &validate_TimestampRules_submsgs[0],
- &validate_TimestampRules__fields[0],
- UPB_SIZE(32, 56), 9, false,
-};
-
-#include "upb/port_undef.inc"
-
+};
+
+const upb_msglayout validate_AnyRules_msginit = {
+ NULL,
+ &validate_AnyRules__fields[0],
+ UPB_SIZE(12, 24), 3, false,
+};
+
+static const upb_msglayout *const validate_DurationRules_submsgs[7] = {
+ &google_protobuf_Duration_msginit,
+};
+
+static const upb_msglayout_field validate_DurationRules__fields[8] = {
+ {1, UPB_SIZE(1, 1), 1, 0, 8, 1},
+ {2, UPB_SIZE(4, 8), 2, 0, 11, 1},
+ {3, UPB_SIZE(8, 16), 3, 0, 11, 1},
+ {4, UPB_SIZE(12, 24), 4, 0, 11, 1},
+ {5, UPB_SIZE(16, 32), 5, 0, 11, 1},
+ {6, UPB_SIZE(20, 40), 6, 0, 11, 1},
+ {7, UPB_SIZE(24, 48), 0, 0, 11, 3},
+ {8, UPB_SIZE(28, 56), 0, 0, 11, 3},
+};
+
+const upb_msglayout validate_DurationRules_msginit = {
+ &validate_DurationRules_submsgs[0],
+ &validate_DurationRules__fields[0],
+ UPB_SIZE(32, 64), 8, false,
+};
+
+static const upb_msglayout *const validate_TimestampRules_submsgs[6] = {
+ &google_protobuf_Duration_msginit,
+ &google_protobuf_Timestamp_msginit,
+};
+
+static const upb_msglayout_field validate_TimestampRules__fields[9] = {
+ {1, UPB_SIZE(2, 2), 1, 0, 8, 1},
+ {2, UPB_SIZE(8, 8), 4, 1, 11, 1},
+ {3, UPB_SIZE(12, 16), 5, 1, 11, 1},
+ {4, UPB_SIZE(16, 24), 6, 1, 11, 1},
+ {5, UPB_SIZE(20, 32), 7, 1, 11, 1},
+ {6, UPB_SIZE(24, 40), 8, 1, 11, 1},
+ {7, UPB_SIZE(3, 3), 2, 0, 8, 1},
+ {8, UPB_SIZE(4, 4), 3, 0, 8, 1},
+ {9, UPB_SIZE(28, 48), 9, 0, 11, 1},
+};
+
+const upb_msglayout validate_TimestampRules_msginit = {
+ &validate_TimestampRules_submsgs[0],
+ &validate_TimestampRules__fields[0],
+ UPB_SIZE(32, 56), 9, false,
+};
+
+#include "upb/port_undef.inc"
+
diff --git a/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.h b/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.h
index c29b4ec589..8f2bdc4926 100644
--- a/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.h
+++ b/contrib/libs/grpc/src/core/ext/upb-generated/validate/validate.upb.h
@@ -1,145 +1,145 @@
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * validate/validate.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-
-#ifndef VALIDATE_VALIDATE_PROTO_UPB_H_
-#define VALIDATE_VALIDATE_PROTO_UPB_H_
-
-#include "upb/msg.h"
-#include "upb/decode.h"
-#include "upb/encode.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct validate_FieldRules;
-struct validate_FloatRules;
-struct validate_DoubleRules;
-struct validate_Int32Rules;
-struct validate_Int64Rules;
-struct validate_UInt32Rules;
-struct validate_UInt64Rules;
-struct validate_SInt32Rules;
-struct validate_SInt64Rules;
-struct validate_Fixed32Rules;
-struct validate_Fixed64Rules;
-struct validate_SFixed32Rules;
-struct validate_SFixed64Rules;
-struct validate_BoolRules;
-struct validate_StringRules;
-struct validate_BytesRules;
-struct validate_EnumRules;
-struct validate_MessageRules;
-struct validate_RepeatedRules;
-struct validate_MapRules;
-struct validate_AnyRules;
-struct validate_DurationRules;
-struct validate_TimestampRules;
-typedef struct validate_FieldRules validate_FieldRules;
-typedef struct validate_FloatRules validate_FloatRules;
-typedef struct validate_DoubleRules validate_DoubleRules;
-typedef struct validate_Int32Rules validate_Int32Rules;
-typedef struct validate_Int64Rules validate_Int64Rules;
-typedef struct validate_UInt32Rules validate_UInt32Rules;
-typedef struct validate_UInt64Rules validate_UInt64Rules;
-typedef struct validate_SInt32Rules validate_SInt32Rules;
-typedef struct validate_SInt64Rules validate_SInt64Rules;
-typedef struct validate_Fixed32Rules validate_Fixed32Rules;
-typedef struct validate_Fixed64Rules validate_Fixed64Rules;
-typedef struct validate_SFixed32Rules validate_SFixed32Rules;
-typedef struct validate_SFixed64Rules validate_SFixed64Rules;
-typedef struct validate_BoolRules validate_BoolRules;
-typedef struct validate_StringRules validate_StringRules;
-typedef struct validate_BytesRules validate_BytesRules;
-typedef struct validate_EnumRules validate_EnumRules;
-typedef struct validate_MessageRules validate_MessageRules;
-typedef struct validate_RepeatedRules validate_RepeatedRules;
-typedef struct validate_MapRules validate_MapRules;
-typedef struct validate_AnyRules validate_AnyRules;
-typedef struct validate_DurationRules validate_DurationRules;
-typedef struct validate_TimestampRules validate_TimestampRules;
-extern const upb_msglayout validate_FieldRules_msginit;
-extern const upb_msglayout validate_FloatRules_msginit;
-extern const upb_msglayout validate_DoubleRules_msginit;
-extern const upb_msglayout validate_Int32Rules_msginit;
-extern const upb_msglayout validate_Int64Rules_msginit;
-extern const upb_msglayout validate_UInt32Rules_msginit;
-extern const upb_msglayout validate_UInt64Rules_msginit;
-extern const upb_msglayout validate_SInt32Rules_msginit;
-extern const upb_msglayout validate_SInt64Rules_msginit;
-extern const upb_msglayout validate_Fixed32Rules_msginit;
-extern const upb_msglayout validate_Fixed64Rules_msginit;
-extern const upb_msglayout validate_SFixed32Rules_msginit;
-extern const upb_msglayout validate_SFixed64Rules_msginit;
-extern const upb_msglayout validate_BoolRules_msginit;
-extern const upb_msglayout validate_StringRules_msginit;
-extern const upb_msglayout validate_BytesRules_msginit;
-extern const upb_msglayout validate_EnumRules_msginit;
-extern const upb_msglayout validate_MessageRules_msginit;
-extern const upb_msglayout validate_RepeatedRules_msginit;
-extern const upb_msglayout validate_MapRules_msginit;
-extern const upb_msglayout validate_AnyRules_msginit;
-extern const upb_msglayout validate_DurationRules_msginit;
-extern const upb_msglayout validate_TimestampRules_msginit;
-struct google_protobuf_Duration;
-struct google_protobuf_Timestamp;
-extern const upb_msglayout google_protobuf_Duration_msginit;
-extern const upb_msglayout google_protobuf_Timestamp_msginit;
-
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * validate/validate.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef VALIDATE_VALIDATE_PROTO_UPB_H_
+#define VALIDATE_VALIDATE_PROTO_UPB_H_
+
+#include "upb/msg.h"
+#include "upb/decode.h"
+#include "upb/encode.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct validate_FieldRules;
+struct validate_FloatRules;
+struct validate_DoubleRules;
+struct validate_Int32Rules;
+struct validate_Int64Rules;
+struct validate_UInt32Rules;
+struct validate_UInt64Rules;
+struct validate_SInt32Rules;
+struct validate_SInt64Rules;
+struct validate_Fixed32Rules;
+struct validate_Fixed64Rules;
+struct validate_SFixed32Rules;
+struct validate_SFixed64Rules;
+struct validate_BoolRules;
+struct validate_StringRules;
+struct validate_BytesRules;
+struct validate_EnumRules;
+struct validate_MessageRules;
+struct validate_RepeatedRules;
+struct validate_MapRules;
+struct validate_AnyRules;
+struct validate_DurationRules;
+struct validate_TimestampRules;
+typedef struct validate_FieldRules validate_FieldRules;
+typedef struct validate_FloatRules validate_FloatRules;
+typedef struct validate_DoubleRules validate_DoubleRules;
+typedef struct validate_Int32Rules validate_Int32Rules;
+typedef struct validate_Int64Rules validate_Int64Rules;
+typedef struct validate_UInt32Rules validate_UInt32Rules;
+typedef struct validate_UInt64Rules validate_UInt64Rules;
+typedef struct validate_SInt32Rules validate_SInt32Rules;
+typedef struct validate_SInt64Rules validate_SInt64Rules;
+typedef struct validate_Fixed32Rules validate_Fixed32Rules;
+typedef struct validate_Fixed64Rules validate_Fixed64Rules;
+typedef struct validate_SFixed32Rules validate_SFixed32Rules;
+typedef struct validate_SFixed64Rules validate_SFixed64Rules;
+typedef struct validate_BoolRules validate_BoolRules;
+typedef struct validate_StringRules validate_StringRules;
+typedef struct validate_BytesRules validate_BytesRules;
+typedef struct validate_EnumRules validate_EnumRules;
+typedef struct validate_MessageRules validate_MessageRules;
+typedef struct validate_RepeatedRules validate_RepeatedRules;
+typedef struct validate_MapRules validate_MapRules;
+typedef struct validate_AnyRules validate_AnyRules;
+typedef struct validate_DurationRules validate_DurationRules;
+typedef struct validate_TimestampRules validate_TimestampRules;
+extern const upb_msglayout validate_FieldRules_msginit;
+extern const upb_msglayout validate_FloatRules_msginit;
+extern const upb_msglayout validate_DoubleRules_msginit;
+extern const upb_msglayout validate_Int32Rules_msginit;
+extern const upb_msglayout validate_Int64Rules_msginit;
+extern const upb_msglayout validate_UInt32Rules_msginit;
+extern const upb_msglayout validate_UInt64Rules_msginit;
+extern const upb_msglayout validate_SInt32Rules_msginit;
+extern const upb_msglayout validate_SInt64Rules_msginit;
+extern const upb_msglayout validate_Fixed32Rules_msginit;
+extern const upb_msglayout validate_Fixed64Rules_msginit;
+extern const upb_msglayout validate_SFixed32Rules_msginit;
+extern const upb_msglayout validate_SFixed64Rules_msginit;
+extern const upb_msglayout validate_BoolRules_msginit;
+extern const upb_msglayout validate_StringRules_msginit;
+extern const upb_msglayout validate_BytesRules_msginit;
+extern const upb_msglayout validate_EnumRules_msginit;
+extern const upb_msglayout validate_MessageRules_msginit;
+extern const upb_msglayout validate_RepeatedRules_msginit;
+extern const upb_msglayout validate_MapRules_msginit;
+extern const upb_msglayout validate_AnyRules_msginit;
+extern const upb_msglayout validate_DurationRules_msginit;
+extern const upb_msglayout validate_TimestampRules_msginit;
+struct google_protobuf_Duration;
+struct google_protobuf_Timestamp;
+extern const upb_msglayout google_protobuf_Duration_msginit;
+extern const upb_msglayout google_protobuf_Timestamp_msginit;
+
typedef enum {
validate_UNKNOWN = 0,
validate_HTTP_HEADER_NAME = 1,
validate_HTTP_HEADER_VALUE = 2
} validate_KnownRegex;
+
-
-/* validate.FieldRules */
-
-UPB_INLINE validate_FieldRules *validate_FieldRules_new(upb_arena *arena) {
+/* validate.FieldRules */
+
+UPB_INLINE validate_FieldRules *validate_FieldRules_new(upb_arena *arena) {
return (validate_FieldRules *)_upb_msg_new(&validate_FieldRules_msginit, arena);
-}
-UPB_INLINE validate_FieldRules *validate_FieldRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_FieldRules *ret = validate_FieldRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_FieldRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_FieldRules_serialize(const validate_FieldRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_FieldRules_msginit, arena, len);
-}
-
-typedef enum {
- validate_FieldRules_type_float = 1,
- validate_FieldRules_type_double = 2,
- validate_FieldRules_type_int32 = 3,
- validate_FieldRules_type_int64 = 4,
- validate_FieldRules_type_uint32 = 5,
- validate_FieldRules_type_uint64 = 6,
- validate_FieldRules_type_sint32 = 7,
- validate_FieldRules_type_sint64 = 8,
- validate_FieldRules_type_fixed32 = 9,
- validate_FieldRules_type_fixed64 = 10,
- validate_FieldRules_type_sfixed32 = 11,
- validate_FieldRules_type_sfixed64 = 12,
- validate_FieldRules_type_bool = 13,
- validate_FieldRules_type_string = 14,
- validate_FieldRules_type_bytes = 15,
- validate_FieldRules_type_enum = 16,
- validate_FieldRules_type_repeated = 18,
- validate_FieldRules_type_map = 19,
- validate_FieldRules_type_any = 20,
- validate_FieldRules_type_duration = 21,
- validate_FieldRules_type_timestamp = 22,
- validate_FieldRules_type_NOT_SET = 0
-} validate_FieldRules_type_oneofcases;
+}
+UPB_INLINE validate_FieldRules *validate_FieldRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_FieldRules *ret = validate_FieldRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_FieldRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_FieldRules_serialize(const validate_FieldRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_FieldRules_msginit, arena, len);
+}
+
+typedef enum {
+ validate_FieldRules_type_float = 1,
+ validate_FieldRules_type_double = 2,
+ validate_FieldRules_type_int32 = 3,
+ validate_FieldRules_type_int64 = 4,
+ validate_FieldRules_type_uint32 = 5,
+ validate_FieldRules_type_uint64 = 6,
+ validate_FieldRules_type_sint32 = 7,
+ validate_FieldRules_type_sint64 = 8,
+ validate_FieldRules_type_fixed32 = 9,
+ validate_FieldRules_type_fixed64 = 10,
+ validate_FieldRules_type_sfixed32 = 11,
+ validate_FieldRules_type_sfixed64 = 12,
+ validate_FieldRules_type_bool = 13,
+ validate_FieldRules_type_string = 14,
+ validate_FieldRules_type_bytes = 15,
+ validate_FieldRules_type_enum = 16,
+ validate_FieldRules_type_repeated = 18,
+ validate_FieldRules_type_map = 19,
+ validate_FieldRules_type_any = 20,
+ validate_FieldRules_type_duration = 21,
+ validate_FieldRules_type_timestamp = 22,
+ validate_FieldRules_type_NOT_SET = 0
+} validate_FieldRules_type_oneofcases;
UPB_INLINE validate_FieldRules_type_oneofcases validate_FieldRules_type_case(const validate_FieldRules* msg) { return (validate_FieldRules_type_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(12, 24), int32_t); }
-
+
UPB_INLINE bool validate_FieldRules_has_float(const validate_FieldRules *msg) { return _upb_getoneofcase(msg, UPB_SIZE(12, 24)) == 1; }
UPB_INLINE const validate_FloatRules* validate_FieldRules_float(const validate_FieldRules *msg) { return UPB_READ_ONEOF(msg, const validate_FloatRules*, UPB_SIZE(8, 16), UPB_SIZE(12, 24), 1, NULL); }
UPB_INLINE bool validate_FieldRules_has_double(const validate_FieldRules *msg) { return _upb_getoneofcase(msg, UPB_SIZE(12, 24)) == 2; }
@@ -184,287 +184,287 @@ UPB_INLINE bool validate_FieldRules_has_duration(const validate_FieldRules *msg)
UPB_INLINE const validate_DurationRules* validate_FieldRules_duration(const validate_FieldRules *msg) { return UPB_READ_ONEOF(msg, const validate_DurationRules*, UPB_SIZE(8, 16), UPB_SIZE(12, 24), 21, NULL); }
UPB_INLINE bool validate_FieldRules_has_timestamp(const validate_FieldRules *msg) { return _upb_getoneofcase(msg, UPB_SIZE(12, 24)) == 22; }
UPB_INLINE const validate_TimestampRules* validate_FieldRules_timestamp(const validate_FieldRules *msg) { return UPB_READ_ONEOF(msg, const validate_TimestampRules*, UPB_SIZE(8, 16), UPB_SIZE(12, 24), 22, NULL); }
-
-UPB_INLINE void validate_FieldRules_set_float(validate_FieldRules *msg, validate_FloatRules* value) {
+
+UPB_INLINE void validate_FieldRules_set_float(validate_FieldRules *msg, validate_FloatRules* value) {
UPB_WRITE_ONEOF(msg, validate_FloatRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 1);
-}
-UPB_INLINE struct validate_FloatRules* validate_FieldRules_mutable_float(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_FloatRules* sub = (struct validate_FloatRules*)validate_FieldRules_float(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_FloatRules* validate_FieldRules_mutable_float(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_FloatRules* sub = (struct validate_FloatRules*)validate_FieldRules_float(msg);
+ if (sub == NULL) {
sub = (struct validate_FloatRules*)_upb_msg_new(&validate_FloatRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_float(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_double(validate_FieldRules *msg, validate_DoubleRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_float(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_double(validate_FieldRules *msg, validate_DoubleRules* value) {
UPB_WRITE_ONEOF(msg, validate_DoubleRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 2);
-}
-UPB_INLINE struct validate_DoubleRules* validate_FieldRules_mutable_double(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_DoubleRules* sub = (struct validate_DoubleRules*)validate_FieldRules_double(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_DoubleRules* validate_FieldRules_mutable_double(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_DoubleRules* sub = (struct validate_DoubleRules*)validate_FieldRules_double(msg);
+ if (sub == NULL) {
sub = (struct validate_DoubleRules*)_upb_msg_new(&validate_DoubleRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_double(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_int32(validate_FieldRules *msg, validate_Int32Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_double(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_int32(validate_FieldRules *msg, validate_Int32Rules* value) {
UPB_WRITE_ONEOF(msg, validate_Int32Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 3);
-}
-UPB_INLINE struct validate_Int32Rules* validate_FieldRules_mutable_int32(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_Int32Rules* sub = (struct validate_Int32Rules*)validate_FieldRules_int32(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_Int32Rules* validate_FieldRules_mutable_int32(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_Int32Rules* sub = (struct validate_Int32Rules*)validate_FieldRules_int32(msg);
+ if (sub == NULL) {
sub = (struct validate_Int32Rules*)_upb_msg_new(&validate_Int32Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_int32(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_int64(validate_FieldRules *msg, validate_Int64Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_int32(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_int64(validate_FieldRules *msg, validate_Int64Rules* value) {
UPB_WRITE_ONEOF(msg, validate_Int64Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 4);
-}
-UPB_INLINE struct validate_Int64Rules* validate_FieldRules_mutable_int64(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_Int64Rules* sub = (struct validate_Int64Rules*)validate_FieldRules_int64(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_Int64Rules* validate_FieldRules_mutable_int64(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_Int64Rules* sub = (struct validate_Int64Rules*)validate_FieldRules_int64(msg);
+ if (sub == NULL) {
sub = (struct validate_Int64Rules*)_upb_msg_new(&validate_Int64Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_int64(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_uint32(validate_FieldRules *msg, validate_UInt32Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_int64(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_uint32(validate_FieldRules *msg, validate_UInt32Rules* value) {
UPB_WRITE_ONEOF(msg, validate_UInt32Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 5);
-}
-UPB_INLINE struct validate_UInt32Rules* validate_FieldRules_mutable_uint32(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_UInt32Rules* sub = (struct validate_UInt32Rules*)validate_FieldRules_uint32(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_UInt32Rules* validate_FieldRules_mutable_uint32(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_UInt32Rules* sub = (struct validate_UInt32Rules*)validate_FieldRules_uint32(msg);
+ if (sub == NULL) {
sub = (struct validate_UInt32Rules*)_upb_msg_new(&validate_UInt32Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_uint32(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_uint64(validate_FieldRules *msg, validate_UInt64Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_uint32(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_uint64(validate_FieldRules *msg, validate_UInt64Rules* value) {
UPB_WRITE_ONEOF(msg, validate_UInt64Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 6);
-}
-UPB_INLINE struct validate_UInt64Rules* validate_FieldRules_mutable_uint64(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_UInt64Rules* sub = (struct validate_UInt64Rules*)validate_FieldRules_uint64(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_UInt64Rules* validate_FieldRules_mutable_uint64(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_UInt64Rules* sub = (struct validate_UInt64Rules*)validate_FieldRules_uint64(msg);
+ if (sub == NULL) {
sub = (struct validate_UInt64Rules*)_upb_msg_new(&validate_UInt64Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_uint64(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_sint32(validate_FieldRules *msg, validate_SInt32Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_uint64(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_sint32(validate_FieldRules *msg, validate_SInt32Rules* value) {
UPB_WRITE_ONEOF(msg, validate_SInt32Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 7);
-}
-UPB_INLINE struct validate_SInt32Rules* validate_FieldRules_mutable_sint32(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_SInt32Rules* sub = (struct validate_SInt32Rules*)validate_FieldRules_sint32(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_SInt32Rules* validate_FieldRules_mutable_sint32(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_SInt32Rules* sub = (struct validate_SInt32Rules*)validate_FieldRules_sint32(msg);
+ if (sub == NULL) {
sub = (struct validate_SInt32Rules*)_upb_msg_new(&validate_SInt32Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_sint32(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_sint64(validate_FieldRules *msg, validate_SInt64Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_sint32(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_sint64(validate_FieldRules *msg, validate_SInt64Rules* value) {
UPB_WRITE_ONEOF(msg, validate_SInt64Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 8);
-}
-UPB_INLINE struct validate_SInt64Rules* validate_FieldRules_mutable_sint64(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_SInt64Rules* sub = (struct validate_SInt64Rules*)validate_FieldRules_sint64(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_SInt64Rules* validate_FieldRules_mutable_sint64(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_SInt64Rules* sub = (struct validate_SInt64Rules*)validate_FieldRules_sint64(msg);
+ if (sub == NULL) {
sub = (struct validate_SInt64Rules*)_upb_msg_new(&validate_SInt64Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_sint64(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_fixed32(validate_FieldRules *msg, validate_Fixed32Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_sint64(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_fixed32(validate_FieldRules *msg, validate_Fixed32Rules* value) {
UPB_WRITE_ONEOF(msg, validate_Fixed32Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 9);
-}
-UPB_INLINE struct validate_Fixed32Rules* validate_FieldRules_mutable_fixed32(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_Fixed32Rules* sub = (struct validate_Fixed32Rules*)validate_FieldRules_fixed32(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_Fixed32Rules* validate_FieldRules_mutable_fixed32(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_Fixed32Rules* sub = (struct validate_Fixed32Rules*)validate_FieldRules_fixed32(msg);
+ if (sub == NULL) {
sub = (struct validate_Fixed32Rules*)_upb_msg_new(&validate_Fixed32Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_fixed32(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_fixed64(validate_FieldRules *msg, validate_Fixed64Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_fixed32(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_fixed64(validate_FieldRules *msg, validate_Fixed64Rules* value) {
UPB_WRITE_ONEOF(msg, validate_Fixed64Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 10);
-}
-UPB_INLINE struct validate_Fixed64Rules* validate_FieldRules_mutable_fixed64(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_Fixed64Rules* sub = (struct validate_Fixed64Rules*)validate_FieldRules_fixed64(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_Fixed64Rules* validate_FieldRules_mutable_fixed64(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_Fixed64Rules* sub = (struct validate_Fixed64Rules*)validate_FieldRules_fixed64(msg);
+ if (sub == NULL) {
sub = (struct validate_Fixed64Rules*)_upb_msg_new(&validate_Fixed64Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_fixed64(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_sfixed32(validate_FieldRules *msg, validate_SFixed32Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_fixed64(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_sfixed32(validate_FieldRules *msg, validate_SFixed32Rules* value) {
UPB_WRITE_ONEOF(msg, validate_SFixed32Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 11);
-}
-UPB_INLINE struct validate_SFixed32Rules* validate_FieldRules_mutable_sfixed32(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_SFixed32Rules* sub = (struct validate_SFixed32Rules*)validate_FieldRules_sfixed32(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_SFixed32Rules* validate_FieldRules_mutable_sfixed32(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_SFixed32Rules* sub = (struct validate_SFixed32Rules*)validate_FieldRules_sfixed32(msg);
+ if (sub == NULL) {
sub = (struct validate_SFixed32Rules*)_upb_msg_new(&validate_SFixed32Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_sfixed32(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_sfixed64(validate_FieldRules *msg, validate_SFixed64Rules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_sfixed32(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_sfixed64(validate_FieldRules *msg, validate_SFixed64Rules* value) {
UPB_WRITE_ONEOF(msg, validate_SFixed64Rules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 12);
-}
-UPB_INLINE struct validate_SFixed64Rules* validate_FieldRules_mutable_sfixed64(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_SFixed64Rules* sub = (struct validate_SFixed64Rules*)validate_FieldRules_sfixed64(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_SFixed64Rules* validate_FieldRules_mutable_sfixed64(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_SFixed64Rules* sub = (struct validate_SFixed64Rules*)validate_FieldRules_sfixed64(msg);
+ if (sub == NULL) {
sub = (struct validate_SFixed64Rules*)_upb_msg_new(&validate_SFixed64Rules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_sfixed64(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_bool(validate_FieldRules *msg, validate_BoolRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_sfixed64(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_bool(validate_FieldRules *msg, validate_BoolRules* value) {
UPB_WRITE_ONEOF(msg, validate_BoolRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 13);
-}
-UPB_INLINE struct validate_BoolRules* validate_FieldRules_mutable_bool(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_BoolRules* sub = (struct validate_BoolRules*)validate_FieldRules_bool(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_BoolRules* validate_FieldRules_mutable_bool(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_BoolRules* sub = (struct validate_BoolRules*)validate_FieldRules_bool(msg);
+ if (sub == NULL) {
sub = (struct validate_BoolRules*)_upb_msg_new(&validate_BoolRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_bool(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_string(validate_FieldRules *msg, validate_StringRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_bool(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_string(validate_FieldRules *msg, validate_StringRules* value) {
UPB_WRITE_ONEOF(msg, validate_StringRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 14);
-}
-UPB_INLINE struct validate_StringRules* validate_FieldRules_mutable_string(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_StringRules* sub = (struct validate_StringRules*)validate_FieldRules_string(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_StringRules* validate_FieldRules_mutable_string(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_StringRules* sub = (struct validate_StringRules*)validate_FieldRules_string(msg);
+ if (sub == NULL) {
sub = (struct validate_StringRules*)_upb_msg_new(&validate_StringRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_string(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_bytes(validate_FieldRules *msg, validate_BytesRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_string(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_bytes(validate_FieldRules *msg, validate_BytesRules* value) {
UPB_WRITE_ONEOF(msg, validate_BytesRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 15);
-}
-UPB_INLINE struct validate_BytesRules* validate_FieldRules_mutable_bytes(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_BytesRules* sub = (struct validate_BytesRules*)validate_FieldRules_bytes(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_BytesRules* validate_FieldRules_mutable_bytes(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_BytesRules* sub = (struct validate_BytesRules*)validate_FieldRules_bytes(msg);
+ if (sub == NULL) {
sub = (struct validate_BytesRules*)_upb_msg_new(&validate_BytesRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_bytes(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_enum(validate_FieldRules *msg, validate_EnumRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_bytes(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_enum(validate_FieldRules *msg, validate_EnumRules* value) {
UPB_WRITE_ONEOF(msg, validate_EnumRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 16);
-}
-UPB_INLINE struct validate_EnumRules* validate_FieldRules_mutable_enum(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_EnumRules* sub = (struct validate_EnumRules*)validate_FieldRules_enum(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_EnumRules* validate_FieldRules_mutable_enum(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_EnumRules* sub = (struct validate_EnumRules*)validate_FieldRules_enum(msg);
+ if (sub == NULL) {
sub = (struct validate_EnumRules*)_upb_msg_new(&validate_EnumRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_enum(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_message(validate_FieldRules *msg, validate_MessageRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_enum(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_message(validate_FieldRules *msg, validate_MessageRules* value) {
_upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), validate_MessageRules*) = value;
-}
-UPB_INLINE struct validate_MessageRules* validate_FieldRules_mutable_message(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_MessageRules* sub = (struct validate_MessageRules*)validate_FieldRules_message(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_MessageRules* validate_FieldRules_mutable_message(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_MessageRules* sub = (struct validate_MessageRules*)validate_FieldRules_message(msg);
+ if (sub == NULL) {
sub = (struct validate_MessageRules*)_upb_msg_new(&validate_MessageRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_message(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_repeated(validate_FieldRules *msg, validate_RepeatedRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_message(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_repeated(validate_FieldRules *msg, validate_RepeatedRules* value) {
UPB_WRITE_ONEOF(msg, validate_RepeatedRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 18);
-}
-UPB_INLINE struct validate_RepeatedRules* validate_FieldRules_mutable_repeated(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_RepeatedRules* sub = (struct validate_RepeatedRules*)validate_FieldRules_repeated(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_RepeatedRules* validate_FieldRules_mutable_repeated(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_RepeatedRules* sub = (struct validate_RepeatedRules*)validate_FieldRules_repeated(msg);
+ if (sub == NULL) {
sub = (struct validate_RepeatedRules*)_upb_msg_new(&validate_RepeatedRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_repeated(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_map(validate_FieldRules *msg, validate_MapRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_repeated(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_map(validate_FieldRules *msg, validate_MapRules* value) {
UPB_WRITE_ONEOF(msg, validate_MapRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 19);
-}
-UPB_INLINE struct validate_MapRules* validate_FieldRules_mutable_map(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_MapRules* sub = (struct validate_MapRules*)validate_FieldRules_map(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_MapRules* validate_FieldRules_mutable_map(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_MapRules* sub = (struct validate_MapRules*)validate_FieldRules_map(msg);
+ if (sub == NULL) {
sub = (struct validate_MapRules*)_upb_msg_new(&validate_MapRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_map(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_any(validate_FieldRules *msg, validate_AnyRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_map(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_any(validate_FieldRules *msg, validate_AnyRules* value) {
UPB_WRITE_ONEOF(msg, validate_AnyRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 20);
-}
-UPB_INLINE struct validate_AnyRules* validate_FieldRules_mutable_any(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_AnyRules* sub = (struct validate_AnyRules*)validate_FieldRules_any(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_AnyRules* validate_FieldRules_mutable_any(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_AnyRules* sub = (struct validate_AnyRules*)validate_FieldRules_any(msg);
+ if (sub == NULL) {
sub = (struct validate_AnyRules*)_upb_msg_new(&validate_AnyRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_any(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_duration(validate_FieldRules *msg, validate_DurationRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_any(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_duration(validate_FieldRules *msg, validate_DurationRules* value) {
UPB_WRITE_ONEOF(msg, validate_DurationRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 21);
-}
-UPB_INLINE struct validate_DurationRules* validate_FieldRules_mutable_duration(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_DurationRules* sub = (struct validate_DurationRules*)validate_FieldRules_duration(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_DurationRules* validate_FieldRules_mutable_duration(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_DurationRules* sub = (struct validate_DurationRules*)validate_FieldRules_duration(msg);
+ if (sub == NULL) {
sub = (struct validate_DurationRules*)_upb_msg_new(&validate_DurationRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_duration(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_FieldRules_set_timestamp(validate_FieldRules *msg, validate_TimestampRules* value) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_duration(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_FieldRules_set_timestamp(validate_FieldRules *msg, validate_TimestampRules* value) {
UPB_WRITE_ONEOF(msg, validate_TimestampRules*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 22);
-}
-UPB_INLINE struct validate_TimestampRules* validate_FieldRules_mutable_timestamp(validate_FieldRules *msg, upb_arena *arena) {
- struct validate_TimestampRules* sub = (struct validate_TimestampRules*)validate_FieldRules_timestamp(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_TimestampRules* validate_FieldRules_mutable_timestamp(validate_FieldRules *msg, upb_arena *arena) {
+ struct validate_TimestampRules* sub = (struct validate_TimestampRules*)validate_FieldRules_timestamp(msg);
+ if (sub == NULL) {
sub = (struct validate_TimestampRules*)_upb_msg_new(&validate_TimestampRules_msginit, arena);
- if (!sub) return NULL;
- validate_FieldRules_set_timestamp(msg, sub);
- }
- return sub;
-}
-
-/* validate.FloatRules */
-
-UPB_INLINE validate_FloatRules *validate_FloatRules_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ validate_FieldRules_set_timestamp(msg, sub);
+ }
+ return sub;
+}
+
+/* validate.FloatRules */
+
+UPB_INLINE validate_FloatRules *validate_FloatRules_new(upb_arena *arena) {
return (validate_FloatRules *)_upb_msg_new(&validate_FloatRules_msginit, arena);
-}
-UPB_INLINE validate_FloatRules *validate_FloatRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_FloatRules *ret = validate_FloatRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_FloatRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_FloatRules_serialize(const validate_FloatRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_FloatRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_FloatRules *validate_FloatRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_FloatRules *ret = validate_FloatRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_FloatRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_FloatRules_serialize(const validate_FloatRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_FloatRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_FloatRules_has_const(const validate_FloatRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE float validate_FloatRules_const(const validate_FloatRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), float); }
UPB_INLINE bool validate_FloatRules_has_lt(const validate_FloatRules *msg) { return _upb_hasbit(msg, 2); }
@@ -475,64 +475,64 @@ UPB_INLINE bool validate_FloatRules_has_gt(const validate_FloatRules *msg) { ret
UPB_INLINE float validate_FloatRules_gt(const validate_FloatRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), float); }
UPB_INLINE bool validate_FloatRules_has_gte(const validate_FloatRules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE float validate_FloatRules_gte(const validate_FloatRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), float); }
-UPB_INLINE float const* validate_FloatRules_in(const validate_FloatRules *msg, size_t *len) { return (float const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
-UPB_INLINE float const* validate_FloatRules_not_in(const validate_FloatRules *msg, size_t *len) { return (float const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void validate_FloatRules_set_const(validate_FloatRules *msg, float value) {
- _upb_sethas(msg, 1);
+UPB_INLINE float const* validate_FloatRules_in(const validate_FloatRules *msg, size_t *len) { return (float const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
+UPB_INLINE float const* validate_FloatRules_not_in(const validate_FloatRules *msg, size_t *len) { return (float const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void validate_FloatRules_set_const(validate_FloatRules *msg, float value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), float) = value;
-}
-UPB_INLINE void validate_FloatRules_set_lt(validate_FloatRules *msg, float value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_FloatRules_set_lt(validate_FloatRules *msg, float value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), float) = value;
-}
-UPB_INLINE void validate_FloatRules_set_lte(validate_FloatRules *msg, float value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_FloatRules_set_lte(validate_FloatRules *msg, float value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 12), float) = value;
-}
-UPB_INLINE void validate_FloatRules_set_gt(validate_FloatRules *msg, float value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_FloatRules_set_gt(validate_FloatRules *msg, float value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), float) = value;
-}
-UPB_INLINE void validate_FloatRules_set_gte(validate_FloatRules *msg, float value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_FloatRules_set_gte(validate_FloatRules *msg, float value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), float) = value;
-}
-UPB_INLINE float* validate_FloatRules_mutable_in(validate_FloatRules *msg, size_t *len) {
- return (float*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
-}
-UPB_INLINE float* validate_FloatRules_resize_in(validate_FloatRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE float* validate_FloatRules_mutable_in(validate_FloatRules *msg, size_t *len) {
+ return (float*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
+}
+UPB_INLINE float* validate_FloatRules_resize_in(validate_FloatRules *msg, size_t len, upb_arena *arena) {
return (float*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 24), len, UPB_TYPE_FLOAT, arena);
-}
-UPB_INLINE bool validate_FloatRules_add_in(validate_FloatRules *msg, float val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_FloatRules_add_in(validate_FloatRules *msg, float val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 24), UPB_SIZE(4, 4), UPB_TYPE_FLOAT, &val,
arena);
-}
-UPB_INLINE float* validate_FloatRules_mutable_not_in(validate_FloatRules *msg, size_t *len) {
- return (float*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE float* validate_FloatRules_resize_not_in(validate_FloatRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE float* validate_FloatRules_mutable_not_in(validate_FloatRules *msg, size_t *len) {
+ return (float*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE float* validate_FloatRules_resize_not_in(validate_FloatRules *msg, size_t len, upb_arena *arena) {
return (float*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_FLOAT, arena);
-}
-UPB_INLINE bool validate_FloatRules_add_not_in(validate_FloatRules *msg, float val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_FloatRules_add_not_in(validate_FloatRules *msg, float val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 32), UPB_SIZE(4, 4), UPB_TYPE_FLOAT, &val,
arena);
-}
-
-/* validate.DoubleRules */
-
-UPB_INLINE validate_DoubleRules *validate_DoubleRules_new(upb_arena *arena) {
+}
+
+/* validate.DoubleRules */
+
+UPB_INLINE validate_DoubleRules *validate_DoubleRules_new(upb_arena *arena) {
return (validate_DoubleRules *)_upb_msg_new(&validate_DoubleRules_msginit, arena);
-}
-UPB_INLINE validate_DoubleRules *validate_DoubleRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_DoubleRules *ret = validate_DoubleRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_DoubleRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_DoubleRules_serialize(const validate_DoubleRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_DoubleRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_DoubleRules *validate_DoubleRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_DoubleRules *ret = validate_DoubleRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_DoubleRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_DoubleRules_serialize(const validate_DoubleRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_DoubleRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_DoubleRules_has_const(const validate_DoubleRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE double validate_DoubleRules_const(const validate_DoubleRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), double); }
UPB_INLINE bool validate_DoubleRules_has_lt(const validate_DoubleRules *msg) { return _upb_hasbit(msg, 2); }
@@ -543,64 +543,64 @@ UPB_INLINE bool validate_DoubleRules_has_gt(const validate_DoubleRules *msg) { r
UPB_INLINE double validate_DoubleRules_gt(const validate_DoubleRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), double); }
UPB_INLINE bool validate_DoubleRules_has_gte(const validate_DoubleRules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE double validate_DoubleRules_gte(const validate_DoubleRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 40), double); }
-UPB_INLINE double const* validate_DoubleRules_in(const validate_DoubleRules *msg, size_t *len) { return (double const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
-UPB_INLINE double const* validate_DoubleRules_not_in(const validate_DoubleRules *msg, size_t *len) { return (double const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
-
-UPB_INLINE void validate_DoubleRules_set_const(validate_DoubleRules *msg, double value) {
- _upb_sethas(msg, 1);
+UPB_INLINE double const* validate_DoubleRules_in(const validate_DoubleRules *msg, size_t *len) { return (double const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
+UPB_INLINE double const* validate_DoubleRules_not_in(const validate_DoubleRules *msg, size_t *len) { return (double const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
+
+UPB_INLINE void validate_DoubleRules_set_const(validate_DoubleRules *msg, double value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), double) = value;
-}
-UPB_INLINE void validate_DoubleRules_set_lt(validate_DoubleRules *msg, double value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_DoubleRules_set_lt(validate_DoubleRules *msg, double value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), double) = value;
-}
-UPB_INLINE void validate_DoubleRules_set_lte(validate_DoubleRules *msg, double value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_DoubleRules_set_lte(validate_DoubleRules *msg, double value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), double) = value;
-}
-UPB_INLINE void validate_DoubleRules_set_gt(validate_DoubleRules *msg, double value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_DoubleRules_set_gt(validate_DoubleRules *msg, double value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), double) = value;
-}
-UPB_INLINE void validate_DoubleRules_set_gte(validate_DoubleRules *msg, double value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_DoubleRules_set_gte(validate_DoubleRules *msg, double value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), double) = value;
-}
-UPB_INLINE double* validate_DoubleRules_mutable_in(validate_DoubleRules *msg, size_t *len) {
- return (double*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
-}
-UPB_INLINE double* validate_DoubleRules_resize_in(validate_DoubleRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE double* validate_DoubleRules_mutable_in(validate_DoubleRules *msg, size_t *len) {
+ return (double*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
+}
+UPB_INLINE double* validate_DoubleRules_resize_in(validate_DoubleRules *msg, size_t len, upb_arena *arena) {
return (double*)_upb_array_resize_accessor(msg, UPB_SIZE(48, 48), len, UPB_TYPE_DOUBLE, arena);
-}
-UPB_INLINE bool validate_DoubleRules_add_in(validate_DoubleRules *msg, double val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_DoubleRules_add_in(validate_DoubleRules *msg, double val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(48, 48), UPB_SIZE(8, 8), UPB_TYPE_DOUBLE, &val,
arena);
-}
-UPB_INLINE double* validate_DoubleRules_mutable_not_in(validate_DoubleRules *msg, size_t *len) {
- return (double*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
-}
-UPB_INLINE double* validate_DoubleRules_resize_not_in(validate_DoubleRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE double* validate_DoubleRules_mutable_not_in(validate_DoubleRules *msg, size_t *len) {
+ return (double*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
+}
+UPB_INLINE double* validate_DoubleRules_resize_not_in(validate_DoubleRules *msg, size_t len, upb_arena *arena) {
return (double*)_upb_array_resize_accessor(msg, UPB_SIZE(52, 56), len, UPB_TYPE_DOUBLE, arena);
-}
-UPB_INLINE bool validate_DoubleRules_add_not_in(validate_DoubleRules *msg, double val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_DoubleRules_add_not_in(validate_DoubleRules *msg, double val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(52, 56), UPB_SIZE(8, 8), UPB_TYPE_DOUBLE, &val,
arena);
-}
-
-/* validate.Int32Rules */
-
-UPB_INLINE validate_Int32Rules *validate_Int32Rules_new(upb_arena *arena) {
+}
+
+/* validate.Int32Rules */
+
+UPB_INLINE validate_Int32Rules *validate_Int32Rules_new(upb_arena *arena) {
return (validate_Int32Rules *)_upb_msg_new(&validate_Int32Rules_msginit, arena);
-}
-UPB_INLINE validate_Int32Rules *validate_Int32Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_Int32Rules *ret = validate_Int32Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_Int32Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_Int32Rules_serialize(const validate_Int32Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_Int32Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_Int32Rules *validate_Int32Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_Int32Rules *ret = validate_Int32Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_Int32Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_Int32Rules_serialize(const validate_Int32Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_Int32Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_Int32Rules_has_const(const validate_Int32Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t validate_Int32Rules_const(const validate_Int32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool validate_Int32Rules_has_lt(const validate_Int32Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -611,64 +611,64 @@ UPB_INLINE bool validate_Int32Rules_has_gt(const validate_Int32Rules *msg) { ret
UPB_INLINE int32_t validate_Int32Rules_gt(const validate_Int32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
UPB_INLINE bool validate_Int32Rules_has_gte(const validate_Int32Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE int32_t validate_Int32Rules_gte(const validate_Int32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), int32_t); }
-UPB_INLINE int32_t const* validate_Int32Rules_in(const validate_Int32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
-UPB_INLINE int32_t const* validate_Int32Rules_not_in(const validate_Int32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void validate_Int32Rules_set_const(validate_Int32Rules *msg, int32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int32_t const* validate_Int32Rules_in(const validate_Int32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
+UPB_INLINE int32_t const* validate_Int32Rules_not_in(const validate_Int32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void validate_Int32Rules_set_const(validate_Int32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void validate_Int32Rules_set_lt(validate_Int32Rules *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_Int32Rules_set_lt(validate_Int32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void validate_Int32Rules_set_lte(validate_Int32Rules *msg, int32_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_Int32Rules_set_lte(validate_Int32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 12), int32_t) = value;
-}
-UPB_INLINE void validate_Int32Rules_set_gt(validate_Int32Rules *msg, int32_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_Int32Rules_set_gt(validate_Int32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
-}
-UPB_INLINE void validate_Int32Rules_set_gte(validate_Int32Rules *msg, int32_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_Int32Rules_set_gte(validate_Int32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), int32_t) = value;
-}
-UPB_INLINE int32_t* validate_Int32Rules_mutable_in(validate_Int32Rules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
-}
-UPB_INLINE int32_t* validate_Int32Rules_resize_in(validate_Int32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_Int32Rules_mutable_in(validate_Int32Rules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
+}
+UPB_INLINE int32_t* validate_Int32Rules_resize_in(validate_Int32Rules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 24), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_Int32Rules_add_in(validate_Int32Rules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Int32Rules_add_in(validate_Int32Rules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 24), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE int32_t* validate_Int32Rules_mutable_not_in(validate_Int32Rules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE int32_t* validate_Int32Rules_resize_not_in(validate_Int32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_Int32Rules_mutable_not_in(validate_Int32Rules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE int32_t* validate_Int32Rules_resize_not_in(validate_Int32Rules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_Int32Rules_add_not_in(validate_Int32Rules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Int32Rules_add_not_in(validate_Int32Rules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-
-/* validate.Int64Rules */
-
-UPB_INLINE validate_Int64Rules *validate_Int64Rules_new(upb_arena *arena) {
+}
+
+/* validate.Int64Rules */
+
+UPB_INLINE validate_Int64Rules *validate_Int64Rules_new(upb_arena *arena) {
return (validate_Int64Rules *)_upb_msg_new(&validate_Int64Rules_msginit, arena);
-}
-UPB_INLINE validate_Int64Rules *validate_Int64Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_Int64Rules *ret = validate_Int64Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_Int64Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_Int64Rules_serialize(const validate_Int64Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_Int64Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_Int64Rules *validate_Int64Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_Int64Rules *ret = validate_Int64Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_Int64Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_Int64Rules_serialize(const validate_Int64Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_Int64Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_Int64Rules_has_const(const validate_Int64Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int64_t validate_Int64Rules_const(const validate_Int64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t); }
UPB_INLINE bool validate_Int64Rules_has_lt(const validate_Int64Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -679,64 +679,64 @@ UPB_INLINE bool validate_Int64Rules_has_gt(const validate_Int64Rules *msg) { ret
UPB_INLINE int64_t validate_Int64Rules_gt(const validate_Int64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), int64_t); }
UPB_INLINE bool validate_Int64Rules_has_gte(const validate_Int64Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE int64_t validate_Int64Rules_gte(const validate_Int64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 40), int64_t); }
-UPB_INLINE int64_t const* validate_Int64Rules_in(const validate_Int64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
-UPB_INLINE int64_t const* validate_Int64Rules_not_in(const validate_Int64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
-
-UPB_INLINE void validate_Int64Rules_set_const(validate_Int64Rules *msg, int64_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int64_t const* validate_Int64Rules_in(const validate_Int64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
+UPB_INLINE int64_t const* validate_Int64Rules_not_in(const validate_Int64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
+
+UPB_INLINE void validate_Int64Rules_set_const(validate_Int64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t) = value;
-}
-UPB_INLINE void validate_Int64Rules_set_lt(validate_Int64Rules *msg, int64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_Int64Rules_set_lt(validate_Int64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
-}
-UPB_INLINE void validate_Int64Rules_set_lte(validate_Int64Rules *msg, int64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_Int64Rules_set_lte(validate_Int64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), int64_t) = value;
-}
-UPB_INLINE void validate_Int64Rules_set_gt(validate_Int64Rules *msg, int64_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_Int64Rules_set_gt(validate_Int64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), int64_t) = value;
-}
-UPB_INLINE void validate_Int64Rules_set_gte(validate_Int64Rules *msg, int64_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_Int64Rules_set_gte(validate_Int64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), int64_t) = value;
-}
-UPB_INLINE int64_t* validate_Int64Rules_mutable_in(validate_Int64Rules *msg, size_t *len) {
- return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
-}
-UPB_INLINE int64_t* validate_Int64Rules_resize_in(validate_Int64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int64_t* validate_Int64Rules_mutable_in(validate_Int64Rules *msg, size_t *len) {
+ return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
+}
+UPB_INLINE int64_t* validate_Int64Rules_resize_in(validate_Int64Rules *msg, size_t len, upb_arena *arena) {
return (int64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(48, 48), len, UPB_TYPE_INT64, arena);
-}
-UPB_INLINE bool validate_Int64Rules_add_in(validate_Int64Rules *msg, int64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Int64Rules_add_in(validate_Int64Rules *msg, int64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(48, 48), UPB_SIZE(8, 8), UPB_TYPE_INT64, &val,
arena);
-}
-UPB_INLINE int64_t* validate_Int64Rules_mutable_not_in(validate_Int64Rules *msg, size_t *len) {
- return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
-}
-UPB_INLINE int64_t* validate_Int64Rules_resize_not_in(validate_Int64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int64_t* validate_Int64Rules_mutable_not_in(validate_Int64Rules *msg, size_t *len) {
+ return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
+}
+UPB_INLINE int64_t* validate_Int64Rules_resize_not_in(validate_Int64Rules *msg, size_t len, upb_arena *arena) {
return (int64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(52, 56), len, UPB_TYPE_INT64, arena);
-}
-UPB_INLINE bool validate_Int64Rules_add_not_in(validate_Int64Rules *msg, int64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Int64Rules_add_not_in(validate_Int64Rules *msg, int64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(52, 56), UPB_SIZE(8, 8), UPB_TYPE_INT64, &val,
arena);
-}
-
-/* validate.UInt32Rules */
-
-UPB_INLINE validate_UInt32Rules *validate_UInt32Rules_new(upb_arena *arena) {
+}
+
+/* validate.UInt32Rules */
+
+UPB_INLINE validate_UInt32Rules *validate_UInt32Rules_new(upb_arena *arena) {
return (validate_UInt32Rules *)_upb_msg_new(&validate_UInt32Rules_msginit, arena);
-}
-UPB_INLINE validate_UInt32Rules *validate_UInt32Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_UInt32Rules *ret = validate_UInt32Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_UInt32Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_UInt32Rules_serialize(const validate_UInt32Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_UInt32Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_UInt32Rules *validate_UInt32Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_UInt32Rules *ret = validate_UInt32Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_UInt32Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_UInt32Rules_serialize(const validate_UInt32Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_UInt32Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_UInt32Rules_has_const(const validate_UInt32Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE uint32_t validate_UInt32Rules_const(const validate_UInt32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t); }
UPB_INLINE bool validate_UInt32Rules_has_lt(const validate_UInt32Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -747,64 +747,64 @@ UPB_INLINE bool validate_UInt32Rules_has_gt(const validate_UInt32Rules *msg) { r
UPB_INLINE uint32_t validate_UInt32Rules_gt(const validate_UInt32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint32_t); }
UPB_INLINE bool validate_UInt32Rules_has_gte(const validate_UInt32Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE uint32_t validate_UInt32Rules_gte(const validate_UInt32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), uint32_t); }
-UPB_INLINE uint32_t const* validate_UInt32Rules_in(const validate_UInt32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
-UPB_INLINE uint32_t const* validate_UInt32Rules_not_in(const validate_UInt32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void validate_UInt32Rules_set_const(validate_UInt32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE uint32_t const* validate_UInt32Rules_in(const validate_UInt32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
+UPB_INLINE uint32_t const* validate_UInt32Rules_not_in(const validate_UInt32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void validate_UInt32Rules_set_const(validate_UInt32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t) = value;
-}
-UPB_INLINE void validate_UInt32Rules_set_lt(validate_UInt32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_UInt32Rules_set_lt(validate_UInt32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint32_t) = value;
-}
-UPB_INLINE void validate_UInt32Rules_set_lte(validate_UInt32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_UInt32Rules_set_lte(validate_UInt32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 12), uint32_t) = value;
-}
-UPB_INLINE void validate_UInt32Rules_set_gt(validate_UInt32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_UInt32Rules_set_gt(validate_UInt32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint32_t) = value;
-}
-UPB_INLINE void validate_UInt32Rules_set_gte(validate_UInt32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_UInt32Rules_set_gte(validate_UInt32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), uint32_t) = value;
-}
-UPB_INLINE uint32_t* validate_UInt32Rules_mutable_in(validate_UInt32Rules *msg, size_t *len) {
- return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
-}
-UPB_INLINE uint32_t* validate_UInt32Rules_resize_in(validate_UInt32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint32_t* validate_UInt32Rules_mutable_in(validate_UInt32Rules *msg, size_t *len) {
+ return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
+}
+UPB_INLINE uint32_t* validate_UInt32Rules_resize_in(validate_UInt32Rules *msg, size_t len, upb_arena *arena) {
return (uint32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 24), len, UPB_TYPE_UINT32, arena);
-}
-UPB_INLINE bool validate_UInt32Rules_add_in(validate_UInt32Rules *msg, uint32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_UInt32Rules_add_in(validate_UInt32Rules *msg, uint32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 24), UPB_SIZE(4, 4), UPB_TYPE_UINT32, &val,
arena);
-}
-UPB_INLINE uint32_t* validate_UInt32Rules_mutable_not_in(validate_UInt32Rules *msg, size_t *len) {
- return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE uint32_t* validate_UInt32Rules_resize_not_in(validate_UInt32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint32_t* validate_UInt32Rules_mutable_not_in(validate_UInt32Rules *msg, size_t *len) {
+ return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE uint32_t* validate_UInt32Rules_resize_not_in(validate_UInt32Rules *msg, size_t len, upb_arena *arena) {
return (uint32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_UINT32, arena);
-}
-UPB_INLINE bool validate_UInt32Rules_add_not_in(validate_UInt32Rules *msg, uint32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_UInt32Rules_add_not_in(validate_UInt32Rules *msg, uint32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 32), UPB_SIZE(4, 4), UPB_TYPE_UINT32, &val,
arena);
-}
-
-/* validate.UInt64Rules */
-
-UPB_INLINE validate_UInt64Rules *validate_UInt64Rules_new(upb_arena *arena) {
+}
+
+/* validate.UInt64Rules */
+
+UPB_INLINE validate_UInt64Rules *validate_UInt64Rules_new(upb_arena *arena) {
return (validate_UInt64Rules *)_upb_msg_new(&validate_UInt64Rules_msginit, arena);
-}
-UPB_INLINE validate_UInt64Rules *validate_UInt64Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_UInt64Rules *ret = validate_UInt64Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_UInt64Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_UInt64Rules_serialize(const validate_UInt64Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_UInt64Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_UInt64Rules *validate_UInt64Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_UInt64Rules *ret = validate_UInt64Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_UInt64Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_UInt64Rules_serialize(const validate_UInt64Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_UInt64Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_UInt64Rules_has_const(const validate_UInt64Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE uint64_t validate_UInt64Rules_const(const validate_UInt64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t); }
UPB_INLINE bool validate_UInt64Rules_has_lt(const validate_UInt64Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -815,64 +815,64 @@ UPB_INLINE bool validate_UInt64Rules_has_gt(const validate_UInt64Rules *msg) { r
UPB_INLINE uint64_t validate_UInt64Rules_gt(const validate_UInt64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), uint64_t); }
UPB_INLINE bool validate_UInt64Rules_has_gte(const validate_UInt64Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE uint64_t validate_UInt64Rules_gte(const validate_UInt64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 40), uint64_t); }
-UPB_INLINE uint64_t const* validate_UInt64Rules_in(const validate_UInt64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
-UPB_INLINE uint64_t const* validate_UInt64Rules_not_in(const validate_UInt64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
-
-UPB_INLINE void validate_UInt64Rules_set_const(validate_UInt64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE uint64_t const* validate_UInt64Rules_in(const validate_UInt64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
+UPB_INLINE uint64_t const* validate_UInt64Rules_not_in(const validate_UInt64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
+
+UPB_INLINE void validate_UInt64Rules_set_const(validate_UInt64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void validate_UInt64Rules_set_lt(validate_UInt64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_UInt64Rules_set_lt(validate_UInt64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
-UPB_INLINE void validate_UInt64Rules_set_lte(validate_UInt64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_UInt64Rules_set_lte(validate_UInt64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), uint64_t) = value;
-}
-UPB_INLINE void validate_UInt64Rules_set_gt(validate_UInt64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_UInt64Rules_set_gt(validate_UInt64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), uint64_t) = value;
-}
-UPB_INLINE void validate_UInt64Rules_set_gte(validate_UInt64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_UInt64Rules_set_gte(validate_UInt64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), uint64_t) = value;
-}
-UPB_INLINE uint64_t* validate_UInt64Rules_mutable_in(validate_UInt64Rules *msg, size_t *len) {
- return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
-}
-UPB_INLINE uint64_t* validate_UInt64Rules_resize_in(validate_UInt64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint64_t* validate_UInt64Rules_mutable_in(validate_UInt64Rules *msg, size_t *len) {
+ return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
+}
+UPB_INLINE uint64_t* validate_UInt64Rules_resize_in(validate_UInt64Rules *msg, size_t len, upb_arena *arena) {
return (uint64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(48, 48), len, UPB_TYPE_UINT64, arena);
-}
-UPB_INLINE bool validate_UInt64Rules_add_in(validate_UInt64Rules *msg, uint64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_UInt64Rules_add_in(validate_UInt64Rules *msg, uint64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(48, 48), UPB_SIZE(8, 8), UPB_TYPE_UINT64, &val,
arena);
-}
-UPB_INLINE uint64_t* validate_UInt64Rules_mutable_not_in(validate_UInt64Rules *msg, size_t *len) {
- return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
-}
-UPB_INLINE uint64_t* validate_UInt64Rules_resize_not_in(validate_UInt64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint64_t* validate_UInt64Rules_mutable_not_in(validate_UInt64Rules *msg, size_t *len) {
+ return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
+}
+UPB_INLINE uint64_t* validate_UInt64Rules_resize_not_in(validate_UInt64Rules *msg, size_t len, upb_arena *arena) {
return (uint64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(52, 56), len, UPB_TYPE_UINT64, arena);
-}
-UPB_INLINE bool validate_UInt64Rules_add_not_in(validate_UInt64Rules *msg, uint64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_UInt64Rules_add_not_in(validate_UInt64Rules *msg, uint64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(52, 56), UPB_SIZE(8, 8), UPB_TYPE_UINT64, &val,
arena);
-}
-
-/* validate.SInt32Rules */
-
-UPB_INLINE validate_SInt32Rules *validate_SInt32Rules_new(upb_arena *arena) {
+}
+
+/* validate.SInt32Rules */
+
+UPB_INLINE validate_SInt32Rules *validate_SInt32Rules_new(upb_arena *arena) {
return (validate_SInt32Rules *)_upb_msg_new(&validate_SInt32Rules_msginit, arena);
-}
-UPB_INLINE validate_SInt32Rules *validate_SInt32Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_SInt32Rules *ret = validate_SInt32Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_SInt32Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_SInt32Rules_serialize(const validate_SInt32Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_SInt32Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_SInt32Rules *validate_SInt32Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_SInt32Rules *ret = validate_SInt32Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_SInt32Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_SInt32Rules_serialize(const validate_SInt32Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_SInt32Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_SInt32Rules_has_const(const validate_SInt32Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t validate_SInt32Rules_const(const validate_SInt32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool validate_SInt32Rules_has_lt(const validate_SInt32Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -883,64 +883,64 @@ UPB_INLINE bool validate_SInt32Rules_has_gt(const validate_SInt32Rules *msg) { r
UPB_INLINE int32_t validate_SInt32Rules_gt(const validate_SInt32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
UPB_INLINE bool validate_SInt32Rules_has_gte(const validate_SInt32Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE int32_t validate_SInt32Rules_gte(const validate_SInt32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), int32_t); }
-UPB_INLINE int32_t const* validate_SInt32Rules_in(const validate_SInt32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
-UPB_INLINE int32_t const* validate_SInt32Rules_not_in(const validate_SInt32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void validate_SInt32Rules_set_const(validate_SInt32Rules *msg, int32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int32_t const* validate_SInt32Rules_in(const validate_SInt32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
+UPB_INLINE int32_t const* validate_SInt32Rules_not_in(const validate_SInt32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void validate_SInt32Rules_set_const(validate_SInt32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void validate_SInt32Rules_set_lt(validate_SInt32Rules *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_SInt32Rules_set_lt(validate_SInt32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void validate_SInt32Rules_set_lte(validate_SInt32Rules *msg, int32_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_SInt32Rules_set_lte(validate_SInt32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 12), int32_t) = value;
-}
-UPB_INLINE void validate_SInt32Rules_set_gt(validate_SInt32Rules *msg, int32_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_SInt32Rules_set_gt(validate_SInt32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
-}
-UPB_INLINE void validate_SInt32Rules_set_gte(validate_SInt32Rules *msg, int32_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_SInt32Rules_set_gte(validate_SInt32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), int32_t) = value;
-}
-UPB_INLINE int32_t* validate_SInt32Rules_mutable_in(validate_SInt32Rules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
-}
-UPB_INLINE int32_t* validate_SInt32Rules_resize_in(validate_SInt32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_SInt32Rules_mutable_in(validate_SInt32Rules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
+}
+UPB_INLINE int32_t* validate_SInt32Rules_resize_in(validate_SInt32Rules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 24), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_SInt32Rules_add_in(validate_SInt32Rules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SInt32Rules_add_in(validate_SInt32Rules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 24), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE int32_t* validate_SInt32Rules_mutable_not_in(validate_SInt32Rules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE int32_t* validate_SInt32Rules_resize_not_in(validate_SInt32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_SInt32Rules_mutable_not_in(validate_SInt32Rules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE int32_t* validate_SInt32Rules_resize_not_in(validate_SInt32Rules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_SInt32Rules_add_not_in(validate_SInt32Rules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SInt32Rules_add_not_in(validate_SInt32Rules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-
-/* validate.SInt64Rules */
-
-UPB_INLINE validate_SInt64Rules *validate_SInt64Rules_new(upb_arena *arena) {
+}
+
+/* validate.SInt64Rules */
+
+UPB_INLINE validate_SInt64Rules *validate_SInt64Rules_new(upb_arena *arena) {
return (validate_SInt64Rules *)_upb_msg_new(&validate_SInt64Rules_msginit, arena);
-}
-UPB_INLINE validate_SInt64Rules *validate_SInt64Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_SInt64Rules *ret = validate_SInt64Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_SInt64Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_SInt64Rules_serialize(const validate_SInt64Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_SInt64Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_SInt64Rules *validate_SInt64Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_SInt64Rules *ret = validate_SInt64Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_SInt64Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_SInt64Rules_serialize(const validate_SInt64Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_SInt64Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_SInt64Rules_has_const(const validate_SInt64Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int64_t validate_SInt64Rules_const(const validate_SInt64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t); }
UPB_INLINE bool validate_SInt64Rules_has_lt(const validate_SInt64Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -951,64 +951,64 @@ UPB_INLINE bool validate_SInt64Rules_has_gt(const validate_SInt64Rules *msg) { r
UPB_INLINE int64_t validate_SInt64Rules_gt(const validate_SInt64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), int64_t); }
UPB_INLINE bool validate_SInt64Rules_has_gte(const validate_SInt64Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE int64_t validate_SInt64Rules_gte(const validate_SInt64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 40), int64_t); }
-UPB_INLINE int64_t const* validate_SInt64Rules_in(const validate_SInt64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
-UPB_INLINE int64_t const* validate_SInt64Rules_not_in(const validate_SInt64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
-
-UPB_INLINE void validate_SInt64Rules_set_const(validate_SInt64Rules *msg, int64_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int64_t const* validate_SInt64Rules_in(const validate_SInt64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
+UPB_INLINE int64_t const* validate_SInt64Rules_not_in(const validate_SInt64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
+
+UPB_INLINE void validate_SInt64Rules_set_const(validate_SInt64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t) = value;
-}
-UPB_INLINE void validate_SInt64Rules_set_lt(validate_SInt64Rules *msg, int64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_SInt64Rules_set_lt(validate_SInt64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
-}
-UPB_INLINE void validate_SInt64Rules_set_lte(validate_SInt64Rules *msg, int64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_SInt64Rules_set_lte(validate_SInt64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), int64_t) = value;
-}
-UPB_INLINE void validate_SInt64Rules_set_gt(validate_SInt64Rules *msg, int64_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_SInt64Rules_set_gt(validate_SInt64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), int64_t) = value;
-}
-UPB_INLINE void validate_SInt64Rules_set_gte(validate_SInt64Rules *msg, int64_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_SInt64Rules_set_gte(validate_SInt64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), int64_t) = value;
-}
-UPB_INLINE int64_t* validate_SInt64Rules_mutable_in(validate_SInt64Rules *msg, size_t *len) {
- return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
-}
-UPB_INLINE int64_t* validate_SInt64Rules_resize_in(validate_SInt64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int64_t* validate_SInt64Rules_mutable_in(validate_SInt64Rules *msg, size_t *len) {
+ return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
+}
+UPB_INLINE int64_t* validate_SInt64Rules_resize_in(validate_SInt64Rules *msg, size_t len, upb_arena *arena) {
return (int64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(48, 48), len, UPB_TYPE_INT64, arena);
-}
-UPB_INLINE bool validate_SInt64Rules_add_in(validate_SInt64Rules *msg, int64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SInt64Rules_add_in(validate_SInt64Rules *msg, int64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(48, 48), UPB_SIZE(8, 8), UPB_TYPE_INT64, &val,
arena);
-}
-UPB_INLINE int64_t* validate_SInt64Rules_mutable_not_in(validate_SInt64Rules *msg, size_t *len) {
- return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
-}
-UPB_INLINE int64_t* validate_SInt64Rules_resize_not_in(validate_SInt64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int64_t* validate_SInt64Rules_mutable_not_in(validate_SInt64Rules *msg, size_t *len) {
+ return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
+}
+UPB_INLINE int64_t* validate_SInt64Rules_resize_not_in(validate_SInt64Rules *msg, size_t len, upb_arena *arena) {
return (int64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(52, 56), len, UPB_TYPE_INT64, arena);
-}
-UPB_INLINE bool validate_SInt64Rules_add_not_in(validate_SInt64Rules *msg, int64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SInt64Rules_add_not_in(validate_SInt64Rules *msg, int64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(52, 56), UPB_SIZE(8, 8), UPB_TYPE_INT64, &val,
arena);
-}
-
-/* validate.Fixed32Rules */
-
-UPB_INLINE validate_Fixed32Rules *validate_Fixed32Rules_new(upb_arena *arena) {
+}
+
+/* validate.Fixed32Rules */
+
+UPB_INLINE validate_Fixed32Rules *validate_Fixed32Rules_new(upb_arena *arena) {
return (validate_Fixed32Rules *)_upb_msg_new(&validate_Fixed32Rules_msginit, arena);
-}
-UPB_INLINE validate_Fixed32Rules *validate_Fixed32Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_Fixed32Rules *ret = validate_Fixed32Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_Fixed32Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_Fixed32Rules_serialize(const validate_Fixed32Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_Fixed32Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_Fixed32Rules *validate_Fixed32Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_Fixed32Rules *ret = validate_Fixed32Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_Fixed32Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_Fixed32Rules_serialize(const validate_Fixed32Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_Fixed32Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_Fixed32Rules_has_const(const validate_Fixed32Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE uint32_t validate_Fixed32Rules_const(const validate_Fixed32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t); }
UPB_INLINE bool validate_Fixed32Rules_has_lt(const validate_Fixed32Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -1019,64 +1019,64 @@ UPB_INLINE bool validate_Fixed32Rules_has_gt(const validate_Fixed32Rules *msg) {
UPB_INLINE uint32_t validate_Fixed32Rules_gt(const validate_Fixed32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint32_t); }
UPB_INLINE bool validate_Fixed32Rules_has_gte(const validate_Fixed32Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE uint32_t validate_Fixed32Rules_gte(const validate_Fixed32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), uint32_t); }
-UPB_INLINE uint32_t const* validate_Fixed32Rules_in(const validate_Fixed32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
-UPB_INLINE uint32_t const* validate_Fixed32Rules_not_in(const validate_Fixed32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void validate_Fixed32Rules_set_const(validate_Fixed32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE uint32_t const* validate_Fixed32Rules_in(const validate_Fixed32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
+UPB_INLINE uint32_t const* validate_Fixed32Rules_not_in(const validate_Fixed32Rules *msg, size_t *len) { return (uint32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void validate_Fixed32Rules_set_const(validate_Fixed32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), uint32_t) = value;
-}
-UPB_INLINE void validate_Fixed32Rules_set_lt(validate_Fixed32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_Fixed32Rules_set_lt(validate_Fixed32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint32_t) = value;
-}
-UPB_INLINE void validate_Fixed32Rules_set_lte(validate_Fixed32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_Fixed32Rules_set_lte(validate_Fixed32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 12), uint32_t) = value;
-}
-UPB_INLINE void validate_Fixed32Rules_set_gt(validate_Fixed32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_Fixed32Rules_set_gt(validate_Fixed32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint32_t) = value;
-}
-UPB_INLINE void validate_Fixed32Rules_set_gte(validate_Fixed32Rules *msg, uint32_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_Fixed32Rules_set_gte(validate_Fixed32Rules *msg, uint32_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), uint32_t) = value;
-}
-UPB_INLINE uint32_t* validate_Fixed32Rules_mutable_in(validate_Fixed32Rules *msg, size_t *len) {
- return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
-}
-UPB_INLINE uint32_t* validate_Fixed32Rules_resize_in(validate_Fixed32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint32_t* validate_Fixed32Rules_mutable_in(validate_Fixed32Rules *msg, size_t *len) {
+ return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
+}
+UPB_INLINE uint32_t* validate_Fixed32Rules_resize_in(validate_Fixed32Rules *msg, size_t len, upb_arena *arena) {
return (uint32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 24), len, UPB_TYPE_UINT32, arena);
-}
-UPB_INLINE bool validate_Fixed32Rules_add_in(validate_Fixed32Rules *msg, uint32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Fixed32Rules_add_in(validate_Fixed32Rules *msg, uint32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 24), UPB_SIZE(4, 4), UPB_TYPE_UINT32, &val,
arena);
-}
-UPB_INLINE uint32_t* validate_Fixed32Rules_mutable_not_in(validate_Fixed32Rules *msg, size_t *len) {
- return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE uint32_t* validate_Fixed32Rules_resize_not_in(validate_Fixed32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint32_t* validate_Fixed32Rules_mutable_not_in(validate_Fixed32Rules *msg, size_t *len) {
+ return (uint32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE uint32_t* validate_Fixed32Rules_resize_not_in(validate_Fixed32Rules *msg, size_t len, upb_arena *arena) {
return (uint32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_UINT32, arena);
-}
-UPB_INLINE bool validate_Fixed32Rules_add_not_in(validate_Fixed32Rules *msg, uint32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Fixed32Rules_add_not_in(validate_Fixed32Rules *msg, uint32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 32), UPB_SIZE(4, 4), UPB_TYPE_UINT32, &val,
arena);
-}
-
-/* validate.Fixed64Rules */
-
-UPB_INLINE validate_Fixed64Rules *validate_Fixed64Rules_new(upb_arena *arena) {
+}
+
+/* validate.Fixed64Rules */
+
+UPB_INLINE validate_Fixed64Rules *validate_Fixed64Rules_new(upb_arena *arena) {
return (validate_Fixed64Rules *)_upb_msg_new(&validate_Fixed64Rules_msginit, arena);
-}
-UPB_INLINE validate_Fixed64Rules *validate_Fixed64Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_Fixed64Rules *ret = validate_Fixed64Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_Fixed64Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_Fixed64Rules_serialize(const validate_Fixed64Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_Fixed64Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_Fixed64Rules *validate_Fixed64Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_Fixed64Rules *ret = validate_Fixed64Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_Fixed64Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_Fixed64Rules_serialize(const validate_Fixed64Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_Fixed64Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_Fixed64Rules_has_const(const validate_Fixed64Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE uint64_t validate_Fixed64Rules_const(const validate_Fixed64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t); }
UPB_INLINE bool validate_Fixed64Rules_has_lt(const validate_Fixed64Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -1087,64 +1087,64 @@ UPB_INLINE bool validate_Fixed64Rules_has_gt(const validate_Fixed64Rules *msg) {
UPB_INLINE uint64_t validate_Fixed64Rules_gt(const validate_Fixed64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), uint64_t); }
UPB_INLINE bool validate_Fixed64Rules_has_gte(const validate_Fixed64Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE uint64_t validate_Fixed64Rules_gte(const validate_Fixed64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 40), uint64_t); }
-UPB_INLINE uint64_t const* validate_Fixed64Rules_in(const validate_Fixed64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
-UPB_INLINE uint64_t const* validate_Fixed64Rules_not_in(const validate_Fixed64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
-
-UPB_INLINE void validate_Fixed64Rules_set_const(validate_Fixed64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE uint64_t const* validate_Fixed64Rules_in(const validate_Fixed64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
+UPB_INLINE uint64_t const* validate_Fixed64Rules_not_in(const validate_Fixed64Rules *msg, size_t *len) { return (uint64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
+
+UPB_INLINE void validate_Fixed64Rules_set_const(validate_Fixed64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void validate_Fixed64Rules_set_lt(validate_Fixed64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_Fixed64Rules_set_lt(validate_Fixed64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
-UPB_INLINE void validate_Fixed64Rules_set_lte(validate_Fixed64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_Fixed64Rules_set_lte(validate_Fixed64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), uint64_t) = value;
-}
-UPB_INLINE void validate_Fixed64Rules_set_gt(validate_Fixed64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_Fixed64Rules_set_gt(validate_Fixed64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), uint64_t) = value;
-}
-UPB_INLINE void validate_Fixed64Rules_set_gte(validate_Fixed64Rules *msg, uint64_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_Fixed64Rules_set_gte(validate_Fixed64Rules *msg, uint64_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), uint64_t) = value;
-}
-UPB_INLINE uint64_t* validate_Fixed64Rules_mutable_in(validate_Fixed64Rules *msg, size_t *len) {
- return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
-}
-UPB_INLINE uint64_t* validate_Fixed64Rules_resize_in(validate_Fixed64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint64_t* validate_Fixed64Rules_mutable_in(validate_Fixed64Rules *msg, size_t *len) {
+ return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
+}
+UPB_INLINE uint64_t* validate_Fixed64Rules_resize_in(validate_Fixed64Rules *msg, size_t len, upb_arena *arena) {
return (uint64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(48, 48), len, UPB_TYPE_UINT64, arena);
-}
-UPB_INLINE bool validate_Fixed64Rules_add_in(validate_Fixed64Rules *msg, uint64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Fixed64Rules_add_in(validate_Fixed64Rules *msg, uint64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(48, 48), UPB_SIZE(8, 8), UPB_TYPE_UINT64, &val,
arena);
-}
-UPB_INLINE uint64_t* validate_Fixed64Rules_mutable_not_in(validate_Fixed64Rules *msg, size_t *len) {
- return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
-}
-UPB_INLINE uint64_t* validate_Fixed64Rules_resize_not_in(validate_Fixed64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE uint64_t* validate_Fixed64Rules_mutable_not_in(validate_Fixed64Rules *msg, size_t *len) {
+ return (uint64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
+}
+UPB_INLINE uint64_t* validate_Fixed64Rules_resize_not_in(validate_Fixed64Rules *msg, size_t len, upb_arena *arena) {
return (uint64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(52, 56), len, UPB_TYPE_UINT64, arena);
-}
-UPB_INLINE bool validate_Fixed64Rules_add_not_in(validate_Fixed64Rules *msg, uint64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_Fixed64Rules_add_not_in(validate_Fixed64Rules *msg, uint64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(52, 56), UPB_SIZE(8, 8), UPB_TYPE_UINT64, &val,
arena);
-}
-
-/* validate.SFixed32Rules */
-
-UPB_INLINE validate_SFixed32Rules *validate_SFixed32Rules_new(upb_arena *arena) {
+}
+
+/* validate.SFixed32Rules */
+
+UPB_INLINE validate_SFixed32Rules *validate_SFixed32Rules_new(upb_arena *arena) {
return (validate_SFixed32Rules *)_upb_msg_new(&validate_SFixed32Rules_msginit, arena);
-}
-UPB_INLINE validate_SFixed32Rules *validate_SFixed32Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_SFixed32Rules *ret = validate_SFixed32Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_SFixed32Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_SFixed32Rules_serialize(const validate_SFixed32Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_SFixed32Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_SFixed32Rules *validate_SFixed32Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_SFixed32Rules *ret = validate_SFixed32Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_SFixed32Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_SFixed32Rules_serialize(const validate_SFixed32Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_SFixed32Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_SFixed32Rules_has_const(const validate_SFixed32Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t validate_SFixed32Rules_const(const validate_SFixed32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool validate_SFixed32Rules_has_lt(const validate_SFixed32Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -1155,64 +1155,64 @@ UPB_INLINE bool validate_SFixed32Rules_has_gt(const validate_SFixed32Rules *msg)
UPB_INLINE int32_t validate_SFixed32Rules_gt(const validate_SFixed32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
UPB_INLINE bool validate_SFixed32Rules_has_gte(const validate_SFixed32Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE int32_t validate_SFixed32Rules_gte(const validate_SFixed32Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), int32_t); }
-UPB_INLINE int32_t const* validate_SFixed32Rules_in(const validate_SFixed32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
-UPB_INLINE int32_t const* validate_SFixed32Rules_not_in(const validate_SFixed32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
-
-UPB_INLINE void validate_SFixed32Rules_set_const(validate_SFixed32Rules *msg, int32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int32_t const* validate_SFixed32Rules_in(const validate_SFixed32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 24), len); }
+UPB_INLINE int32_t const* validate_SFixed32Rules_not_in(const validate_SFixed32Rules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
+
+UPB_INLINE void validate_SFixed32Rules_set_const(validate_SFixed32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void validate_SFixed32Rules_set_lt(validate_SFixed32Rules *msg, int32_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_SFixed32Rules_set_lt(validate_SFixed32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
-}
-UPB_INLINE void validate_SFixed32Rules_set_lte(validate_SFixed32Rules *msg, int32_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_SFixed32Rules_set_lte(validate_SFixed32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(12, 12), int32_t) = value;
-}
-UPB_INLINE void validate_SFixed32Rules_set_gt(validate_SFixed32Rules *msg, int32_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_SFixed32Rules_set_gt(validate_SFixed32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
-}
-UPB_INLINE void validate_SFixed32Rules_set_gte(validate_SFixed32Rules *msg, int32_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_SFixed32Rules_set_gte(validate_SFixed32Rules *msg, int32_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(20, 20), int32_t) = value;
-}
-UPB_INLINE int32_t* validate_SFixed32Rules_mutable_in(validate_SFixed32Rules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
-}
-UPB_INLINE int32_t* validate_SFixed32Rules_resize_in(validate_SFixed32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_SFixed32Rules_mutable_in(validate_SFixed32Rules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 24), len);
+}
+UPB_INLINE int32_t* validate_SFixed32Rules_resize_in(validate_SFixed32Rules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 24), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_SFixed32Rules_add_in(validate_SFixed32Rules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SFixed32Rules_add_in(validate_SFixed32Rules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(24, 24), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE int32_t* validate_SFixed32Rules_mutable_not_in(validate_SFixed32Rules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
-}
-UPB_INLINE int32_t* validate_SFixed32Rules_resize_not_in(validate_SFixed32Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_SFixed32Rules_mutable_not_in(validate_SFixed32Rules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
+}
+UPB_INLINE int32_t* validate_SFixed32Rules_resize_not_in(validate_SFixed32Rules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_SFixed32Rules_add_not_in(validate_SFixed32Rules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SFixed32Rules_add_not_in(validate_SFixed32Rules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(28, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-
-/* validate.SFixed64Rules */
-
-UPB_INLINE validate_SFixed64Rules *validate_SFixed64Rules_new(upb_arena *arena) {
+}
+
+/* validate.SFixed64Rules */
+
+UPB_INLINE validate_SFixed64Rules *validate_SFixed64Rules_new(upb_arena *arena) {
return (validate_SFixed64Rules *)_upb_msg_new(&validate_SFixed64Rules_msginit, arena);
-}
-UPB_INLINE validate_SFixed64Rules *validate_SFixed64Rules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_SFixed64Rules *ret = validate_SFixed64Rules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_SFixed64Rules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_SFixed64Rules_serialize(const validate_SFixed64Rules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_SFixed64Rules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_SFixed64Rules *validate_SFixed64Rules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_SFixed64Rules *ret = validate_SFixed64Rules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_SFixed64Rules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_SFixed64Rules_serialize(const validate_SFixed64Rules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_SFixed64Rules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_SFixed64Rules_has_const(const validate_SFixed64Rules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int64_t validate_SFixed64Rules_const(const validate_SFixed64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t); }
UPB_INLINE bool validate_SFixed64Rules_has_lt(const validate_SFixed64Rules *msg) { return _upb_hasbit(msg, 2); }
@@ -1223,101 +1223,101 @@ UPB_INLINE bool validate_SFixed64Rules_has_gt(const validate_SFixed64Rules *msg)
UPB_INLINE int64_t validate_SFixed64Rules_gt(const validate_SFixed64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), int64_t); }
UPB_INLINE bool validate_SFixed64Rules_has_gte(const validate_SFixed64Rules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE int64_t validate_SFixed64Rules_gte(const validate_SFixed64Rules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 40), int64_t); }
-UPB_INLINE int64_t const* validate_SFixed64Rules_in(const validate_SFixed64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
-UPB_INLINE int64_t const* validate_SFixed64Rules_not_in(const validate_SFixed64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
-
-UPB_INLINE void validate_SFixed64Rules_set_const(validate_SFixed64Rules *msg, int64_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int64_t const* validate_SFixed64Rules_in(const validate_SFixed64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(48, 48), len); }
+UPB_INLINE int64_t const* validate_SFixed64Rules_not_in(const validate_SFixed64Rules *msg, size_t *len) { return (int64_t const*)_upb_array_accessor(msg, UPB_SIZE(52, 56), len); }
+
+UPB_INLINE void validate_SFixed64Rules_set_const(validate_SFixed64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), int64_t) = value;
-}
-UPB_INLINE void validate_SFixed64Rules_set_lt(validate_SFixed64Rules *msg, int64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_SFixed64Rules_set_lt(validate_SFixed64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
-}
-UPB_INLINE void validate_SFixed64Rules_set_lte(validate_SFixed64Rules *msg, int64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_SFixed64Rules_set_lte(validate_SFixed64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), int64_t) = value;
-}
-UPB_INLINE void validate_SFixed64Rules_set_gt(validate_SFixed64Rules *msg, int64_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_SFixed64Rules_set_gt(validate_SFixed64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), int64_t) = value;
-}
-UPB_INLINE void validate_SFixed64Rules_set_gte(validate_SFixed64Rules *msg, int64_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_SFixed64Rules_set_gte(validate_SFixed64Rules *msg, int64_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), int64_t) = value;
-}
-UPB_INLINE int64_t* validate_SFixed64Rules_mutable_in(validate_SFixed64Rules *msg, size_t *len) {
- return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
-}
-UPB_INLINE int64_t* validate_SFixed64Rules_resize_in(validate_SFixed64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int64_t* validate_SFixed64Rules_mutable_in(validate_SFixed64Rules *msg, size_t *len) {
+ return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 48), len);
+}
+UPB_INLINE int64_t* validate_SFixed64Rules_resize_in(validate_SFixed64Rules *msg, size_t len, upb_arena *arena) {
return (int64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(48, 48), len, UPB_TYPE_INT64, arena);
-}
-UPB_INLINE bool validate_SFixed64Rules_add_in(validate_SFixed64Rules *msg, int64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SFixed64Rules_add_in(validate_SFixed64Rules *msg, int64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(48, 48), UPB_SIZE(8, 8), UPB_TYPE_INT64, &val,
arena);
-}
-UPB_INLINE int64_t* validate_SFixed64Rules_mutable_not_in(validate_SFixed64Rules *msg, size_t *len) {
- return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
-}
-UPB_INLINE int64_t* validate_SFixed64Rules_resize_not_in(validate_SFixed64Rules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int64_t* validate_SFixed64Rules_mutable_not_in(validate_SFixed64Rules *msg, size_t *len) {
+ return (int64_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 56), len);
+}
+UPB_INLINE int64_t* validate_SFixed64Rules_resize_not_in(validate_SFixed64Rules *msg, size_t len, upb_arena *arena) {
return (int64_t*)_upb_array_resize_accessor(msg, UPB_SIZE(52, 56), len, UPB_TYPE_INT64, arena);
-}
-UPB_INLINE bool validate_SFixed64Rules_add_not_in(validate_SFixed64Rules *msg, int64_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_SFixed64Rules_add_not_in(validate_SFixed64Rules *msg, int64_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(52, 56), UPB_SIZE(8, 8), UPB_TYPE_INT64, &val,
arena);
-}
-
-/* validate.BoolRules */
-
-UPB_INLINE validate_BoolRules *validate_BoolRules_new(upb_arena *arena) {
+}
+
+/* validate.BoolRules */
+
+UPB_INLINE validate_BoolRules *validate_BoolRules_new(upb_arena *arena) {
return (validate_BoolRules *)_upb_msg_new(&validate_BoolRules_msginit, arena);
-}
-UPB_INLINE validate_BoolRules *validate_BoolRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_BoolRules *ret = validate_BoolRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_BoolRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_BoolRules_serialize(const validate_BoolRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_BoolRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_BoolRules *validate_BoolRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_BoolRules *ret = validate_BoolRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_BoolRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_BoolRules_serialize(const validate_BoolRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_BoolRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_BoolRules_has_const(const validate_BoolRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool validate_BoolRules_const(const validate_BoolRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
-
-UPB_INLINE void validate_BoolRules_set_const(validate_BoolRules *msg, bool value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void validate_BoolRules_set_const(validate_BoolRules *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-
-/* validate.StringRules */
-
-UPB_INLINE validate_StringRules *validate_StringRules_new(upb_arena *arena) {
+}
+
+/* validate.StringRules */
+
+UPB_INLINE validate_StringRules *validate_StringRules_new(upb_arena *arena) {
return (validate_StringRules *)_upb_msg_new(&validate_StringRules_msginit, arena);
-}
-UPB_INLINE validate_StringRules *validate_StringRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_StringRules *ret = validate_StringRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_StringRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_StringRules_serialize(const validate_StringRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_StringRules_msginit, arena, len);
-}
-
-typedef enum {
- validate_StringRules_well_known_email = 12,
- validate_StringRules_well_known_hostname = 13,
- validate_StringRules_well_known_ip = 14,
- validate_StringRules_well_known_ipv4 = 15,
- validate_StringRules_well_known_ipv6 = 16,
- validate_StringRules_well_known_uri = 17,
- validate_StringRules_well_known_uri_ref = 18,
+}
+UPB_INLINE validate_StringRules *validate_StringRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_StringRules *ret = validate_StringRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_StringRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_StringRules_serialize(const validate_StringRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_StringRules_msginit, arena, len);
+}
+
+typedef enum {
+ validate_StringRules_well_known_email = 12,
+ validate_StringRules_well_known_hostname = 13,
+ validate_StringRules_well_known_ip = 14,
+ validate_StringRules_well_known_ipv4 = 15,
+ validate_StringRules_well_known_ipv6 = 16,
+ validate_StringRules_well_known_uri = 17,
+ validate_StringRules_well_known_uri_ref = 18,
validate_StringRules_well_known_address = 21,
validate_StringRules_well_known_uuid = 22,
validate_StringRules_well_known_well_known_regex = 24,
- validate_StringRules_well_known_NOT_SET = 0
-} validate_StringRules_well_known_oneofcases;
+ validate_StringRules_well_known_NOT_SET = 0
+} validate_StringRules_well_known_oneofcases;
UPB_INLINE validate_StringRules_well_known_oneofcases validate_StringRules_well_known_case(const validate_StringRules* msg) { return (validate_StringRules_well_known_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(128, 184), int32_t); }
-
+
UPB_INLINE bool validate_StringRules_has_const(const validate_StringRules *msg) { return _upb_hasbit(msg, 8); }
UPB_INLINE upb_strview validate_StringRules_const(const validate_StringRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(60, 64), upb_strview); }
UPB_INLINE bool validate_StringRules_has_min_len(const validate_StringRules *msg) { return _upb_hasbit(msg, 1); }
@@ -1366,92 +1366,92 @@ UPB_INLINE bool validate_StringRules_has_well_known_regex(const validate_StringR
UPB_INLINE int32_t validate_StringRules_well_known_regex(const validate_StringRules *msg) { return UPB_READ_ONEOF(msg, int32_t, UPB_SIZE(120, 176), UPB_SIZE(128, 184), 24, 0); }
UPB_INLINE bool validate_StringRules_has_strict(const validate_StringRules *msg) { return _upb_hasbit(msg, 7); }
UPB_INLINE bool validate_StringRules_strict(const validate_StringRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(56, 56), bool); }
-
-UPB_INLINE void validate_StringRules_set_const(validate_StringRules *msg, upb_strview value) {
+
+UPB_INLINE void validate_StringRules_set_const(validate_StringRules *msg, upb_strview value) {
_upb_sethas(msg, 8);
*UPB_PTR_AT(msg, UPB_SIZE(60, 64), upb_strview) = value;
-}
-UPB_INLINE void validate_StringRules_set_min_len(validate_StringRules *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void validate_StringRules_set_min_len(validate_StringRules *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void validate_StringRules_set_max_len(validate_StringRules *msg, uint64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_StringRules_set_max_len(validate_StringRules *msg, uint64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
-UPB_INLINE void validate_StringRules_set_min_bytes(validate_StringRules *msg, uint64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_StringRules_set_min_bytes(validate_StringRules *msg, uint64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), uint64_t) = value;
-}
-UPB_INLINE void validate_StringRules_set_max_bytes(validate_StringRules *msg, uint64_t value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_StringRules_set_max_bytes(validate_StringRules *msg, uint64_t value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), uint64_t) = value;
-}
-UPB_INLINE void validate_StringRules_set_pattern(validate_StringRules *msg, upb_strview value) {
+}
+UPB_INLINE void validate_StringRules_set_pattern(validate_StringRules *msg, upb_strview value) {
_upb_sethas(msg, 9);
*UPB_PTR_AT(msg, UPB_SIZE(68, 80), upb_strview) = value;
-}
-UPB_INLINE void validate_StringRules_set_prefix(validate_StringRules *msg, upb_strview value) {
+}
+UPB_INLINE void validate_StringRules_set_prefix(validate_StringRules *msg, upb_strview value) {
_upb_sethas(msg, 10);
*UPB_PTR_AT(msg, UPB_SIZE(76, 96), upb_strview) = value;
-}
-UPB_INLINE void validate_StringRules_set_suffix(validate_StringRules *msg, upb_strview value) {
+}
+UPB_INLINE void validate_StringRules_set_suffix(validate_StringRules *msg, upb_strview value) {
_upb_sethas(msg, 11);
*UPB_PTR_AT(msg, UPB_SIZE(84, 112), upb_strview) = value;
-}
-UPB_INLINE void validate_StringRules_set_contains(validate_StringRules *msg, upb_strview value) {
+}
+UPB_INLINE void validate_StringRules_set_contains(validate_StringRules *msg, upb_strview value) {
_upb_sethas(msg, 12);
*UPB_PTR_AT(msg, UPB_SIZE(92, 128), upb_strview) = value;
-}
-UPB_INLINE upb_strview* validate_StringRules_mutable_in(validate_StringRules *msg, size_t *len) {
+}
+UPB_INLINE upb_strview* validate_StringRules_mutable_in(validate_StringRules *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(108, 160), len);
-}
-UPB_INLINE upb_strview* validate_StringRules_resize_in(validate_StringRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* validate_StringRules_resize_in(validate_StringRules *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(108, 160), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool validate_StringRules_add_in(validate_StringRules *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_StringRules_add_in(validate_StringRules *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(108, 160), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE upb_strview* validate_StringRules_mutable_not_in(validate_StringRules *msg, size_t *len) {
+}
+UPB_INLINE upb_strview* validate_StringRules_mutable_not_in(validate_StringRules *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(112, 168), len);
-}
-UPB_INLINE upb_strview* validate_StringRules_resize_not_in(validate_StringRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* validate_StringRules_resize_not_in(validate_StringRules *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(112, 168), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool validate_StringRules_add_not_in(validate_StringRules *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_StringRules_add_not_in(validate_StringRules *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(112, 168), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE void validate_StringRules_set_email(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_email(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 12);
-}
-UPB_INLINE void validate_StringRules_set_hostname(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_hostname(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 13);
-}
-UPB_INLINE void validate_StringRules_set_ip(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_ip(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 14);
-}
-UPB_INLINE void validate_StringRules_set_ipv4(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_ipv4(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 15);
-}
-UPB_INLINE void validate_StringRules_set_ipv6(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_ipv6(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 16);
-}
-UPB_INLINE void validate_StringRules_set_uri(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_uri(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 17);
-}
-UPB_INLINE void validate_StringRules_set_uri_ref(validate_StringRules *msg, bool value) {
+}
+UPB_INLINE void validate_StringRules_set_uri_ref(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 18);
-}
-UPB_INLINE void validate_StringRules_set_len(validate_StringRules *msg, uint64_t value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_StringRules_set_len(validate_StringRules *msg, uint64_t value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 40), uint64_t) = value;
-}
-UPB_INLINE void validate_StringRules_set_len_bytes(validate_StringRules *msg, uint64_t value) {
- _upb_sethas(msg, 6);
+}
+UPB_INLINE void validate_StringRules_set_len_bytes(validate_StringRules *msg, uint64_t value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(48, 48), uint64_t) = value;
-}
+}
UPB_INLINE void validate_StringRules_set_address(validate_StringRules *msg, bool value) {
UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(120, 176), value, UPB_SIZE(128, 184), 21);
}
@@ -1469,29 +1469,29 @@ UPB_INLINE void validate_StringRules_set_strict(validate_StringRules *msg, bool
_upb_sethas(msg, 7);
*UPB_PTR_AT(msg, UPB_SIZE(56, 56), bool) = value;
}
-
-/* validate.BytesRules */
-
-UPB_INLINE validate_BytesRules *validate_BytesRules_new(upb_arena *arena) {
+
+/* validate.BytesRules */
+
+UPB_INLINE validate_BytesRules *validate_BytesRules_new(upb_arena *arena) {
return (validate_BytesRules *)_upb_msg_new(&validate_BytesRules_msginit, arena);
-}
-UPB_INLINE validate_BytesRules *validate_BytesRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_BytesRules *ret = validate_BytesRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_BytesRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_BytesRules_serialize(const validate_BytesRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_BytesRules_msginit, arena, len);
-}
-
-typedef enum {
- validate_BytesRules_well_known_ip = 10,
- validate_BytesRules_well_known_ipv4 = 11,
- validate_BytesRules_well_known_ipv6 = 12,
- validate_BytesRules_well_known_NOT_SET = 0
-} validate_BytesRules_well_known_oneofcases;
+}
+UPB_INLINE validate_BytesRules *validate_BytesRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_BytesRules *ret = validate_BytesRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_BytesRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_BytesRules_serialize(const validate_BytesRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_BytesRules_msginit, arena, len);
+}
+
+typedef enum {
+ validate_BytesRules_well_known_ip = 10,
+ validate_BytesRules_well_known_ipv4 = 11,
+ validate_BytesRules_well_known_ipv6 = 12,
+ validate_BytesRules_well_known_NOT_SET = 0
+} validate_BytesRules_well_known_oneofcases;
UPB_INLINE validate_BytesRules_well_known_oneofcases validate_BytesRules_well_known_case(const validate_BytesRules* msg) { return (validate_BytesRules_well_known_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(84, 132), int32_t); }
-
+
UPB_INLINE bool validate_BytesRules_has_const(const validate_BytesRules *msg) { return _upb_hasbit(msg, 4); }
UPB_INLINE upb_strview validate_BytesRules_const(const validate_BytesRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview); }
UPB_INLINE bool validate_BytesRules_has_min_len(const validate_BytesRules *msg) { return _upb_hasbit(msg, 1); }
@@ -1506,171 +1506,171 @@ UPB_INLINE bool validate_BytesRules_has_suffix(const validate_BytesRules *msg) {
UPB_INLINE upb_strview validate_BytesRules_suffix(const validate_BytesRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(56, 80), upb_strview); }
UPB_INLINE bool validate_BytesRules_has_contains(const validate_BytesRules *msg) { return _upb_hasbit(msg, 8); }
UPB_INLINE upb_strview validate_BytesRules_contains(const validate_BytesRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(64, 96), upb_strview); }
-UPB_INLINE upb_strview const* validate_BytesRules_in(const validate_BytesRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(72, 112), len); }
-UPB_INLINE upb_strview const* validate_BytesRules_not_in(const validate_BytesRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(76, 120), len); }
+UPB_INLINE upb_strview const* validate_BytesRules_in(const validate_BytesRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(72, 112), len); }
+UPB_INLINE upb_strview const* validate_BytesRules_not_in(const validate_BytesRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(76, 120), len); }
UPB_INLINE bool validate_BytesRules_has_ip(const validate_BytesRules *msg) { return _upb_getoneofcase(msg, UPB_SIZE(84, 132)) == 10; }
-UPB_INLINE bool validate_BytesRules_ip(const validate_BytesRules *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(80, 128), UPB_SIZE(84, 132), 10, false); }
+UPB_INLINE bool validate_BytesRules_ip(const validate_BytesRules *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(80, 128), UPB_SIZE(84, 132), 10, false); }
UPB_INLINE bool validate_BytesRules_has_ipv4(const validate_BytesRules *msg) { return _upb_getoneofcase(msg, UPB_SIZE(84, 132)) == 11; }
-UPB_INLINE bool validate_BytesRules_ipv4(const validate_BytesRules *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(80, 128), UPB_SIZE(84, 132), 11, false); }
+UPB_INLINE bool validate_BytesRules_ipv4(const validate_BytesRules *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(80, 128), UPB_SIZE(84, 132), 11, false); }
UPB_INLINE bool validate_BytesRules_has_ipv6(const validate_BytesRules *msg) { return _upb_getoneofcase(msg, UPB_SIZE(84, 132)) == 12; }
-UPB_INLINE bool validate_BytesRules_ipv6(const validate_BytesRules *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(80, 128), UPB_SIZE(84, 132), 12, false); }
+UPB_INLINE bool validate_BytesRules_ipv6(const validate_BytesRules *msg) { return UPB_READ_ONEOF(msg, bool, UPB_SIZE(80, 128), UPB_SIZE(84, 132), 12, false); }
UPB_INLINE bool validate_BytesRules_has_len(const validate_BytesRules *msg) { return _upb_hasbit(msg, 3); }
UPB_INLINE uint64_t validate_BytesRules_len(const validate_BytesRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), uint64_t); }
-
-UPB_INLINE void validate_BytesRules_set_const(validate_BytesRules *msg, upb_strview value) {
- _upb_sethas(msg, 4);
+
+UPB_INLINE void validate_BytesRules_set_const(validate_BytesRules *msg, upb_strview value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview) = value;
-}
-UPB_INLINE void validate_BytesRules_set_min_len(validate_BytesRules *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+}
+UPB_INLINE void validate_BytesRules_set_min_len(validate_BytesRules *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void validate_BytesRules_set_max_len(validate_BytesRules *msg, uint64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_BytesRules_set_max_len(validate_BytesRules *msg, uint64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
-UPB_INLINE void validate_BytesRules_set_pattern(validate_BytesRules *msg, upb_strview value) {
- _upb_sethas(msg, 5);
+}
+UPB_INLINE void validate_BytesRules_set_pattern(validate_BytesRules *msg, upb_strview value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview) = value;
-}
-UPB_INLINE void validate_BytesRules_set_prefix(validate_BytesRules *msg, upb_strview value) {
- _upb_sethas(msg, 6);
+}
+UPB_INLINE void validate_BytesRules_set_prefix(validate_BytesRules *msg, upb_strview value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview) = value;
-}
-UPB_INLINE void validate_BytesRules_set_suffix(validate_BytesRules *msg, upb_strview value) {
- _upb_sethas(msg, 7);
+}
+UPB_INLINE void validate_BytesRules_set_suffix(validate_BytesRules *msg, upb_strview value) {
+ _upb_sethas(msg, 7);
*UPB_PTR_AT(msg, UPB_SIZE(56, 80), upb_strview) = value;
-}
-UPB_INLINE void validate_BytesRules_set_contains(validate_BytesRules *msg, upb_strview value) {
- _upb_sethas(msg, 8);
+}
+UPB_INLINE void validate_BytesRules_set_contains(validate_BytesRules *msg, upb_strview value) {
+ _upb_sethas(msg, 8);
*UPB_PTR_AT(msg, UPB_SIZE(64, 96), upb_strview) = value;
-}
-UPB_INLINE upb_strview* validate_BytesRules_mutable_in(validate_BytesRules *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(72, 112), len);
-}
-UPB_INLINE upb_strview* validate_BytesRules_resize_in(validate_BytesRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* validate_BytesRules_mutable_in(validate_BytesRules *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(72, 112), len);
+}
+UPB_INLINE upb_strview* validate_BytesRules_resize_in(validate_BytesRules *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(72, 112), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool validate_BytesRules_add_in(validate_BytesRules *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_BytesRules_add_in(validate_BytesRules *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(72, 112), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE upb_strview* validate_BytesRules_mutable_not_in(validate_BytesRules *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(76, 120), len);
-}
-UPB_INLINE upb_strview* validate_BytesRules_resize_not_in(validate_BytesRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* validate_BytesRules_mutable_not_in(validate_BytesRules *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(76, 120), len);
+}
+UPB_INLINE upb_strview* validate_BytesRules_resize_not_in(validate_BytesRules *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(76, 120), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool validate_BytesRules_add_not_in(validate_BytesRules *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_BytesRules_add_not_in(validate_BytesRules *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(76, 120), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE void validate_BytesRules_set_ip(validate_BytesRules *msg, bool value) {
- UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(80, 128), value, UPB_SIZE(84, 132), 10);
-}
-UPB_INLINE void validate_BytesRules_set_ipv4(validate_BytesRules *msg, bool value) {
- UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(80, 128), value, UPB_SIZE(84, 132), 11);
-}
-UPB_INLINE void validate_BytesRules_set_ipv6(validate_BytesRules *msg, bool value) {
- UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(80, 128), value, UPB_SIZE(84, 132), 12);
-}
-UPB_INLINE void validate_BytesRules_set_len(validate_BytesRules *msg, uint64_t value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_BytesRules_set_ip(validate_BytesRules *msg, bool value) {
+ UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(80, 128), value, UPB_SIZE(84, 132), 10);
+}
+UPB_INLINE void validate_BytesRules_set_ipv4(validate_BytesRules *msg, bool value) {
+ UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(80, 128), value, UPB_SIZE(84, 132), 11);
+}
+UPB_INLINE void validate_BytesRules_set_ipv6(validate_BytesRules *msg, bool value) {
+ UPB_WRITE_ONEOF(msg, bool, UPB_SIZE(80, 128), value, UPB_SIZE(84, 132), 12);
+}
+UPB_INLINE void validate_BytesRules_set_len(validate_BytesRules *msg, uint64_t value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), uint64_t) = value;
-}
-
-/* validate.EnumRules */
-
-UPB_INLINE validate_EnumRules *validate_EnumRules_new(upb_arena *arena) {
+}
+
+/* validate.EnumRules */
+
+UPB_INLINE validate_EnumRules *validate_EnumRules_new(upb_arena *arena) {
return (validate_EnumRules *)_upb_msg_new(&validate_EnumRules_msginit, arena);
-}
-UPB_INLINE validate_EnumRules *validate_EnumRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_EnumRules *ret = validate_EnumRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_EnumRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_EnumRules_serialize(const validate_EnumRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_EnumRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_EnumRules *validate_EnumRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_EnumRules *ret = validate_EnumRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_EnumRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_EnumRules_serialize(const validate_EnumRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_EnumRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_EnumRules_has_const(const validate_EnumRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE int32_t validate_EnumRules_const(const validate_EnumRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool validate_EnumRules_has_defined_only(const validate_EnumRules *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE bool validate_EnumRules_defined_only(const validate_EnumRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), bool); }
-UPB_INLINE int32_t const* validate_EnumRules_in(const validate_EnumRules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(12, 16), len); }
-UPB_INLINE int32_t const* validate_EnumRules_not_in(const validate_EnumRules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(16, 24), len); }
-
-UPB_INLINE void validate_EnumRules_set_const(validate_EnumRules *msg, int32_t value) {
- _upb_sethas(msg, 1);
+UPB_INLINE int32_t const* validate_EnumRules_in(const validate_EnumRules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(12, 16), len); }
+UPB_INLINE int32_t const* validate_EnumRules_not_in(const validate_EnumRules *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(16, 24), len); }
+
+UPB_INLINE void validate_EnumRules_set_const(validate_EnumRules *msg, int32_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
-}
-UPB_INLINE void validate_EnumRules_set_defined_only(validate_EnumRules *msg, bool value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_EnumRules_set_defined_only(validate_EnumRules *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), bool) = value;
-}
-UPB_INLINE int32_t* validate_EnumRules_mutable_in(validate_EnumRules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(12, 16), len);
-}
-UPB_INLINE int32_t* validate_EnumRules_resize_in(validate_EnumRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_EnumRules_mutable_in(validate_EnumRules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(12, 16), len);
+}
+UPB_INLINE int32_t* validate_EnumRules_resize_in(validate_EnumRules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(12, 16), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_EnumRules_add_in(validate_EnumRules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_EnumRules_add_in(validate_EnumRules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(12, 16), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-UPB_INLINE int32_t* validate_EnumRules_mutable_not_in(validate_EnumRules *msg, size_t *len) {
- return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 24), len);
-}
-UPB_INLINE int32_t* validate_EnumRules_resize_not_in(validate_EnumRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE int32_t* validate_EnumRules_mutable_not_in(validate_EnumRules *msg, size_t *len) {
+ return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 24), len);
+}
+UPB_INLINE int32_t* validate_EnumRules_resize_not_in(validate_EnumRules *msg, size_t len, upb_arena *arena) {
return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(16, 24), len, UPB_TYPE_INT32, arena);
-}
-UPB_INLINE bool validate_EnumRules_add_not_in(validate_EnumRules *msg, int32_t val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_EnumRules_add_not_in(validate_EnumRules *msg, int32_t val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(16, 24), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
arena);
-}
-
-/* validate.MessageRules */
-
-UPB_INLINE validate_MessageRules *validate_MessageRules_new(upb_arena *arena) {
+}
+
+/* validate.MessageRules */
+
+UPB_INLINE validate_MessageRules *validate_MessageRules_new(upb_arena *arena) {
return (validate_MessageRules *)_upb_msg_new(&validate_MessageRules_msginit, arena);
-}
-UPB_INLINE validate_MessageRules *validate_MessageRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_MessageRules *ret = validate_MessageRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_MessageRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_MessageRules_serialize(const validate_MessageRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_MessageRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_MessageRules *validate_MessageRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_MessageRules *ret = validate_MessageRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_MessageRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_MessageRules_serialize(const validate_MessageRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_MessageRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_MessageRules_has_skip(const validate_MessageRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool validate_MessageRules_skip(const validate_MessageRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool validate_MessageRules_has_required(const validate_MessageRules *msg) { return _upb_hasbit(msg, 2); }
UPB_INLINE bool validate_MessageRules_required(const validate_MessageRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
-
-UPB_INLINE void validate_MessageRules_set_skip(validate_MessageRules *msg, bool value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void validate_MessageRules_set_skip(validate_MessageRules *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE void validate_MessageRules_set_required(validate_MessageRules *msg, bool value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_MessageRules_set_required(validate_MessageRules *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
-}
-
-/* validate.RepeatedRules */
-
-UPB_INLINE validate_RepeatedRules *validate_RepeatedRules_new(upb_arena *arena) {
+}
+
+/* validate.RepeatedRules */
+
+UPB_INLINE validate_RepeatedRules *validate_RepeatedRules_new(upb_arena *arena) {
return (validate_RepeatedRules *)_upb_msg_new(&validate_RepeatedRules_msginit, arena);
-}
-UPB_INLINE validate_RepeatedRules *validate_RepeatedRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_RepeatedRules *ret = validate_RepeatedRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_RepeatedRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_RepeatedRules_serialize(const validate_RepeatedRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_RepeatedRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_RepeatedRules *validate_RepeatedRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_RepeatedRules *ret = validate_RepeatedRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_RepeatedRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_RepeatedRules_serialize(const validate_RepeatedRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_RepeatedRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_RepeatedRules_has_min_items(const validate_RepeatedRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE uint64_t validate_RepeatedRules_min_items(const validate_RepeatedRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t); }
UPB_INLINE bool validate_RepeatedRules_has_max_items(const validate_RepeatedRules *msg) { return _upb_hasbit(msg, 2); }
@@ -1679,47 +1679,47 @@ UPB_INLINE bool validate_RepeatedRules_has_unique(const validate_RepeatedRules *
UPB_INLINE bool validate_RepeatedRules_unique(const validate_RepeatedRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool); }
UPB_INLINE bool validate_RepeatedRules_has_items(const validate_RepeatedRules *msg) { return _upb_hasbit(msg, 4); }
UPB_INLINE const validate_FieldRules* validate_RepeatedRules_items(const validate_RepeatedRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 32), const validate_FieldRules*); }
-
-UPB_INLINE void validate_RepeatedRules_set_min_items(validate_RepeatedRules *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void validate_RepeatedRules_set_min_items(validate_RepeatedRules *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void validate_RepeatedRules_set_max_items(validate_RepeatedRules *msg, uint64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_RepeatedRules_set_max_items(validate_RepeatedRules *msg, uint64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
-UPB_INLINE void validate_RepeatedRules_set_unique(validate_RepeatedRules *msg, bool value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_RepeatedRules_set_unique(validate_RepeatedRules *msg, bool value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
-}
-UPB_INLINE void validate_RepeatedRules_set_items(validate_RepeatedRules *msg, validate_FieldRules* value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_RepeatedRules_set_items(validate_RepeatedRules *msg, validate_FieldRules* value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(28, 32), validate_FieldRules*) = value;
-}
-UPB_INLINE struct validate_FieldRules* validate_RepeatedRules_mutable_items(validate_RepeatedRules *msg, upb_arena *arena) {
- struct validate_FieldRules* sub = (struct validate_FieldRules*)validate_RepeatedRules_items(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_FieldRules* validate_RepeatedRules_mutable_items(validate_RepeatedRules *msg, upb_arena *arena) {
+ struct validate_FieldRules* sub = (struct validate_FieldRules*)validate_RepeatedRules_items(msg);
+ if (sub == NULL) {
sub = (struct validate_FieldRules*)_upb_msg_new(&validate_FieldRules_msginit, arena);
- if (!sub) return NULL;
- validate_RepeatedRules_set_items(msg, sub);
- }
- return sub;
-}
-
-/* validate.MapRules */
-
-UPB_INLINE validate_MapRules *validate_MapRules_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ validate_RepeatedRules_set_items(msg, sub);
+ }
+ return sub;
+}
+
+/* validate.MapRules */
+
+UPB_INLINE validate_MapRules *validate_MapRules_new(upb_arena *arena) {
return (validate_MapRules *)_upb_msg_new(&validate_MapRules_msginit, arena);
-}
-UPB_INLINE validate_MapRules *validate_MapRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_MapRules *ret = validate_MapRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_MapRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_MapRules_serialize(const validate_MapRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_MapRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_MapRules *validate_MapRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_MapRules *ret = validate_MapRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_MapRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_MapRules_serialize(const validate_MapRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_MapRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_MapRules_has_min_pairs(const validate_MapRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE uint64_t validate_MapRules_min_pairs(const validate_MapRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t); }
UPB_INLINE bool validate_MapRules_has_max_pairs(const validate_MapRules *msg) { return _upb_hasbit(msg, 2); }
@@ -1730,104 +1730,104 @@ UPB_INLINE bool validate_MapRules_has_keys(const validate_MapRules *msg) { retur
UPB_INLINE const validate_FieldRules* validate_MapRules_keys(const validate_MapRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 32), const validate_FieldRules*); }
UPB_INLINE bool validate_MapRules_has_values(const validate_MapRules *msg) { return _upb_hasbit(msg, 5); }
UPB_INLINE const validate_FieldRules* validate_MapRules_values(const validate_MapRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 40), const validate_FieldRules*); }
-
-UPB_INLINE void validate_MapRules_set_min_pairs(validate_MapRules *msg, uint64_t value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void validate_MapRules_set_min_pairs(validate_MapRules *msg, uint64_t value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
-}
-UPB_INLINE void validate_MapRules_set_max_pairs(validate_MapRules *msg, uint64_t value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_MapRules_set_max_pairs(validate_MapRules *msg, uint64_t value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(16, 16), uint64_t) = value;
-}
-UPB_INLINE void validate_MapRules_set_no_sparse(validate_MapRules *msg, bool value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_MapRules_set_no_sparse(validate_MapRules *msg, bool value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
-}
-UPB_INLINE void validate_MapRules_set_keys(validate_MapRules *msg, validate_FieldRules* value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_MapRules_set_keys(validate_MapRules *msg, validate_FieldRules* value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(28, 32), validate_FieldRules*) = value;
-}
-UPB_INLINE struct validate_FieldRules* validate_MapRules_mutable_keys(validate_MapRules *msg, upb_arena *arena) {
- struct validate_FieldRules* sub = (struct validate_FieldRules*)validate_MapRules_keys(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_FieldRules* validate_MapRules_mutable_keys(validate_MapRules *msg, upb_arena *arena) {
+ struct validate_FieldRules* sub = (struct validate_FieldRules*)validate_MapRules_keys(msg);
+ if (sub == NULL) {
sub = (struct validate_FieldRules*)_upb_msg_new(&validate_FieldRules_msginit, arena);
- if (!sub) return NULL;
- validate_MapRules_set_keys(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_MapRules_set_values(validate_MapRules *msg, validate_FieldRules* value) {
- _upb_sethas(msg, 5);
+ if (!sub) return NULL;
+ validate_MapRules_set_keys(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_MapRules_set_values(validate_MapRules *msg, validate_FieldRules* value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(32, 40), validate_FieldRules*) = value;
-}
-UPB_INLINE struct validate_FieldRules* validate_MapRules_mutable_values(validate_MapRules *msg, upb_arena *arena) {
- struct validate_FieldRules* sub = (struct validate_FieldRules*)validate_MapRules_values(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct validate_FieldRules* validate_MapRules_mutable_values(validate_MapRules *msg, upb_arena *arena) {
+ struct validate_FieldRules* sub = (struct validate_FieldRules*)validate_MapRules_values(msg);
+ if (sub == NULL) {
sub = (struct validate_FieldRules*)_upb_msg_new(&validate_FieldRules_msginit, arena);
- if (!sub) return NULL;
- validate_MapRules_set_values(msg, sub);
- }
- return sub;
-}
-
-/* validate.AnyRules */
-
-UPB_INLINE validate_AnyRules *validate_AnyRules_new(upb_arena *arena) {
+ if (!sub) return NULL;
+ validate_MapRules_set_values(msg, sub);
+ }
+ return sub;
+}
+
+/* validate.AnyRules */
+
+UPB_INLINE validate_AnyRules *validate_AnyRules_new(upb_arena *arena) {
return (validate_AnyRules *)_upb_msg_new(&validate_AnyRules_msginit, arena);
-}
-UPB_INLINE validate_AnyRules *validate_AnyRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_AnyRules *ret = validate_AnyRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_AnyRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_AnyRules_serialize(const validate_AnyRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_AnyRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_AnyRules *validate_AnyRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_AnyRules *ret = validate_AnyRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_AnyRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_AnyRules_serialize(const validate_AnyRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_AnyRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_AnyRules_has_required(const validate_AnyRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool validate_AnyRules_required(const validate_AnyRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
-UPB_INLINE upb_strview const* validate_AnyRules_in(const validate_AnyRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
-UPB_INLINE upb_strview const* validate_AnyRules_not_in(const validate_AnyRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(8, 16), len); }
-
-UPB_INLINE void validate_AnyRules_set_required(validate_AnyRules *msg, bool value) {
- _upb_sethas(msg, 1);
+UPB_INLINE upb_strview const* validate_AnyRules_in(const validate_AnyRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
+UPB_INLINE upb_strview const* validate_AnyRules_not_in(const validate_AnyRules *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(8, 16), len); }
+
+UPB_INLINE void validate_AnyRules_set_required(validate_AnyRules *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE upb_strview* validate_AnyRules_mutable_in(validate_AnyRules *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
-}
-UPB_INLINE upb_strview* validate_AnyRules_resize_in(validate_AnyRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* validate_AnyRules_mutable_in(validate_AnyRules *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
+}
+UPB_INLINE upb_strview* validate_AnyRules_resize_in(validate_AnyRules *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool validate_AnyRules_add_in(validate_AnyRules *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_AnyRules_add_in(validate_AnyRules *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(4, 8), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-UPB_INLINE upb_strview* validate_AnyRules_mutable_not_in(validate_AnyRules *msg, size_t *len) {
- return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 16), len);
-}
-UPB_INLINE upb_strview* validate_AnyRules_resize_not_in(validate_AnyRules *msg, size_t len, upb_arena *arena) {
+}
+UPB_INLINE upb_strview* validate_AnyRules_mutable_not_in(validate_AnyRules *msg, size_t *len) {
+ return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 16), len);
+}
+UPB_INLINE upb_strview* validate_AnyRules_resize_not_in(validate_AnyRules *msg, size_t len, upb_arena *arena) {
return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(8, 16), len, UPB_TYPE_STRING, arena);
-}
-UPB_INLINE bool validate_AnyRules_add_not_in(validate_AnyRules *msg, upb_strview val, upb_arena *arena) {
+}
+UPB_INLINE bool validate_AnyRules_add_not_in(validate_AnyRules *msg, upb_strview val, upb_arena *arena) {
return _upb_array_append_accessor(msg, UPB_SIZE(8, 16), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
arena);
-}
-
-/* validate.DurationRules */
-
-UPB_INLINE validate_DurationRules *validate_DurationRules_new(upb_arena *arena) {
+}
+
+/* validate.DurationRules */
+
+UPB_INLINE validate_DurationRules *validate_DurationRules_new(upb_arena *arena) {
return (validate_DurationRules *)_upb_msg_new(&validate_DurationRules_msginit, arena);
-}
-UPB_INLINE validate_DurationRules *validate_DurationRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_DurationRules *ret = validate_DurationRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_DurationRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_DurationRules_serialize(const validate_DurationRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_DurationRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_DurationRules *validate_DurationRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_DurationRules *ret = validate_DurationRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_DurationRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_DurationRules_serialize(const validate_DurationRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_DurationRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_DurationRules_has_required(const validate_DurationRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool validate_DurationRules_required(const validate_DurationRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool validate_DurationRules_has_const(const validate_DurationRules *msg) { return _upb_hasbit(msg, 2); }
@@ -1841,120 +1841,120 @@ UPB_INLINE const struct google_protobuf_Duration* validate_DurationRules_gt(cons
UPB_INLINE bool validate_DurationRules_has_gte(const validate_DurationRules *msg) { return _upb_hasbit(msg, 6); }
UPB_INLINE const struct google_protobuf_Duration* validate_DurationRules_gte(const validate_DurationRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), const struct google_protobuf_Duration*); }
UPB_INLINE bool validate_DurationRules_has_in(const validate_DurationRules *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(24, 48)); }
-UPB_INLINE const struct google_protobuf_Duration* const* validate_DurationRules_in(const validate_DurationRules *msg, size_t *len) { return (const struct google_protobuf_Duration* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+UPB_INLINE const struct google_protobuf_Duration* const* validate_DurationRules_in(const validate_DurationRules *msg, size_t *len) { return (const struct google_protobuf_Duration* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE bool validate_DurationRules_has_not_in(const validate_DurationRules *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 56)); }
-UPB_INLINE const struct google_protobuf_Duration* const* validate_DurationRules_not_in(const validate_DurationRules *msg, size_t *len) { return (const struct google_protobuf_Duration* const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
-
-UPB_INLINE void validate_DurationRules_set_required(validate_DurationRules *msg, bool value) {
- _upb_sethas(msg, 1);
+UPB_INLINE const struct google_protobuf_Duration* const* validate_DurationRules_not_in(const validate_DurationRules *msg, size_t *len) { return (const struct google_protobuf_Duration* const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
+
+UPB_INLINE void validate_DurationRules_set_required(validate_DurationRules *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
-}
-UPB_INLINE void validate_DurationRules_set_const(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
- _upb_sethas(msg, 2);
+}
+UPB_INLINE void validate_DurationRules_set_const(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_const(validate_DurationRules *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_const(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_const(validate_DurationRules *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_const(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- validate_DurationRules_set_const(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_DurationRules_set_lt(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
- _upb_sethas(msg, 3);
+ if (!sub) return NULL;
+ validate_DurationRules_set_const(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_DurationRules_set_lt(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_lt(validate_DurationRules *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_lt(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_lt(validate_DurationRules *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_lt(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- validate_DurationRules_set_lt(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_DurationRules_set_lte(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
- _upb_sethas(msg, 4);
+ if (!sub) return NULL;
+ validate_DurationRules_set_lt(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_DurationRules_set_lte(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_lte(validate_DurationRules *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_lte(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_lte(validate_DurationRules *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_lte(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- validate_DurationRules_set_lte(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_DurationRules_set_gt(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
- _upb_sethas(msg, 5);
+ if (!sub) return NULL;
+ validate_DurationRules_set_lte(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_DurationRules_set_gt(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(16, 32), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_gt(validate_DurationRules *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_gt(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_gt(validate_DurationRules *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_gt(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- validate_DurationRules_set_gt(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_DurationRules_set_gte(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
- _upb_sethas(msg, 6);
+ if (!sub) return NULL;
+ validate_DurationRules_set_gt(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_DurationRules_set_gte(validate_DurationRules *msg, struct google_protobuf_Duration* value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(20, 40), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_gte(validate_DurationRules *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_gte(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_mutable_gte(validate_DurationRules *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_DurationRules_gte(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- validate_DurationRules_set_gte(msg, sub);
- }
- return sub;
-}
-UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_mutable_in(validate_DurationRules *msg, size_t *len) {
- return (struct google_protobuf_Duration**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
-}
-UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_resize_in(validate_DurationRules *msg, size_t len, upb_arena *arena) {
+ if (!sub) return NULL;
+ validate_DurationRules_set_gte(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_mutable_in(validate_DurationRules *msg, size_t *len) {
+ return (struct google_protobuf_Duration**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
+}
+UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_resize_in(validate_DurationRules *msg, size_t len, upb_arena *arena) {
return (struct google_protobuf_Duration**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_add_in(validate_DurationRules *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_add_in(validate_DurationRules *msg, upb_arena *arena) {
struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_mutable_not_in(validate_DurationRules *msg, size_t *len) {
- return (struct google_protobuf_Duration**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
-}
-UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_resize_not_in(validate_DurationRules *msg, size_t len, upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_mutable_not_in(validate_DurationRules *msg, size_t *len) {
+ return (struct google_protobuf_Duration**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
+}
+UPB_INLINE struct google_protobuf_Duration** validate_DurationRules_resize_not_in(validate_DurationRules *msg, size_t len, upb_arena *arena) {
return (struct google_protobuf_Duration**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_MESSAGE, arena);
-}
-UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_add_not_in(validate_DurationRules *msg, upb_arena *arena) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_DurationRules_add_not_in(validate_DurationRules *msg, upb_arena *arena) {
struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- bool ok = _upb_array_append_accessor(
- msg, UPB_SIZE(28, 56), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
- if (!ok) return NULL;
- return sub;
-}
-
-/* validate.TimestampRules */
-
-UPB_INLINE validate_TimestampRules *validate_TimestampRules_new(upb_arena *arena) {
+ bool ok = _upb_array_append_accessor(
+ msg, UPB_SIZE(28, 56), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
+ if (!ok) return NULL;
+ return sub;
+}
+
+/* validate.TimestampRules */
+
+UPB_INLINE validate_TimestampRules *validate_TimestampRules_new(upb_arena *arena) {
return (validate_TimestampRules *)_upb_msg_new(&validate_TimestampRules_msginit, arena);
-}
-UPB_INLINE validate_TimestampRules *validate_TimestampRules_parse(const char *buf, size_t size,
- upb_arena *arena) {
- validate_TimestampRules *ret = validate_TimestampRules_new(arena);
- return (ret && upb_decode(buf, size, ret, &validate_TimestampRules_msginit, arena)) ? ret : NULL;
-}
-UPB_INLINE char *validate_TimestampRules_serialize(const validate_TimestampRules *msg, upb_arena *arena, size_t *len) {
- return upb_encode(msg, &validate_TimestampRules_msginit, arena, len);
-}
-
+}
+UPB_INLINE validate_TimestampRules *validate_TimestampRules_parse(const char *buf, size_t size,
+ upb_arena *arena) {
+ validate_TimestampRules *ret = validate_TimestampRules_new(arena);
+ return (ret && upb_decode(buf, size, ret, &validate_TimestampRules_msginit, arena)) ? ret : NULL;
+}
+UPB_INLINE char *validate_TimestampRules_serialize(const validate_TimestampRules *msg, upb_arena *arena, size_t *len) {
+ return upb_encode(msg, &validate_TimestampRules_msginit, arena, len);
+}
+
UPB_INLINE bool validate_TimestampRules_has_required(const validate_TimestampRules *msg) { return _upb_hasbit(msg, 1); }
UPB_INLINE bool validate_TimestampRules_required(const validate_TimestampRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
UPB_INLINE bool validate_TimestampRules_has_const(const validate_TimestampRules *msg) { return _upb_hasbit(msg, 4); }
@@ -1973,102 +1973,102 @@ UPB_INLINE bool validate_TimestampRules_has_gt_now(const validate_TimestampRules
UPB_INLINE bool validate_TimestampRules_gt_now(const validate_TimestampRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool); }
UPB_INLINE bool validate_TimestampRules_has_within(const validate_TimestampRules *msg) { return _upb_hasbit(msg, 9); }
UPB_INLINE const struct google_protobuf_Duration* validate_TimestampRules_within(const validate_TimestampRules *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 48), const struct google_protobuf_Duration*); }
-
-UPB_INLINE void validate_TimestampRules_set_required(validate_TimestampRules *msg, bool value) {
- _upb_sethas(msg, 1);
+
+UPB_INLINE void validate_TimestampRules_set_required(validate_TimestampRules *msg, bool value) {
+ _upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
-}
-UPB_INLINE void validate_TimestampRules_set_const(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
- _upb_sethas(msg, 4);
+}
+UPB_INLINE void validate_TimestampRules_set_const(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
+ _upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(8, 8), struct google_protobuf_Timestamp*) = value;
-}
-UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_const(validate_TimestampRules *msg, upb_arena *arena) {
- struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_const(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_const(validate_TimestampRules *msg, upb_arena *arena) {
+ struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_const(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Timestamp*)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
- if (!sub) return NULL;
- validate_TimestampRules_set_const(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_TimestampRules_set_lt(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
- _upb_sethas(msg, 5);
+ if (!sub) return NULL;
+ validate_TimestampRules_set_const(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_TimestampRules_set_lt(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
+ _upb_sethas(msg, 5);
*UPB_PTR_AT(msg, UPB_SIZE(12, 16), struct google_protobuf_Timestamp*) = value;
-}
-UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_lt(validate_TimestampRules *msg, upb_arena *arena) {
- struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_lt(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_lt(validate_TimestampRules *msg, upb_arena *arena) {
+ struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_lt(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Timestamp*)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
- if (!sub) return NULL;
- validate_TimestampRules_set_lt(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_TimestampRules_set_lte(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
- _upb_sethas(msg, 6);
+ if (!sub) return NULL;
+ validate_TimestampRules_set_lt(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_TimestampRules_set_lte(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
+ _upb_sethas(msg, 6);
*UPB_PTR_AT(msg, UPB_SIZE(16, 24), struct google_protobuf_Timestamp*) = value;
-}
-UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_lte(validate_TimestampRules *msg, upb_arena *arena) {
- struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_lte(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_lte(validate_TimestampRules *msg, upb_arena *arena) {
+ struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_lte(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Timestamp*)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
- if (!sub) return NULL;
- validate_TimestampRules_set_lte(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_TimestampRules_set_gt(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
- _upb_sethas(msg, 7);
+ if (!sub) return NULL;
+ validate_TimestampRules_set_lte(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_TimestampRules_set_gt(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
+ _upb_sethas(msg, 7);
*UPB_PTR_AT(msg, UPB_SIZE(20, 32), struct google_protobuf_Timestamp*) = value;
-}
-UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_gt(validate_TimestampRules *msg, upb_arena *arena) {
- struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_gt(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_gt(validate_TimestampRules *msg, upb_arena *arena) {
+ struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_gt(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Timestamp*)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
- if (!sub) return NULL;
- validate_TimestampRules_set_gt(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_TimestampRules_set_gte(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
- _upb_sethas(msg, 8);
+ if (!sub) return NULL;
+ validate_TimestampRules_set_gt(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_TimestampRules_set_gte(validate_TimestampRules *msg, struct google_protobuf_Timestamp* value) {
+ _upb_sethas(msg, 8);
*UPB_PTR_AT(msg, UPB_SIZE(24, 40), struct google_protobuf_Timestamp*) = value;
-}
-UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_gte(validate_TimestampRules *msg, upb_arena *arena) {
- struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_gte(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Timestamp* validate_TimestampRules_mutable_gte(validate_TimestampRules *msg, upb_arena *arena) {
+ struct google_protobuf_Timestamp* sub = (struct google_protobuf_Timestamp*)validate_TimestampRules_gte(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Timestamp*)_upb_msg_new(&google_protobuf_Timestamp_msginit, arena);
- if (!sub) return NULL;
- validate_TimestampRules_set_gte(msg, sub);
- }
- return sub;
-}
-UPB_INLINE void validate_TimestampRules_set_lt_now(validate_TimestampRules *msg, bool value) {
- _upb_sethas(msg, 2);
+ if (!sub) return NULL;
+ validate_TimestampRules_set_gte(msg, sub);
+ }
+ return sub;
+}
+UPB_INLINE void validate_TimestampRules_set_lt_now(validate_TimestampRules *msg, bool value) {
+ _upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(3, 3), bool) = value;
-}
-UPB_INLINE void validate_TimestampRules_set_gt_now(validate_TimestampRules *msg, bool value) {
- _upb_sethas(msg, 3);
+}
+UPB_INLINE void validate_TimestampRules_set_gt_now(validate_TimestampRules *msg, bool value) {
+ _upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool) = value;
-}
-UPB_INLINE void validate_TimestampRules_set_within(validate_TimestampRules *msg, struct google_protobuf_Duration* value) {
- _upb_sethas(msg, 9);
+}
+UPB_INLINE void validate_TimestampRules_set_within(validate_TimestampRules *msg, struct google_protobuf_Duration* value) {
+ _upb_sethas(msg, 9);
*UPB_PTR_AT(msg, UPB_SIZE(28, 48), struct google_protobuf_Duration*) = value;
-}
-UPB_INLINE struct google_protobuf_Duration* validate_TimestampRules_mutable_within(validate_TimestampRules *msg, upb_arena *arena) {
- struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_TimestampRules_within(msg);
- if (sub == NULL) {
+}
+UPB_INLINE struct google_protobuf_Duration* validate_TimestampRules_mutable_within(validate_TimestampRules *msg, upb_arena *arena) {
+ struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)validate_TimestampRules_within(msg);
+ if (sub == NULL) {
sub = (struct google_protobuf_Duration*)_upb_msg_new(&google_protobuf_Duration_msginit, arena);
- if (!sub) return NULL;
- validate_TimestampRules_set_within(msg, sub);
- }
- return sub;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* VALIDATE_VALIDATE_PROTO_UPB_H_ */
+ if (!sub) return NULL;
+ validate_TimestampRules_set_within(msg, sub);
+ }
+ return sub;
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* VALIDATE_VALIDATE_PROTO_UPB_H_ */
diff --git a/contrib/libs/grpc/src/core/lib/avl/avl.cc b/contrib/libs/grpc/src/core/lib/avl/avl.cc
index e04fe35b19..e10328b83e 100644
--- a/contrib/libs/grpc/src/core/lib/avl/avl.cc
+++ b/contrib/libs/grpc/src/core/lib/avl/avl.cc
@@ -294,7 +294,7 @@ grpc_avl grpc_avl_remove(grpc_avl avl, void* key, void* user_data) {
return avl;
}
-grpc_avl grpc_avl_ref(grpc_avl avl, void* /*user_data*/) {
+grpc_avl grpc_avl_ref(grpc_avl avl, void* /*user_data*/) {
ref_node(avl.root);
return avl;
}
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_args.cc b/contrib/libs/grpc/src/core/lib/channel/channel_args.cc
index cb3d61fc4d..dec1656c11 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_args.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_args.cc
@@ -27,8 +27,8 @@
#include "y_absl/strings/str_join.h"
#include <grpc/grpc.h>
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/impl/codegen/log.h>
+#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/impl/codegen/log.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@@ -124,8 +124,8 @@ grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src) {
grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a,
const grpc_channel_args* b) {
- if (a == nullptr) return grpc_channel_args_copy(b);
- if (b == nullptr) return grpc_channel_args_copy(a);
+ if (a == nullptr) return grpc_channel_args_copy(b);
+ if (b == nullptr) return grpc_channel_args_copy(a);
const size_t max_out = (a->num_args + b->num_args);
grpc_arg* uniques =
static_cast<grpc_arg*>(gpr_malloc(sizeof(*uniques) * max_out));
@@ -221,8 +221,8 @@ void grpc_channel_args_destroy(grpc_channel_args* a) {
int grpc_channel_args_compare(const grpc_channel_args* a,
const grpc_channel_args* b) {
- if (a == nullptr && b == nullptr) return 0;
- if (a == nullptr || b == nullptr) return a == nullptr ? -1 : 1;
+ if (a == nullptr && b == nullptr) return 0;
+ if (a == nullptr || b == nullptr) return a == nullptr ? -1 : 1;
int c = GPR_ICMP(a->num_args, b->num_args);
if (c != 0) return c;
for (size_t i = 0; i < a->num_args; i++) {
@@ -264,13 +264,13 @@ int grpc_channel_arg_get_integer(const grpc_arg* arg,
return arg->value.integer;
}
-int grpc_channel_args_find_integer(const grpc_channel_args* args,
- const char* name,
- const grpc_integer_options options) {
- const grpc_arg* arg = grpc_channel_args_find(args, name);
- return grpc_channel_arg_get_integer(arg, options);
-}
-
+int grpc_channel_args_find_integer(const grpc_channel_args* args,
+ const char* name,
+ const grpc_integer_options options) {
+ const grpc_arg* arg = grpc_channel_args_find(args, name);
+ return grpc_channel_arg_get_integer(arg, options);
+}
+
char* grpc_channel_arg_get_string(const grpc_arg* arg) {
if (arg == nullptr) return nullptr;
if (arg->type != GRPC_ARG_STRING) {
@@ -280,12 +280,12 @@ char* grpc_channel_arg_get_string(const grpc_arg* arg) {
return arg->value.string;
}
-char* grpc_channel_args_find_string(const grpc_channel_args* args,
- const char* name) {
- const grpc_arg* arg = grpc_channel_args_find(args, name);
- return grpc_channel_arg_get_string(arg);
-}
-
+char* grpc_channel_args_find_string(const grpc_channel_args* args,
+ const char* name) {
+ const grpc_arg* arg = grpc_channel_args_find(args, name);
+ return grpc_channel_arg_get_string(arg);
+}
+
bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value) {
if (arg == nullptr) return default_value;
if (arg->type != GRPC_ARG_INTEGER) {
@@ -304,12 +304,12 @@ bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value) {
}
}
-bool grpc_channel_args_find_bool(const grpc_channel_args* args,
- const char* name, bool default_value) {
- const grpc_arg* arg = grpc_channel_args_find(args, name);
- return grpc_channel_arg_get_bool(arg, default_value);
-}
-
+bool grpc_channel_args_find_bool(const grpc_channel_args* args,
+ const char* name, bool default_value) {
+ const grpc_arg* arg = grpc_channel_args_find(args, name);
+ return grpc_channel_arg_get_bool(arg, default_value);
+}
+
bool grpc_channel_args_want_minimal_stack(const grpc_channel_args* args) {
return grpc_channel_arg_get_bool(
grpc_channel_args_find(args, GRPC_ARG_MINIMAL_STACK), false);
@@ -364,17 +364,17 @@ TString grpc_channel_args_string(const grpc_channel_args* args) {
}
return y_absl::StrJoin(arg_strings, ", ");
}
-
-namespace {
-grpc_channel_args_client_channel_creation_mutator g_mutator = nullptr;
-} // namespace
-
-void grpc_channel_args_set_client_channel_creation_mutator(
- grpc_channel_args_client_channel_creation_mutator cb) {
- GPR_DEBUG_ASSERT(g_mutator == nullptr);
- g_mutator = cb;
-}
-grpc_channel_args_client_channel_creation_mutator
-grpc_channel_args_get_client_channel_creation_mutator() {
- return g_mutator;
-}
+
+namespace {
+grpc_channel_args_client_channel_creation_mutator g_mutator = nullptr;
+} // namespace
+
+void grpc_channel_args_set_client_channel_creation_mutator(
+ grpc_channel_args_client_channel_creation_mutator cb) {
+ GPR_DEBUG_ASSERT(g_mutator == nullptr);
+ g_mutator = cb;
+}
+grpc_channel_args_client_channel_creation_mutator
+grpc_channel_args_get_client_channel_creation_mutator() {
+ return g_mutator;
+}
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_args.h b/contrib/libs/grpc/src/core/lib/channel/channel_args.h
index 6b973aa94d..f52e1326d4 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_args.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_args.h
@@ -25,8 +25,8 @@
#include <grpc/grpc.h>
-#include "src/core/lib/surface/channel_stack_type.h"
-
+#include "src/core/lib/surface/channel_stack_type.h"
+
// Channel args are intentionally immutable, to avoid the need for locking.
/** Copy the arguments in \a src into a new instance */
@@ -58,9 +58,9 @@ grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a,
/** Destroy arguments created by \a grpc_channel_args_copy */
void grpc_channel_args_destroy(grpc_channel_args* a);
-inline void grpc_channel_args_destroy(const grpc_channel_args* a) {
- grpc_channel_args_destroy(const_cast<grpc_channel_args*>(a));
-}
+inline void grpc_channel_args_destroy(const grpc_channel_args* a) {
+ grpc_channel_args_destroy(const_cast<grpc_channel_args*>(a));
+}
int grpc_channel_args_compare(const grpc_channel_args* a,
const grpc_channel_args* b);
@@ -77,39 +77,39 @@ typedef struct grpc_integer_options {
int max_value;
} grpc_integer_options;
-/** Returns the value of \a arg, subject to the constraints in \a options. */
+/** Returns the value of \a arg, subject to the constraints in \a options. */
int grpc_channel_arg_get_integer(const grpc_arg* arg,
const grpc_integer_options options);
-/** Similar to the above, but needs to find the arg from \a args by the name
- * first. */
-int grpc_channel_args_find_integer(const grpc_channel_args* args,
- const char* name,
- const grpc_integer_options options);
+/** Similar to the above, but needs to find the arg from \a args by the name
+ * first. */
+int grpc_channel_args_find_integer(const grpc_channel_args* args,
+ const char* name,
+ const grpc_integer_options options);
/** Returns the value of \a arg if \a arg is of type GRPC_ARG_STRING.
Otherwise, emits a warning log, and returns nullptr.
If arg is nullptr, returns nullptr, and does not emit a warning. */
char* grpc_channel_arg_get_string(const grpc_arg* arg);
-/** Similar to the above, but needs to find the arg from \a args by the name
- * first. */
-char* grpc_channel_args_find_string(const grpc_channel_args* args,
- const char* name);
-/** If \a arg is of type GRPC_ARG_INTEGER, returns true if it's non-zero.
- * Returns \a default_value if \a arg is of other types. */
+/** Similar to the above, but needs to find the arg from \a args by the name
+ * first. */
+char* grpc_channel_args_find_string(const grpc_channel_args* args,
+ const char* name);
+/** If \a arg is of type GRPC_ARG_INTEGER, returns true if it's non-zero.
+ * Returns \a default_value if \a arg is of other types. */
bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value);
-/** Similar to the above, but needs to find the arg from \a args by the name
- * first. */
-bool grpc_channel_args_find_bool(const grpc_channel_args* args,
- const char* name, bool default_value);
-
-template <typename T>
-T* grpc_channel_args_find_pointer(const grpc_channel_args* args,
- const char* name) {
- const grpc_arg* arg = grpc_channel_args_find(args, name);
- if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
- return static_cast<T*>(arg->value.pointer.p);
-}
-
+/** Similar to the above, but needs to find the arg from \a args by the name
+ * first. */
+bool grpc_channel_args_find_bool(const grpc_channel_args* args,
+ const char* name, bool default_value);
+
+template <typename T>
+T* grpc_channel_args_find_pointer(const grpc_channel_args* args,
+ const char* name) {
+ const grpc_arg* arg = grpc_channel_args_find(args, name);
+ if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
+ return static_cast<T*>(arg->value.pointer.p);
+}
+
// Helpers for creating channel args.
grpc_arg grpc_channel_arg_string_create(char* name, char* value);
grpc_arg grpc_channel_arg_integer_create(char* name, int value);
@@ -119,16 +119,16 @@ grpc_arg grpc_channel_arg_pointer_create(char* name, void* value,
// Returns a string representing channel args in human-readable form.
TString grpc_channel_args_string(const grpc_channel_args* args);
-// Takes ownership of the old_args
-typedef grpc_channel_args* (*grpc_channel_args_client_channel_creation_mutator)(
- const char* target, grpc_channel_args* old_args,
- grpc_channel_stack_type type);
-
-// Should be called only once globaly before grpc is init'ed.
-void grpc_channel_args_set_client_channel_creation_mutator(
- grpc_channel_args_client_channel_creation_mutator cb);
-// This will be called at the creation of each channel.
-grpc_channel_args_client_channel_creation_mutator
-grpc_channel_args_get_client_channel_creation_mutator();
-
+// Takes ownership of the old_args
+typedef grpc_channel_args* (*grpc_channel_args_client_channel_creation_mutator)(
+ const char* target, grpc_channel_args* old_args,
+ grpc_channel_stack_type type);
+
+// Should be called only once globaly before grpc is init'ed.
+void grpc_channel_args_set_client_channel_creation_mutator(
+ grpc_channel_args_client_channel_creation_mutator cb);
+// This will be called at the creation of each channel.
+grpc_channel_args_client_channel_creation_mutator
+grpc_channel_args_get_client_channel_creation_mutator();
+
#endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_ARGS_H */
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc b/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc
index e9b348972f..7efed640b2 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc
@@ -203,7 +203,7 @@ void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
}
void grpc_call_stack_ignore_set_pollset_or_pollset_set(
- grpc_call_element* /*elem*/, grpc_polling_entity* /*pollent*/) {}
+ grpc_call_element* /*elem*/, grpc_polling_entity* /*pollent*/) {}
void grpc_call_stack_destroy(grpc_call_stack* stack,
const grpc_call_final_info* final_info,
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack.h b/contrib/libs/grpc/src/core/lib/channel/channel_stack.h
index e297df9488..a5ed2f7428 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_stack.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack.h
@@ -53,8 +53,8 @@
#include <grpc/support/time.h>
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/time_precise.h"
-#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gpr/time_precise.h"
+#include "src/core/lib/gprpp/arena.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/transport/transport.h"
@@ -77,11 +77,11 @@ struct grpc_call_element_args {
grpc_call_stack* call_stack;
const void* server_transport_data;
grpc_call_context_element* context;
- const grpc_slice& path;
- gpr_cycle_counter start_time;
+ const grpc_slice& path;
+ gpr_cycle_counter start_time;
grpc_millis deadline;
- grpc_core::Arena* arena;
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::Arena* arena;
+ grpc_core::CallCombiner* call_combiner;
};
struct grpc_call_stats {
grpc_transport_stream_stats transport_stream_stats;
@@ -242,25 +242,25 @@ void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
grpc_stream_unref(&(channel_stack)->refcount, reason)
#else
#define GRPC_CALL_STACK_REF(call_stack, reason) \
- do { \
- grpc_stream_ref(&(call_stack)->refcount); \
- (void)(reason); \
- } while (0);
+ do { \
+ grpc_stream_ref(&(call_stack)->refcount); \
+ (void)(reason); \
+ } while (0);
#define GRPC_CALL_STACK_UNREF(call_stack, reason) \
- do { \
- grpc_stream_unref(&(call_stack)->refcount); \
- (void)(reason); \
- } while (0);
+ do { \
+ grpc_stream_unref(&(call_stack)->refcount); \
+ (void)(reason); \
+ } while (0);
#define GRPC_CHANNEL_STACK_REF(channel_stack, reason) \
- do { \
- grpc_stream_ref(&(channel_stack)->refcount); \
- (void)(reason); \
- } while (0);
+ do { \
+ grpc_stream_ref(&(channel_stack)->refcount); \
+ (void)(reason); \
+ } while (0);
#define GRPC_CHANNEL_STACK_UNREF(channel_stack, reason) \
- do { \
- grpc_stream_unref(&(channel_stack)->refcount); \
- (void)(reason); \
- } while (0);
+ do { \
+ grpc_stream_unref(&(channel_stack)->refcount); \
+ (void)(reason); \
+ } while (0);
#endif
/* Destroy a call stack */
@@ -294,11 +294,11 @@ void grpc_call_log_op(const char* file, int line, gpr_log_severity severity,
extern grpc_core::TraceFlag grpc_trace_channel;
-#define GRPC_CALL_LOG_OP(sev, elem, op) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_channel)) { \
- grpc_call_log_op(sev, elem, op); \
- } \
- } while (0)
+#define GRPC_CALL_LOG_OP(sev, elem, op) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_channel)) { \
+ grpc_call_log_op(sev, elem, op); \
+ } \
+ } while (0)
#endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_STACK_H */
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc b/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc
index dbc33af2d4..0ee6f40b8b 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc
@@ -41,7 +41,7 @@
namespace grpc_core {
namespace channelz {
-ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data,
+ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity)
: severity_(severity),
data_(data),
@@ -51,7 +51,7 @@ ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data,
referenced_entity_(std::move(referenced_entity)),
memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {}
-ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data)
+ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data)
: severity_(severity),
data_(data),
timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
@@ -81,7 +81,7 @@ ChannelTrace::~ChannelTrace() {
while (it != nullptr) {
TraceEvent* to_free = it;
it = it->next();
- delete to_free;
+ delete to_free;
}
gpr_mu_destroy(&tracer_mu_);
}
@@ -103,20 +103,20 @@ void ChannelTrace::AddTraceEventHelper(TraceEvent* new_trace_event) {
TraceEvent* to_free = head_trace_;
event_list_memory_usage_ -= to_free->memory_usage();
head_trace_ = head_trace_->next();
- delete to_free;
+ delete to_free;
}
}
-void ChannelTrace::AddTraceEvent(Severity severity, const grpc_slice& data) {
+void ChannelTrace::AddTraceEvent(Severity severity, const grpc_slice& data) {
if (max_event_memory_ == 0) {
grpc_slice_unref_internal(data);
return; // tracing is disabled if max_event_memory_ == 0
}
- AddTraceEventHelper(new TraceEvent(severity, data));
+ AddTraceEventHelper(new TraceEvent(severity, data));
}
void ChannelTrace::AddTraceEventWithReference(
- Severity severity, const grpc_slice& data,
+ Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity) {
if (max_event_memory_ == 0) {
grpc_slice_unref_internal(data);
@@ -124,7 +124,7 @@ void ChannelTrace::AddTraceEventWithReference(
}
// create and fill up the new event
AddTraceEventHelper(
- new TraceEvent(severity, data, std::move(referenced_entity)));
+ new TraceEvent(severity, data, std::move(referenced_entity)));
}
namespace {
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_trace.h b/contrib/libs/grpc/src/core/lib/channel/channel_trace.h
index c26e3016da..340f29eb26 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_trace.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_trace.h
@@ -62,7 +62,7 @@ class ChannelTrace {
// TODO(ncteisen): as this call is used more and more throughout the gRPC
// stack, determine if it makes more sense to accept a char* instead of a
// slice.
- void AddTraceEvent(Severity severity, const grpc_slice& data);
+ void AddTraceEvent(Severity severity, const grpc_slice& data);
// Adds a new trace event to the tracing object. This trace event refers to a
// an event that concerns a different channelz entity. For example, if this
@@ -72,7 +72,7 @@ class ChannelTrace {
// NOTE: see the note in the method above.
//
// TODO(ncteisen): see the todo in the method above.
- void AddTraceEventWithReference(Severity severity, const grpc_slice& data,
+ void AddTraceEventWithReference(Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity);
// Creates and returns the raw Json object, so a parent channelz
@@ -87,12 +87,12 @@ class ChannelTrace {
class TraceEvent {
public:
// Constructor for a TraceEvent that references a channel.
- TraceEvent(Severity severity, const grpc_slice& data,
+ TraceEvent(Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity_);
// Constructor for a TraceEvent that does not reverence a different
// channel.
- TraceEvent(Severity severity, const grpc_slice& data);
+ TraceEvent(Severity severity, const grpc_slice& data);
~TraceEvent();
diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz.cc b/contrib/libs/grpc/src/core/lib/channel/channelz.cc
index 16f505c053..810a07039f 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channelz.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channelz.cc
@@ -32,8 +32,8 @@
#include "src/core/lib/channel/status_util.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/exec_ctx.h"
@@ -41,7 +41,7 @@
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/server.h"
-#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/error_utils.h"
#include "src/core/lib/uri/uri_parser.h"
@@ -50,12 +50,12 @@
namespace grpc_core {
namespace channelz {
-//
-// BaseNode
-//
-
+//
+// BaseNode
+//
+
BaseNode::BaseNode(EntityType type, TString name)
- : type_(type), uuid_(-1), name_(std::move(name)) {
+ : type_(type), uuid_(-1), name_(std::move(name)) {
// The registry will set uuid_ under its lock.
ChannelzRegistry::Register(this);
}
@@ -67,51 +67,51 @@ TString BaseNode::RenderJsonString() {
return json.Dump();
}
-//
-// CallCountingHelper
-//
-
+//
+// CallCountingHelper
+//
+
CallCountingHelper::CallCountingHelper() {
num_cores_ = GPR_MAX(1, gpr_cpu_num_cores());
- per_cpu_counter_data_storage_.reserve(num_cores_);
- for (size_t i = 0; i < num_cores_; ++i) {
- per_cpu_counter_data_storage_.emplace_back();
- }
+ per_cpu_counter_data_storage_.reserve(num_cores_);
+ for (size_t i = 0; i < num_cores_; ++i) {
+ per_cpu_counter_data_storage_.emplace_back();
+ }
}
void CallCountingHelper::RecordCallStarted() {
- AtomicCounterData& data =
- per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()];
- data.calls_started.FetchAdd(1, MemoryOrder::RELAXED);
- data.last_call_started_cycle.Store(gpr_get_cycle_counter(),
- MemoryOrder::RELAXED);
+ AtomicCounterData& data =
+ per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()];
+ data.calls_started.FetchAdd(1, MemoryOrder::RELAXED);
+ data.last_call_started_cycle.Store(gpr_get_cycle_counter(),
+ MemoryOrder::RELAXED);
}
void CallCountingHelper::RecordCallFailed() {
- per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
- .calls_failed.FetchAdd(1, MemoryOrder::RELAXED);
+ per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
+ .calls_failed.FetchAdd(1, MemoryOrder::RELAXED);
}
void CallCountingHelper::RecordCallSucceeded() {
- per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
- .calls_succeeded.FetchAdd(1, MemoryOrder::RELAXED);
+ per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
+ .calls_succeeded.FetchAdd(1, MemoryOrder::RELAXED);
}
void CallCountingHelper::CollectData(CounterData* out) {
for (size_t core = 0; core < num_cores_; ++core) {
- AtomicCounterData& data = per_cpu_counter_data_storage_[core];
-
- out->calls_started += data.calls_started.Load(MemoryOrder::RELAXED);
- out->calls_succeeded +=
- per_cpu_counter_data_storage_[core].calls_succeeded.Load(
- MemoryOrder::RELAXED);
- out->calls_failed += per_cpu_counter_data_storage_[core].calls_failed.Load(
- MemoryOrder::RELAXED);
- const gpr_cycle_counter last_call =
- per_cpu_counter_data_storage_[core].last_call_started_cycle.Load(
- MemoryOrder::RELAXED);
- if (last_call > out->last_call_started_cycle) {
- out->last_call_started_cycle = last_call;
+ AtomicCounterData& data = per_cpu_counter_data_storage_[core];
+
+ out->calls_started += data.calls_started.Load(MemoryOrder::RELAXED);
+ out->calls_succeeded +=
+ per_cpu_counter_data_storage_[core].calls_succeeded.Load(
+ MemoryOrder::RELAXED);
+ out->calls_failed += per_cpu_counter_data_storage_[core].calls_failed.Load(
+ MemoryOrder::RELAXED);
+ const gpr_cycle_counter last_call =
+ per_cpu_counter_data_storage_[core].last_call_started_cycle.Load(
+ MemoryOrder::RELAXED);
+ if (last_call > out->last_call_started_cycle) {
+ out->last_call_started_cycle = last_call;
}
}
}
@@ -134,49 +134,49 @@ void CallCountingHelper::PopulateCallCounts(Json::Object* object) {
}
}
-//
-// ChannelNode
-//
+//
+// ChannelNode
+//
ChannelNode::ChannelNode(TString target, size_t channel_tracer_max_nodes,
bool is_internal_channel)
: BaseNode(is_internal_channel ? EntityType::kInternalChannel
: EntityType::kTopLevelChannel,
- target),
- target_(std::move(target)),
+ target),
+ target_(std::move(target)),
trace_(channel_tracer_max_nodes) {}
-const char* ChannelNode::GetChannelConnectivityStateChangeString(
- grpc_connectivity_state state) {
- switch (state) {
- case GRPC_CHANNEL_IDLE:
- return "Channel state change to IDLE";
- case GRPC_CHANNEL_CONNECTING:
- return "Channel state change to CONNECTING";
- case GRPC_CHANNEL_READY:
- return "Channel state change to READY";
- case GRPC_CHANNEL_TRANSIENT_FAILURE:
- return "Channel state change to TRANSIENT_FAILURE";
- case GRPC_CHANNEL_SHUTDOWN:
- return "Channel state change to SHUTDOWN";
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
-
+const char* ChannelNode::GetChannelConnectivityStateChangeString(
+ grpc_connectivity_state state) {
+ switch (state) {
+ case GRPC_CHANNEL_IDLE:
+ return "Channel state change to IDLE";
+ case GRPC_CHANNEL_CONNECTING:
+ return "Channel state change to CONNECTING";
+ case GRPC_CHANNEL_READY:
+ return "Channel state change to READY";
+ case GRPC_CHANNEL_TRANSIENT_FAILURE:
+ return "Channel state change to TRANSIENT_FAILURE";
+ case GRPC_CHANNEL_SHUTDOWN:
+ return "Channel state change to SHUTDOWN";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
Json ChannelNode::RenderJson() {
Json::Object data = {
{"target", target_},
};
// Connectivity state.
- // If low-order bit is on, then the field is set.
- int state_field = connectivity_state_.Load(MemoryOrder::RELAXED);
- if ((state_field & 1) != 0) {
- grpc_connectivity_state state =
- static_cast<grpc_connectivity_state>(state_field >> 1);
+ // If low-order bit is on, then the field is set.
+ int state_field = connectivity_state_.Load(MemoryOrder::RELAXED);
+ if ((state_field & 1) != 0) {
+ grpc_connectivity_state state =
+ static_cast<grpc_connectivity_state>(state_field >> 1);
data["state"] = Json::Object{
{"state", ConnectivityStateName(state)},
};
- }
+ }
// Fill in the channel trace if applicable.
Json trace_json = trace_.RenderJson();
if (trace_json.type() != Json::Type::JSON_NULL) {
@@ -199,87 +199,87 @@ Json ChannelNode::RenderJson() {
}
void ChannelNode::PopulateChildRefs(Json::Object* json) {
- MutexLock lock(&child_mu_);
- if (!child_subchannels_.empty()) {
+ MutexLock lock(&child_mu_);
+ if (!child_subchannels_.empty()) {
Json::Array array;
for (intptr_t subchannel_uuid : child_subchannels_) {
array.emplace_back(Json::Object{
{"subchannelId", ToString(subchannel_uuid)},
});
- }
+ }
(*json)["subchannelRef"] = std::move(array);
- }
- if (!child_channels_.empty()) {
+ }
+ if (!child_channels_.empty()) {
Json::Array array;
for (intptr_t channel_uuid : child_channels_) {
array.emplace_back(Json::Object{
{"channelId", ToString(channel_uuid)},
});
- }
+ }
(*json)["channelRef"] = std::move(array);
- }
+ }
}
-void ChannelNode::SetConnectivityState(grpc_connectivity_state state) {
- // Store with low-order bit set to indicate that the field is set.
- int state_field = (state << 1) + 1;
- connectivity_state_.Store(state_field, MemoryOrder::RELAXED);
-}
+void ChannelNode::SetConnectivityState(grpc_connectivity_state state) {
+ // Store with low-order bit set to indicate that the field is set.
+ int state_field = (state << 1) + 1;
+ connectivity_state_.Store(state_field, MemoryOrder::RELAXED);
+}
-void ChannelNode::AddChildChannel(intptr_t child_uuid) {
- MutexLock lock(&child_mu_);
+void ChannelNode::AddChildChannel(intptr_t child_uuid) {
+ MutexLock lock(&child_mu_);
child_channels_.insert(child_uuid);
-}
-
-void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
- MutexLock lock(&child_mu_);
- child_channels_.erase(child_uuid);
-}
-
-void ChannelNode::AddChildSubchannel(intptr_t child_uuid) {
- MutexLock lock(&child_mu_);
+}
+
+void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
+ MutexLock lock(&child_mu_);
+ child_channels_.erase(child_uuid);
+}
+
+void ChannelNode::AddChildSubchannel(intptr_t child_uuid) {
+ MutexLock lock(&child_mu_);
child_subchannels_.insert(child_uuid);
-}
-
-void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) {
- MutexLock lock(&child_mu_);
- child_subchannels_.erase(child_uuid);
-}
-
-//
-// ServerNode
-//
-
+}
+
+void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) {
+ MutexLock lock(&child_mu_);
+ child_subchannels_.erase(child_uuid);
+}
+
+//
+// ServerNode
+//
+
ServerNode::ServerNode(size_t channel_tracer_max_nodes)
- : BaseNode(EntityType::kServer, ""), trace_(channel_tracer_max_nodes) {}
-
+ : BaseNode(EntityType::kServer, ""), trace_(channel_tracer_max_nodes) {}
+
ServerNode::~ServerNode() {}
-void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
- MutexLock lock(&child_mu_);
- child_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
-}
-
-void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
- MutexLock lock(&child_mu_);
- child_sockets_.erase(child_uuid);
-}
-
-void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) {
- MutexLock lock(&child_mu_);
- child_listen_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
-}
-
-void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {
- MutexLock lock(&child_mu_);
- child_listen_sockets_.erase(child_uuid);
-}
-
+void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
+ MutexLock lock(&child_mu_);
+ child_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
+}
+
+void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
+ MutexLock lock(&child_mu_);
+ child_sockets_.erase(child_uuid);
+}
+
+void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) {
+ MutexLock lock(&child_mu_);
+ child_listen_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
+}
+
+void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {
+ MutexLock lock(&child_mu_);
+ child_listen_sockets_.erase(child_uuid);
+}
+
TString ServerNode::RenderServerSockets(intptr_t start_socket_id,
intptr_t max_results) {
GPR_ASSERT(start_socket_id >= 0);
GPR_ASSERT(max_results >= 0);
- // If user does not set max_results, we choose 500.
+ // If user does not set max_results, we choose 500.
size_t pagination_limit = max_results == 0 ? 500 : max_results;
Json::Object object;
{
@@ -336,14 +336,14 @@ Json ServerNode::RenderJson() {
return object;
}
-//
-// SocketNode
-//
-
-namespace {
-
+//
+// SocketNode
+//
+
+namespace {
+
void PopulateSocketAddressJson(Json::Object* json, const char* name,
- const char* addr_str) {
+ const char* addr_str) {
if (addr_str == nullptr) return;
Json::Object data;
grpc_uri* uri = grpc_uri_parse(addr_str, true);
@@ -353,7 +353,7 @@ void PopulateSocketAddressJson(Json::Object* json, const char* name,
if (*host_port == '/') ++host_port;
TString host;
TString port;
- GPR_ASSERT(SplitHostPort(host_port, &host, &port));
+ GPR_ASSERT(SplitHostPort(host_port, &host, &port));
int port_num = -1;
if (!port.empty()) {
port_num = atoi(port.data());
@@ -377,88 +377,88 @@ void PopulateSocketAddressJson(Json::Object* json, const char* name,
(*json)[name] = std::move(data);
}
-} // namespace
-
+} // namespace
+
SocketNode::SocketNode(TString local, TString remote, TString name)
- : BaseNode(EntityType::kSocket, std::move(name)),
+ : BaseNode(EntityType::kSocket, std::move(name)),
local_(std::move(local)),
remote_(std::move(remote)) {}
void SocketNode::RecordStreamStartedFromLocal() {
- streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
- last_local_stream_created_cycle_.Store(gpr_get_cycle_counter(),
- MemoryOrder::RELAXED);
+ streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
+ last_local_stream_created_cycle_.Store(gpr_get_cycle_counter(),
+ MemoryOrder::RELAXED);
}
void SocketNode::RecordStreamStartedFromRemote() {
- streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
- last_remote_stream_created_cycle_.Store(gpr_get_cycle_counter(),
- MemoryOrder::RELAXED);
+ streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
+ last_remote_stream_created_cycle_.Store(gpr_get_cycle_counter(),
+ MemoryOrder::RELAXED);
}
void SocketNode::RecordMessagesSent(uint32_t num_sent) {
- messages_sent_.FetchAdd(num_sent, MemoryOrder::RELAXED);
- last_message_sent_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED);
+ messages_sent_.FetchAdd(num_sent, MemoryOrder::RELAXED);
+ last_message_sent_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED);
}
void SocketNode::RecordMessageReceived() {
- messages_received_.FetchAdd(1, MemoryOrder::RELAXED);
- last_message_received_cycle_.Store(gpr_get_cycle_counter(),
- MemoryOrder::RELAXED);
+ messages_received_.FetchAdd(1, MemoryOrder::RELAXED);
+ last_message_received_cycle_.Store(gpr_get_cycle_counter(),
+ MemoryOrder::RELAXED);
}
Json SocketNode::RenderJson() {
// Create and fill the data child.
Json::Object data;
gpr_timespec ts;
- int64_t streams_started = streams_started_.Load(MemoryOrder::RELAXED);
- if (streams_started != 0) {
+ int64_t streams_started = streams_started_.Load(MemoryOrder::RELAXED);
+ if (streams_started != 0) {
data["streamsStarted"] = ToString(streams_started);
- gpr_cycle_counter last_local_stream_created_cycle =
- last_local_stream_created_cycle_.Load(MemoryOrder::RELAXED);
- if (last_local_stream_created_cycle != 0) {
- ts = gpr_convert_clock_type(
- gpr_cycle_counter_to_time(last_local_stream_created_cycle),
- GPR_CLOCK_REALTIME);
+ gpr_cycle_counter last_local_stream_created_cycle =
+ last_local_stream_created_cycle_.Load(MemoryOrder::RELAXED);
+ if (last_local_stream_created_cycle != 0) {
+ ts = gpr_convert_clock_type(
+ gpr_cycle_counter_to_time(last_local_stream_created_cycle),
+ GPR_CLOCK_REALTIME);
data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
}
- gpr_cycle_counter last_remote_stream_created_cycle =
- last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED);
- if (last_remote_stream_created_cycle != 0) {
- ts = gpr_convert_clock_type(
- gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
- GPR_CLOCK_REALTIME);
+ gpr_cycle_counter last_remote_stream_created_cycle =
+ last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED);
+ if (last_remote_stream_created_cycle != 0) {
+ ts = gpr_convert_clock_type(
+ gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
+ GPR_CLOCK_REALTIME);
data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
}
}
- int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
- if (streams_succeeded != 0) {
+ int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
+ if (streams_succeeded != 0) {
data["streamsSucceeded"] = ToString(streams_succeeded);
}
- int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED);
+ int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED);
if (streams_failed != 0) {
data["streamsFailed"] = ToString(streams_failed);
}
- int64_t messages_sent = messages_sent_.Load(MemoryOrder::RELAXED);
- if (messages_sent != 0) {
+ int64_t messages_sent = messages_sent_.Load(MemoryOrder::RELAXED);
+ if (messages_sent != 0) {
data["messagesSent"] = ToString(messages_sent);
- ts = gpr_convert_clock_type(
- gpr_cycle_counter_to_time(
- last_message_sent_cycle_.Load(MemoryOrder::RELAXED)),
- GPR_CLOCK_REALTIME);
+ ts = gpr_convert_clock_type(
+ gpr_cycle_counter_to_time(
+ last_message_sent_cycle_.Load(MemoryOrder::RELAXED)),
+ GPR_CLOCK_REALTIME);
data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
}
- int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED);
- if (messages_received != 0) {
+ int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED);
+ if (messages_received != 0) {
data["messagesReceived"] = ToString(messages_received);
- ts = gpr_convert_clock_type(
- gpr_cycle_counter_to_time(
- last_message_received_cycle_.Load(MemoryOrder::RELAXED)),
- GPR_CLOCK_REALTIME);
+ ts = gpr_convert_clock_type(
+ gpr_cycle_counter_to_time(
+ last_message_received_cycle_.Load(MemoryOrder::RELAXED)),
+ GPR_CLOCK_REALTIME);
data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
}
- int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
- if (keepalives_sent != 0) {
+ int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
+ if (keepalives_sent != 0) {
data["keepAlivesSent"] = ToString(keepalives_sent);
}
// Create and fill the parent object.
@@ -475,14 +475,14 @@ Json SocketNode::RenderJson() {
return object;
}
-//
-// ListenSocketNode
-//
+//
+// ListenSocketNode
+//
ListenSocketNode::ListenSocketNode(TString local_addr, TString name)
- : BaseNode(EntityType::kSocket, std::move(name)),
- local_addr_(std::move(local_addr)) {}
-
+ : BaseNode(EntityType::kSocket, std::move(name)),
+ local_addr_(std::move(local_addr)) {}
+
Json ListenSocketNode::RenderJson() {
Json::Object object = {
{"ref",
diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz.h b/contrib/libs/grpc/src/core/lib/channel/channelz.h
index 596770ccdc..9fa6d58144 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channelz.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channelz.h
@@ -25,23 +25,23 @@
#include <set>
#include <util/generic/string.h>
-
+
#include "y_absl/container/inlined_vector.h"
#include "src/core/lib/channel/channel_trace.h"
-#include "src/core/lib/gpr/time_precise.h"
-#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gpr/time_precise.h"
+#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/gprpp/map.h"
+#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/json/json.h"
-// Channel arg key for channelz node.
-#define GRPC_ARG_CHANNELZ_CHANNEL_NODE "grpc.channelz_channel_node"
+// Channel arg key for channelz node.
+#define GRPC_ARG_CHANNELZ_CHANNEL_NODE "grpc.channelz_channel_node"
// Channel arg key for indicating an internal channel.
#define GRPC_ARG_CHANNELZ_IS_INTERNAL_CHANNEL \
@@ -62,7 +62,7 @@ namespace grpc_core {
namespace channelz {
class SocketNode;
-class ListenSocketNode;
+class ListenSocketNode;
namespace testing {
class CallCountingHelperPeer;
@@ -83,10 +83,10 @@ class BaseNode : public RefCounted<BaseNode> {
kSocket,
};
- protected:
+ protected:
BaseNode(EntityType type, TString name);
-
- public:
+
+ public:
virtual ~BaseNode();
// All children must implement this function.
@@ -129,24 +129,24 @@ class CallCountingHelper {
// testing peer friend.
friend class testing::CallCountingHelperPeer;
- // TODO(soheil): add a proper PerCPU helper and use it here.
+ // TODO(soheil): add a proper PerCPU helper and use it here.
struct AtomicCounterData {
- // Define the ctors so that we can use this structure in InlinedVector.
- AtomicCounterData() = default;
- AtomicCounterData(const AtomicCounterData& that)
- : calls_started(that.calls_started.Load(MemoryOrder::RELAXED)),
- calls_succeeded(that.calls_succeeded.Load(MemoryOrder::RELAXED)),
- calls_failed(that.calls_failed.Load(MemoryOrder::RELAXED)),
- last_call_started_cycle(
- that.last_call_started_cycle.Load(MemoryOrder::RELAXED)) {}
-
- Atomic<int64_t> calls_started{0};
- Atomic<int64_t> calls_succeeded{0};
- Atomic<int64_t> calls_failed{0};
- Atomic<gpr_cycle_counter> last_call_started_cycle{0};
- // Make sure the size is exactly one cache line.
- uint8_t padding[GPR_CACHELINE_SIZE - 3 * sizeof(Atomic<intptr_t>) -
- sizeof(Atomic<gpr_cycle_counter>)];
+ // Define the ctors so that we can use this structure in InlinedVector.
+ AtomicCounterData() = default;
+ AtomicCounterData(const AtomicCounterData& that)
+ : calls_started(that.calls_started.Load(MemoryOrder::RELAXED)),
+ calls_succeeded(that.calls_succeeded.Load(MemoryOrder::RELAXED)),
+ calls_failed(that.calls_failed.Load(MemoryOrder::RELAXED)),
+ last_call_started_cycle(
+ that.last_call_started_cycle.Load(MemoryOrder::RELAXED)) {}
+
+ Atomic<int64_t> calls_started{0};
+ Atomic<int64_t> calls_succeeded{0};
+ Atomic<int64_t> calls_failed{0};
+ Atomic<gpr_cycle_counter> last_call_started_cycle{0};
+ // Make sure the size is exactly one cache line.
+ uint8_t padding[GPR_CACHELINE_SIZE - 3 * sizeof(Atomic<intptr_t>) -
+ sizeof(Atomic<gpr_cycle_counter>)];
};
// TODO(soheilhy,veblush): Revist this after abseil integration.
// This has a problem when using abseil inlined_vector because it
@@ -154,18 +154,18 @@ class CallCountingHelper {
// respect this. To avoid UBSAN errors, this should be removed with
// abseil inlined_vector.
// GPR_ALIGN_STRUCT(GPR_CACHELINE_SIZE);
-
+
struct CounterData {
- int64_t calls_started = 0;
- int64_t calls_succeeded = 0;
- int64_t calls_failed = 0;
- gpr_cycle_counter last_call_started_cycle = 0;
+ int64_t calls_started = 0;
+ int64_t calls_succeeded = 0;
+ int64_t calls_failed = 0;
+ gpr_cycle_counter last_call_started_cycle = 0;
};
// collects the sharded data into one CounterData struct.
void CollectData(CounterData* out);
- // Really zero-sized, but 0-sized arrays are illegal on MSVC.
+ // Really zero-sized, but 0-sized arrays are illegal on MSVC.
y_absl::InlinedVector<AtomicCounterData, 1> per_cpu_counter_data_storage_;
size_t num_cores_ = 0;
};
@@ -176,18 +176,18 @@ class ChannelNode : public BaseNode {
ChannelNode(TString target, size_t channel_tracer_max_nodes,
bool is_internal_channel);
- // Returns the string description of the given connectivity state.
- static const char* GetChannelConnectivityStateChangeString(
- grpc_connectivity_state state);
+ // Returns the string description of the given connectivity state.
+ static const char* GetChannelConnectivityStateChangeString(
+ grpc_connectivity_state state);
Json RenderJson() override;
// proxy methods to composed classes.
- void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
+ void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
trace_.AddTraceEvent(severity, data);
}
void AddTraceEventWithReference(ChannelTrace::Severity severity,
- const grpc_slice& data,
+ const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_channel) {
trace_.AddTraceEventWithReference(severity, data,
std::move(referenced_channel));
@@ -196,32 +196,32 @@ class ChannelNode : public BaseNode {
void RecordCallFailed() { call_counter_.RecordCallFailed(); }
void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); }
- void SetConnectivityState(grpc_connectivity_state state);
-
- // TODO(roth): take in a RefCountedPtr to the child channel so we can retrieve
- // the human-readable name.
- void AddChildChannel(intptr_t child_uuid);
- void RemoveChildChannel(intptr_t child_uuid);
-
- // TODO(roth): take in a RefCountedPtr to the child subchannel so we can
- // retrieve the human-readable name.
- void AddChildSubchannel(intptr_t child_uuid);
- void RemoveChildSubchannel(intptr_t child_uuid);
-
+ void SetConnectivityState(grpc_connectivity_state state);
+
+ // TODO(roth): take in a RefCountedPtr to the child channel so we can retrieve
+ // the human-readable name.
+ void AddChildChannel(intptr_t child_uuid);
+ void RemoveChildChannel(intptr_t child_uuid);
+
+ // TODO(roth): take in a RefCountedPtr to the child subchannel so we can
+ // retrieve the human-readable name.
+ void AddChildSubchannel(intptr_t child_uuid);
+ void RemoveChildSubchannel(intptr_t child_uuid);
+
private:
// Allows the channel trace test to access trace_.
friend class testing::ChannelNodePeer;
void PopulateChildRefs(Json::Object* json);
-
+
TString target_;
CallCountingHelper call_counter_;
ChannelTrace trace_;
-
- // Least significant bit indicates whether the value is set. Remaining
- // bits are a grpc_connectivity_state value.
- Atomic<int> connectivity_state_{0};
-
+
+ // Least significant bit indicates whether the value is set. Remaining
+ // bits are a grpc_connectivity_state value.
+ Atomic<int> connectivity_state_{0};
+
Mutex child_mu_; // Guards sets below.
std::set<intptr_t> child_channels_;
std::set<intptr_t> child_subchannels_;
@@ -231,7 +231,7 @@ class ChannelNode : public BaseNode {
class ServerNode : public BaseNode {
public:
explicit ServerNode(size_t channel_tracer_max_nodes);
-
+
~ServerNode() override;
Json RenderJson() override;
@@ -239,20 +239,20 @@ class ServerNode : public BaseNode {
TString RenderServerSockets(intptr_t start_socket_id,
intptr_t max_results);
- void AddChildSocket(RefCountedPtr<SocketNode> node);
-
- void RemoveChildSocket(intptr_t child_uuid);
-
- void AddChildListenSocket(RefCountedPtr<ListenSocketNode> node);
-
- void RemoveChildListenSocket(intptr_t child_uuid);
-
+ void AddChildSocket(RefCountedPtr<SocketNode> node);
+
+ void RemoveChildSocket(intptr_t child_uuid);
+
+ void AddChildListenSocket(RefCountedPtr<ListenSocketNode> node);
+
+ void RemoveChildListenSocket(intptr_t child_uuid);
+
// proxy methods to composed classes.
- void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
+ void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
trace_.AddTraceEvent(severity, data);
}
void AddTraceEventWithReference(ChannelTrace::Severity severity,
- const grpc_slice& data,
+ const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_channel) {
trace_.AddTraceEventWithReference(severity, data,
std::move(referenced_channel));
@@ -264,9 +264,9 @@ class ServerNode : public BaseNode {
private:
CallCountingHelper call_counter_;
ChannelTrace trace_;
- Mutex child_mu_; // Guards child maps below.
- std::map<intptr_t, RefCountedPtr<SocketNode>> child_sockets_;
- std::map<intptr_t, RefCountedPtr<ListenSocketNode>> child_listen_sockets_;
+ Mutex child_mu_; // Guards child maps below.
+ std::map<intptr_t, RefCountedPtr<SocketNode>> child_sockets_;
+ std::map<intptr_t, RefCountedPtr<ListenSocketNode>> child_listen_sockets_;
};
// Handles channelz bookkeeping for sockets
@@ -280,30 +280,30 @@ class SocketNode : public BaseNode {
void RecordStreamStartedFromLocal();
void RecordStreamStartedFromRemote();
void RecordStreamSucceeded() {
- streams_succeeded_.FetchAdd(1, MemoryOrder::RELAXED);
+ streams_succeeded_.FetchAdd(1, MemoryOrder::RELAXED);
}
void RecordStreamFailed() {
- streams_failed_.FetchAdd(1, MemoryOrder::RELAXED);
+ streams_failed_.FetchAdd(1, MemoryOrder::RELAXED);
}
void RecordMessagesSent(uint32_t num_sent);
void RecordMessageReceived();
void RecordKeepaliveSent() {
- keepalives_sent_.FetchAdd(1, MemoryOrder::RELAXED);
+ keepalives_sent_.FetchAdd(1, MemoryOrder::RELAXED);
}
const TString& remote() { return remote_; }
private:
- Atomic<int64_t> streams_started_{0};
- Atomic<int64_t> streams_succeeded_{0};
- Atomic<int64_t> streams_failed_{0};
- Atomic<int64_t> messages_sent_{0};
- Atomic<int64_t> messages_received_{0};
- Atomic<int64_t> keepalives_sent_{0};
- Atomic<gpr_cycle_counter> last_local_stream_created_cycle_{0};
- Atomic<gpr_cycle_counter> last_remote_stream_created_cycle_{0};
- Atomic<gpr_cycle_counter> last_message_sent_cycle_{0};
- Atomic<gpr_cycle_counter> last_message_received_cycle_{0};
+ Atomic<int64_t> streams_started_{0};
+ Atomic<int64_t> streams_succeeded_{0};
+ Atomic<int64_t> streams_failed_{0};
+ Atomic<int64_t> messages_sent_{0};
+ Atomic<int64_t> messages_received_{0};
+ Atomic<int64_t> keepalives_sent_{0};
+ Atomic<gpr_cycle_counter> last_local_stream_created_cycle_{0};
+ Atomic<gpr_cycle_counter> last_remote_stream_created_cycle_{0};
+ Atomic<gpr_cycle_counter> last_message_sent_cycle_{0};
+ Atomic<gpr_cycle_counter> last_message_received_cycle_{0};
TString local_;
TString remote_;
};
diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc
index 5a6e28ad78..5ebc1baf75 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc
@@ -18,9 +18,9 @@
#include <grpc/impl/codegen/port_platform.h>
-#include <algorithm>
-#include <cstring>
-
+#include <algorithm>
+#include <cstring>
+
#include "y_absl/container/inlined_vector.h"
#include "src/core/lib/channel/channel_trace.h"
@@ -28,7 +28,7 @@
#include "src/core/lib/channel/channelz_registry.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
@@ -46,9 +46,9 @@ const int kPaginationLimit = 100;
} // anonymous namespace
-void ChannelzRegistry::Init() { g_channelz_registry = new ChannelzRegistry(); }
+void ChannelzRegistry::Init() { g_channelz_registry = new ChannelzRegistry(); }
-void ChannelzRegistry::Shutdown() { delete g_channelz_registry; }
+void ChannelzRegistry::Shutdown() { delete g_channelz_registry; }
ChannelzRegistry* ChannelzRegistry::Default() {
GPR_DEBUG_ASSERT(g_channelz_registry != nullptr);
@@ -58,51 +58,51 @@ ChannelzRegistry* ChannelzRegistry::Default() {
void ChannelzRegistry::InternalRegister(BaseNode* node) {
MutexLock lock(&mu_);
node->uuid_ = ++uuid_generator_;
- node_map_[node->uuid_] = node;
+ node_map_[node->uuid_] = node;
}
void ChannelzRegistry::InternalUnregister(intptr_t uuid) {
GPR_ASSERT(uuid >= 1);
MutexLock lock(&mu_);
GPR_ASSERT(uuid <= uuid_generator_);
- node_map_.erase(uuid);
+ node_map_.erase(uuid);
}
-RefCountedPtr<BaseNode> ChannelzRegistry::InternalGet(intptr_t uuid) {
+RefCountedPtr<BaseNode> ChannelzRegistry::InternalGet(intptr_t uuid) {
MutexLock lock(&mu_);
if (uuid < 1 || uuid > uuid_generator_) {
return nullptr;
}
- auto it = node_map_.find(uuid);
- if (it == node_map_.end()) return nullptr;
- // Found node. Return only if its refcount is not zero (i.e., when we
- // know that there is no other thread about to destroy it).
- BaseNode* node = it->second;
+ auto it = node_map_.find(uuid);
+ if (it == node_map_.end()) return nullptr;
+ // Found node. Return only if its refcount is not zero (i.e., when we
+ // know that there is no other thread about to destroy it).
+ BaseNode* node = it->second;
return node->RefIfNonZero();
}
TString ChannelzRegistry::InternalGetTopChannels(
intptr_t start_channel_id) {
y_absl::InlinedVector<RefCountedPtr<BaseNode>, 10> top_level_channels;
- RefCountedPtr<BaseNode> node_after_pagination_limit;
- {
- MutexLock lock(&mu_);
- for (auto it = node_map_.lower_bound(start_channel_id);
- it != node_map_.end(); ++it) {
- BaseNode* node = it->second;
+ RefCountedPtr<BaseNode> node_after_pagination_limit;
+ {
+ MutexLock lock(&mu_);
+ for (auto it = node_map_.lower_bound(start_channel_id);
+ it != node_map_.end(); ++it) {
+ BaseNode* node = it->second;
RefCountedPtr<BaseNode> node_ref;
- if (node->type() == BaseNode::EntityType::kTopLevelChannel &&
+ if (node->type() == BaseNode::EntityType::kTopLevelChannel &&
(node_ref = node->RefIfNonZero()) != nullptr) {
- // Check if we are over pagination limit to determine if we need to set
- // the "end" element. If we don't go through this block, we know that
- // when the loop terminates, we have <= to kPaginationLimit.
- // Note that because we have already increased this node's
- // refcount, we need to decrease it, but we can't unref while
- // holding the lock, because this may lead to a deadlock.
- if (top_level_channels.size() == kPaginationLimit) {
+ // Check if we are over pagination limit to determine if we need to set
+ // the "end" element. If we don't go through this block, we know that
+ // when the loop terminates, we have <= to kPaginationLimit.
+ // Note that because we have already increased this node's
+ // refcount, we need to decrease it, but we can't unref while
+ // holding the lock, because this may lead to a deadlock.
+ if (top_level_channels.size() == kPaginationLimit) {
node_after_pagination_limit = std::move(node_ref);
- break;
- }
+ break;
+ }
top_level_channels.emplace_back(std::move(node_ref));
}
}
@@ -123,25 +123,25 @@ TString ChannelzRegistry::InternalGetTopChannels(
TString ChannelzRegistry::InternalGetServers(intptr_t start_server_id) {
y_absl::InlinedVector<RefCountedPtr<BaseNode>, 10> servers;
- RefCountedPtr<BaseNode> node_after_pagination_limit;
- {
- MutexLock lock(&mu_);
- for (auto it = node_map_.lower_bound(start_server_id);
- it != node_map_.end(); ++it) {
- BaseNode* node = it->second;
+ RefCountedPtr<BaseNode> node_after_pagination_limit;
+ {
+ MutexLock lock(&mu_);
+ for (auto it = node_map_.lower_bound(start_server_id);
+ it != node_map_.end(); ++it) {
+ BaseNode* node = it->second;
RefCountedPtr<BaseNode> node_ref;
- if (node->type() == BaseNode::EntityType::kServer &&
+ if (node->type() == BaseNode::EntityType::kServer &&
(node_ref = node->RefIfNonZero()) != nullptr) {
- // Check if we are over pagination limit to determine if we need to set
- // the "end" element. If we don't go through this block, we know that
- // when the loop terminates, we have <= to kPaginationLimit.
- // Note that because we have already increased this node's
- // refcount, we need to decrease it, but we can't unref while
- // holding the lock, because this may lead to a deadlock.
- if (servers.size() == kPaginationLimit) {
+ // Check if we are over pagination limit to determine if we need to set
+ // the "end" element. If we don't go through this block, we know that
+ // when the loop terminates, we have <= to kPaginationLimit.
+ // Note that because we have already increased this node's
+ // refcount, we need to decrease it, but we can't unref while
+ // holding the lock, because this may lead to a deadlock.
+ if (servers.size() == kPaginationLimit) {
node_after_pagination_limit = std::move(node_ref);
- break;
- }
+ break;
+ }
servers.emplace_back(std::move(node_ref));
}
}
@@ -162,19 +162,19 @@ TString ChannelzRegistry::InternalGetServers(intptr_t start_server_id) {
void ChannelzRegistry::InternalLogAllEntities() {
y_absl::InlinedVector<RefCountedPtr<BaseNode>, 10> nodes;
- {
- MutexLock lock(&mu_);
- for (auto& p : node_map_) {
+ {
+ MutexLock lock(&mu_);
+ for (auto& p : node_map_) {
RefCountedPtr<BaseNode> node = p.second->RefIfNonZero();
if (node != nullptr) {
nodes.emplace_back(std::move(node));
- }
+ }
}
}
- for (size_t i = 0; i < nodes.size(); ++i) {
+ for (size_t i = 0; i < nodes.size(); ++i) {
TString json = nodes[i]->RenderJsonString();
gpr_log(GPR_INFO, "%s", json.c_str());
- }
+ }
}
} // namespace channelz
@@ -193,7 +193,7 @@ char* grpc_channelz_get_servers(intptr_t start_server_id) {
}
char* grpc_channelz_get_server(intptr_t server_id) {
- 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);
if (server_node == nullptr ||
server_node->type() !=
@@ -210,7 +210,7 @@ char* grpc_channelz_get_server_sockets(intptr_t server_id,
intptr_t start_socket_id,
intptr_t max_results) {
// 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 =
grpc_core::channelz::ChannelzRegistry::Get(server_id);
if (base_node == nullptr ||
base_node->type() != grpc_core::channelz::BaseNode::EntityType::kServer ||
@@ -220,13 +220,13 @@ char* grpc_channelz_get_server_sockets(intptr_t server_id,
// This cast is ok since we have just checked to make sure base_node is
// actually a server node.
grpc_core::channelz::ServerNode* server_node =
- static_cast<grpc_core::channelz::ServerNode*>(base_node.get());
+ static_cast<grpc_core::channelz::ServerNode*>(base_node.get());
return gpr_strdup(
server_node->RenderServerSockets(start_socket_id, max_results).c_str());
}
char* grpc_channelz_get_channel(intptr_t channel_id) {
- 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);
if (channel_node == nullptr ||
(channel_node->type() !=
@@ -242,7 +242,7 @@ char* grpc_channelz_get_channel(intptr_t channel_id) {
}
char* grpc_channelz_get_subchannel(intptr_t subchannel_id) {
- 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);
if (subchannel_node == nullptr ||
subchannel_node->type() !=
@@ -256,7 +256,7 @@ char* grpc_channelz_get_subchannel(intptr_t subchannel_id) {
}
char* grpc_channelz_get_socket(intptr_t socket_id) {
- 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);
if (socket_node == nullptr ||
socket_node->type() !=
diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h
index 73a5e20fbd..b36fe731a2 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h
@@ -21,15 +21,15 @@
#include <grpc/impl/codegen/port_platform.h>
-#include <stdint.h>
-
+#include <stdint.h>
+
#include <map>
#include <util/generic/string.h>
#include "src/core/lib/channel/channel_trace.h"
#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/gprpp/map.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/map.h"
+#include "src/core/lib/gprpp/sync.h"
namespace grpc_core {
namespace channelz {
@@ -48,9 +48,9 @@ class ChannelzRegistry {
return Default()->InternalRegister(node);
}
static void Unregister(intptr_t uuid) { Default()->InternalUnregister(uuid); }
- static RefCountedPtr<BaseNode> Get(intptr_t uuid) {
- return Default()->InternalGet(uuid);
- }
+ static RefCountedPtr<BaseNode> Get(intptr_t uuid) {
+ return Default()->InternalGet(uuid);
+ }
// Returns the allocated JSON string that represents the proto
// GetTopChannelsResponse as per channelz.proto.
@@ -81,7 +81,7 @@ class ChannelzRegistry {
// if object with uuid has previously been registered as the correct type,
// returns the void* associated with that uuid. Else returns nullptr.
- RefCountedPtr<BaseNode> InternalGet(intptr_t uuid);
+ RefCountedPtr<BaseNode> InternalGet(intptr_t uuid);
TString InternalGetTopChannels(intptr_t start_channel_id);
TString InternalGetServers(intptr_t start_server_id);
@@ -89,8 +89,8 @@ class ChannelzRegistry {
void InternalLogAllEntities();
// protects members
- Mutex mu_;
- std::map<intptr_t, BaseNode*> node_map_;
+ Mutex mu_;
+ std::map<intptr_t, BaseNode*> node_map_;
intptr_t uuid_generator_ = 0;
};
diff --git a/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc b/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc
index be74d9e88b..c2b15ff14a 100644
--- a/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc
@@ -41,11 +41,11 @@ typedef struct connected_channel_channel_data {
struct callback_state {
grpc_closure closure;
grpc_closure* original_closure;
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
const char* reason;
};
typedef struct connected_channel_call_data {
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
// Closures used for returning results on the call combiner.
callback_state on_complete[6]; // Max number of pending batches.
callback_state recv_initial_metadata_ready;
@@ -99,7 +99,7 @@ static callback_state* get_state_for_batch(
/* Intercept a call operation and either push it directly up or translate it
into transport stream operations */
-static void connected_channel_start_transport_stream_op_batch(
+static void connected_channel_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
call_data* calld = static_cast<call_data*>(elem->call_data);
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
@@ -139,15 +139,15 @@ static void connected_channel_start_transport_stream_op_batch(
GRPC_CALL_COMBINER_STOP(calld->call_combiner, "passed batch to transport");
}
-static void connected_channel_start_transport_op(grpc_channel_element* elem,
- grpc_transport_op* op) {
+static void connected_channel_start_transport_op(grpc_channel_element* elem,
+ grpc_transport_op* op) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
grpc_transport_perform_op(chand->transport, op);
}
/* Constructor for call_data */
-static grpc_error* connected_channel_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* args) {
+static grpc_error* connected_channel_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* args) {
call_data* calld = static_cast<call_data*>(elem->call_data);
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
calld->call_combiner = args->call_combiner;
@@ -168,9 +168,9 @@ static void set_pollset_or_pollset_set(grpc_call_element* elem,
}
/* Destructor for call_data */
-static void connected_channel_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* then_schedule_closure) {
+static void connected_channel_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* then_schedule_closure) {
call_data* calld = static_cast<call_data*>(elem->call_data);
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
grpc_transport_destroy_stream(chand->transport,
@@ -179,8 +179,8 @@ static void connected_channel_destroy_call_elem(
}
/* Constructor for channel_data */
-static grpc_error* connected_channel_init_channel_elem(
- grpc_channel_element* elem, grpc_channel_element_args* args) {
+static grpc_error* connected_channel_init_channel_elem(
+ grpc_channel_element* elem, grpc_channel_element_args* args) {
channel_data* cd = static_cast<channel_data*>(elem->channel_data);
GPR_ASSERT(args->is_last);
cd->transport = nullptr;
@@ -188,7 +188,7 @@ static grpc_error* connected_channel_init_channel_elem(
}
/* Destructor for channel_data */
-static void connected_channel_destroy_channel_elem(grpc_channel_element* elem) {
+static void connected_channel_destroy_channel_elem(grpc_channel_element* elem) {
channel_data* cd = static_cast<channel_data*>(elem->channel_data);
if (cd->transport) {
grpc_transport_destroy(cd->transport);
@@ -196,21 +196,21 @@ static void connected_channel_destroy_channel_elem(grpc_channel_element* elem) {
}
/* No-op. */
-static void connected_channel_get_channel_info(
- grpc_channel_element* /*elem*/, const grpc_channel_info* /*channel_info*/) {
-}
+static void connected_channel_get_channel_info(
+ grpc_channel_element* /*elem*/, const grpc_channel_info* /*channel_info*/) {
+}
const grpc_channel_filter grpc_connected_filter = {
- connected_channel_start_transport_stream_op_batch,
- connected_channel_start_transport_op,
+ connected_channel_start_transport_stream_op_batch,
+ connected_channel_start_transport_op,
sizeof(call_data),
- connected_channel_init_call_elem,
+ connected_channel_init_call_elem,
set_pollset_or_pollset_set,
- connected_channel_destroy_call_elem,
+ connected_channel_destroy_call_elem,
sizeof(channel_data),
- connected_channel_init_channel_elem,
- connected_channel_destroy_channel_elem,
- connected_channel_get_channel_info,
+ connected_channel_init_channel_elem,
+ connected_channel_destroy_channel_elem,
+ connected_channel_get_channel_info,
"connected",
};
diff --git a/contrib/libs/grpc/src/core/lib/channel/context.h b/contrib/libs/grpc/src/core/lib/channel/context.h
index bd7fd495e4..dfab9ea086 100644
--- a/contrib/libs/grpc/src/core/lib/channel/context.h
+++ b/contrib/libs/grpc/src/core/lib/channel/context.h
@@ -36,7 +36,7 @@ typedef enum {
GRPC_CONTEXT_TRAFFIC,
/// Holds a pointer to ServiceConfigCallData associated with this call.
- GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA,
+ GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA,
GRPC_CONTEXT_COUNT
} grpc_context_index;
diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker.cc b/contrib/libs/grpc/src/core/lib/channel/handshaker.cc
index 826be41cbb..d9223104f6 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker.cc
@@ -22,7 +22,7 @@
#include "y_absl/strings/str_format.h"
-#include <grpc/impl/codegen/slice.h>
+#include <grpc/impl/codegen/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@@ -94,7 +94,7 @@ void HandshakeManager::ShutdownAllPending(grpc_error* why) {
}
void HandshakeManager::Add(RefCountedPtr<Handshaker> handshaker) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
gpr_log(
GPR_INFO,
"handshake_manager %p: adding handshaker %s [%p] at index %" PRIuPTR,
@@ -125,7 +125,7 @@ void HandshakeManager::Shutdown(grpc_error* why) {
// on_handshake_done callback.
// Returns true if we've scheduled the on_handshake_done callback.
bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
gpr_log(GPR_INFO,
"handshake_manager %p: error=%s shutdown=%d index=%" PRIuPTR
", args=%s",
@@ -158,7 +158,7 @@ bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) {
args_.read_buffer = nullptr;
}
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
gpr_log(GPR_INFO,
"handshake_manager %p: handshaking complete -- scheduling "
"on_handshake_done with error=%s",
@@ -167,11 +167,11 @@ bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) {
// Cancel deadline timer, since we're invoking the on_handshake_done
// callback now.
grpc_timer_cancel(&deadline_timer_);
- ExecCtx::Run(DEBUG_LOCATION, &on_handshake_done_, error);
+ ExecCtx::Run(DEBUG_LOCATION, &on_handshake_done_, error);
is_shutdown_ = true;
} else {
auto handshaker = handshakers_[index_];
- if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
gpr_log(
GPR_INFO,
"handshake_manager %p: calling handshaker %s [%p] at index %" PRIuPTR,
@@ -225,11 +225,11 @@ void HandshakeManager::DoHandshake(grpc_endpoint* endpoint,
args_.read_buffer =
static_cast<grpc_slice_buffer*>(gpr_malloc(sizeof(*args_.read_buffer)));
grpc_slice_buffer_init(args_.read_buffer);
- if (acceptor != nullptr && acceptor->external_connection &&
- acceptor->pending_data != nullptr) {
- grpc_slice_buffer_swap(args_.read_buffer,
- &(acceptor->pending_data->data.raw.slice_buffer));
- }
+ if (acceptor != nullptr && acceptor->external_connection &&
+ acceptor->pending_data != nullptr) {
+ grpc_slice_buffer_swap(args_.read_buffer,
+ &(acceptor->pending_data->data.raw.slice_buffer));
+ }
// Initialize state needed for calling handshakers.
acceptor_ = acceptor;
GRPC_CLOSURE_INIT(&call_next_handshaker_,
diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker.h b/contrib/libs/grpc/src/core/lib/channel/handshaker.h
index cc8e9b2578..5fd2259e98 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker.h
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker.h
@@ -29,7 +29,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/exec_ctx.h"
@@ -78,11 +78,11 @@ struct HandshakerArgs {
class Handshaker : public RefCounted<Handshaker> {
public:
virtual ~Handshaker() = default;
- virtual void Shutdown(grpc_error* why) = 0;
+ virtual void Shutdown(grpc_error* why) = 0;
virtual void DoHandshake(grpc_tcp_server_acceptor* acceptor,
grpc_closure* on_handshake_done,
- HandshakerArgs* args) = 0;
- virtual const char* name() const = 0;
+ HandshakerArgs* args) = 0;
+ virtual const char* name() const = 0;
};
//
diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h b/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h
index 520e5e4b25..637d018fbf 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h
@@ -33,7 +33,7 @@ class HandshakerFactory {
public:
virtual void AddHandshakers(const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
- HandshakeManager* handshake_mgr) = 0;
+ HandshakeManager* handshake_mgr) = 0;
virtual ~HandshakerFactory() = default;
};
diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc
index 614531832d..d3b89bb5f8 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc
@@ -21,7 +21,7 @@
#include "y_absl/container/inlined_vector.h"
#include "src/core/lib/channel/handshaker_registry.h"
-#include "src/core/lib/gpr/alloc.h"
+#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/gprpp/memory.h"
#include <string.h>
@@ -39,7 +39,7 @@ namespace {
class HandshakerFactoryList {
public:
- void Register(bool at_start, std::unique_ptr<HandshakerFactory> factory);
+ void Register(bool at_start, std::unique_ptr<HandshakerFactory> factory);
void AddHandshakers(const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
HandshakeManager* handshake_mgr);
@@ -52,8 +52,8 @@ HandshakerFactoryList* g_handshaker_factory_lists = nullptr;
} // namespace
-void HandshakerFactoryList::Register(
- bool at_start, std::unique_ptr<HandshakerFactory> factory) {
+void HandshakerFactoryList::Register(
+ bool at_start, std::unique_ptr<HandshakerFactory> factory) {
factories_.push_back(std::move(factory));
if (at_start) {
auto* end = &factories_[factories_.size() - 1];
@@ -87,7 +87,7 @@ void HandshakerRegistry::Shutdown() {
void HandshakerRegistry::RegisterHandshakerFactory(
bool at_start, HandshakerType handshaker_type,
- std::unique_ptr<HandshakerFactory> factory) {
+ std::unique_ptr<HandshakerFactory> factory) {
GPR_ASSERT(g_handshaker_factory_lists != nullptr);
auto& factory_list = g_handshaker_factory_lists[handshaker_type];
factory_list.Register(at_start, std::move(factory));
diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h
index 4a02efc3f2..2cf49efbfe 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h
@@ -38,9 +38,9 @@ class HandshakerRegistry {
/// Registers a new handshaker factory. Takes ownership.
/// If \a at_start is true, the new handshaker will be at the beginning of
/// the list. Otherwise, it will be added to the end.
- static void RegisterHandshakerFactory(
- bool at_start, HandshakerType handshaker_type,
- std::unique_ptr<HandshakerFactory> factory);
+ static void RegisterHandshakerFactory(
+ bool at_start, HandshakerType handshaker_type,
+ std::unique_ptr<HandshakerFactory> factory);
static void AddHandshakers(HandshakerType handshaker_type,
const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
diff --git a/contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h b/contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h
index d58d2f541a..f8360ce711 100644
--- a/contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h
@@ -32,7 +32,7 @@ grpc_slice grpc_compression_algorithm_slice(
/** Find compression algorithm based on passed in mdstr - returns
* GRPC_COMPRESS_ALGORITHM_COUNT on failure */
grpc_compression_algorithm grpc_compression_algorithm_from_slice(
- const grpc_slice& str);
+ const grpc_slice& str);
/** Return compression algorithm based metadata element */
grpc_mdelem grpc_compression_encoding_mdelem(
@@ -51,11 +51,11 @@ grpc_mdelem grpc_stream_compression_encoding_mdelem(
/** Find compression algorithm based on passed in mdstr - returns
* GRPC_COMPRESS_ALGORITHM_COUNT on failure */
grpc_message_compression_algorithm
-grpc_message_compression_algorithm_from_slice(const grpc_slice& str);
+grpc_message_compression_algorithm_from_slice(const grpc_slice& str);
/** Find stream compression algorithm based on passed in mdstr - returns
* GRPC_STREAM_COMPRESS_ALGORITHM_COUNT on failure */
grpc_stream_compression_algorithm grpc_stream_compression_algorithm_from_slice(
- const grpc_slice& str);
+ const grpc_slice& str);
#endif /* GRPC_CORE_LIB_COMPRESSION_ALGORITHM_METADATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/compression/compression.cc b/contrib/libs/grpc/src/core/lib/compression/compression.cc
index 8a0abca8dd..9262400980 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/compression.cc
@@ -26,7 +26,7 @@
#include "src/core/lib/compression/algorithm_metadata.h"
#include "src/core/lib/compression/compression_internal.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/slice/slice_utils.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/transport/static_metadata.h"
@@ -43,17 +43,17 @@ int grpc_compression_algorithm_is_stream(grpc_compression_algorithm algorithm) {
int grpc_compression_algorithm_parse(grpc_slice name,
grpc_compression_algorithm* algorithm) {
- if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_IDENTITY)) {
+ if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_IDENTITY)) {
*algorithm = GRPC_COMPRESS_NONE;
return 1;
- } else if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_DEFLATE)) {
+ } else if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_DEFLATE)) {
*algorithm = GRPC_COMPRESS_DEFLATE;
return 1;
- } else if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_GZIP)) {
+ } else if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_GZIP)) {
*algorithm = GRPC_COMPRESS_GZIP;
return 1;
- } else if (grpc_slice_eq_static_interned(name,
- GRPC_MDSTR_STREAM_SLASH_GZIP)) {
+ } else if (grpc_slice_eq_static_interned(name,
+ GRPC_MDSTR_STREAM_SLASH_GZIP)) {
*algorithm = GRPC_COMPRESS_STREAM_GZIP;
return 1;
} else {
@@ -63,7 +63,7 @@ int grpc_compression_algorithm_parse(grpc_slice name,
int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm,
const char** name) {
- GRPC_API_TRACE("grpc_compression_algorithm_name(algorithm=%d, name=%p)", 2,
+ GRPC_API_TRACE("grpc_compression_algorithm_name(algorithm=%d, name=%p)", 2,
((int)algorithm, name));
switch (algorithm) {
case GRPC_COMPRESS_NONE:
@@ -127,8 +127,8 @@ void grpc_compression_options_disable_algorithm(
int grpc_compression_options_is_algorithm_enabled(
const grpc_compression_options* opts,
grpc_compression_algorithm algorithm) {
- return grpc_compression_options_is_algorithm_enabled_internal(opts,
- algorithm);
+ return grpc_compression_options_is_algorithm_enabled_internal(opts,
+ algorithm);
}
grpc_slice grpc_compression_algorithm_slice(
@@ -149,14 +149,14 @@ grpc_slice grpc_compression_algorithm_slice(
}
grpc_compression_algorithm grpc_compression_algorithm_from_slice(
- const grpc_slice& str) {
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_IDENTITY))
- return GRPC_COMPRESS_NONE;
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_DEFLATE))
- return GRPC_COMPRESS_DEFLATE;
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_GZIP))
- return GRPC_COMPRESS_GZIP;
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_STREAM_SLASH_GZIP))
+ const grpc_slice& str) {
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_IDENTITY))
+ return GRPC_COMPRESS_NONE;
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_DEFLATE))
+ return GRPC_COMPRESS_DEFLATE;
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_GZIP))
+ return GRPC_COMPRESS_GZIP;
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_STREAM_SLASH_GZIP))
return GRPC_COMPRESS_STREAM_GZIP;
return GRPC_COMPRESS_ALGORITHMS_COUNT;
}
diff --git a/contrib/libs/grpc/src/core/lib/compression/compression_args.cc b/contrib/libs/grpc/src/core/lib/compression/compression_args.cc
index 6bbda64e26..784586daa1 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression_args.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/compression_args.cc
@@ -1,134 +1,134 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <limits.h>
-#include <string.h>
-
-#include <grpc/compression.h>
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/compression/compression_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
-
-grpc_compression_algorithm
-grpc_channel_args_get_channel_default_compression_algorithm(
- const grpc_channel_args* a) {
- size_t i;
- if (a == nullptr) return GRPC_COMPRESS_NONE;
- for (i = 0; i < a->num_args; ++i) {
- if (a->args[i].type == GRPC_ARG_INTEGER &&
- !strcmp(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, a->args[i].key)) {
- grpc_compression_algorithm default_algorithm =
- static_cast<grpc_compression_algorithm>(a->args[i].value.integer);
- return default_algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT
- ? default_algorithm
- : GRPC_COMPRESS_NONE;
- }
- }
- return GRPC_COMPRESS_NONE;
-}
-
-grpc_channel_args* grpc_channel_args_set_channel_default_compression_algorithm(
- grpc_channel_args* a, grpc_compression_algorithm algorithm) {
- GPR_ASSERT(algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT);
- grpc_arg tmp;
- tmp.type = GRPC_ARG_INTEGER;
- tmp.key = (char*)GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM;
- tmp.value.integer = algorithm;
- return grpc_channel_args_copy_and_add(a, &tmp, 1);
-}
-
-/** Returns 1 if the argument for compression algorithm's enabled states bitset
- * was found in \a a, returning the arg's value in \a states. Otherwise, returns
- * 0. */
-static int find_compression_algorithm_states_bitset(const grpc_channel_args* a,
- int** states_arg) {
- if (a != nullptr) {
- size_t i;
- for (i = 0; i < a->num_args; ++i) {
- if (a->args[i].type == GRPC_ARG_INTEGER &&
- !strcmp(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
- a->args[i].key)) {
- *states_arg = &a->args[i].value.integer;
- **states_arg =
- (**states_arg & ((1 << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1)) |
- 0x1; /* forcefully enable support for no compression */
- return 1;
- }
- }
- }
- return 0; /* GPR_FALSE */
-}
-
-grpc_channel_args* grpc_channel_args_compression_algorithm_set_state(
- grpc_channel_args** a, grpc_compression_algorithm algorithm, int state) {
- int* states_arg = nullptr;
- grpc_channel_args* result = *a;
- const int states_arg_found =
- find_compression_algorithm_states_bitset(*a, &states_arg);
-
- if (grpc_channel_args_get_channel_default_compression_algorithm(*a) ==
- algorithm &&
- state == 0) {
- const char* algo_name = nullptr;
- GPR_ASSERT(grpc_compression_algorithm_name(algorithm, &algo_name) != 0);
- gpr_log(GPR_ERROR,
- "Tried to disable default compression algorithm '%s'. The "
- "operation has been ignored.",
- algo_name);
- } else if (states_arg_found) {
- if (state != 0) {
- GPR_BITSET((unsigned*)states_arg, algorithm);
- } else if (algorithm != GRPC_COMPRESS_NONE) {
- GPR_BITCLEAR((unsigned*)states_arg, algorithm);
- }
- } else {
- /* create a new arg */
- grpc_arg tmp;
- tmp.type = GRPC_ARG_INTEGER;
- tmp.key = (char*)GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET;
- /* all enabled by default */
- tmp.value.integer = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1;
- if (state != 0) {
- GPR_BITSET((unsigned*)&tmp.value.integer, algorithm);
- } else if (algorithm != GRPC_COMPRESS_NONE) {
- GPR_BITCLEAR((unsigned*)&tmp.value.integer, algorithm);
- }
- result = grpc_channel_args_copy_and_add(*a, &tmp, 1);
- grpc_channel_args_destroy(*a);
- *a = result;
- }
- return result;
-}
-
-uint32_t grpc_channel_args_compression_algorithm_get_states(
- const grpc_channel_args* a) {
- int* states_arg;
- if (find_compression_algorithm_states_bitset(a, &states_arg)) {
- return static_cast<uint32_t>(*states_arg);
- } else {
- return (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; /* All algs. enabled */
- }
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <limits.h>
+#include <string.h>
+
+#include <grpc/compression.h>
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/compression/compression_args.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
+
+grpc_compression_algorithm
+grpc_channel_args_get_channel_default_compression_algorithm(
+ const grpc_channel_args* a) {
+ size_t i;
+ if (a == nullptr) return GRPC_COMPRESS_NONE;
+ for (i = 0; i < a->num_args; ++i) {
+ if (a->args[i].type == GRPC_ARG_INTEGER &&
+ !strcmp(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, a->args[i].key)) {
+ grpc_compression_algorithm default_algorithm =
+ static_cast<grpc_compression_algorithm>(a->args[i].value.integer);
+ return default_algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT
+ ? default_algorithm
+ : GRPC_COMPRESS_NONE;
+ }
+ }
+ return GRPC_COMPRESS_NONE;
+}
+
+grpc_channel_args* grpc_channel_args_set_channel_default_compression_algorithm(
+ grpc_channel_args* a, grpc_compression_algorithm algorithm) {
+ GPR_ASSERT(algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT);
+ grpc_arg tmp;
+ tmp.type = GRPC_ARG_INTEGER;
+ tmp.key = (char*)GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM;
+ tmp.value.integer = algorithm;
+ return grpc_channel_args_copy_and_add(a, &tmp, 1);
+}
+
+/** Returns 1 if the argument for compression algorithm's enabled states bitset
+ * was found in \a a, returning the arg's value in \a states. Otherwise, returns
+ * 0. */
+static int find_compression_algorithm_states_bitset(const grpc_channel_args* a,
+ int** states_arg) {
+ if (a != nullptr) {
+ size_t i;
+ for (i = 0; i < a->num_args; ++i) {
+ if (a->args[i].type == GRPC_ARG_INTEGER &&
+ !strcmp(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
+ a->args[i].key)) {
+ *states_arg = &a->args[i].value.integer;
+ **states_arg =
+ (**states_arg & ((1 << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1)) |
+ 0x1; /* forcefully enable support for no compression */
+ return 1;
+ }
+ }
+ }
+ return 0; /* GPR_FALSE */
+}
+
+grpc_channel_args* grpc_channel_args_compression_algorithm_set_state(
+ grpc_channel_args** a, grpc_compression_algorithm algorithm, int state) {
+ int* states_arg = nullptr;
+ grpc_channel_args* result = *a;
+ const int states_arg_found =
+ find_compression_algorithm_states_bitset(*a, &states_arg);
+
+ if (grpc_channel_args_get_channel_default_compression_algorithm(*a) ==
+ algorithm &&
+ state == 0) {
+ const char* algo_name = nullptr;
+ GPR_ASSERT(grpc_compression_algorithm_name(algorithm, &algo_name) != 0);
+ gpr_log(GPR_ERROR,
+ "Tried to disable default compression algorithm '%s'. The "
+ "operation has been ignored.",
+ algo_name);
+ } else if (states_arg_found) {
+ if (state != 0) {
+ GPR_BITSET((unsigned*)states_arg, algorithm);
+ } else if (algorithm != GRPC_COMPRESS_NONE) {
+ GPR_BITCLEAR((unsigned*)states_arg, algorithm);
+ }
+ } else {
+ /* create a new arg */
+ grpc_arg tmp;
+ tmp.type = GRPC_ARG_INTEGER;
+ tmp.key = (char*)GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET;
+ /* all enabled by default */
+ tmp.value.integer = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1;
+ if (state != 0) {
+ GPR_BITSET((unsigned*)&tmp.value.integer, algorithm);
+ } else if (algorithm != GRPC_COMPRESS_NONE) {
+ GPR_BITCLEAR((unsigned*)&tmp.value.integer, algorithm);
+ }
+ result = grpc_channel_args_copy_and_add(*a, &tmp, 1);
+ grpc_channel_args_destroy(*a);
+ *a = result;
+ }
+ return result;
+}
+
+uint32_t grpc_channel_args_compression_algorithm_get_states(
+ const grpc_channel_args* a) {
+ int* states_arg;
+ if (find_compression_algorithm_states_bitset(a, &states_arg)) {
+ return static_cast<uint32_t>(*states_arg);
+ } else {
+ return (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; /* All algs. enabled */
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/compression/compression_args.h b/contrib/libs/grpc/src/core/lib/compression/compression_args.h
index f1abc122ce..e127fd54df 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression_args.h
+++ b/contrib/libs/grpc/src/core/lib/compression/compression_args.h
@@ -1,56 +1,56 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H
-#define GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/compression.h>
-#include <grpc/impl/codegen/grpc_types.h>
-
-/** Returns the compression algorithm set in \a a. */
-grpc_compression_algorithm
-grpc_channel_args_get_channel_default_compression_algorithm(
- const grpc_channel_args* a);
-
-/** Returns a channel arg instance with compression enabled. If \a a is
- * non-NULL, its args are copied. N.B. GRPC_COMPRESS_NONE disables compression
- * for the channel. */
-grpc_channel_args* grpc_channel_args_set_channel_default_compression_algorithm(
- grpc_channel_args* a, grpc_compression_algorithm algorithm);
-
-/** Sets the support for the given compression algorithm. By default, all
- * compression algorithms are enabled. It's an error to disable an algorithm set
- * by grpc_channel_args_set_compression_algorithm.
- *
- * Returns an instance with the updated algorithm states. The \a a pointer is
- * modified to point to the returned instance (which may be different from the
- * input value of \a a). */
-grpc_channel_args* grpc_channel_args_compression_algorithm_set_state(
- grpc_channel_args** a, grpc_compression_algorithm algorithm, int state);
-
-/** Returns the bitset representing the support state (true for enabled, false
- * for disabled) for compression algorithms.
- *
- * The i-th bit of the returned bitset corresponds to the i-th entry in the
- * grpc_compression_algorithm enum. */
-uint32_t grpc_channel_args_compression_algorithm_get_states(
- const grpc_channel_args* a);
-
-#endif /* GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H
+#define GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/compression.h>
+#include <grpc/impl/codegen/grpc_types.h>
+
+/** Returns the compression algorithm set in \a a. */
+grpc_compression_algorithm
+grpc_channel_args_get_channel_default_compression_algorithm(
+ const grpc_channel_args* a);
+
+/** Returns a channel arg instance with compression enabled. If \a a is
+ * non-NULL, its args are copied. N.B. GRPC_COMPRESS_NONE disables compression
+ * for the channel. */
+grpc_channel_args* grpc_channel_args_set_channel_default_compression_algorithm(
+ grpc_channel_args* a, grpc_compression_algorithm algorithm);
+
+/** Sets the support for the given compression algorithm. By default, all
+ * compression algorithms are enabled. It's an error to disable an algorithm set
+ * by grpc_channel_args_set_compression_algorithm.
+ *
+ * Returns an instance with the updated algorithm states. The \a a pointer is
+ * modified to point to the returned instance (which may be different from the
+ * input value of \a a). */
+grpc_channel_args* grpc_channel_args_compression_algorithm_set_state(
+ grpc_channel_args** a, grpc_compression_algorithm algorithm, int state);
+
+/** Returns the bitset representing the support state (true for enabled, false
+ * for disabled) for compression algorithms.
+ *
+ * The i-th bit of the returned bitset corresponds to the i-th entry in the
+ * grpc_compression_algorithm enum. */
+uint32_t grpc_channel_args_compression_algorithm_get_states(
+ const grpc_channel_args* a);
+
+#endif /* GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H */
diff --git a/contrib/libs/grpc/src/core/lib/compression/compression_internal.cc b/contrib/libs/grpc/src/core/lib/compression/compression_internal.cc
index e0cf6d4519..2de672640e 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression_internal.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/compression_internal.cc
@@ -26,29 +26,29 @@
#include "src/core/lib/compression/algorithm_metadata.h"
#include "src/core/lib/compression/compression_internal.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/slice/slice_utils.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/transport/static_metadata.h"
/* Interfaces related to MD */
grpc_message_compression_algorithm
-grpc_message_compression_algorithm_from_slice(const grpc_slice& str) {
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_IDENTITY))
+grpc_message_compression_algorithm_from_slice(const grpc_slice& str) {
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_IDENTITY))
return GRPC_MESSAGE_COMPRESS_NONE;
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_DEFLATE))
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_DEFLATE))
return GRPC_MESSAGE_COMPRESS_DEFLATE;
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_GZIP))
- return GRPC_MESSAGE_COMPRESS_GZIP;
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_GZIP))
+ return GRPC_MESSAGE_COMPRESS_GZIP;
return GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT;
}
grpc_stream_compression_algorithm grpc_stream_compression_algorithm_from_slice(
- const grpc_slice& str) {
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_IDENTITY))
- return GRPC_STREAM_COMPRESS_NONE;
- if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_GZIP))
- return GRPC_STREAM_COMPRESS_GZIP;
+ const grpc_slice& str) {
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_IDENTITY))
+ return GRPC_STREAM_COMPRESS_NONE;
+ if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_GZIP))
+ return GRPC_STREAM_COMPRESS_GZIP;
return GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT;
}
@@ -171,7 +171,7 @@ int grpc_compression_algorithm_from_message_stream_compression_algorithm(
int grpc_message_compression_algorithm_name(
grpc_message_compression_algorithm algorithm, const char** name) {
GRPC_API_TRACE(
- "grpc_message_compression_algorithm_name(algorithm=%d, name=%p)", 2,
+ "grpc_message_compression_algorithm_name(algorithm=%d, name=%p)", 2,
((int)algorithm, name));
switch (algorithm) {
case GRPC_MESSAGE_COMPRESS_NONE:
@@ -248,13 +248,13 @@ grpc_message_compression_algorithm grpc_message_compression_algorithm_for_level(
int grpc_message_compression_algorithm_parse(
grpc_slice value, grpc_message_compression_algorithm* algorithm) {
- if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
+ if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
*algorithm = GRPC_MESSAGE_COMPRESS_NONE;
return 1;
- } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_DEFLATE)) {
+ } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_DEFLATE)) {
*algorithm = GRPC_MESSAGE_COMPRESS_DEFLATE;
return 1;
- } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
+ } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
*algorithm = GRPC_MESSAGE_COMPRESS_GZIP;
return 1;
} else {
@@ -267,10 +267,10 @@ int grpc_message_compression_algorithm_parse(
int grpc_stream_compression_algorithm_parse(
grpc_slice value, grpc_stream_compression_algorithm* algorithm) {
- if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
+ if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
*algorithm = GRPC_STREAM_COMPRESS_NONE;
return 1;
- } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
+ } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
*algorithm = GRPC_STREAM_COMPRESS_GZIP;
return 1;
} else {
diff --git a/contrib/libs/grpc/src/core/lib/compression/compression_internal.h b/contrib/libs/grpc/src/core/lib/compression/compression_internal.h
index 49afb941d7..8c4c7dc484 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression_internal.h
+++ b/contrib/libs/grpc/src/core/lib/compression/compression_internal.h
@@ -23,8 +23,8 @@
#include <grpc/impl/codegen/compression_types.h>
-#include "src/core/lib/gpr/useful.h"
-
+#include "src/core/lib/gpr/useful.h"
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -37,7 +37,7 @@ typedef enum {
GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT
} grpc_message_compression_algorithm;
-/** Stream compression algorithms supported by gRPC */
+/** Stream compression algorithms supported by gRPC */
typedef enum {
GRPC_STREAM_COMPRESS_NONE = 0,
GRPC_STREAM_COMPRESS_GZIP,
@@ -87,10 +87,10 @@ int grpc_stream_compression_algorithm_parse(
}
#endif
-inline int grpc_compression_options_is_algorithm_enabled_internal(
- const grpc_compression_options* opts,
- grpc_compression_algorithm algorithm) {
- return GPR_BITGET(opts->enabled_algorithms_bitset, algorithm);
-}
-
+inline int grpc_compression_options_is_algorithm_enabled_internal(
+ const grpc_compression_options* opts,
+ grpc_compression_algorithm algorithm) {
+ return GPR_BITGET(opts->enabled_algorithms_bitset, algorithm);
+}
+
#endif /* GRPC_CORE_LIB_COMPRESSION_COMPRESSION_INTERNAL_H */
diff --git a/contrib/libs/grpc/src/core/lib/compression/message_compress.cc b/contrib/libs/grpc/src/core/lib/compression/message_compress.cc
index 7c2a70bad4..8605b53d5f 100644
--- a/contrib/libs/grpc/src/core/lib/compression/message_compress.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/message_compress.cc
@@ -84,12 +84,12 @@ error:
return 0;
}
-static void* zalloc_gpr(void* /*opaque*/, unsigned int items,
- unsigned int size) {
+static void* zalloc_gpr(void* /*opaque*/, unsigned int items,
+ unsigned int size) {
return gpr_malloc(items * size);
}
-static void zfree_gpr(void* /*opaque*/, void* address) { gpr_free(address); }
+static void zfree_gpr(void* /*opaque*/, void* address) { gpr_free(address); }
static int zlib_compress(grpc_slice_buffer* input, grpc_slice_buffer* output,
int gzip) {
diff --git a/contrib/libs/grpc/src/core/lib/compression/stream_compression.cc b/contrib/libs/grpc/src/core/lib/compression/stream_compression.cc
index e085798864..a956b899b4 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression.cc
@@ -22,7 +22,7 @@
#include "src/core/lib/compression/stream_compression.h"
#include "src/core/lib/compression/stream_compression_gzip.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/slice/slice_utils.h"
extern const grpc_stream_compression_vtable
grpc_stream_compression_identity_vtable;
@@ -66,11 +66,11 @@ void grpc_stream_compression_context_destroy(
int grpc_stream_compression_method_parse(
grpc_slice value, bool is_compress,
grpc_stream_compression_method* method) {
- if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
+ if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
*method = is_compress ? GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
: GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
return 1;
- } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
+ } else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
*method = is_compress ? GRPC_STREAM_COMPRESSION_GZIP_COMPRESS
: GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS;
return 1;
diff --git a/contrib/libs/grpc/src/core/lib/compression/stream_compression.h b/contrib/libs/grpc/src/core/lib/compression/stream_compression.h
index 7328c3ec0f..26b20056fb 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression.h
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression.h
@@ -68,7 +68,7 @@ struct grpc_stream_compression_vtable {
* at the end of compression. Emits at most \a max_output_size compressed bytes
* into \a out. If all the bytes in input buffer \a in are depleted and \a flush
* is not GRPC_STREAM_COMPRESSION_FLUSH_NONE, the corresponding flush method is
- * executed. The total number of bytes emitted is outputted in \a output_size.
+ * executed. The total number of bytes emitted is outputted in \a output_size.
*
* A SYNC flush indicates that the entire messages in \a in can be decompressed
* from \a out. A FINISH flush implies a SYNC flush, and that any further
@@ -85,7 +85,7 @@ bool grpc_stream_compress(grpc_stream_compression_context* ctx,
* Decompress bytes provided in \a in with a given context. Emits at most \a
* max_output_size decompressed bytes into \a out. If decompression process
* reached the end of a gzip stream, \a end_of_context is set to true; otherwise
- * it is set to false. The total number of bytes emitted is outputted in \a
+ * it is set to false. The total number of bytes emitted is outputted in \a
* output_size.
*/
bool grpc_stream_decompress(grpc_stream_compression_context* ctx,
diff --git a/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.cc b/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.cc
index 452b22b762..47f384e503 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.cc
@@ -53,24 +53,24 @@ static bool gzip_flate(grpc_stream_compression_context_gzip* ctx,
ctx->zs.avail_out = static_cast<uInt>(slice_size);
ctx->zs.next_out = GRPC_SLICE_START_PTR(slice_out);
while (ctx->zs.avail_out > 0 && in->length > 0 && !eoc) {
- grpc_slice* slice = grpc_slice_buffer_peek_first(in);
- ctx->zs.avail_in = static_cast<uInt> GRPC_SLICE_LENGTH(*slice);
- ctx->zs.next_in = GRPC_SLICE_START_PTR(*slice);
+ grpc_slice* slice = grpc_slice_buffer_peek_first(in);
+ ctx->zs.avail_in = static_cast<uInt> GRPC_SLICE_LENGTH(*slice);
+ ctx->zs.next_in = GRPC_SLICE_START_PTR(*slice);
r = ctx->flate(&ctx->zs, Z_NO_FLUSH);
if (r < 0 && r != Z_BUF_ERROR) {
gpr_log(GPR_ERROR, "zlib error (%d)", r);
grpc_slice_unref_internal(slice_out);
- grpc_slice_buffer_remove_first(in);
+ grpc_slice_buffer_remove_first(in);
return false;
} else if (r == Z_STREAM_END && ctx->flate == inflate) {
eoc = true;
}
if (ctx->zs.avail_in > 0) {
- grpc_slice_buffer_sub_first(
- in, GRPC_SLICE_LENGTH(*slice) - ctx->zs.avail_in,
- GRPC_SLICE_LENGTH(*slice));
- } else {
- grpc_slice_buffer_remove_first(in);
+ grpc_slice_buffer_sub_first(
+ in, GRPC_SLICE_LENGTH(*slice) - ctx->zs.avail_in,
+ GRPC_SLICE_LENGTH(*slice));
+ } else {
+ grpc_slice_buffer_remove_first(in);
}
}
if (flush != 0 && ctx->zs.avail_out > 0 && !eoc) {
diff --git a/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.cc b/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.cc
index d5e3afff05..5bf9ba7ba5 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.cc
@@ -47,10 +47,10 @@ static void grpc_stream_compression_pass_through(grpc_slice_buffer* in,
}
}
-static bool grpc_stream_compress_identity(
- grpc_stream_compression_context* ctx, grpc_slice_buffer* in,
- grpc_slice_buffer* out, size_t* output_size, size_t max_output_size,
- grpc_stream_compression_flush /*flush*/) {
+static bool grpc_stream_compress_identity(
+ grpc_stream_compression_context* ctx, grpc_slice_buffer* in,
+ grpc_slice_buffer* out, size_t* output_size, size_t max_output_size,
+ grpc_stream_compression_flush /*flush*/) {
if (ctx == nullptr) {
return false;
}
@@ -82,7 +82,7 @@ grpc_stream_compression_context_create_identity(
}
static void grpc_stream_compression_context_destroy_identity(
- grpc_stream_compression_context* /*ctx*/) {
+ grpc_stream_compression_context* /*ctx*/) {
return;
}
diff --git a/contrib/libs/grpc/src/core/lib/debug/trace.cc b/contrib/libs/grpc/src/core/lib/debug/trace.cc
index 84c0a3805d..4b4c612c7a 100644
--- a/contrib/libs/grpc/src/core/lib/debug/trace.cc
+++ b/contrib/libs/grpc/src/core/lib/debug/trace.cc
@@ -27,11 +27,11 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-GPR_GLOBAL_CONFIG_DEFINE_STRING(
- grpc_trace, "",
- "A comma separated list of tracers that provide additional insight into "
- "how gRPC C core is processing requests via debug logs.");
-
+GPR_GLOBAL_CONFIG_DEFINE_STRING(
+ grpc_trace, "",
+ "A comma separated list of tracers that provide additional insight into "
+ "how gRPC C core is processing requests via debug logs.");
+
int grpc_tracer_set_enabled(const char* name, int enabled);
namespace grpc_core {
@@ -137,16 +137,16 @@ static void parse(const char* s) {
gpr_free(strings);
}
-void grpc_tracer_init(const char* env_var_name) {
- (void)env_var_name; // suppress unused variable error
- grpc_tracer_init();
-}
-
-void grpc_tracer_init() {
- grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_trace);
- parse(value.get());
+void grpc_tracer_init(const char* env_var_name) {
+ (void)env_var_name; // suppress unused variable error
+ grpc_tracer_init();
}
+void grpc_tracer_init() {
+ grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_trace);
+ parse(value.get());
+}
+
void grpc_tracer_shutdown(void) {}
int grpc_tracer_set_enabled(const char* name, int enabled) {
diff --git a/contrib/libs/grpc/src/core/lib/debug/trace.h b/contrib/libs/grpc/src/core/lib/debug/trace.h
index ac7b40e58a..fea799b2b9 100644
--- a/contrib/libs/grpc/src/core/lib/debug/trace.h
+++ b/contrib/libs/grpc/src/core/lib/debug/trace.h
@@ -24,15 +24,15 @@
#include <grpc/support/atm.h>
#include <stdbool.h>
-#include "src/core/lib/gprpp/global_config.h"
-
-GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_trace);
-
-// TODO(veblush): Remove this deprecated function once codes depending on this
-// function are updated in the internal repo.
+#include "src/core/lib/gprpp/global_config.h"
+
+GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_trace);
+
+// TODO(veblush): Remove this deprecated function once codes depending on this
+// function are updated in the internal repo.
void grpc_tracer_init(const char* env_var_name);
-
-void grpc_tracer_init();
+
+void grpc_tracer_init();
void grpc_tracer_shutdown(void);
#if defined(__has_feature)
@@ -61,8 +61,8 @@ void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag);
class TraceFlag {
public:
TraceFlag(bool default_enabled, const char* name);
- // TraceFlag needs to be trivially destructible since it is used as global
- // variable.
+ // TraceFlag needs to be trivially destructible since it is used as global
+ // variable.
~TraceFlag() = default;
const char* name() const { return name_; }
@@ -73,8 +73,8 @@ class TraceFlag {
// wrapped language (wr don't want to force recompilation to get tracing).
// Internally, however, for performance reasons, we compile them out by
// default, since internal build systems make recompiling trivial.
-//
-// Prefer GRPC_TRACE_FLAG_ENABLED() macro instead of using enabled() directly.
+//
+// Prefer GRPC_TRACE_FLAG_ENABLED() macro instead of using enabled() directly.
#define GRPC_USE_TRACERS // tracers on by default in OSS
#if defined(GRPC_USE_TRACERS) || !defined(NDEBUG)
bool enabled() {
@@ -109,20 +109,20 @@ class TraceFlag {
#endif
};
-#define GRPC_TRACE_FLAG_ENABLED(f) GPR_UNLIKELY((f).enabled())
-
+#define GRPC_TRACE_FLAG_ENABLED(f) GPR_UNLIKELY((f).enabled())
+
#ifndef NDEBUG
typedef TraceFlag DebugOnlyTraceFlag;
#else
class DebugOnlyTraceFlag {
public:
- constexpr DebugOnlyTraceFlag(bool /*default_enabled*/, const char* /*name*/) {
- }
+ constexpr DebugOnlyTraceFlag(bool /*default_enabled*/, const char* /*name*/) {
+ }
constexpr bool enabled() const { return false; }
constexpr const char* name() const { return "DebugOnlyTraceFlag"; }
private:
- void set_enabled(bool /*enabled*/) {}
+ void set_enabled(bool /*enabled*/) {}
};
#endif
diff --git a/contrib/libs/grpc/src/core/lib/gpr/alloc.cc b/contrib/libs/grpc/src/core/lib/gpr/alloc.cc
index 8c7345b7db..3a7b4a83e4 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/alloc.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/alloc.cc
@@ -29,7 +29,7 @@ void* gpr_malloc(size_t size) {
GPR_TIMER_SCOPE("gpr_malloc", 0);
void* p;
if (size == 0) return nullptr;
- p = malloc(size);
+ p = malloc(size);
if (!p) {
abort();
}
@@ -40,7 +40,7 @@ void* gpr_zalloc(size_t size) {
GPR_TIMER_SCOPE("gpr_zalloc", 0);
void* p;
if (size == 0) return nullptr;
- p = calloc(size, 1);
+ p = calloc(size, 1);
if (!p) {
abort();
}
@@ -49,13 +49,13 @@ void* gpr_zalloc(size_t size) {
void gpr_free(void* p) {
GPR_TIMER_SCOPE("gpr_free", 0);
- free(p);
+ free(p);
}
void* gpr_realloc(void* p, size_t size) {
GPR_TIMER_SCOPE("gpr_realloc", 0);
if ((size == 0) && (p == nullptr)) return nullptr;
- p = realloc(p, size);
+ p = realloc(p, size);
if (!p) {
abort();
}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/arena.h b/contrib/libs/grpc/src/core/lib/gpr/arena.h
index 4d70695149..efcfbe0722 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/arena.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/arena.h
@@ -21,27 +21,27 @@
// the arena as a whole is freed
// Tracks the total memory allocated against it, so that future arenas can
// pre-allocate the right amount of memory
-// This transitional API is deprecated and will be removed soon in favour of
-// src/core/lib/gprpp/arena.h .
+// This transitional API is deprecated and will be removed soon in favour of
+// src/core/lib/gprpp/arena.h .
#ifndef GRPC_CORE_LIB_GPR_ARENA_H
#define GRPC_CORE_LIB_GPR_ARENA_H
#include <grpc/support/port_platform.h>
-#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/arena.h"
-// TODO(arjunroy) : Remove deprecated gpr_arena API once all callers are gone.
-typedef class grpc_core::Arena gpr_arena;
+// TODO(arjunroy) : Remove deprecated gpr_arena API once all callers are gone.
+typedef class grpc_core::Arena gpr_arena;
// Create an arena, with \a initial_size bytes in the first allocated buffer
-inline gpr_arena* gpr_arena_create(size_t initial_size) {
- return grpc_core::Arena::Create(initial_size);
-}
-// Destroy an arena, returning the total number of bytes allocated
-inline size_t gpr_arena_destroy(gpr_arena* arena) { return arena->Destroy(); }
+inline gpr_arena* gpr_arena_create(size_t initial_size) {
+ return grpc_core::Arena::Create(initial_size);
+}
+// Destroy an arena, returning the total number of bytes allocated
+inline size_t gpr_arena_destroy(gpr_arena* arena) { return arena->Destroy(); }
// Allocate \a size bytes from the arena
-inline void* gpr_arena_alloc(gpr_arena* arena, size_t size) {
- return arena->Alloc(size);
-}
+inline void* gpr_arena_alloc(gpr_arena* arena, size_t size) {
+ return arena->Alloc(size);
+}
#endif /* GRPC_CORE_LIB_GPR_ARENA_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc b/contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc
index 2e16e3d992..ab89ac92dd 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc
@@ -72,7 +72,7 @@ unsigned gpr_cpu_current_cpu(void) {
return 0;
}
if (static_cast<unsigned>(cpu) >= gpr_cpu_num_cores()) {
- gpr_log(GPR_DEBUG, "Cannot handle hot-plugged CPUs");
+ gpr_log(GPR_DEBUG, "Cannot handle hot-plugged CPUs");
return 0;
}
return static_cast<unsigned>(cpu);
diff --git a/contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc
index 982ccbd6ff..ce3b5f98b1 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc
@@ -51,7 +51,7 @@ unsigned gpr_cpu_num_cores(void) {
static void delete_thread_id(void* value) {
if (value) {
- free(value);
+ free(value);
}
}
@@ -70,10 +70,10 @@ unsigned gpr_cpu_current_cpu(void) {
unsigned int* thread_id =
static_cast<unsigned int*>(pthread_getspecific(thread_id_key));
if (thread_id == nullptr) {
- // Note we cannot use gpr_malloc here because this allocation can happen in
- // a main thread and will only be free'd when the main thread exits, which
- // will cause our internal memory counters to believe it is a leak.
- thread_id = static_cast<unsigned int*>(malloc(sizeof(unsigned int)));
+ // Note we cannot use gpr_malloc here because this allocation can happen in
+ // a main thread and will only be free'd when the main thread exits, which
+ // will cause our internal memory counters to believe it is a leak.
+ thread_id = static_cast<unsigned int*>(malloc(sizeof(unsigned int)));
pthread_setspecific(thread_id_key, thread_id);
}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/env.h b/contrib/libs/grpc/src/core/lib/gpr/env.h
index f5016c6fa0..e12c0b5b20 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/env.h
@@ -26,7 +26,7 @@
/* Env utility functions */
/* Gets the environment variable value with the specified name.
- Returns a newly allocated string. It is the responsibility of the caller to
+ Returns a newly allocated string. It is the responsibility of the caller to
gpr_free the return value if not NULL (which means that the environment
variable exists). */
char* gpr_getenv(const char* name);
@@ -34,7 +34,7 @@ char* gpr_getenv(const char* name);
/* Sets the environment with the specified name to the specified value. */
void gpr_setenv(const char* name, const char* value);
-/* Deletes the variable name from the environment. */
-void gpr_unsetenv(const char* name);
+/* Deletes the variable name from the environment. */
+void gpr_unsetenv(const char* name);
#endif /* GRPC_CORE_LIB_GPR_ENV_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/env_linux.cc b/contrib/libs/grpc/src/core/lib/gpr/env_linux.cc
index 6a78dc1415..118cfbdbcf 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/env_linux.cc
@@ -38,20 +38,20 @@
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-char* gpr_getenv(const char* name) {
+char* gpr_getenv(const char* name) {
char* result = nullptr;
#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
typedef char* (*getenv_type)(const char*);
- static getenv_type getenv_func = nullptr;
+ static getenv_type getenv_func = nullptr;
/* Check to see which getenv variant is supported (go from most
* to least secure) */
- if (getenv_func == nullptr) {
- const char* names[] = {"secure_getenv", "__secure_getenv", "getenv"};
- for (size_t i = 0; i < GPR_ARRAY_SIZE(names); i++) {
- getenv_func = (getenv_type)dlsym(RTLD_DEFAULT, names[i]);
- if (getenv_func != nullptr) {
- break;
- }
+ if (getenv_func == nullptr) {
+ const char* names[] = {"secure_getenv", "__secure_getenv", "getenv"};
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(names); i++) {
+ getenv_func = (getenv_type)dlsym(RTLD_DEFAULT, names[i]);
+ if (getenv_func != nullptr) {
+ break;
+ }
}
}
result = getenv_func(name);
@@ -60,7 +60,7 @@ char* gpr_getenv(const char* name) {
#else
result = getenv(name);
#endif
- return result == nullptr ? result : gpr_strdup(result);
+ return result == nullptr ? result : gpr_strdup(result);
}
void gpr_setenv(const char* name, const char* value) {
@@ -68,9 +68,9 @@ void gpr_setenv(const char* name, const char* value) {
GPR_ASSERT(res == 0);
}
-void gpr_unsetenv(const char* name) {
- int res = unsetenv(name);
- GPR_ASSERT(res == 0);
-}
-
+void gpr_unsetenv(const char* name) {
+ int res = unsetenv(name);
+ GPR_ASSERT(res == 0);
+}
+
#endif /* GPR_LINUX_ENV */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/env_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/env_posix.cc
index 232095b4e2..849afa88e8 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/env_posix.cc
@@ -39,9 +39,9 @@ void gpr_setenv(const char* name, const char* value) {
GPR_ASSERT(res == 0);
}
-void gpr_unsetenv(const char* name) {
- int res = unsetenv(name);
- GPR_ASSERT(res == 0);
-}
-
+void gpr_unsetenv(const char* name) {
+ int res = unsetenv(name);
+ GPR_ASSERT(res == 0);
+}
+
#endif /* GPR_POSIX_ENV */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/env_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/env_windows.cc
index 76c45fb87a..185491464a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/env_windows.cc
@@ -64,11 +64,11 @@ void gpr_setenv(const char* name, const char* value) {
GPR_ASSERT(res);
}
-void gpr_unsetenv(const char* name) {
- LPTSTR tname = gpr_char_to_tchar(name);
- BOOL res = SetEnvironmentVariable(tname, NULL);
- gpr_free(tname);
- GPR_ASSERT(res);
-}
-
+void gpr_unsetenv(const char* name) {
+ LPTSTR tname = gpr_char_to_tchar(name);
+ BOOL res = SetEnvironmentVariable(tname, NULL);
+ gpr_free(tname);
+ GPR_ASSERT(res);
+}
+
#endif /* GPR_WINDOWS_ENV */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/log.cc b/contrib/libs/grpc/src/core/lib/gpr/log.cc
index 8a229b2adf..7e2fcc6856 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log.cc
@@ -23,14 +23,14 @@
#include <grpc/support/log.h>
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include <stdio.h>
#include <string.h>
-GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_verbosity, "ERROR",
- "Default gRPC logging verbosity")
-
+GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_verbosity, "ERROR",
+ "Default gRPC logging verbosity")
+
void gpr_default_log(gpr_log_func_args* args);
static gpr_atm g_log_func = (gpr_atm)gpr_default_log;
static gpr_atm g_min_severity_to_print = GPR_LOG_VERBOSITY_UNSET;
@@ -75,15 +75,15 @@ void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print) {
}
void gpr_log_verbosity_init() {
- grpc_core::UniquePtr<char> verbosity = GPR_GLOBAL_CONFIG_GET(grpc_verbosity);
+ grpc_core::UniquePtr<char> verbosity = GPR_GLOBAL_CONFIG_GET(grpc_verbosity);
gpr_atm min_severity_to_print = GPR_LOG_SEVERITY_ERROR;
- if (strlen(verbosity.get()) > 0) {
- if (gpr_stricmp(verbosity.get(), "DEBUG") == 0) {
+ if (strlen(verbosity.get()) > 0) {
+ if (gpr_stricmp(verbosity.get(), "DEBUG") == 0) {
min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_DEBUG);
- } else if (gpr_stricmp(verbosity.get(), "INFO") == 0) {
+ } else if (gpr_stricmp(verbosity.get(), "INFO") == 0) {
min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_INFO);
- } else if (gpr_stricmp(verbosity.get(), "ERROR") == 0) {
+ } else if (gpr_stricmp(verbosity.get(), "ERROR") == 0) {
min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_ERROR);
}
}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/log_linux.cc b/contrib/libs/grpc/src/core/lib/gpr/log_linux.cc
index 7b098d4711..1b572bd472 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log_linux.cc
@@ -41,7 +41,7 @@
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-static long sys_gettid(void) { return syscall(__NR_gettid); }
+static long sys_gettid(void) { return syscall(__NR_gettid); }
void gpr_log(const char* file, int line, gpr_log_severity severity,
const char* format, ...) {
@@ -70,7 +70,7 @@ void gpr_default_log(gpr_log_func_args* args) {
gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
struct tm tm;
static __thread long tid = 0;
- if (tid == 0) tid = sys_gettid();
+ if (tid == 0) tid = sys_gettid();
timer = static_cast<time_t>(now.tv_sec);
final_slash = strrchr(args->file, '/');
diff --git a/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc
index bc02118d94..dfeb3d4dac 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc
@@ -32,7 +32,7 @@
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-static intptr_t sys_gettid(void) { return (intptr_t)pthread_self(); }
+static intptr_t sys_gettid(void) { return (intptr_t)pthread_self(); }
void gpr_log(const char* file, int line, gpr_log_severity severity,
const char* format, ...) {
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string.cc b/contrib/libs/grpc/src/core/lib/gpr/string.cc
index 28f1ae437d..3984cb4191 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/string.cc
@@ -126,8 +126,8 @@ static void asciidump(dump_out* out, const char* buf, size_t len) {
}
}
-char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
- size_t* out_len) {
+char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
+ size_t* out_len) {
dump_out out = dump_out_create();
if (flags & GPR_DUMP_HEX) {
hexdump(&out, buf, len);
@@ -136,15 +136,15 @@ char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
asciidump(&out, buf, len);
}
dump_out_append(&out, 0);
- *out_len = out.length;
+ *out_len = out.length;
return out.data;
}
-char* gpr_dump(const char* buf, size_t len, uint32_t flags) {
- size_t unused;
- return gpr_dump_return_len(buf, len, flags, &unused);
-}
-
+char* gpr_dump(const char* buf, size_t len, uint32_t flags) {
+ size_t unused;
+ return gpr_dump_return_len(buf, len, flags, &unused);
+}
+
int gpr_parse_bytes_to_uint32(const char* buf, size_t len, uint32_t* result) {
uint32_t out = 0;
uint32_t new_val;
@@ -266,22 +266,22 @@ char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
return out;
}
-int gpr_strincmp(const char* a, const char* b, size_t n) {
+int gpr_strincmp(const char* a, const char* b, size_t n) {
int ca, cb;
do {
ca = tolower(*a);
cb = tolower(*b);
++a;
++b;
- --n;
- } while (ca == cb && ca != 0 && cb != 0 && n != 0);
+ --n;
+ } while (ca == cb && ca != 0 && cb != 0 && n != 0);
return ca - cb;
}
-int gpr_stricmp(const char* a, const char* b) {
- return gpr_strincmp(a, b, SIZE_MAX);
-}
-
+int gpr_stricmp(const char* a, const char* b) {
+ return gpr_strincmp(a, b, SIZE_MAX);
+}
+
static void add_string_to_split(const char* beg, const char* end, char*** strs,
size_t* nstrs, size_t* capstrs) {
char* out =
@@ -321,22 +321,22 @@ void* gpr_memrchr(const void* s, int c, size_t n) {
return nullptr;
}
-bool gpr_parse_bool_value(const char* s, bool* dst) {
- const char* kTrue[] = {"1", "t", "true", "y", "yes"};
- const char* kFalse[] = {"0", "f", "false", "n", "no"};
- static_assert(sizeof(kTrue) == sizeof(kFalse), "true_false_equal");
-
+bool gpr_parse_bool_value(const char* s, bool* dst) {
+ const char* kTrue[] = {"1", "t", "true", "y", "yes"};
+ const char* kFalse[] = {"0", "f", "false", "n", "no"};
+ static_assert(sizeof(kTrue) == sizeof(kFalse), "true_false_equal");
+
if (s == nullptr) {
return false;
}
- for (size_t i = 0; i < GPR_ARRAY_SIZE(kTrue); ++i) {
- if (gpr_stricmp(s, kTrue[i]) == 0) {
- *dst = true;
- return true;
- } else if (gpr_stricmp(s, kFalse[i]) == 0) {
- *dst = false;
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(kTrue); ++i) {
+ if (gpr_stricmp(s, kTrue[i]) == 0) {
+ *dst = true;
return true;
+ } else if (gpr_stricmp(s, kFalse[i]) == 0) {
+ *dst = false;
+ return true;
}
}
- return false; // didn't match a legal input
+ return false; // didn't match a legal input
}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string.h b/contrib/libs/grpc/src/core/lib/gpr/string.h
index 4b348198b8..146a2823f9 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/string.h
@@ -34,14 +34,14 @@
#define GPR_DUMP_HEX 0x00000001
#define GPR_DUMP_ASCII 0x00000002
-/* Converts array buf, of length len, into a C string according to the flags.
+/* Converts array buf, of length len, into a C string according to the flags.
Result should be freed with gpr_free() */
char* gpr_dump(const char* buf, size_t len, uint32_t flags);
-/* Converts array buf, of length len, into a C string according to the flags.
- The length of the returned buffer is stored in out_len.
- Result should be freed with gpr_free() */
-char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
- size_t* out_len);
+/* Converts array buf, of length len, into a C string according to the flags.
+ The length of the returned buffer is stored in out_len.
+ Result should be freed with gpr_free() */
+char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
+ size_t* out_len);
/* Parses an array of bytes into an integer (base 10). Returns 1 on success,
0 on failure. */
@@ -101,13 +101,13 @@ TString gpr_format_timespec(gpr_timespec);
/** Case insensitive string comparison... return <0 if lower(a)<lower(b), ==0 if
lower(a)==lower(b), >0 if lower(a)>lower(b) */
int gpr_stricmp(const char* a, const char* b);
-int gpr_strincmp(const char* a, const char* b, size_t n);
+int gpr_strincmp(const char* a, const char* b, size_t n);
void* gpr_memrchr(const void* s, int c, size_t n);
-/* Try to parse given string into a boolean value.
- When parsed successfully, dst will have the value and returns true.
- Otherwise, it returns false. */
-bool gpr_parse_bool_value(const char* value, bool* dst);
+/* Try to parse given string into a boolean value.
+ When parsed successfully, dst will have the value and returns true.
+ Otherwise, it returns false. */
+bool gpr_parse_bool_value(const char* value, bool* dst);
#endif /* GRPC_CORE_LIB_GPR_STRING_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc
index fdd278be23..f0b2374122 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc
@@ -21,7 +21,7 @@
#if defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC)
-#include <grpc/support/alloc.h>
+#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
@@ -38,53 +38,53 @@ gpr_atm gpr_counter_atm_add = 0;
#endif
void gpr_mu_init(gpr_mu* mu) {
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_mutex_init(&mu->mutex, nullptr) == 0);
- mu->leak_checker = static_cast<int*>(malloc(sizeof(*mu->leak_checker)));
- GPR_ASSERT(mu->leak_checker != nullptr);
-#else
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_mutex_init(&mu->mutex, nullptr) == 0);
+ mu->leak_checker = static_cast<int*>(malloc(sizeof(*mu->leak_checker)));
+ GPR_ASSERT(mu->leak_checker != nullptr);
+#else
GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);
-#endif
+#endif
}
-void gpr_mu_destroy(gpr_mu* mu) {
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);
- free(mu->leak_checker);
-#else
- GPR_ASSERT(pthread_mutex_destroy(mu) == 0);
-#endif
-}
+void gpr_mu_destroy(gpr_mu* mu) {
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);
+ free(mu->leak_checker);
+#else
+ GPR_ASSERT(pthread_mutex_destroy(mu) == 0);
+#endif
+}
void gpr_mu_lock(gpr_mu* mu) {
#ifdef GPR_LOW_LEVEL_COUNTERS
GPR_ATM_INC_COUNTER(gpr_mu_locks);
#endif
GPR_TIMER_SCOPE("gpr_mu_lock", 0);
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_mutex_lock(&mu->mutex) == 0);
-#else
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_mutex_lock(&mu->mutex) == 0);
+#else
GPR_ASSERT(pthread_mutex_lock(mu) == 0);
-#endif
+#endif
}
void gpr_mu_unlock(gpr_mu* mu) {
GPR_TIMER_SCOPE("gpr_mu_unlock", 0);
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_mutex_unlock(&mu->mutex) == 0);
-#else
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_mutex_unlock(&mu->mutex) == 0);
+#else
GPR_ASSERT(pthread_mutex_unlock(mu) == 0);
-#endif
+#endif
}
int gpr_mu_trylock(gpr_mu* mu) {
GPR_TIMER_SCOPE("gpr_mu_trylock", 0);
- int err = 0;
-#ifdef GRPC_ASAN_ENABLED
- err = pthread_mutex_trylock(&mu->mutex);
-#else
- err = pthread_mutex_trylock(mu);
-#endif
+ int err = 0;
+#ifdef GRPC_ASAN_ENABLED
+ err = pthread_mutex_trylock(&mu->mutex);
+#else
+ err = pthread_mutex_trylock(mu);
+#endif
GPR_ASSERT(err == 0 || err == EBUSY);
return err == 0;
}
@@ -97,34 +97,34 @@ void gpr_cv_init(gpr_cv* cv) {
#if GPR_LINUX
GPR_ASSERT(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0);
#endif // GPR_LINUX
-
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_cond_init(&cv->cond_var, &attr) == 0);
- cv->leak_checker = static_cast<int*>(malloc(sizeof(*cv->leak_checker)));
- GPR_ASSERT(cv->leak_checker != nullptr);
-#else
+
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_cond_init(&cv->cond_var, &attr) == 0);
+ cv->leak_checker = static_cast<int*>(malloc(sizeof(*cv->leak_checker)));
+ GPR_ASSERT(cv->leak_checker != nullptr);
+#else
GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);
-#endif
+#endif
}
-void gpr_cv_destroy(gpr_cv* cv) {
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);
- free(cv->leak_checker);
-#else
- GPR_ASSERT(pthread_cond_destroy(cv) == 0);
-#endif
+void gpr_cv_destroy(gpr_cv* cv) {
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);
+ free(cv->leak_checker);
+#else
+ GPR_ASSERT(pthread_cond_destroy(cv) == 0);
+#endif
}
int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
int err = 0;
if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
0) {
-#ifdef GRPC_ASAN_ENABLED
- err = pthread_cond_wait(&cv->cond_var, &mu->mutex);
-#else
+#ifdef GRPC_ASAN_ENABLED
+ err = pthread_cond_wait(&cv->cond_var, &mu->mutex);
+#else
err = pthread_cond_wait(cv, mu);
-#endif
+#endif
} else {
struct timespec abs_deadline_ts;
#if GPR_LINUX
@@ -134,9 +134,9 @@ int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
#endif // GPR_LINUX
abs_deadline_ts.tv_sec = static_cast<time_t>(abs_deadline.tv_sec);
abs_deadline_ts.tv_nsec = abs_deadline.tv_nsec;
-#ifdef GRPC_ASAN_ENABLED
- err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts);
-#else
+#ifdef GRPC_ASAN_ENABLED
+ err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts);
+#else
err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);
#endif
}
@@ -144,20 +144,20 @@ int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
return err == ETIMEDOUT;
}
-void gpr_cv_signal(gpr_cv* cv) {
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);
-#else
- GPR_ASSERT(pthread_cond_signal(cv) == 0);
-#endif
-}
+void gpr_cv_signal(gpr_cv* cv) {
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);
+#else
+ GPR_ASSERT(pthread_cond_signal(cv) == 0);
+#endif
+}
void gpr_cv_broadcast(gpr_cv* cv) {
-#ifdef GRPC_ASAN_ENABLED
- GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);
-#else
+#ifdef GRPC_ASAN_ENABLED
+ GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);
+#else
GPR_ASSERT(pthread_cond_broadcast(cv) == 0);
-#endif
+#endif
}
/*----------------------------------------*/
diff --git a/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc
index 0a9e1158b3..0dae41d0bd 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc
@@ -108,9 +108,9 @@ static gpr_timespec now_impl(gpr_clock_type clock) {
now.clock_type = clock;
switch (clock) {
case GPR_CLOCK_REALTIME:
- // gettimeofday(...) function may return with a value whose tv_usec is
- // greater than 1e6 on iOS The case is resolved with the guard at end of
- // this function.
+ // gettimeofday(...) function may return with a value whose tv_usec is
+ // greater than 1e6 on iOS The case is resolved with the guard at end of
+ // this function.
gettimeofday(&now_tv, nullptr);
now.tv_sec = now_tv.tv_sec;
now.tv_nsec = now_tv.tv_usec * 1000;
@@ -127,16 +127,16 @@ static gpr_timespec now_impl(gpr_clock_type clock) {
abort();
}
- // Guard the tv_nsec field in valid range for all clock types
- while (GPR_UNLIKELY(now.tv_nsec >= 1e9)) {
- now.tv_sec++;
- now.tv_nsec -= 1e9;
- }
- while (GPR_UNLIKELY(now.tv_nsec < 0)) {
- now.tv_sec--;
- now.tv_nsec += 1e9;
- }
-
+ // Guard the tv_nsec field in valid range for all clock types
+ while (GPR_UNLIKELY(now.tv_nsec >= 1e9)) {
+ now.tv_sec++;
+ now.tv_nsec -= 1e9;
+ }
+ while (GPR_UNLIKELY(now.tv_nsec < 0)) {
+ now.tv_sec--;
+ now.tv_nsec += 1e9;
+ }
+
return now;
}
#endif
diff --git a/contrib/libs/grpc/src/core/lib/gpr/time_precise.cc b/contrib/libs/grpc/src/core/lib/gpr/time_precise.cc
index 4d1b64b8b2..f44244efef 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_precise.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_precise.cc
@@ -18,14 +18,14 @@
#include <grpc/support/port_platform.h>
-#if GPR_LINUX
-#include <fcntl.h>
-#include <unistd.h>
-#endif
-
-#include <algorithm>
-
-#include <grpc/impl/codegen/gpr_types.h>
+#if GPR_LINUX
+#include <fcntl.h>
+#include <unistd.h>
+#endif
+
+#include <algorithm>
+
+#include <grpc/impl/codegen/gpr_types.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
@@ -33,135 +33,135 @@
#ifndef GPR_CYCLE_COUNTER_CUSTOM
#if GPR_CYCLE_COUNTER_RDTSC_32 || GPR_CYCLE_COUNTER_RDTSC_64
-#if GPR_LINUX
-static bool read_freq_from_kernel(double* freq) {
- // Google production kernel export the frequency for us in kHz.
- int fd = open("/sys/devices/system/cpu/cpu0/tsc_freq_khz", O_RDONLY);
- if (fd == -1) {
- return false;
- }
- char line[1024] = {};
- char* err;
- bool ret = false;
- int len = read(fd, line, sizeof(line) - 1);
- if (len > 0) {
- const long val = strtol(line, &err, 10);
- if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
- *freq = val * 1e3; // Value is kHz.
- ret = true;
- }
- }
- close(fd);
- return ret;
+#if GPR_LINUX
+static bool read_freq_from_kernel(double* freq) {
+ // Google production kernel export the frequency for us in kHz.
+ int fd = open("/sys/devices/system/cpu/cpu0/tsc_freq_khz", O_RDONLY);
+ if (fd == -1) {
+ return false;
+ }
+ char line[1024] = {};
+ char* err;
+ bool ret = false;
+ int len = read(fd, line, sizeof(line) - 1);
+ if (len > 0) {
+ const long val = strtol(line, &err, 10);
+ if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
+ *freq = val * 1e3; // Value is kHz.
+ ret = true;
+ }
+ }
+ close(fd);
+ return ret;
}
-#endif /* GPR_LINUX */
-
-static double cycles_per_second = 0;
-static gpr_cycle_counter start_cycle;
-
-static bool is_fake_clock() {
- gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
- int64_t sum = 0;
- for (int i = 0; i < 8; ++i) {
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- gpr_timespec delta = gpr_time_sub(now, start);
- sum += delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
- }
- // If the clock doesn't move even a nano after 8 tries, it's a fake one.
- return sum == 0;
+#endif /* GPR_LINUX */
+
+static double cycles_per_second = 0;
+static gpr_cycle_counter start_cycle;
+
+static bool is_fake_clock() {
+ gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
+ int64_t sum = 0;
+ for (int i = 0; i < 8; ++i) {
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ gpr_timespec delta = gpr_time_sub(now, start);
+ sum += delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
+ }
+ // If the clock doesn't move even a nano after 8 tries, it's a fake one.
+ return sum == 0;
}
void gpr_precise_clock_init(void) {
gpr_log(GPR_DEBUG, "Calibrating timers");
-
-#if GPR_LINUX
- if (read_freq_from_kernel(&cycles_per_second)) {
- start_cycle = gpr_get_cycle_counter();
- return;
- }
-#endif /* GPR_LINUX */
-
- if (is_fake_clock()) {
- cycles_per_second = 1;
- start_cycle = 0;
- return;
- }
- // Start from a loop of 1ms, and gradually increase the loop duration
- // until we either converge or we have passed 255ms (1ms+2ms+...+128ms).
- int64_t measurement_ns = GPR_NS_PER_MS;
- double last_freq = -1;
- bool converged = false;
- for (int i = 0; i < 8 && !converged; ++i, measurement_ns *= 2) {
- start_cycle = gpr_get_cycle_counter();
- int64_t loop_ns;
- gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
- do {
- // TODO(soheil): Maybe sleep instead of busy polling.
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- gpr_timespec delta = gpr_time_sub(now, start);
- loop_ns = delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
- } while (loop_ns < measurement_ns);
- gpr_cycle_counter end_cycle = gpr_get_cycle_counter();
- // Frequency should be in Hz.
- const double freq =
- static_cast<double>(end_cycle - start_cycle) / loop_ns * GPR_NS_PER_SEC;
- converged =
- last_freq != -1 && (freq * 0.99 < last_freq && last_freq < freq * 1.01);
- last_freq = freq;
- }
- cycles_per_second = last_freq;
+
+#if GPR_LINUX
+ if (read_freq_from_kernel(&cycles_per_second)) {
+ start_cycle = gpr_get_cycle_counter();
+ return;
+ }
+#endif /* GPR_LINUX */
+
+ if (is_fake_clock()) {
+ cycles_per_second = 1;
+ start_cycle = 0;
+ return;
+ }
+ // Start from a loop of 1ms, and gradually increase the loop duration
+ // until we either converge or we have passed 255ms (1ms+2ms+...+128ms).
+ int64_t measurement_ns = GPR_NS_PER_MS;
+ double last_freq = -1;
+ bool converged = false;
+ for (int i = 0; i < 8 && !converged; ++i, measurement_ns *= 2) {
+ start_cycle = gpr_get_cycle_counter();
+ int64_t loop_ns;
+ gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
+ do {
+ // TODO(soheil): Maybe sleep instead of busy polling.
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ gpr_timespec delta = gpr_time_sub(now, start);
+ loop_ns = delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
+ } while (loop_ns < measurement_ns);
+ gpr_cycle_counter end_cycle = gpr_get_cycle_counter();
+ // Frequency should be in Hz.
+ const double freq =
+ static_cast<double>(end_cycle - start_cycle) / loop_ns * GPR_NS_PER_SEC;
+ converged =
+ last_freq != -1 && (freq * 0.99 < last_freq && last_freq < freq * 1.01);
+ last_freq = freq;
+ }
+ cycles_per_second = last_freq;
gpr_log(GPR_DEBUG, "... cycles_per_second = %f\n", cycles_per_second);
}
-gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
- const double secs =
- static_cast<double>(cycles - start_cycle) / cycles_per_second;
- gpr_timespec ts;
- ts.tv_sec = static_cast<int64_t>(secs);
- ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
- (secs - static_cast<double>(ts.tv_sec)));
- ts.clock_type = GPR_CLOCK_PRECISE;
- return ts;
-}
-
-gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
- const double secs = static_cast<double>(a - b) / cycles_per_second;
- gpr_timespec ts;
- ts.tv_sec = static_cast<int64_t>(secs);
- ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
- (secs - static_cast<double>(ts.tv_sec)));
- ts.clock_type = GPR_TIMESPAN;
- return ts;
-}
-
+gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
+ const double secs =
+ static_cast<double>(cycles - start_cycle) / cycles_per_second;
+ gpr_timespec ts;
+ ts.tv_sec = static_cast<int64_t>(secs);
+ ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
+ (secs - static_cast<double>(ts.tv_sec)));
+ ts.clock_type = GPR_CLOCK_PRECISE;
+ return ts;
+}
+
+gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
+ const double secs = static_cast<double>(a - b) / cycles_per_second;
+ gpr_timespec ts;
+ ts.tv_sec = static_cast<int64_t>(secs);
+ ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
+ (secs - static_cast<double>(ts.tv_sec)));
+ ts.clock_type = GPR_TIMESPAN;
+ return ts;
+}
+
void gpr_precise_clock_now(gpr_timespec* clk) {
- int64_t counter = gpr_get_cycle_counter();
- *clk = gpr_cycle_counter_to_time(counter);
+ int64_t counter = gpr_get_cycle_counter();
+ *clk = gpr_cycle_counter_to_time(counter);
}
-#elif GPR_CYCLE_COUNTER_FALLBACK
+#elif GPR_CYCLE_COUNTER_FALLBACK
void gpr_precise_clock_init(void) {}
-gpr_cycle_counter gpr_get_cycle_counter() {
- gpr_timespec ts = gpr_now(GPR_CLOCK_REALTIME);
- return gpr_timespec_to_micros(ts);
-}
-
-gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
- gpr_timespec ts;
- ts.tv_sec = cycles / GPR_US_PER_SEC;
- ts.tv_nsec = (cycles - ts.tv_sec * GPR_US_PER_SEC) * GPR_NS_PER_US;
- ts.clock_type = GPR_CLOCK_PRECISE;
- return ts;
-}
-
+gpr_cycle_counter gpr_get_cycle_counter() {
+ gpr_timespec ts = gpr_now(GPR_CLOCK_REALTIME);
+ return gpr_timespec_to_micros(ts);
+}
+
+gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
+ gpr_timespec ts;
+ ts.tv_sec = cycles / GPR_US_PER_SEC;
+ ts.tv_nsec = (cycles - ts.tv_sec * GPR_US_PER_SEC) * GPR_NS_PER_US;
+ ts.clock_type = GPR_CLOCK_PRECISE;
+ return ts;
+}
+
void gpr_precise_clock_now(gpr_timespec* clk) {
*clk = gpr_now(GPR_CLOCK_REALTIME);
clk->clock_type = GPR_CLOCK_PRECISE;
}
-
-gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
- return gpr_time_sub(gpr_cycle_counter_to_time(a),
- gpr_cycle_counter_to_time(b));
-}
-#endif /* GPR_CYCLE_COUNTER_FALLBACK */
+
+gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
+ return gpr_time_sub(gpr_cycle_counter_to_time(a),
+ gpr_cycle_counter_to_time(b));
+}
+#endif /* GPR_CYCLE_COUNTER_FALLBACK */
#endif /* !GPR_CYCLE_COUNTER_CUSTOM */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/time_precise.h b/contrib/libs/grpc/src/core/lib/gpr/time_precise.h
index 1dcfa3b57e..eea1408e3f 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_precise.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_precise.h
@@ -21,50 +21,50 @@
#include <grpc/support/port_platform.h>
-#include <grpc/impl/codegen/gpr_types.h>
+#include <grpc/impl/codegen/gpr_types.h>
#include <grpc/support/time.h>
-// Depending on the platform gpr_get_cycle_counter() can have a resolution as
-// low as a usec. Use other clock sources or gpr_precise_clock_now(),
-// where you need high resolution clocks.
-//
-// Using gpr_get_cycle_counter() is preferred to using ExecCtx::Get()->Now()
-// whenever possible.
-
+// Depending on the platform gpr_get_cycle_counter() can have a resolution as
+// low as a usec. Use other clock sources or gpr_precise_clock_now(),
+// where you need high resolution clocks.
+//
+// Using gpr_get_cycle_counter() is preferred to using ExecCtx::Get()->Now()
+// whenever possible.
+
#if GPR_CYCLE_COUNTER_CUSTOM
-typedef int64_t gpr_cycle_counter;
+typedef int64_t gpr_cycle_counter;
gpr_cycle_counter gpr_get_cycle_counter();
#elif GPR_CYCLE_COUNTER_RDTSC_32
typedef int64_t gpr_cycle_counter;
-inline gpr_cycle_counter gpr_get_cycle_counter() {
- int64_t ret;
- __asm__ volatile("rdtsc" : "=A"(ret));
- return ret;
-}
-#elif GPR_CYCLE_COUNTER_RDTSC_64
-typedef int64_t gpr_cycle_counter;
-inline gpr_cycle_counter gpr_get_cycle_counter() {
- uint64_t low, high;
- __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
- return (high << 32) | low;
-}
-#elif GPR_CYCLE_COUNTER_FALLBACK
-// TODO(soheil): add support for mrs on Arm.
-
-// Real time in micros.
-typedef double gpr_cycle_counter;
-gpr_cycle_counter gpr_get_cycle_counter();
-#else
-#error Must define exactly one of \
- GPR_CYCLE_COUNTER_RDTSC_32, \
+inline gpr_cycle_counter gpr_get_cycle_counter() {
+ int64_t ret;
+ __asm__ volatile("rdtsc" : "=A"(ret));
+ return ret;
+}
+#elif GPR_CYCLE_COUNTER_RDTSC_64
+typedef int64_t gpr_cycle_counter;
+inline gpr_cycle_counter gpr_get_cycle_counter() {
+ uint64_t low, high;
+ __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
+ return (high << 32) | low;
+}
+#elif GPR_CYCLE_COUNTER_FALLBACK
+// TODO(soheil): add support for mrs on Arm.
+
+// Real time in micros.
+typedef double gpr_cycle_counter;
+gpr_cycle_counter gpr_get_cycle_counter();
+#else
+#error Must define exactly one of \
+ GPR_CYCLE_COUNTER_RDTSC_32, \
GPR_CYCLE_COUNTER_RDTSC_64, \
GPR_CYCLE_COUNTER_CUSTOM, or \
- GPR_CYCLE_COUNTER_FALLBACK
-#endif
-
+ GPR_CYCLE_COUNTER_FALLBACK
+#endif
+
void gpr_precise_clock_init(void);
void gpr_precise_clock_now(gpr_timespec* clk);
-gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles);
-gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b);
+gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles);
+gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b);
#endif /* GRPC_CORE_LIB_GPR_TIME_PRECISE_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/README.md b/contrib/libs/grpc/src/core/lib/gprpp/README.md
index f541d22bbc..9603c99c17 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/README.md
+++ b/contrib/libs/grpc/src/core/lib/gprpp/README.md
@@ -9,4 +9,4 @@ the use of portability macros.
Note that this is the only place in src/core where we allow
use of the C++ standard library (i.e., anything in the `std::`
-namespace).
+namespace).
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/arena.cc b/contrib/libs/grpc/src/core/lib/gprpp/arena.cc
index 61688258a1..bf4a64ff51 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/arena.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/arena.cc
@@ -1,103 +1,103 @@
-/*
- *
- * Copyright 2017 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/arena.h"
-
-#include <string.h>
-#include <new>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/gpr/alloc.h"
-#include "src/core/lib/gprpp/memory.h"
-
-namespace {
-
-void* ArenaStorage(size_t initial_size) {
- static constexpr size_t base_size =
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_core::Arena));
- initial_size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(initial_size);
- size_t alloc_size = base_size + initial_size;
- static constexpr size_t alignment =
- (GPR_CACHELINE_SIZE > GPR_MAX_ALIGNMENT &&
- GPR_CACHELINE_SIZE % GPR_MAX_ALIGNMENT == 0)
- ? GPR_CACHELINE_SIZE
- : GPR_MAX_ALIGNMENT;
- return gpr_malloc_aligned(alloc_size, alignment);
-}
-
-} // namespace
-
-namespace grpc_core {
-
-Arena::~Arena() {
- Zone* z = last_zone_;
- while (z) {
- Zone* prev_z = z->prev;
- z->~Zone();
- gpr_free_aligned(z);
- z = prev_z;
- }
-}
-
-Arena* Arena::Create(size_t initial_size) {
- return new (ArenaStorage(initial_size)) Arena(initial_size);
-}
-
-std::pair<Arena*, void*> Arena::CreateWithAlloc(size_t initial_size,
- size_t alloc_size) {
- static constexpr size_t base_size =
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
- auto* new_arena =
- new (ArenaStorage(initial_size)) Arena(initial_size, alloc_size);
- void* first_alloc = reinterpret_cast<char*>(new_arena) + base_size;
- return std::make_pair(new_arena, first_alloc);
-}
-
-size_t Arena::Destroy() {
- size_t size = total_used_.Load(MemoryOrder::RELAXED);
- this->~Arena();
- gpr_free_aligned(this);
- return size;
-}
-
-void* Arena::AllocZone(size_t size) {
- // If the allocation isn't able to end in the initial zone, create a new
- // zone for this allocation, and any unused space in the initial zone is
- // wasted. This overflowing and wasting is uncommon because of our arena
- // sizing hysteresis (that is, most calls should have a large enough initial
- // zone and will not need to grow the arena).
- static constexpr size_t zone_base_size =
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Zone));
- size_t alloc_size = zone_base_size + size;
- Zone* z = new (gpr_malloc_aligned(alloc_size, GPR_MAX_ALIGNMENT)) Zone();
- {
- gpr_spinlock_lock(&arena_growth_spinlock_);
- z->prev = last_zone_;
- last_zone_ = z;
- gpr_spinlock_unlock(&arena_growth_spinlock_);
- }
- return reinterpret_cast<char*>(z) + zone_base_size;
-}
-
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2017 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/arena.h"
+
+#include <string.h>
+#include <new>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/gpr/alloc.h"
+#include "src/core/lib/gprpp/memory.h"
+
+namespace {
+
+void* ArenaStorage(size_t initial_size) {
+ static constexpr size_t base_size =
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_core::Arena));
+ initial_size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(initial_size);
+ size_t alloc_size = base_size + initial_size;
+ static constexpr size_t alignment =
+ (GPR_CACHELINE_SIZE > GPR_MAX_ALIGNMENT &&
+ GPR_CACHELINE_SIZE % GPR_MAX_ALIGNMENT == 0)
+ ? GPR_CACHELINE_SIZE
+ : GPR_MAX_ALIGNMENT;
+ return gpr_malloc_aligned(alloc_size, alignment);
+}
+
+} // namespace
+
+namespace grpc_core {
+
+Arena::~Arena() {
+ Zone* z = last_zone_;
+ while (z) {
+ Zone* prev_z = z->prev;
+ z->~Zone();
+ gpr_free_aligned(z);
+ z = prev_z;
+ }
+}
+
+Arena* Arena::Create(size_t initial_size) {
+ return new (ArenaStorage(initial_size)) Arena(initial_size);
+}
+
+std::pair<Arena*, void*> Arena::CreateWithAlloc(size_t initial_size,
+ size_t alloc_size) {
+ static constexpr size_t base_size =
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
+ auto* new_arena =
+ new (ArenaStorage(initial_size)) Arena(initial_size, alloc_size);
+ void* first_alloc = reinterpret_cast<char*>(new_arena) + base_size;
+ return std::make_pair(new_arena, first_alloc);
+}
+
+size_t Arena::Destroy() {
+ size_t size = total_used_.Load(MemoryOrder::RELAXED);
+ this->~Arena();
+ gpr_free_aligned(this);
+ return size;
+}
+
+void* Arena::AllocZone(size_t size) {
+ // If the allocation isn't able to end in the initial zone, create a new
+ // zone for this allocation, and any unused space in the initial zone is
+ // wasted. This overflowing and wasting is uncommon because of our arena
+ // sizing hysteresis (that is, most calls should have a large enough initial
+ // zone and will not need to grow the arena).
+ static constexpr size_t zone_base_size =
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Zone));
+ size_t alloc_size = zone_base_size + size;
+ Zone* z = new (gpr_malloc_aligned(alloc_size, GPR_MAX_ALIGNMENT)) Zone();
+ {
+ gpr_spinlock_lock(&arena_growth_spinlock_);
+ z->prev = last_zone_;
+ last_zone_ = z;
+ gpr_spinlock_unlock(&arena_growth_spinlock_);
+ }
+ return reinterpret_cast<char*>(z) + zone_base_size;
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/arena.h b/contrib/libs/grpc/src/core/lib/gprpp/arena.h
index 67c91d9f49..93801884be 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/arena.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/arena.h
@@ -1,120 +1,120 @@
-/*
- *
- * Copyright 2017 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.
- *
- */
-
-// \file Arena based allocator
-// Allows very fast allocation of memory, but that memory cannot be freed until
-// the arena as a whole is freed
-// Tracks the total memory allocated against it, so that future arenas can
-// pre-allocate the right amount of memory
-
-#ifndef GRPC_CORE_LIB_GPRPP_ARENA_H
-#define GRPC_CORE_LIB_GPRPP_ARENA_H
-
-#include <grpc/support/port_platform.h>
-
-#include <new>
-#include <utility>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/gpr/alloc.h"
-#include "src/core/lib/gpr/spinlock.h"
-#include "src/core/lib/gprpp/atomic.h"
-
-#include <stddef.h>
-
-namespace grpc_core {
-
-class Arena {
- public:
- // Create an arena, with \a initial_size bytes in the first allocated buffer.
- static Arena* Create(size_t initial_size);
-
- // Create an arena, with \a initial_size bytes in the first allocated buffer,
- // and return both a void pointer to the returned arena and a void* with the
- // first allocation.
- static std::pair<Arena*, void*> CreateWithAlloc(size_t initial_size,
- size_t alloc_size);
-
- // Destroy an arena, returning the total number of bytes allocated.
- size_t Destroy();
- // Allocate \a size bytes from the arena.
- void* Alloc(size_t size) {
- static constexpr size_t base_size =
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
- size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(size);
- size_t begin = total_used_.FetchAdd(size, MemoryOrder::RELAXED);
- if (begin + size <= initial_zone_size_) {
- return reinterpret_cast<char*>(this) + base_size + begin;
- } else {
- return AllocZone(size);
- }
- }
-
- // TODO(roth): We currently assume that all callers need alignment of 16
- // bytes, which may be wrong in some cases. When we have time, we should
- // change this to instead use the alignment of the type being allocated by
- // this method.
- template <typename T, typename... Args>
- T* New(Args&&... args) {
- T* t = static_cast<T*>(Alloc(sizeof(T)));
- new (t) T(std::forward<Args>(args)...);
- return t;
- }
-
- private:
- struct Zone {
- Zone* prev;
- };
-
- // Initialize an arena.
- // Parameters:
- // initial_size: The initial size of the whole arena in bytes. These bytes
- // are contained within 'zone 0'. If the arena user ends up requiring more
- // memory than the arena contains in zone 0, subsequent zones are allocated
- // on demand and maintained in a tail-linked list.
- //
- // initial_alloc: Optionally, construct the arena as though a call to
- // Alloc() had already been made for initial_alloc bytes. This provides a
- // quick optimization (avoiding an atomic fetch-add) for the common case
- // where we wish to create an arena and then perform an immediate
- // allocation.
- explicit Arena(size_t initial_size, size_t initial_alloc = 0)
- : total_used_(initial_alloc), initial_zone_size_(initial_size) {}
-
- ~Arena();
-
- void* AllocZone(size_t size);
-
- // Keep track of the total used size. We use this in our call sizing
- // hysteresis.
- Atomic<size_t> total_used_;
- size_t initial_zone_size_;
- gpr_spinlock arena_growth_spinlock_ = GPR_SPINLOCK_STATIC_INITIALIZER;
- // If the initial arena allocation wasn't enough, we allocate additional zones
- // in a reverse linked list. Each additional zone consists of (1) a pointer to
- // the zone added before this zone (null if this is the first additional zone)
- // and (2) the allocated memory. The arena itself maintains a pointer to the
- // last zone; the zone list is reverse-walked during arena destruction only.
- Zone* last_zone_ = nullptr;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_ARENA_H */
+/*
+ *
+ * Copyright 2017 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.
+ *
+ */
+
+// \file Arena based allocator
+// Allows very fast allocation of memory, but that memory cannot be freed until
+// the arena as a whole is freed
+// Tracks the total memory allocated against it, so that future arenas can
+// pre-allocate the right amount of memory
+
+#ifndef GRPC_CORE_LIB_GPRPP_ARENA_H
+#define GRPC_CORE_LIB_GPRPP_ARENA_H
+
+#include <grpc/support/port_platform.h>
+
+#include <new>
+#include <utility>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/gpr/alloc.h"
+#include "src/core/lib/gpr/spinlock.h"
+#include "src/core/lib/gprpp/atomic.h"
+
+#include <stddef.h>
+
+namespace grpc_core {
+
+class Arena {
+ public:
+ // Create an arena, with \a initial_size bytes in the first allocated buffer.
+ static Arena* Create(size_t initial_size);
+
+ // Create an arena, with \a initial_size bytes in the first allocated buffer,
+ // and return both a void pointer to the returned arena and a void* with the
+ // first allocation.
+ static std::pair<Arena*, void*> CreateWithAlloc(size_t initial_size,
+ size_t alloc_size);
+
+ // Destroy an arena, returning the total number of bytes allocated.
+ size_t Destroy();
+ // Allocate \a size bytes from the arena.
+ void* Alloc(size_t size) {
+ static constexpr size_t base_size =
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
+ size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(size);
+ size_t begin = total_used_.FetchAdd(size, MemoryOrder::RELAXED);
+ if (begin + size <= initial_zone_size_) {
+ return reinterpret_cast<char*>(this) + base_size + begin;
+ } else {
+ return AllocZone(size);
+ }
+ }
+
+ // TODO(roth): We currently assume that all callers need alignment of 16
+ // bytes, which may be wrong in some cases. When we have time, we should
+ // change this to instead use the alignment of the type being allocated by
+ // this method.
+ template <typename T, typename... Args>
+ T* New(Args&&... args) {
+ T* t = static_cast<T*>(Alloc(sizeof(T)));
+ new (t) T(std::forward<Args>(args)...);
+ return t;
+ }
+
+ private:
+ struct Zone {
+ Zone* prev;
+ };
+
+ // Initialize an arena.
+ // Parameters:
+ // initial_size: The initial size of the whole arena in bytes. These bytes
+ // are contained within 'zone 0'. If the arena user ends up requiring more
+ // memory than the arena contains in zone 0, subsequent zones are allocated
+ // on demand and maintained in a tail-linked list.
+ //
+ // initial_alloc: Optionally, construct the arena as though a call to
+ // Alloc() had already been made for initial_alloc bytes. This provides a
+ // quick optimization (avoiding an atomic fetch-add) for the common case
+ // where we wish to create an arena and then perform an immediate
+ // allocation.
+ explicit Arena(size_t initial_size, size_t initial_alloc = 0)
+ : total_used_(initial_alloc), initial_zone_size_(initial_size) {}
+
+ ~Arena();
+
+ void* AllocZone(size_t size);
+
+ // Keep track of the total used size. We use this in our call sizing
+ // hysteresis.
+ Atomic<size_t> total_used_;
+ size_t initial_zone_size_;
+ gpr_spinlock arena_growth_spinlock_ = GPR_SPINLOCK_STATIC_INITIALIZER;
+ // If the initial arena allocation wasn't enough, we allocate additional zones
+ // in a reverse linked list. Each additional zone consists of (1) a pointer to
+ // the zone added before this zone (null if this is the first additional zone)
+ // and (2) the allocated memory. The arena itself maintains a pointer to the
+ // last zone; the zone list is reverse-walked during arena destruction only.
+ Zone* last_zone_ = nullptr;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_ARENA_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/atomic.h b/contrib/libs/grpc/src/core/lib/gprpp/atomic.h
index 4a53d2cfa5..dc4e677404 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/atomic.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/atomic.h
@@ -21,84 +21,84 @@
#include <grpc/support/port_platform.h>
-#include <atomic>
+#include <atomic>
-#include <grpc/support/atm.h>
-
-namespace grpc_core {
-
-enum class MemoryOrder {
+#include <grpc/support/atm.h>
+
+namespace grpc_core {
+
+enum class MemoryOrder {
RELAXED = static_cast<int>(std::memory_order_relaxed),
CONSUME = static_cast<int>(std::memory_order_consume),
ACQUIRE = static_cast<int>(std::memory_order_acquire),
RELEASE = static_cast<int>(std::memory_order_release),
ACQ_REL = static_cast<int>(std::memory_order_acq_rel),
SEQ_CST = static_cast<int>(std::memory_order_seq_cst)
-};
-
-template <typename T>
-class Atomic {
- public:
- explicit Atomic(T val = T()) : storage_(val) {}
-
- T Load(MemoryOrder order) const {
- return storage_.load(static_cast<std::memory_order>(order));
- }
-
- void Store(T val, MemoryOrder order) {
- storage_.store(val, static_cast<std::memory_order>(order));
- }
-
- T Exchange(T desired, MemoryOrder order) {
- return storage_.exchange(desired, static_cast<std::memory_order>(order));
- }
-
- bool CompareExchangeWeak(T* expected, T desired, MemoryOrder success,
- MemoryOrder failure) {
- return GPR_ATM_INC_CAS_THEN(storage_.compare_exchange_weak(
- *expected, desired, static_cast<std::memory_order>(success),
- static_cast<std::memory_order>(failure)));
- }
-
- bool CompareExchangeStrong(T* expected, T desired, MemoryOrder success,
- MemoryOrder failure) {
- return GPR_ATM_INC_CAS_THEN(storage_.compare_exchange_strong(
- *expected, desired, static_cast<std::memory_order>(success),
- static_cast<std::memory_order>(failure)));
- }
-
- template <typename Arg>
- T FetchAdd(Arg arg, MemoryOrder order = MemoryOrder::SEQ_CST) {
- return GPR_ATM_INC_ADD_THEN(storage_.fetch_add(
- static_cast<Arg>(arg), static_cast<std::memory_order>(order)));
- }
-
- template <typename Arg>
- T FetchSub(Arg arg, MemoryOrder order = MemoryOrder::SEQ_CST) {
- return GPR_ATM_INC_ADD_THEN(storage_.fetch_sub(
- static_cast<Arg>(arg), static_cast<std::memory_order>(order)));
- }
-
- // Atomically increment a counter only if the counter value is not zero.
- // Returns true if increment took place; false if counter is zero.
- bool IncrementIfNonzero(MemoryOrder load_order = MemoryOrder::ACQUIRE) {
- T count = storage_.load(static_cast<std::memory_order>(load_order));
- do {
- // If zero, we are done (without an increment). If not, we must do a CAS
- // to maintain the contract: do not increment the counter if it is already
- // zero
- if (count == 0) {
- return false;
- }
- } while (!CompareExchangeWeak(&count, count + 1, MemoryOrder::ACQ_REL,
- load_order));
- return true;
- }
-
- private:
- std::atomic<T> storage_;
-};
-
-} // namespace grpc_core
-
+};
+
+template <typename T>
+class Atomic {
+ public:
+ explicit Atomic(T val = T()) : storage_(val) {}
+
+ T Load(MemoryOrder order) const {
+ return storage_.load(static_cast<std::memory_order>(order));
+ }
+
+ void Store(T val, MemoryOrder order) {
+ storage_.store(val, static_cast<std::memory_order>(order));
+ }
+
+ T Exchange(T desired, MemoryOrder order) {
+ return storage_.exchange(desired, static_cast<std::memory_order>(order));
+ }
+
+ bool CompareExchangeWeak(T* expected, T desired, MemoryOrder success,
+ MemoryOrder failure) {
+ return GPR_ATM_INC_CAS_THEN(storage_.compare_exchange_weak(
+ *expected, desired, static_cast<std::memory_order>(success),
+ static_cast<std::memory_order>(failure)));
+ }
+
+ bool CompareExchangeStrong(T* expected, T desired, MemoryOrder success,
+ MemoryOrder failure) {
+ return GPR_ATM_INC_CAS_THEN(storage_.compare_exchange_strong(
+ *expected, desired, static_cast<std::memory_order>(success),
+ static_cast<std::memory_order>(failure)));
+ }
+
+ template <typename Arg>
+ T FetchAdd(Arg arg, MemoryOrder order = MemoryOrder::SEQ_CST) {
+ return GPR_ATM_INC_ADD_THEN(storage_.fetch_add(
+ static_cast<Arg>(arg), static_cast<std::memory_order>(order)));
+ }
+
+ template <typename Arg>
+ T FetchSub(Arg arg, MemoryOrder order = MemoryOrder::SEQ_CST) {
+ return GPR_ATM_INC_ADD_THEN(storage_.fetch_sub(
+ static_cast<Arg>(arg), static_cast<std::memory_order>(order)));
+ }
+
+ // Atomically increment a counter only if the counter value is not zero.
+ // Returns true if increment took place; false if counter is zero.
+ bool IncrementIfNonzero(MemoryOrder load_order = MemoryOrder::ACQUIRE) {
+ T count = storage_.load(static_cast<std::memory_order>(load_order));
+ do {
+ // If zero, we are done (without an increment). If not, we must do a CAS
+ // to maintain the contract: do not increment the counter if it is already
+ // zero
+ if (count == 0) {
+ return false;
+ }
+ } while (!CompareExchangeWeak(&count, count + 1, MemoryOrder::ACQ_REL,
+ load_order));
+ return true;
+ }
+
+ private:
+ std::atomic<T> storage_;
+};
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_GPRPP_ATOMIC_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/debug_location.h b/contrib/libs/grpc/src/core/lib/gprpp/debug_location.h
index a96e06e235..d605cd83d0 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/debug_location.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/debug_location.h
@@ -25,9 +25,9 @@ namespace grpc_core {
// No-op for non-debug builds.
// Callers can use the DEBUG_LOCATION macro in either case.
#ifndef NDEBUG
-// TODO(roth): See if there's a way to automatically populate this,
+// TODO(roth): See if there's a way to automatically populate this,
// similarly to how y_absl::SourceLocation::current() works, so that
-// callers don't need to explicitly pass DEBUG_LOCATION anywhere.
+// callers don't need to explicitly pass DEBUG_LOCATION anywhere.
class DebugLocation {
public:
DebugLocation(const char* file, int line) : file_(file), line_(line) {}
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/fork.cc b/contrib/libs/grpc/src/core/lib/gprpp/fork.cc
index 51d1c80e67..83daa73971 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/fork.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/fork.cc
@@ -27,7 +27,7 @@
#include <grpc/support/time.h>
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/memory.h"
/*
@@ -35,16 +35,16 @@
* AROUND VERY SPECIFIC USE CASES.
*/
-#ifdef GRPC_ENABLE_FORK_SUPPORT
-#define GRPC_ENABLE_FORK_SUPPORT_DEFAULT true
-#else
-#define GRPC_ENABLE_FORK_SUPPORT_DEFAULT false
-#endif // GRPC_ENABLE_FORK_SUPPORT
-
-GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_enable_fork_support,
- GRPC_ENABLE_FORK_SUPPORT_DEFAULT,
- "Enable folk support");
-
+#ifdef GRPC_ENABLE_FORK_SUPPORT
+#define GRPC_ENABLE_FORK_SUPPORT_DEFAULT true
+#else
+#define GRPC_ENABLE_FORK_SUPPORT_DEFAULT false
+#endif // GRPC_ENABLE_FORK_SUPPORT
+
+GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_enable_fork_support,
+ GRPC_ENABLE_FORK_SUPPORT_DEFAULT,
+ "Enable folk support");
+
namespace grpc_core {
namespace internal {
// The exec_ctx_count has 2 modes, blocked and unblocked.
@@ -168,33 +168,33 @@ class ThreadState {
void Fork::GlobalInit() {
if (!override_enabled_) {
- support_enabled_.Store(GPR_GLOBAL_CONFIG_GET(grpc_enable_fork_support),
- MemoryOrder::RELAXED);
+ support_enabled_.Store(GPR_GLOBAL_CONFIG_GET(grpc_enable_fork_support),
+ MemoryOrder::RELAXED);
}
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
- exec_ctx_state_ = new internal::ExecCtxState();
- thread_state_ = new internal::ThreadState();
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ exec_ctx_state_ = new internal::ExecCtxState();
+ thread_state_ = new internal::ThreadState();
}
}
void Fork::GlobalShutdown() {
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
- delete exec_ctx_state_;
- delete thread_state_;
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ delete exec_ctx_state_;
+ delete thread_state_;
}
}
-bool Fork::Enabled() { return support_enabled_.Load(MemoryOrder::RELAXED); }
+bool Fork::Enabled() { return support_enabled_.Load(MemoryOrder::RELAXED); }
// Testing Only
void Fork::Enable(bool enable) {
override_enabled_ = true;
- support_enabled_.Store(enable, MemoryOrder::RELAXED);
+ support_enabled_.Store(enable, MemoryOrder::RELAXED);
}
-void Fork::DoIncExecCtxCount() { exec_ctx_state_->IncExecCtxCount(); }
+void Fork::DoIncExecCtxCount() { exec_ctx_state_->IncExecCtxCount(); }
-void Fork::DoDecExecCtxCount() { exec_ctx_state_->DecExecCtxCount(); }
+void Fork::DoDecExecCtxCount() { exec_ctx_state_->DecExecCtxCount(); }
void Fork::SetResetChildPollingEngineFunc(
Fork::child_postfork_func reset_child_polling_engine) {
@@ -205,38 +205,38 @@ Fork::child_postfork_func Fork::GetResetChildPollingEngineFunc() {
}
bool Fork::BlockExecCtx() {
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
return exec_ctx_state_->BlockExecCtx();
}
return false;
}
void Fork::AllowExecCtx() {
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
exec_ctx_state_->AllowExecCtx();
}
}
void Fork::IncThreadCount() {
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
thread_state_->IncThreadCount();
}
}
void Fork::DecThreadCount() {
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
thread_state_->DecThreadCount();
}
}
void Fork::AwaitThreads() {
- if (support_enabled_.Load(MemoryOrder::RELAXED)) {
+ if (support_enabled_.Load(MemoryOrder::RELAXED)) {
thread_state_->AwaitThreads();
}
}
internal::ExecCtxState* Fork::exec_ctx_state_ = nullptr;
internal::ThreadState* Fork::thread_state_ = nullptr;
-Atomic<bool> Fork::support_enabled_(false);
+Atomic<bool> Fork::support_enabled_(false);
bool Fork::override_enabled_ = false;
Fork::child_postfork_func Fork::reset_child_polling_engine_ = nullptr;
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/fork.h b/contrib/libs/grpc/src/core/lib/gprpp/fork.h
index 3601d7ca92..2240b178f8 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/fork.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/fork.h
@@ -19,10 +19,10 @@
#ifndef GRPC_CORE_LIB_GPRPP_FORK_H
#define GRPC_CORE_LIB_GPRPP_FORK_H
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/atomic.h"
-
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/atomic.h"
+
/*
* NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
* AROUND VERY SPECIFIC USE CASES.
@@ -47,18 +47,18 @@ class Fork {
// Increment the count of active ExecCtxs.
// Will block until a pending fork is complete if one is in progress.
- static void IncExecCtxCount() {
- if (GPR_UNLIKELY(support_enabled_.Load(MemoryOrder::RELAXED))) {
- DoIncExecCtxCount();
- }
- }
+ static void IncExecCtxCount() {
+ if (GPR_UNLIKELY(support_enabled_.Load(MemoryOrder::RELAXED))) {
+ DoIncExecCtxCount();
+ }
+ }
// Decrement the count of active ExecCtxs
- static void DecExecCtxCount() {
- if (GPR_UNLIKELY(support_enabled_.Load(MemoryOrder::RELAXED))) {
- DoDecExecCtxCount();
- }
- }
+ static void DecExecCtxCount() {
+ if (GPR_UNLIKELY(support_enabled_.Load(MemoryOrder::RELAXED))) {
+ DoDecExecCtxCount();
+ }
+ }
// Provide a function that will be invoked in the child's postfork handler to
// reset the polling engine's internal state.
@@ -88,12 +88,12 @@ class Fork {
static void Enable(bool enable);
private:
- static void DoIncExecCtxCount();
- static void DoDecExecCtxCount();
-
+ static void DoIncExecCtxCount();
+ static void DoDecExecCtxCount();
+
static internal::ExecCtxState* exec_ctx_state_;
static internal::ThreadState* thread_state_;
- static grpc_core::Atomic<bool> support_enabled_;
+ static grpc_core::Atomic<bool> support_enabled_;
static bool override_enabled_;
static child_postfork_func reset_child_polling_engine_;
};
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/global_config.h b/contrib/libs/grpc/src/core/lib/gprpp/global_config.h
index ed986b8e04..c3eb9fb92f 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/global_config.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/global_config.h
@@ -1,96 +1,96 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H
-#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdint.h>
-
-// --------------------------------------------------------------------
-// How to use global configuration variables:
-//
-// Defining config variables of a specified type:
-// GPR_GLOBAL_CONFIG_DEFINE_*TYPE*(name, default_value, help);
-//
-// Supported TYPEs: BOOL, INT32, STRING
-//
-// It's recommended to use lowercase letters for 'name' like
-// regular variables. The builtin configuration system uses
-// environment variable and the name is converted to uppercase
-// when looking up the value. For example,
-// GPR_GLOBAL_CONFIG_DEFINE(grpc_latency) looks up the value with the
-// name, "GRPC_LATENCY".
-//
-// The variable initially has the specified 'default_value'
-// which must be an expression convertible to 'Type'.
-// 'default_value' may be evaluated 0 or more times,
-// and at an unspecified time; keep it
-// simple and usually free of side-effects.
-//
-// GPR_GLOBAL_CONFIG_DEFINE_*TYPE* should not be called in a C++ header.
-// It should be called at the top-level (outside any namespaces)
-// in a .cc file.
-//
-// Getting the variables:
-// GPR_GLOBAL_CONFIG_GET(name)
-//
-// If error happens during getting variables, error messages will
-// be logged and default value will be returned.
-//
-// Setting the variables with new value:
-// GPR_GLOBAL_CONFIG_SET(name, new_value)
-//
-// Declaring config variables for other modules to access:
-// GPR_GLOBAL_CONFIG_DECLARE_*TYPE*(name)
-//
-// * Caveat for setting global configs at runtime
-//
-// Setting global configs at runtime multiple times is safe but it doesn't
-// mean that it will have a valid effect on the module depending configs.
-// In unit tests, it may be unpredictable to set different global configs
-// between test cases because grpc init and shutdown can ignore changes.
-// It's considered safe to set global configs before the first call to
-// grpc_init().
-
-// --------------------------------------------------------------------
-// How to customize the global configuration system:
-//
-// How to read and write configuration value can be customized.
-// Builtin system uses environment variables but it can be extended to
-// support command-line flag, file, etc.
-//
-// To customize it, following macros should be redefined.
-//
-// GPR_GLOBAL_CONFIG_DEFINE_BOOL
-// GPR_GLOBAL_CONFIG_DEFINE_INT32
-// GPR_GLOBAL_CONFIG_DEFINE_STRING
-//
-// These macros should define functions for getting and setting variable.
-// For example, GPR_GLOBAL_CONFIG_DEFINE_BOOL(test, ...) would define two
-// functions.
-//
-// bool gpr_global_config_get_test();
-// void gpr_global_config_set_test(bool value);
-
-#include "src/core/lib/gprpp/global_config_env.h"
-
-#include "src/core/lib/gprpp/global_config_custom.h"
-
-#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H
+#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdint.h>
+
+// --------------------------------------------------------------------
+// How to use global configuration variables:
+//
+// Defining config variables of a specified type:
+// GPR_GLOBAL_CONFIG_DEFINE_*TYPE*(name, default_value, help);
+//
+// Supported TYPEs: BOOL, INT32, STRING
+//
+// It's recommended to use lowercase letters for 'name' like
+// regular variables. The builtin configuration system uses
+// environment variable and the name is converted to uppercase
+// when looking up the value. For example,
+// GPR_GLOBAL_CONFIG_DEFINE(grpc_latency) looks up the value with the
+// name, "GRPC_LATENCY".
+//
+// The variable initially has the specified 'default_value'
+// which must be an expression convertible to 'Type'.
+// 'default_value' may be evaluated 0 or more times,
+// and at an unspecified time; keep it
+// simple and usually free of side-effects.
+//
+// GPR_GLOBAL_CONFIG_DEFINE_*TYPE* should not be called in a C++ header.
+// It should be called at the top-level (outside any namespaces)
+// in a .cc file.
+//
+// Getting the variables:
+// GPR_GLOBAL_CONFIG_GET(name)
+//
+// If error happens during getting variables, error messages will
+// be logged and default value will be returned.
+//
+// Setting the variables with new value:
+// GPR_GLOBAL_CONFIG_SET(name, new_value)
+//
+// Declaring config variables for other modules to access:
+// GPR_GLOBAL_CONFIG_DECLARE_*TYPE*(name)
+//
+// * Caveat for setting global configs at runtime
+//
+// Setting global configs at runtime multiple times is safe but it doesn't
+// mean that it will have a valid effect on the module depending configs.
+// In unit tests, it may be unpredictable to set different global configs
+// between test cases because grpc init and shutdown can ignore changes.
+// It's considered safe to set global configs before the first call to
+// grpc_init().
+
+// --------------------------------------------------------------------
+// How to customize the global configuration system:
+//
+// How to read and write configuration value can be customized.
+// Builtin system uses environment variables but it can be extended to
+// support command-line flag, file, etc.
+//
+// To customize it, following macros should be redefined.
+//
+// GPR_GLOBAL_CONFIG_DEFINE_BOOL
+// GPR_GLOBAL_CONFIG_DEFINE_INT32
+// GPR_GLOBAL_CONFIG_DEFINE_STRING
+//
+// These macros should define functions for getting and setting variable.
+// For example, GPR_GLOBAL_CONFIG_DEFINE_BOOL(test, ...) would define two
+// functions.
+//
+// bool gpr_global_config_get_test();
+// void gpr_global_config_set_test(bool value);
+
+#include "src/core/lib/gprpp/global_config_env.h"
+
+#include "src/core/lib/gprpp/global_config_custom.h"
+
+#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/global_config_custom.h b/contrib/libs/grpc/src/core/lib/gprpp/global_config_custom.h
index 175677e07c..9b00e928bd 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/global_config_custom.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/global_config_custom.h
@@ -1,29 +1,29 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H
-#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H
-
-// This is a placeholder for custom global configuration implementation.
-// To use the custom one, please define following macros here.
-//
-// GPR_GLOBAL_CONFIG_DEFINE_BOOL
-// GPR_GLOBAL_CONFIG_DEFINE_INT32
-// GPR_GLOBAL_CONFIG_DEFINE_STRING
-
-#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H
+#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H
+
+// This is a placeholder for custom global configuration implementation.
+// To use the custom one, please define following macros here.
+//
+// GPR_GLOBAL_CONFIG_DEFINE_BOOL
+// GPR_GLOBAL_CONFIG_DEFINE_INT32
+// GPR_GLOBAL_CONFIG_DEFINE_STRING
+
+#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.cc b/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.cc
index 72e3760661..20a20e7549 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.cc
@@ -1,137 +1,137 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/global_config_env.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/gpr/string.h"
-
-#include <ctype.h>
-#include <string.h>
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/global_config_env.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/gpr/string.h"
+
+#include <ctype.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-namespace grpc_core {
-
-namespace {
-
-void DefaultGlobalConfigEnvErrorFunction(const char* error_message) {
- gpr_log(GPR_ERROR, "%s", error_message);
-}
-
-GlobalConfigEnvErrorFunctionType g_global_config_env_error_func =
- DefaultGlobalConfigEnvErrorFunction;
-
-void LogParsingError(const char* name, const char* value) {
+namespace grpc_core {
+
+namespace {
+
+void DefaultGlobalConfigEnvErrorFunction(const char* error_message) {
+ gpr_log(GPR_ERROR, "%s", error_message);
+}
+
+GlobalConfigEnvErrorFunctionType g_global_config_env_error_func =
+ DefaultGlobalConfigEnvErrorFunction;
+
+void LogParsingError(const char* name, const char* value) {
TString error_message = y_absl::StrFormat(
"Illegal value '%s' specified for environment variable '%s'", value,
name);
(*g_global_config_env_error_func)(error_message.c_str());
-}
-
-} // namespace
-
-void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func) {
- g_global_config_env_error_func = func;
-}
-
-grpc_core::UniquePtr<char> GlobalConfigEnv::GetValue() {
- return grpc_core::UniquePtr<char>(gpr_getenv(GetName()));
-}
-
-void GlobalConfigEnv::SetValue(const char* value) {
- gpr_setenv(GetName(), value);
-}
-
-void GlobalConfigEnv::Unset() { gpr_unsetenv(GetName()); }
-
-char* GlobalConfigEnv::GetName() {
- // This makes sure that name_ is in a canonical form having uppercase
- // letters. This is okay to be called serveral times.
- for (char* c = name_; *c != 0; ++c) {
- *c = toupper(*c);
- }
- return name_;
-}
-static_assert(std::is_trivially_destructible<GlobalConfigEnvBool>::value,
- "GlobalConfigEnvBool needs to be trivially destructible.");
-
-bool GlobalConfigEnvBool::Get() {
- grpc_core::UniquePtr<char> str = GetValue();
- if (str == nullptr) {
- return default_value_;
- }
- // parsing given value string.
- bool result = false;
- if (!gpr_parse_bool_value(str.get(), &result)) {
- LogParsingError(GetName(), str.get());
- result = default_value_;
- }
- return result;
-}
-
-void GlobalConfigEnvBool::Set(bool value) {
- SetValue(value ? "true" : "false");
-}
-
-static_assert(std::is_trivially_destructible<GlobalConfigEnvInt32>::value,
- "GlobalConfigEnvInt32 needs to be trivially destructible.");
-
-int32_t GlobalConfigEnvInt32::Get() {
- grpc_core::UniquePtr<char> str = GetValue();
- if (str == nullptr) {
- return default_value_;
- }
- // parsing given value string.
- char* end = str.get();
- long result = strtol(str.get(), &end, 10);
- if (*end != 0) {
- LogParsingError(GetName(), str.get());
- result = default_value_;
- }
- return static_cast<int32_t>(result);
-}
-
-void GlobalConfigEnvInt32::Set(int32_t value) {
- char buffer[GPR_LTOA_MIN_BUFSIZE];
- gpr_ltoa(value, buffer);
- SetValue(buffer);
-}
-
-static_assert(std::is_trivially_destructible<GlobalConfigEnvString>::value,
- "GlobalConfigEnvString needs to be trivially destructible.");
-
-grpc_core::UniquePtr<char> GlobalConfigEnvString::Get() {
- grpc_core::UniquePtr<char> str = GetValue();
- if (str == nullptr) {
- return grpc_core::UniquePtr<char>(gpr_strdup(default_value_));
- }
- return str;
-}
-
-void GlobalConfigEnvString::Set(const char* value) { SetValue(value); }
-
-} // namespace grpc_core
+}
+
+} // namespace
+
+void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func) {
+ g_global_config_env_error_func = func;
+}
+
+grpc_core::UniquePtr<char> GlobalConfigEnv::GetValue() {
+ return grpc_core::UniquePtr<char>(gpr_getenv(GetName()));
+}
+
+void GlobalConfigEnv::SetValue(const char* value) {
+ gpr_setenv(GetName(), value);
+}
+
+void GlobalConfigEnv::Unset() { gpr_unsetenv(GetName()); }
+
+char* GlobalConfigEnv::GetName() {
+ // This makes sure that name_ is in a canonical form having uppercase
+ // letters. This is okay to be called serveral times.
+ for (char* c = name_; *c != 0; ++c) {
+ *c = toupper(*c);
+ }
+ return name_;
+}
+static_assert(std::is_trivially_destructible<GlobalConfigEnvBool>::value,
+ "GlobalConfigEnvBool needs to be trivially destructible.");
+
+bool GlobalConfigEnvBool::Get() {
+ grpc_core::UniquePtr<char> str = GetValue();
+ if (str == nullptr) {
+ return default_value_;
+ }
+ // parsing given value string.
+ bool result = false;
+ if (!gpr_parse_bool_value(str.get(), &result)) {
+ LogParsingError(GetName(), str.get());
+ result = default_value_;
+ }
+ return result;
+}
+
+void GlobalConfigEnvBool::Set(bool value) {
+ SetValue(value ? "true" : "false");
+}
+
+static_assert(std::is_trivially_destructible<GlobalConfigEnvInt32>::value,
+ "GlobalConfigEnvInt32 needs to be trivially destructible.");
+
+int32_t GlobalConfigEnvInt32::Get() {
+ grpc_core::UniquePtr<char> str = GetValue();
+ if (str == nullptr) {
+ return default_value_;
+ }
+ // parsing given value string.
+ char* end = str.get();
+ long result = strtol(str.get(), &end, 10);
+ if (*end != 0) {
+ LogParsingError(GetName(), str.get());
+ result = default_value_;
+ }
+ return static_cast<int32_t>(result);
+}
+
+void GlobalConfigEnvInt32::Set(int32_t value) {
+ char buffer[GPR_LTOA_MIN_BUFSIZE];
+ gpr_ltoa(value, buffer);
+ SetValue(buffer);
+}
+
+static_assert(std::is_trivially_destructible<GlobalConfigEnvString>::value,
+ "GlobalConfigEnvString needs to be trivially destructible.");
+
+grpc_core::UniquePtr<char> GlobalConfigEnvString::Get() {
+ grpc_core::UniquePtr<char> str = GetValue();
+ if (str == nullptr) {
+ return grpc_core::UniquePtr<char>(gpr_strdup(default_value_));
+ }
+ return str;
+}
+
+void GlobalConfigEnvString::Set(const char* value) { SetValue(value); }
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.h b/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.h
index b6d7d574ec..05d7f85fbe 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/global_config_env.h
@@ -1,131 +1,131 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H
-#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/global_config_generic.h"
-#include "src/core/lib/gprpp/memory.h"
-
-namespace grpc_core {
-
-typedef void (*GlobalConfigEnvErrorFunctionType)(const char* error_message);
-
-/*
- * Set global_config_env_error_function which is called when config system
- * encounters errors such as parsing error. What the default function does
- * is logging error message.
- */
-void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func);
-
-// Base class for all classes to access environment variables.
-class GlobalConfigEnv {
- protected:
- // `name` should be writable and alive after constructor is called.
- constexpr explicit GlobalConfigEnv(char* name) : name_(name) {}
-
- public:
- // Returns the value of `name` variable.
- grpc_core::UniquePtr<char> GetValue();
-
- // Sets the value of `name` variable.
- void SetValue(const char* value);
-
- // Unsets `name` variable.
- void Unset();
-
- protected:
- char* GetName();
-
- private:
- char* name_;
-};
-
-class GlobalConfigEnvBool : public GlobalConfigEnv {
- public:
- constexpr GlobalConfigEnvBool(char* name, bool default_value)
- : GlobalConfigEnv(name), default_value_(default_value) {}
-
- bool Get();
- void Set(bool value);
-
- private:
- bool default_value_;
-};
-
-class GlobalConfigEnvInt32 : public GlobalConfigEnv {
- public:
- constexpr GlobalConfigEnvInt32(char* name, int32_t default_value)
- : GlobalConfigEnv(name), default_value_(default_value) {}
-
- int32_t Get();
- void Set(int32_t value);
-
- private:
- int32_t default_value_;
-};
-
-class GlobalConfigEnvString : public GlobalConfigEnv {
- public:
- constexpr GlobalConfigEnvString(char* name, const char* default_value)
- : GlobalConfigEnv(name), default_value_(default_value) {}
-
- grpc_core::UniquePtr<char> Get();
- void Set(const char* value);
-
- private:
- const char* default_value_;
-};
-
-} // namespace grpc_core
-
-// Macros for defining global config instances using environment variables.
-// This defines a GlobalConfig*Type* instance with arguments for
-// mutable variable name and default value.
-// Mutable name (g_env_str_##name) is here for having an array
-// for the canonical name without dynamic allocation.
-// `help` argument is ignored for this implementation.
-
-#define GPR_GLOBAL_CONFIG_DEFINE_BOOL(name, default_value, help) \
- static char g_env_str_##name[] = #name; \
- static ::grpc_core::GlobalConfigEnvBool g_env_##name(g_env_str_##name, \
- default_value); \
- bool gpr_global_config_get_##name() { return g_env_##name.Get(); } \
- void gpr_global_config_set_##name(bool value) { g_env_##name.Set(value); }
-
-#define GPR_GLOBAL_CONFIG_DEFINE_INT32(name, default_value, help) \
- static char g_env_str_##name[] = #name; \
- static ::grpc_core::GlobalConfigEnvInt32 g_env_##name(g_env_str_##name, \
- default_value); \
- int32_t gpr_global_config_get_##name() { return g_env_##name.Get(); } \
- void gpr_global_config_set_##name(int32_t value) { g_env_##name.Set(value); }
-
-#define GPR_GLOBAL_CONFIG_DEFINE_STRING(name, default_value, help) \
- static char g_env_str_##name[] = #name; \
- static ::grpc_core::GlobalConfigEnvString g_env_##name(g_env_str_##name, \
- default_value); \
- ::grpc_core::UniquePtr<char> gpr_global_config_get_##name() { \
- return g_env_##name.Get(); \
- } \
- void gpr_global_config_set_##name(const char* value) { \
- g_env_##name.Set(value); \
- }
-
-#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H
+#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/global_config_generic.h"
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+
+typedef void (*GlobalConfigEnvErrorFunctionType)(const char* error_message);
+
+/*
+ * Set global_config_env_error_function which is called when config system
+ * encounters errors such as parsing error. What the default function does
+ * is logging error message.
+ */
+void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func);
+
+// Base class for all classes to access environment variables.
+class GlobalConfigEnv {
+ protected:
+ // `name` should be writable and alive after constructor is called.
+ constexpr explicit GlobalConfigEnv(char* name) : name_(name) {}
+
+ public:
+ // Returns the value of `name` variable.
+ grpc_core::UniquePtr<char> GetValue();
+
+ // Sets the value of `name` variable.
+ void SetValue(const char* value);
+
+ // Unsets `name` variable.
+ void Unset();
+
+ protected:
+ char* GetName();
+
+ private:
+ char* name_;
+};
+
+class GlobalConfigEnvBool : public GlobalConfigEnv {
+ public:
+ constexpr GlobalConfigEnvBool(char* name, bool default_value)
+ : GlobalConfigEnv(name), default_value_(default_value) {}
+
+ bool Get();
+ void Set(bool value);
+
+ private:
+ bool default_value_;
+};
+
+class GlobalConfigEnvInt32 : public GlobalConfigEnv {
+ public:
+ constexpr GlobalConfigEnvInt32(char* name, int32_t default_value)
+ : GlobalConfigEnv(name), default_value_(default_value) {}
+
+ int32_t Get();
+ void Set(int32_t value);
+
+ private:
+ int32_t default_value_;
+};
+
+class GlobalConfigEnvString : public GlobalConfigEnv {
+ public:
+ constexpr GlobalConfigEnvString(char* name, const char* default_value)
+ : GlobalConfigEnv(name), default_value_(default_value) {}
+
+ grpc_core::UniquePtr<char> Get();
+ void Set(const char* value);
+
+ private:
+ const char* default_value_;
+};
+
+} // namespace grpc_core
+
+// Macros for defining global config instances using environment variables.
+// This defines a GlobalConfig*Type* instance with arguments for
+// mutable variable name and default value.
+// Mutable name (g_env_str_##name) is here for having an array
+// for the canonical name without dynamic allocation.
+// `help` argument is ignored for this implementation.
+
+#define GPR_GLOBAL_CONFIG_DEFINE_BOOL(name, default_value, help) \
+ static char g_env_str_##name[] = #name; \
+ static ::grpc_core::GlobalConfigEnvBool g_env_##name(g_env_str_##name, \
+ default_value); \
+ bool gpr_global_config_get_##name() { return g_env_##name.Get(); } \
+ void gpr_global_config_set_##name(bool value) { g_env_##name.Set(value); }
+
+#define GPR_GLOBAL_CONFIG_DEFINE_INT32(name, default_value, help) \
+ static char g_env_str_##name[] = #name; \
+ static ::grpc_core::GlobalConfigEnvInt32 g_env_##name(g_env_str_##name, \
+ default_value); \
+ int32_t gpr_global_config_get_##name() { return g_env_##name.Get(); } \
+ void gpr_global_config_set_##name(int32_t value) { g_env_##name.Set(value); }
+
+#define GPR_GLOBAL_CONFIG_DEFINE_STRING(name, default_value, help) \
+ static char g_env_str_##name[] = #name; \
+ static ::grpc_core::GlobalConfigEnvString g_env_##name(g_env_str_##name, \
+ default_value); \
+ ::grpc_core::UniquePtr<char> gpr_global_config_get_##name() { \
+ return g_env_##name.Get(); \
+ } \
+ void gpr_global_config_set_##name(const char* value) { \
+ g_env_##name.Set(value); \
+ }
+
+#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/global_config_generic.h b/contrib/libs/grpc/src/core/lib/gprpp/global_config_generic.h
index d3e3e2a2db..07c6ada780 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/global_config_generic.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/global_config_generic.h
@@ -1,44 +1,44 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H
-#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/memory.h"
-
-#include <stdint.h>
-
-#define GPR_GLOBAL_CONFIG_GET(name) gpr_global_config_get_##name()
-
-#define GPR_GLOBAL_CONFIG_SET(name, value) gpr_global_config_set_##name(value)
-
-#define GPR_GLOBAL_CONFIG_DECLARE_BOOL(name) \
- extern bool gpr_global_config_get_##name(); \
- extern void gpr_global_config_set_##name(bool value)
-
-#define GPR_GLOBAL_CONFIG_DECLARE_INT32(name) \
- extern int32_t gpr_global_config_get_##name(); \
- extern void gpr_global_config_set_##name(int32_t value)
-
-#define GPR_GLOBAL_CONFIG_DECLARE_STRING(name) \
- extern grpc_core::UniquePtr<char> gpr_global_config_get_##name(); \
- extern void gpr_global_config_set_##name(const char* value)
-
-#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H
+#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/memory.h"
+
+#include <stdint.h>
+
+#define GPR_GLOBAL_CONFIG_GET(name) gpr_global_config_get_##name()
+
+#define GPR_GLOBAL_CONFIG_SET(name, value) gpr_global_config_set_##name(value)
+
+#define GPR_GLOBAL_CONFIG_DECLARE_BOOL(name) \
+ extern bool gpr_global_config_get_##name(); \
+ extern void gpr_global_config_set_##name(bool value)
+
+#define GPR_GLOBAL_CONFIG_DECLARE_INT32(name) \
+ extern int32_t gpr_global_config_get_##name(); \
+ extern void gpr_global_config_set_##name(int32_t value)
+
+#define GPR_GLOBAL_CONFIG_DECLARE_STRING(name) \
+ extern grpc_core::UniquePtr<char> gpr_global_config_get_##name(); \
+ extern void gpr_global_config_set_##name(const char* value)
+
+#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/host_port.cc b/contrib/libs/grpc/src/core/lib/gprpp/host_port.cc
index e9db87f938..f9836b3c17 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/host_port.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/host_port.cc
@@ -1,112 +1,112 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/host_port.h"
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/host_port.h"
+
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/string_view.h"
-
-#include <grpc/support/log.h>
-
+
+#include <grpc/support/log.h>
+
namespace grpc_core {
-
+
TString JoinHostPort(y_absl::string_view host, int port) {
if (!host.empty() && host[0] != '[' && host.rfind(':') != host.npos) {
// IPv6 literals must be enclosed in brackets.
return y_absl::StrFormat("[%s]:%d", host, port);
- }
+ }
// Ordinary non-bracketed host:port.
return y_absl::StrFormat("%s:%d", host, port);
-}
-
-namespace {
+}
+
+namespace {
bool DoSplitHostPort(y_absl::string_view name, y_absl::string_view* host,
y_absl::string_view* port, bool* has_port) {
- *has_port = false;
+ *has_port = false;
if (!name.empty() && name[0] == '[') {
- /* Parse a bracketed host, typically an IPv6 literal. */
- const size_t rbracket = name.find(']', 1);
+ /* Parse a bracketed host, typically an IPv6 literal. */
+ const size_t rbracket = name.find(']', 1);
if (rbracket == y_absl::string_view::npos) {
- /* Unmatched [ */
- return false;
- }
- if (rbracket == name.size() - 1) {
- /* ]<end> */
+ /* Unmatched [ */
+ return false;
+ }
+ if (rbracket == name.size() - 1) {
+ /* ]<end> */
*port = y_absl::string_view();
- } else if (name[rbracket + 1] == ':') {
- /* ]:<port?> */
- *port = name.substr(rbracket + 2, name.size() - rbracket - 2);
- *has_port = true;
- } else {
- /* ]<invalid> */
- return false;
- }
- *host = name.substr(1, rbracket - 1);
+ } else if (name[rbracket + 1] == ':') {
+ /* ]:<port?> */
+ *port = name.substr(rbracket + 2, name.size() - rbracket - 2);
+ *has_port = true;
+ } else {
+ /* ]<invalid> */
+ return false;
+ }
+ *host = name.substr(1, rbracket - 1);
if (host->find(':') == y_absl::string_view::npos) {
- /* Require all bracketed hosts to contain a colon, because a hostname or
- IPv4 address should never use brackets. */
+ /* Require all bracketed hosts to contain a colon, because a hostname or
+ IPv4 address should never use brackets. */
*host = y_absl::string_view();
- return false;
- }
- } else {
- size_t colon = name.find(':');
+ return false;
+ }
+ } else {
+ size_t colon = name.find(':');
if (colon != y_absl::string_view::npos &&
name.find(':', colon + 1) == y_absl::string_view::npos) {
- /* Exactly 1 colon. Split into host:port. */
- *host = name.substr(0, colon);
- *port = name.substr(colon + 1, name.size() - colon - 1);
- *has_port = true;
- } else {
- /* 0 or 2+ colons. Bare hostname or IPv6 litearal. */
- *host = name;
+ /* Exactly 1 colon. Split into host:port. */
+ *host = name.substr(0, colon);
+ *port = name.substr(colon + 1, name.size() - colon - 1);
+ *has_port = true;
+ } else {
+ /* 0 or 2+ colons. Bare hostname or IPv6 litearal. */
+ *host = name;
*port = y_absl::string_view();
- }
- }
- return true;
-}
-} // namespace
-
+ }
+ }
+ return true;
+}
+} // namespace
+
bool SplitHostPort(y_absl::string_view name, y_absl::string_view* host,
y_absl::string_view* port) {
- bool unused;
- return DoSplitHostPort(name, host, port, &unused);
-}
-
+ bool unused;
+ return DoSplitHostPort(name, host, port, &unused);
+}
+
bool SplitHostPort(y_absl::string_view name, TString* host,
TString* port) {
GPR_DEBUG_ASSERT(host != nullptr && host->empty());
GPR_DEBUG_ASSERT(port != nullptr && port->empty());
y_absl::string_view host_view;
y_absl::string_view port_view;
- bool has_port;
- const bool ret = DoSplitHostPort(name, &host_view, &port_view, &has_port);
- if (ret) {
- // We always set the host, but port is set only when DoSplitHostPort find a
- // port in the string, to remain backward compatible with the old
- // gpr_split_host_port API.
+ bool has_port;
+ const bool ret = DoSplitHostPort(name, &host_view, &port_view, &has_port);
+ if (ret) {
+ // We always set the host, but port is set only when DoSplitHostPort find a
+ // port in the string, to remain backward compatible with the old
+ // gpr_split_host_port API.
*host = TString(host_view);
- if (has_port) {
+ if (has_port) {
*port = TString(port_view);
- }
- }
- return ret;
-}
+ }
+ }
+ return ret;
+}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/host_port.h b/contrib/libs/grpc/src/core/lib/gprpp/host_port.h
index 4591b85817..1a0e06fc1c 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/host_port.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/host_port.h
@@ -1,56 +1,56 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_HOST_PORT_H
-#define GRPC_CORE_LIB_GPRPP_HOST_PORT_H
-
-#include <grpc/support/port_platform.h>
-
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_HOST_PORT_H
+#define GRPC_CORE_LIB_GPRPP_HOST_PORT_H
+
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
-
+
#include "y_absl/strings/string_view.h"
-namespace grpc_core {
-
+namespace grpc_core {
+
// Given a host and port, creates a newly-allocated string of the form
// "host:port" or "[ho:st]:port", depending on whether the host contains colons
// like an IPv6 literal. If the host is already bracketed, then additional
// brackets will not be added.
TString JoinHostPort(y_absl::string_view host, int port);
-
-/** Given a name in the form "host:port" or "[ho:st]:port", split into hostname
- and port number.
-
- There are two variants of this method:
+
+/** Given a name in the form "host:port" or "[ho:st]:port", split into hostname
+ and port number.
+
+ There are two variants of this method:
1) y_absl::string_view output: port and host are returned as views on name.
2) TString output: port and host are copied into newly allocated strings.
-
- Prefer variant (1) over (2), because no allocation or copy is performed in
- variant (1). Use (2) only when interacting with C API that mandate
- null-terminated strings.
-
- Return true on success, false on failure. Guarantees *host and *port are
- cleared on failure. */
+
+ Prefer variant (1) over (2), because no allocation or copy is performed in
+ variant (1). Use (2) only when interacting with C API that mandate
+ null-terminated strings.
+
+ Return true on success, false on failure. Guarantees *host and *port are
+ cleared on failure. */
bool SplitHostPort(y_absl::string_view name, y_absl::string_view* host,
y_absl::string_view* port);
bool SplitHostPort(y_absl::string_view name, TString* host,
TString* port);
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_HOST_PORT_H */
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_HOST_PORT_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/map.h b/contrib/libs/grpc/src/core/lib/gprpp/map.h
index 741b0b1ed5..97c5f40f95 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/map.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/map.h
@@ -1,53 +1,53 @@
-/*
- *
- * Copyright 2017 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_MAP_H
-#define GRPC_CORE_LIB_GPRPP_MAP_H
-
-#include <grpc/support/port_platform.h>
-
-#include <string.h>
-
-#include <map>
-
+/*
+ *
+ * Copyright 2017 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_MAP_H
+#define GRPC_CORE_LIB_GPRPP_MAP_H
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
+
+#include <map>
+
#include "y_absl/strings/string_view.h"
-
+
#include "src/core/lib/gprpp/memory.h"
-namespace grpc_core {
-
-struct StringLess {
- bool operator()(const char* a, const char* b) const {
- return strcmp(a, b) < 0;
- }
- bool operator()(const grpc_core::UniquePtr<char>& a,
- const grpc_core::UniquePtr<char>& b) const {
- return strcmp(a.get(), b.get()) < 0;
- }
+namespace grpc_core {
+
+struct StringLess {
+ bool operator()(const char* a, const char* b) const {
+ return strcmp(a, b) < 0;
+ }
+ bool operator()(const grpc_core::UniquePtr<char>& a,
+ const grpc_core::UniquePtr<char>& b) const {
+ return strcmp(a.get(), b.get()) < 0;
+ }
bool operator()(const y_absl::string_view& a,
const y_absl::string_view& b) const {
- const size_t min_size = std::min(a.size(), b.size());
- int c = strncmp(a.data(), b.data(), min_size);
- if (c != 0) return c < 0;
- return a.size() < b.size();
- }
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_MAP_H */
+ const size_t min_size = std::min(a.size(), b.size());
+ int c = strncmp(a.data(), b.data(), min_size);
+ if (c != 0) return c < 0;
+ return a.size() < b.size();
+ }
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_MAP_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/memory.h b/contrib/libs/grpc/src/core/lib/gprpp/memory.h
index becf273510..af1095e7b6 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/memory.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/memory.h
@@ -22,7 +22,7 @@
#include <grpc/support/port_platform.h>
#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
+#include <grpc/support/log.h>
#include <limits>
#include <memory>
@@ -32,19 +32,19 @@
namespace grpc_core {
-class DefaultDeleteChar {
+class DefaultDeleteChar {
public:
- void operator()(char* p) {
- if (p == nullptr) return;
- gpr_free(p);
- }
+ void operator()(char* p) {
+ if (p == nullptr) return;
+ gpr_free(p);
+ }
};
-// UniquePtr<T> is only allowed for char and UniquePtr<char> is deprecated
+// UniquePtr<T> is only allowed for char and UniquePtr<char> is deprecated
// in favor of TString. UniquePtr<char> is equivalent std::unique_ptr
-// except that it uses gpr_free for deleter.
-template <typename T>
-using UniquePtr = std::unique_ptr<T, DefaultDeleteChar>;
+// except that it uses gpr_free for deleter.
+template <typename T>
+using UniquePtr = std::unique_ptr<T, DefaultDeleteChar>;
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/mpscq.cc b/contrib/libs/grpc/src/core/lib/gprpp/mpscq.cc
index 2bf9981ee2..3f2cde617a 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/mpscq.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/mpscq.cc
@@ -1,108 +1,108 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/mpscq.h"
-
-namespace grpc_core {
-
-//
-// MultiProducerSingleConsumerQueue
-//
-
-bool MultiProducerSingleConsumerQueue::Push(Node* node) {
- node->next.Store(nullptr, MemoryOrder::RELAXED);
- Node* prev = head_.Exchange(node, MemoryOrder::ACQ_REL);
- prev->next.Store(node, MemoryOrder::RELEASE);
- return prev == &stub_;
-}
-
-MultiProducerSingleConsumerQueue::Node*
-MultiProducerSingleConsumerQueue::Pop() {
- bool empty;
- return PopAndCheckEnd(&empty);
-}
-
-MultiProducerSingleConsumerQueue::Node*
-MultiProducerSingleConsumerQueue::PopAndCheckEnd(bool* empty) {
- Node* tail = tail_;
- Node* next = tail_->next.Load(MemoryOrder::ACQUIRE);
- if (tail == &stub_) {
- // indicates the list is actually (ephemerally) empty
- if (next == nullptr) {
- *empty = true;
- return nullptr;
- }
- tail_ = next;
- tail = next;
- next = tail->next.Load(MemoryOrder::ACQUIRE);
- }
- if (next != nullptr) {
- *empty = false;
- tail_ = next;
- return tail;
- }
- Node* head = head_.Load(MemoryOrder::ACQUIRE);
- if (tail != head) {
- *empty = false;
- // indicates a retry is in order: we're still adding
- return nullptr;
- }
- Push(&stub_);
- next = tail->next.Load(MemoryOrder::ACQUIRE);
- if (next != nullptr) {
- *empty = false;
- tail_ = next;
- return tail;
- }
- // indicates a retry is in order: we're still adding
- *empty = false;
- return nullptr;
-}
-
-//
-// LockedMultiProducerSingleConsumerQueue
-//
-
-bool LockedMultiProducerSingleConsumerQueue::Push(Node* node) {
- return queue_.Push(node);
-}
-
-LockedMultiProducerSingleConsumerQueue::Node*
-LockedMultiProducerSingleConsumerQueue::TryPop() {
- if (gpr_mu_trylock(mu_.get())) {
- Node* node = queue_.Pop();
- gpr_mu_unlock(mu_.get());
- return node;
- }
- return nullptr;
-}
-
-LockedMultiProducerSingleConsumerQueue::Node*
-LockedMultiProducerSingleConsumerQueue::Pop() {
- MutexLock lock(&mu_);
- bool empty = false;
- Node* node;
- do {
- node = queue_.PopAndCheckEnd(&empty);
- } while (node == nullptr && !empty);
- return node;
-}
-
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/mpscq.h"
+
+namespace grpc_core {
+
+//
+// MultiProducerSingleConsumerQueue
+//
+
+bool MultiProducerSingleConsumerQueue::Push(Node* node) {
+ node->next.Store(nullptr, MemoryOrder::RELAXED);
+ Node* prev = head_.Exchange(node, MemoryOrder::ACQ_REL);
+ prev->next.Store(node, MemoryOrder::RELEASE);
+ return prev == &stub_;
+}
+
+MultiProducerSingleConsumerQueue::Node*
+MultiProducerSingleConsumerQueue::Pop() {
+ bool empty;
+ return PopAndCheckEnd(&empty);
+}
+
+MultiProducerSingleConsumerQueue::Node*
+MultiProducerSingleConsumerQueue::PopAndCheckEnd(bool* empty) {
+ Node* tail = tail_;
+ Node* next = tail_->next.Load(MemoryOrder::ACQUIRE);
+ if (tail == &stub_) {
+ // indicates the list is actually (ephemerally) empty
+ if (next == nullptr) {
+ *empty = true;
+ return nullptr;
+ }
+ tail_ = next;
+ tail = next;
+ next = tail->next.Load(MemoryOrder::ACQUIRE);
+ }
+ if (next != nullptr) {
+ *empty = false;
+ tail_ = next;
+ return tail;
+ }
+ Node* head = head_.Load(MemoryOrder::ACQUIRE);
+ if (tail != head) {
+ *empty = false;
+ // indicates a retry is in order: we're still adding
+ return nullptr;
+ }
+ Push(&stub_);
+ next = tail->next.Load(MemoryOrder::ACQUIRE);
+ if (next != nullptr) {
+ *empty = false;
+ tail_ = next;
+ return tail;
+ }
+ // indicates a retry is in order: we're still adding
+ *empty = false;
+ return nullptr;
+}
+
+//
+// LockedMultiProducerSingleConsumerQueue
+//
+
+bool LockedMultiProducerSingleConsumerQueue::Push(Node* node) {
+ return queue_.Push(node);
+}
+
+LockedMultiProducerSingleConsumerQueue::Node*
+LockedMultiProducerSingleConsumerQueue::TryPop() {
+ if (gpr_mu_trylock(mu_.get())) {
+ Node* node = queue_.Pop();
+ gpr_mu_unlock(mu_.get());
+ return node;
+ }
+ return nullptr;
+}
+
+LockedMultiProducerSingleConsumerQueue::Node*
+LockedMultiProducerSingleConsumerQueue::Pop() {
+ MutexLock lock(&mu_);
+ bool empty = false;
+ Node* node;
+ do {
+ node = queue_.PopAndCheckEnd(&empty);
+ } while (node == nullptr && !empty);
+ return node;
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/mpscq.h b/contrib/libs/grpc/src/core/lib/gprpp/mpscq.h
index a1c04cae23..16170661d5 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/mpscq.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/mpscq.h
@@ -1,98 +1,98 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_MPSCQ_H
-#define GRPC_CORE_LIB_GPRPP_MPSCQ_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/gprpp/sync.h"
-
-#include <grpc/support/log.h>
-
-namespace grpc_core {
-
-// Multiple-producer single-consumer lock free queue, based upon the
-// implementation from Dmitry Vyukov here:
-// http://www.1024cores.net/home/lock-free-algorithms/queues/intrusive-mpsc-node-based-queue
-class MultiProducerSingleConsumerQueue {
- public:
- // List node. Application node types can inherit from this.
- struct Node {
- Atomic<Node*> next;
- };
-
- MultiProducerSingleConsumerQueue() : head_{&stub_}, tail_(&stub_) {}
- ~MultiProducerSingleConsumerQueue() {
- GPR_ASSERT(head_.Load(MemoryOrder::RELAXED) == &stub_);
- GPR_ASSERT(tail_ == &stub_);
- }
-
- // Push a node
- // Thread safe - can be called from multiple threads concurrently
- // Returns true if this was possibly the first node (may return true
- // sporadically, will not return false sporadically)
- bool Push(Node* node);
- // Pop a node (returns NULL if no node is ready - which doesn't indicate that
- // the queue is empty!!)
- // Thread compatible - can only be called from one thread at a time
- Node* Pop();
- // Pop a node; sets *empty to true if the queue is empty, or false if it is
- // not.
- Node* PopAndCheckEnd(bool* empty);
-
- private:
- // make sure head & tail don't share a cacheline
- union {
- char padding_[GPR_CACHELINE_SIZE];
- Atomic<Node*> head_;
- };
- Node* tail_;
- Node stub_;
-};
-
-// An mpscq with a lock: it's safe to pop from multiple threads, but doing
-// only one thread will succeed concurrently.
-class LockedMultiProducerSingleConsumerQueue {
- public:
- typedef MultiProducerSingleConsumerQueue::Node Node;
-
- // Push a node
- // Thread safe - can be called from multiple threads concurrently
- // Returns true if this was possibly the first node (may return true
- // sporadically, will not return false sporadically)
- bool Push(Node* node);
-
- // Pop a node (returns NULL if no node is ready - which doesn't indicate that
- // the queue is empty!!)
- // Thread safe - can be called from multiple threads concurrently
- Node* TryPop();
-
- // Pop a node. Returns NULL only if the queue was empty at some point after
- // calling this function
- Node* Pop();
-
- private:
- MultiProducerSingleConsumerQueue queue_;
- Mutex mu_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_MPSCQ_H */
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_MPSCQ_H
+#define GRPC_CORE_LIB_GPRPP_MPSCQ_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/sync.h"
+
+#include <grpc/support/log.h>
+
+namespace grpc_core {
+
+// Multiple-producer single-consumer lock free queue, based upon the
+// implementation from Dmitry Vyukov here:
+// http://www.1024cores.net/home/lock-free-algorithms/queues/intrusive-mpsc-node-based-queue
+class MultiProducerSingleConsumerQueue {
+ public:
+ // List node. Application node types can inherit from this.
+ struct Node {
+ Atomic<Node*> next;
+ };
+
+ MultiProducerSingleConsumerQueue() : head_{&stub_}, tail_(&stub_) {}
+ ~MultiProducerSingleConsumerQueue() {
+ GPR_ASSERT(head_.Load(MemoryOrder::RELAXED) == &stub_);
+ GPR_ASSERT(tail_ == &stub_);
+ }
+
+ // Push a node
+ // Thread safe - can be called from multiple threads concurrently
+ // Returns true if this was possibly the first node (may return true
+ // sporadically, will not return false sporadically)
+ bool Push(Node* node);
+ // Pop a node (returns NULL if no node is ready - which doesn't indicate that
+ // the queue is empty!!)
+ // Thread compatible - can only be called from one thread at a time
+ Node* Pop();
+ // Pop a node; sets *empty to true if the queue is empty, or false if it is
+ // not.
+ Node* PopAndCheckEnd(bool* empty);
+
+ private:
+ // make sure head & tail don't share a cacheline
+ union {
+ char padding_[GPR_CACHELINE_SIZE];
+ Atomic<Node*> head_;
+ };
+ Node* tail_;
+ Node stub_;
+};
+
+// An mpscq with a lock: it's safe to pop from multiple threads, but doing
+// only one thread will succeed concurrently.
+class LockedMultiProducerSingleConsumerQueue {
+ public:
+ typedef MultiProducerSingleConsumerQueue::Node Node;
+
+ // Push a node
+ // Thread safe - can be called from multiple threads concurrently
+ // Returns true if this was possibly the first node (may return true
+ // sporadically, will not return false sporadically)
+ bool Push(Node* node);
+
+ // Pop a node (returns NULL if no node is ready - which doesn't indicate that
+ // the queue is empty!!)
+ // Thread safe - can be called from multiple threads concurrently
+ Node* TryPop();
+
+ // Pop a node. Returns NULL only if the queue was empty at some point after
+ // calling this function
+ Node* Pop();
+
+ private:
+ MultiProducerSingleConsumerQueue queue_;
+ Mutex mu_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_MPSCQ_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h b/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h
index 79542de6dd..703e3fbfaf 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h
@@ -45,7 +45,7 @@ class Orphanable {
// Gives up ownership of the object. The implementation must arrange
// to eventually destroy the object without further interaction from the
// caller.
- virtual void Orphan() = 0;
+ virtual void Orphan() = 0;
// Not copyable or movable.
Orphanable(const Orphanable&) = delete;
@@ -58,18 +58,18 @@ class Orphanable {
class OrphanableDelete {
public:
- template <typename T>
- void operator()(T* p) {
- p->Orphan();
- }
+ template <typename T>
+ void operator()(T* p) {
+ p->Orphan();
+ }
};
-template <typename T, typename Deleter = OrphanableDelete>
+template <typename T, typename Deleter = OrphanableDelete>
using OrphanablePtr = std::unique_ptr<T, Deleter>;
template <typename T, typename... Args>
inline OrphanablePtr<T> MakeOrphanable(Args&&... args) {
- return OrphanablePtr<T>(new T(std::forward<Args>(args)...));
+ return OrphanablePtr<T>(new T(std::forward<Args>(args)...));
}
// A type of Orphanable with internal ref-counting.
@@ -89,9 +89,9 @@ class InternallyRefCounted : public Orphanable {
// Note: RefCount tracing is only enabled on debug builds, even when a
// TraceFlag is used.
template <typename TraceFlagT = TraceFlag>
- explicit InternallyRefCounted(TraceFlagT* trace_flag = nullptr,
- intptr_t initial_refcount = 1)
- : refs_(initial_refcount, trace_flag) {}
+ explicit InternallyRefCounted(TraceFlagT* trace_flag = nullptr,
+ intptr_t initial_refcount = 1)
+ : refs_(initial_refcount, trace_flag) {}
virtual ~InternallyRefCounted() = default;
RefCountedPtr<Child> Ref() GRPC_MUST_USE_RESULT {
@@ -105,13 +105,13 @@ class InternallyRefCounted : public Orphanable {
}
void Unref() {
- if (GPR_UNLIKELY(refs_.Unref())) {
- delete this;
+ if (GPR_UNLIKELY(refs_.Unref())) {
+ delete this;
}
}
void Unref(const DebugLocation& location, const char* reason) {
- if (GPR_UNLIKELY(refs_.Unref(location, reason))) {
- delete this;
+ if (GPR_UNLIKELY(refs_.Unref(location, reason))) {
+ delete this;
}
}
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h
index d05ff6e44c..2b38aa4a01 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h
@@ -30,7 +30,7 @@
#include <cinttypes>
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
@@ -55,14 +55,14 @@ class RefCount {
// Note: RefCount tracing is only enabled on debug builds, even when a
// TraceFlag is used.
template <typename TraceFlagT = TraceFlag>
- constexpr explicit RefCount(
- Value init = 1,
- TraceFlagT*
-#ifndef NDEBUG
- // Leave unnamed if NDEBUG to avoid unused parameter warning
- trace_flag
-#endif
- = nullptr)
+ constexpr explicit RefCount(
+ Value init = 1,
+ TraceFlagT*
+#ifndef NDEBUG
+ // Leave unnamed if NDEBUG to avoid unused parameter warning
+ trace_flag
+#endif
+ = nullptr)
:
#ifndef NDEBUG
trace_flag_(trace_flag),
@@ -72,136 +72,136 @@ class RefCount {
// Increases the ref-count by `n`.
void Ref(Value n = 1) {
-#ifndef NDEBUG
- const Value prior = value_.FetchAdd(n, MemoryOrder::RELAXED);
- if (trace_flag_ != nullptr && trace_flag_->enabled()) {
- gpr_log(GPR_INFO, "%s:%p ref %" PRIdPTR " -> %" PRIdPTR,
- trace_flag_->name(), this, prior, prior + n);
- }
-#else
- value_.FetchAdd(n, MemoryOrder::RELAXED);
-#endif
+#ifndef NDEBUG
+ const Value prior = value_.FetchAdd(n, MemoryOrder::RELAXED);
+ if (trace_flag_ != nullptr && trace_flag_->enabled()) {
+ gpr_log(GPR_INFO, "%s:%p ref %" PRIdPTR " -> %" PRIdPTR,
+ trace_flag_->name(), this, prior, prior + n);
+ }
+#else
+ value_.FetchAdd(n, MemoryOrder::RELAXED);
+#endif
}
void Ref(const DebugLocation& location, const char* reason, Value n = 1) {
#ifndef NDEBUG
- const Value prior = value_.FetchAdd(n, MemoryOrder::RELAXED);
- if (trace_flag_ != nullptr && trace_flag_->enabled()) {
+ const Value prior = value_.FetchAdd(n, MemoryOrder::RELAXED);
+ if (trace_flag_ != nullptr && trace_flag_->enabled()) {
gpr_log(GPR_INFO, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s",
trace_flag_->name(), this, location.file(), location.line(),
- prior, prior + n, reason);
+ prior, prior + n, reason);
}
-#else
- // Use conditionally-important parameters
- (void)location;
- (void)reason;
-
- value_.FetchAdd(n, MemoryOrder::RELAXED);
+#else
+ // Use conditionally-important parameters
+ (void)location;
+ (void)reason;
+
+ value_.FetchAdd(n, MemoryOrder::RELAXED);
#endif
}
// Similar to Ref() with an assert on the ref-count being non-zero.
void RefNonZero() {
#ifndef NDEBUG
- const Value prior = value_.FetchAdd(1, MemoryOrder::RELAXED);
- if (trace_flag_ != nullptr && trace_flag_->enabled()) {
- gpr_log(GPR_INFO, "%s:%p ref %" PRIdPTR " -> %" PRIdPTR,
- trace_flag_->name(), this, prior, prior + 1);
- }
+ const Value prior = value_.FetchAdd(1, MemoryOrder::RELAXED);
+ if (trace_flag_ != nullptr && trace_flag_->enabled()) {
+ gpr_log(GPR_INFO, "%s:%p ref %" PRIdPTR " -> %" PRIdPTR,
+ trace_flag_->name(), this, prior, prior + 1);
+ }
assert(prior > 0);
#else
- value_.FetchAdd(1, MemoryOrder::RELAXED);
+ value_.FetchAdd(1, MemoryOrder::RELAXED);
#endif
}
void RefNonZero(const DebugLocation& location, const char* reason) {
#ifndef NDEBUG
- const Value prior = value_.FetchAdd(1, MemoryOrder::RELAXED);
- if (trace_flag_ != nullptr && trace_flag_->enabled()) {
+ const Value prior = value_.FetchAdd(1, MemoryOrder::RELAXED);
+ if (trace_flag_ != nullptr && trace_flag_->enabled()) {
gpr_log(GPR_INFO, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s",
trace_flag_->name(), this, location.file(), location.line(),
- prior, prior + 1, reason);
- }
- assert(prior > 0);
-#else
- // Avoid unused-parameter warnings for debug-only parameters
- (void)location;
- (void)reason;
- RefNonZero();
-#endif
- }
-
- bool RefIfNonZero() {
-#ifndef NDEBUG
- if (trace_flag_ != nullptr && trace_flag_->enabled()) {
- const Value prior = get();
- gpr_log(GPR_INFO, "%s:%p ref_if_non_zero %" PRIdPTR " -> %" PRIdPTR,
- trace_flag_->name(), this, prior, prior + 1);
- }
-#endif
- return value_.IncrementIfNonzero();
- }
- bool RefIfNonZero(const DebugLocation& location, const char* reason) {
-#ifndef NDEBUG
- if (trace_flag_ != nullptr && trace_flag_->enabled()) {
- const Value prior = get();
- gpr_log(GPR_INFO,
- "%s:%p %s:%d ref_if_non_zero "
- "%" PRIdPTR " -> %" PRIdPTR " %s",
- trace_flag_->name(), this, location.file(), location.line(),
- prior, prior + 1, reason);
+ prior, prior + 1, reason);
}
+ assert(prior > 0);
+#else
+ // Avoid unused-parameter warnings for debug-only parameters
+ (void)location;
+ (void)reason;
+ RefNonZero();
#endif
- // Avoid unused-parameter warnings for debug-only parameters
- (void)location;
- (void)reason;
- return value_.IncrementIfNonzero();
}
+ bool RefIfNonZero() {
+#ifndef NDEBUG
+ if (trace_flag_ != nullptr && trace_flag_->enabled()) {
+ const Value prior = get();
+ gpr_log(GPR_INFO, "%s:%p ref_if_non_zero %" PRIdPTR " -> %" PRIdPTR,
+ trace_flag_->name(), this, prior, prior + 1);
+ }
+#endif
+ return value_.IncrementIfNonzero();
+ }
+ bool RefIfNonZero(const DebugLocation& location, const char* reason) {
+#ifndef NDEBUG
+ if (trace_flag_ != nullptr && trace_flag_->enabled()) {
+ const Value prior = get();
+ gpr_log(GPR_INFO,
+ "%s:%p %s:%d ref_if_non_zero "
+ "%" PRIdPTR " -> %" PRIdPTR " %s",
+ trace_flag_->name(), this, location.file(), location.line(),
+ prior, prior + 1, reason);
+ }
+#endif
+ // Avoid unused-parameter warnings for debug-only parameters
+ (void)location;
+ (void)reason;
+ return value_.IncrementIfNonzero();
+ }
+
// Decrements the ref-count and returns true if the ref-count reaches 0.
bool Unref() {
-#ifndef NDEBUG
- // Grab a copy of the trace flag before the atomic change, since we
- // can't safely access it afterwards if we're going to be freed.
- auto* trace_flag = trace_flag_;
-#endif
- const Value prior = value_.FetchSub(1, MemoryOrder::ACQ_REL);
-#ifndef NDEBUG
- if (trace_flag != nullptr && trace_flag->enabled()) {
- gpr_log(GPR_INFO, "%s:%p unref %" PRIdPTR " -> %" PRIdPTR,
- trace_flag->name(), this, prior, prior - 1);
- }
+#ifndef NDEBUG
+ // Grab a copy of the trace flag before the atomic change, since we
+ // can't safely access it afterwards if we're going to be freed.
+ auto* trace_flag = trace_flag_;
+#endif
+ const Value prior = value_.FetchSub(1, MemoryOrder::ACQ_REL);
+#ifndef NDEBUG
+ if (trace_flag != nullptr && trace_flag->enabled()) {
+ gpr_log(GPR_INFO, "%s:%p unref %" PRIdPTR " -> %" PRIdPTR,
+ trace_flag->name(), this, prior, prior - 1);
+ }
GPR_DEBUG_ASSERT(prior > 0);
-#endif
+#endif
return prior == 1;
}
bool Unref(const DebugLocation& location, const char* reason) {
#ifndef NDEBUG
- // Grab a copy of the trace flag before the atomic change, since we
- // can't safely access it afterwards if we're going to be freed.
- auto* trace_flag = trace_flag_;
-#endif
- const Value prior = value_.FetchSub(1, MemoryOrder::ACQ_REL);
-#ifndef NDEBUG
- if (trace_flag != nullptr && trace_flag->enabled()) {
+ // Grab a copy of the trace flag before the atomic change, since we
+ // can't safely access it afterwards if we're going to be freed.
+ auto* trace_flag = trace_flag_;
+#endif
+ const Value prior = value_.FetchSub(1, MemoryOrder::ACQ_REL);
+#ifndef NDEBUG
+ if (trace_flag != nullptr && trace_flag->enabled()) {
gpr_log(GPR_INFO, "%s:%p %s:%d unref %" PRIdPTR " -> %" PRIdPTR " %s",
- trace_flag->name(), this, location.file(), location.line(), prior,
- prior - 1, reason);
+ trace_flag->name(), this, location.file(), location.line(), prior,
+ prior - 1, reason);
}
- GPR_DEBUG_ASSERT(prior > 0);
-#else
- // Avoid unused-parameter warnings for debug-only parameters
- (void)location;
- (void)reason;
+ GPR_DEBUG_ASSERT(prior > 0);
+#else
+ // Avoid unused-parameter warnings for debug-only parameters
+ (void)location;
+ (void)reason;
#endif
- return prior == 1;
+ return prior == 1;
}
private:
- Value get() const { return value_.Load(MemoryOrder::RELAXED); }
+ Value get() const { return value_.Load(MemoryOrder::RELAXED); }
#ifndef NDEBUG
TraceFlag* trace_flag_;
#endif
- Atomic<Value> value_;
+ Atomic<Value> value_;
};
// PolymorphicRefCount enforces polymorphic destruction of RefCounted.
@@ -254,7 +254,7 @@ class Delete<T, false> {
// So, use NonPolymorphicRefCount only when both of the following conditions
// are guaranteed to hold:
// (a) Child is a concrete leaf class in RefCounted<Child>, and
-// (b) you are guaranteed to call Unref only on concrete leaf classes and not
+// (b) you are guaranteed to call Unref only on concrete leaf classes and not
// their parents.
//
// The following example is illegal, because calling Unref() will not call
@@ -270,9 +270,9 @@ template <typename Child, typename Impl = PolymorphicRefCount,
bool DeleteUponUnref = true>
class RefCounted : public Impl {
public:
- // Note: Depending on the Impl used, this dtor can be implicitly virtual.
- ~RefCounted() = default;
-
+ // Note: Depending on the Impl used, this dtor can be implicitly virtual.
+ ~RefCounted() = default;
+
RefCountedPtr<Child> Ref() GRPC_MUST_USE_RESULT {
IncrementRefCount();
return RefCountedPtr<Child>(static_cast<Child*>(this));
@@ -289,12 +289,12 @@ class RefCounted : public Impl {
// private, since it will only be used by RefCountedPtr<>, which is a
// friend of this class.
void Unref() {
- if (GPR_UNLIKELY(refs_.Unref())) {
+ if (GPR_UNLIKELY(refs_.Unref())) {
internal::Delete<Child, DeleteUponUnref>(static_cast<Child*>(this));
}
}
void Unref(const DebugLocation& location, const char* reason) {
- if (GPR_UNLIKELY(refs_.Unref(location, reason))) {
+ if (GPR_UNLIKELY(refs_.Unref(location, reason))) {
internal::Delete<Child, DeleteUponUnref>(static_cast<Child*>(this));
}
}
@@ -302,14 +302,14 @@ class RefCounted : public Impl {
RefCountedPtr<Child> RefIfNonZero() GRPC_MUST_USE_RESULT {
return RefCountedPtr<Child>(refs_.RefIfNonZero() ? static_cast<Child*>(this)
: nullptr);
- }
+ }
RefCountedPtr<Child> RefIfNonZero(const DebugLocation& location,
const char* reason) GRPC_MUST_USE_RESULT {
return RefCountedPtr<Child>(refs_.RefIfNonZero(location, reason)
? static_cast<Child*>(this)
: nullptr);
}
-
+
// Not copyable nor movable.
RefCounted(const RefCounted&) = delete;
RefCounted& operator=(const RefCounted&) = delete;
@@ -319,9 +319,9 @@ class RefCounted : public Impl {
// Note: RefCount tracing is only enabled on debug builds, even when a
// TraceFlag is used.
template <typename TraceFlagT = TraceFlag>
- explicit RefCounted(TraceFlagT* trace_flag = nullptr,
- intptr_t initial_refcount = 1)
- : refs_(initial_refcount, trace_flag) {}
+ explicit RefCounted(TraceFlagT* trace_flag = nullptr,
+ intptr_t initial_refcount = 1)
+ : refs_(initial_refcount, trace_flag) {}
private:
// Allow RefCountedPtr<> to access IncrementRefCount().
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h
index c28e762532..f43c08948c 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h
@@ -103,8 +103,8 @@ class RefCountedPtr {
if (value_ != nullptr) value_->Unref();
}
- void swap(RefCountedPtr& other) { std::swap(value_, other.value_); }
-
+ void swap(RefCountedPtr& other) { std::swap(value_, other.value_); }
+
// If value is non-null, we take ownership of a ref to it.
void reset(T* value = nullptr) {
if (value_ != nullptr) value_->Unref();
@@ -327,7 +327,7 @@ class WeakRefCountedPtr {
template <typename T, typename... Args>
inline RefCountedPtr<T> MakeRefCounted(Args&&... args) {
- return RefCountedPtr<T>(new T(std::forward<Args>(args)...));
+ return RefCountedPtr<T>(new T(std::forward<Args>(args)...));
}
template <typename T>
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/sync.h b/contrib/libs/grpc/src/core/lib/gprpp/sync.h
index 0a911b1cd2..c13991c7b0 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/sync.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/sync.h
@@ -1,122 +1,122 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_SYNC_H
-#define GRPC_CORE_LIB_GPRPP_SYNC_H
-
-#include <grpc/impl/codegen/port_platform.h>
-
-#include <grpc/impl/codegen/log.h>
-#include <grpc/impl/codegen/sync.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-
-// The core library is not accessible in C++ codegen headers, and vice versa.
-// Thus, we need to have duplicate headers with similar functionality.
-// Make sure any change to this file is also reflected in
-// include/grpcpp/impl/codegen/sync.h.
-//
-// Whenever possible, prefer using this file over <grpcpp/impl/codegen/sync.h>
-// since this file doesn't rely on g_core_codegen_interface and hence does not
-// pay the costs of virtual function calls.
-
-namespace grpc_core {
-
-class Mutex {
- public:
- Mutex() { gpr_mu_init(&mu_); }
- ~Mutex() { gpr_mu_destroy(&mu_); }
-
- Mutex(const Mutex&) = delete;
- Mutex& operator=(const Mutex&) = delete;
-
- gpr_mu* get() { return &mu_; }
- const gpr_mu* get() const { return &mu_; }
-
- private:
- gpr_mu mu_;
-};
-
-// MutexLock is a std::
-class MutexLock {
- public:
- explicit MutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
- explicit MutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
- ~MutexLock() { gpr_mu_unlock(mu_); }
-
- MutexLock(const MutexLock&) = delete;
- MutexLock& operator=(const MutexLock&) = delete;
-
- private:
- gpr_mu* const mu_;
-};
-
-class ReleasableMutexLock {
- public:
- explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
- explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
- ~ReleasableMutexLock() {
- if (!released_) gpr_mu_unlock(mu_);
- }
-
- ReleasableMutexLock(const ReleasableMutexLock&) = delete;
- ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
-
- void Lock() {
- GPR_DEBUG_ASSERT(released_);
- gpr_mu_lock(mu_);
- released_ = false;
- }
-
- void Unlock() {
- GPR_DEBUG_ASSERT(!released_);
- released_ = true;
- gpr_mu_unlock(mu_);
- }
-
- private:
- gpr_mu* const mu_;
- bool released_ = false;
-};
-
-class CondVar {
- public:
- CondVar() { gpr_cv_init(&cv_); }
- ~CondVar() { gpr_cv_destroy(&cv_); }
-
- CondVar(const CondVar&) = delete;
- CondVar& operator=(const CondVar&) = delete;
-
- void Signal() { gpr_cv_signal(&cv_); }
- void Broadcast() { gpr_cv_broadcast(&cv_); }
-
- int Wait(Mutex* mu) { return Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME)); }
- int Wait(Mutex* mu, const gpr_timespec& deadline) {
- return gpr_cv_wait(&cv_, mu->get(), deadline);
- }
-
- template <typename Predicate>
- void WaitUntil(Mutex* mu, Predicate pred) {
- while (!pred()) {
- Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME));
- }
- }
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_SYNC_H
+#define GRPC_CORE_LIB_GPRPP_SYNC_H
+
+#include <grpc/impl/codegen/port_platform.h>
+
+#include <grpc/impl/codegen/log.h>
+#include <grpc/impl/codegen/sync.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+
+// The core library is not accessible in C++ codegen headers, and vice versa.
+// Thus, we need to have duplicate headers with similar functionality.
+// Make sure any change to this file is also reflected in
+// include/grpcpp/impl/codegen/sync.h.
+//
+// Whenever possible, prefer using this file over <grpcpp/impl/codegen/sync.h>
+// since this file doesn't rely on g_core_codegen_interface and hence does not
+// pay the costs of virtual function calls.
+
+namespace grpc_core {
+
+class Mutex {
+ public:
+ Mutex() { gpr_mu_init(&mu_); }
+ ~Mutex() { gpr_mu_destroy(&mu_); }
+
+ Mutex(const Mutex&) = delete;
+ Mutex& operator=(const Mutex&) = delete;
+
+ gpr_mu* get() { return &mu_; }
+ const gpr_mu* get() const { return &mu_; }
+
+ private:
+ gpr_mu mu_;
+};
+
+// MutexLock is a std::
+class MutexLock {
+ public:
+ explicit MutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
+ explicit MutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
+ ~MutexLock() { gpr_mu_unlock(mu_); }
+
+ MutexLock(const MutexLock&) = delete;
+ MutexLock& operator=(const MutexLock&) = delete;
+
+ private:
+ gpr_mu* const mu_;
+};
+
+class ReleasableMutexLock {
+ public:
+ explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
+ explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
+ ~ReleasableMutexLock() {
+ if (!released_) gpr_mu_unlock(mu_);
+ }
+
+ ReleasableMutexLock(const ReleasableMutexLock&) = delete;
+ ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
+
+ void Lock() {
+ GPR_DEBUG_ASSERT(released_);
+ gpr_mu_lock(mu_);
+ released_ = false;
+ }
+
+ void Unlock() {
+ GPR_DEBUG_ASSERT(!released_);
+ released_ = true;
+ gpr_mu_unlock(mu_);
+ }
+
+ private:
+ gpr_mu* const mu_;
+ bool released_ = false;
+};
+
+class CondVar {
+ public:
+ CondVar() { gpr_cv_init(&cv_); }
+ ~CondVar() { gpr_cv_destroy(&cv_); }
+
+ CondVar(const CondVar&) = delete;
+ CondVar& operator=(const CondVar&) = delete;
+
+ void Signal() { gpr_cv_signal(&cv_); }
+ void Broadcast() { gpr_cv_broadcast(&cv_); }
+
+ int Wait(Mutex* mu) { return Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME)); }
+ int Wait(Mutex* mu, const gpr_timespec& deadline) {
+ return gpr_cv_wait(&cv_, mu->get(), deadline);
+ }
+
+ template <typename Predicate>
+ void WaitUntil(Mutex* mu, Predicate pred) {
+ while (!pred()) {
+ Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME));
+ }
+ }
+
// Returns true iff we timed-out
template <typename Predicate>
bool WaitUntil(Mutex* mu, Predicate pred, const gpr_timespec& deadline) {
@@ -126,10 +126,10 @@ class CondVar {
return false;
}
- private:
- gpr_cv cv_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_SYNC_H */
+ private:
+ gpr_cv cv_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_SYNC_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/thd.h b/contrib/libs/grpc/src/core/lib/gprpp/thd.h
index 8e50f545e2..9bc7baa044 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/thd.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/thd.h
@@ -37,44 +37,44 @@ namespace internal {
class ThreadInternalsInterface {
public:
virtual ~ThreadInternalsInterface() {}
- virtual void Start() = 0;
- virtual void Join() = 0;
+ virtual void Start() = 0;
+ virtual void Join() = 0;
};
} // namespace internal
class Thread {
public:
- class Options {
- public:
- Options() : joinable_(true), tracked_(true), stack_size_(0) {}
- /// Set whether the thread is joinable or detached.
- Options& set_joinable(bool joinable) {
- joinable_ = joinable;
- return *this;
- }
- bool joinable() const { return joinable_; }
-
- /// Set whether the thread is tracked for fork support.
- Options& set_tracked(bool tracked) {
- tracked_ = tracked;
- return *this;
- }
- bool tracked() const { return tracked_; }
-
- /// Sets thread stack size (in bytes). Sets to 0 will use the default stack
- /// size which is 64KB for Windows threads and 2MB for Posix(x86) threads.
- Options& set_stack_size(size_t bytes) {
- stack_size_ = bytes;
- return *this;
- }
- size_t stack_size() const { return stack_size_; }
-
- private:
- bool joinable_;
- bool tracked_;
- size_t stack_size_;
- };
+ class Options {
+ public:
+ Options() : joinable_(true), tracked_(true), stack_size_(0) {}
+ /// Set whether the thread is joinable or detached.
+ Options& set_joinable(bool joinable) {
+ joinable_ = joinable;
+ return *this;
+ }
+ bool joinable() const { return joinable_; }
+
+ /// Set whether the thread is tracked for fork support.
+ Options& set_tracked(bool tracked) {
+ tracked_ = tracked;
+ return *this;
+ }
+ bool tracked() const { return tracked_; }
+
+ /// Sets thread stack size (in bytes). Sets to 0 will use the default stack
+ /// size which is 64KB for Windows threads and 2MB for Posix(x86) threads.
+ Options& set_stack_size(size_t bytes) {
+ stack_size_ = bytes;
+ return *this;
+ }
+ size_t stack_size() const { return stack_size_; }
+
+ private:
+ bool joinable_;
+ bool tracked_;
+ size_t stack_size_;
+ };
/// Default constructor only to allow use in structs that lack constructors
/// Does not produce a validly-constructed thread; must later
/// use placement new to construct a real thread. Does not init mu_ and cv_
@@ -85,17 +85,17 @@ class Thread {
/// with argument \a arg once it is started.
/// The optional \a success argument indicates whether the thread
/// is successfully created.
- /// The optional \a options can be used to set the thread detachable.
+ /// The optional \a options can be used to set the thread detachable.
Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
- bool* success = nullptr, const Options& options = Options());
+ bool* success = nullptr, const Options& options = Options());
/// Move constructor for thread. After this is called, the other thread
/// no longer represents a living thread object
- Thread(Thread&& other)
- : state_(other.state_), impl_(other.impl_), options_(other.options_) {
+ Thread(Thread&& other)
+ : state_(other.state_), impl_(other.impl_), options_(other.options_) {
other.state_ = MOVED;
other.impl_ = nullptr;
- other.options_ = Options();
+ other.options_ = Options();
}
/// Move assignment operator for thread. After this is called, the other
@@ -110,47 +110,47 @@ class Thread {
// assert it for the time being.
state_ = other.state_;
impl_ = other.impl_;
- options_ = other.options_;
+ options_ = other.options_;
other.state_ = MOVED;
other.impl_ = nullptr;
- other.options_ = Options();
+ other.options_ = Options();
}
return *this;
}
/// The destructor is strictly optional; either the thread never came to life
- /// and the constructor itself killed it, or it has already been joined and
- /// the Join function kills it, or it was detached (non-joinable) and it has
- /// run to completion and is now killing itself. The destructor shouldn't have
- /// to do anything.
- ~Thread() { GPR_ASSERT(!options_.joinable() || impl_ == nullptr); }
+ /// and the constructor itself killed it, or it has already been joined and
+ /// the Join function kills it, or it was detached (non-joinable) and it has
+ /// run to completion and is now killing itself. The destructor shouldn't have
+ /// to do anything.
+ ~Thread() { GPR_ASSERT(!options_.joinable() || impl_ == nullptr); }
void Start() {
if (impl_ != nullptr) {
GPR_ASSERT(state_ == ALIVE);
state_ = STARTED;
impl_->Start();
- // If the Thread is not joinable, then the impl_ will cause the deletion
- // of this Thread object when the thread function completes. Since no
- // other operation is allowed to a detached thread after Start, there is
- // no need to change the value of the impl_ or state_ . The next operation
- // on this object will be the deletion, which will trigger the destructor.
+ // If the Thread is not joinable, then the impl_ will cause the deletion
+ // of this Thread object when the thread function completes. Since no
+ // other operation is allowed to a detached thread after Start, there is
+ // no need to change the value of the impl_ or state_ . The next operation
+ // on this object will be the deletion, which will trigger the destructor.
} else {
GPR_ASSERT(state_ == FAILED);
}
- }
+ }
- // It is only legal to call Join if the Thread is created as joinable.
+ // It is only legal to call Join if the Thread is created as joinable.
void Join() {
if (impl_ != nullptr) {
impl_->Join();
- delete impl_;
+ delete impl_;
state_ = DONE;
impl_ = nullptr;
} else {
GPR_ASSERT(state_ == FAILED);
}
- }
+ }
private:
Thread(const Thread&) = delete;
@@ -166,7 +166,7 @@ class Thread {
enum ThreadState { FAKE, ALIVE, STARTED, DONE, FAILED, MOVED };
ThreadState state_;
internal::ThreadInternalsInterface* impl_;
- Options options_;
+ Options options_;
};
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc b/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc
index f6f6af9c26..aaf65e247f 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc
@@ -32,7 +32,7 @@
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
-#include <unistd.h>
+#include <unistd.h>
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/fork.h"
@@ -46,34 +46,34 @@ struct thd_arg {
void (*body)(void* arg); /* body of a thread */
void* arg; /* argument to a thread */
const char* name; /* name of thread. Can be nullptr. */
- bool joinable;
- bool tracked;
+ bool joinable;
+ bool tracked;
};
-size_t RoundUpToPageSize(size_t size) {
- // TODO(yunjiaw): Change this variable (page_size) to a function-level static
- // when possible
- size_t page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
- return (size + page_size - 1) & ~(page_size - 1);
-}
-
-// Returns the minimum valid stack size that can be passed to
-// pthread_attr_setstacksize.
-size_t MinValidStackSize(size_t request_size) {
- size_t min_stacksize = sysconf(_SC_THREAD_STACK_MIN);
- if (request_size < min_stacksize) {
- request_size = min_stacksize;
- }
-
- // On some systems, pthread_attr_setstacksize() can fail if stacksize is
- // not a multiple of the system page size.
- return RoundUpToPageSize(request_size);
-}
-
-class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
+size_t RoundUpToPageSize(size_t size) {
+ // TODO(yunjiaw): Change this variable (page_size) to a function-level static
+ // when possible
+ size_t page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
+ return (size + page_size - 1) & ~(page_size - 1);
+}
+
+// Returns the minimum valid stack size that can be passed to
+// pthread_attr_setstacksize.
+size_t MinValidStackSize(size_t request_size) {
+ size_t min_stacksize = sysconf(_SC_THREAD_STACK_MIN);
+ if (request_size < min_stacksize) {
+ request_size = min_stacksize;
+ }
+
+ // On some systems, pthread_attr_setstacksize() can fail if stacksize is
+ // not a multiple of the system page size.
+ return RoundUpToPageSize(request_size);
+}
+
+class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
public:
ThreadInternalsPosix(const char* thd_name, void (*thd_body)(void* arg),
- void* arg, bool* success, const Thread::Options& options)
+ void* arg, bool* success, const Thread::Options& options)
: started_(false) {
gpr_mu_init(&mu_);
gpr_cv_init(&ready_);
@@ -86,26 +86,26 @@ class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
info->body = thd_body;
info->arg = arg;
info->name = thd_name;
- info->joinable = options.joinable();
- info->tracked = options.tracked();
- if (options.tracked()) {
- Fork::IncThreadCount();
- }
+ info->joinable = options.joinable();
+ info->tracked = options.tracked();
+ if (options.tracked()) {
+ Fork::IncThreadCount();
+ }
GPR_ASSERT(pthread_attr_init(&attr) == 0);
- if (options.joinable()) {
- GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) ==
- 0);
- } else {
- GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ==
- 0);
- }
-
- if (options.stack_size() != 0) {
- size_t stack_size = MinValidStackSize(options.stack_size());
- GPR_ASSERT(pthread_attr_setstacksize(&attr, stack_size) == 0);
- }
-
+ if (options.joinable()) {
+ GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) ==
+ 0);
+ } else {
+ GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ==
+ 0);
+ }
+
+ if (options.stack_size() != 0) {
+ size_t stack_size = MinValidStackSize(options.stack_size());
+ GPR_ASSERT(pthread_attr_setstacksize(&attr, stack_size) == 0);
+ }
+
*success =
(pthread_create(&pthread_id_, &attr,
[](void* v) -> void* {
@@ -122,14 +122,14 @@ class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
}
gpr_mu_unlock(&arg.thread->mu_);
- if (!arg.joinable) {
- delete arg.thread;
- }
-
+ if (!arg.joinable) {
+ delete arg.thread;
+ }
+
(*arg.body)(arg.arg);
- if (arg.tracked) {
- Fork::DecThreadCount();
- }
+ if (arg.tracked) {
+ Fork::DecThreadCount();
+ }
return nullptr;
},
info) == 0);
@@ -139,11 +139,11 @@ class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
if (!(*success)) {
/* don't use gpr_free, as this was allocated using malloc (see above) */
free(info);
- if (options.tracked()) {
- Fork::DecThreadCount();
- }
+ if (options.tracked()) {
+ Fork::DecThreadCount();
+ }
}
- }
+ }
~ThreadInternalsPosix() override {
gpr_mu_destroy(&mu_);
@@ -169,15 +169,15 @@ class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
} // namespace
Thread::Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
- bool* success, const Options& options)
- : options_(options) {
+ bool* success, const Options& options)
+ : options_(options) {
bool outcome = false;
- impl_ = new ThreadInternalsPosix(thd_name, thd_body, arg, &outcome, options);
+ impl_ = new ThreadInternalsPosix(thd_name, thd_body, arg, &outcome, options);
if (outcome) {
state_ = ALIVE;
} else {
state_ = FAILED;
- delete impl_;
+ delete impl_;
impl_ = nullptr;
}
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc b/contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc
index bd3b7a36eb..a1c5c6bb66 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc
@@ -46,7 +46,7 @@ struct thd_info {
void (*body)(void* arg); /* body of a thread */
void* arg; /* argument to a thread */
HANDLE join_event; /* the join event */
- bool joinable; /* whether it is joinable */
+ bool joinable; /* whether it is joinable */
};
thread_local struct thd_info* g_thd_info;
@@ -54,8 +54,8 @@ thread_local struct thd_info* g_thd_info;
class ThreadInternalsWindows
: public grpc_core::internal::ThreadInternalsInterface {
public:
- ThreadInternalsWindows(void (*thd_body)(void* arg), void* arg, bool* success,
- const grpc_core::Thread::Options& options)
+ ThreadInternalsWindows(void (*thd_body)(void* arg), void* arg, bool* success,
+ const grpc_core::Thread::Options& options)
: started_(false) {
gpr_mu_init(&mu_);
gpr_cv_init(&ready_);
@@ -65,31 +65,31 @@ class ThreadInternalsWindows
info_->thread = this;
info_->body = thd_body;
info_->arg = arg;
- info_->join_event = nullptr;
- info_->joinable = options.joinable();
- if (info_->joinable) {
- info_->join_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
- if (info_->join_event == nullptr) {
- gpr_free(info_);
- *success = false;
- return;
- }
- }
-
- if (options.stack_size() != 0) {
- // Windows will round up the given stack_size value to nearest page.
- handle = CreateThread(nullptr, options.stack_size(), thread_body, info_,
- 0, nullptr);
- } else {
- handle = CreateThread(nullptr, 64 * 1024, thread_body, info_, 0, nullptr);
- }
-
- if (handle == nullptr) {
- destroy_thread();
+ info_->join_event = nullptr;
+ info_->joinable = options.joinable();
+ if (info_->joinable) {
+ info_->join_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
+ if (info_->join_event == nullptr) {
+ gpr_free(info_);
+ *success = false;
+ return;
+ }
+ }
+
+ if (options.stack_size() != 0) {
+ // Windows will round up the given stack_size value to nearest page.
+ handle = CreateThread(nullptr, options.stack_size(), thread_body, info_,
+ 0, nullptr);
+ } else {
+ handle = CreateThread(nullptr, 64 * 1024, thread_body, info_, 0, nullptr);
+ }
+
+ if (handle == nullptr) {
+ destroy_thread();
*success = false;
} else {
- CloseHandle(handle);
- *success = true;
+ CloseHandle(handle);
+ *success = true;
}
}
@@ -112,32 +112,32 @@ class ThreadInternalsWindows
}
private:
- static DWORD WINAPI thread_body(void* v) {
- g_thd_info = static_cast<thd_info*>(v);
- gpr_mu_lock(&g_thd_info->thread->mu_);
- while (!g_thd_info->thread->started_) {
- gpr_cv_wait(&g_thd_info->thread->ready_, &g_thd_info->thread->mu_,
- gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
- gpr_mu_unlock(&g_thd_info->thread->mu_);
- if (!g_thd_info->joinable) {
- delete g_thd_info->thread;
- g_thd_info->thread = nullptr;
- }
- g_thd_info->body(g_thd_info->arg);
- if (g_thd_info->joinable) {
- BOOL ret = SetEvent(g_thd_info->join_event);
- GPR_ASSERT(ret);
- } else {
- gpr_free(g_thd_info);
- }
- return 0;
- }
-
+ static DWORD WINAPI thread_body(void* v) {
+ g_thd_info = static_cast<thd_info*>(v);
+ gpr_mu_lock(&g_thd_info->thread->mu_);
+ while (!g_thd_info->thread->started_) {
+ gpr_cv_wait(&g_thd_info->thread->ready_, &g_thd_info->thread->mu_,
+ gpr_inf_future(GPR_CLOCK_MONOTONIC));
+ }
+ gpr_mu_unlock(&g_thd_info->thread->mu_);
+ if (!g_thd_info->joinable) {
+ delete g_thd_info->thread;
+ g_thd_info->thread = nullptr;
+ }
+ g_thd_info->body(g_thd_info->arg);
+ if (g_thd_info->joinable) {
+ BOOL ret = SetEvent(g_thd_info->join_event);
+ GPR_ASSERT(ret);
+ } else {
+ gpr_free(g_thd_info);
+ }
+ return 0;
+ }
+
void destroy_thread() {
- if (info_ != nullptr && info_->joinable) {
- CloseHandle(info_->join_event);
- }
+ if (info_ != nullptr && info_->joinable) {
+ CloseHandle(info_->join_event);
+ }
gpr_free(info_);
}
@@ -152,15 +152,15 @@ class ThreadInternalsWindows
namespace grpc_core {
Thread::Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
- bool* success, const Options& options)
- : options_(options) {
+ bool* success, const Options& options)
+ : options_(options) {
bool outcome = false;
- impl_ = new ThreadInternalsWindows(thd_body, arg, &outcome, options);
+ impl_ = new ThreadInternalsWindows(thd_body, arg, &outcome, options);
if (outcome) {
state_ = ALIVE;
} else {
state_ = FAILED;
- delete impl_;
+ delete impl_;
impl_ = nullptr;
}
diff --git a/contrib/libs/grpc/src/core/lib/http/httpcli.cc b/contrib/libs/grpc/src/core/lib/http/httpcli.cc
index c196a8faac..da2b157c14 100644
--- a/contrib/libs/grpc/src/core/lib/http/httpcli.cc
+++ b/contrib/libs/grpc/src/core/lib/http/httpcli.cc
@@ -32,7 +32,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/http/format_request.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/endpoint.h"
@@ -69,7 +69,7 @@ static grpc_httpcli_get_override g_get_override = nullptr;
static grpc_httpcli_post_override g_post_override = nullptr;
static void plaintext_handshake(void* arg, grpc_endpoint* endpoint,
- const char* /*host*/, grpc_millis /*deadline*/,
+ const char* /*host*/, grpc_millis /*deadline*/,
void (*on_done)(void* arg,
grpc_endpoint* endpoint)) {
on_done(arg, endpoint);
@@ -91,7 +91,7 @@ static void next_address(internal_request* req, grpc_error* due_to_error);
static void finish(internal_request* req, grpc_error* error) {
grpc_polling_entity_del_from_pollset_set(req->pollent,
req->context->pollset_set);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, req->on_done, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, req->on_done, error);
grpc_http_parser_destroy(&req->parser);
if (req->addresses != nullptr) {
grpc_resolved_addresses_destroy(req->addresses);
@@ -124,7 +124,7 @@ static void append_error(internal_request* req, grpc_error* error) {
}
static void do_read(internal_request* req) {
- grpc_endpoint_read(req->ep, &req->incoming, &req->on_read, /*urgent=*/true);
+ grpc_endpoint_read(req->ep, &req->incoming, &req->on_read, /*urgent=*/true);
}
static void on_read(void* user_data, grpc_error* error) {
@@ -232,8 +232,8 @@ static void internal_request_begin(grpc_httpcli_context* context,
const grpc_httpcli_request* request,
grpc_millis deadline, grpc_closure* on_done,
grpc_httpcli_response* response,
- const char* name,
- const grpc_slice& request_text) {
+ const char* name,
+ const grpc_slice& request_text) {
internal_request* req =
static_cast<internal_request*>(gpr_malloc(sizeof(internal_request)));
memset(req, 0, sizeof(*req));
diff --git a/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc b/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc
index 62643186ad..2168ac0b2f 100644
--- a/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc
+++ b/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc
@@ -43,7 +43,7 @@
class grpc_httpcli_ssl_channel_security_connector final
: public grpc_channel_security_connector {
public:
- grpc_httpcli_ssl_channel_security_connector(char* secure_peer_name)
+ grpc_httpcli_ssl_channel_security_connector(char* secure_peer_name)
: grpc_channel_security_connector(
/*url_scheme=*/nullptr,
/*channel_creds=*/nullptr,
@@ -68,8 +68,8 @@ class grpc_httpcli_ssl_channel_security_connector final
&options, &handshaker_factory_);
}
- void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* /*interested_parties*/,
+ void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_mgr) override {
tsi_handshaker* handshaker = nullptr;
if (handshaker_factory_ != nullptr) {
@@ -80,15 +80,15 @@ class grpc_httpcli_ssl_channel_security_connector final
tsi_result_to_string(result));
}
}
- handshake_mgr->Add(
- grpc_core::SecurityHandshakerCreate(handshaker, this, args));
+ handshake_mgr->Add(
+ grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
tsi_ssl_client_handshaker_factory* handshaker_factory() const {
return handshaker_factory_;
}
- void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
+ void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* /*auth_context*/,
grpc_closure* on_peer_checked) override {
grpc_error* error = GRPC_ERROR_NONE;
@@ -101,7 +101,7 @@ class grpc_httpcli_ssl_channel_security_connector final
" is not in peer certificate")
.c_str());
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
tsi_peer_destruct(&peer);
}
@@ -113,14 +113,14 @@ class grpc_httpcli_ssl_channel_security_connector final
}
bool check_call_host(y_absl::string_view /*host*/,
- grpc_auth_context* /*auth_context*/,
- grpc_closure* /*on_call_host_checked*/,
+ grpc_auth_context* /*auth_context*/,
+ grpc_closure* /*on_call_host_checked*/,
grpc_error** error) override {
*error = GRPC_ERROR_NONE;
return true;
}
- void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
+ void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
@@ -135,7 +135,7 @@ class grpc_httpcli_ssl_channel_security_connector final
static grpc_core::RefCountedPtr<grpc_channel_security_connector>
httpcli_ssl_channel_security_connector_create(
const char* pem_root_certs, const tsi_ssl_root_certs_store* root_store,
- const char* secure_peer_name, grpc_channel_args* /*channel_args*/) {
+ const char* secure_peer_name, grpc_channel_args* /*channel_args*/) {
if (secure_peer_name != nullptr && pem_root_certs == nullptr) {
gpr_log(GPR_ERROR,
"Cannot assert a secure peer name without a trust root.");
@@ -174,13 +174,13 @@ static void on_handshake_done(void* arg, grpc_error* error) {
gpr_free(args->read_buffer);
c->func(c->arg, args->endpoint);
}
- delete c;
+ delete c;
}
static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host,
grpc_millis deadline,
void (*on_done)(void* arg, grpc_endpoint* endpoint)) {
- auto* c = new on_done_closure();
+ auto* c = new on_done_closure();
const char* pem_root_certs =
grpc_core::DefaultSslRootStore::GetPemRootCerts();
const tsi_ssl_root_certs_store* root_store =
@@ -194,10 +194,10 @@ static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host,
c->func = on_done;
c->arg = arg;
grpc_core::RefCountedPtr<grpc_channel_security_connector> sc =
- httpcli_ssl_channel_security_connector_create(
- pem_root_certs, root_store, host,
- static_cast<grpc_core::HandshakerArgs*>(arg)->args);
-
+ httpcli_ssl_channel_security_connector_create(
+ pem_root_certs, root_store, host,
+ static_cast<grpc_core::HandshakerArgs*>(arg)->args);
+
GPR_ASSERT(sc != nullptr);
grpc_arg channel_arg = grpc_security_connector_to_arg(sc.get());
grpc_channel_args args = {1, &channel_arg};
diff --git a/contrib/libs/grpc/src/core/lib/http/parser.cc b/contrib/libs/grpc/src/core/lib/http/parser.cc
index 022ef9a2e7..ac71408107 100644
--- a/contrib/libs/grpc/src/core/lib/http/parser.cc
+++ b/contrib/libs/grpc/src/core/lib/http/parser.cc
@@ -300,7 +300,7 @@ static grpc_error* addbyte(grpc_http_parser* parser, uint8_t byte,
case GRPC_HTTP_FIRST_LINE:
case GRPC_HTTP_HEADERS:
if (parser->cur_line_length >= GRPC_HTTP_PARSER_MAX_HEADER_LENGTH) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_http1_trace))
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_http1_trace))
gpr_log(GPR_ERROR, "HTTP header max line length (%d) exceeded",
GRPC_HTTP_PARSER_MAX_HEADER_LENGTH);
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
@@ -327,7 +327,7 @@ void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type,
parser->cur_line_end_length = 2;
}
-void grpc_http_parser_destroy(grpc_http_parser* /*parser*/) {}
+void grpc_http_parser_destroy(grpc_http_parser* /*parser*/) {}
void grpc_http_request_destroy(grpc_http_request* request) {
size_t i;
@@ -351,8 +351,8 @@ void grpc_http_response_destroy(grpc_http_response* response) {
gpr_free(response->hdrs);
}
-grpc_error* grpc_http_parser_parse(grpc_http_parser* parser,
- const grpc_slice& slice,
+grpc_error* grpc_http_parser_parse(grpc_http_parser* parser,
+ const grpc_slice& slice,
size_t* start_of_body) {
for (size_t i = 0; i < GRPC_SLICE_LENGTH(slice); i++) {
bool found_body_start = false;
diff --git a/contrib/libs/grpc/src/core/lib/http/parser.h b/contrib/libs/grpc/src/core/lib/http/parser.h
index 2da21903e6..474844d539 100644
--- a/contrib/libs/grpc/src/core/lib/http/parser.h
+++ b/contrib/libs/grpc/src/core/lib/http/parser.h
@@ -100,8 +100,8 @@ void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type,
void grpc_http_parser_destroy(grpc_http_parser* parser);
/* Sets \a start_of_body to the offset in \a slice of the start of the body. */
-grpc_error* grpc_http_parser_parse(grpc_http_parser* parser,
- const grpc_slice& slice,
+grpc_error* grpc_http_parser_parse(grpc_http_parser* parser,
+ const grpc_slice& slice,
size_t* start_of_body);
grpc_error* grpc_http_parser_eof(grpc_http_parser* parser);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc
index e1b87da4d0..b19b68ebbe 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc
@@ -39,8 +39,8 @@ void fill_gpr_from_timestamp(gpr_timespec* gts, const struct timespec* ts) {
gts->clock_type = GPR_CLOCK_REALTIME;
}
-void default_timestamps_callback(void* /*arg*/, grpc_core::Timestamps* /*ts*/,
- grpc_error* /*shudown_err*/) {
+void default_timestamps_callback(void* /*arg*/, grpc_core::Timestamps* /*ts*/,
+ grpc_error* /*shudown_err*/) {
gpr_log(GPR_DEBUG, "Timestamps callback has not been registered");
}
@@ -198,7 +198,7 @@ static int get_socket_tcp_info(grpc_core::tcp_info* info, int fd) {
void TracedBuffer::AddNewEntry(TracedBuffer** head, uint32_t seq_no, int fd,
void* arg) {
GPR_DEBUG_ASSERT(head != nullptr);
- TracedBuffer* new_elem = new TracedBuffer(seq_no, arg);
+ TracedBuffer* new_elem = new TracedBuffer(seq_no, arg);
/* Store the current time as the sendmsg time. */
new_elem->ts_.sendmsg_time.time = gpr_now(GPR_CLOCK_REALTIME);
new_elem->ts_.scheduled_time.time = gpr_inf_past(GPR_CLOCK_REALTIME);
@@ -255,7 +255,7 @@ void TracedBuffer::ProcessTimestamp(TracedBuffer** head,
* restriction on the lifetime. */
timestamps_callback(elem->arg_, &(elem->ts_), GRPC_ERROR_NONE);
next = elem->next_;
- delete static_cast<TracedBuffer*>(elem);
+ delete static_cast<TracedBuffer*>(elem);
*head = elem = next;
break;
default:
@@ -274,7 +274,7 @@ void TracedBuffer::Shutdown(TracedBuffer** head, void* remaining,
while (elem != nullptr) {
timestamps_callback(elem->arg_, &(elem->ts_), shutdown_err);
auto* next = elem->next_;
- delete elem;
+ delete elem;
elem = next;
}
*head = nullptr;
@@ -297,10 +297,10 @@ namespace grpc_core {
void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*,
grpc_core::Timestamps*,
grpc_error* error)) {
- // Cast value of fn to void to avoid unused parameter warning.
- // Can't comment out the name because some compilers and formatters don't
- // like the sequence */* , which would arise from */*fn*/.
- (void)fn;
+ // Cast value of fn to void to avoid unused parameter warning.
+ // Can't comment out the name because some compilers and formatters don't
+ // like the sequence */* , which would arise from */*fn*/.
+ (void)fn;
gpr_log(GPR_DEBUG, "Timestamps callback is not enabled for this platform");
}
} /* namespace grpc_core */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h
index 54a2dc748f..6ee365c040 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h
@@ -115,10 +115,10 @@ struct Timestamps {
#ifdef GRPC_LINUX_ERRQUEUE
class TracedBuffer {
public:
- /** Use AddNewEntry function instead of using this directly. */
- TracedBuffer(uint32_t seq_no, void* arg)
- : seq_no_(seq_no), arg_(arg), next_(nullptr) {}
-
+ /** Use AddNewEntry function instead of using this directly. */
+ TracedBuffer(uint32_t seq_no, void* arg)
+ : seq_no_(seq_no), arg_(arg), next_(nullptr) {}
+
/** Add a new entry in the TracedBuffer list pointed to by head. Also saves
* sendmsg_time with the current timestamp. */
static void AddNewEntry(grpc_core::TracedBuffer** head, uint32_t seq_no,
@@ -147,7 +147,7 @@ class TracedBuffer {
class TracedBuffer {
public:
/* Dummy shutdown function */
- static void Shutdown(grpc_core::TracedBuffer** /*head*/, void* /*remaining*/,
+ static void Shutdown(grpc_core::TracedBuffer** /*head*/, void* /*remaining*/,
grpc_error* shutdown_err) {
GRPC_ERROR_UNREF(shutdown_err);
}
@@ -160,6 +160,6 @@ void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*,
grpc_core::Timestamps*,
grpc_error* error));
-} /* namespace grpc_core */
+} /* namespace grpc_core */
#endif /* GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc
index ed0ae17488..4586309638 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc
@@ -26,41 +26,41 @@
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/profiling/timers.h"
-namespace grpc_core {
+namespace grpc_core {
-DebugOnlyTraceFlag grpc_call_combiner_trace(false, "call_combiner");
-
-namespace {
-
-grpc_error* DecodeCancelStateError(gpr_atm cancel_state) {
+DebugOnlyTraceFlag grpc_call_combiner_trace(false, "call_combiner");
+
+namespace {
+
+grpc_error* DecodeCancelStateError(gpr_atm cancel_state) {
if (cancel_state & 1) {
return (grpc_error*)(cancel_state & ~static_cast<gpr_atm>(1));
}
return GRPC_ERROR_NONE;
}
-gpr_atm EncodeCancelStateError(grpc_error* error) {
+gpr_atm EncodeCancelStateError(grpc_error* error) {
return static_cast<gpr_atm>(1) | (gpr_atm)error;
}
-} // namespace
-
-CallCombiner::CallCombiner() {
- gpr_atm_no_barrier_store(&cancel_state_, 0);
- gpr_atm_no_barrier_store(&size_, 0);
-#ifdef GRPC_TSAN_ENABLED
- GRPC_CLOSURE_INIT(&tsan_closure_, TsanClosure, this,
- grpc_schedule_on_exec_ctx);
-#endif
-}
-
-CallCombiner::~CallCombiner() {
- GRPC_ERROR_UNREF(DecodeCancelStateError(cancel_state_));
-}
-
+} // namespace
+
+CallCombiner::CallCombiner() {
+ gpr_atm_no_barrier_store(&cancel_state_, 0);
+ gpr_atm_no_barrier_store(&size_, 0);
#ifdef GRPC_TSAN_ENABLED
-void CallCombiner::TsanClosure(void* arg, grpc_error* error) {
- CallCombiner* self = static_cast<CallCombiner*>(arg);
+ GRPC_CLOSURE_INIT(&tsan_closure_, TsanClosure, this,
+ grpc_schedule_on_exec_ctx);
+#endif
+}
+
+CallCombiner::~CallCombiner() {
+ GRPC_ERROR_UNREF(DecodeCancelStateError(cancel_state_));
+}
+
+#ifdef GRPC_TSAN_ENABLED
+void CallCombiner::TsanClosure(void* arg, grpc_error* error) {
+ CallCombiner* self = static_cast<CallCombiner*>(arg);
// We ref-count the lock, and check if it's already taken.
// If it was taken, we should do nothing. Otherwise, we will mark it as
// locked. Note that if two different threads try to do this, only one of
@@ -69,19 +69,19 @@ void CallCombiner::TsanClosure(void* arg, grpc_error* error) {
// TSAN will correctly produce an error.
//
// TODO(soheil): This only covers the callbacks scheduled by
- // CallCombiner::Start() and CallCombiner::Stop().
- // If in the future, a callback gets scheduled using other
- // mechanisms, we will need to add APIs to externally lock
- // call combiners.
- RefCountedPtr<TsanLock> lock = self->tsan_lock_;
+ // CallCombiner::Start() and CallCombiner::Stop().
+ // If in the future, a callback gets scheduled using other
+ // mechanisms, we will need to add APIs to externally lock
+ // call combiners.
+ RefCountedPtr<TsanLock> lock = self->tsan_lock_;
bool prev = false;
if (lock->taken.compare_exchange_strong(prev, true)) {
TSAN_ANNOTATE_RWLOCK_ACQUIRED(&lock->taken, true);
} else {
lock.reset();
}
- grpc_core::Closure::Run(DEBUG_LOCATION, self->original_closure_,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION, self->original_closure_,
+ GRPC_ERROR_REF(error));
if (lock != nullptr) {
TSAN_ANNOTATE_RWLOCK_RELEASED(&lock->taken, true);
bool prev = true;
@@ -90,17 +90,17 @@ void CallCombiner::TsanClosure(void* arg, grpc_error* error) {
}
#endif
-void CallCombiner::ScheduleClosure(grpc_closure* closure, grpc_error* error) {
+void CallCombiner::ScheduleClosure(grpc_closure* closure, grpc_error* error) {
#ifdef GRPC_TSAN_ENABLED
- original_closure_ = closure;
- ExecCtx::Run(DEBUG_LOCATION, &tsan_closure_, error);
+ original_closure_ = closure;
+ ExecCtx::Run(DEBUG_LOCATION, &tsan_closure_, error);
#else
- ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ ExecCtx::Run(DEBUG_LOCATION, closure, error);
#endif
}
#ifndef NDEBUG
-#define DEBUG_ARGS const char *file, int line,
+#define DEBUG_ARGS const char *file, int line,
#define DEBUG_FMT_STR "%s:%d: "
#define DEBUG_FMT_ARGS , file, line
#else
@@ -109,18 +109,18 @@ void CallCombiner::ScheduleClosure(grpc_closure* closure, grpc_error* error) {
#define DEBUG_FMT_ARGS
#endif
-void CallCombiner::Start(grpc_closure* closure, grpc_error* error,
- DEBUG_ARGS const char* reason) {
- GPR_TIMER_SCOPE("CallCombiner::Start", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+void CallCombiner::Start(grpc_closure* closure, grpc_error* error,
+ DEBUG_ARGS const char* reason) {
+ GPR_TIMER_SCOPE("CallCombiner::Start", 0);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO,
- "==> CallCombiner::Start() [%p] closure=%p [" DEBUG_FMT_STR
+ "==> CallCombiner::Start() [%p] closure=%p [" DEBUG_FMT_STR
"%s] error=%s",
- this, closure DEBUG_FMT_ARGS, reason, grpc_error_string(error));
+ this, closure DEBUG_FMT_ARGS, reason, grpc_error_string(error));
}
- size_t prev_size =
- static_cast<size_t>(gpr_atm_full_fetch_add(&size_, (gpr_atm)1));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ size_t prev_size =
+ static_cast<size_t>(gpr_atm_full_fetch_add(&size_, (gpr_atm)1));
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size,
prev_size + 1);
}
@@ -128,97 +128,97 @@ void CallCombiner::Start(grpc_closure* closure, grpc_error* error,
if (prev_size == 0) {
GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED();
GPR_TIMER_MARK("call_combiner_initiate", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " EXECUTING IMMEDIATELY");
}
// Queue was empty, so execute this closure immediately.
- ScheduleClosure(closure, error);
+ ScheduleClosure(closure, error);
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " QUEUING");
}
// Queue was not empty, so add closure to queue.
closure->error_data.error = error;
- queue_.Push(
- reinterpret_cast<MultiProducerSingleConsumerQueue::Node*>(closure));
+ queue_.Push(
+ reinterpret_cast<MultiProducerSingleConsumerQueue::Node*>(closure));
}
}
-void CallCombiner::Stop(DEBUG_ARGS const char* reason) {
- GPR_TIMER_SCOPE("CallCombiner::Stop", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
- gpr_log(GPR_INFO, "==> CallCombiner::Stop() [%p] [" DEBUG_FMT_STR "%s]",
- this DEBUG_FMT_ARGS, reason);
+void CallCombiner::Stop(DEBUG_ARGS const char* reason) {
+ GPR_TIMER_SCOPE("CallCombiner::Stop", 0);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ gpr_log(GPR_INFO, "==> CallCombiner::Stop() [%p] [" DEBUG_FMT_STR "%s]",
+ this DEBUG_FMT_ARGS, reason);
}
- size_t prev_size =
- static_cast<size_t>(gpr_atm_full_fetch_add(&size_, (gpr_atm)-1));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ size_t prev_size =
+ static_cast<size_t>(gpr_atm_full_fetch_add(&size_, (gpr_atm)-1));
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size,
prev_size - 1);
}
GPR_ASSERT(prev_size >= 1);
if (prev_size > 1) {
while (true) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " checking queue");
}
bool empty;
- grpc_closure* closure =
- reinterpret_cast<grpc_closure*>(queue_.PopAndCheckEnd(&empty));
+ grpc_closure* closure =
+ reinterpret_cast<grpc_closure*>(queue_.PopAndCheckEnd(&empty));
if (closure == nullptr) {
// This can happen either due to a race condition within the mpscq
- // code or because of a race with Start().
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ // code or because of a race with Start().
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " queue returned no result; checking again");
}
continue;
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " EXECUTING FROM QUEUE: closure=%p error=%s",
closure, grpc_error_string(closure->error_data.error));
}
- ScheduleClosure(closure, closure->error_data.error);
+ ScheduleClosure(closure, closure->error_data.error);
break;
}
- } else if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ } else if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, " queue empty");
}
}
-void CallCombiner::SetNotifyOnCancel(grpc_closure* closure) {
+void CallCombiner::SetNotifyOnCancel(grpc_closure* closure) {
GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL();
while (true) {
// Decode original state.
- gpr_atm original_state = gpr_atm_acq_load(&cancel_state_);
- grpc_error* original_error = DecodeCancelStateError(original_state);
+ gpr_atm original_state = gpr_atm_acq_load(&cancel_state_);
+ grpc_error* original_error = DecodeCancelStateError(original_state);
// If error is set, invoke the cancellation closure immediately.
// Otherwise, store the new closure.
if (original_error != GRPC_ERROR_NONE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO,
"call_combiner=%p: scheduling notify_on_cancel callback=%p "
"for pre-existing cancellation",
- this, closure);
+ this, closure);
}
- ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(original_error));
+ ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(original_error));
break;
} else {
- if (gpr_atm_full_cas(&cancel_state_, original_state, (gpr_atm)closure)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (gpr_atm_full_cas(&cancel_state_, original_state, (gpr_atm)closure)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO, "call_combiner=%p: setting notify_on_cancel=%p",
- this, closure);
+ this, closure);
}
// If we replaced an earlier closure, invoke the original
// closure with GRPC_ERROR_NONE. This allows callers to clean
// up any resources they may be holding for the callback.
if (original_state != 0) {
closure = (grpc_closure*)original_state;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO,
- "call_combiner=%p: scheduling old cancel callback=%p", this,
- closure);
+ "call_combiner=%p: scheduling old cancel callback=%p", this,
+ closure);
}
- ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
}
break;
}
@@ -227,30 +227,30 @@ void CallCombiner::SetNotifyOnCancel(grpc_closure* closure) {
}
}
-void CallCombiner::Cancel(grpc_error* error) {
+void CallCombiner::Cancel(grpc_error* error) {
GRPC_STATS_INC_CALL_COMBINER_CANCELLED();
while (true) {
- gpr_atm original_state = gpr_atm_acq_load(&cancel_state_);
- grpc_error* original_error = DecodeCancelStateError(original_state);
+ gpr_atm original_state = gpr_atm_acq_load(&cancel_state_);
+ grpc_error* original_error = DecodeCancelStateError(original_state);
if (original_error != GRPC_ERROR_NONE) {
GRPC_ERROR_UNREF(error);
break;
}
- if (gpr_atm_full_cas(&cancel_state_, original_state,
- EncodeCancelStateError(error))) {
+ if (gpr_atm_full_cas(&cancel_state_, original_state,
+ EncodeCancelStateError(error))) {
if (original_state != 0) {
grpc_closure* notify_on_cancel = (grpc_closure*)original_state;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO,
"call_combiner=%p: scheduling notify_on_cancel callback=%p",
- this, notify_on_cancel);
+ this, notify_on_cancel);
}
- ExecCtx::Run(DEBUG_LOCATION, notify_on_cancel, GRPC_ERROR_REF(error));
+ ExecCtx::Run(DEBUG_LOCATION, notify_on_cancel, GRPC_ERROR_REF(error));
}
break;
}
// cas failed, try again.
}
}
-
-} // namespace grpc_core
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h
index aed847c972..e9626c2e77 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h
@@ -27,12 +27,12 @@
#include <grpc/support/atm.h>
-#include "src/core/lib/gprpp/mpscq.h"
+#include "src/core/lib/gprpp/mpscq.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/dynamic_annotations.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
// A simple, lock-free mechanism for serializing activity related to a
// single call. This is similar to a combiner but is more lightweight.
@@ -43,78 +43,78 @@
// when it is done with the action that was kicked off by the original
// callback.
-namespace grpc_core {
-
-extern DebugOnlyTraceFlag grpc_call_combiner_trace;
-
-class CallCombiner {
- public:
- CallCombiner();
- ~CallCombiner();
-
-#ifndef NDEBUG
-#define GRPC_CALL_COMBINER_START(call_combiner, closure, error, reason) \
- (call_combiner)->Start((closure), (error), __FILE__, __LINE__, (reason))
-#define GRPC_CALL_COMBINER_STOP(call_combiner, reason) \
- (call_combiner)->Stop(__FILE__, __LINE__, (reason))
- /// Starts processing \a closure.
- void Start(grpc_closure* closure, grpc_error* error, const char* file,
- int line, const char* reason);
- /// Yields the call combiner to the next closure in the queue, if any.
- void Stop(const char* file, int line, const char* reason);
-#else
-#define GRPC_CALL_COMBINER_START(call_combiner, closure, error, reason) \
- (call_combiner)->Start((closure), (error), (reason))
-#define GRPC_CALL_COMBINER_STOP(call_combiner, reason) \
- (call_combiner)->Stop((reason))
- /// Starts processing \a closure.
- void Start(grpc_closure* closure, grpc_error* error, const char* reason);
- /// Yields the call combiner to the next closure in the queue, if any.
- void Stop(const char* reason);
-#endif
-
- /// Registers \a closure to be invoked when Cancel() is called.
- ///
- /// Once a closure is registered, it will always be scheduled exactly
- /// once; this allows the closure to hold references that will be freed
- /// regardless of whether or not the call was cancelled. If a cancellation
- /// does occur, the closure will be scheduled with the cancellation error;
- /// otherwise, it will be scheduled with GRPC_ERROR_NONE.
- ///
- /// The closure will be scheduled in the following cases:
- /// - If Cancel() was called prior to registering the closure, it will be
- /// scheduled immediately with the cancelation error.
- /// - If Cancel() is called after registering the closure, the closure will
- /// be scheduled with the cancellation error.
- /// - If SetNotifyOnCancel() is called again to register a new cancellation
- /// closure, the previous cancellation closure will be scheduled with
- /// GRPC_ERROR_NONE.
- ///
- /// If \a closure is NULL, then no closure will be invoked on
- /// cancellation; this effectively unregisters the previously set closure.
- /// However, most filters will not need to explicitly unregister their
- /// callbacks, as this is done automatically when the call is destroyed.
- /// Filters that schedule the cancellation closure on ExecCtx do not need
- /// to take a ref on the call stack to guarantee closure liveness. This is
- /// done by explicitly flushing ExecCtx after the unregistration during
- /// call destruction.
- void SetNotifyOnCancel(grpc_closure* closure);
-
- /// Indicates that the call has been cancelled.
- void Cancel(grpc_error* error);
-
- private:
- void ScheduleClosure(grpc_closure* closure, grpc_error* error);
-#ifdef GRPC_TSAN_ENABLED
- static void TsanClosure(void* arg, grpc_error* error);
-#endif
-
- gpr_atm size_ = 0; // size_t, num closures in queue or currently executing
- MultiProducerSingleConsumerQueue queue_;
+namespace grpc_core {
+
+extern DebugOnlyTraceFlag grpc_call_combiner_trace;
+
+class CallCombiner {
+ public:
+ CallCombiner();
+ ~CallCombiner();
+
+#ifndef NDEBUG
+#define GRPC_CALL_COMBINER_START(call_combiner, closure, error, reason) \
+ (call_combiner)->Start((closure), (error), __FILE__, __LINE__, (reason))
+#define GRPC_CALL_COMBINER_STOP(call_combiner, reason) \
+ (call_combiner)->Stop(__FILE__, __LINE__, (reason))
+ /// Starts processing \a closure.
+ void Start(grpc_closure* closure, grpc_error* error, const char* file,
+ int line, const char* reason);
+ /// Yields the call combiner to the next closure in the queue, if any.
+ void Stop(const char* file, int line, const char* reason);
+#else
+#define GRPC_CALL_COMBINER_START(call_combiner, closure, error, reason) \
+ (call_combiner)->Start((closure), (error), (reason))
+#define GRPC_CALL_COMBINER_STOP(call_combiner, reason) \
+ (call_combiner)->Stop((reason))
+ /// Starts processing \a closure.
+ void Start(grpc_closure* closure, grpc_error* error, const char* reason);
+ /// Yields the call combiner to the next closure in the queue, if any.
+ void Stop(const char* reason);
+#endif
+
+ /// Registers \a closure to be invoked when Cancel() is called.
+ ///
+ /// Once a closure is registered, it will always be scheduled exactly
+ /// once; this allows the closure to hold references that will be freed
+ /// regardless of whether or not the call was cancelled. If a cancellation
+ /// does occur, the closure will be scheduled with the cancellation error;
+ /// otherwise, it will be scheduled with GRPC_ERROR_NONE.
+ ///
+ /// The closure will be scheduled in the following cases:
+ /// - If Cancel() was called prior to registering the closure, it will be
+ /// scheduled immediately with the cancelation error.
+ /// - If Cancel() is called after registering the closure, the closure will
+ /// be scheduled with the cancellation error.
+ /// - If SetNotifyOnCancel() is called again to register a new cancellation
+ /// closure, the previous cancellation closure will be scheduled with
+ /// GRPC_ERROR_NONE.
+ ///
+ /// If \a closure is NULL, then no closure will be invoked on
+ /// cancellation; this effectively unregisters the previously set closure.
+ /// However, most filters will not need to explicitly unregister their
+ /// callbacks, as this is done automatically when the call is destroyed.
+ /// Filters that schedule the cancellation closure on ExecCtx do not need
+ /// to take a ref on the call stack to guarantee closure liveness. This is
+ /// done by explicitly flushing ExecCtx after the unregistration during
+ /// call destruction.
+ void SetNotifyOnCancel(grpc_closure* closure);
+
+ /// Indicates that the call has been cancelled.
+ void Cancel(grpc_error* error);
+
+ private:
+ void ScheduleClosure(grpc_closure* closure, grpc_error* error);
+#ifdef GRPC_TSAN_ENABLED
+ static void TsanClosure(void* arg, grpc_error* error);
+#endif
+
+ gpr_atm size_ = 0; // size_t, num closures in queue or currently executing
+ MultiProducerSingleConsumerQueue queue_;
// Either 0 (if not cancelled and no cancellation closure set),
// a grpc_closure* (if the lowest bit is 0),
// or a grpc_error* (if the lowest bit is 1).
- gpr_atm cancel_state_ = 0;
+ gpr_atm cancel_state_ = 0;
#ifdef GRPC_TSAN_ENABLED
// A fake ref-counted lock that is kept alive after the destruction of
// grpc_call_combiner, when we are running the original closure.
@@ -123,7 +123,7 @@ class CallCombiner {
// callback is called. However, original_closure is free to trigger
// anything on the call combiner (including destruction of grpc_call).
// Thus, we need a ref-counted structure that can outlive the call combiner.
- struct TsanLock : public RefCounted<TsanLock, NonPolymorphicRefCount> {
+ struct TsanLock : public RefCounted<TsanLock, NonPolymorphicRefCount> {
TsanLock() { TSAN_ANNOTATE_RWLOCK_CREATE(&taken); }
~TsanLock() { TSAN_ANNOTATE_RWLOCK_DESTROY(&taken); }
// To avoid double-locking by the same thread, we should acquire/release
@@ -131,9 +131,9 @@ class CallCombiner {
// true.
std::atomic<bool> taken{false};
};
- RefCountedPtr<TsanLock> tsan_lock_ = MakeRefCounted<TsanLock>();
- grpc_closure tsan_closure_;
- grpc_closure* original_closure_;
+ RefCountedPtr<TsanLock> tsan_lock_ = MakeRefCounted<TsanLock>();
+ grpc_closure tsan_closure_;
+ grpc_closure* original_closure_;
#endif
};
@@ -158,10 +158,10 @@ class CallCombinerClosureList {
//
// All but one of the closures in the list will be scheduled via
// GRPC_CALL_COMBINER_START(), and the remaining closure will be
- // scheduled via ExecCtx::Run(), which will eventually result
- // in yielding the call combiner. If the list is empty, then the call
+ // scheduled via ExecCtx::Run(), which will eventually result
+ // in yielding the call combiner. If the list is empty, then the call
// combiner will be yielded immediately.
- void RunClosures(CallCombiner* call_combiner) {
+ void RunClosures(CallCombiner* call_combiner) {
if (closures_.empty()) {
GRPC_CALL_COMBINER_STOP(call_combiner, "no closures to schedule");
return;
@@ -171,7 +171,7 @@ class CallCombinerClosureList {
GRPC_CALL_COMBINER_START(call_combiner, closure.closure, closure.error,
closure.reason);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
gpr_log(GPR_INFO,
"CallCombinerClosureList executing closure while already "
"holding call_combiner %p: closure=%p error=%s reason=%s",
@@ -179,13 +179,13 @@ class CallCombinerClosureList {
grpc_error_string(closures_[0].error), closures_[0].reason);
}
// This will release the call combiner.
- ExecCtx::Run(DEBUG_LOCATION, closures_[0].closure, closures_[0].error);
+ ExecCtx::Run(DEBUG_LOCATION, closures_[0].closure, closures_[0].error);
closures_.clear();
}
// Runs all closures in the call combiner, but does NOT yield the call
// combiner. All closures will be scheduled via GRPC_CALL_COMBINER_START().
- void RunClosuresWithoutYielding(CallCombiner* call_combiner) {
+ void RunClosuresWithoutYielding(CallCombiner* call_combiner) {
for (size_t i = 0; i < closures_.size(); ++i) {
auto& closure = closures_[i];
GRPC_CALL_COMBINER_START(call_combiner, closure.closure, closure.error,
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc
index 46914e5175..050d2d75c5 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc
@@ -18,29 +18,29 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/port.h"
#ifdef GRPC_CFSTREAM
#import <CoreFoundation/CoreFoundation.h>
#import "src/core/lib/iomgr/cfstream_handle.h"
-#include <grpc/grpc.h>
+#include <grpc/grpc.h>
#include <grpc/support/atm.h>
#include <grpc/support/sync.h>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/error_cfstream.h"
+#include "src/core/lib/iomgr/error_cfstream.h"
#include "src/core/lib/iomgr/ev_apple.h"
#include "src/core/lib/iomgr/exec_ctx.h"
extern grpc_core::TraceFlag grpc_tcp_trace;
-GrpcLibraryInitHolder::GrpcLibraryInitHolder() { grpc_init(); }
-
-GrpcLibraryInitHolder::~GrpcLibraryInitHolder() { grpc_shutdown(); }
-
+GrpcLibraryInitHolder::GrpcLibraryInitHolder() { grpc_init(); }
+
+GrpcLibraryInitHolder::~GrpcLibraryInitHolder() { grpc_shutdown(); }
+
void* CFStreamHandle::Retain(void* info) {
CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);
CFSTREAM_HANDLE_REF(handle, "retain");
@@ -62,8 +62,8 @@ void CFStreamHandle::ReadCallback(CFReadStreamRef stream,
void* client_callback_info) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
- grpc_error* error;
- CFErrorRef stream_error;
+ grpc_error* error;
+ CFErrorRef stream_error;
CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info);
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_DEBUG, "CFStream ReadCallback (%p, %p, %lu, %p)", handle,
@@ -78,15 +78,15 @@ void CFStreamHandle::ReadCallback(CFReadStreamRef stream,
handle->read_event_.SetReady();
break;
case kCFStreamEventErrorOccurred:
- stream_error = CFReadStreamCopyError(stream);
- error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "read error"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- CFRelease(stream_error);
- handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));
- handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));
- handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));
- GRPC_ERROR_UNREF(error);
+ stream_error = CFReadStreamCopyError(stream);
+ error = grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "read error"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ CFRelease(stream_error);
+ handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));
+ handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));
+ handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));
+ GRPC_ERROR_UNREF(error);
break;
default:
GPR_UNREACHABLE_CODE(return );
@@ -97,8 +97,8 @@ void CFStreamHandle::WriteCallback(CFWriteStreamRef stream,
void* clientCallBackInfo) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
- grpc_error* error;
- CFErrorRef stream_error;
+ grpc_error* error;
+ CFErrorRef stream_error;
CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo);
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_DEBUG, "CFStream WriteCallback (%p, %p, %lu, %p)", handle,
@@ -113,15 +113,15 @@ void CFStreamHandle::WriteCallback(CFWriteStreamRef stream,
handle->write_event_.SetReady();
break;
case kCFStreamEventErrorOccurred:
- stream_error = CFWriteStreamCopyError(stream);
- error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "write error"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
- CFRelease(stream_error);
- handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));
- handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));
- handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));
- GRPC_ERROR_UNREF(error);
+ stream_error = CFWriteStreamCopyError(stream);
+ error = grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "write error"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
+ CFRelease(stream_error);
+ handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));
+ handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));
+ handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));
+ GRPC_ERROR_UNREF(error);
break;
default:
GPR_UNREACHABLE_CODE(return );
@@ -191,7 +191,7 @@ void CFStreamHandle::Ref(const char* file, int line, const char* reason) {
void CFStreamHandle::Unref(const char* file, int line, const char* reason) {
if (grpc_tcp_trace.enabled()) {
gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);
- gpr_log(GPR_DEBUG,
+ gpr_log(GPR_DEBUG,
"CFStream Handle unref %p : %s %" PRIdPTR " -> %" PRIdPTR, this,
reason, val, val - 1);
}
@@ -200,11 +200,11 @@ void CFStreamHandle::Unref(const char* file, int line, const char* reason) {
}
}
-#else
-
-/* Creating a dummy function so that the grpc_cfstream library will be
- * non-empty.
- */
-void CFStreamDummy() {}
-
+#else
+
+/* Creating a dummy function so that the grpc_cfstream library will be
+ * non-empty.
+ */
+void CFStreamDummy() {}
+
#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h
index b0f0664a04..fda3bf0161 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h
@@ -29,26 +29,26 @@
#ifdef GRPC_CFSTREAM
#import <CoreFoundation/CoreFoundation.h>
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/lockfree_event.h"
-class GrpcLibraryInitHolder {
- public:
- GrpcLibraryInitHolder();
- virtual ~GrpcLibraryInitHolder();
-};
-
-class CFStreamHandle : public GrpcLibraryInitHolder {
+class GrpcLibraryInitHolder {
public:
+ GrpcLibraryInitHolder();
+ virtual ~GrpcLibraryInitHolder();
+};
+
+class CFStreamHandle : public GrpcLibraryInitHolder {
+ public:
static CFStreamHandle* CreateStreamHandle(CFReadStreamRef read_stream,
CFWriteStreamRef write_stream);
- /** Use CreateStreamHandle function instead of using this directly. */
- CFStreamHandle(CFReadStreamRef read_stream, CFWriteStreamRef write_stream);
- CFStreamHandle(const CFStreamHandle& ref) = delete;
- CFStreamHandle(CFStreamHandle&& ref) = delete;
+ /** Use CreateStreamHandle function instead of using this directly. */
+ CFStreamHandle(CFReadStreamRef read_stream, CFWriteStreamRef write_stream);
+ CFStreamHandle(const CFStreamHandle& ref) = delete;
+ CFStreamHandle(CFStreamHandle&& ref) = delete;
CFStreamHandle& operator=(const CFStreamHandle& rhs) = delete;
- ~CFStreamHandle() override;
+ ~CFStreamHandle() override;
void NotifyOnOpen(grpc_closure* closure);
void NotifyOnRead(grpc_closure* closure);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/closure.h b/contrib/libs/grpc/src/core/lib/iomgr/closure.h
index 6bb65340d1..633fe9381d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/closure.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/closure.h
@@ -22,14 +22,14 @@
#include <grpc/support/port_platform.h>
#include <assert.h>
-#include <stdbool.h>
-
+#include <stdbool.h>
+
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-
-#include "src/core/lib/gprpp/debug_location.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/gprpp/mpscq.h"
+
+#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/gprpp/mpscq.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/profiling/timers.h"
@@ -58,9 +58,9 @@ struct grpc_closure {
* space */
union {
grpc_closure* next;
- grpc_core::ManualConstructor<
- grpc_core::MultiProducerSingleConsumerQueue::Node>
- mpscq_node;
+ grpc_core::ManualConstructor<
+ grpc_core::MultiProducerSingleConsumerQueue::Node>
+ mpscq_node;
uintptr_t scratch;
} next_data;
@@ -91,10 +91,10 @@ struct grpc_closure {
#ifndef NDEBUG
inline grpc_closure* grpc_closure_init(const char* file, int line,
grpc_closure* closure,
- grpc_iomgr_cb_func cb, void* cb_arg) {
+ grpc_iomgr_cb_func cb, void* cb_arg) {
#else
inline grpc_closure* grpc_closure_init(grpc_closure* closure,
- grpc_iomgr_cb_func cb, void* cb_arg) {
+ grpc_iomgr_cb_func cb, void* cb_arg) {
#endif
closure->cb = cb;
closure->cb_arg = cb_arg;
@@ -113,10 +113,10 @@ inline grpc_closure* grpc_closure_init(grpc_closure* closure,
/** Initializes \a closure with \a cb and \a cb_arg. Returns \a closure. */
#ifndef NDEBUG
#define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \
- grpc_closure_init(__FILE__, __LINE__, closure, cb, cb_arg)
+ grpc_closure_init(__FILE__, __LINE__, closure, cb, cb_arg)
#else
#define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \
- grpc_closure_init(closure, cb, cb_arg)
+ grpc_closure_init(closure, cb, cb_arg)
#endif
namespace closure_impl {
@@ -138,19 +138,19 @@ inline void closure_wrapper(void* arg, grpc_error* error) {
#ifndef NDEBUG
inline grpc_closure* grpc_closure_create(const char* file, int line,
- grpc_iomgr_cb_func cb, void* cb_arg) {
+ grpc_iomgr_cb_func cb, void* cb_arg) {
#else
-inline grpc_closure* grpc_closure_create(grpc_iomgr_cb_func cb, void* cb_arg) {
+inline grpc_closure* grpc_closure_create(grpc_iomgr_cb_func cb, void* cb_arg) {
#endif
closure_impl::wrapped_closure* wc =
static_cast<closure_impl::wrapped_closure*>(gpr_malloc(sizeof(*wc)));
wc->cb = cb;
wc->cb_arg = cb_arg;
#ifndef NDEBUG
- grpc_closure_init(file, line, &wc->wrapper, closure_impl::closure_wrapper,
- wc);
+ grpc_closure_init(file, line, &wc->wrapper, closure_impl::closure_wrapper,
+ wc);
#else
- grpc_closure_init(&wc->wrapper, closure_impl::closure_wrapper, wc);
+ grpc_closure_init(&wc->wrapper, closure_impl::closure_wrapper, wc);
#endif
return &wc->wrapper;
}
@@ -158,10 +158,10 @@ inline grpc_closure* grpc_closure_create(grpc_iomgr_cb_func cb, void* cb_arg) {
/* Create a heap allocated closure: try to avoid except for very rare events */
#ifndef NDEBUG
#define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \
- grpc_closure_create(__FILE__, __LINE__, cb, cb_arg)
+ grpc_closure_create(__FILE__, __LINE__, cb, cb_arg)
#else
#define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \
- grpc_closure_create(cb, cb_arg)
+ grpc_closure_create(cb, cb_arg)
#endif
#define GRPC_CLOSURE_LIST_INIT \
@@ -223,33 +223,33 @@ inline bool grpc_closure_list_empty(grpc_closure_list closure_list) {
return closure_list.head == nullptr;
}
-namespace grpc_core {
-class Closure {
- public:
- static void Run(const DebugLocation& location, grpc_closure* closure,
- grpc_error* error) {
- (void)location;
- if (closure == nullptr) {
- GRPC_ERROR_UNREF(error);
- return;
- }
+namespace grpc_core {
+class Closure {
+ public:
+ static void Run(const DebugLocation& location, grpc_closure* closure,
+ grpc_error* error) {
+ (void)location;
+ if (closure == nullptr) {
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
#ifndef NDEBUG
- if (grpc_trace_closure.enabled()) {
- gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: run [%s:%d]",
- closure, closure->file_created, closure->line_created,
- location.file(), location.line());
- }
- GPR_ASSERT(closure->cb != nullptr);
+ if (grpc_trace_closure.enabled()) {
+ gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: run [%s:%d]",
+ closure, closure->file_created, closure->line_created,
+ location.file(), location.line());
+ }
+ GPR_ASSERT(closure->cb != nullptr);
#endif
- closure->cb(closure->cb_arg, error);
+ closure->cb(closure->cb_arg, error);
#ifndef NDEBUG
- if (grpc_trace_closure.enabled()) {
- gpr_log(GPR_DEBUG, "closure %p finished", closure);
+ if (grpc_trace_closure.enabled()) {
+ gpr_log(GPR_DEBUG, "closure %p finished", closure);
}
#endif
GRPC_ERROR_UNREF(error);
}
-};
-} // namespace grpc_core
+};
+} // namespace grpc_core
#endif /* GRPC_CORE_LIB_IOMGR_CLOSURE_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc b/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc
index 4b85766aef..7f491d78e8 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc
@@ -28,7 +28,7 @@
#include <grpc/support/log.h>
#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gprpp/mpscq.h"
+#include "src/core/lib/gprpp/mpscq.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/profiling/timers.h"
@@ -45,30 +45,30 @@ grpc_core::DebugOnlyTraceFlag grpc_combiner_trace(false, "combiner");
#define STATE_UNORPHANED 1
#define STATE_ELEM_COUNT_LOW_BIT 2
-static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* closure,
- grpc_error* error);
-static void combiner_finally_exec(grpc_core::Combiner* lock,
- grpc_closure* closure, grpc_error* error);
+static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* closure,
+ grpc_error* error);
+static void combiner_finally_exec(grpc_core::Combiner* lock,
+ grpc_closure* closure, grpc_error* error);
static void offload(void* arg, grpc_error* error);
-grpc_core::Combiner* grpc_combiner_create(void) {
- grpc_core::Combiner* lock = new grpc_core::Combiner();
+grpc_core::Combiner* grpc_combiner_create(void) {
+ grpc_core::Combiner* lock = new grpc_core::Combiner();
gpr_ref_init(&lock->refs, 1);
gpr_atm_no_barrier_store(&lock->state, STATE_UNORPHANED);
grpc_closure_list_init(&lock->final_list);
- GRPC_CLOSURE_INIT(&lock->offload, offload, lock, nullptr);
+ GRPC_CLOSURE_INIT(&lock->offload, offload, lock, nullptr);
GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p create", lock));
return lock;
}
-static void really_destroy(grpc_core::Combiner* lock) {
+static void really_destroy(grpc_core::Combiner* lock) {
GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p really_destroy", lock));
GPR_ASSERT(gpr_atm_no_barrier_load(&lock->state) == 0);
- delete lock;
+ delete lock;
}
-static void start_destroy(grpc_core::Combiner* lock) {
+static void start_destroy(grpc_core::Combiner* lock) {
gpr_atm old_state = gpr_atm_full_fetch_add(&lock->state, -STATE_UNORPHANED);
GRPC_COMBINER_TRACE(gpr_log(
GPR_INFO, "C:%p really_destroy old_state=%" PRIdPTR, lock, old_state));
@@ -89,21 +89,21 @@ static void start_destroy(grpc_core::Combiner* lock) {
#define GRPC_COMBINER_DEBUG_SPAM(op, delta)
#endif
-void grpc_combiner_unref(grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS) {
+void grpc_combiner_unref(grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS) {
GRPC_COMBINER_DEBUG_SPAM("UNREF", -1);
if (gpr_unref(&lock->refs)) {
start_destroy(lock);
}
}
-grpc_core::Combiner* grpc_combiner_ref(
- grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS) {
+grpc_core::Combiner* grpc_combiner_ref(
+ grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS) {
GRPC_COMBINER_DEBUG_SPAM(" REF", 1);
gpr_ref(&lock->refs);
return lock;
}
-static void push_last_on_exec_ctx(grpc_core::Combiner* lock) {
+static void push_last_on_exec_ctx(grpc_core::Combiner* lock) {
lock->next_combiner_on_this_exec_ctx = nullptr;
if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner == nullptr) {
grpc_core::ExecCtx::Get()->combiner_data()->active_combiner =
@@ -116,7 +116,7 @@ static void push_last_on_exec_ctx(grpc_core::Combiner* lock) {
}
}
-static void push_first_on_exec_ctx(grpc_core::Combiner* lock) {
+static void push_first_on_exec_ctx(grpc_core::Combiner* lock) {
lock->next_combiner_on_this_exec_ctx =
grpc_core::ExecCtx::Get()->combiner_data()->active_combiner;
grpc_core::ExecCtx::Get()->combiner_data()->active_combiner = lock;
@@ -125,8 +125,8 @@ static void push_first_on_exec_ctx(grpc_core::Combiner* lock) {
}
}
-static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* cl,
- grpc_error* error) {
+static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* cl,
+ grpc_error* error) {
GPR_TIMER_SCOPE("combiner.execute", 0);
GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS();
gpr_atm last = gpr_atm_full_fetch_add(&lock->state, STATE_ELEM_COUNT_LOW_BIT);
@@ -153,7 +153,7 @@ static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* cl,
GPR_ASSERT(last & STATE_UNORPHANED); // ensure lock has not been destroyed
assert(cl->cb);
cl->error_data.error = error;
- lock->queue.Push(cl->next_data.mpscq_node.get());
+ lock->queue.Push(cl->next_data.mpscq_node.get());
}
static void move_next() {
@@ -166,21 +166,21 @@ static void move_next() {
}
}
-static void offload(void* arg, grpc_error* /*error*/) {
- grpc_core::Combiner* lock = static_cast<grpc_core::Combiner*>(arg);
+static void offload(void* arg, grpc_error* /*error*/) {
+ grpc_core::Combiner* lock = static_cast<grpc_core::Combiner*>(arg);
push_last_on_exec_ctx(lock);
}
-static void queue_offload(grpc_core::Combiner* lock) {
+static void queue_offload(grpc_core::Combiner* lock) {
GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED();
move_next();
GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p queue_offload", lock));
- grpc_core::Executor::Run(&lock->offload, GRPC_ERROR_NONE);
+ grpc_core::Executor::Run(&lock->offload, GRPC_ERROR_NONE);
}
bool grpc_combiner_continue_exec_ctx() {
GPR_TIMER_SCOPE("combiner.continue_exec_ctx", 0);
- grpc_core::Combiner* lock =
+ grpc_core::Combiner* lock =
grpc_core::ExecCtx::Get()->combiner_data()->active_combiner;
if (lock == nullptr) {
return false;
@@ -201,11 +201,11 @@ bool grpc_combiner_continue_exec_ctx() {
// offload only if all the following conditions are true:
// 1. the combiner is contended and has more than one closure to execute
// 2. the current execution context needs to finish as soon as possible
- // 3. the current thread is not a worker for any background poller
- // 4. the DEFAULT executor is threaded
+ // 3. the current thread is not a worker for any background poller
+ // 4. the DEFAULT executor is threaded
if (contended && grpc_core::ExecCtx::Get()->IsReadyToFinish() &&
- !grpc_iomgr_is_any_background_poller_thread() &&
- grpc_core::Executor::IsThreadedDefault()) {
+ !grpc_iomgr_is_any_background_poller_thread() &&
+ grpc_core::Executor::IsThreadedDefault()) {
GPR_TIMER_MARK("offload_from_finished_exec_ctx", 0);
// this execution context wants to move on: schedule remaining work to be
// picked up on the executor
@@ -217,7 +217,7 @@ bool grpc_combiner_continue_exec_ctx() {
// peek to see if something new has shown up, and execute that with
// priority
(gpr_atm_acq_load(&lock->state) >> 1) > 1) {
- grpc_core::MultiProducerSingleConsumerQueue::Node* n = lock->queue.Pop();
+ grpc_core::MultiProducerSingleConsumerQueue::Node* n = lock->queue.Pop();
GRPC_COMBINER_TRACE(
gpr_log(GPR_INFO, "C:%p maybe_finish_one n=%p", lock, n));
if (n == nullptr) {
@@ -298,9 +298,9 @@ bool grpc_combiner_continue_exec_ctx() {
static void enqueue_finally(void* closure, grpc_error* error);
-static void combiner_finally_exec(grpc_core::Combiner* lock,
- grpc_closure* closure, grpc_error* error) {
- GPR_ASSERT(lock != nullptr);
+static void combiner_finally_exec(grpc_core::Combiner* lock,
+ grpc_closure* closure, grpc_error* error) {
+ GPR_ASSERT(lock != nullptr);
GPR_TIMER_SCOPE("combiner.execute_finally", 0);
GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS();
GRPC_COMBINER_TRACE(gpr_log(
@@ -308,10 +308,10 @@ static void combiner_finally_exec(grpc_core::Combiner* lock,
grpc_core::ExecCtx::Get()->combiner_data()->active_combiner));
if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner != lock) {
GPR_TIMER_MARK("slowpath", 0);
- // Using error_data.scratch to store the combiner so that it can be accessed
- // in enqueue_finally.
- closure->error_data.scratch = reinterpret_cast<uintptr_t>(lock);
- lock->Run(GRPC_CLOSURE_CREATE(enqueue_finally, closure, nullptr), error);
+ // Using error_data.scratch to store the combiner so that it can be accessed
+ // in enqueue_finally.
+ closure->error_data.scratch = reinterpret_cast<uintptr_t>(lock);
+ lock->Run(GRPC_CLOSURE_CREATE(enqueue_finally, closure, nullptr), error);
return;
}
@@ -322,18 +322,18 @@ static void combiner_finally_exec(grpc_core::Combiner* lock,
}
static void enqueue_finally(void* closure, grpc_error* error) {
- grpc_closure* cl = static_cast<grpc_closure*>(closure);
- combiner_finally_exec(
- reinterpret_cast<grpc_core::Combiner*>(cl->error_data.scratch), cl,
- GRPC_ERROR_REF(error));
+ grpc_closure* cl = static_cast<grpc_closure*>(closure);
+ combiner_finally_exec(
+ reinterpret_cast<grpc_core::Combiner*>(cl->error_data.scratch), cl,
+ GRPC_ERROR_REF(error));
}
-namespace grpc_core {
-void Combiner::Run(grpc_closure* closure, grpc_error* error) {
- combiner_exec(this, closure, error);
+namespace grpc_core {
+void Combiner::Run(grpc_closure* closure, grpc_error* error) {
+ combiner_exec(this, closure, error);
}
-void Combiner::FinallyRun(grpc_closure* closure, grpc_error* error) {
- combiner_finally_exec(this, closure, error);
+void Combiner::FinallyRun(grpc_closure* closure, grpc_error* error) {
+ combiner_finally_exec(this, closure, error);
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/combiner.h b/contrib/libs/grpc/src/core/lib/iomgr/combiner.h
index 32712066be..748295b857 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/combiner.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/combiner.h
@@ -27,40 +27,40 @@
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-namespace grpc_core {
-// TODO(yashkt) : Remove this class and replace it with a class that does not
-// use ExecCtx
-class Combiner {
- public:
- void Run(grpc_closure* closure, grpc_error* error);
- // TODO(yashkt) : Remove this method
- void FinallyRun(grpc_closure* closure, grpc_error* error);
- Combiner* next_combiner_on_this_exec_ctx = nullptr;
- MultiProducerSingleConsumerQueue queue;
- // either:
- // a pointer to the initiating exec ctx if that is the only exec_ctx that has
- // ever queued to this combiner, or NULL. If this is non-null, it's not
- // dereferencable (since the initiating exec_ctx may have gone out of scope)
- gpr_atm initiating_exec_ctx_or_null;
- // state is:
- // lower bit - zero if orphaned (STATE_UNORPHANED)
- // other bits - number of items queued on the lock (STATE_ELEM_COUNT_LOW_BIT)
- gpr_atm state;
- bool time_to_execute_final_list = false;
- grpc_closure_list final_list;
- grpc_closure offload;
- gpr_refcount refs;
-};
-} // namespace grpc_core
-
+namespace grpc_core {
+// TODO(yashkt) : Remove this class and replace it with a class that does not
+// use ExecCtx
+class Combiner {
+ public:
+ void Run(grpc_closure* closure, grpc_error* error);
+ // TODO(yashkt) : Remove this method
+ void FinallyRun(grpc_closure* closure, grpc_error* error);
+ Combiner* next_combiner_on_this_exec_ctx = nullptr;
+ MultiProducerSingleConsumerQueue queue;
+ // either:
+ // a pointer to the initiating exec ctx if that is the only exec_ctx that has
+ // ever queued to this combiner, or NULL. If this is non-null, it's not
+ // dereferencable (since the initiating exec_ctx may have gone out of scope)
+ gpr_atm initiating_exec_ctx_or_null;
+ // state is:
+ // lower bit - zero if orphaned (STATE_UNORPHANED)
+ // other bits - number of items queued on the lock (STATE_ELEM_COUNT_LOW_BIT)
+ gpr_atm state;
+ bool time_to_execute_final_list = false;
+ grpc_closure_list final_list;
+ grpc_closure offload;
+ gpr_refcount refs;
+};
+} // namespace grpc_core
+
// Provides serialized access to some resource.
// Each action queued on a combiner is executed serially in a borrowed thread.
// The actual thread executing actions may change over time (but there will only
-// ever be one at a time).
+// ever be one at a time).
// Initialize the lock, with an optional workqueue to shift load to when
// necessary
-grpc_core::Combiner* grpc_combiner_create(void);
+grpc_core::Combiner* grpc_combiner_create(void);
#ifndef NDEBUG
#define GRPC_COMBINER_DEBUG_ARGS \
@@ -77,9 +77,9 @@ grpc_core::Combiner* grpc_combiner_create(void);
// Ref/unref the lock, for when we're sharing the lock ownership
// Prefer to use the macros above
-grpc_core::Combiner* grpc_combiner_ref(
- grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS);
-void grpc_combiner_unref(grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS);
+grpc_core::Combiner* grpc_combiner_ref(
+ grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS);
+void grpc_combiner_unref(grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS);
bool grpc_combiner_continue_exec_ctx();
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc
index 37e0400102..8e447a8809 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc
@@ -23,8 +23,8 @@
grpc_core::TraceFlag grpc_tcp_trace(false, "tcp");
void grpc_endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool urgent) {
- ep->vtable->read(ep, slices, cb, urgent);
+ grpc_closure* cb, bool urgent) {
+ ep->vtable->read(ep, slices, cb, urgent);
}
void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h
index e704c3be49..b69e98b8d1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h
@@ -37,8 +37,8 @@ typedef struct grpc_endpoint grpc_endpoint;
typedef struct grpc_endpoint_vtable grpc_endpoint_vtable;
struct grpc_endpoint_vtable {
- void (*read)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb,
- bool urgent);
+ void (*read)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb,
+ bool urgent);
void (*write)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb,
void* arg);
void (*add_to_pollset)(grpc_endpoint* ep, grpc_pollset* pollset);
@@ -59,7 +59,7 @@ struct grpc_endpoint_vtable {
Valid slices may be placed into \a slices even when the callback is
invoked with error != GRPC_ERROR_NONE. */
void grpc_endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool urgent);
+ grpc_closure* cb, bool urgent);
y_absl::string_view grpc_endpoint_get_peer(grpc_endpoint* ep);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc
index d3a9c9b200..7c0f616a6c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc
@@ -134,7 +134,7 @@ static void CallReadCb(CFStreamEndpoint* ep, grpc_error* error) {
grpc_closure* cb = ep->read_cb;
ep->read_cb = nullptr;
ep->read_slices = nullptr;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
}
static void CallWriteCb(CFStreamEndpoint* ep, grpc_error* error) {
@@ -147,7 +147,7 @@ static void CallWriteCb(CFStreamEndpoint* ep, grpc_error* error) {
grpc_closure* cb = ep->write_cb;
ep->write_cb = nullptr;
ep->write_slices = nullptr;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
}
static void ReadAction(void* arg, grpc_error* error) {
@@ -184,7 +184,7 @@ static void ReadAction(void* arg, grpc_error* error) {
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Socket closed"), ep));
EP_UNREF(ep, "read");
} else {
- if (read_size < static_cast<CFIndex>(len)) {
+ if (read_size < static_cast<CFIndex>(len)) {
grpc_slice_buffer_trim_end(ep->read_slices, len - read_size, nullptr);
}
CallReadCb(ep, GRPC_ERROR_NONE);
@@ -219,7 +219,7 @@ static void WriteAction(void* arg, grpc_error* error) {
CallWriteCb(ep, error);
EP_UNREF(ep, "write");
} else {
- if (write_size < static_cast<CFIndex>(GRPC_SLICE_LENGTH(slice))) {
+ if (write_size < static_cast<CFIndex>(GRPC_SLICE_LENGTH(slice))) {
grpc_slice_buffer_undo_take_first(
ep->write_slices, grpc_slice_sub(slice, write_size, slice_len));
}
@@ -254,7 +254,7 @@ static void CFStreamReadAllocationDone(void* arg, grpc_error* error) {
}
static void CFStreamRead(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool urgent) {
+ grpc_closure* cb, bool urgent) {
CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep);
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_DEBUG, "CFStream endpoint:%p read (%p, %p) length:%zu", ep_impl,
@@ -265,11 +265,11 @@ static void CFStreamRead(grpc_endpoint* ep, grpc_slice_buffer* slices,
ep_impl->read_slices = slices;
grpc_slice_buffer_reset_and_unref_internal(slices);
EP_REF(ep_impl, "read");
- if (grpc_resource_user_alloc_slices(&ep_impl->slice_allocator,
- GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1,
- ep_impl->read_slices)) {
- ep_impl->stream_sync->NotifyOnRead(&ep_impl->read_action);
- }
+ if (grpc_resource_user_alloc_slices(&ep_impl->slice_allocator,
+ GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1,
+ ep_impl->read_slices)) {
+ ep_impl->stream_sync->NotifyOnRead(&ep_impl->read_action);
+ }
}
static void CFStreamWrite(grpc_endpoint* ep, grpc_slice_buffer* slices,
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_posix.cc
index 7f95da7365..698fd0a548 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_posix.cc
@@ -20,7 +20,7 @@
#include "src/core/lib/iomgr/port.h"
-#ifdef GRPC_POSIX_SOCKET_TCP
+#ifdef GRPC_POSIX_SOCKET_TCP
#include "src/core/lib/iomgr/endpoint_pair.h"
#include "src/core/lib/iomgr/socket_utils_posix.h"
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_windows.cc
index 9962809a27..99a71165f3 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_windows.cc
@@ -41,7 +41,7 @@ static void create_sockets(SOCKET sv[2]) {
int addr_len = sizeof(addr);
lst_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
- grpc_get_default_wsa_socket_flags());
+ grpc_get_default_wsa_socket_flags());
GPR_ASSERT(lst_sock != INVALID_SOCKET);
memset(&addr, 0, sizeof(addr));
@@ -54,7 +54,7 @@ static void create_sockets(SOCKET sv[2]) {
SOCKET_ERROR);
cli_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
- grpc_get_default_wsa_socket_flags());
+ grpc_get_default_wsa_socket_flags());
GPR_ASSERT(cli_sock != INVALID_SOCKET);
GPR_ASSERT(WSAConnect(cli_sock, (grpc_sockaddr*)&addr, addr_len, NULL, NULL,
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error.cc b/contrib/libs/grpc/src/core/lib/iomgr/error.cc
index c4b5c73952..f9df249328 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/error.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/error.cc
@@ -73,8 +73,8 @@ static const char* error_int_name(grpc_error_ints key) {
return "limit";
case GRPC_ERROR_INT_OCCURRED_DURING_WRITE:
return "occurred_during_write";
- case GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE:
- return "channel_connectivity_state";
+ case GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE:
+ return "channel_connectivity_state";
case GRPC_ERROR_INT_MAX:
GPR_UNREACHABLE_CODE(return "unknown");
}
@@ -156,8 +156,8 @@ static void unref_strs(grpc_error* err) {
for (size_t which = 0; which < GRPC_ERROR_STR_MAX; ++which) {
uint8_t slot = err->strs[which];
if (slot != UINT8_MAX) {
- grpc_slice_unref_internal(
- *reinterpret_cast<grpc_slice*>(err->arena + slot));
+ grpc_slice_unref_internal(
+ *reinterpret_cast<grpc_slice*>(err->arena + slot));
}
}
}
@@ -232,7 +232,7 @@ static void internal_set_int(grpc_error** err, grpc_error_ints which,
}
static void internal_set_str(grpc_error** err, grpc_error_strs which,
- const grpc_slice& value) {
+ const grpc_slice& value) {
uint8_t slot = (*err)->strs[which];
if (slot == UINT8_MAX) {
slot = get_placement(err, sizeof(value));
@@ -244,8 +244,8 @@ static void internal_set_str(grpc_error** err, grpc_error_strs which,
return;
}
} else {
- grpc_slice_unref_internal(
- *reinterpret_cast<grpc_slice*>((*err)->arena + slot));
+ grpc_slice_unref_internal(
+ *reinterpret_cast<grpc_slice*>((*err)->arena + slot));
}
(*err)->strs[which] = slot;
memcpy((*err)->arena + slot, &value, sizeof(value));
@@ -315,8 +315,8 @@ void grpc_enable_error_creation() {
gpr_atm_no_barrier_store(&g_error_creation_allowed, true);
}
-grpc_error* grpc_error_create(const char* file, int line,
- const grpc_slice& desc, grpc_error** referencing,
+grpc_error* grpc_error_create(const char* file, int line,
+ const grpc_slice& desc, grpc_error** referencing,
size_t num_referencing) {
GPR_TIMER_SCOPE("grpc_error_create", 0);
uint8_t initial_arena_capacity = static_cast<uint8_t>(
@@ -449,16 +449,16 @@ grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which,
struct special_error_status_map {
grpc_status_code code;
const char* msg;
- size_t len;
+ size_t len;
};
-const special_error_status_map error_status_map[] = {
- {GRPC_STATUS_OK, "", 0}, // GRPC_ERROR_NONE
- {GRPC_STATUS_INVALID_ARGUMENT, "", 0}, // GRPC_ERROR_RESERVED_1
- {GRPC_STATUS_RESOURCE_EXHAUSTED, "Out of memory",
- strlen("Out of memory")}, // GRPC_ERROR_OOM
- {GRPC_STATUS_INVALID_ARGUMENT, "", 0}, // GRPC_ERROR_RESERVED_2
- {GRPC_STATUS_CANCELLED, "Cancelled",
- strlen("Cancelled")}, // GRPC_ERROR_CANCELLED
+const special_error_status_map error_status_map[] = {
+ {GRPC_STATUS_OK, "", 0}, // GRPC_ERROR_NONE
+ {GRPC_STATUS_INVALID_ARGUMENT, "", 0}, // GRPC_ERROR_RESERVED_1
+ {GRPC_STATUS_RESOURCE_EXHAUSTED, "Out of memory",
+ strlen("Out of memory")}, // GRPC_ERROR_OOM
+ {GRPC_STATUS_INVALID_ARGUMENT, "", 0}, // GRPC_ERROR_RESERVED_2
+ {GRPC_STATUS_CANCELLED, "Cancelled",
+ strlen("Cancelled")}, // GRPC_ERROR_CANCELLED
};
bool grpc_error_get_int(grpc_error* err, grpc_error_ints which, intptr_t* p) {
@@ -477,7 +477,7 @@ bool grpc_error_get_int(grpc_error* err, grpc_error_ints which, intptr_t* p) {
}
grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which,
- const grpc_slice& str) {
+ const grpc_slice& str) {
GPR_TIMER_SCOPE("grpc_error_set_str", 0);
grpc_error* new_err = copy_error_and_unref(src);
internal_set_str(&new_err, which, str);
@@ -488,12 +488,12 @@ bool grpc_error_get_str(grpc_error* err, grpc_error_strs which,
grpc_slice* str) {
if (grpc_error_is_special(err)) {
if (which != GRPC_ERROR_STR_GRPC_MESSAGE) return false;
- const special_error_status_map& msg =
- error_status_map[reinterpret_cast<size_t>(err)];
- str->refcount = &grpc_core::kNoopRefcount;
- str->data.refcounted.bytes =
- reinterpret_cast<uint8_t*>(const_cast<char*>(msg.msg));
- str->data.refcounted.length = msg.len;
+ const special_error_status_map& msg =
+ error_status_map[reinterpret_cast<size_t>(err)];
+ str->refcount = &grpc_core::kNoopRefcount;
+ str->data.refcounted.bytes =
+ reinterpret_cast<uint8_t*>(const_cast<char*>(msg.msg));
+ str->data.refcounted.length = msg.len;
return true;
}
uint8_t slot = err->strs[which];
@@ -627,7 +627,7 @@ static char* key_str(grpc_error_strs which) {
return gpr_strdup(error_str_name(which));
}
-static char* fmt_str(const grpc_slice& slice) {
+static char* fmt_str(const grpc_slice& slice) {
char* s = nullptr;
size_t sz = 0;
size_t cap = 0;
@@ -805,9 +805,9 @@ grpc_error* grpc_wsa_error(const char* file, int line, int err,
}
#endif
-bool grpc_log_error(const char* what, grpc_error* error, const char* file,
- int line) {
- GPR_DEBUG_ASSERT(error != GRPC_ERROR_NONE);
+bool grpc_log_error(const char* what, grpc_error* error, const char* file,
+ int line) {
+ GPR_DEBUG_ASSERT(error != GRPC_ERROR_NONE);
const char* msg = grpc_error_string(error);
gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "%s: %s", what, msg);
GRPC_ERROR_UNREF(error);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error.h b/contrib/libs/grpc/src/core/lib/iomgr/error.h
index ac3ff87628..256c884f93 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/error.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/error.h
@@ -72,8 +72,8 @@ typedef enum {
GRPC_ERROR_INT_LIMIT,
/// chttp2: did the error occur while a write was in progress
GRPC_ERROR_INT_OCCURRED_DURING_WRITE,
- /// channel connectivity state associated with the error
- GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE,
+ /// channel connectivity state associated with the error
+ GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE,
/// Must always be last
GRPC_ERROR_INT_MAX,
@@ -140,9 +140,9 @@ void grpc_enable_error_creation();
const char* grpc_error_string(grpc_error* error);
/// Create an error - but use GRPC_ERROR_CREATE instead
-grpc_error* grpc_error_create(const char* file, int line,
- const grpc_slice& desc, grpc_error** referencing,
- size_t num_referencing);
+grpc_error* grpc_error_create(const char* file, int line,
+ const grpc_slice& desc, grpc_error** referencing,
+ size_t num_referencing);
/// Create an error (this is the preferred way of generating an error that is
/// not due to a system call - for system calls, use GRPC_OS_ERROR or
/// GRPC_WSA_ERROR as appropriate)
@@ -167,9 +167,9 @@ grpc_error* grpc_error_create(const char* file, int line,
grpc_error_create(__FILE__, __LINE__, grpc_slice_from_copied_string(desc), \
errs, count)
-#define GRPC_ERROR_CREATE_FROM_VECTOR(desc, error_list) \
- grpc_error_create_from_vector(__FILE__, __LINE__, desc, error_list)
-
+#define GRPC_ERROR_CREATE_FROM_VECTOR(desc, error_list) \
+ grpc_error_create_from_vector(__FILE__, __LINE__, desc, error_list)
+
#ifndef NDEBUG
grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line);
void grpc_error_do_unref(grpc_error* err, const char* file, int line);
@@ -198,25 +198,25 @@ inline void grpc_error_unref(grpc_error* err) {
#define GRPC_ERROR_UNREF(err) grpc_error_unref(err)
#endif
-// Consumes all the errors in the vector and forms a referencing error from
-// them. If the vector is empty, return GRPC_ERROR_NONE.
+// Consumes all the errors in the vector and forms a referencing error from
+// them. If the vector is empty, return GRPC_ERROR_NONE.
template <typename VectorType>
static grpc_error* grpc_error_create_from_vector(const char* file, int line,
const char* desc,
VectorType* error_list) {
- grpc_error* error = GRPC_ERROR_NONE;
- if (error_list->size() != 0) {
- error = grpc_error_create(file, line, grpc_slice_from_static_string(desc),
- error_list->data(), error_list->size());
- // Remove refs to all errors in error_list.
- for (size_t i = 0; i < error_list->size(); i++) {
- GRPC_ERROR_UNREF((*error_list)[i]);
- }
- error_list->clear();
- }
- return error;
-}
-
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (error_list->size() != 0) {
+ error = grpc_error_create(file, line, grpc_slice_from_static_string(desc),
+ error_list->data(), error_list->size());
+ // Remove refs to all errors in error_list.
+ for (size_t i = 0; i < error_list->size(); i++) {
+ GRPC_ERROR_UNREF((*error_list)[i]);
+ }
+ error_list->clear();
+ }
+ return error;
+}
+
grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which,
intptr_t value) GRPC_MUST_USE_RESULT;
/// It is an error to pass nullptr as `p`. Caller should allocate a dummy
@@ -225,7 +225,7 @@ bool grpc_error_get_int(grpc_error* error, grpc_error_ints which, intptr_t* p);
/// This call takes ownership of the slice; the error is responsible for
/// eventually unref-ing it.
grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which,
- const grpc_slice& str) GRPC_MUST_USE_RESULT;
+ const grpc_slice& str) GRPC_MUST_USE_RESULT;
/// Returns false if the specified string is not set.
/// Caller does NOT own the slice.
bool grpc_error_get_str(grpc_error* error, grpc_error_strs which,
@@ -262,15 +262,15 @@ grpc_error* grpc_wsa_error(const char* file, int line, int err,
#define GRPC_WSA_ERROR(err, call_name) \
grpc_wsa_error(__FILE__, __LINE__, err, call_name)
-bool grpc_log_error(const char* what, grpc_error* error, const char* file,
- int line);
-inline bool grpc_log_if_error(const char* what, grpc_error* error,
- const char* file, int line) {
- return error == GRPC_ERROR_NONE ? true
- : grpc_log_error(what, error, file, line);
-}
-
+bool grpc_log_error(const char* what, grpc_error* error, const char* file,
+ int line);
+inline bool grpc_log_if_error(const char* what, grpc_error* error,
+ const char* file, int line) {
+ return error == GRPC_ERROR_NONE ? true
+ : grpc_log_error(what, error, file, line);
+}
+
#define GRPC_LOG_IF_ERROR(what, error) \
- (grpc_log_if_error((what), (error), __FILE__, __LINE__))
+ (grpc_log_if_error((what), (error), __FILE__, __LINE__))
#endif /* GRPC_CORE_LIB_IOMGR_ERROR_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error_internal.h b/contrib/libs/grpc/src/core/lib/iomgr/error_internal.h
index 7b0cbd6d98..623b41351a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/error_internal.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/error_internal.h
@@ -49,7 +49,7 @@ struct grpc_error {
uint8_t strs[GRPC_ERROR_STR_MAX];
uint8_t times[GRPC_ERROR_TIME_MAX];
// The child errors are stored in the arena, but are effectively a linked list
- // structure, since they are contained within grpc_linked_error objects.
+ // structure, since they are contained within grpc_linked_error objects.
uint8_t first_err;
uint8_t last_err;
// The arena is dynamically reallocated with a grow factor of 1.5.
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc
index f09dcee0c0..690829e75a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc
@@ -219,7 +219,7 @@ struct grpc_pollset {
poll */
bool seen_inactive;
bool shutting_down; /* Is the pollset shutting down ? */
- grpc_closure* shutdown_closure; /* Called after shutdown is complete */
+ grpc_closure* shutdown_closure; /* Called after shutdown is complete */
/* Number of workers who are *about-to* attach themselves to the pollset
* worker list */
@@ -356,7 +356,7 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name.c_str());
fork_fd_list_add_grpc_fd(new_fd);
#ifndef NDEBUG
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, new_fd, fd_name.c_str());
}
#endif
@@ -387,13 +387,13 @@ static void fd_shutdown_internal(grpc_fd* fd, grpc_error* why,
if (fd->read_closure->SetShutdown(GRPC_ERROR_REF(why))) {
if (!releasing_fd) {
shutdown(fd->fd, SHUT_RDWR);
- } else {
- /* we need a dummy event for earlier linux versions. */
- epoll_event dummy_event;
- if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_DEL, fd->fd, &dummy_event) !=
- 0) {
- gpr_log(GPR_ERROR, "epoll_ctl failed: %s", strerror(errno));
- }
+ } else {
+ /* we need a dummy event for earlier linux versions. */
+ epoll_event dummy_event;
+ if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_DEL, fd->fd, &dummy_event) !=
+ 0) {
+ gpr_log(GPR_ERROR, "epoll_ctl failed: %s", strerror(errno));
+ }
}
fd->write_closure->SetShutdown(GRPC_ERROR_REF(why));
fd->error_closure->SetShutdown(GRPC_ERROR_REF(why));
@@ -424,7 +424,7 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
close(fd->fd);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, GRPC_ERROR_REF(error));
grpc_iomgr_unregister_object(&fd->iomgr_object);
fork_fd_list_remove_grpc_fd(fd);
@@ -627,8 +627,8 @@ static void pollset_maybe_finish_shutdown(grpc_pollset* pollset) {
if (pollset->shutdown_closure != nullptr && pollset->root_worker == nullptr &&
pollset->begin_refs == 0) {
GPR_TIMER_MARK("pollset_finish_shutdown", 0);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_closure,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_closure,
+ GRPC_ERROR_NONE);
pollset->shutdown_closure = nullptr;
}
}
@@ -663,7 +663,7 @@ static int poll_deadline_to_millis_timeout(grpc_millis millis) {
NOTE ON SYNCRHONIZATION: Similar to do_epoll_wait(), this function is only
called by g_active_poller thread. So there is no need for synchronization
when accessing fields in g_epoll_set */
-static grpc_error* process_epoll_events(grpc_pollset* /*pollset*/) {
+static grpc_error* process_epoll_events(grpc_pollset* /*pollset*/) {
GPR_TIMER_SCOPE("process_epoll_events", 0);
static const char* err_desc = "process_events";
@@ -736,7 +736,7 @@ static grpc_error* do_epoll_wait(grpc_pollset* ps, grpc_millis deadline) {
GRPC_STATS_INC_POLL_EVENTS_RETURNED(r);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "ps: %p poll got %d events", ps, r);
}
@@ -756,7 +756,7 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
worker->schedule_on_end_work = (grpc_closure_list)GRPC_CLOSURE_LIST_INIT;
pollset->begin_refs++;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p BEGIN_STARTS:%p", pollset, worker);
}
@@ -775,7 +775,7 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
retry_lock_neighborhood:
gpr_mu_lock(&neighborhood->mu);
gpr_mu_lock(&pollset->mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p BEGIN_REORG:%p kick_state=%s is_reassigning=%d",
pollset, worker, kick_state_string(worker->state),
is_reassigning);
@@ -827,7 +827,7 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
worker->initialized_cv = true;
gpr_cv_init(&worker->cv);
while (worker->state == UNKICKED && !pollset->shutting_down) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p BEGIN_WAIT:%p kick_state=%s shutdown=%d",
pollset, worker, kick_state_string(worker->state),
pollset->shutting_down);
@@ -844,7 +844,7 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
grpc_core::ExecCtx::Get()->InvalidateNow();
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p BEGIN_DONE:%p kick_state=%s shutdown=%d "
"kicked_without_poller: %d",
@@ -887,7 +887,7 @@ static bool check_neighborhood_for_available_poller(
case UNKICKED:
if (gpr_atm_no_barrier_cas(&g_active_poller, 0,
(gpr_atm)inspect_worker)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. choose next poller to be %p",
inspect_worker);
}
@@ -898,7 +898,7 @@ static bool check_neighborhood_for_available_poller(
gpr_cv_signal(&inspect_worker->cv);
}
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. beaten to choose next poller");
}
}
@@ -916,7 +916,7 @@ static bool check_neighborhood_for_available_poller(
} while (!found_worker && inspect_worker != inspect->root_worker);
}
if (!found_worker) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. mark pollset %p inactive", inspect);
}
inspect->seen_inactive = true;
@@ -936,7 +936,7 @@ static bool check_neighborhood_for_available_poller(
static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
grpc_pollset_worker** worker_hdl) {
GPR_TIMER_SCOPE("end_worker", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p END_WORKER:%p", pollset, worker);
}
if (worker_hdl != nullptr) *worker_hdl = nullptr;
@@ -946,7 +946,7 @@ static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
grpc_core::ExecCtx::Get()->closure_list());
if (gpr_atm_no_barrier_load(&g_active_poller) == (gpr_atm)worker) {
if (worker->next != worker && worker->next->state == UNKICKED) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. choose next poller to be peer %p", worker);
}
GPR_ASSERT(worker->next->initialized_cv);
@@ -998,7 +998,7 @@ static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
if (worker->initialized_cv) {
gpr_cv_destroy(&worker->cv);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. remove worker");
}
if (EMPTIED == worker_remove(pollset, worker)) {
@@ -1036,7 +1036,7 @@ static grpc_error* pollset_work(grpc_pollset* ps,
process the pending epoll events.
The reason for decoupling do_epoll_wait and process_epoll_events is to
- better distribute the work (i.e handling epoll events) across multiple
+ better distribute the work (i.e handling epoll events) across multiple
threads
process_epoll_events() returns very quickly: It just queues the work on
@@ -1067,7 +1067,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
GPR_TIMER_SCOPE("pollset_kick", 0);
GRPC_STATS_INC_POLLSET_KICK();
grpc_error* ret_err = GRPC_ERROR_NONE;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
std::vector<TString> log;
log.push_back(y_absl::StrFormat(
"PS:%p KICK:%p curps=%p curworker=%p root=%p", pollset, specific_worker,
@@ -1093,7 +1093,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
if (root_worker == nullptr) {
GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER();
pollset->kicked_without_poller = true;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kicked_without_poller");
}
goto done;
@@ -1101,14 +1101,14 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
grpc_pollset_worker* next_worker = root_worker->next;
if (root_worker->state == KICKED) {
GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. already kicked %p", root_worker);
}
SET_KICK_STATE(root_worker, KICKED);
goto done;
} else if (next_worker->state == KICKED) {
GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. already kicked %p", next_worker);
}
SET_KICK_STATE(next_worker, KICKED);
@@ -1118,7 +1118,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
root_worker == (grpc_pollset_worker*)gpr_atm_no_barrier_load(
&g_active_poller)) {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kicked %p", root_worker);
}
SET_KICK_STATE(root_worker, KICKED);
@@ -1126,7 +1126,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
goto done;
} else if (next_worker->state == UNKICKED) {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kicked %p", next_worker);
}
GPR_ASSERT(next_worker->initialized_cv);
@@ -1135,7 +1135,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
goto done;
} else if (next_worker->state == DESIGNATED_POLLER) {
if (root_worker->state != DESIGNATED_POLLER) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(
GPR_INFO,
" .. kicked root non-poller %p (initialized_cv=%d) (poller=%p)",
@@ -1149,7 +1149,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
goto done;
} else {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. non-root poller %p (root=%p)", next_worker,
root_worker);
}
@@ -1165,7 +1165,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
}
} else {
GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kicked while waking up");
}
goto done;
@@ -1175,14 +1175,14 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
}
if (specific_worker->state == KICKED) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. specific worker already kicked");
}
goto done;
} else if (gpr_tls_get(&g_current_thread_worker) ==
(intptr_t)specific_worker) {
GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. mark %p kicked", specific_worker);
}
SET_KICK_STATE(specific_worker, KICKED);
@@ -1190,7 +1190,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
} else if (specific_worker ==
(grpc_pollset_worker*)gpr_atm_no_barrier_load(&g_active_poller)) {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kick active poller");
}
SET_KICK_STATE(specific_worker, KICKED);
@@ -1198,7 +1198,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
goto done;
} else if (specific_worker->initialized_cv) {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kick waiting worker");
}
SET_KICK_STATE(specific_worker, KICKED);
@@ -1206,7 +1206,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
goto done;
} else {
GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, " .. kick non-waiting worker");
}
SET_KICK_STATE(specific_worker, KICKED);
@@ -1216,7 +1216,7 @@ done:
return ret_err;
}
-static void pollset_add_fd(grpc_pollset* /*pollset*/, grpc_fd* /*fd*/) {}
+static void pollset_add_fd(grpc_pollset* /*pollset*/, grpc_fd* /*fd*/) {}
/*******************************************************************************
* Pollset-set Definitions
@@ -1226,23 +1226,23 @@ static grpc_pollset_set* pollset_set_create(void) {
return (grpc_pollset_set*)(static_cast<intptr_t>(0xdeafbeef));
}
-static void pollset_set_destroy(grpc_pollset_set* /*pss*/) {}
+static void pollset_set_destroy(grpc_pollset_set* /*pss*/) {}
-static void pollset_set_add_fd(grpc_pollset_set* /*pss*/, grpc_fd* /*fd*/) {}
+static void pollset_set_add_fd(grpc_pollset_set* /*pss*/, grpc_fd* /*fd*/) {}
-static void pollset_set_del_fd(grpc_pollset_set* /*pss*/, grpc_fd* /*fd*/) {}
+static void pollset_set_del_fd(grpc_pollset_set* /*pss*/, grpc_fd* /*fd*/) {}
-static void pollset_set_add_pollset(grpc_pollset_set* /*pss*/,
- grpc_pollset* /*ps*/) {}
+static void pollset_set_add_pollset(grpc_pollset_set* /*pss*/,
+ grpc_pollset* /*ps*/) {}
-static void pollset_set_del_pollset(grpc_pollset_set* /*pss*/,
- grpc_pollset* /*ps*/) {}
+static void pollset_set_del_pollset(grpc_pollset_set* /*pss*/,
+ grpc_pollset* /*ps*/) {}
-static void pollset_set_add_pollset_set(grpc_pollset_set* /*bag*/,
- grpc_pollset_set* /*item*/) {}
+static void pollset_set_add_pollset_set(grpc_pollset_set* /*bag*/,
+ grpc_pollset_set* /*item*/) {}
-static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/,
- grpc_pollset_set* /*item*/) {}
+static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/,
+ grpc_pollset_set* /*item*/) {}
/*******************************************************************************
* Event engine binding
@@ -1252,11 +1252,11 @@ static bool is_any_background_poller_thread(void) { return false; }
static void shutdown_background_closure(void) {}
-static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
- grpc_error* /*error*/) {
- return false;
-}
-
+static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
+ grpc_error* /*error*/) {
+ return false;
+}
+
static void shutdown_engine(void) {
fd_global_shutdown();
pollset_global_shutdown();
@@ -1303,7 +1303,7 @@ static const grpc_event_engine_vtable vtable = {
is_any_background_poller_thread,
shutdown_background_closure,
shutdown_engine,
- add_closure_to_background_poller,
+ add_closure_to_background_poller,
};
/* Called by the child process's post-fork handler to close open fds, including
@@ -1324,8 +1324,8 @@ static void reset_event_manager_on_fork() {
/* It is possible that GLIBC has epoll but the underlying kernel doesn't.
* Create epoll_fd (epoll_set_init() takes care of that) to make sure epoll
* support is available */
-const grpc_event_engine_vtable* grpc_init_epoll1_linux(
- bool /*explicit_request*/) {
+const grpc_event_engine_vtable* grpc_init_epoll1_linux(
+ bool /*explicit_request*/) {
if (!grpc_has_wakeup_fd()) {
gpr_log(GPR_ERROR, "Skipping epoll1 because of no wakeup fd.");
return nullptr;
@@ -1356,8 +1356,8 @@ const grpc_event_engine_vtable* grpc_init_epoll1_linux(
#include "src/core/lib/iomgr/ev_epoll1_linux.h"
/* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return
* NULL */
-const grpc_event_engine_vtable* grpc_init_epoll1_linux(
- bool /*explicit_request*/) {
+const grpc_event_engine_vtable* grpc_init_epoll1_linux(
+ bool /*explicit_request*/) {
return nullptr;
}
#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLL1) */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc
index 2dd9bbdffd..c541a0c89b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc
@@ -51,8 +51,8 @@
#include "src/core/lib/gpr/tls.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/block_annotate.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/is_epollexclusive_available.h"
@@ -90,7 +90,7 @@ typedef struct pollable pollable;
/// - PO_MULTI - a pollable containing many fds
struct pollable {
pollable_type type; // immutable
- grpc_core::RefCount refs;
+ grpc_core::RefCount refs;
int epfd;
grpc_wakeup_fd wakeup;
@@ -135,26 +135,26 @@ static TString pollable_desc(pollable* p) {
static pollable* g_empty_pollable;
static grpc_error* pollable_create(pollable_type type, pollable** p);
-static pollable* pollable_ref(pollable* p,
- const grpc_core::DebugLocation& dbg_loc,
- const char* reason) {
- p->refs.Ref(dbg_loc, reason);
- return p;
-}
-static void pollable_unref(pollable* p, const grpc_core::DebugLocation& dbg_loc,
- const char* reason) {
- if (p == nullptr) return;
- if (GPR_UNLIKELY(p != nullptr && p->refs.Unref(dbg_loc, reason))) {
- GRPC_FD_TRACE("pollable_unref: Closing epfd: %d", p->epfd);
- close(p->epfd);
- grpc_wakeup_fd_destroy(&p->wakeup);
- gpr_mu_destroy(&p->owner_orphan_mu);
- gpr_mu_destroy(&p->mu);
- gpr_free(p);
- }
-}
-#define POLLABLE_REF(p, r) pollable_ref((p), DEBUG_LOCATION, (r))
-#define POLLABLE_UNREF(p, r) pollable_unref((p), DEBUG_LOCATION, (r))
+static pollable* pollable_ref(pollable* p,
+ const grpc_core::DebugLocation& dbg_loc,
+ const char* reason) {
+ p->refs.Ref(dbg_loc, reason);
+ return p;
+}
+static void pollable_unref(pollable* p, const grpc_core::DebugLocation& dbg_loc,
+ const char* reason) {
+ if (p == nullptr) return;
+ if (GPR_UNLIKELY(p != nullptr && p->refs.Unref(dbg_loc, reason))) {
+ GRPC_FD_TRACE("pollable_unref: Closing epfd: %d", p->epfd);
+ close(p->epfd);
+ grpc_wakeup_fd_destroy(&p->wakeup);
+ gpr_mu_destroy(&p->owner_orphan_mu);
+ gpr_mu_destroy(&p->mu);
+ gpr_free(p);
+ }
+}
+#define POLLABLE_REF(p, r) pollable_ref((p), DEBUG_LOCATION, (r))
+#define POLLABLE_UNREF(p, r) pollable_unref((p), DEBUG_LOCATION, (r))
/*******************************************************************************
* Fd Declarations
@@ -172,7 +172,7 @@ struct grpc_fd {
TString fd_name = y_absl::StrCat(name, " fd=", fd);
grpc_iomgr_register_object(&iomgr_object, fd_name.c_str());
#ifndef NDEBUG
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, this, fd_name.c_str());
}
#endif
@@ -297,7 +297,7 @@ struct grpc_pollset {
*/
struct grpc_pollset_set {
- grpc_core::RefCount refs;
+ grpc_core::RefCount refs;
gpr_mu mu;
grpc_pollset_set* parent;
@@ -349,30 +349,30 @@ static gpr_mu fd_freelist_mu;
#define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__)
static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file,
int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG,
"FD %d %p ref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]",
fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst),
gpr_atm_no_barrier_load(&fd->refst) + n, reason, file, line);
}
#else
-#define REF_BY(fd, n, reason) \
- do { \
- ref_by(fd, n); \
- (void)(reason); \
- } while (0)
-#define UNREF_BY(fd, n, reason) \
- do { \
- unref_by(fd, n); \
- (void)(reason); \
- } while (0)
+#define REF_BY(fd, n, reason) \
+ do { \
+ ref_by(fd, n); \
+ (void)(reason); \
+ } while (0)
+#define UNREF_BY(fd, n, reason) \
+ do { \
+ unref_by(fd, n); \
+ (void)(reason); \
+ } while (0)
static void ref_by(grpc_fd* fd, int n) {
#endif
GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0);
}
/* Uninitialize and add to the freelist */
-static void fd_destroy(void* arg, grpc_error* /*error*/) {
+static void fd_destroy(void* arg, grpc_error* /*error*/) {
grpc_fd* fd = static_cast<grpc_fd*>(arg);
fd->destroy();
@@ -386,7 +386,7 @@ static void fd_destroy(void* arg, grpc_error* /*error*/) {
#ifndef NDEBUG
static void unref_by(grpc_fd* fd, int n, const char* reason, const char* file,
int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG,
"FD %d %p unref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]",
fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst),
@@ -397,8 +397,8 @@ static void unref_by(grpc_fd* fd, int n) {
#endif
gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n);
if (old == n) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
GRPC_CLOSURE_CREATE(fd_destroy, fd, grpc_schedule_on_exec_ctx),
GRPC_ERROR_NONE);
} else {
@@ -470,13 +470,13 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
// Otherwise, we will receive epoll events after we release the FD.
epoll_event ev_fd;
memset(&ev_fd, 0, sizeof(ev_fd));
- if (pollable_obj != nullptr) { // For PO_FD.
- epoll_ctl(pollable_obj->epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd);
- }
- for (size_t i = 0; i < fd->pollset_fds.size(); ++i) { // For PO_MULTI.
- const int epfd = fd->pollset_fds[i];
- epoll_ctl(epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd);
+ if (pollable_obj != nullptr) { // For PO_FD.
+ epoll_ctl(pollable_obj->epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd);
}
+ for (size_t i = 0; i < fd->pollset_fds.size(); ++i) { // For PO_MULTI.
+ const int epfd = fd->pollset_fds[i];
+ epoll_ctl(epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd);
+ }
*release_fd = fd->fd;
} else {
close(fd->fd);
@@ -492,7 +492,7 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
to be alive (and not added to freelist) until the end of this function */
REF_BY(fd, 1, reason);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, fd->on_done_closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, fd->on_done_closure, GRPC_ERROR_NONE);
if (pollable_obj) {
gpr_mu_unlock(&pollable_obj->owner_orphan_mu);
@@ -591,7 +591,7 @@ static grpc_error* pollable_create(pollable_type type, pollable** p) {
}
(*p)->type = type;
- new (&(*p)->refs) grpc_core::RefCount(1, &grpc_trace_pollable_refcount);
+ new (&(*p)->refs) grpc_core::RefCount(1, &grpc_trace_pollable_refcount);
gpr_mu_init(&(*p)->mu);
(*p)->epfd = epfd;
(*p)->owner_fd = nullptr;
@@ -609,7 +609,7 @@ static grpc_error* pollable_add_fd(pollable* p, grpc_fd* fd) {
grpc_error* error = GRPC_ERROR_NONE;
static const char* err_desc = "pollable_add_fd";
const int epfd = p->epfd;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "add fd %p (%d) to pollable %p", fd, fd->fd, p);
}
@@ -657,7 +657,7 @@ static void pollset_global_shutdown(void) {
/* pollset->mu must be held while calling this function */
static void pollset_maybe_finish_shutdown(grpc_pollset* pollset) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p (pollable:%p) maybe_finish_shutdown sc=%p (target:!NULL) "
"rw=%p (target:NULL) cpsc=%d (target:0)",
@@ -667,8 +667,8 @@ static void pollset_maybe_finish_shutdown(grpc_pollset* pollset) {
if (pollset->shutdown_closure != nullptr && pollset->root_worker == nullptr &&
pollset->containing_pollset_set_count == 0) {
GPR_TIMER_MARK("pollset_finish_shutdown", 0);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_closure,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_closure,
+ GRPC_ERROR_NONE);
pollset->shutdown_closure = nullptr;
pollset->already_shutdown = true;
}
@@ -683,14 +683,14 @@ static grpc_error* kick_one_worker(grpc_pollset_worker* specific_worker) {
grpc_core::MutexLock lock(&p->mu);
GPR_ASSERT(specific_worker != nullptr);
if (specific_worker->kicked) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p kicked_specific_but_already_kicked", p);
}
GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
return GRPC_ERROR_NONE;
}
if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p kicked_specific_but_awake", p);
}
GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
@@ -699,7 +699,7 @@ static grpc_error* kick_one_worker(grpc_pollset_worker* specific_worker) {
}
if (specific_worker == p->root_worker) {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p kicked_specific_via_wakeup_fd", p);
}
specific_worker->kicked = true;
@@ -708,7 +708,7 @@ static grpc_error* kick_one_worker(grpc_pollset_worker* specific_worker) {
}
if (specific_worker->initialized_cv) {
GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p kicked_specific_via_cv", p);
}
specific_worker->kicked = true;
@@ -724,7 +724,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
grpc_pollset_worker* specific_worker) {
GPR_TIMER_SCOPE("pollset_kick", 0);
GRPC_STATS_INC_POLLSET_KICK();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p kick %p tls_pollset=%p tls_worker=%p pollset.root_worker=%p",
pollset, specific_worker,
@@ -734,7 +734,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
if (specific_worker == nullptr) {
if (gpr_tls_get(&g_current_thread_pollset) != (intptr_t)pollset) {
if (pollset->root_worker == nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p kicked_any_without_poller", pollset);
}
GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER();
@@ -760,7 +760,7 @@ static grpc_error* pollset_kick(grpc_pollset* pollset,
pollset->root_worker->links[PWLINK_POLLSET].next);
}
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p kicked_any_but_awake", pollset);
}
GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
@@ -878,7 +878,7 @@ static grpc_error* pollable_process_events(grpc_pollset* pollset,
struct epoll_event* ev = &pollable_obj->events[n];
void* data_ptr = ev->data.ptr;
if (1 & (intptr_t)data_ptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p got pollset_wakeup %p", pollset, data_ptr);
}
append_error(&error,
@@ -896,7 +896,7 @@ static grpc_error* pollable_process_events(grpc_pollset* pollset,
bool write_ev = (ev->events & EPOLLOUT) != 0;
bool err_fallback = error && !track_err;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p got fd %p: cancel=%d read=%d "
"write=%d",
@@ -928,7 +928,7 @@ static grpc_error* pollable_epoll(pollable* p, grpc_millis deadline) {
GPR_TIMER_SCOPE("pollable_epoll", 0);
int timeout = poll_deadline_to_millis_timeout(deadline);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "POLLABLE:%p[%s] poll for %dms", p,
pollable_desc(p).c_str(), timeout);
}
@@ -947,7 +947,7 @@ static grpc_error* pollable_epoll(pollable* p, grpc_millis deadline) {
if (r < 0) return GRPC_OS_ERROR(errno, "epoll_wait");
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "POLLABLE:%p got %d events", p, r);
}
@@ -1017,7 +1017,7 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
worker->initialized_cv = true;
gpr_cv_init(&worker->cv);
gpr_mu_unlock(&pollset->mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace) &&
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace) &&
worker->pollable_obj->root_worker != worker) {
gpr_log(GPR_INFO, "PS:%p wait %p w=%p for %dms", pollset,
worker->pollable_obj, worker,
@@ -1026,18 +1026,18 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
while (do_poll && worker->pollable_obj->root_worker != worker) {
if (gpr_cv_wait(&worker->cv, &worker->pollable_obj->mu,
grpc_millis_to_timespec(deadline, GPR_CLOCK_REALTIME))) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p timeout_wait %p w=%p", pollset,
worker->pollable_obj, worker);
}
do_poll = false;
} else if (worker->kicked) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PS:%p wakeup %p w=%p", pollset,
worker->pollable_obj, worker);
}
do_poll = false;
- } else if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace) &&
+ } else if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace) &&
worker->pollable_obj->root_worker != worker) {
gpr_log(GPR_INFO, "PS:%p spurious_wakeup %p w=%p", pollset,
worker->pollable_obj, worker);
@@ -1053,7 +1053,7 @@ static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
}
static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
- grpc_pollset_worker** /*worker_hdl*/) {
+ grpc_pollset_worker** /*worker_hdl*/) {
GPR_TIMER_SCOPE("end_worker", 0);
gpr_mu_lock(&pollset->mu);
gpr_mu_lock(&worker->pollable_obj->mu);
@@ -1088,7 +1088,7 @@ static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
}
#ifndef NDEBUG
-static long sys_gettid(void) { return syscall(__NR_gettid); }
+static long sys_gettid(void) { return syscall(__NR_gettid); }
#endif
/* pollset->mu lock must be held by the caller before calling this.
@@ -1108,9 +1108,9 @@ static grpc_error* pollset_work(grpc_pollset* pollset,
#define WORKER_PTR (&worker)
#endif
#ifndef NDEBUG
- WORKER_PTR->originator = sys_gettid();
+ WORKER_PTR->originator = sys_gettid();
#endif
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p work hdl=%p worker=%p now=%" PRId64 " deadline=%" PRId64
" kwp=%d pollable=%p",
@@ -1151,7 +1151,7 @@ static grpc_error* pollset_transition_pollable_from_empty_to_fd_locked(
grpc_pollset* pollset, grpc_fd* fd) {
static const char* err_desc = "pollset_transition_pollable_from_empty_to_fd";
grpc_error* error = GRPC_ERROR_NONE;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p add fd %p (%d); transition pollable from empty to fd",
pollset, fd, fd->fd);
@@ -1167,7 +1167,7 @@ static grpc_error* pollset_transition_pollable_from_fd_to_multi_locked(
grpc_pollset* pollset, grpc_fd* and_add_fd) {
static const char* err_desc = "pollset_transition_pollable_from_fd_to_multi";
grpc_error* error = GRPC_ERROR_NONE;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(
GPR_INFO,
"PS:%p add fd %p (%d); transition pollable from fd %p to multipoller",
@@ -1239,7 +1239,7 @@ static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset,
error = pollable_create(PO_MULTI, &pollset->active_pollable);
/* Any workers currently polling on this pollset must now be woked up so
* that they can pick up the new active_pollable */
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO,
"PS:%p active pollable transition from empty to multi",
pollset);
@@ -1280,7 +1280,7 @@ static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset,
static void pollset_add_fd(grpc_pollset* pollset, grpc_fd* fd) {
GPR_TIMER_SCOPE("pollset_add_fd", 0);
- // We never transition from PO_MULTI to other modes (i.e., PO_FD or PO_EMPTY)
+ // We never transition from PO_MULTI to other modes (i.e., PO_FD or PO_EMPTY)
// and, thus, it is safe to simply store and check whether the FD has already
// been added to the active pollable previously.
if (gpr_atm_acq_load(&pollset->active_pollable_type) == PO_MULTI &&
@@ -1317,13 +1317,13 @@ static grpc_pollset_set* pollset_set_create(void) {
grpc_pollset_set* pss =
static_cast<grpc_pollset_set*>(gpr_zalloc(sizeof(*pss)));
gpr_mu_init(&pss->mu);
- new (&pss->refs) grpc_core::RefCount();
+ new (&pss->refs) grpc_core::RefCount();
return pss;
}
static void pollset_set_unref(grpc_pollset_set* pss) {
if (pss == nullptr) return;
- if (GPR_LIKELY(!pss->refs.Unref())) return;
+ if (GPR_LIKELY(!pss->refs.Unref())) return;
pollset_set_unref(pss->parent);
gpr_mu_destroy(&pss->mu);
for (size_t i = 0; i < pss->pollset_count; i++) {
@@ -1343,7 +1343,7 @@ static void pollset_set_unref(grpc_pollset_set* pss) {
static void pollset_set_add_fd(grpc_pollset_set* pss, grpc_fd* fd) {
GPR_TIMER_SCOPE("pollset_set_add_fd", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PSS:%p: add fd %p (%d)", pss, fd, fd->fd);
}
grpc_error* error = GRPC_ERROR_NONE;
@@ -1367,7 +1367,7 @@ static void pollset_set_add_fd(grpc_pollset_set* pss, grpc_fd* fd) {
static void pollset_set_del_fd(grpc_pollset_set* pss, grpc_fd* fd) {
GPR_TIMER_SCOPE("pollset_set_del_fd", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PSS:%p: del fd %p", pss, fd);
}
pss = pss_lock_adam(pss);
@@ -1388,7 +1388,7 @@ static void pollset_set_del_fd(grpc_pollset_set* pss, grpc_fd* fd) {
static void pollset_set_del_pollset(grpc_pollset_set* pss, grpc_pollset* ps) {
GPR_TIMER_SCOPE("pollset_set_del_pollset", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PSS:%p: del pollset %p", pss, ps);
}
pss = pss_lock_adam(pss);
@@ -1440,7 +1440,7 @@ static grpc_error* add_fds_to_pollsets(grpc_fd** fds, size_t fd_count,
static void pollset_set_add_pollset(grpc_pollset_set* pss, grpc_pollset* ps) {
GPR_TIMER_SCOPE("pollset_set_add_pollset", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PSS:%p: add pollset %p", pss, ps);
}
grpc_error* error = GRPC_ERROR_NONE;
@@ -1477,7 +1477,7 @@ static void pollset_set_add_pollset(grpc_pollset_set* pss, grpc_pollset* ps) {
static void pollset_set_add_pollset_set(grpc_pollset_set* a,
grpc_pollset_set* b) {
GPR_TIMER_SCOPE("pollset_set_add_pollset_set", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PSS: merge (%p, %p)", a, b);
}
grpc_error* error = GRPC_ERROR_NONE;
@@ -1511,10 +1511,10 @@ static void pollset_set_add_pollset_set(grpc_pollset_set* a,
if (b_size > a_size) {
GPR_SWAP(grpc_pollset_set*, a, b);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "PSS: parent %p to %p", b, a);
}
- a->refs.Ref();
+ a->refs.Ref();
b->parent = a;
if (a->fd_capacity < a->fd_count + b->fd_count) {
a->fd_capacity = GPR_MAX(2 * a->fd_capacity, a->fd_count + b->fd_count);
@@ -1553,8 +1553,8 @@ static void pollset_set_add_pollset_set(grpc_pollset_set* a,
gpr_mu_unlock(&b->mu);
}
-static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/,
- grpc_pollset_set* /*item*/) {}
+static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/,
+ grpc_pollset_set* /*item*/) {}
/*******************************************************************************
* Event engine binding
@@ -1564,11 +1564,11 @@ static bool is_any_background_poller_thread(void) { return false; }
static void shutdown_background_closure(void) {}
-static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
- grpc_error* /*error*/) {
- return false;
-}
-
+static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
+ grpc_error* /*error*/) {
+ return false;
+}
+
static void shutdown_engine(void) {
fd_global_shutdown();
pollset_global_shutdown();
@@ -1610,11 +1610,11 @@ static const grpc_event_engine_vtable vtable = {
is_any_background_poller_thread,
shutdown_background_closure,
shutdown_engine,
- add_closure_to_background_poller,
+ add_closure_to_background_poller,
};
const grpc_event_engine_vtable* grpc_init_epollex_linux(
- bool /*explicitly_requested*/) {
+ bool /*explicitly_requested*/) {
if (!grpc_has_wakeup_fd()) {
gpr_log(GPR_ERROR, "Skipping epollex because of no wakeup fd.");
return nullptr;
@@ -1642,7 +1642,7 @@ const grpc_event_engine_vtable* grpc_init_epollex_linux(
/* If GRPC_LINUX_EPOLL_CREATE1 is not defined, it means
epoll_create1 is not available. Return NULL */
const grpc_event_engine_vtable* grpc_init_epollex_linux(
- bool /*explicitly_requested*/) {
+ bool /*explicitly_requested*/) {
return nullptr;
}
#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLLEX) */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc
index a46ab7ea0d..76d5cbd392 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc
@@ -128,7 +128,7 @@ struct grpc_fd {
grpc_fork_fd_list* fork_fd_list;
};
-/* True when GRPC_ENABLE_FORK_SUPPORT=1. */
+/* True when GRPC_ENABLE_FORK_SUPPORT=1. */
static bool track_fds_for_fork = false;
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
@@ -319,23 +319,23 @@ static void fork_fd_list_add_wakeup_fd(grpc_cached_wakeup_fd* fd) {
#define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__)
static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file,
int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG,
"FD %d %p ref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]",
fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst),
gpr_atm_no_barrier_load(&fd->refst) + n, reason, file, line);
}
#else
-#define REF_BY(fd, n, reason) \
- do { \
- ref_by(fd, n); \
- (void)(reason); \
- } while (0)
-#define UNREF_BY(fd, n, reason) \
- do { \
- unref_by(fd, n); \
- (void)(reason); \
- } while (0)
+#define REF_BY(fd, n, reason) \
+ do { \
+ ref_by(fd, n); \
+ (void)(reason); \
+ } while (0)
+#define UNREF_BY(fd, n, reason) \
+ do { \
+ unref_by(fd, n); \
+ (void)(reason); \
+ } while (0)
static void ref_by(grpc_fd* fd, int n) {
#endif
GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0);
@@ -344,7 +344,7 @@ static void ref_by(grpc_fd* fd, int n) {
#ifndef NDEBUG
static void unref_by(grpc_fd* fd, int n, const char* reason, const char* file,
int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG,
"FD %d %p unref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]",
fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst),
@@ -366,8 +366,8 @@ static void unref_by(grpc_fd* fd, int n) {
}
static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
- // Avoid unused-parameter warning for debug-only parameter
- (void)track_err;
+ // Avoid unused-parameter warning for debug-only parameter
+ (void)track_err;
GPR_DEBUG_ASSERT(track_err == false);
grpc_fd* r = static_cast<grpc_fd*>(gpr_malloc(sizeof(*r)));
gpr_mu_init(&r->mu);
@@ -437,7 +437,7 @@ static void close_fd_locked(grpc_fd* fd) {
if (!fd->released) {
close(fd->fd);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, fd->on_done_closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, fd->on_done_closure, GRPC_ERROR_NONE);
}
static int fd_wrapped_fd(grpc_fd* fd) {
@@ -498,18 +498,18 @@ static grpc_error* fd_shutdown_error(grpc_fd* fd) {
static void notify_on_locked(grpc_fd* fd, grpc_closure** st,
grpc_closure* closure) {
if (fd->shutdown || gpr_atm_no_barrier_load(&fd->pollhup)) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, closure,
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("FD shutdown"),
- GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, closure,
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("FD shutdown"),
+ GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE));
} else if (*st == CLOSURE_NOT_READY) {
/* not ready ==> switch to a waiting state by setting the closure */
*st = closure;
} else if (*st == CLOSURE_READY) {
/* already ready ==> queue the closure to run immediately */
*st = CLOSURE_NOT_READY;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, fd_shutdown_error(fd));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, fd_shutdown_error(fd));
maybe_wake_one_watcher_locked(fd);
} else {
/* upcallptr was set to a different closure. This is an error! */
@@ -531,7 +531,7 @@ static int set_ready_locked(grpc_fd* fd, grpc_closure** st) {
return 0;
} else {
/* waiting ==> queue closure */
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, *st, fd_shutdown_error(fd));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, *st, fd_shutdown_error(fd));
*st = CLOSURE_NOT_READY;
return 1;
}
@@ -572,11 +572,11 @@ static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
gpr_mu_unlock(&fd->mu);
}
-static void fd_notify_on_error(grpc_fd* /*fd*/, grpc_closure* closure) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+static void fd_notify_on_error(grpc_fd* /*fd*/, grpc_closure* closure) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_ERROR, "Polling engine does not support tracking errors.");
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_CANCELLED);
}
static void fd_set_readable(grpc_fd* fd) {
@@ -591,8 +591,8 @@ static void fd_set_writable(grpc_fd* fd) {
gpr_mu_unlock(&fd->mu);
}
-static void fd_set_error(grpc_fd* /*fd*/) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+static void fd_set_error(grpc_fd* /*fd*/) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_ERROR, "Polling engine does not support tracking errors.");
}
}
@@ -708,7 +708,7 @@ static void fd_end_poll(grpc_fd_watcher* watcher, int got_read, int got_write) {
GPR_TLS_DECL(g_current_thread_poller);
GPR_TLS_DECL(g_current_thread_worker);
-static void remove_worker(grpc_pollset* /*p*/, grpc_pollset_worker* worker) {
+static void remove_worker(grpc_pollset* /*p*/, grpc_pollset_worker* worker) {
worker->prev->next = worker->next;
worker->next->prev = worker->prev;
}
@@ -898,8 +898,8 @@ static void finish_shutdown(grpc_pollset* pollset) {
GRPC_FD_UNREF(pollset->fds[i], "multipoller");
}
pollset->fd_count = 0;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_done,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_done,
+ GRPC_ERROR_NONE);
}
static void work_combine_error(grpc_error** composite, grpc_error* error) {
@@ -1025,7 +1025,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset,
r = grpc_poll_function(pfds, pfd_count, timeout);
GRPC_SCHEDULING_END_BLOCKING_REGION;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "%p poll=%d", pollset, r);
}
@@ -1049,7 +1049,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset,
}
} else {
if (pfds[0].revents & POLLIN_CHECK) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "%p: got_wakeup", pollset);
}
work_combine_error(
@@ -1059,7 +1059,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset,
if (watchers[i].fd == nullptr) {
fd_end_poll(&watchers[i], 0, 0);
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
gpr_log(GPR_INFO, "%p got_event: %d r:%d w:%d [%d]", pollset,
pfds[i].fd, (pfds[i].revents & POLLIN_CHECK) != 0,
(pfds[i].revents & POLLOUT_CHECK) != 0, pfds[i].revents);
@@ -1333,11 +1333,11 @@ static bool is_any_background_poller_thread(void) { return false; }
static void shutdown_background_closure(void) {}
-static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
- grpc_error* /*error*/) {
- return false;
-}
-
+static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
+ grpc_error* /*error*/) {
+ return false;
+}
+
static void shutdown_engine(void) {
pollset_global_shutdown();
if (track_fds_for_fork) {
@@ -1382,7 +1382,7 @@ static const grpc_event_engine_vtable vtable = {
is_any_background_poller_thread,
shutdown_background_closure,
shutdown_engine,
- add_closure_to_background_poller,
+ add_closure_to_background_poller,
};
/* Called by the child process's post-fork handler to close open fds, including
@@ -1392,9 +1392,9 @@ static void reset_event_manager_on_fork() {
gpr_mu_lock(&fork_fd_list_mu);
while (fork_fd_list_head != nullptr) {
if (fork_fd_list_head->fd != nullptr) {
- if (!fork_fd_list_head->fd->closed) {
- close(fork_fd_list_head->fd->fd);
- }
+ if (!fork_fd_list_head->fd->closed) {
+ close(fork_fd_list_head->fd->fd);
+ }
fork_fd_list_head->fd->fd = -1;
} else {
close(fork_fd_list_head->cached_wakeup_fd->fd.read_fd);
@@ -1407,8 +1407,8 @@ static void reset_event_manager_on_fork() {
gpr_mu_unlock(&fork_fd_list_mu);
}
-const grpc_event_engine_vtable* grpc_init_poll_posix(
- bool /*explicit_request*/) {
+const grpc_event_engine_vtable* grpc_init_poll_posix(
+ bool /*explicit_request*/) {
if (!grpc_has_wakeup_fd()) {
gpr_log(GPR_ERROR, "Skipping poll because of no wakeup fd.");
return nullptr;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc
index 3d32359be4..341dfc6057 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc
@@ -32,35 +32,35 @@
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/ev_epoll1_linux.h"
#include "src/core/lib/iomgr/ev_epollex_linux.h"
#include "src/core/lib/iomgr/ev_poll_posix.h"
#include "src/core/lib/iomgr/internal_errqueue.h"
-GPR_GLOBAL_CONFIG_DEFINE_STRING(
- grpc_poll_strategy, "all",
- "Declares which polling engines to try when starting gRPC. "
- "This is a comma-separated list of engines, which are tried in priority "
- "order first -> last.")
-
-grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
- false, "polling"); /* Disabled by default */
+GPR_GLOBAL_CONFIG_DEFINE_STRING(
+ grpc_poll_strategy, "all",
+ "Declares which polling engines to try when starting gRPC. "
+ "This is a comma-separated list of engines, which are tried in priority "
+ "order first -> last.")
+grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
+ false, "polling"); /* Disabled by default */
+
/* Traces fd create/close operations */
-grpc_core::DebugOnlyTraceFlag grpc_fd_trace(false, "fd_trace");
+grpc_core::DebugOnlyTraceFlag grpc_fd_trace(false, "fd_trace");
grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount");
grpc_core::DebugOnlyTraceFlag grpc_polling_api_trace(false, "polling_api");
-// Polling API trace only enabled in debug builds
+// Polling API trace only enabled in debug builds
#ifndef NDEBUG
#define GRPC_POLLING_API_TRACE(format, ...) \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_api_trace)) { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_api_trace)) { \
gpr_log(GPR_INFO, "(polling-api) " format, __VA_ARGS__); \
}
#else
#define GRPC_POLLING_API_TRACE(...)
-#endif // NDEBUG
+#endif // NDEBUG
/** Default poll() function - a pointer so that it can be overridden by some
* tests */
@@ -71,7 +71,7 @@ int aix_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
return poll(fds, nfds, timeout);
}
grpc_poll_function_type grpc_poll_function = aix_poll;
-#endif // GPR_AIX
+#endif // GPR_AIX
grpc_wakeup_fd grpc_global_wakeup_fd;
@@ -130,9 +130,9 @@ static event_engine_factory g_factories[] = {
{ENGINE_HEAD_CUSTOM, nullptr}, {ENGINE_HEAD_CUSTOM, nullptr},
{ENGINE_HEAD_CUSTOM, nullptr}, {ENGINE_HEAD_CUSTOM, nullptr},
{"epollex", grpc_init_epollex_linux}, {"epoll1", grpc_init_epoll1_linux},
- {"poll", grpc_init_poll_posix}, {"none", init_non_polling},
- {ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr},
+ {"poll", grpc_init_poll_posix}, {"none", init_non_polling},
{ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr},
+ {ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr},
};
static void add(const char* beg, const char* end, char*** ss, size_t* ns) {
@@ -205,16 +205,16 @@ void grpc_register_event_engine_factory(const char* name,
GPR_ASSERT(false);
}
-/*If grpc_event_engine_init() has been called, returns the poll_strategy_name.
- * Otherwise, returns nullptr. */
+/*If grpc_event_engine_init() has been called, returns the poll_strategy_name.
+ * Otherwise, returns nullptr. */
const char* grpc_get_poll_strategy_name() { return g_poll_strategy_name; }
void grpc_event_engine_init(void) {
- grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
+ grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
char** strings = nullptr;
size_t nstrings = 0;
- split(value.get(), &strings, &nstrings);
+ split(value.get(), &strings, &nstrings);
for (size_t i = 0; g_event_engine == nullptr && i < nstrings; i++) {
try_engine(strings[i]);
@@ -226,8 +226,8 @@ void grpc_event_engine_init(void) {
gpr_free(strings);
if (g_event_engine == nullptr) {
- gpr_log(GPR_ERROR, "No event engine could be initialized from %s",
- value.get());
+ gpr_log(GPR_ERROR, "No event engine could be initialized from %s",
+ value.get());
abort();
}
}
@@ -246,8 +246,8 @@ bool grpc_event_engine_can_track_errors(void) {
}
bool grpc_event_engine_run_in_background(void) {
- // g_event_engine is nullptr when using a custom iomgr.
- return g_event_engine != nullptr && g_event_engine->run_in_background;
+ // g_event_engine is nullptr when using a custom iomgr.
+ return g_event_engine != nullptr && g_event_engine->run_in_background;
}
grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err) {
@@ -405,11 +405,11 @@ bool grpc_is_any_background_poller_thread(void) {
return g_event_engine->is_any_background_poller_thread();
}
-bool grpc_add_closure_to_background_poller(grpc_closure* closure,
- grpc_error* error) {
- return g_event_engine->add_closure_to_background_poller(closure, error);
-}
-
+bool grpc_add_closure_to_background_poller(grpc_closure* closure,
+ grpc_error* error) {
+ return g_event_engine->add_closure_to_background_poller(closure, error);
+}
+
void grpc_shutdown_background_closure(void) {
g_event_engine->shutdown_background_closure();
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h
index 84edabce71..4a5f7fb42c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h
@@ -24,20 +24,20 @@
#include <poll.h>
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_set.h"
#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_poll_strategy);
-
-extern grpc_core::DebugOnlyTraceFlag grpc_fd_trace; /* Disabled by default */
-extern grpc_core::DebugOnlyTraceFlag
- grpc_polling_trace; /* Disabled by default */
+GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_poll_strategy);
+extern grpc_core::DebugOnlyTraceFlag grpc_fd_trace; /* Disabled by default */
+extern grpc_core::DebugOnlyTraceFlag
+ grpc_polling_trace; /* Disabled by default */
+
#define GRPC_FD_TRACE(format, ...) \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_fd_trace)) { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_fd_trace)) { \
gpr_log(GPR_INFO, "(fd-trace) " format, __VA_ARGS__); \
}
@@ -87,8 +87,8 @@ typedef struct grpc_event_engine_vtable {
bool (*is_any_background_poller_thread)(void);
void (*shutdown_background_closure)(void);
void (*shutdown_engine)(void);
- bool (*add_closure_to_background_poller)(grpc_closure* closure,
- grpc_error* error);
+ bool (*add_closure_to_background_poller)(grpc_closure* closure,
+ grpc_error* error);
} grpc_event_engine_vtable;
/* register a new event engine factory */
@@ -191,12 +191,12 @@ void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd);
/* Returns true if the caller is a worker thread for any background poller. */
bool grpc_is_any_background_poller_thread();
-/* Returns true if the closure is registered into the background poller. Note
- * that the closure may or may not run yet when this function returns, and the
- * closure should not be blocking or long-running. */
-bool grpc_add_closure_to_background_poller(grpc_closure* closure,
- grpc_error* error);
-
+/* Returns true if the closure is registered into the background poller. Note
+ * that the closure may or may not run yet when this function returns, and the
+ * closure should not be blocking or long-running. */
+bool grpc_add_closure_to_background_poller(grpc_closure* closure,
+ grpc_error* error);
+
/* Shut down all the closures registered in the background poller. */
void grpc_shutdown_background_closure();
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc
index e3f5715a87..0ee4654531 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc
@@ -24,7 +24,7 @@
#include "src/core/lib/debug/trace.h"
-grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
- false, "polling"); /* Disabled by default */
+grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
+ false, "polling"); /* Disabled by default */
#endif // GRPC_WINSOCK_SOCKET
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc
index e392a9960b..a05dcd5ef1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc
@@ -52,9 +52,9 @@ static void exec_ctx_sched(grpc_closure* closure, grpc_error* error) {
}
static gpr_timespec g_start_time;
-static gpr_cycle_counter g_start_cycle;
+static gpr_cycle_counter g_start_cycle;
-static grpc_millis timespan_to_millis_round_down(gpr_timespec ts) {
+static grpc_millis timespan_to_millis_round_down(gpr_timespec ts) {
double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) +
static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS;
if (x < 0) return 0;
@@ -62,11 +62,11 @@ static grpc_millis timespan_to_millis_round_down(gpr_timespec ts) {
return static_cast<grpc_millis>(x);
}
-static grpc_millis timespec_to_millis_round_down(gpr_timespec ts) {
- return timespan_to_millis_round_down(gpr_time_sub(ts, g_start_time));
-}
-
-static grpc_millis timespan_to_millis_round_up(gpr_timespec ts) {
+static grpc_millis timespec_to_millis_round_down(gpr_timespec ts) {
+ return timespan_to_millis_round_down(gpr_time_sub(ts, g_start_time));
+}
+
+static grpc_millis timespan_to_millis_round_up(gpr_timespec ts) {
double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) +
static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS +
static_cast<double>(GPR_NS_PER_SEC - 1) /
@@ -76,10 +76,10 @@ static grpc_millis timespan_to_millis_round_up(gpr_timespec ts) {
return static_cast<grpc_millis>(x);
}
-static grpc_millis timespec_to_millis_round_up(gpr_timespec ts) {
- return timespan_to_millis_round_up(gpr_time_sub(ts, g_start_time));
-}
-
+static grpc_millis timespec_to_millis_round_up(gpr_timespec ts) {
+ return timespan_to_millis_round_up(gpr_time_sub(ts, g_start_time));
+}
+
gpr_timespec grpc_millis_to_timespec(grpc_millis millis,
gpr_clock_type clock_type) {
// special-case infinities as grpc_millis can be 32bit on some platforms
@@ -108,16 +108,16 @@ grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) {
gpr_convert_clock_type(ts, g_start_time.clock_type));
}
-grpc_millis grpc_cycle_counter_to_millis_round_down(gpr_cycle_counter cycles) {
- return timespan_to_millis_round_down(
- gpr_cycle_counter_sub(cycles, g_start_cycle));
-}
-
-grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles) {
- return timespan_to_millis_round_up(
- gpr_cycle_counter_sub(cycles, g_start_cycle));
-}
+grpc_millis grpc_cycle_counter_to_millis_round_down(gpr_cycle_counter cycles) {
+ return timespan_to_millis_round_down(
+ gpr_cycle_counter_sub(cycles, g_start_cycle));
+}
+grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles) {
+ return timespan_to_millis_round_up(
+ gpr_cycle_counter_sub(cycles, g_start_cycle));
+}
+
namespace grpc_core {
GPR_TLS_CLASS_DEF(ExecCtx::exec_ctx_);
GPR_TLS_CLASS_DEF(ApplicationCallbackExecCtx::callback_exec_ctx_);
@@ -129,13 +129,13 @@ void ExecCtx::TestOnlyGlobalInit(gpr_timespec new_val) {
}
void ExecCtx::GlobalInit(void) {
- // gpr_now(GPR_CLOCK_MONOTONIC) incurs a syscall. We don't actually know the
- // exact cycle the time was captured, so we use the average of cycles before
- // and after the syscall as the starting cycle.
- const gpr_cycle_counter cycle_before = gpr_get_cycle_counter();
+ // gpr_now(GPR_CLOCK_MONOTONIC) incurs a syscall. We don't actually know the
+ // exact cycle the time was captured, so we use the average of cycles before
+ // and after the syscall as the starting cycle.
+ const gpr_cycle_counter cycle_before = gpr_get_cycle_counter();
g_start_time = gpr_now(GPR_CLOCK_MONOTONIC);
- const gpr_cycle_counter cycle_after = gpr_get_cycle_counter();
- g_start_cycle = (cycle_before + cycle_after) / 2;
+ const gpr_cycle_counter cycle_after = gpr_get_cycle_counter();
+ g_start_cycle = (cycle_before + cycle_after) / 2;
gpr_tls_init(&exec_ctx_);
}
@@ -169,56 +169,56 @@ grpc_millis ExecCtx::Now() {
return now_;
}
-void ExecCtx::Run(const DebugLocation& location, grpc_closure* closure,
- grpc_error* error) {
- (void)location;
- if (closure == nullptr) {
- GRPC_ERROR_UNREF(error);
- return;
- }
-#ifndef NDEBUG
- if (closure->scheduled) {
- gpr_log(GPR_ERROR,
- "Closure already scheduled. (closure: %p, created: [%s:%d], "
- "previously scheduled at: [%s: %d], newly scheduled at [%s: %d]",
- closure, closure->file_created, closure->line_created,
- closure->file_initiated, closure->line_initiated, location.file(),
- location.line());
- abort();
- }
- closure->scheduled = true;
- closure->file_initiated = location.file();
- closure->line_initiated = location.line();
- closure->run = false;
- GPR_ASSERT(closure->cb != nullptr);
-#endif
- exec_ctx_sched(closure, error);
-}
-
-void ExecCtx::RunList(const DebugLocation& location, grpc_closure_list* list) {
- (void)location;
- grpc_closure* c = list->head;
- while (c != nullptr) {
- grpc_closure* next = c->next_data.next;
-#ifndef NDEBUG
- if (c->scheduled) {
- gpr_log(GPR_ERROR,
- "Closure already scheduled. (closure: %p, created: [%s:%d], "
- "previously scheduled at: [%s: %d], newly scheduled at [%s:%d]",
- c, c->file_created, c->line_created, c->file_initiated,
- c->line_initiated, location.file(), location.line());
- abort();
- }
- c->scheduled = true;
- c->file_initiated = location.file();
- c->line_initiated = location.line();
- c->run = false;
- GPR_ASSERT(c->cb != nullptr);
-#endif
- exec_ctx_sched(c, c->error_data.error);
- c = next;
- }
- list->head = list->tail = nullptr;
-}
-
+void ExecCtx::Run(const DebugLocation& location, grpc_closure* closure,
+ grpc_error* error) {
+ (void)location;
+ if (closure == nullptr) {
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
+#ifndef NDEBUG
+ if (closure->scheduled) {
+ gpr_log(GPR_ERROR,
+ "Closure already scheduled. (closure: %p, created: [%s:%d], "
+ "previously scheduled at: [%s: %d], newly scheduled at [%s: %d]",
+ closure, closure->file_created, closure->line_created,
+ closure->file_initiated, closure->line_initiated, location.file(),
+ location.line());
+ abort();
+ }
+ closure->scheduled = true;
+ closure->file_initiated = location.file();
+ closure->line_initiated = location.line();
+ closure->run = false;
+ GPR_ASSERT(closure->cb != nullptr);
+#endif
+ exec_ctx_sched(closure, error);
+}
+
+void ExecCtx::RunList(const DebugLocation& location, grpc_closure_list* list) {
+ (void)location;
+ grpc_closure* c = list->head;
+ while (c != nullptr) {
+ grpc_closure* next = c->next_data.next;
+#ifndef NDEBUG
+ if (c->scheduled) {
+ gpr_log(GPR_ERROR,
+ "Closure already scheduled. (closure: %p, created: [%s:%d], "
+ "previously scheduled at: [%s: %d], newly scheduled at [%s:%d]",
+ c, c->file_created, c->line_created, c->file_initiated,
+ c->line_initiated, location.file(), location.line());
+ abort();
+ }
+ c->scheduled = true;
+ c->file_initiated = location.file();
+ c->line_initiated = location.line();
+ c->run = false;
+ GPR_ASSERT(c->cb != nullptr);
+#endif
+ exec_ctx_sched(c, c->error_data.error);
+ c = next;
+ }
+ list->head = list->tail = nullptr;
+}
+
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h
index 6b4e184cad..12565496e2 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h
@@ -28,9 +28,9 @@
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
-#include "src/core/lib/gpr/time_precise.h"
+#include "src/core/lib/gpr/time_precise.h"
#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/fork.h"
#include "src/core/lib/iomgr/closure.h"
@@ -60,11 +60,11 @@ typedef struct grpc_combiner grpc_combiner;
gpr_timespec grpc_millis_to_timespec(grpc_millis millis, gpr_clock_type clock);
grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec timespec);
grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec timespec);
-grpc_millis grpc_cycle_counter_to_millis_round_down(gpr_cycle_counter cycles);
-grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles);
+grpc_millis grpc_cycle_counter_to_millis_round_down(gpr_cycle_counter cycles);
+grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles);
namespace grpc_core {
-class Combiner;
+class Combiner;
/** Execution context.
* A bag of data that collects information along a callstack.
* It is created on the stack at core entry points (public API or iomgr), and
@@ -143,9 +143,9 @@ class ExecCtx {
struct CombinerData {
/* currently active combiner: updated only via combiner.c */
- Combiner* active_combiner;
+ Combiner* active_combiner;
/* last active combiner in the active combiner list */
- Combiner* last_combiner;
+ Combiner* last_combiner;
};
/** Only to be used by grpc-combiner code */
@@ -227,17 +227,17 @@ class ExecCtx {
gpr_tls_set(&exec_ctx_, reinterpret_cast<intptr_t>(exec_ctx));
}
- static void Run(const DebugLocation& location, grpc_closure* closure,
- grpc_error* error);
-
- static void RunList(const DebugLocation& location, grpc_closure_list* list);
-
+ static void Run(const DebugLocation& location, grpc_closure* closure,
+ grpc_error* error);
+
+ static void RunList(const DebugLocation& location, grpc_closure_list* list);
+
protected:
/** Check if ready to finish. */
virtual bool CheckReadyToFinish() { return false; }
/** Disallow delete on ExecCtx. */
- static void operator delete(void* /* p */) { abort(); }
+ static void operator delete(void* /* p */) { abort(); }
private:
/** Set exec_ctx_ to exec_ctx. */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor.cc b/contrib/libs/grpc/src/core/lib/iomgr/executor.cc
index 10b2f948ec..b4caf8ccc1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor.cc
@@ -32,23 +32,23 @@
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/iomgr.h"
#define MAX_DEPTH 2
-#define EXECUTOR_TRACE(format, ...) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \
- gpr_log(GPR_INFO, "EXECUTOR " format, __VA_ARGS__); \
- } \
- } while (0)
+#define EXECUTOR_TRACE(format, ...) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \
+ gpr_log(GPR_INFO, "EXECUTOR " format, __VA_ARGS__); \
+ } \
+ } while (0)
-#define EXECUTOR_TRACE0(str) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \
- gpr_log(GPR_INFO, "EXECUTOR " str); \
- } \
- } while (0)
+#define EXECUTOR_TRACE0(str) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \
+ gpr_log(GPR_INFO, "EXECUTOR " str); \
+ } \
+ } while (0)
namespace grpc_core {
namespace {
@@ -77,13 +77,13 @@ void resolver_enqueue_long(grpc_closure* closure, grpc_error* error) {
closure, error, false /* is_short */);
}
-using EnqueueFunc = void (*)(grpc_closure* closure, grpc_error* error);
+using EnqueueFunc = void (*)(grpc_closure* closure, grpc_error* error);
-const EnqueueFunc
- executor_enqueue_fns_[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)]
- [static_cast<size_t>(ExecutorJobType::NUM_JOB_TYPES)] =
- {{default_enqueue_short, default_enqueue_long},
- {resolver_enqueue_short, resolver_enqueue_long}};
+const EnqueueFunc
+ executor_enqueue_fns_[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)]
+ [static_cast<size_t>(ExecutorJobType::NUM_JOB_TYPES)] =
+ {{default_enqueue_short, default_enqueue_long},
+ {resolver_enqueue_short, resolver_enqueue_long}};
size_t threads_limit_ = 0;
@@ -116,10 +116,10 @@ size_t Executor::RunClosures(const char* executor_name,
// thread itself, but this is the point where we could start seeing
// application-level callbacks. No need to create a new ExecCtx, though,
// since there already is one and it is flushed (but not destructed) in this
- // function itself. The ApplicationCallbackExecCtx will have its callbacks
- // invoked on its destruction, which will be after completing any closures in
- // the executor's closure list (which were explicitly scheduled onto the
- // executor).
+ // function itself. The ApplicationCallbackExecCtx will have its callbacks
+ // invoked on its destruction, which will be after completing any closures in
+ // the executor's closure list (which were explicitly scheduled onto the
+ // executor).
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx(
GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD);
@@ -208,14 +208,14 @@ void Executor::SetThreading(bool threading) {
}
gpr_free(thd_state_);
-
- // grpc_iomgr_shutdown_background_closure() will close all the registered
- // fds in the background poller, and wait for all pending closures to
- // finish. Thus, never call Executor::SetThreading(false) in the middle of
- // an application.
- // TODO(guantaol): create another method to finish all the pending closures
- // registered in the background poller by grpc_core::Executor.
- grpc_iomgr_shutdown_background_closure();
+
+ // grpc_iomgr_shutdown_background_closure() will close all the registered
+ // fds in the background poller, and wait for all pending closures to
+ // finish. Thus, never call Executor::SetThreading(false) in the middle of
+ // an application.
+ // TODO(guantaol): create another method to finish all the pending closures
+ // registered in the background poller by grpc_core::Executor.
+ grpc_iomgr_shutdown_background_closure();
}
EXECUTOR_TRACE("(%s) SetThreading(%d) done", name_, threading);
@@ -258,8 +258,8 @@ void Executor::ThreadMain(void* arg) {
grpc_core::ExecCtx::Get()->InvalidateNow();
subtract_depth = RunClosures(ts->name, closures);
}
-
- gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(nullptr));
+
+ gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(nullptr));
}
void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
@@ -290,10 +290,10 @@ void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
return;
}
- if (grpc_iomgr_add_closure_to_background_poller(closure, error)) {
- return;
- }
-
+ if (grpc_iomgr_add_closure_to_background_poller(closure, error)) {
+ return;
+ }
+
ThreadState* ts = (ThreadState*)gpr_tls_get(&g_this_thread_state);
if (ts == nullptr) {
ts = &thd_state_[GPR_HASH_POINTER(grpc_core::ExecCtx::Get(),
@@ -404,9 +404,9 @@ void Executor::InitAll() {
}
executors[static_cast<size_t>(ExecutorType::DEFAULT)] =
- new Executor("default-executor");
+ new Executor("default-executor");
executors[static_cast<size_t>(ExecutorType::RESOLVER)] =
- new Executor("resolver-executor");
+ new Executor("resolver-executor");
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Init();
executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Init();
@@ -414,10 +414,10 @@ void Executor::InitAll() {
EXECUTOR_TRACE0("Executor::InitAll() done");
}
-void Executor::Run(grpc_closure* closure, grpc_error* error,
- ExecutorType executor_type, ExecutorJobType job_type) {
- executor_enqueue_fns_[static_cast<size_t>(executor_type)]
- [static_cast<size_t>(job_type)](closure, error);
+void Executor::Run(grpc_closure* closure, grpc_error* error,
+ ExecutorType executor_type, ExecutorJobType job_type) {
+ executor_enqueue_fns_[static_cast<size_t>(executor_type)]
+ [static_cast<size_t>(job_type)](closure, error);
}
void Executor::ShutdownAll() {
@@ -436,7 +436,7 @@ void Executor::ShutdownAll() {
// Delete the executor objects.
//
// NOTE: It is important to call Shutdown() on all executors first before
- // calling delete because it is possible for one executor (that is not
+ // calling delete because it is possible for one executor (that is not
// shutdown yet) to call Enqueue() on a different executor which is already
// shutdown. This is legal and in such cases, the Enqueue() operation
// effectively "fails" and enqueues that closure on the calling thread's
@@ -445,8 +445,8 @@ void Executor::ShutdownAll() {
// By ensuring that all executors are shutdown first, we are also ensuring
// that no thread is active across all executors.
- delete executors[static_cast<size_t>(ExecutorType::DEFAULT)];
- delete executors[static_cast<size_t>(ExecutorType::RESOLVER)];
+ delete executors[static_cast<size_t>(ExecutorType::DEFAULT)];
+ delete executors[static_cast<size_t>(ExecutorType::RESOLVER)];
executors[static_cast<size_t>(ExecutorType::DEFAULT)] = nullptr;
executors[static_cast<size_t>(ExecutorType::RESOLVER)] = nullptr;
@@ -475,6 +475,6 @@ void Executor::SetThreadingDefault(bool enable) {
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->SetThreading(enable);
}
-void grpc_executor_global_init() { gpr_tls_init(&g_this_thread_state); }
-
+void grpc_executor_global_init() { gpr_tls_init(&g_this_thread_state); }
+
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor.h b/contrib/libs/grpc/src/core/lib/iomgr/executor.h
index ae523ff212..cf180ae12b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor.h
@@ -61,8 +61,8 @@ class Executor {
/** Is the executor multi-threaded? */
bool IsThreaded() const;
- /* Enable/disable threading - must be called after Init and Shutdown(). Never
- * call SetThreading(false) in the middle of an application */
+ /* Enable/disable threading - must be called after Init and Shutdown(). Never
+ * call SetThreading(false) in the middle of an application */
void SetThreading(bool threading);
/** Shutdown the executor, running all pending work as part of the call */
@@ -83,10 +83,10 @@ class Executor {
// Initialize ALL the executors
static void InitAll();
- static void Run(grpc_closure* closure, grpc_error* error,
- ExecutorType executor_type = ExecutorType::DEFAULT,
- ExecutorJobType job_type = ExecutorJobType::SHORT);
-
+ static void Run(grpc_closure* closure, grpc_error* error,
+ ExecutorType executor_type = ExecutorType::DEFAULT,
+ ExecutorJobType job_type = ExecutorJobType::SHORT);
+
// Shutdown ALL the executors
static void ShutdownAll();
@@ -117,9 +117,9 @@ class Executor {
gpr_spinlock adding_thread_lock_;
};
-// Global initializer for executor
-void grpc_executor_global_init();
-
+// Global initializer for executor
+void grpc_executor_global_init();
+
} // namespace grpc_core
#endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.cc b/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.cc
index 74096a4c5b..a99b2c44b9 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.cc
@@ -1,183 +1,183 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/executor/mpmcqueue.h"
-
-namespace grpc_core {
-
-DebugOnlyTraceFlag grpc_thread_pool_trace(false, "thread_pool");
-
-inline void* InfLenFIFOQueue::PopFront() {
- // Caller should already check queue is not empty and has already held the
- // mutex. This function will assume that there is at least one element in the
- // queue (i.e. queue_head_->content is valid).
- void* result = queue_head_->content;
- count_.Store(count_.Load(MemoryOrder::RELAXED) - 1, MemoryOrder::RELAXED);
-
- // Updates Stats when trace flag turned on.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {
- gpr_timespec wait_time =
- gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), queue_head_->insert_time);
- stats_.num_completed++;
- stats_.total_queue_time = gpr_time_add(stats_.total_queue_time, wait_time);
- stats_.max_queue_time = gpr_time_max(
- gpr_convert_clock_type(stats_.max_queue_time, GPR_TIMESPAN), wait_time);
-
- if (count_.Load(MemoryOrder::RELAXED) == 0) {
- stats_.busy_queue_time =
- gpr_time_add(stats_.busy_queue_time,
- gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), busy_time));
- }
-
- gpr_log(GPR_INFO,
- "[InfLenFIFOQueue PopFront] num_completed: %" PRIu64
- " total_queue_time: %f max_queue_time: %f busy_queue_time: %f",
- stats_.num_completed,
- gpr_timespec_to_micros(stats_.total_queue_time),
- gpr_timespec_to_micros(stats_.max_queue_time),
- gpr_timespec_to_micros(stats_.busy_queue_time));
- }
-
- queue_head_ = queue_head_->next;
- // Signal waiting thread
- if (count_.Load(MemoryOrder::RELAXED) > 0) {
- TopWaiter()->cv.Signal();
- }
-
- return result;
-}
-
-InfLenFIFOQueue::Node* InfLenFIFOQueue::AllocateNodes(int num) {
- num_nodes_ = num_nodes_ + num;
- Node* new_chunk = static_cast<Node*>(gpr_zalloc(sizeof(Node) * num));
- new_chunk[0].next = &new_chunk[1];
- new_chunk[num - 1].prev = &new_chunk[num - 2];
- for (int i = 1; i < num - 1; ++i) {
- new_chunk[i].prev = &new_chunk[i - 1];
- new_chunk[i].next = &new_chunk[i + 1];
- }
- return new_chunk;
-}
-
-InfLenFIFOQueue::InfLenFIFOQueue() {
- delete_list_size_ = kDeleteListInitSize;
- delete_list_ =
- static_cast<Node**>(gpr_zalloc(sizeof(Node*) * delete_list_size_));
-
- Node* new_chunk = AllocateNodes(kQueueInitNumNodes);
- delete_list_[delete_list_count_++] = new_chunk;
- queue_head_ = queue_tail_ = new_chunk;
- new_chunk[0].prev = &new_chunk[kQueueInitNumNodes - 1];
- new_chunk[kQueueInitNumNodes - 1].next = &new_chunk[0];
-
- waiters_.next = &waiters_;
- waiters_.prev = &waiters_;
-}
-
-InfLenFIFOQueue::~InfLenFIFOQueue() {
- GPR_ASSERT(count_.Load(MemoryOrder::RELAXED) == 0);
- for (size_t i = 0; i < delete_list_count_; ++i) {
- gpr_free(delete_list_[i]);
- }
- gpr_free(delete_list_);
-}
-
-void InfLenFIFOQueue::Put(void* elem) {
- MutexLock l(&mu_);
-
- int curr_count = count_.Load(MemoryOrder::RELAXED);
-
- if (queue_tail_ == queue_head_ && curr_count != 0) {
- // List is full. Expands list to double size by inserting new chunk of nodes
- Node* new_chunk = AllocateNodes(curr_count);
- delete_list_[delete_list_count_++] = new_chunk;
- // Expands delete list on full.
- if (delete_list_count_ == delete_list_size_) {
- delete_list_size_ = delete_list_size_ * 2;
- delete_list_ = static_cast<Node**>(
- gpr_realloc(delete_list_, sizeof(Node*) * delete_list_size_));
- }
- new_chunk[0].prev = queue_tail_->prev;
- new_chunk[curr_count - 1].next = queue_head_;
- queue_tail_->prev->next = new_chunk;
- queue_head_->prev = &new_chunk[curr_count - 1];
- queue_tail_ = new_chunk;
- }
- queue_tail_->content = static_cast<void*>(elem);
-
- // Updates Stats info
- if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {
- stats_.num_started++;
- gpr_log(GPR_INFO, "[InfLenFIFOQueue Put] num_started: %" PRIu64,
- stats_.num_started);
- auto current_time = gpr_now(GPR_CLOCK_MONOTONIC);
- if (curr_count == 0) {
- busy_time = current_time;
- }
- queue_tail_->insert_time = current_time;
- }
-
- count_.Store(curr_count + 1, MemoryOrder::RELAXED);
- queue_tail_ = queue_tail_->next;
-
- TopWaiter()->cv.Signal();
-}
-
-void* InfLenFIFOQueue::Get(gpr_timespec* wait_time) {
- MutexLock l(&mu_);
-
- if (count_.Load(MemoryOrder::RELAXED) == 0) {
- gpr_timespec start_time;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace) &&
- wait_time != nullptr) {
- start_time = gpr_now(GPR_CLOCK_MONOTONIC);
- }
-
- Waiter self;
- PushWaiter(&self);
- do {
- self.cv.Wait(&mu_);
- } while (count_.Load(MemoryOrder::RELAXED) == 0);
- RemoveWaiter(&self);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace) &&
- wait_time != nullptr) {
- *wait_time = gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), start_time);
- }
- }
- GPR_DEBUG_ASSERT(count_.Load(MemoryOrder::RELAXED) > 0);
- return PopFront();
-}
-
-void InfLenFIFOQueue::PushWaiter(Waiter* waiter) {
- waiter->next = waiters_.next;
- waiter->prev = &waiters_;
- waiter->next->prev = waiter;
- waiter->prev->next = waiter;
-}
-
-void InfLenFIFOQueue::RemoveWaiter(Waiter* waiter) {
- GPR_DEBUG_ASSERT(waiter != &waiters_);
- waiter->next->prev = waiter->prev;
- waiter->prev->next = waiter->next;
-}
-
-InfLenFIFOQueue::Waiter* InfLenFIFOQueue::TopWaiter() { return waiters_.next; }
-
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/executor/mpmcqueue.h"
+
+namespace grpc_core {
+
+DebugOnlyTraceFlag grpc_thread_pool_trace(false, "thread_pool");
+
+inline void* InfLenFIFOQueue::PopFront() {
+ // Caller should already check queue is not empty and has already held the
+ // mutex. This function will assume that there is at least one element in the
+ // queue (i.e. queue_head_->content is valid).
+ void* result = queue_head_->content;
+ count_.Store(count_.Load(MemoryOrder::RELAXED) - 1, MemoryOrder::RELAXED);
+
+ // Updates Stats when trace flag turned on.
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {
+ gpr_timespec wait_time =
+ gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), queue_head_->insert_time);
+ stats_.num_completed++;
+ stats_.total_queue_time = gpr_time_add(stats_.total_queue_time, wait_time);
+ stats_.max_queue_time = gpr_time_max(
+ gpr_convert_clock_type(stats_.max_queue_time, GPR_TIMESPAN), wait_time);
+
+ if (count_.Load(MemoryOrder::RELAXED) == 0) {
+ stats_.busy_queue_time =
+ gpr_time_add(stats_.busy_queue_time,
+ gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), busy_time));
+ }
+
+ gpr_log(GPR_INFO,
+ "[InfLenFIFOQueue PopFront] num_completed: %" PRIu64
+ " total_queue_time: %f max_queue_time: %f busy_queue_time: %f",
+ stats_.num_completed,
+ gpr_timespec_to_micros(stats_.total_queue_time),
+ gpr_timespec_to_micros(stats_.max_queue_time),
+ gpr_timespec_to_micros(stats_.busy_queue_time));
+ }
+
+ queue_head_ = queue_head_->next;
+ // Signal waiting thread
+ if (count_.Load(MemoryOrder::RELAXED) > 0) {
+ TopWaiter()->cv.Signal();
+ }
+
+ return result;
+}
+
+InfLenFIFOQueue::Node* InfLenFIFOQueue::AllocateNodes(int num) {
+ num_nodes_ = num_nodes_ + num;
+ Node* new_chunk = static_cast<Node*>(gpr_zalloc(sizeof(Node) * num));
+ new_chunk[0].next = &new_chunk[1];
+ new_chunk[num - 1].prev = &new_chunk[num - 2];
+ for (int i = 1; i < num - 1; ++i) {
+ new_chunk[i].prev = &new_chunk[i - 1];
+ new_chunk[i].next = &new_chunk[i + 1];
+ }
+ return new_chunk;
+}
+
+InfLenFIFOQueue::InfLenFIFOQueue() {
+ delete_list_size_ = kDeleteListInitSize;
+ delete_list_ =
+ static_cast<Node**>(gpr_zalloc(sizeof(Node*) * delete_list_size_));
+
+ Node* new_chunk = AllocateNodes(kQueueInitNumNodes);
+ delete_list_[delete_list_count_++] = new_chunk;
+ queue_head_ = queue_tail_ = new_chunk;
+ new_chunk[0].prev = &new_chunk[kQueueInitNumNodes - 1];
+ new_chunk[kQueueInitNumNodes - 1].next = &new_chunk[0];
+
+ waiters_.next = &waiters_;
+ waiters_.prev = &waiters_;
+}
+
+InfLenFIFOQueue::~InfLenFIFOQueue() {
+ GPR_ASSERT(count_.Load(MemoryOrder::RELAXED) == 0);
+ for (size_t i = 0; i < delete_list_count_; ++i) {
+ gpr_free(delete_list_[i]);
+ }
+ gpr_free(delete_list_);
+}
+
+void InfLenFIFOQueue::Put(void* elem) {
+ MutexLock l(&mu_);
+
+ int curr_count = count_.Load(MemoryOrder::RELAXED);
+
+ if (queue_tail_ == queue_head_ && curr_count != 0) {
+ // List is full. Expands list to double size by inserting new chunk of nodes
+ Node* new_chunk = AllocateNodes(curr_count);
+ delete_list_[delete_list_count_++] = new_chunk;
+ // Expands delete list on full.
+ if (delete_list_count_ == delete_list_size_) {
+ delete_list_size_ = delete_list_size_ * 2;
+ delete_list_ = static_cast<Node**>(
+ gpr_realloc(delete_list_, sizeof(Node*) * delete_list_size_));
+ }
+ new_chunk[0].prev = queue_tail_->prev;
+ new_chunk[curr_count - 1].next = queue_head_;
+ queue_tail_->prev->next = new_chunk;
+ queue_head_->prev = &new_chunk[curr_count - 1];
+ queue_tail_ = new_chunk;
+ }
+ queue_tail_->content = static_cast<void*>(elem);
+
+ // Updates Stats info
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {
+ stats_.num_started++;
+ gpr_log(GPR_INFO, "[InfLenFIFOQueue Put] num_started: %" PRIu64,
+ stats_.num_started);
+ auto current_time = gpr_now(GPR_CLOCK_MONOTONIC);
+ if (curr_count == 0) {
+ busy_time = current_time;
+ }
+ queue_tail_->insert_time = current_time;
+ }
+
+ count_.Store(curr_count + 1, MemoryOrder::RELAXED);
+ queue_tail_ = queue_tail_->next;
+
+ TopWaiter()->cv.Signal();
+}
+
+void* InfLenFIFOQueue::Get(gpr_timespec* wait_time) {
+ MutexLock l(&mu_);
+
+ if (count_.Load(MemoryOrder::RELAXED) == 0) {
+ gpr_timespec start_time;
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace) &&
+ wait_time != nullptr) {
+ start_time = gpr_now(GPR_CLOCK_MONOTONIC);
+ }
+
+ Waiter self;
+ PushWaiter(&self);
+ do {
+ self.cv.Wait(&mu_);
+ } while (count_.Load(MemoryOrder::RELAXED) == 0);
+ RemoveWaiter(&self);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace) &&
+ wait_time != nullptr) {
+ *wait_time = gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), start_time);
+ }
+ }
+ GPR_DEBUG_ASSERT(count_.Load(MemoryOrder::RELAXED) > 0);
+ return PopFront();
+}
+
+void InfLenFIFOQueue::PushWaiter(Waiter* waiter) {
+ waiter->next = waiters_.next;
+ waiter->prev = &waiters_;
+ waiter->next->prev = waiter;
+ waiter->prev->next = waiter;
+}
+
+void InfLenFIFOQueue::RemoveWaiter(Waiter* waiter) {
+ GPR_DEBUG_ASSERT(waiter != &waiters_);
+ waiter->next->prev = waiter->prev;
+ waiter->prev->next = waiter->next;
+}
+
+InfLenFIFOQueue::Waiter* InfLenFIFOQueue::TopWaiter() { return waiters_.next; }
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.h b/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.h
index 474f40bbf8..37306c6f95 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor/mpmcqueue.h
@@ -1,175 +1,175 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_EXECUTOR_MPMCQUEUE_H
-#define GRPC_CORE_LIB_IOMGR_EXECUTOR_MPMCQUEUE_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/gprpp/sync.h"
-
-namespace grpc_core {
-
-extern DebugOnlyTraceFlag grpc_thread_pool_trace;
-
-// Abstract base class of a Multiple-Producer-Multiple-Consumer(MPMC) queue
-// interface
-class MPMCQueueInterface {
- public:
- virtual ~MPMCQueueInterface() {}
-
- // Puts elem into queue immediately at the end of queue.
- // This might cause to block on full queue depending on implementation.
- virtual void Put(void* elem) = 0;
-
- // Removes the oldest element from the queue and return it.
- // This might cause to block on empty queue depending on implementation.
- // Optional argument for collecting stats purpose.
- virtual void* Get(gpr_timespec* wait_time = nullptr) = 0;
-
- // Returns number of elements in the queue currently
- virtual int count() const = 0;
-};
-
-class InfLenFIFOQueue : public MPMCQueueInterface {
- public:
- // Creates a new MPMC Queue. The queue created will have infinite length.
- InfLenFIFOQueue();
-
- // Releases all resources held by the queue. The queue must be empty, and no
- // one waits on conditional variables.
- ~InfLenFIFOQueue();
-
- // Puts elem into queue immediately at the end of queue. Since the queue has
- // infinite length, this routine will never block and should never fail.
- void Put(void* elem);
-
- // Removes the oldest element from the queue and returns it.
- // This routine will cause the thread to block if queue is currently empty.
- // Argument wait_time should be passed in when trace flag turning on (for
- // collecting stats info purpose.)
- void* Get(gpr_timespec* wait_time = nullptr);
-
- // Returns number of elements in queue currently.
- // There might be concurrently add/remove on queue, so count might change
- // quickly.
- int count() const { return count_.Load(MemoryOrder::RELAXED); }
-
- struct Node {
- Node* next; // Linking
- Node* prev;
- void* content; // Points to actual element
- gpr_timespec insert_time; // Time for stats
-
- Node() {
- next = prev = nullptr;
- content = nullptr;
- }
- };
-
- // For test purpose only. Returns number of nodes allocated in queue.
- // Any allocated node will be alive until the destruction of the queue.
- int num_nodes() const { return num_nodes_; }
-
- // For test purpose only. Returns the initial number of nodes in queue.
- int init_num_nodes() const { return kQueueInitNumNodes; }
-
- private:
- // For Internal Use Only.
- // Removes the oldest element from the queue and returns it. This routine
- // will NOT check whether queue is empty, and it will NOT acquire mutex.
- // Caller MUST check that queue is not empty and must acquire mutex before
- // callling.
- void* PopFront();
-
- // Stats of queue. This will only be collect when debug trace mode is on.
- // All printed stats info will have time measurement in microsecond.
- struct Stats {
- uint64_t num_started; // Number of elements have been added to queue
- uint64_t num_completed; // Number of elements have been removed from
- // the queue
- gpr_timespec total_queue_time; // Total waiting time that all the
- // removed elements have spent in queue
- gpr_timespec max_queue_time; // Max waiting time among all removed
- // elements
- gpr_timespec busy_queue_time; // Accumulated amount of time that queue
- // was not empty
-
- Stats() {
- num_started = 0;
- num_completed = 0;
- total_queue_time = gpr_time_0(GPR_TIMESPAN);
- max_queue_time = gpr_time_0(GPR_TIMESPAN);
- busy_queue_time = gpr_time_0(GPR_TIMESPAN);
- }
- };
-
- // Node for waiting thread queue. Stands for one waiting thread, should have
- // exact one thread waiting on its CondVar.
- // Using a doubly linked list for waiting thread queue to wake up waiting
- // threads in LIFO order to reduce cache misses.
- struct Waiter {
- CondVar cv;
- Waiter* next;
- Waiter* prev;
- };
-
- // Pushs waiter to the front of queue, require caller held mutex
- void PushWaiter(Waiter* waiter);
-
- // Removes waiter from queue, require caller held mutex
- void RemoveWaiter(Waiter* waiter);
-
- // Returns pointer to the waiter that should be waken up next, should be the
- // last added waiter.
- Waiter* TopWaiter();
-
- Mutex mu_; // Protecting lock
- Waiter waiters_; // Head of waiting thread queue
-
- // Initial size for delete list
- static const int kDeleteListInitSize = 1024;
- // Initial number of nodes allocated
- static const int kQueueInitNumNodes = 1024;
-
- Node** delete_list_ = nullptr; // Keeps track of all allocated array entries
- // for deleting on destruction
- size_t delete_list_count_ = 0; // Number of entries in list
- size_t delete_list_size_ = 0; // Size of the list. List will be expanded to
- // double size on full
-
- Node* queue_head_ = nullptr; // Head of the queue, remove position
- Node* queue_tail_ = nullptr; // End of queue, insert position
- Atomic<int> count_{0}; // Number of elements in queue
- int num_nodes_ = 0; // Number of nodes allocated
-
- Stats stats_; // Stats info
- gpr_timespec busy_time; // Start time of busy queue
-
- // Internal Helper.
- // Allocates an array of nodes of size "num", links all nodes together except
- // the first node's prev and last node's next. They should be set by caller
- // manually afterward.
- Node* AllocateNodes(int num);
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_MPMCQUEUE_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_EXECUTOR_MPMCQUEUE_H
+#define GRPC_CORE_LIB_IOMGR_EXECUTOR_MPMCQUEUE_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/sync.h"
+
+namespace grpc_core {
+
+extern DebugOnlyTraceFlag grpc_thread_pool_trace;
+
+// Abstract base class of a Multiple-Producer-Multiple-Consumer(MPMC) queue
+// interface
+class MPMCQueueInterface {
+ public:
+ virtual ~MPMCQueueInterface() {}
+
+ // Puts elem into queue immediately at the end of queue.
+ // This might cause to block on full queue depending on implementation.
+ virtual void Put(void* elem) = 0;
+
+ // Removes the oldest element from the queue and return it.
+ // This might cause to block on empty queue depending on implementation.
+ // Optional argument for collecting stats purpose.
+ virtual void* Get(gpr_timespec* wait_time = nullptr) = 0;
+
+ // Returns number of elements in the queue currently
+ virtual int count() const = 0;
+};
+
+class InfLenFIFOQueue : public MPMCQueueInterface {
+ public:
+ // Creates a new MPMC Queue. The queue created will have infinite length.
+ InfLenFIFOQueue();
+
+ // Releases all resources held by the queue. The queue must be empty, and no
+ // one waits on conditional variables.
+ ~InfLenFIFOQueue();
+
+ // Puts elem into queue immediately at the end of queue. Since the queue has
+ // infinite length, this routine will never block and should never fail.
+ void Put(void* elem);
+
+ // Removes the oldest element from the queue and returns it.
+ // This routine will cause the thread to block if queue is currently empty.
+ // Argument wait_time should be passed in when trace flag turning on (for
+ // collecting stats info purpose.)
+ void* Get(gpr_timespec* wait_time = nullptr);
+
+ // Returns number of elements in queue currently.
+ // There might be concurrently add/remove on queue, so count might change
+ // quickly.
+ int count() const { return count_.Load(MemoryOrder::RELAXED); }
+
+ struct Node {
+ Node* next; // Linking
+ Node* prev;
+ void* content; // Points to actual element
+ gpr_timespec insert_time; // Time for stats
+
+ Node() {
+ next = prev = nullptr;
+ content = nullptr;
+ }
+ };
+
+ // For test purpose only. Returns number of nodes allocated in queue.
+ // Any allocated node will be alive until the destruction of the queue.
+ int num_nodes() const { return num_nodes_; }
+
+ // For test purpose only. Returns the initial number of nodes in queue.
+ int init_num_nodes() const { return kQueueInitNumNodes; }
+
+ private:
+ // For Internal Use Only.
+ // Removes the oldest element from the queue and returns it. This routine
+ // will NOT check whether queue is empty, and it will NOT acquire mutex.
+ // Caller MUST check that queue is not empty and must acquire mutex before
+ // callling.
+ void* PopFront();
+
+ // Stats of queue. This will only be collect when debug trace mode is on.
+ // All printed stats info will have time measurement in microsecond.
+ struct Stats {
+ uint64_t num_started; // Number of elements have been added to queue
+ uint64_t num_completed; // Number of elements have been removed from
+ // the queue
+ gpr_timespec total_queue_time; // Total waiting time that all the
+ // removed elements have spent in queue
+ gpr_timespec max_queue_time; // Max waiting time among all removed
+ // elements
+ gpr_timespec busy_queue_time; // Accumulated amount of time that queue
+ // was not empty
+
+ Stats() {
+ num_started = 0;
+ num_completed = 0;
+ total_queue_time = gpr_time_0(GPR_TIMESPAN);
+ max_queue_time = gpr_time_0(GPR_TIMESPAN);
+ busy_queue_time = gpr_time_0(GPR_TIMESPAN);
+ }
+ };
+
+ // Node for waiting thread queue. Stands for one waiting thread, should have
+ // exact one thread waiting on its CondVar.
+ // Using a doubly linked list for waiting thread queue to wake up waiting
+ // threads in LIFO order to reduce cache misses.
+ struct Waiter {
+ CondVar cv;
+ Waiter* next;
+ Waiter* prev;
+ };
+
+ // Pushs waiter to the front of queue, require caller held mutex
+ void PushWaiter(Waiter* waiter);
+
+ // Removes waiter from queue, require caller held mutex
+ void RemoveWaiter(Waiter* waiter);
+
+ // Returns pointer to the waiter that should be waken up next, should be the
+ // last added waiter.
+ Waiter* TopWaiter();
+
+ Mutex mu_; // Protecting lock
+ Waiter waiters_; // Head of waiting thread queue
+
+ // Initial size for delete list
+ static const int kDeleteListInitSize = 1024;
+ // Initial number of nodes allocated
+ static const int kQueueInitNumNodes = 1024;
+
+ Node** delete_list_ = nullptr; // Keeps track of all allocated array entries
+ // for deleting on destruction
+ size_t delete_list_count_ = 0; // Number of entries in list
+ size_t delete_list_size_ = 0; // Size of the list. List will be expanded to
+ // double size on full
+
+ Node* queue_head_ = nullptr; // Head of the queue, remove position
+ Node* queue_tail_ = nullptr; // End of queue, insert position
+ Atomic<int> count_{0}; // Number of elements in queue
+ int num_nodes_ = 0; // Number of nodes allocated
+
+ Stats stats_; // Stats info
+ gpr_timespec busy_time; // Start time of busy queue
+
+ // Internal Helper.
+ // Allocates an array of nodes of size "num", links all nodes together except
+ // the first node's prev and last node's next. They should be set by caller
+ // manually afterward.
+ Node* AllocateNodes(int num);
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_MPMCQUEUE_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.cc b/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.cc
index 859c49a3ea..72a2344346 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.cc
@@ -1,137 +1,137 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/executor/threadpool.h"
-
-namespace grpc_core {
-
-void ThreadPoolWorker::Run() {
- while (true) {
- void* elem;
-
- if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {
- // Updates stats and print
- gpr_timespec wait_time = gpr_time_0(GPR_TIMESPAN);
- elem = queue_->Get(&wait_time);
- stats_.sleep_time = gpr_time_add(stats_.sleep_time, wait_time);
- gpr_log(GPR_INFO,
- "ThreadPool Worker [%s %d] Stats: sleep_time %f",
- thd_name_, index_, gpr_timespec_to_micros(stats_.sleep_time));
- } else {
- elem = queue_->Get(nullptr);
- }
- if (elem == nullptr) {
- break;
- }
- // Runs closure
- auto* closure =
- static_cast<grpc_experimental_completion_queue_functor*>(elem);
- closure->functor_run(closure, closure->internal_success);
- }
-}
-
-void ThreadPool::SharedThreadPoolConstructor() {
- // All worker threads in thread pool must be joinable.
- thread_options_.set_joinable(true);
-
- // Create at least 1 worker thread.
- if (num_threads_ <= 0) num_threads_ = 1;
-
- queue_ = new InfLenFIFOQueue();
- threads_ = static_cast<ThreadPoolWorker**>(
- gpr_zalloc(num_threads_ * sizeof(ThreadPoolWorker*)));
- for (int i = 0; i < num_threads_; ++i) {
- threads_[i] = new ThreadPoolWorker(thd_name_, queue_, thread_options_, i);
- threads_[i]->Start();
- }
-}
-
-size_t ThreadPool::DefaultStackSize() {
-#if defined(__ANDROID__) || defined(__APPLE__)
- return 1952 * 1024;
-#else
- return 64 * 1024;
-#endif
-}
-
-void ThreadPool::AssertHasNotBeenShutDown() {
- // For debug checking purpose, using RELAXED order is sufficient.
- GPR_DEBUG_ASSERT(!shut_down_.Load(MemoryOrder::RELAXED));
-}
-
-ThreadPool::ThreadPool(int num_threads) : num_threads_(num_threads) {
- thd_name_ = "ThreadPoolWorker";
- thread_options_ = Thread::Options();
- thread_options_.set_stack_size(DefaultStackSize());
- SharedThreadPoolConstructor();
-}
-
-ThreadPool::ThreadPool(int num_threads, const char* thd_name)
- : num_threads_(num_threads), thd_name_(thd_name) {
- thread_options_ = Thread::Options();
- thread_options_.set_stack_size(DefaultStackSize());
- SharedThreadPoolConstructor();
-}
-
-ThreadPool::ThreadPool(int num_threads, const char* thd_name,
- const Thread::Options& thread_options)
- : num_threads_(num_threads),
- thd_name_(thd_name),
- thread_options_(thread_options) {
- if (thread_options_.stack_size() == 0) {
- thread_options_.set_stack_size(DefaultStackSize());
- }
- SharedThreadPoolConstructor();
-}
-
-ThreadPool::~ThreadPool() {
- // For debug checking purpose, using RELAXED order is sufficient.
- shut_down_.Store(true, MemoryOrder::RELAXED);
-
- for (int i = 0; i < num_threads_; ++i) {
- queue_->Put(nullptr);
- }
-
- for (int i = 0; i < num_threads_; ++i) {
- threads_[i]->Join();
- }
-
- for (int i = 0; i < num_threads_; ++i) {
- delete threads_[i];
- }
- gpr_free(threads_);
- delete queue_;
-}
-
-void ThreadPool::Add(grpc_experimental_completion_queue_functor* closure) {
- AssertHasNotBeenShutDown();
- queue_->Put(static_cast<void*>(closure));
-}
-
-int ThreadPool::num_pending_closures() const { return queue_->count(); }
-
-int ThreadPool::pool_capacity() const { return num_threads_; }
-
-const Thread::Options& ThreadPool::thread_options() const {
- return thread_options_;
-}
-
-const char* ThreadPool::thread_name() const { return thd_name_; }
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/executor/threadpool.h"
+
+namespace grpc_core {
+
+void ThreadPoolWorker::Run() {
+ while (true) {
+ void* elem;
+
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {
+ // Updates stats and print
+ gpr_timespec wait_time = gpr_time_0(GPR_TIMESPAN);
+ elem = queue_->Get(&wait_time);
+ stats_.sleep_time = gpr_time_add(stats_.sleep_time, wait_time);
+ gpr_log(GPR_INFO,
+ "ThreadPool Worker [%s %d] Stats: sleep_time %f",
+ thd_name_, index_, gpr_timespec_to_micros(stats_.sleep_time));
+ } else {
+ elem = queue_->Get(nullptr);
+ }
+ if (elem == nullptr) {
+ break;
+ }
+ // Runs closure
+ auto* closure =
+ static_cast<grpc_experimental_completion_queue_functor*>(elem);
+ closure->functor_run(closure, closure->internal_success);
+ }
+}
+
+void ThreadPool::SharedThreadPoolConstructor() {
+ // All worker threads in thread pool must be joinable.
+ thread_options_.set_joinable(true);
+
+ // Create at least 1 worker thread.
+ if (num_threads_ <= 0) num_threads_ = 1;
+
+ queue_ = new InfLenFIFOQueue();
+ threads_ = static_cast<ThreadPoolWorker**>(
+ gpr_zalloc(num_threads_ * sizeof(ThreadPoolWorker*)));
+ for (int i = 0; i < num_threads_; ++i) {
+ threads_[i] = new ThreadPoolWorker(thd_name_, queue_, thread_options_, i);
+ threads_[i]->Start();
+ }
+}
+
+size_t ThreadPool::DefaultStackSize() {
+#if defined(__ANDROID__) || defined(__APPLE__)
+ return 1952 * 1024;
+#else
+ return 64 * 1024;
+#endif
+}
+
+void ThreadPool::AssertHasNotBeenShutDown() {
+ // For debug checking purpose, using RELAXED order is sufficient.
+ GPR_DEBUG_ASSERT(!shut_down_.Load(MemoryOrder::RELAXED));
+}
+
+ThreadPool::ThreadPool(int num_threads) : num_threads_(num_threads) {
+ thd_name_ = "ThreadPoolWorker";
+ thread_options_ = Thread::Options();
+ thread_options_.set_stack_size(DefaultStackSize());
+ SharedThreadPoolConstructor();
+}
+
+ThreadPool::ThreadPool(int num_threads, const char* thd_name)
+ : num_threads_(num_threads), thd_name_(thd_name) {
+ thread_options_ = Thread::Options();
+ thread_options_.set_stack_size(DefaultStackSize());
+ SharedThreadPoolConstructor();
+}
+
+ThreadPool::ThreadPool(int num_threads, const char* thd_name,
+ const Thread::Options& thread_options)
+ : num_threads_(num_threads),
+ thd_name_(thd_name),
+ thread_options_(thread_options) {
+ if (thread_options_.stack_size() == 0) {
+ thread_options_.set_stack_size(DefaultStackSize());
+ }
+ SharedThreadPoolConstructor();
+}
+
+ThreadPool::~ThreadPool() {
+ // For debug checking purpose, using RELAXED order is sufficient.
+ shut_down_.Store(true, MemoryOrder::RELAXED);
+
+ for (int i = 0; i < num_threads_; ++i) {
+ queue_->Put(nullptr);
+ }
+
+ for (int i = 0; i < num_threads_; ++i) {
+ threads_[i]->Join();
+ }
+
+ for (int i = 0; i < num_threads_; ++i) {
+ delete threads_[i];
+ }
+ gpr_free(threads_);
+ delete queue_;
+}
+
+void ThreadPool::Add(grpc_experimental_completion_queue_functor* closure) {
+ AssertHasNotBeenShutDown();
+ queue_->Put(static_cast<void*>(closure));
+}
+
+int ThreadPool::num_pending_closures() const { return queue_->count(); }
+
+int ThreadPool::pool_capacity() const { return num_threads_; }
+
+const Thread::Options& ThreadPool::thread_options() const {
+ return thread_options_;
+}
+
+const char* ThreadPool::thread_name() const { return thd_name_; }
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.h b/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.h
index 01a00c025f..97f524a1a4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor/threadpool.h
@@ -1,149 +1,149 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_EXECUTOR_THREADPOOL_H
-#define GRPC_CORE_LIB_IOMGR_EXECUTOR_THREADPOOL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/executor/mpmcqueue.h"
-
-namespace grpc_core {
-
-// A base abstract base class for threadpool.
-// Threadpool is an executor that maintains a pool of threads sitting around
-// and waiting for closures. A threadpool also maintains a queue of pending
-// closures, when closures appearing in the queue, the threads in pool will
-// pull them out and execute them.
-class ThreadPoolInterface {
- public:
- // Waits for all pending closures to complete, then shuts down thread pool.
- virtual ~ThreadPoolInterface() {}
-
- // Schedules a given closure for execution later.
- // Depending on specific subclass implementation, this routine might cause
- // current thread to be blocked (in case of unable to schedule).
- // Closure should contain a function pointer and arguments it will take, more
- // details for closure struct at /grpc/include/grpc/impl/codegen/grpc_types.h
- virtual void Add(grpc_experimental_completion_queue_functor* closure) = 0;
-
- // Returns the current number of pending closures
- virtual int num_pending_closures() const = 0;
-
- // Returns the capacity of pool (number of worker threads in pool)
- virtual int pool_capacity() const = 0;
-
- // Thread option accessor
- virtual const Thread::Options& thread_options() const = 0;
-
- // Returns the thread name for threads in this ThreadPool.
- virtual const char* thread_name() const = 0;
-};
-
-// Worker thread for threadpool. Executes closures in the queue, until getting a
-// NULL closure.
-class ThreadPoolWorker {
- public:
- ThreadPoolWorker(const char* thd_name, MPMCQueueInterface* queue,
- Thread::Options& options, int index)
- : queue_(queue), thd_name_(thd_name), index_(index) {
- thd_ = Thread(thd_name,
- [](void* th) { static_cast<ThreadPoolWorker*>(th)->Run(); },
- this, nullptr, options);
- }
-
- ~ThreadPoolWorker() {}
-
- void Start() { thd_.Start(); }
- void Join() { thd_.Join(); }
-
- private:
- // struct for tracking stats of thread
- struct Stats {
- gpr_timespec sleep_time;
- Stats() { sleep_time = gpr_time_0(GPR_TIMESPAN); }
- };
-
- void Run(); // Pulls closures from queue and executes them
-
- MPMCQueueInterface* queue_; // Queue in thread pool to pull closures from
- Thread thd_; // Thread wrapped in
- Stats stats_; // Stats to be collected in run time
- const char* thd_name_; // Name of thread
- int index_; // Index in thread pool
-};
-
-// A fixed size thread pool implementation of abstract thread pool interface.
-// In this implementation, the number of threads in pool is fixed, but the
-// capacity of closure queue is unlimited.
-class ThreadPool : public ThreadPoolInterface {
- public:
- // Creates a thread pool with size of "num_threads", with default thread name
- // "ThreadPoolWorker" and all thread options set to default. If the given size
- // is 0 or less, there will be 1 worker thread created inside pool.
- ThreadPool(int num_threads);
-
- // Same as ThreadPool(int num_threads) constructor, except
- // that it also sets "thd_name" as the name of all threads in the thread pool.
- ThreadPool(int num_threads, const char* thd_name);
-
- // Same as ThreadPool(const char *thd_name, int num_threads) constructor,
- // except that is also set thread_options for threads.
- // Notes for stack size:
- // If the stack size field of the passed in Thread::Options is set to default
- // value 0, default ThreadPool stack size will be used. The current default
- // stack size of this implementation is 1952K for mobile platform and 64K for
- // all others.
- ThreadPool(int num_threads, const char* thd_name,
- const Thread::Options& thread_options);
-
- // Waits for all pending closures to complete, then shuts down thread pool.
- ~ThreadPool() override;
-
- // Adds given closure into pending queue immediately. Since closure queue has
- // infinite length, this routine will not block.
- void Add(grpc_experimental_completion_queue_functor* closure) override;
-
- int num_pending_closures() const override;
- int pool_capacity() const override;
- const Thread::Options& thread_options() const override;
- const char* thread_name() const override;
-
- private:
- int num_threads_ = 0;
- const char* thd_name_ = nullptr;
- Thread::Options thread_options_;
- ThreadPoolWorker** threads_ = nullptr; // Array of worker threads
- MPMCQueueInterface* queue_ = nullptr; // Closure queue
-
- Atomic<bool> shut_down_{false}; // Destructor has been called if set to true
-
- void SharedThreadPoolConstructor();
- // For ThreadPool, default stack size for mobile platform is 1952K. for other
- // platforms is 64K.
- size_t DefaultStackSize();
- // Internal Use Only for debug checking.
- void AssertHasNotBeenShutDown();
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_THREADPOOL_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_EXECUTOR_THREADPOOL_H
+#define GRPC_CORE_LIB_IOMGR_EXECUTOR_THREADPOOL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/executor/mpmcqueue.h"
+
+namespace grpc_core {
+
+// A base abstract base class for threadpool.
+// Threadpool is an executor that maintains a pool of threads sitting around
+// and waiting for closures. A threadpool also maintains a queue of pending
+// closures, when closures appearing in the queue, the threads in pool will
+// pull them out and execute them.
+class ThreadPoolInterface {
+ public:
+ // Waits for all pending closures to complete, then shuts down thread pool.
+ virtual ~ThreadPoolInterface() {}
+
+ // Schedules a given closure for execution later.
+ // Depending on specific subclass implementation, this routine might cause
+ // current thread to be blocked (in case of unable to schedule).
+ // Closure should contain a function pointer and arguments it will take, more
+ // details for closure struct at /grpc/include/grpc/impl/codegen/grpc_types.h
+ virtual void Add(grpc_experimental_completion_queue_functor* closure) = 0;
+
+ // Returns the current number of pending closures
+ virtual int num_pending_closures() const = 0;
+
+ // Returns the capacity of pool (number of worker threads in pool)
+ virtual int pool_capacity() const = 0;
+
+ // Thread option accessor
+ virtual const Thread::Options& thread_options() const = 0;
+
+ // Returns the thread name for threads in this ThreadPool.
+ virtual const char* thread_name() const = 0;
+};
+
+// Worker thread for threadpool. Executes closures in the queue, until getting a
+// NULL closure.
+class ThreadPoolWorker {
+ public:
+ ThreadPoolWorker(const char* thd_name, MPMCQueueInterface* queue,
+ Thread::Options& options, int index)
+ : queue_(queue), thd_name_(thd_name), index_(index) {
+ thd_ = Thread(thd_name,
+ [](void* th) { static_cast<ThreadPoolWorker*>(th)->Run(); },
+ this, nullptr, options);
+ }
+
+ ~ThreadPoolWorker() {}
+
+ void Start() { thd_.Start(); }
+ void Join() { thd_.Join(); }
+
+ private:
+ // struct for tracking stats of thread
+ struct Stats {
+ gpr_timespec sleep_time;
+ Stats() { sleep_time = gpr_time_0(GPR_TIMESPAN); }
+ };
+
+ void Run(); // Pulls closures from queue and executes them
+
+ MPMCQueueInterface* queue_; // Queue in thread pool to pull closures from
+ Thread thd_; // Thread wrapped in
+ Stats stats_; // Stats to be collected in run time
+ const char* thd_name_; // Name of thread
+ int index_; // Index in thread pool
+};
+
+// A fixed size thread pool implementation of abstract thread pool interface.
+// In this implementation, the number of threads in pool is fixed, but the
+// capacity of closure queue is unlimited.
+class ThreadPool : public ThreadPoolInterface {
+ public:
+ // Creates a thread pool with size of "num_threads", with default thread name
+ // "ThreadPoolWorker" and all thread options set to default. If the given size
+ // is 0 or less, there will be 1 worker thread created inside pool.
+ ThreadPool(int num_threads);
+
+ // Same as ThreadPool(int num_threads) constructor, except
+ // that it also sets "thd_name" as the name of all threads in the thread pool.
+ ThreadPool(int num_threads, const char* thd_name);
+
+ // Same as ThreadPool(const char *thd_name, int num_threads) constructor,
+ // except that is also set thread_options for threads.
+ // Notes for stack size:
+ // If the stack size field of the passed in Thread::Options is set to default
+ // value 0, default ThreadPool stack size will be used. The current default
+ // stack size of this implementation is 1952K for mobile platform and 64K for
+ // all others.
+ ThreadPool(int num_threads, const char* thd_name,
+ const Thread::Options& thread_options);
+
+ // Waits for all pending closures to complete, then shuts down thread pool.
+ ~ThreadPool() override;
+
+ // Adds given closure into pending queue immediately. Since closure queue has
+ // infinite length, this routine will not block.
+ void Add(grpc_experimental_completion_queue_functor* closure) override;
+
+ int num_pending_closures() const override;
+ int pool_capacity() const override;
+ const Thread::Options& thread_options() const override;
+ const char* thread_name() const override;
+
+ private:
+ int num_threads_ = 0;
+ const char* thd_name_ = nullptr;
+ Thread::Options thread_options_;
+ ThreadPoolWorker** threads_ = nullptr; // Array of worker threads
+ MPMCQueueInterface* queue_ = nullptr; // Closure queue
+
+ Atomic<bool> shut_down_{false}; // Destructor has been called if set to true
+
+ void SharedThreadPoolConstructor();
+ // For ThreadPool, default stack size for mobile platform is 1952K. for other
+ // platforms is 64K.
+ size_t DefaultStackSize();
+ // Internal Use Only for debug checking.
+ void AssertHasNotBeenShutDown();
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_THREADPOOL_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc
index 82654b5a88..9376358dd4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc
@@ -63,10 +63,10 @@ void grpc_prefork() {
"environment variable GRPC_ENABLE_FORK_SUPPORT=1");
return;
}
- const char* poll_strategy_name = grpc_get_poll_strategy_name();
- if (poll_strategy_name == nullptr ||
- (strcmp(poll_strategy_name, "epoll1") != 0 &&
- strcmp(poll_strategy_name, "poll") != 0)) {
+ const char* poll_strategy_name = grpc_get_poll_strategy_name();
+ if (poll_strategy_name == nullptr ||
+ (strcmp(poll_strategy_name, "epoll1") != 0 &&
+ strcmp(poll_strategy_name, "poll") != 0)) {
gpr_log(GPR_INFO,
"Fork support is only compatible with the epoll1 and poll polling "
"strategies");
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc b/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc
index b68c66b757..118819a639 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc
@@ -36,9 +36,9 @@ static bool errqueue_supported = false;
bool kernel_supports_errqueue() { return errqueue_supported; }
void grpc_errqueue_init() {
-/* Both-compile time and run-time linux kernel versions should be at least 4.0.0
+/* Both-compile time and run-time linux kernel versions should be at least 4.0.0
*/
-#ifdef GRPC_LINUX_ERRQUEUE
+#ifdef GRPC_LINUX_ERRQUEUE
struct utsname buffer;
if (uname(&buffer) != 0) {
gpr_log(GPR_ERROR, "uname: %s", strerror(errno));
@@ -54,7 +54,7 @@ void grpc_errqueue_init() {
} else {
gpr_log(GPR_DEBUG, "ERRQUEUE support not enabled");
}
-#endif /* GRPC_LINUX_ERRQUEUE */
+#endif /* GRPC_LINUX_ERRQUEUE */
}
} /* namespace grpc_core */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc
index 29a05ee309..2758f7a274 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc
@@ -90,12 +90,12 @@ grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline) {
abort();
}
if (socket->shutdown_called) {
- info->bytes_transferred = 0;
+ info->bytes_transferred = 0;
info->wsa_error = WSA_OPERATION_ABORTED;
} else {
success = WSAGetOverlappedResult(socket->socket, &info->overlapped, &bytes,
FALSE, &flags);
- info->bytes_transferred = bytes;
+ info->bytes_transferred = bytes;
info->wsa_error = success ? 0 : WSAGetLastError();
}
GPR_ASSERT(overlapped == &info->overlapped);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc
index 802e3bdcb4..df3e416eb1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc
@@ -31,7 +31,7 @@
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/buffer_list.h"
#include "src/core/lib/iomgr/exec_ctx.h"
@@ -41,15 +41,15 @@
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/iomgr/timer_manager.h"
-GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_abort_on_leaks, false,
- "A debugging aid to cause a call to abort() when "
- "gRPC objects are leaked past grpc_shutdown()");
-
+GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_abort_on_leaks, false,
+ "A debugging aid to cause a call to abort() when "
+ "gRPC objects are leaked past grpc_shutdown()");
+
static gpr_mu g_mu;
static gpr_cv g_rcv;
static int g_shutdown;
static grpc_iomgr_object g_root_object;
-static bool g_grpc_abort_on_leaks;
+static bool g_grpc_abort_on_leaks;
void grpc_iomgr_init() {
grpc_core::ExecCtx exec_ctx;
@@ -61,9 +61,9 @@ void grpc_iomgr_init() {
g_root_object.next = g_root_object.prev = &g_root_object;
g_root_object.name = (char*)"root";
grpc_iomgr_platform_init();
- grpc_timer_list_init();
+ grpc_timer_list_init();
grpc_core::grpc_errqueue_init();
- g_grpc_abort_on_leaks = GPR_GLOBAL_CONFIG_GET(grpc_abort_on_leaks);
+ g_grpc_abort_on_leaks = GPR_GLOBAL_CONFIG_GET(grpc_abort_on_leaks);
}
void grpc_iomgr_start() { grpc_timer_manager_init(); }
@@ -168,11 +168,11 @@ bool grpc_iomgr_is_any_background_poller_thread() {
return grpc_iomgr_platform_is_any_background_poller_thread();
}
-bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure,
- grpc_error* error) {
- return grpc_iomgr_platform_add_closure_to_background_poller(closure, error);
-}
-
+bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure,
+ grpc_error* error) {
+ return grpc_iomgr_platform_add_closure_to_background_poller(closure, error);
+}
+
void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name) {
obj->name = gpr_strdup(name);
gpr_mu_lock(&g_mu);
@@ -191,4 +191,4 @@ void grpc_iomgr_unregister_object(grpc_iomgr_object* obj) {
gpr_free(obj->name);
}
-bool grpc_iomgr_abort_on_leaks(void) { return g_grpc_abort_on_leaks; }
+bool grpc_iomgr_abort_on_leaks(void) { return g_grpc_abort_on_leaks; }
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h
index e02f15e551..e85e09436c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h
@@ -21,7 +21,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/port.h"
#include <stdlib.h>
@@ -48,12 +48,12 @@ bool grpc_iomgr_run_in_background();
/** Returns true if the caller is a worker thread for any background poller. */
bool grpc_iomgr_is_any_background_poller_thread();
-/** Returns true if the closure is registered into the background poller. Note
- * that the closure may or may not run yet when this function returns, and the
- * closure should not be blocking or long-running. */
-bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure,
- grpc_error* error);
-
+/** Returns true if the closure is registered into the background poller. Note
+ * that the closure may or may not run yet when this function returns, and the
+ * closure should not be blocking or long-running. */
+bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure,
+ grpc_error* error);
+
/* Exposed only for testing */
size_t grpc_iomgr_count_objects_for_testing();
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc
index 684044a5bb..3d4ae0e3d8 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc
@@ -44,26 +44,26 @@ static void iomgr_platform_shutdown_background_closure(void) {}
static bool iomgr_platform_is_any_background_poller_thread(void) {
return false;
}
-static bool iomgr_platform_add_closure_to_background_poller(
- grpc_closure* /*closure*/, grpc_error* /*error*/) {
- return false;
-}
-
-bool g_custom_iomgr_enabled = false;
+static bool iomgr_platform_add_closure_to_background_poller(
+ grpc_closure* /*closure*/, grpc_error* /*error*/) {
+ return false;
+}
+bool g_custom_iomgr_enabled = false;
+
static grpc_iomgr_platform_vtable vtable = {
- iomgr_platform_init,
- iomgr_platform_flush,
- iomgr_platform_shutdown,
+ iomgr_platform_init,
+ iomgr_platform_flush,
+ iomgr_platform_shutdown,
iomgr_platform_shutdown_background_closure,
- iomgr_platform_is_any_background_poller_thread,
- iomgr_platform_add_closure_to_background_poller};
+ iomgr_platform_is_any_background_poller_thread,
+ iomgr_platform_add_closure_to_background_poller};
void grpc_custom_iomgr_init(grpc_socket_vtable* socket,
grpc_custom_resolver_vtable* resolver,
grpc_custom_timer_vtable* timer,
grpc_custom_poller_vtable* poller) {
- g_custom_iomgr_enabled = true;
+ g_custom_iomgr_enabled = true;
grpc_custom_endpoint_init(socket);
grpc_custom_timer_init(timer);
grpc_custom_pollset_init(poller);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h
index e6a88843e5..7c177c4440 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h
@@ -39,8 +39,8 @@ extern gpr_thd_id g_init_thread;
#define GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD()
#endif /* GRPC_CUSTOM_IOMGR_THREAD_CHECK */
-extern bool g_custom_iomgr_enabled;
-
+extern bool g_custom_iomgr_enabled;
+
void grpc_custom_iomgr_init(grpc_socket_vtable* socket,
grpc_custom_resolver_vtable* resolver,
grpc_custom_timer_vtable* timer,
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc
index 896d9fce67..6332138b1e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc
@@ -49,9 +49,9 @@ void grpc_iomgr_platform_shutdown_background_closure() {
bool grpc_iomgr_platform_is_any_background_poller_thread() {
return iomgr_platform_vtable->is_any_background_poller_thread();
}
-
-bool grpc_iomgr_platform_add_closure_to_background_poller(grpc_closure* closure,
- grpc_error* error) {
- return iomgr_platform_vtable->add_closure_to_background_poller(closure,
- error);
-}
+
+bool grpc_iomgr_platform_add_closure_to_background_poller(grpc_closure* closure,
+ grpc_error* error) {
+ return iomgr_platform_vtable->add_closure_to_background_poller(closure,
+ error);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h
index 17607f98f1..9e325b2dfa 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h
@@ -37,8 +37,8 @@ typedef struct grpc_iomgr_platform_vtable {
void (*shutdown)(void);
void (*shutdown_background_closure)(void);
bool (*is_any_background_poller_thread)(void);
- bool (*add_closure_to_background_poller)(grpc_closure* closure,
- grpc_error* error);
+ bool (*add_closure_to_background_poller)(grpc_closure* closure,
+ grpc_error* error);
} grpc_iomgr_platform_vtable;
void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name);
@@ -59,15 +59,15 @@ void grpc_iomgr_platform_shutdown(void);
/** shut down all the closures registered in the background poller */
void grpc_iomgr_platform_shutdown_background_closure(void);
-/** return true if the caller is a worker thread for any background poller */
+/** return true if the caller is a worker thread for any background poller */
bool grpc_iomgr_platform_is_any_background_poller_thread(void);
-/** Return true if the closure is registered into the background poller. Note
- * that the closure may or may not run yet when this function returns, and the
- * closure should not be blocking or long-running. */
-bool grpc_iomgr_platform_add_closure_to_background_poller(grpc_closure* closure,
- grpc_error* error);
-
+/** Return true if the closure is registered into the background poller. Note
+ * that the closure may or may not run yet when this function returns, and the
+ * closure should not be blocking or long-running. */
+bool grpc_iomgr_platform_add_closure_to_background_poller(grpc_closure* closure,
+ grpc_error* error);
+
bool grpc_iomgr_abort_on_leaks(void);
#endif /* GRPC_CORE_LIB_IOMGR_IOMGR_INTERNAL_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc
index de22d20a63..ea37946a6e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc
@@ -59,18 +59,18 @@ static bool iomgr_platform_is_any_background_poller_thread(void) {
return grpc_is_any_background_poller_thread();
}
-static bool iomgr_platform_add_closure_to_background_poller(
- grpc_closure* closure, grpc_error* error) {
- return grpc_add_closure_to_background_poller(closure, error);
-}
-
+static bool iomgr_platform_add_closure_to_background_poller(
+ grpc_closure* closure, grpc_error* error) {
+ return grpc_add_closure_to_background_poller(closure, error);
+}
+
static grpc_iomgr_platform_vtable vtable = {
- iomgr_platform_init,
- iomgr_platform_flush,
- iomgr_platform_shutdown,
+ iomgr_platform_init,
+ iomgr_platform_flush,
+ iomgr_platform_shutdown,
iomgr_platform_shutdown_background_closure,
- iomgr_platform_is_any_background_poller_thread,
- iomgr_platform_add_closure_to_background_poller};
+ iomgr_platform_is_any_background_poller_thread,
+ iomgr_platform_add_closure_to_background_poller};
void grpc_set_default_iomgr_platform() {
grpc_set_tcp_client_impl(&grpc_posix_tcp_client_vtable);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc
index 30c44edb5d..6f6b1b6254 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc
@@ -105,18 +105,18 @@ static bool iomgr_platform_is_any_background_poller_thread(void) {
return grpc_is_any_background_poller_thread();
}
-static bool iomgr_platform_add_closure_to_background_poller(
- grpc_closure* closure, grpc_error* error) {
- return grpc_add_closure_to_background_poller(closure, error);
-}
-
+static bool iomgr_platform_add_closure_to_background_poller(
+ grpc_closure* closure, grpc_error* error) {
+ return grpc_add_closure_to_background_poller(closure, error);
+}
+
static grpc_iomgr_platform_vtable vtable = {
- iomgr_platform_init,
- iomgr_platform_flush,
- iomgr_platform_shutdown,
+ iomgr_platform_init,
+ iomgr_platform_flush,
+ iomgr_platform_shutdown,
iomgr_platform_shutdown_background_closure,
- iomgr_platform_is_any_background_poller_thread,
- iomgr_platform_add_closure_to_background_poller};
+ iomgr_platform_is_any_background_poller_thread,
+ iomgr_platform_add_closure_to_background_poller};
void grpc_set_default_iomgr_platform() {
char* enable_cfstream_str = getenv(grpc_cfstream_env_var);
@@ -147,12 +147,12 @@ void grpc_set_default_iomgr_platform() {
grpc_set_pollset_vtable(&grpc_apple_pollset_vtable);
grpc_set_pollset_set_vtable(&grpc_apple_pollset_set_vtable);
grpc_set_iomgr_platform_vtable(&apple_vtable);
- }
+ }
grpc_set_timer_impl(&grpc_generic_timer_vtable);
grpc_set_resolver_impl(&grpc_posix_resolver_vtable);
}
-bool grpc_iomgr_run_in_background() {
+bool grpc_iomgr_run_in_background() {
char* enable_cfstream_str = getenv(grpc_cfstream_env_var);
bool enable_cfstream =
enable_cfstream_str == nullptr || enable_cfstream_str[0] != '0';
@@ -166,6 +166,6 @@ bool grpc_iomgr_run_in_background() {
} else {
return grpc_event_engine_run_in_background();
}
-}
-
+}
+
#endif /* GRPC_CFSTREAM_IOMGR */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc
index a617239678..b017284bca 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc
@@ -37,7 +37,7 @@ void grpc_set_default_iomgr_platform() {
grpc_custom_iomgr_init(&grpc_uv_socket_vtable, &uv_resolver_vtable,
&uv_timer_vtable, &uv_pollset_vtable);
}
-
-bool grpc_iomgr_run_in_background() { return false; }
-
+
+bool grpc_iomgr_run_in_background() { return false; }
+
#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc
index 728d404081..09624564e4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc
@@ -61,7 +61,7 @@ static void iomgr_platform_init(void) {
winsock_init();
grpc_iocp_init();
grpc_pollset_global_init();
- grpc_wsa_socket_flags_init();
+ grpc_wsa_socket_flags_init();
}
static void iomgr_platform_flush(void) { grpc_iocp_flush(); }
@@ -78,18 +78,18 @@ static bool iomgr_platform_is_any_background_poller_thread(void) {
return false;
}
-static bool iomgr_platform_add_closure_to_background_poller(
- grpc_closure* closure, grpc_error* error) {
- return false;
-}
-
+static bool iomgr_platform_add_closure_to_background_poller(
+ grpc_closure* closure, grpc_error* error) {
+ return false;
+}
+
static grpc_iomgr_platform_vtable vtable = {
- iomgr_platform_init,
- iomgr_platform_flush,
- iomgr_platform_shutdown,
+ iomgr_platform_init,
+ iomgr_platform_flush,
+ iomgr_platform_shutdown,
iomgr_platform_shutdown_background_closure,
- iomgr_platform_is_any_background_poller_thread,
- iomgr_platform_add_closure_to_background_poller};
+ iomgr_platform_is_any_background_poller_thread,
+ iomgr_platform_add_closure_to_background_poller};
void grpc_set_default_iomgr_platform() {
grpc_set_tcp_client_impl(&grpc_windows_tcp_client_vtable);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc
index 4b28af4ba4..a67b33291a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc
@@ -23,9 +23,9 @@
#include <grpc/support/log.h>
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
-extern grpc_core::DebugOnlyTraceFlag grpc_polling_trace;
+extern grpc_core::DebugOnlyTraceFlag grpc_polling_trace;
/* 'state' holds the to call when the fd is readable or writable respectively.
It can contain one of the following values:
@@ -95,8 +95,8 @@ void LockfreeEvent::NotifyOn(grpc_closure* closure) {
* sure that the shutdown error has been initialized properly before us
* referencing it. */
gpr_atm curr = gpr_atm_acq_load(&state_);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_DEBUG, "LockfreeEvent::NotifyOn: %p curr=%p closure=%p", this,
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ gpr_log(GPR_DEBUG, "LockfreeEvent::NotifyOn: %p curr=%p closure=%p", this,
(void*)curr, closure);
}
switch (curr) {
@@ -125,7 +125,7 @@ void LockfreeEvent::NotifyOn(grpc_closure* closure) {
closure when transitioning out of CLOSURE_NO_READY state (i.e there
is no other code that needs to 'happen-after' this) */
if (gpr_atm_no_barrier_cas(&state_, kClosureReady, kClosureNotReady)) {
- ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
return; /* Successful. Return */
}
@@ -138,9 +138,9 @@ void LockfreeEvent::NotifyOn(grpc_closure* closure) {
schedule the closure with the shutdown error */
if ((curr & kShutdownBit) > 0) {
grpc_error* shutdown_err = (grpc_error*)(curr & ~kShutdownBit);
- ExecCtx::Run(DEBUG_LOCATION, closure,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "FD Shutdown", &shutdown_err, 1));
+ ExecCtx::Run(DEBUG_LOCATION, closure,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "FD Shutdown", &shutdown_err, 1));
return;
}
@@ -161,8 +161,8 @@ bool LockfreeEvent::SetShutdown(grpc_error* shutdown_err) {
while (true) {
gpr_atm curr = gpr_atm_no_barrier_load(&state_);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_DEBUG, "LockfreeEvent::SetShutdown: %p curr=%p err=%s",
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ gpr_log(GPR_DEBUG, "LockfreeEvent::SetShutdown: %p curr=%p err=%s",
&state_, (void*)curr, grpc_error_string(shutdown_err));
}
switch (curr) {
@@ -190,9 +190,9 @@ bool LockfreeEvent::SetShutdown(grpc_error* shutdown_err) {
happens-after on that edge), and a release to pair with anything
loading the shutdown state. */
if (gpr_atm_full_cas(&state_, curr, new_state)) {
- ExecCtx::Run(DEBUG_LOCATION, (grpc_closure*)curr,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "FD Shutdown", &shutdown_err, 1));
+ ExecCtx::Run(DEBUG_LOCATION, (grpc_closure*)curr,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "FD Shutdown", &shutdown_err, 1));
return true;
}
@@ -210,8 +210,8 @@ void LockfreeEvent::SetReady() {
while (true) {
gpr_atm curr = gpr_atm_no_barrier_load(&state_);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_DEBUG, "LockfreeEvent::SetReady: %p curr=%p", &state_,
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
+ gpr_log(GPR_DEBUG, "LockfreeEvent::SetReady: %p curr=%p", &state_,
(void*)curr);
}
@@ -240,7 +240,7 @@ void LockfreeEvent::SetReady() {
spurious set_ready; release pairs with this or the acquire in
notify_on (or set_shutdown) */
else if (gpr_atm_full_cas(&state_, curr, kClosureNotReady)) {
- ExecCtx::Run(DEBUG_LOCATION, (grpc_closure*)curr, GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION, (grpc_closure*)curr, GRPC_ERROR_NONE);
return;
}
/* else the state changed again (only possible by either a racing
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/poller/eventmanager_interface.h b/contrib/libs/grpc/src/core/lib/iomgr/poller/eventmanager_interface.h
index b4fbaeb7bb..911f4aaf5a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/poller/eventmanager_interface.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/poller/eventmanager_interface.h
@@ -1,35 +1,35 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H
-#define GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H
-
-namespace grpc {
-namespace experimental {
-
-class BaseEventManagerInterface {
- public:
- virtual ~BaseEventManagerInterface() {}
-};
-
-class EpollEventManagerInterface : public BaseEventManagerInterface {};
-
-} // namespace experimental
-} // namespace grpc
-
-#endif /* GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H
+#define GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H
+
+namespace grpc {
+namespace experimental {
+
+class BaseEventManagerInterface {
+ public:
+ virtual ~BaseEventManagerInterface() {}
+};
+
+class EpollEventManagerInterface : public BaseEventManagerInterface {};
+
+} // namespace experimental
+} // namespace grpc
+
+#endif /* GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc
index 98c8e64e2f..714894639c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc
@@ -53,9 +53,9 @@ static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
*mu = &pollset->mu;
}
-static void pollset_shutdown(grpc_pollset* /*pollset*/, grpc_closure* closure) {
+static void pollset_shutdown(grpc_pollset* /*pollset*/, grpc_closure* closure) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
}
static void pollset_destroy(grpc_pollset* pollset) {
@@ -64,7 +64,7 @@ static void pollset_destroy(grpc_pollset* pollset) {
}
static grpc_error* pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** /*worker_hdl*/,
+ grpc_pollset_worker** /*worker_hdl*/,
grpc_millis deadline) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
gpr_mu_unlock(&pollset->mu);
@@ -87,8 +87,8 @@ static grpc_error* pollset_work(grpc_pollset* pollset,
return GRPC_ERROR_NONE;
}
-static grpc_error* pollset_kick(grpc_pollset* /*pollset*/,
- grpc_pollset_worker* /*specific_worker*/) {
+static grpc_error* pollset_kick(grpc_pollset* /*pollset*/,
+ grpc_pollset_worker* /*specific_worker*/) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
poller_vtable->kick();
return GRPC_ERROR_NONE;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc
index 184c330cf7..67621ca6b0 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc
@@ -98,7 +98,7 @@ static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
pollset->shutting_down = 1;
grpc_pollset_kick(pollset, GRPC_POLLSET_KICK_BROADCAST);
if (!pollset->is_iocp_worker) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
} else {
pollset->on_shutdown = closure;
}
@@ -146,8 +146,8 @@ static grpc_error* pollset_work(grpc_pollset* pollset,
}
if (pollset->shutting_down && pollset->on_shutdown != NULL) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->on_shutdown,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->on_shutdown,
+ GRPC_ERROR_NONE);
pollset->on_shutdown = NULL;
}
goto done;
@@ -185,23 +185,23 @@ done:
static grpc_error* pollset_kick(grpc_pollset* p,
grpc_pollset_worker* specific_worker) {
- bool should_kick_global = false;
+ bool should_kick_global = false;
if (specific_worker != NULL) {
if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
- should_kick_global = true;
+ should_kick_global = true;
for (specific_worker =
p->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next;
specific_worker != &p->root_worker;
specific_worker =
specific_worker->links[GRPC_POLLSET_WORKER_LINK_POLLSET].next) {
specific_worker->kicked = 1;
- should_kick_global = false;
+ should_kick_global = false;
gpr_cv_signal(&specific_worker->cv);
}
p->kicked_without_pollers = 1;
if (p->is_iocp_worker) {
grpc_iocp_kick();
- should_kick_global = false;
+ should_kick_global = false;
}
} else {
if (p->is_iocp_worker && g_active_poller == specific_worker) {
@@ -220,17 +220,17 @@ static grpc_error* pollset_kick(grpc_pollset* p,
grpc_iocp_kick();
} else {
p->kicked_without_pollers = 1;
- should_kick_global = true;
- }
- }
- if (should_kick_global && g_active_poller == NULL) {
- grpc_pollset_worker* next_global_worker = pop_front_worker(
- &g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL);
- if (next_global_worker != NULL) {
- next_global_worker->kicked = 1;
- gpr_cv_signal(&next_global_worker->cv);
+ should_kick_global = true;
}
}
+ if (should_kick_global && g_active_poller == NULL) {
+ grpc_pollset_worker* next_global_worker = pop_front_worker(
+ &g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL);
+ if (next_global_worker != NULL) {
+ next_global_worker->kicked = 1;
+ gpr_cv_signal(&next_global_worker->cv);
+ }
+ }
return GRPC_ERROR_NONE;
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/port.h b/contrib/libs/grpc/src/core/lib/iomgr/port.h
index 2a8d67b261..bacbe5546b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/port.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/port.h
@@ -26,17 +26,17 @@
#define GRPC_CUSTOM_SOCKET
#endif
#endif
-/* This needs to be separate from the other conditions because it needs to
- * apply to custom sockets too */
-#ifdef GPR_WINDOWS
-#define GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY 1
-#endif
+/* This needs to be separate from the other conditions because it needs to
+ * apply to custom sockets too */
+#ifdef GPR_WINDOWS
+#define GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY 1
+#endif
#if defined(GRPC_CUSTOM_SOCKET)
// Do Nothing
#elif defined(GPR_WINDOWS)
#define GRPC_WINSOCK_SOCKET 1
#define GRPC_WINDOWS_SOCKETUTILS 1
-#define GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER 1
+#define GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER 1
#elif defined(GPR_ANDROID)
#define GRPC_HAVE_IPV6_RECVPKTINFO 1
#define GRPC_HAVE_IP_PKTINFO 1
@@ -53,9 +53,9 @@
#define GRPC_HAVE_IP_PKTINFO 1
#define GRPC_HAVE_MSG_NOSIGNAL 1
#define GRPC_HAVE_UNIX_SOCKET 1
-/* Linux has TCP_INQ support since 4.18, but it is safe to set
- the socket option on older kernels. */
-#define GRPC_HAVE_TCP_INQ 1
+/* Linux has TCP_INQ support since 4.18, but it is safe to set
+ the socket option on older kernels. */
+#define GRPC_HAVE_TCP_INQ 1
#ifdef LINUX_VERSION_CODE
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0)
#define GRPC_LINUX_ERRQUEUE 1
@@ -77,13 +77,13 @@
#if __GLIBC_PREREQ(2, 10)
#define GRPC_LINUX_SOCKETUTILS 1
#endif
-#if !(__GLIBC_PREREQ(2, 17))
-/*
- * TCP_USER_TIMEOUT wasn't imported to glibc until 2.17. Use Linux system
- * header instead.
- */
-#define GRPC_LINUX_TCP_H 1
-#endif /* __GLIBC_PREREQ(2, 17) */
+#if !(__GLIBC_PREREQ(2, 17))
+/*
+ * TCP_USER_TIMEOUT wasn't imported to glibc until 2.17. Use Linux system
+ * header instead.
+ */
+#define GRPC_LINUX_TCP_H 1
+#endif /* __GLIBC_PREREQ(2, 17) */
#endif
#ifndef __GLIBC__
#define GRPC_LINUX_EPOLL 1
@@ -115,7 +115,7 @@
#define GRPC_POSIX_SOCKET_EV_EPOLL1 1
#define GRPC_POSIX_SOCKET_EV_EPOLLEX 1
#define GRPC_POSIX_SOCKET_EV_POLL 1
-#define GRPC_POSIX_SOCKET_IF_NAMETOINDEX 1
+#define GRPC_POSIX_SOCKET_IF_NAMETOINDEX 1
#define GRPC_POSIX_SOCKET_RESOLVE_ADDRESS 1
#define GRPC_POSIX_SOCKET_SOCKADDR 1
#define GRPC_POSIX_SOCKET_SOCKET_FACTORY 1
@@ -123,7 +123,7 @@
#define GRPC_POSIX_SOCKET_TCP_CLIENT 1
#define GRPC_POSIX_SOCKET_TCP_SERVER 1
#define GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON 1
-#define GRPC_POSIX_SOCKET_UDP_SERVER 1
+#define GRPC_POSIX_SOCKET_UDP_SERVER 1
#define GRPC_POSIX_SOCKET_UTILS_COMMON 1
#else
#define GRPC_POSIX_SOCKET 1
@@ -168,22 +168,22 @@
#define GRPC_POSIX_SOCKET 1
#define GRPC_POSIX_SOCKETUTILS 1
#define GRPC_POSIX_WAKEUP_FD 1
-#elif defined(GPR_FUCHSIA)
-#define GRPC_HAVE_IFADDRS 1
-#define GRPC_HAVE_IPV6_RECVPKTINFO 1
-#define GRPC_HAVE_IP_PKTINFO 1
-// Zircon does not support the MSG_NOSIGNAL flag since it doesn't support
-// signals.
-#undef GRPC_HAVE_MSG_NOSIGNAL
-#define GRPC_HAVE_UNIX_SOCKET 1
-#define GRPC_POSIX_WAKEUP_FD 1
-// TODO(rudominer) Check that this does something we want.
-#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
-#define GRPC_POSIX_SOCKET 1
-#define GRPC_POSIX_SOCKETADDR 1
-// TODO(rudominer) Check this does something we want.
-#define GRPC_POSIX_SOCKETUTILS 1
-#define GRPC_TIMER_USE_GENERIC 1
+#elif defined(GPR_FUCHSIA)
+#define GRPC_HAVE_IFADDRS 1
+#define GRPC_HAVE_IPV6_RECVPKTINFO 1
+#define GRPC_HAVE_IP_PKTINFO 1
+// Zircon does not support the MSG_NOSIGNAL flag since it doesn't support
+// signals.
+#undef GRPC_HAVE_MSG_NOSIGNAL
+#define GRPC_HAVE_UNIX_SOCKET 1
+#define GRPC_POSIX_WAKEUP_FD 1
+// TODO(rudominer) Check that this does something we want.
+#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
+#define GRPC_POSIX_SOCKET 1
+#define GRPC_POSIX_SOCKETADDR 1
+// TODO(rudominer) Check this does something we want.
+#define GRPC_POSIX_SOCKETUTILS 1
+#define GRPC_TIMER_USE_GENERIC 1
#elif !defined(GPR_NO_AUTODETECT_PLATFORM)
#error "Platform not recognized"
#endif
@@ -210,7 +210,7 @@
#define GRPC_POSIX_SOCKET_TCP_CLIENT 1
#define GRPC_POSIX_SOCKET_TCP_SERVER 1
#define GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON 1
-#define GRPC_POSIX_SOCKET_UDP_SERVER 1
+#define GRPC_POSIX_SOCKET_UDP_SERVER 1
#define GRPC_POSIX_SOCKET_UTILS_COMMON 1
#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/python_util.h b/contrib/libs/grpc/src/core/lib/iomgr/python_util.h
index 42174ab8d8..15b725663a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/python_util.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/python_util.h
@@ -1,46 +1,46 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_PYTHON_UTIL_H
-#define GRPC_CORE_LIB_IOMGR_PYTHON_UTIL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/slice.h>
-#include <grpc/status.h>
-#include "src/core/lib/iomgr/error.h"
-
-// These are only used by the gRPC Python extensions.
-// They are easier to define here (rather than in Cython)
-// because Cython doesn't handle #defines well.
-
-grpc_error* grpc_socket_error(char* error) {
- return grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(error),
- GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE);
-}
-
-char* grpc_slice_buffer_start(grpc_slice_buffer* buffer, int i) {
- return (char*)GRPC_SLICE_START_PTR(buffer->slices[i]);
-}
-
-int grpc_slice_buffer_length(grpc_slice_buffer* buffer, int i) {
- return GRPC_SLICE_LENGTH(buffer->slices[i]);
-}
-
-#endif
+/*
+ *
+ * Copyright 2018 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_PYTHON_UTIL_H
+#define GRPC_CORE_LIB_IOMGR_PYTHON_UTIL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/slice.h>
+#include <grpc/status.h>
+#include "src/core/lib/iomgr/error.h"
+
+// These are only used by the gRPC Python extensions.
+// They are easier to define here (rather than in Cython)
+// because Cython doesn't handle #defines well.
+
+grpc_error* grpc_socket_error(char* error) {
+ return grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(error),
+ GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE);
+}
+
+char* grpc_slice_buffer_start(grpc_slice_buffer* buffer, int i) {
+ return (char*)GRPC_SLICE_START_PTR(buffer->slices[i]);
+}
+
+int grpc_slice_buffer_length(grpc_slice_buffer* buffer, int i) {
+ return GRPC_SLICE_LENGTH(buffer->slices[i]);
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.cc
index 69b4382b2b..26d8939bdd 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.cc
@@ -31,7 +31,7 @@
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/iomgr/iomgr_custom.h"
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
@@ -73,7 +73,7 @@ void grpc_custom_resolve_callback(grpc_custom_resolver* r,
grpc_resolved_addresses* result,
grpc_error* error) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
if (error == GRPC_ERROR_NONE) {
*r->addresses = result;
@@ -81,16 +81,16 @@ void grpc_custom_resolve_callback(grpc_custom_resolver* r,
return;
}
if (r->on_done) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
}
delete r;
}
static grpc_error* try_split_host_port(const char* name,
- const char* default_port,
+ const char* default_port,
TString* host, TString* port) {
/* parse name, splitting it into host and port parts */
- grpc_core::SplitHostPort(name, host, port);
+ grpc_core::SplitHostPort(name, host, port);
if (host->empty()) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("unparseable host:port: '%s'", name).c_str());
@@ -138,7 +138,7 @@ static grpc_error* blocking_resolve_address_impl(
}
static void resolve_address_impl(const char* name, const char* default_port,
- grpc_pollset_set* /*interested_parties*/,
+ grpc_pollset_set* /*interested_parties*/,
grpc_closure* on_done,
grpc_resolved_addresses** addrs) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
@@ -146,7 +146,7 @@ static void resolve_address_impl(const char* name, const char* default_port,
TString port;
grpc_error* err = try_split_host_port(name, default_port, &host, &port);
if (err != GRPC_ERROR_NONE) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, err);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, err);
return;
}
grpc_custom_resolver* r = new grpc_custom_resolver();
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc
index 4f29087391..8ef7f93aa2 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc
@@ -35,7 +35,7 @@
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/block_annotate.h"
#include "src/core/lib/iomgr/executor.h"
@@ -60,7 +60,7 @@ static grpc_error* posix_blocking_resolve_address(
TString host;
TString port;
/* parse name, splitting it into host and port parts */
- grpc_core::SplitHostPort(name, &host, &port);
+ grpc_core::SplitHostPort(name, &host, &port);
if (host.empty()) {
err = grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"),
@@ -149,28 +149,28 @@ struct request {
};
/* Callback to be passed to grpc Executor to asynch-ify
* grpc_blocking_resolve_address */
-static void do_request_thread(void* rp, grpc_error* /*error*/) {
+static void do_request_thread(void* rp, grpc_error* /*error*/) {
request* r = static_cast<request*>(rp);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, r->on_done,
- grpc_blocking_resolve_address(r->name, r->default_port, r->addrs_out));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, r->on_done,
+ grpc_blocking_resolve_address(r->name, r->default_port, r->addrs_out));
gpr_free(r->name);
gpr_free(r->default_port);
gpr_free(r);
}
static void posix_resolve_address(const char* name, const char* default_port,
- grpc_pollset_set* /*interested_parties*/,
+ grpc_pollset_set* /*interested_parties*/,
grpc_closure* on_done,
grpc_resolved_addresses** addrs) {
request* r = static_cast<request*>(gpr_malloc(sizeof(request)));
- GRPC_CLOSURE_INIT(&r->request_closure, do_request_thread, r, nullptr);
+ GRPC_CLOSURE_INIT(&r->request_closure, do_request_thread, r, nullptr);
r->name = gpr_strdup(name);
r->default_port = gpr_strdup(default_port);
r->on_done = on_done;
r->addrs_out = addrs;
- grpc_core::Executor::Run(&r->request_closure, GRPC_ERROR_NONE,
- grpc_core::ExecutorType::RESOLVER);
+ grpc_core::Executor::Run(&r->request_closure, GRPC_ERROR_NONE,
+ grpc_core::ExecutorType::RESOLVER);
}
grpc_address_resolver_vtable grpc_posix_resolver_vtable = {
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_windows.cc
index 9922b88065..f4a39929c6 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_windows.cc
@@ -40,7 +40,7 @@
#include <grpc/support/time.h>
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/block_annotate.h"
#include "src/core/lib/iomgr/executor.h"
@@ -67,7 +67,7 @@ static grpc_error* windows_blocking_resolve_address(
/* parse name, splitting it into host and port parts */
TString host;
TString port;
- grpc_core::SplitHostPort(name, &host, &port);
+ grpc_core::SplitHostPort(name, &host, &port);
if (host.empty()) {
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("unparseable host:port: '%s'", name).c_str());
@@ -129,7 +129,7 @@ static void do_request_thread(void* rp, grpc_error* error) {
} else {
GRPC_ERROR_REF(error);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
gpr_free(r->name);
gpr_free(r->default_port);
gpr_free(r);
@@ -140,13 +140,13 @@ static void windows_resolve_address(const char* name, const char* default_port,
grpc_closure* on_done,
grpc_resolved_addresses** addresses) {
request* r = (request*)gpr_malloc(sizeof(request));
- GRPC_CLOSURE_INIT(&r->request_closure, do_request_thread, r, nullptr);
+ GRPC_CLOSURE_INIT(&r->request_closure, do_request_thread, r, nullptr);
r->name = gpr_strdup(name);
r->default_port = gpr_strdup(default_port);
r->on_done = on_done;
r->addresses = addresses;
- grpc_core::Executor::Run(&r->request_closure, GRPC_ERROR_NONE,
- grpc_core::ExecutorType::RESOLVER);
+ grpc_core::Executor::Run(&r->request_closure, GRPC_ERROR_NONE,
+ grpc_core::ExecutorType::RESOLVER);
}
grpc_address_resolver_vtable grpc_windows_resolver_vtable = {
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc
index f416e096f4..6e0b985ca0 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc
@@ -35,7 +35,7 @@
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/iomgr/combiner.h"
-#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_internal.h"
grpc_core::TraceFlag grpc_resource_quota_trace(false, "resource_quota");
@@ -134,7 +134,7 @@ struct grpc_resource_quota {
/* Master combiner lock: all activity on a quota executes under this combiner
* (so no mutex is needed for this data structure) */
- grpc_core::Combiner* combiner;
+ grpc_core::Combiner* combiner;
/* Size of the resource quota */
int64_t size;
/* Amount of free memory in the resource quota */
@@ -276,7 +276,7 @@ static bool rq_reclaim_from_per_user_free_pool(
grpc_resource_quota* resource_quota);
static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive);
-static void rq_step(void* rq, grpc_error* /*error*/) {
+static void rq_step(void* rq, grpc_error* /*error*/) {
grpc_resource_quota* resource_quota = static_cast<grpc_resource_quota*>(rq);
resource_quota->step_scheduled = false;
do {
@@ -295,8 +295,8 @@ static void rq_step_sched(grpc_resource_quota* resource_quota) {
if (resource_quota->step_scheduled) return;
resource_quota->step_scheduled = true;
grpc_resource_quota_ref_internal(resource_quota);
- resource_quota->combiner->FinallyRun(&resource_quota->rq_step_closure,
- GRPC_ERROR_NONE);
+ resource_quota->combiner->FinallyRun(&resource_quota->rq_step_closure,
+ GRPC_ERROR_NONE);
}
/* update the atomically available resource estimate - use no barriers since
@@ -320,7 +320,7 @@ static bool rq_alloc(grpc_resource_quota* resource_quota) {
while ((resource_user = rulist_pop_head(resource_quota,
GRPC_RULIST_AWAITING_ALLOCATION))) {
gpr_mu_lock(&resource_user->mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO,
"RQ: check allocation for user %p shutdown=%" PRIdPTR
" free_pool=%" PRId64 " outstanding_allocations=%" PRId64,
@@ -335,7 +335,7 @@ static bool rq_alloc(grpc_resource_quota* resource_quota) {
int64_t aborted_allocations = resource_user->outstanding_allocations;
resource_user->outstanding_allocations = 0;
resource_user->free_pool += aborted_allocations;
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &resource_user->on_allocated);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &resource_user->on_allocated);
gpr_mu_unlock(&resource_user->mu);
if (aborted_allocations > 0) {
ru_unref_by(resource_user, static_cast<gpr_atm>(aborted_allocations));
@@ -348,14 +348,14 @@ static bool rq_alloc(grpc_resource_quota* resource_quota) {
resource_user->free_pool = 0;
resource_quota->free_pool -= amt;
rq_update_estimate(resource_quota);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO,
"RQ %s %s: grant alloc %" PRId64
" bytes; rq_free_pool -> %" PRId64,
resource_quota->name.c_str(), resource_user->name.c_str(), amt,
resource_quota->free_pool);
}
- } else if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace) &&
+ } else if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace) &&
resource_user->free_pool >= 0) {
gpr_log(GPR_INFO, "RQ %s %s: discard already satisfied alloc request",
resource_quota->name.c_str(), resource_user->name.c_str());
@@ -363,7 +363,7 @@ static bool rq_alloc(grpc_resource_quota* resource_quota) {
if (resource_user->free_pool >= 0) {
resource_user->allocating = false;
resource_user->outstanding_allocations = 0;
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &resource_user->on_allocated);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &resource_user->on_allocated);
gpr_mu_unlock(&resource_user->mu);
} else {
rulist_add_head(resource_user, GRPC_RULIST_AWAITING_ALLOCATION);
@@ -387,7 +387,7 @@ static bool rq_reclaim_from_per_user_free_pool(
resource_user->free_pool = 0;
resource_quota->free_pool += amt;
rq_update_estimate(resource_quota);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO,
"RQ %s %s: reclaim_from_per_user_free_pool %" PRId64
" bytes; rq_free_pool -> %" PRId64,
@@ -397,7 +397,7 @@ static bool rq_reclaim_from_per_user_free_pool(
gpr_mu_unlock(&resource_user->mu);
return true;
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO,
"RQ %s %s: failed to reclaim_from_per_user_free_pool; "
"free_pool = %" PRId64 "; rq_free_pool = %" PRId64,
@@ -417,7 +417,7 @@ static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive) {
: GRPC_RULIST_RECLAIMER_BENIGN;
grpc_resource_user* resource_user = rulist_pop_head(resource_quota, list);
if (resource_user == nullptr) return false;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: initiate %s reclamation",
resource_quota->name.c_str(), resource_user->name.c_str(),
destructive ? "destructive" : "benign");
@@ -429,7 +429,7 @@ static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive) {
resource_quota->debug_only_last_reclaimer_resource_user = resource_user;
resource_quota->debug_only_last_initiated_reclaimer = c;
resource_user->reclaimers[destructive] = nullptr;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, c, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, c, GRPC_ERROR_NONE);
return true;
}
@@ -437,43 +437,43 @@ static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive) {
* ru_slice: a slice implementation that is backed by a grpc_resource_user
*/
-namespace grpc_core {
+namespace grpc_core {
-class RuSliceRefcount {
- public:
- static void Destroy(void* p) {
- auto* rc = static_cast<RuSliceRefcount*>(p);
- rc->~RuSliceRefcount();
+class RuSliceRefcount {
+ public:
+ static void Destroy(void* p) {
+ auto* rc = static_cast<RuSliceRefcount*>(p);
+ rc->~RuSliceRefcount();
gpr_free(rc);
}
- RuSliceRefcount(grpc_resource_user* resource_user, size_t size)
- : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
- &base_),
- resource_user_(resource_user),
- size_(size) {
- // Nothing to do here.
- }
- ~RuSliceRefcount() { grpc_resource_user_free(resource_user_, size_); }
-
- grpc_slice_refcount* base_refcount() { return &base_; }
-
- private:
- grpc_slice_refcount base_;
- RefCount refs_;
- grpc_resource_user* resource_user_;
- size_t size_;
-};
-
-} // namespace grpc_core
-
+ RuSliceRefcount(grpc_resource_user* resource_user, size_t size)
+ : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
+ &base_),
+ resource_user_(resource_user),
+ size_(size) {
+ // Nothing to do here.
+ }
+ ~RuSliceRefcount() { grpc_resource_user_free(resource_user_, size_); }
+
+ grpc_slice_refcount* base_refcount() { return &base_; }
+
+ private:
+ grpc_slice_refcount base_;
+ RefCount refs_;
+ grpc_resource_user* resource_user_;
+ size_t size_;
+};
+
+} // namespace grpc_core
+
static grpc_slice ru_slice_create(grpc_resource_user* resource_user,
size_t size) {
- auto* rc = static_cast<grpc_core::RuSliceRefcount*>(
- gpr_malloc(sizeof(grpc_core::RuSliceRefcount) + size));
- new (rc) grpc_core::RuSliceRefcount(resource_user, size);
+ auto* rc = static_cast<grpc_core::RuSliceRefcount*>(
+ gpr_malloc(sizeof(grpc_core::RuSliceRefcount) + size));
+ new (rc) grpc_core::RuSliceRefcount(resource_user, size);
grpc_slice slice;
-
- slice.refcount = rc->base_refcount();
+
+ slice.refcount = rc->base_refcount();
slice.data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
slice.data.refcounted.length = size;
return slice;
@@ -484,7 +484,7 @@ static grpc_slice ru_slice_create(grpc_resource_user* resource_user,
* the combiner
*/
-static void ru_allocate(void* ru, grpc_error* /*error*/) {
+static void ru_allocate(void* ru, grpc_error* /*error*/) {
grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
if (rulist_empty(resource_user->resource_quota,
GRPC_RULIST_AWAITING_ALLOCATION)) {
@@ -493,7 +493,7 @@ static void ru_allocate(void* ru, grpc_error* /*error*/) {
rulist_add_tail(resource_user, GRPC_RULIST_AWAITING_ALLOCATION);
}
-static void ru_add_to_free_pool(void* ru, grpc_error* /*error*/) {
+static void ru_add_to_free_pool(void* ru, grpc_error* /*error*/) {
grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
if (!rulist_empty(resource_user->resource_quota,
GRPC_RULIST_AWAITING_ALLOCATION) &&
@@ -511,14 +511,14 @@ static bool ru_post_reclaimer(grpc_resource_user* resource_user,
resource_user->new_reclaimers[destructive] = nullptr;
GPR_ASSERT(resource_user->reclaimers[destructive] == nullptr);
if (gpr_atm_acq_load(&resource_user->shutdown) > 0) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_CANCELLED);
return false;
}
resource_user->reclaimers[destructive] = closure;
return true;
}
-static void ru_post_benign_reclaimer(void* ru, grpc_error* /*error*/) {
+static void ru_post_benign_reclaimer(void* ru, grpc_error* /*error*/) {
grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
if (!ru_post_reclaimer(resource_user, false)) return;
if (!rulist_empty(resource_user->resource_quota,
@@ -532,7 +532,7 @@ static void ru_post_benign_reclaimer(void* ru, grpc_error* /*error*/) {
rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_BENIGN);
}
-static void ru_post_destructive_reclaimer(void* ru, grpc_error* /*error*/) {
+static void ru_post_destructive_reclaimer(void* ru, grpc_error* /*error*/) {
grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
if (!ru_post_reclaimer(resource_user, true)) return;
if (!rulist_empty(resource_user->resource_quota,
@@ -548,16 +548,16 @@ static void ru_post_destructive_reclaimer(void* ru, grpc_error* /*error*/) {
rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE);
}
-static void ru_shutdown(void* ru, grpc_error* /*error*/) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+static void ru_shutdown(void* ru, grpc_error* /*error*/) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RU shutdown %p", ru);
}
grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
gpr_mu_lock(&resource_user->mu);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[0],
- GRPC_ERROR_CANCELLED);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[1],
- GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[0],
+ GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[1],
+ GRPC_ERROR_CANCELLED);
resource_user->reclaimers[0] = nullptr;
resource_user->reclaimers[1] = nullptr;
rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_BENIGN);
@@ -568,7 +568,7 @@ static void ru_shutdown(void* ru, grpc_error* /*error*/) {
gpr_mu_unlock(&resource_user->mu);
}
-static void ru_destroy(void* ru, grpc_error* /*error*/) {
+static void ru_destroy(void* ru, grpc_error* /*error*/) {
grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
GPR_ASSERT(gpr_atm_no_barrier_load(&resource_user->refs) == 0);
// Free all the remaining thread quota
@@ -579,10 +579,10 @@ static void ru_destroy(void* ru, grpc_error* /*error*/) {
for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
rulist_remove(resource_user, static_cast<grpc_rulist>(i));
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[0],
- GRPC_ERROR_CANCELLED);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[1],
- GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[0],
+ GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, resource_user->reclaimers[1],
+ GRPC_ERROR_CANCELLED);
if (resource_user->free_pool != 0) {
resource_user->resource_quota->free_pool += resource_user->free_pool;
rq_step_sched(resource_user->resource_quota);
@@ -592,21 +592,21 @@ static void ru_destroy(void* ru, grpc_error* /*error*/) {
delete resource_user;
}
-static void ru_alloc_slices(
- grpc_resource_user_slice_allocator* slice_allocator) {
- for (size_t i = 0; i < slice_allocator->count; i++) {
- grpc_slice_buffer_add_indexed(
- slice_allocator->dest, ru_slice_create(slice_allocator->resource_user,
- slice_allocator->length));
- }
-}
-
+static void ru_alloc_slices(
+ grpc_resource_user_slice_allocator* slice_allocator) {
+ for (size_t i = 0; i < slice_allocator->count; i++) {
+ grpc_slice_buffer_add_indexed(
+ slice_allocator->dest, ru_slice_create(slice_allocator->resource_user,
+ slice_allocator->length));
+ }
+}
+
static void ru_allocated_slices(void* arg, grpc_error* error) {
grpc_resource_user_slice_allocator* slice_allocator =
static_cast<grpc_resource_user_slice_allocator*>(arg);
- if (error == GRPC_ERROR_NONE) ru_alloc_slices(slice_allocator);
- grpc_core::Closure::Run(DEBUG_LOCATION, &slice_allocator->on_done,
- GRPC_ERROR_REF(error));
+ if (error == GRPC_ERROR_NONE) ru_alloc_slices(slice_allocator);
+ grpc_core::Closure::Run(DEBUG_LOCATION, &slice_allocator->on_done,
+ GRPC_ERROR_REF(error));
}
/*******************************************************************************
@@ -619,7 +619,7 @@ struct rq_resize_args {
grpc_resource_quota* resource_quota;
grpc_closure closure;
};
-static void rq_resize(void* args, grpc_error* /*error*/) {
+static void rq_resize(void* args, grpc_error* /*error*/) {
rq_resize_args* a = static_cast<rq_resize_args*>(args);
int64_t delta = a->size - a->resource_quota->size;
a->resource_quota->size += delta;
@@ -630,7 +630,7 @@ static void rq_resize(void* args, grpc_error* /*error*/) {
gpr_free(a);
}
-static void rq_reclamation_done(void* rq, grpc_error* /*error*/) {
+static void rq_reclamation_done(void* rq, grpc_error* /*error*/) {
grpc_resource_quota* resource_quota = static_cast<grpc_resource_quota*>(rq);
resource_quota->reclaiming = false;
rq_step_sched(resource_quota);
@@ -663,9 +663,9 @@ grpc_resource_quota* grpc_resource_quota_create(const char* name) {
y_absl::StrCat("anonymous_pool_", (intptr_t)resource_quota);
}
GRPC_CLOSURE_INIT(&resource_quota->rq_step_closure, rq_step, resource_quota,
- nullptr);
+ nullptr);
GRPC_CLOSURE_INIT(&resource_quota->rq_reclamation_done_closure,
- rq_reclamation_done, resource_quota, nullptr);
+ rq_reclamation_done, resource_quota, nullptr);
for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
resource_quota->roots[i] = nullptr;
}
@@ -725,7 +725,7 @@ void grpc_resource_quota_resize(grpc_resource_quota* resource_quota,
gpr_atm_no_barrier_store(&resource_quota->last_size,
(gpr_atm)GPR_MIN((size_t)GPR_ATM_MAX, size));
GRPC_CLOSURE_INIT(&a->closure, rq_resize, a, grpc_schedule_on_exec_ctx);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, &a->closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, &a->closure, GRPC_ERROR_NONE);
}
size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota) {
@@ -779,15 +779,15 @@ grpc_resource_user* grpc_resource_user_create(
resource_user->resource_quota =
grpc_resource_quota_ref_internal(resource_quota);
GRPC_CLOSURE_INIT(&resource_user->allocate_closure, &ru_allocate,
- resource_user, nullptr);
+ resource_user, nullptr);
GRPC_CLOSURE_INIT(&resource_user->add_to_free_pool_closure,
- &ru_add_to_free_pool, resource_user, nullptr);
+ &ru_add_to_free_pool, resource_user, nullptr);
GRPC_CLOSURE_INIT(&resource_user->post_reclaimer_closure[0],
- &ru_post_benign_reclaimer, resource_user, nullptr);
+ &ru_post_benign_reclaimer, resource_user, nullptr);
GRPC_CLOSURE_INIT(&resource_user->post_reclaimer_closure[1],
- &ru_post_destructive_reclaimer, resource_user, nullptr);
+ &ru_post_destructive_reclaimer, resource_user, nullptr);
GRPC_CLOSURE_INIT(&resource_user->destroy_closure, &ru_destroy, resource_user,
- nullptr);
+ nullptr);
gpr_mu_init(&resource_user->mu);
gpr_atm_rel_store(&resource_user->refs, 1);
gpr_atm_rel_store(&resource_user->shutdown, 0);
@@ -828,8 +828,8 @@ static void ru_unref_by(grpc_resource_user* resource_user, gpr_atm amount) {
gpr_atm old = gpr_atm_full_fetch_add(&resource_user->refs, -amount);
GPR_ASSERT(old >= amount);
if (old == amount) {
- resource_user->resource_quota->combiner->Run(
- &resource_user->destroy_closure, GRPC_ERROR_NONE);
+ resource_user->resource_quota->combiner->Run(
+ &resource_user->destroy_closure, GRPC_ERROR_NONE);
}
}
@@ -843,8 +843,8 @@ void grpc_resource_user_unref(grpc_resource_user* resource_user) {
void grpc_resource_user_shutdown(grpc_resource_user* resource_user) {
if (gpr_atm_full_fetch_add(&resource_user->shutdown, 1) == 0) {
- resource_user->resource_quota->combiner->Run(
- GRPC_CLOSURE_CREATE(ru_shutdown, resource_user, nullptr),
+ resource_user->resource_quota->combiner->Run(
+ GRPC_CLOSURE_CREATE(ru_shutdown, resource_user, nullptr),
GRPC_ERROR_NONE);
}
}
@@ -883,29 +883,29 @@ void grpc_resource_user_free_threads(grpc_resource_user* resource_user,
gpr_mu_unlock(&resource_user->resource_quota->thread_count_mu);
}
-static bool resource_user_alloc_locked(grpc_resource_user* resource_user,
+static bool resource_user_alloc_locked(grpc_resource_user* resource_user,
size_t size,
grpc_closure* optional_on_done) {
ru_ref_by(resource_user, static_cast<gpr_atm>(size));
resource_user->free_pool -= static_cast<int64_t>(size);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: alloc %" PRIdPTR "; free_pool -> %" PRId64,
resource_user->resource_quota->name.c_str(),
resource_user->name.c_str(), size, resource_user->free_pool);
}
- if (GPR_LIKELY(resource_user->free_pool >= 0)) return true;
- // Slow path: We need to wait for the free pool to refill.
- if (optional_on_done != nullptr) {
- resource_user->outstanding_allocations += static_cast<int64_t>(size);
- grpc_closure_list_append(&resource_user->on_allocated, optional_on_done,
- GRPC_ERROR_NONE);
+ if (GPR_LIKELY(resource_user->free_pool >= 0)) return true;
+ // Slow path: We need to wait for the free pool to refill.
+ if (optional_on_done != nullptr) {
+ resource_user->outstanding_allocations += static_cast<int64_t>(size);
+ grpc_closure_list_append(&resource_user->on_allocated, optional_on_done,
+ GRPC_ERROR_NONE);
}
- if (!resource_user->allocating) {
- resource_user->allocating = true;
- resource_user->resource_quota->combiner->Run(
- &resource_user->allocate_closure, GRPC_ERROR_NONE);
- }
- return false;
+ if (!resource_user->allocating) {
+ resource_user->allocating = true;
+ resource_user->resource_quota->combiner->Run(
+ &resource_user->allocate_closure, GRPC_ERROR_NONE);
+ }
+ return false;
}
bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user,
@@ -929,17 +929,17 @@ bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user,
return true;
}
-bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size,
+bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size,
grpc_closure* optional_on_done) {
// TODO(juanlishen): Maybe return immediately if shutting down. Deferring this
// because some tests become flaky after the change.
gpr_mu_lock(&resource_user->mu);
grpc_resource_quota* resource_quota = resource_user->resource_quota;
gpr_atm_no_barrier_fetch_add(&resource_quota->used, size);
- const bool ret =
- resource_user_alloc_locked(resource_user, size, optional_on_done);
+ const bool ret =
+ resource_user_alloc_locked(resource_user, size, optional_on_done);
gpr_mu_unlock(&resource_user->mu);
- return ret;
+ return ret;
}
void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) {
@@ -949,7 +949,7 @@ void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) {
GPR_ASSERT(prior >= static_cast<long>(size));
bool was_zero_or_negative = resource_user->free_pool <= 0;
resource_user->free_pool += static_cast<int64_t>(size);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: free %" PRIdPTR "; free_pool -> %" PRId64,
resource_user->resource_quota->name.c_str(),
resource_user->name.c_str(), size, resource_user->free_pool);
@@ -958,8 +958,8 @@ void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) {
if (is_bigger_than_zero && was_zero_or_negative &&
!resource_user->added_to_free_pool) {
resource_user->added_to_free_pool = true;
- resource_quota->combiner->Run(&resource_user->add_to_free_pool_closure,
- GRPC_ERROR_NONE);
+ resource_quota->combiner->Run(&resource_user->add_to_free_pool_closure,
+ GRPC_ERROR_NONE);
}
gpr_mu_unlock(&resource_user->mu);
ru_unref_by(resource_user, static_cast<gpr_atm>(size));
@@ -970,17 +970,17 @@ void grpc_resource_user_post_reclaimer(grpc_resource_user* resource_user,
grpc_closure* closure) {
GPR_ASSERT(resource_user->new_reclaimers[destructive] == nullptr);
resource_user->new_reclaimers[destructive] = closure;
- resource_user->resource_quota->combiner->Run(
- &resource_user->post_reclaimer_closure[destructive], GRPC_ERROR_NONE);
+ resource_user->resource_quota->combiner->Run(
+ &resource_user->post_reclaimer_closure[destructive], GRPC_ERROR_NONE);
}
void grpc_resource_user_finish_reclamation(grpc_resource_user* resource_user) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: reclamation complete",
resource_user->resource_quota->name.c_str(),
resource_user->name.c_str());
}
- resource_user->resource_quota->combiner->Run(
+ resource_user->resource_quota->combiner->Run(
&resource_user->resource_quota->rq_reclamation_done_closure,
GRPC_ERROR_NONE);
}
@@ -995,22 +995,22 @@ void grpc_resource_user_slice_allocator_init(
slice_allocator->resource_user = resource_user;
}
-bool grpc_resource_user_alloc_slices(
+bool grpc_resource_user_alloc_slices(
grpc_resource_user_slice_allocator* slice_allocator, size_t length,
size_t count, grpc_slice_buffer* dest) {
- if (GPR_UNLIKELY(
- gpr_atm_no_barrier_load(&slice_allocator->resource_user->shutdown))) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, &slice_allocator->on_allocated,
+ if (GPR_UNLIKELY(
+ gpr_atm_no_barrier_load(&slice_allocator->resource_user->shutdown))) {
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, &slice_allocator->on_allocated,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resource user shutdown"));
- return false;
+ return false;
}
slice_allocator->length = length;
slice_allocator->count = count;
slice_allocator->dest = dest;
- const bool ret =
- grpc_resource_user_alloc(slice_allocator->resource_user, count * length,
- &slice_allocator->on_allocated);
- if (ret) ru_alloc_slices(slice_allocator);
- return ret;
+ const bool ret =
+ grpc_resource_user_alloc(slice_allocator->resource_user, count * length,
+ &slice_allocator->on_allocated);
+ if (ret) ru_alloc_slices(slice_allocator);
+ return ret;
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h
index ec89a92020..ae1b4f2008 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h
@@ -124,15 +124,15 @@ bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user,
* If optional_on_done is NULL, then allocate immediately. This may push the
* quota over-limit, at which point reclamation will kick in. The caller is
* always responsible to free the memory eventually.
- * Returns true if the allocation was successful. Otherwise, if optional_on_done
- * is non-NULL, it will be scheduled without error when the allocation has been
- * granted by the quota, and the caller is responsible to free the memory
- * eventually. Or it may be scheduled with an error, in which case the caller
- * fails to allocate the memory and shouldn't free the memory.
+ * Returns true if the allocation was successful. Otherwise, if optional_on_done
+ * is non-NULL, it will be scheduled without error when the allocation has been
+ * granted by the quota, and the caller is responsible to free the memory
+ * eventually. Or it may be scheduled with an error, in which case the caller
+ * fails to allocate the memory and shouldn't free the memory.
*/
-bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size,
- grpc_closure* optional_on_done)
- GRPC_MUST_USE_RESULT;
+bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size,
+ grpc_closure* optional_on_done)
+ GRPC_MUST_USE_RESULT;
/* Release memory back to the quota */
void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size);
/* Post a memory reclaimer to the resource user. Only one benign and one
@@ -167,11 +167,11 @@ void grpc_resource_user_slice_allocator_init(
grpc_resource_user* resource_user, grpc_iomgr_cb_func cb, void* p);
/* Allocate \a count slices of length \a length into \a dest. Only one request
- can be outstanding at a time.
- Returns whether the slice was allocated inline in the function. If true,
- the \a slice_allocator->on_allocated callback will not be called. */
-bool grpc_resource_user_alloc_slices(
+ can be outstanding at a time.
+ Returns whether the slice was allocated inline in the function. If true,
+ the \a slice_allocator->on_allocated callback will not be called. */
+bool grpc_resource_user_alloc_slices(
grpc_resource_user_slice_allocator* slice_allocator, size_t length,
- size_t count, grpc_slice_buffer* dest) GRPC_MUST_USE_RESULT;
+ size_t count, grpc_slice_buffer* dest) GRPC_MUST_USE_RESULT;
#endif /* GRPC_CORE_LIB_IOMGR_RESOURCE_QUOTA_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc
index b43dbc9923..ed04d20eb6 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc
@@ -33,7 +33,7 @@
#include <grpc/support/log.h>
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/socket_utils.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
@@ -200,7 +200,7 @@ TString grpc_sockaddr_to_string(const grpc_resolved_address* resolved_addr,
void grpc_string_to_sockaddr(grpc_resolved_address* out, const char* addr,
int port) {
- memset(out, 0, sizeof(grpc_resolved_address));
+ memset(out, 0, sizeof(grpc_resolved_address));
grpc_sockaddr_in6* addr6 = (grpc_sockaddr_in6*)out->addr;
grpc_sockaddr_in* addr4 = (grpc_sockaddr_in*)out->addr;
if (grpc_inet_pton(GRPC_AF_INET6, addr, &addr6->sin6_addr) == 1) {
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc
index 8a8d4d3a22..783fe783bb 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc
@@ -30,11 +30,11 @@
#include <fcntl.h>
#include <limits.h>
#include <netinet/in.h>
-#ifdef GRPC_LINUX_TCP_H
-#include <linux/tcp.h>
-#else
+#ifdef GRPC_LINUX_TCP_H
+#include <linux/tcp.h>
+#else
#include <netinet/tcp.h>
-#endif
+#endif
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
@@ -111,16 +111,16 @@ grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd) {
if ((newval != 0) != (val != 0)) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_NOSIGPIPE");
}
-#else
- // Avoid unused parameter warning for conditional parameter
- (void)fd;
+#else
+ // Avoid unused parameter warning for conditional parameter
+ (void)fd;
#endif
return GRPC_ERROR_NONE;
}
grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd) {
- // Use conditionally-important parameter to avoid warning
- (void)fd;
+ // Use conditionally-important parameter to avoid warning
+ (void)fd;
#ifdef GRPC_HAVE_IP_PKTINFO
int get_local_ip = 1;
if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip,
@@ -132,8 +132,8 @@ grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd) {
}
grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) {
- // Use conditionally-important parameter to avoid warning
- (void)fd;
+ // Use conditionally-important parameter to avoid warning
+ (void)fd;
#ifdef GRPC_HAVE_IPV6_RECVPKTINFO
int get_local_ip = 1;
if (0 != setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip,
@@ -308,10 +308,10 @@ void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client) {
/* Set TCP_USER_TIMEOUT */
grpc_error* grpc_set_socket_tcp_user_timeout(
int fd, const grpc_channel_args* channel_args, bool is_client) {
- // Use conditionally-important parameter to avoid warning
- (void)fd;
- (void)channel_args;
- (void)is_client;
+ // Use conditionally-important parameter to avoid warning
+ (void)fd;
+ (void)channel_args;
+ (void)is_client;
extern grpc_core::TraceFlag grpc_tcp_trace;
if (g_socket_supports_tcp_user_timeout.load() >= 0) {
bool enable;
@@ -389,7 +389,7 @@ grpc_error* grpc_set_socket_tcp_user_timeout(
}
}
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP_USER_TIMEOUT not supported for this platform");
}
}
@@ -405,19 +405,19 @@ grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) {
return GRPC_ERROR_NONE;
}
-grpc_error* grpc_apply_socket_mutator_in_args(int fd,
- const grpc_channel_args* args) {
- const grpc_arg* socket_mutator_arg =
- grpc_channel_args_find(args, GRPC_ARG_SOCKET_MUTATOR);
- if (socket_mutator_arg == nullptr) {
- return GRPC_ERROR_NONE;
- }
- GPR_DEBUG_ASSERT(socket_mutator_arg->type == GRPC_ARG_POINTER);
- grpc_socket_mutator* mutator =
- static_cast<grpc_socket_mutator*>(socket_mutator_arg->value.pointer.p);
- return grpc_set_socket_with_mutator(fd, mutator);
-}
-
+grpc_error* grpc_apply_socket_mutator_in_args(int fd,
+ const grpc_channel_args* args) {
+ const grpc_arg* socket_mutator_arg =
+ grpc_channel_args_find(args, GRPC_ARG_SOCKET_MUTATOR);
+ if (socket_mutator_arg == nullptr) {
+ return GRPC_ERROR_NONE;
+ }
+ GPR_DEBUG_ASSERT(socket_mutator_arg->type == GRPC_ARG_POINTER);
+ grpc_socket_mutator* mutator =
+ static_cast<grpc_socket_mutator*>(socket_mutator_arg->value.pointer.p);
+ return grpc_set_socket_with_mutator(fd, mutator);
+}
+
static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
static int g_ipv6_loopback_available;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h
index b4dc909d1e..5db5df89dc 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h
@@ -103,10 +103,10 @@ grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes);
/* Tries to set the socket using a grpc_socket_mutator */
grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator);
-/* Extracts the first socket mutator from args if any and applies on the fd. */
-grpc_error* grpc_apply_socket_mutator_in_args(int fd,
- const grpc_channel_args* args);
-
+/* Extracts the first socket mutator from args if any and applies on the fd. */
+grpc_error* grpc_apply_socket_mutator_in_args(int fd,
+ const grpc_channel_args* args);
+
/* An enum to keep track of IPv4/IPv6 socket modes.
Currently, this information is only used when a socket is first created, but
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc
index f117653c49..9fcc4ce06b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc
@@ -44,8 +44,8 @@
#include "src/core/lib/iomgr/sockaddr_windows.h"
#include "src/core/lib/iomgr/socket_windows.h"
-static DWORD s_wsa_socket_flags;
-
+static DWORD s_wsa_socket_flags;
+
grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name) {
grpc_winsocket* r = (grpc_winsocket*)gpr_malloc(sizeof(grpc_winsocket));
memset(r, 0, sizeof(grpc_winsocket));
@@ -127,7 +127,7 @@ static void socket_notify_on_iocp(grpc_winsocket* socket, grpc_closure* closure,
gpr_mu_lock(&socket->state_mu);
if (info->has_pending_iocp) {
info->has_pending_iocp = 0;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
} else {
info->closure = closure;
}
@@ -148,7 +148,7 @@ void grpc_socket_become_ready(grpc_winsocket* socket,
GPR_ASSERT(!info->has_pending_iocp);
gpr_mu_lock(&socket->state_mu);
if (info->closure) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, info->closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, info->closure, GRPC_ERROR_NONE);
info->closure = NULL;
} else {
info->has_pending_iocp = 1;
@@ -186,21 +186,21 @@ int grpc_ipv6_loopback_available(void) {
return g_ipv6_loopback_available;
}
-DWORD grpc_get_default_wsa_socket_flags() { return s_wsa_socket_flags; }
-
-void grpc_wsa_socket_flags_init() {
- s_wsa_socket_flags = WSA_FLAG_OVERLAPPED;
- /* WSA_FLAG_NO_HANDLE_INHERIT may be not supported on the older Windows
- versions, see
- https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
- for details. */
- SOCKET sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
- s_wsa_socket_flags | WSA_FLAG_NO_HANDLE_INHERIT);
- if (sock != INVALID_SOCKET) {
- /* Windows 7, Windows 2008 R2 with SP1 or later */
- s_wsa_socket_flags |= WSA_FLAG_NO_HANDLE_INHERIT;
- closesocket(sock);
- }
-}
-
+DWORD grpc_get_default_wsa_socket_flags() { return s_wsa_socket_flags; }
+
+void grpc_wsa_socket_flags_init() {
+ s_wsa_socket_flags = WSA_FLAG_OVERLAPPED;
+ /* WSA_FLAG_NO_HANDLE_INHERIT may be not supported on the older Windows
+ versions, see
+ https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
+ for details. */
+ SOCKET sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
+ s_wsa_socket_flags | WSA_FLAG_NO_HANDLE_INHERIT);
+ if (sock != INVALID_SOCKET) {
+ /* Windows 7, Windows 2008 R2 with SP1 or later */
+ s_wsa_socket_flags |= WSA_FLAG_NO_HANDLE_INHERIT;
+ closesocket(sock);
+ }
+}
+
#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h
index 78f79453c6..c3ca401505 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h
@@ -32,10 +32,10 @@
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
-#ifndef WSA_FLAG_NO_HANDLE_INHERIT
-#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
-#endif
-
+#ifndef WSA_FLAG_NO_HANDLE_INHERIT
+#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
+#endif
+
/* This holds the data for an outstanding read or write on a socket.
The mutex to protect the concurrent access to that data is the one
inside the winsocket wrapper. */
@@ -59,7 +59,7 @@ typedef struct grpc_winsocket_callback_info {
to hold a mutex for a long amount of time. */
int has_pending_iocp;
/* The results of the overlapped operation. */
- DWORD bytes_transferred;
+ DWORD bytes_transferred;
int wsa_error;
} grpc_winsocket_callback_info;
@@ -118,10 +118,10 @@ void grpc_socket_become_ready(grpc_winsocket* winsocket,
The value is probed once, and cached for the life of the process. */
int grpc_ipv6_loopback_available(void);
-void grpc_wsa_socket_flags_init();
-
-DWORD grpc_get_default_wsa_socket_flags();
-
+void grpc_wsa_socket_flags_init();
+
+DWORD grpc_get_default_wsa_socket_flags();
+
#endif
#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc
index eafa885e2c..3f43b8f088 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc
@@ -34,7 +34,7 @@
#include <netinet/in.h>
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/iomgr/cfstream_handle.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/endpoint_cfstream.h"
@@ -95,7 +95,7 @@ static void OnAlarm(void* arg, grpc_error* error) {
} else {
grpc_error* error =
GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
}
}
@@ -137,7 +137,7 @@ static void OnOpen(void* arg, grpc_error* error) {
GRPC_ERROR_REF(error);
}
gpr_mu_unlock(&connect->mu);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
}
}
@@ -146,7 +146,7 @@ static void ParseResolvedAddress(const grpc_resolved_address* addr,
TString host_port = grpc_sockaddr_to_string(addr, true);
TString host_string;
TString port_string;
- grpc_core::SplitHostPort(host_port, &host_string, &port_string);
+ grpc_core::SplitHostPort(host_port, &host_string, &port_string);
*host = CFStringCreateWithCString(NULL, host_string.c_str(),
kCFStringEncodingUTF8);
*port = grpc_sockaddr_get_port(addr);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc
index dbcf62c94f..fbbfd98678 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc
@@ -57,13 +57,13 @@ static void custom_tcp_connect_cleanup(grpc_custom_tcp_connect* connect) {
}
}
-static void custom_close_callback(grpc_custom_socket* /*socket*/) {}
+static void custom_close_callback(grpc_custom_socket* /*socket*/) {}
static void on_alarm(void* acp, grpc_error* error) {
int done;
grpc_custom_socket* socket = (grpc_custom_socket*)acp;
grpc_custom_tcp_connect* connect = socket->connector;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
connect->addr_name.c_str(), str);
@@ -95,12 +95,12 @@ static void custom_connect_callback_internal(grpc_custom_socket* socket,
grpc_core::ExecCtx::Get()->Flush();
custom_tcp_connect_cleanup(connect);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
}
static void custom_connect_callback(grpc_custom_socket* socket,
grpc_error* error) {
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
if (grpc_core::ExecCtx::Get() == nullptr) {
/* If we are being run on a thread which does not have an exec_ctx created
* yet, we should create one. */
@@ -144,7 +144,7 @@ static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
socket->listener = nullptr;
connect->refs = 2;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "CLIENT_CONNECT: %p %s: asynchronously connecting",
socket, connect->addr_name.c_str());
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc
index 401ddd2f68..35fab2a4a3 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc
@@ -85,10 +85,10 @@ static grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd,
}
err = grpc_set_socket_no_sigpipe_if_possible(fd);
if (err != GRPC_ERROR_NONE) goto error;
-
- err = grpc_apply_socket_mutator_in_args(fd, channel_args);
- if (err != GRPC_ERROR_NONE) goto error;
-
+
+ err = grpc_apply_socket_mutator_in_args(fd, channel_args);
+ if (err != GRPC_ERROR_NONE) goto error;
+
goto done;
error:
@@ -102,7 +102,7 @@ done:
static void tc_on_alarm(void* acp, grpc_error* error) {
int done;
async_connect* ac = static_cast<async_connect*>(acp);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
ac->addr_str.c_str(), str);
@@ -138,7 +138,7 @@ static void on_writable(void* acp, grpc_error* error) {
GRPC_ERROR_REF(error);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_writable: error=%s",
ac->addr_str.c_str(), str);
@@ -239,7 +239,7 @@ finish:
grpc_channel_args_destroy(ac->channel_args);
delete ac;
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
}
grpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,
@@ -289,7 +289,7 @@ void grpc_tcp_client_create_from_prepared_fd(
if (err >= 0) {
*ep = grpc_tcp_client_create_from_fd(fdobj, channel_args,
grpc_sockaddr_to_uri(addr).c_str());
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
return;
}
if (errno != EWOULDBLOCK && errno != EINPROGRESS) {
@@ -316,7 +316,7 @@ void grpc_tcp_client_create_from_prepared_fd(
grpc_schedule_on_exec_ctx);
ac->channel_args = grpc_channel_args_copy(channel_args);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: asynchronously connecting fd %p",
ac->addr_str.c_str(), fdobj);
}
@@ -339,7 +339,7 @@ static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
*ep = nullptr;
if ((error = grpc_tcp_client_prepare_fd(channel_args, addr, &mapped_addr,
&fd)) != GRPC_ERROR_NONE) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
return;
}
grpc_tcp_client_create_from_prepared_fd(interested_parties, closure, fd,
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_windows.cc
index a57e7539f2..def3edced4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_windows.cc
@@ -117,7 +117,7 @@ static void on_connect(void* acp, grpc_error* error) {
async_connect_unlock_and_cleanup(ac, socket);
/* If the connection was aborted, the callback was already called when
the deadline was met. */
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, error);
}
/* Tries to issue one async connection, then schedules both an IOCP
@@ -148,7 +148,7 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
}
sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
- grpc_get_default_wsa_socket_flags());
+ grpc_get_default_wsa_socket_flags());
if (sock == INVALID_SOCKET) {
error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
goto failure;
@@ -213,10 +213,10 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
failure:
GPR_ASSERT(error != GRPC_ERROR_NONE);
TString target_uri = grpc_sockaddr_to_uri(addr);
- grpc_error* final_error =
- grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed to connect", &error, 1),
- GRPC_ERROR_STR_TARGET_ADDRESS,
+ grpc_error* final_error =
+ grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed to connect", &error, 1),
+ GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_cpp_string(std::move(target_uri)));
GRPC_ERROR_UNREF(error);
if (socket != NULL) {
@@ -224,7 +224,7 @@ failure:
} else if (sock != INVALID_SOCKET) {
closesocket(sock);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, final_error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, final_error);
}
grpc_tcp_client_vtable grpc_windows_tcp_client_vtable = {tcp_connect};
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc
index 3e562da508..026ab27432 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc
@@ -88,7 +88,7 @@ static void tcp_free(grpc_custom_socket* s) {
#define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__)
static void tcp_unref(custom_tcp_endpoint* tcp, const char* reason,
const char* file, int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
gpr_log(file, line, GPR_LOG_SEVERITY_ERROR,
"TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp->socket, reason,
@@ -101,7 +101,7 @@ static void tcp_unref(custom_tcp_endpoint* tcp, const char* reason,
static void tcp_ref(custom_tcp_endpoint* tcp, const char* reason,
const char* file, int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
gpr_log(file, line, GPR_LOG_SEVERITY_ERROR,
"TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp->socket, reason,
@@ -123,7 +123,7 @@ static void tcp_ref(custom_tcp_endpoint* tcp) { gpr_ref(&tcp->refcount); }
static void call_read_cb(custom_tcp_endpoint* tcp, grpc_error* error) {
grpc_closure* cb = tcp->read_cb;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p call_cb %p %p:%p", tcp->socket, cb, cb->cb,
cb->cb_arg);
size_t i;
@@ -141,12 +141,12 @@ static void call_read_cb(custom_tcp_endpoint* tcp, grpc_error* error) {
TCP_UNREF(tcp, "read");
tcp->read_slices = nullptr;
tcp->read_cb = nullptr;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
}
static void custom_read_callback(grpc_custom_socket* socket, size_t nread,
grpc_error* error) {
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
grpc_slice_buffer garbage;
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
@@ -171,7 +171,7 @@ static void custom_read_callback(grpc_custom_socket* socket, size_t nread,
static void tcp_read_allocation_done(void* tcpp, grpc_error* error) {
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)tcpp;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp->socket,
grpc_error_string(error));
}
@@ -187,14 +187,14 @@ static void tcp_read_allocation_done(void* tcpp, grpc_error* error) {
grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
call_read_cb(tcp, GRPC_ERROR_REF(error));
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "Initiating read on %p: error=%s", tcp->socket, str);
}
}
static void endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
- grpc_closure* cb, bool /*urgent*/) {
+ grpc_closure* cb, bool /*urgent*/) {
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
GPR_ASSERT(tcp->read_cb == nullptr);
@@ -202,34 +202,34 @@ static void endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
tcp->read_slices = read_slices;
grpc_slice_buffer_reset_and_unref_internal(read_slices);
TCP_REF(tcp, "read");
- if (grpc_resource_user_alloc_slices(&tcp->slice_allocator,
- GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1,
- tcp->read_slices)) {
- tcp_read_allocation_done(tcp, GRPC_ERROR_NONE);
- }
+ if (grpc_resource_user_alloc_slices(&tcp->slice_allocator,
+ GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1,
+ tcp->read_slices)) {
+ tcp_read_allocation_done(tcp, GRPC_ERROR_NONE);
+ }
}
static void custom_write_callback(grpc_custom_socket* socket,
grpc_error* error) {
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
grpc_closure* cb = tcp->write_cb;
tcp->write_cb = nullptr;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "write complete on %p: error=%s", tcp->socket, str);
}
TCP_UNREF(tcp, "write");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
}
static void endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* write_slices,
- grpc_closure* cb, void* /*arg*/) {
+ grpc_closure* cb, void* /*arg*/) {
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
size_t j;
for (j = 0; j < write_slices->count; j++) {
@@ -242,9 +242,9 @@ static void endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* write_slices,
}
if (tcp->shutting_down) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, cb,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP socket is shutting down"));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, cb,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP socket is shutting down"));
return;
}
@@ -254,7 +254,7 @@ static void endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* write_slices,
if (tcp->write_slices->count == 0) {
// No slices means we don't have to do anything,
// and libuv doesn't like empty writes
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
return;
}
tcp->write_cb = cb;
@@ -286,15 +286,15 @@ static void endpoint_delete_from_pollset_set(grpc_endpoint* ep,
static void endpoint_shutdown(grpc_endpoint* ep, grpc_error* why) {
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
if (!tcp->shutting_down) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(why);
gpr_log(GPR_INFO, "TCP %p shutdown why=%s", tcp->socket, str);
}
tcp->shutting_down = true;
- // grpc_core::ExecCtx::Run(DEBUG_LOCATION,tcp->read_cb,
- // GRPC_ERROR_REF(why));
- // grpc_core::ExecCtx::Run(DEBUG_LOCATION,tcp->write_cb,
- // GRPC_ERROR_REF(why)); tcp->read_cb = nullptr; tcp->write_cb = nullptr;
+ // grpc_core::ExecCtx::Run(DEBUG_LOCATION,tcp->read_cb,
+ // GRPC_ERROR_REF(why));
+ // grpc_core::ExecCtx::Run(DEBUG_LOCATION,tcp->write_cb,
+ // GRPC_ERROR_REF(why)); tcp->read_cb = nullptr; tcp->write_cb = nullptr;
grpc_resource_user_shutdown(tcp->resource_user);
grpc_custom_socket_vtable->shutdown(tcp->socket);
}
@@ -307,7 +307,7 @@ static void custom_close_callback(grpc_custom_socket* socket) {
grpc_custom_socket_vtable->destroy(socket);
gpr_free(socket);
} else if (socket->endpoint) {
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
TCP_UNREF(tcp, "destroy");
@@ -334,9 +334,9 @@ static grpc_resource_user* endpoint_get_resource_user(grpc_endpoint* ep) {
return tcp->resource_user;
}
-static int endpoint_get_fd(grpc_endpoint* /*ep*/) { return -1; }
+static int endpoint_get_fd(grpc_endpoint* /*ep*/) { return -1; }
-static bool endpoint_can_track_err(grpc_endpoint* /*ep*/) { return false; }
+static bool endpoint_can_track_err(grpc_endpoint* /*ep*/) { return false; }
static grpc_endpoint_vtable vtable = {endpoint_read,
endpoint_write,
@@ -355,10 +355,10 @@ grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
grpc_resource_quota* resource_quota,
const char* peer_string) {
custom_tcp_endpoint* tcp = new custom_tcp_endpoint;
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "Creating TCP endpoint %p", socket);
}
socket->refs++;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc
index b1cd892964..66caf9c20d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc
@@ -27,7 +27,7 @@
#include <errno.h>
#include <limits.h>
#include <netinet/in.h>
-#include <netinet/tcp.h>
+#include <netinet/tcp.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
@@ -35,7 +35,7 @@
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
-#include <algorithm>
+#include <algorithm>
#include <unordered_map>
#include <grpc/slice.h>
@@ -60,15 +60,15 @@
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
-#ifndef SOL_TCP
-#define SOL_TCP IPPROTO_TCP
-#endif
-
-#ifndef TCP_INQ
-#define TCP_INQ 36
-#define TCP_CM_INQ TCP_INQ
-#endif
-
+#ifndef SOL_TCP
+#define SOL_TCP IPPROTO_TCP
+#endif
+
+#ifndef TCP_INQ
+#define TCP_INQ 36
+#define TCP_CM_INQ TCP_INQ
+#endif
+
#ifdef GRPC_HAVE_MSG_NOSIGNAL
#define SENDMSG_FLAGS MSG_NOSIGNAL
#else
@@ -362,7 +362,7 @@ struct grpc_tcp {
bool is_first_read;
double target_length;
double bytes_read_this_round;
- grpc_core::RefCount refcount;
+ grpc_core::RefCount refcount;
gpr_atm shutdown_count;
int min_read_chunk_size;
@@ -372,11 +372,11 @@ struct grpc_tcp {
grpc_slice_buffer last_read_buffer;
grpc_slice_buffer* incoming_buffer;
- int inq; /* bytes pending on the socket from the last read. */
- bool inq_capable; /* cache whether kernel supports inq */
-
+ int inq; /* bytes pending on the socket from the last read. */
+ bool inq_capable; /* cache whether kernel supports inq */
+
grpc_slice_buffer* outgoing_buffer;
- /* byte within outgoing_buffer->slices[0] to write next */
+ /* byte within outgoing_buffer->slices[0] to write next */
size_t outgoing_byte_idx;
grpc_closure* read_cb;
@@ -439,18 +439,18 @@ static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error);
static void tcp_drop_uncovered_then_handle_write(void* arg /* grpc_tcp */,
grpc_error* error);
-static void done_poller(void* bp, grpc_error* /*error_ignored*/) {
+static void done_poller(void* bp, grpc_error* /*error_ignored*/) {
backup_poller* p = static_cast<backup_poller*>(bp);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p destroy", p);
}
grpc_pollset_destroy(BACKUP_POLLER_POLLSET(p));
gpr_free(p);
}
-static void run_poller(void* bp, grpc_error* /*error_ignored*/) {
+static void run_poller(void* bp, grpc_error* /*error_ignored*/) {
backup_poller* p = static_cast<backup_poller*>(bp);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p run", p);
}
gpr_mu_lock(p->pollset_mu);
@@ -466,31 +466,31 @@ static void run_poller(void* bp, grpc_error* /*error_ignored*/) {
gpr_atm_full_cas(&g_uncovered_notifications_pending, 1, 0)) {
gpr_mu_lock(p->pollset_mu);
bool cas_ok = gpr_atm_full_cas(&g_backup_poller, (gpr_atm)p, 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p done cas_ok=%d", p, cas_ok);
}
gpr_mu_unlock(p->pollset_mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p shutdown", p);
}
grpc_pollset_shutdown(BACKUP_POLLER_POLLSET(p),
GRPC_CLOSURE_INIT(&p->run_poller, done_poller, p,
grpc_schedule_on_exec_ctx));
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p reschedule", p);
}
- grpc_core::Executor::Run(&p->run_poller, GRPC_ERROR_NONE,
- grpc_core::ExecutorType::DEFAULT,
- grpc_core::ExecutorJobType::LONG);
+ grpc_core::Executor::Run(&p->run_poller, GRPC_ERROR_NONE,
+ grpc_core::ExecutorType::DEFAULT,
+ grpc_core::ExecutorJobType::LONG);
}
}
-static void drop_uncovered(grpc_tcp* /*tcp*/) {
+static void drop_uncovered(grpc_tcp* /*tcp*/) {
backup_poller* p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller);
gpr_atm old_count =
gpr_atm_full_fetch_add(&g_uncovered_notifications_pending, -1);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p uncover cnt %d->%d", p,
static_cast<int>(old_count), static_cast<int>(old_count) - 1);
}
@@ -508,7 +508,7 @@ static void cover_self(grpc_tcp* tcp) {
backup_poller* p;
gpr_atm old_count =
gpr_atm_no_barrier_fetch_add(&g_uncovered_notifications_pending, 2);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER: cover cnt %d->%d",
static_cast<int>(old_count), 2 + static_cast<int>(old_count));
}
@@ -516,22 +516,22 @@ static void cover_self(grpc_tcp* tcp) {
GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED();
p = static_cast<backup_poller*>(
gpr_zalloc(sizeof(*p) + grpc_pollset_size()));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p create", p);
}
grpc_pollset_init(BACKUP_POLLER_POLLSET(p), &p->pollset_mu);
gpr_atm_rel_store(&g_backup_poller, (gpr_atm)p);
- grpc_core::Executor::Run(
- GRPC_CLOSURE_INIT(&p->run_poller, run_poller, p, nullptr),
- GRPC_ERROR_NONE, grpc_core::ExecutorType::DEFAULT,
- grpc_core::ExecutorJobType::LONG);
+ grpc_core::Executor::Run(
+ GRPC_CLOSURE_INIT(&p->run_poller, run_poller, p, nullptr),
+ GRPC_ERROR_NONE, grpc_core::ExecutorType::DEFAULT,
+ grpc_core::ExecutorJobType::LONG);
} else {
while ((p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller)) ==
nullptr) {
// spin waiting for backup poller
}
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "BACKUP_POLLER:%p add %p", p, tcp);
}
grpc_pollset_add_fd(BACKUP_POLLER_POLLSET(p), tcp->em_fd);
@@ -541,24 +541,24 @@ static void cover_self(grpc_tcp* tcp) {
}
static void notify_on_read(grpc_tcp* tcp) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p notify_on_read", tcp);
}
grpc_fd_notify_on_read(tcp->em_fd, &tcp->read_done_closure);
}
static void notify_on_write(grpc_tcp* tcp) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p notify_on_write", tcp);
}
- if (!grpc_event_engine_run_in_background()) {
+ if (!grpc_event_engine_run_in_background()) {
cover_self(tcp);
}
grpc_fd_notify_on_write(tcp->em_fd, &tcp->write_done_closure);
}
static void tcp_drop_uncovered_then_handle_write(void* arg, grpc_error* error) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p got_write: %s", arg, grpc_error_string(error));
}
drop_uncovered(static_cast<grpc_tcp*>(arg));
@@ -639,29 +639,29 @@ static void tcp_free(grpc_tcp* tcp) {
}
#ifndef NDEBUG
-#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), DEBUG_LOCATION)
-#define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), DEBUG_LOCATION)
-static void tcp_unref(grpc_tcp* tcp, const char* reason,
- const grpc_core::DebugLocation& debug_location) {
- if (GPR_UNLIKELY(tcp->refcount.Unref(debug_location, reason))) {
+#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), DEBUG_LOCATION)
+#define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), DEBUG_LOCATION)
+static void tcp_unref(grpc_tcp* tcp, const char* reason,
+ const grpc_core::DebugLocation& debug_location) {
+ if (GPR_UNLIKELY(tcp->refcount.Unref(debug_location, reason))) {
tcp_free(tcp);
}
}
-static void tcp_ref(grpc_tcp* tcp, const char* reason,
- const grpc_core::DebugLocation& debug_location) {
- tcp->refcount.Ref(debug_location, reason);
+static void tcp_ref(grpc_tcp* tcp, const char* reason,
+ const grpc_core::DebugLocation& debug_location) {
+ tcp->refcount.Ref(debug_location, reason);
}
#else
#define TCP_UNREF(tcp, reason) tcp_unref((tcp))
#define TCP_REF(tcp, reason) tcp_ref((tcp))
static void tcp_unref(grpc_tcp* tcp) {
- if (GPR_UNLIKELY(tcp->refcount.Unref())) {
+ if (GPR_UNLIKELY(tcp->refcount.Unref())) {
tcp_free(tcp);
}
}
-static void tcp_ref(grpc_tcp* tcp) { tcp->refcount.Ref(); }
+static void tcp_ref(grpc_tcp* tcp) { tcp->refcount.Ref(); }
#endif
static void tcp_destroy(grpc_endpoint* ep) {
@@ -678,7 +678,7 @@ static void tcp_destroy(grpc_endpoint* ep) {
static void call_read_cb(grpc_tcp* tcp, grpc_error* error) {
grpc_closure* cb = tcp->read_cb;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p call_cb %p %p:%p", tcp, cb, cb->cb, cb->cb_arg);
size_t i;
const char* str = grpc_error_string(error);
@@ -697,7 +697,7 @@ static void call_read_cb(grpc_tcp* tcp, grpc_error* error) {
tcp->read_cb = nullptr;
tcp->incoming_buffer = nullptr;
- grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
}
#define MAX_READ_IOVEC 4
@@ -706,154 +706,154 @@ static void tcp_do_read(grpc_tcp* tcp) {
struct msghdr msg;
struct iovec iov[MAX_READ_IOVEC];
ssize_t read_bytes;
- size_t total_read_bytes = 0;
- size_t iov_len =
- std::min<size_t>(MAX_READ_IOVEC, tcp->incoming_buffer->count);
-#ifdef GRPC_LINUX_ERRQUEUE
- constexpr size_t cmsg_alloc_space =
- CMSG_SPACE(sizeof(grpc_core::scm_timestamping)) + CMSG_SPACE(sizeof(int));
-#else
- constexpr size_t cmsg_alloc_space = 24 /* CMSG_SPACE(sizeof(int)) */;
-#endif /* GRPC_LINUX_ERRQUEUE */
- char cmsgbuf[cmsg_alloc_space];
- for (size_t i = 0; i < iov_len; i++) {
+ size_t total_read_bytes = 0;
+ size_t iov_len =
+ std::min<size_t>(MAX_READ_IOVEC, tcp->incoming_buffer->count);
+#ifdef GRPC_LINUX_ERRQUEUE
+ constexpr size_t cmsg_alloc_space =
+ CMSG_SPACE(sizeof(grpc_core::scm_timestamping)) + CMSG_SPACE(sizeof(int));
+#else
+ constexpr size_t cmsg_alloc_space = 24 /* CMSG_SPACE(sizeof(int)) */;
+#endif /* GRPC_LINUX_ERRQUEUE */
+ char cmsgbuf[cmsg_alloc_space];
+ for (size_t i = 0; i < iov_len; i++) {
iov[i].iov_base = GRPC_SLICE_START_PTR(tcp->incoming_buffer->slices[i]);
iov[i].iov_len = GRPC_SLICE_LENGTH(tcp->incoming_buffer->slices[i]);
}
- do {
- /* Assume there is something on the queue. If we receive TCP_INQ from
- * kernel, we will update this value, otherwise, we have to assume there is
- * always something to read until we get EAGAIN. */
- tcp->inq = 1;
-
- msg.msg_name = nullptr;
- msg.msg_namelen = 0;
- msg.msg_iov = iov;
- msg.msg_iovlen = static_cast<msg_iovlen_type>(iov_len);
- if (tcp->inq_capable) {
- msg.msg_control = cmsgbuf;
- msg.msg_controllen = sizeof(cmsgbuf);
- } else {
- msg.msg_control = nullptr;
- msg.msg_controllen = 0;
- }
- msg.msg_flags = 0;
-
- GRPC_STATS_INC_TCP_READ_OFFER(tcp->incoming_buffer->length);
- GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(tcp->incoming_buffer->count);
-
- do {
- GPR_TIMER_SCOPE("recvmsg", 0);
- GRPC_STATS_INC_SYSCALL_READ();
- read_bytes = recvmsg(tcp->fd, &msg, 0);
- } while (read_bytes < 0 && errno == EINTR);
-
- /* We have read something in previous reads. We need to deliver those
- * bytes to the upper layer. */
- if (read_bytes <= 0 && total_read_bytes > 0) {
- tcp->inq = 1;
- break;
- }
-
- if (read_bytes < 0) {
- /* NB: After calling call_read_cb a parallel call of the read handler may
- * be running. */
- if (errno == EAGAIN) {
- finish_estimate(tcp);
- tcp->inq = 0;
- /* We've consumed the edge, request a new one */
- notify_on_read(tcp);
- } else {
- grpc_slice_buffer_reset_and_unref_internal(tcp->incoming_buffer);
- call_read_cb(tcp,
- tcp_annotate_error(GRPC_OS_ERROR(errno, "recvmsg"), tcp));
- TCP_UNREF(tcp, "read");
- }
- return;
- }
- if (read_bytes == 0) {
- /* 0 read size ==> end of stream
- *
- * We may have read something, i.e., total_read_bytes > 0, but
- * since the connection is closed we will drop the data here, because we
- * can't call the callback multiple times. */
+ do {
+ /* Assume there is something on the queue. If we receive TCP_INQ from
+ * kernel, we will update this value, otherwise, we have to assume there is
+ * always something to read until we get EAGAIN. */
+ tcp->inq = 1;
+
+ msg.msg_name = nullptr;
+ msg.msg_namelen = 0;
+ msg.msg_iov = iov;
+ msg.msg_iovlen = static_cast<msg_iovlen_type>(iov_len);
+ if (tcp->inq_capable) {
+ msg.msg_control = cmsgbuf;
+ msg.msg_controllen = sizeof(cmsgbuf);
+ } else {
+ msg.msg_control = nullptr;
+ msg.msg_controllen = 0;
+ }
+ msg.msg_flags = 0;
+
+ GRPC_STATS_INC_TCP_READ_OFFER(tcp->incoming_buffer->length);
+ GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(tcp->incoming_buffer->count);
+
+ do {
+ GPR_TIMER_SCOPE("recvmsg", 0);
+ GRPC_STATS_INC_SYSCALL_READ();
+ read_bytes = recvmsg(tcp->fd, &msg, 0);
+ } while (read_bytes < 0 && errno == EINTR);
+
+ /* We have read something in previous reads. We need to deliver those
+ * bytes to the upper layer. */
+ if (read_bytes <= 0 && total_read_bytes > 0) {
+ tcp->inq = 1;
+ break;
+ }
+
+ if (read_bytes < 0) {
+ /* NB: After calling call_read_cb a parallel call of the read handler may
+ * be running. */
+ if (errno == EAGAIN) {
+ finish_estimate(tcp);
+ tcp->inq = 0;
+ /* We've consumed the edge, request a new one */
+ notify_on_read(tcp);
+ } else {
+ grpc_slice_buffer_reset_and_unref_internal(tcp->incoming_buffer);
+ call_read_cb(tcp,
+ tcp_annotate_error(GRPC_OS_ERROR(errno, "recvmsg"), tcp));
+ TCP_UNREF(tcp, "read");
+ }
+ return;
+ }
+ if (read_bytes == 0) {
+ /* 0 read size ==> end of stream
+ *
+ * We may have read something, i.e., total_read_bytes > 0, but
+ * since the connection is closed we will drop the data here, because we
+ * can't call the callback multiple times. */
grpc_slice_buffer_reset_and_unref_internal(tcp->incoming_buffer);
- call_read_cb(
- tcp, tcp_annotate_error(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Socket closed"), tcp));
+ call_read_cb(
+ tcp, tcp_annotate_error(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Socket closed"), tcp));
TCP_UNREF(tcp, "read");
- return;
+ return;
}
-
+
GRPC_STATS_INC_TCP_READ_SIZE(read_bytes);
add_to_estimate(tcp, static_cast<size_t>(read_bytes));
- GPR_DEBUG_ASSERT((size_t)read_bytes <=
- tcp->incoming_buffer->length - total_read_bytes);
-
-#ifdef GRPC_HAVE_TCP_INQ
- if (tcp->inq_capable) {
- GPR_DEBUG_ASSERT(!(msg.msg_flags & MSG_CTRUNC));
- struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
- for (; cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
- if (cmsg->cmsg_level == SOL_TCP && cmsg->cmsg_type == TCP_CM_INQ &&
- cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
- tcp->inq = *reinterpret_cast<int*>(CMSG_DATA(cmsg));
- break;
- }
- }
- }
-#endif /* GRPC_HAVE_TCP_INQ */
-
- total_read_bytes += read_bytes;
- if (tcp->inq == 0 || total_read_bytes == tcp->incoming_buffer->length) {
- /* We have filled incoming_buffer, and we cannot read any more. */
- break;
- }
-
- /* We had a partial read, and still have space to read more data.
- * So, adjust IOVs and try to read more. */
- size_t remaining = read_bytes;
- size_t j = 0;
- for (size_t i = 0; i < iov_len; i++) {
- if (remaining >= iov[i].iov_len) {
- remaining -= iov[i].iov_len;
- continue;
- }
- if (remaining > 0) {
- iov[j].iov_base = static_cast<char*>(iov[i].iov_base) + remaining;
- iov[j].iov_len = iov[i].iov_len - remaining;
- remaining = 0;
- } else {
- iov[j].iov_base = iov[i].iov_base;
- iov[j].iov_len = iov[i].iov_len;
- }
- ++j;
+ GPR_DEBUG_ASSERT((size_t)read_bytes <=
+ tcp->incoming_buffer->length - total_read_bytes);
+
+#ifdef GRPC_HAVE_TCP_INQ
+ if (tcp->inq_capable) {
+ GPR_DEBUG_ASSERT(!(msg.msg_flags & MSG_CTRUNC));
+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
+ for (; cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+ if (cmsg->cmsg_level == SOL_TCP && cmsg->cmsg_type == TCP_CM_INQ &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
+ tcp->inq = *reinterpret_cast<int*>(CMSG_DATA(cmsg));
+ break;
+ }
+ }
}
- iov_len = j;
- } while (true);
-
- if (tcp->inq == 0) {
- finish_estimate(tcp);
- }
-
- GPR_DEBUG_ASSERT(total_read_bytes > 0);
- if (total_read_bytes < tcp->incoming_buffer->length) {
- grpc_slice_buffer_trim_end(tcp->incoming_buffer,
- tcp->incoming_buffer->length - total_read_bytes,
- &tcp->last_read_buffer);
- }
- call_read_cb(tcp, GRPC_ERROR_NONE);
- TCP_UNREF(tcp, "read");
+#endif /* GRPC_HAVE_TCP_INQ */
+
+ total_read_bytes += read_bytes;
+ if (tcp->inq == 0 || total_read_bytes == tcp->incoming_buffer->length) {
+ /* We have filled incoming_buffer, and we cannot read any more. */
+ break;
+ }
+
+ /* We had a partial read, and still have space to read more data.
+ * So, adjust IOVs and try to read more. */
+ size_t remaining = read_bytes;
+ size_t j = 0;
+ for (size_t i = 0; i < iov_len; i++) {
+ if (remaining >= iov[i].iov_len) {
+ remaining -= iov[i].iov_len;
+ continue;
+ }
+ if (remaining > 0) {
+ iov[j].iov_base = static_cast<char*>(iov[i].iov_base) + remaining;
+ iov[j].iov_len = iov[i].iov_len - remaining;
+ remaining = 0;
+ } else {
+ iov[j].iov_base = iov[i].iov_base;
+ iov[j].iov_len = iov[i].iov_len;
+ }
+ ++j;
+ }
+ iov_len = j;
+ } while (true);
+
+ if (tcp->inq == 0) {
+ finish_estimate(tcp);
+ }
+
+ GPR_DEBUG_ASSERT(total_read_bytes > 0);
+ if (total_read_bytes < tcp->incoming_buffer->length) {
+ grpc_slice_buffer_trim_end(tcp->incoming_buffer,
+ tcp->incoming_buffer->length - total_read_bytes,
+ &tcp->last_read_buffer);
+ }
+ call_read_cb(tcp, GRPC_ERROR_NONE);
+ TCP_UNREF(tcp, "read");
}
static void tcp_read_allocation_done(void* tcpp, grpc_error* error) {
grpc_tcp* tcp = static_cast<grpc_tcp*>(tcpp);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp,
grpc_error_string(error));
}
- if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
+ if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
grpc_slice_buffer_reset_and_unref_internal(tcp->incoming_buffer);
grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
call_read_cb(tcp, GRPC_ERROR_REF(error));
@@ -865,32 +865,32 @@ static void tcp_read_allocation_done(void* tcpp, grpc_error* error) {
static void tcp_continue_read(grpc_tcp* tcp) {
size_t target_read_size = get_target_read_size(tcp);
- /* Wait for allocation only when there is no buffer left. */
- if (tcp->incoming_buffer->length == 0 &&
+ /* Wait for allocation only when there is no buffer left. */
+ if (tcp->incoming_buffer->length == 0 &&
tcp->incoming_buffer->count < MAX_READ_IOVEC) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p alloc_slices", tcp);
}
- if (GPR_UNLIKELY(!grpc_resource_user_alloc_slices(&tcp->slice_allocator,
- target_read_size, 1,
- tcp->incoming_buffer))) {
- // Wait for allocation.
- return;
+ if (GPR_UNLIKELY(!grpc_resource_user_alloc_slices(&tcp->slice_allocator,
+ target_read_size, 1,
+ tcp->incoming_buffer))) {
+ // Wait for allocation.
+ return;
}
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "TCP:%p do_read", tcp);
- }
- tcp_do_read(tcp);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ gpr_log(GPR_INFO, "TCP:%p do_read", tcp);
+ }
+ tcp_do_read(tcp);
}
static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error* error) {
grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p got_read: %s", tcp, grpc_error_string(error));
}
- if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
+ if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
grpc_slice_buffer_reset_and_unref_internal(tcp->incoming_buffer);
grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
call_read_cb(tcp, GRPC_ERROR_REF(error));
@@ -901,7 +901,7 @@ static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error* error) {
}
static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer,
- grpc_closure* cb, bool urgent) {
+ grpc_closure* cb, bool urgent) {
grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
GPR_ASSERT(tcp->read_cb == nullptr);
tcp->read_cb = cb;
@@ -914,19 +914,19 @@ static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer,
* the polling engine */
tcp->is_first_read = false;
notify_on_read(tcp);
- } else if (!urgent && tcp->inq == 0) {
- /* Upper layer asked to read more but we know there is no pending data
- * to read from previous reads. So, wait for POLLIN.
- */
- notify_on_read(tcp);
+ } else if (!urgent && tcp->inq == 0) {
+ /* Upper layer asked to read more but we know there is no pending data
+ * to read from previous reads. So, wait for POLLIN.
+ */
+ notify_on_read(tcp);
} else {
/* Not the first time. We may or may not have more bytes available. In any
* case call tcp->read_done_closure (i.e tcp_handle_read()) which does the
* right thing (i.e calls tcp_do_read() which either reads the available
* bytes or calls notify_on_read() to be notified when new bytes become
* available */
- grpc_core::Closure::Run(DEBUG_LOCATION, &tcp->read_done_closure,
- GRPC_ERROR_NONE);
+ grpc_core::Closure::Run(DEBUG_LOCATION, &tcp->read_done_closure,
+ GRPC_ERROR_NONE);
}
}
@@ -1001,7 +1001,7 @@ static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg,
uint32_t opt = grpc_core::kTimestampingSocketOptions;
if (setsockopt(tcp->fd, SOL_SOCKET, SO_TIMESTAMPING,
static_cast<void*>(&opt), sizeof(opt)) != 0) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_ERROR, "Failed to set timestamping options on the socket.");
}
return false;
@@ -1087,7 +1087,7 @@ struct cmsghdr* process_timestamp(grpc_tcp* tcp, msghdr* msg,
auto next_cmsg = CMSG_NXTHDR(msg, cmsg);
cmsghdr* opt_stats = nullptr;
if (next_cmsg == nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_ERROR, "Received timestamp without extended error");
}
return cmsg;
@@ -1099,7 +1099,7 @@ struct cmsghdr* process_timestamp(grpc_tcp* tcp, msghdr* msg,
opt_stats = next_cmsg;
next_cmsg = CMSG_NXTHDR(msg, opt_stats);
if (next_cmsg == nullptr) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_ERROR, "Received timestamp without extended error");
}
return opt_stats;
@@ -1109,7 +1109,7 @@ struct cmsghdr* process_timestamp(grpc_tcp* tcp, msghdr* msg,
if (!(next_cmsg->cmsg_level == SOL_IP || next_cmsg->cmsg_level == SOL_IPV6) ||
!(next_cmsg->cmsg_type == IP_RECVERR ||
next_cmsg->cmsg_type == IPV6_RECVERR)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_ERROR, "Unexpected control message");
}
return cmsg;
@@ -1196,7 +1196,7 @@ static bool process_errors(grpc_tcp* tcp) {
} else {
/* Got a control message that is not a timestamp or zerocopy. Don't know
* how to handle this. */
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO,
"unknown control message cmsg_level:%d cmsg_type:%d",
cmsg->cmsg_level, cmsg->cmsg_type);
@@ -1212,7 +1212,7 @@ static bool process_errors(grpc_tcp* tcp) {
static void tcp_handle_error(void* arg /* grpc_tcp */, grpc_error* error) {
grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "TCP:%p got_error: %s", tcp, grpc_error_string(error));
}
@@ -1244,8 +1244,8 @@ static TcpZerocopySendRecord* tcp_get_send_zerocopy_record(
static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* tcp) {}
-static bool tcp_write_with_timestamps(grpc_tcp* /*tcp*/, struct msghdr* /*msg*/,
- size_t /*sending_length*/,
+static bool tcp_write_with_timestamps(grpc_tcp* /*tcp*/, struct msghdr* /*msg*/,
+ size_t /*sending_length*/,
ssize_t* /*sent_length*/,
int /*additional_flags*/) {
gpr_log(GPR_ERROR, "Write with timestamps not supported for this platform");
@@ -1253,8 +1253,8 @@ static bool tcp_write_with_timestamps(grpc_tcp* /*tcp*/, struct msghdr* /*msg*/,
return false;
}
-static void tcp_handle_error(void* /*arg*/ /* grpc_tcp */,
- grpc_error* /*error*/) {
+static void tcp_handle_error(void* /*arg*/ /* grpc_tcp */,
+ grpc_error* /*error*/) {
gpr_log(GPR_ERROR, "Error handling is not supported for this platform");
GPR_ASSERT(0);
}
@@ -1473,7 +1473,7 @@ static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) {
// unref all and forget about all slices that have been written to this
// point
for (size_t idx = 0; idx < unwind_slice_idx; ++idx) {
- grpc_slice_buffer_remove_first(tcp->outgoing_buffer);
+ grpc_slice_buffer_remove_first(tcp->outgoing_buffer);
}
return false;
} else if (errno == EPIPE) {
@@ -1525,7 +1525,7 @@ static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error) {
"handle_write_err");
tcp->current_zerocopy_send = nullptr;
}
- grpc_core::Closure::Run(DEBUG_LOCATION, cb, GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION, cb, GRPC_ERROR_REF(error));
TCP_UNREF(tcp, "write");
return;
}
@@ -1535,22 +1535,22 @@ static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error) {
? tcp_flush_zerocopy(tcp, tcp->current_zerocopy_send, &error)
: tcp_flush(tcp, &error);
if (!flush_result) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "write: delayed");
}
notify_on_write(tcp);
- // tcp_flush does not populate error if it has returned false.
- GPR_DEBUG_ASSERT(error == GRPC_ERROR_NONE);
+ // tcp_flush does not populate error if it has returned false.
+ GPR_DEBUG_ASSERT(error == GRPC_ERROR_NONE);
} else {
cb = tcp->write_cb;
tcp->write_cb = nullptr;
tcp->current_zerocopy_send = nullptr;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "write: %s", str);
}
- // No need to take a ref on error since tcp_flush provides a ref.
- grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
+ // No need to take a ref on error since tcp_flush provides a ref.
+ grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
TCP_UNREF(tcp, "write");
}
}
@@ -1562,7 +1562,7 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
grpc_error* error = GRPC_ERROR_NONE;
TcpZerocopySendRecord* zerocopy_send_record = nullptr;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
size_t i;
for (i = 0; i < buf->count; i++) {
@@ -1580,12 +1580,12 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
GPR_DEBUG_ASSERT(tcp->current_zerocopy_send == nullptr);
if (buf->length == 0) {
- grpc_core::Closure::Run(
- DEBUG_LOCATION, cb,
- grpc_fd_is_shutdown(tcp->em_fd)
- ? tcp_annotate_error(GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF"),
- tcp)
- : GRPC_ERROR_NONE);
+ grpc_core::Closure::Run(
+ DEBUG_LOCATION, cb,
+ grpc_fd_is_shutdown(tcp->em_fd)
+ ? tcp_annotate_error(GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF"),
+ tcp)
+ : GRPC_ERROR_NONE);
tcp_shutdown_buffer_list(tcp);
return;
}
@@ -1609,16 +1609,16 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
TCP_REF(tcp, "write");
tcp->write_cb = cb;
tcp->current_zerocopy_send = zerocopy_send_record;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "write: delayed");
}
notify_on_write(tcp);
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "write: %s", str);
}
- grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
}
}
@@ -1798,7 +1798,7 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
#endif
}
/* paired with unref in grpc_tcp_destroy */
- new (&tcp->refcount) grpc_core::RefCount(1, &grpc_tcp_trace);
+ new (&tcp->refcount) grpc_core::RefCount(1, &grpc_tcp_trace);
gpr_atm_no_barrier_store(&tcp->shutdown_count, 0);
tcp->em_fd = em_fd;
grpc_slice_buffer_init(&tcp->last_read_buffer);
@@ -1808,31 +1808,31 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
grpc_resource_quota_unref_internal(resource_quota);
gpr_mu_init(&tcp->tb_mu);
tcp->tb_head = nullptr;
- GRPC_CLOSURE_INIT(&tcp->read_done_closure, tcp_handle_read, tcp,
- grpc_schedule_on_exec_ctx);
- if (grpc_event_engine_run_in_background()) {
- // If there is a polling engine always running in the background, there is
- // no need to run the backup poller.
- GRPC_CLOSURE_INIT(&tcp->write_done_closure, tcp_handle_write, tcp,
- grpc_schedule_on_exec_ctx);
- } else {
- GRPC_CLOSURE_INIT(&tcp->write_done_closure,
- tcp_drop_uncovered_then_handle_write, tcp,
- grpc_schedule_on_exec_ctx);
- }
- /* Always assume there is something on the queue to read. */
- tcp->inq = 1;
-#ifdef GRPC_HAVE_TCP_INQ
- int one = 1;
- if (setsockopt(tcp->fd, SOL_TCP, TCP_INQ, &one, sizeof(one)) == 0) {
- tcp->inq_capable = true;
- } else {
- gpr_log(GPR_DEBUG, "cannot set inq fd=%d errno=%d", tcp->fd, errno);
- tcp->inq_capable = false;
- }
-#else
- tcp->inq_capable = false;
-#endif /* GRPC_HAVE_TCP_INQ */
+ GRPC_CLOSURE_INIT(&tcp->read_done_closure, tcp_handle_read, tcp,
+ grpc_schedule_on_exec_ctx);
+ if (grpc_event_engine_run_in_background()) {
+ // If there is a polling engine always running in the background, there is
+ // no need to run the backup poller.
+ GRPC_CLOSURE_INIT(&tcp->write_done_closure, tcp_handle_write, tcp,
+ grpc_schedule_on_exec_ctx);
+ } else {
+ GRPC_CLOSURE_INIT(&tcp->write_done_closure,
+ tcp_drop_uncovered_then_handle_write, tcp,
+ grpc_schedule_on_exec_ctx);
+ }
+ /* Always assume there is something on the queue to read. */
+ tcp->inq = 1;
+#ifdef GRPC_HAVE_TCP_INQ
+ int one = 1;
+ if (setsockopt(tcp->fd, SOL_TCP, TCP_INQ, &one, sizeof(one)) == 0) {
+ tcp->inq_capable = true;
+ } else {
+ gpr_log(GPR_DEBUG, "cannot set inq fd=%d errno=%d", tcp->fd, errno);
+ tcp->inq_capable = false;
+ }
+#else
+ tcp->inq_capable = false;
+#endif /* GRPC_HAVE_TCP_INQ */
/* Start being notified on errors if event engine can track errors. */
if (grpc_event_engine_can_track_errors()) {
/* Grab a ref to tcp so that we can safely access the tcp struct when
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc
index 046fd4979b..a6f28dc1a4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc
@@ -40,11 +40,11 @@ grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s,
return grpc_tcp_server_impl->add_port(s, addr, out_port);
}
-grpc_core::TcpServerFdHandler* grpc_tcp_server_create_fd_handler(
- grpc_tcp_server* s) {
- return grpc_tcp_server_impl->create_fd_handler(s);
-}
-
+grpc_core::TcpServerFdHandler* grpc_tcp_server_create_fd_handler(
+ grpc_tcp_server* s) {
+ return grpc_tcp_server_impl->create_fd_handler(s);
+}
+
unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s,
unsigned port_index) {
return grpc_tcp_server_impl->port_fd_count(s, port_index);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h
index 6ba3513da5..f6200ad48a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h
@@ -22,7 +22,7 @@
#include <grpc/support/port_platform.h>
#include <grpc/grpc.h>
-#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/impl/codegen/grpc_types.h>
#include <vector>
@@ -40,10 +40,10 @@ typedef struct grpc_tcp_server_acceptor {
/* Indices that may be passed to grpc_tcp_server_port_fd(). */
unsigned port_index;
unsigned fd_index;
- /* Data when the connection is passed to tcp_server from external. */
- bool external_connection;
- int listener_fd;
- grpc_byte_buffer* pending_data;
+ /* Data when the connection is passed to tcp_server from external. */
+ bool external_connection;
+ int listener_fd;
+ grpc_byte_buffer* pending_data;
} grpc_tcp_server_acceptor;
/* Called for newly connected TCP connections.
@@ -51,16 +51,16 @@ typedef struct grpc_tcp_server_acceptor {
typedef void (*grpc_tcp_server_cb)(void* arg, grpc_endpoint* ep,
grpc_pollset* accepting_pollset,
grpc_tcp_server_acceptor* acceptor);
-namespace grpc_core {
-// An interface for a handler to take a externally connected fd as a internal
-// connection.
-class TcpServerFdHandler {
- public:
- virtual ~TcpServerFdHandler() = default;
- virtual void Handle(int listener_fd, int fd,
- grpc_byte_buffer* pending_read) = 0;
-};
-} // namespace grpc_core
+namespace grpc_core {
+// An interface for a handler to take a externally connected fd as a internal
+// connection.
+class TcpServerFdHandler {
+ public:
+ virtual ~TcpServerFdHandler() = default;
+ virtual void Handle(int listener_fd, int fd,
+ grpc_byte_buffer* pending_read) = 0;
+};
+} // namespace grpc_core
typedef struct grpc_tcp_server_vtable {
grpc_error* (*create)(grpc_closure* shutdown_complete,
@@ -71,7 +71,7 @@ typedef struct grpc_tcp_server_vtable {
grpc_tcp_server_cb on_accept_cb, void* cb_arg);
grpc_error* (*add_port)(grpc_tcp_server* s, const grpc_resolved_address* addr,
int* out_port);
- grpc_core::TcpServerFdHandler* (*create_fd_handler)(grpc_tcp_server* s);
+ grpc_core::TcpServerFdHandler* (*create_fd_handler)(grpc_tcp_server* s);
unsigned (*port_fd_count)(grpc_tcp_server* s, unsigned port_index);
int (*port_fd)(grpc_tcp_server* s, unsigned port_index, unsigned fd_index);
grpc_tcp_server* (*ref)(grpc_tcp_server* s);
@@ -106,11 +106,11 @@ grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s,
const grpc_resolved_address* addr,
int* out_port);
-/* Create and return a TcpServerFdHandler so that it can be used by upper layer
- to hand over an externally connected fd to the grpc server. */
-grpc_core::TcpServerFdHandler* grpc_tcp_server_create_fd_handler(
- grpc_tcp_server* s);
-
+/* Create and return a TcpServerFdHandler so that it can be used by upper layer
+ to hand over an externally connected fd to the grpc server. */
+grpc_core::TcpServerFdHandler* grpc_tcp_server_create_fd_handler(
+ grpc_tcp_server* s);
+
/* Number of fds at the given port_index, or 0 if port_index is out of
bounds. */
unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_custom.cc
index 0cffa1f571..cba3782f2b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_custom.cc
@@ -133,8 +133,8 @@ static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
static void finish_shutdown(grpc_tcp_server* s) {
GPR_ASSERT(s->shutdown);
if (s->shutdown_complete != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
+ GRPC_ERROR_NONE);
}
while (s->head) {
@@ -205,7 +205,7 @@ static void tcp_server_unref(grpc_tcp_server* s) {
if (gpr_unref(&s->refs)) {
/* Complete shutdown_starting work before destroying. */
grpc_core::ExecCtx exec_ctx;
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
grpc_core::ExecCtx::Get()->Flush();
tcp_server_destroy(s);
}
@@ -229,7 +229,7 @@ static void finish_accept(grpc_tcp_listener* sp, grpc_custom_socket* socket) {
GRPC_LOG_IF_ERROR("getpeername error", err);
GRPC_ERROR_UNREF(err);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection: %s", sp->server,
peer_name_string.c_str());
}
@@ -238,7 +238,7 @@ static void finish_accept(grpc_tcp_listener* sp, grpc_custom_socket* socket) {
acceptor->from_server = sp->server;
acceptor->port_index = sp->port_index;
acceptor->fd_index = 0;
- acceptor->external_connection = false;
+ acceptor->external_connection = false;
sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, nullptr, acceptor);
}
@@ -249,7 +249,7 @@ static void custom_accept_callback(grpc_custom_socket* socket,
static void custom_accept_callback(grpc_custom_socket* socket,
grpc_custom_socket* client,
grpc_error* error) {
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
grpc_tcp_listener* sp = socket->listener;
if (error != GRPC_ERROR_NONE) {
@@ -384,7 +384,7 @@ static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
addr = &wildcard;
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "SERVER %p add_port %s error=%s", s,
grpc_sockaddr_to_string(addr, false).c_str(),
grpc_error_string(error));
@@ -396,7 +396,7 @@ static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
socket->endpoint = nullptr;
socket->listener = nullptr;
socket->connector = nullptr;
- error = grpc_custom_socket_vtable->init(socket, family);
+ error = grpc_custom_socket_vtable->init(socket, family);
if (error == GRPC_ERROR_NONE) {
error = add_socket_to_server(s, socket, addr, port_index, &sp);
@@ -422,7 +422,7 @@ static void tcp_server_start(grpc_tcp_server* server,
grpc_tcp_server_cb on_accept_cb, void* cb_arg) {
grpc_tcp_listener* sp;
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "SERVER_START %p", server);
}
GPR_ASSERT(on_accept_cb);
@@ -441,13 +441,13 @@ static void tcp_server_start(grpc_tcp_server* server,
}
}
-static unsigned tcp_server_port_fd_count(grpc_tcp_server* /*s*/,
- unsigned /*port_index*/) {
+static unsigned tcp_server_port_fd_count(grpc_tcp_server* /*s*/,
+ unsigned /*port_index*/) {
return 0;
}
-static int tcp_server_port_fd(grpc_tcp_server* /*s*/, unsigned /*port_index*/,
- unsigned /*fd_index*/) {
+static int tcp_server_port_fd(grpc_tcp_server* /*s*/, unsigned /*port_index*/,
+ unsigned /*fd_index*/) {
return -1;
}
@@ -460,17 +460,17 @@ static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {
}
}
-static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
- grpc_tcp_server* /*s*/) {
- return nullptr;
-}
-
+static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
+ grpc_tcp_server* /*s*/) {
+ return nullptr;
+}
+
grpc_tcp_server_vtable custom_tcp_server_vtable = {
- tcp_server_create, tcp_server_start,
- tcp_server_add_port, tcp_server_create_fd_handler,
- tcp_server_port_fd_count, tcp_server_port_fd,
- tcp_server_ref, tcp_server_shutdown_starting_add,
- tcp_server_unref, tcp_server_shutdown_listeners};
+ tcp_server_create, tcp_server_start,
+ tcp_server_add_port, tcp_server_create_fd_handler,
+ tcp_server_port_fd_count, tcp_server_port_fd,
+ tcp_server_ref, tcp_server_shutdown_starting_add,
+ tcp_server_unref, tcp_server_shutdown_listeners};
#ifdef GRPC_UV_TEST
grpc_tcp_server_vtable* default_tcp_server_vtable = &custom_tcp_server_vtable;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc
index b3f3febe63..879cc428ed 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc
@@ -49,14 +49,14 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/iomgr/socket_utils_posix.h"
#include "src/core/lib/iomgr/tcp_posix.h"
-#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/lib/iomgr/tcp_server.h"
#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
@@ -101,7 +101,7 @@ static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
s->tail = nullptr;
s->nports = 0;
s->channel_args = grpc_channel_args_copy(args);
- s->fd_handler = nullptr;
+ s->fd_handler = nullptr;
gpr_atm_no_barrier_store(&s->next_pollset_to_assign, 0);
*server = s;
return GRPC_ERROR_NONE;
@@ -112,8 +112,8 @@ static void finish_shutdown(grpc_tcp_server* s) {
GPR_ASSERT(s->shutdown);
gpr_mu_unlock(&s->mu);
if (s->shutdown_complete != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
+ GRPC_ERROR_NONE);
}
gpr_mu_destroy(&s->mu);
@@ -124,12 +124,12 @@ static void finish_shutdown(grpc_tcp_server* s) {
gpr_free(sp);
}
grpc_channel_args_destroy(s->channel_args);
- delete s->fd_handler;
+ delete s->fd_handler;
gpr_free(s);
}
-static void destroyed_port(void* server, grpc_error* /*error*/) {
+static void destroyed_port(void* server, grpc_error* /*error*/) {
grpc_tcp_server* s = static_cast<grpc_tcp_server*>(server);
gpr_mu_lock(&s->mu);
s->destroyed_ports++;
@@ -223,23 +223,23 @@ static void on_read(void* arg, grpc_error* err) {
}
}
- /* For UNIX sockets, the accept call might not fill up the member sun_path
- * of sockaddr_un, so explicitly call getsockname to get it. */
- if (grpc_is_unix_socket(&addr)) {
- memset(&addr, 0, sizeof(addr));
- addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
- if (getsockname(fd, reinterpret_cast<struct sockaddr*>(addr.addr),
- &(addr.len)) < 0) {
- gpr_log(GPR_ERROR, "Failed getsockname: %s", strerror(errno));
- close(fd);
- goto error;
- }
- }
-
+ /* For UNIX sockets, the accept call might not fill up the member sun_path
+ * of sockaddr_un, so explicitly call getsockname to get it. */
+ if (grpc_is_unix_socket(&addr)) {
+ memset(&addr, 0, sizeof(addr));
+ addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+ if (getsockname(fd, reinterpret_cast<struct sockaddr*>(addr.addr),
+ &(addr.len)) < 0) {
+ gpr_log(GPR_ERROR, "Failed getsockname: %s", strerror(errno));
+ close(fd);
+ goto error;
+ }
+ }
+
grpc_set_socket_no_sigpipe_if_possible(fd);
TString addr_str = grpc_sockaddr_to_uri(&addr);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "SERVER_CONNECT: incoming connection: %s",
addr_str.c_str());
}
@@ -260,7 +260,7 @@ static void on_read(void* arg, grpc_error* err) {
acceptor->from_server = sp->server;
acceptor->port_index = sp->port_index;
acceptor->fd_index = sp->fd_index;
- acceptor->external_connection = false;
+ acceptor->external_connection = false;
sp->server->on_accept_cb(
sp->server->on_accept_cb_arg,
@@ -545,7 +545,7 @@ static void tcp_server_unref(grpc_tcp_server* s) {
if (gpr_unref(&s->refs)) {
grpc_tcp_server_shutdown_listeners(s);
gpr_mu_lock(&s->mu);
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
gpr_mu_unlock(&s->mu);
tcp_server_destroy(s);
}
@@ -565,67 +565,67 @@ static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {
gpr_mu_unlock(&s->mu);
}
-namespace {
-class ExternalConnectionHandler : public grpc_core::TcpServerFdHandler {
- public:
- explicit ExternalConnectionHandler(grpc_tcp_server* s) : s_(s) {}
-
- // TODO(yangg) resolve duplicate code with on_read
- void Handle(int listener_fd, int fd, grpc_byte_buffer* buf) override {
- grpc_pollset* read_notifier_pollset;
- grpc_resolved_address addr;
- memset(&addr, 0, sizeof(addr));
- addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
- grpc_core::ExecCtx exec_ctx;
-
- if (getpeername(fd, reinterpret_cast<struct sockaddr*>(addr.addr),
- &(addr.len)) < 0) {
- gpr_log(GPR_ERROR, "Failed getpeername: %s", strerror(errno));
- close(fd);
- return;
- }
- grpc_set_socket_no_sigpipe_if_possible(fd);
+namespace {
+class ExternalConnectionHandler : public grpc_core::TcpServerFdHandler {
+ public:
+ explicit ExternalConnectionHandler(grpc_tcp_server* s) : s_(s) {}
+
+ // TODO(yangg) resolve duplicate code with on_read
+ void Handle(int listener_fd, int fd, grpc_byte_buffer* buf) override {
+ grpc_pollset* read_notifier_pollset;
+ grpc_resolved_address addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+ grpc_core::ExecCtx exec_ctx;
+
+ if (getpeername(fd, reinterpret_cast<struct sockaddr*>(addr.addr),
+ &(addr.len)) < 0) {
+ gpr_log(GPR_ERROR, "Failed getpeername: %s", strerror(errno));
+ close(fd);
+ return;
+ }
+ grpc_set_socket_no_sigpipe_if_possible(fd);
TString addr_str = grpc_sockaddr_to_uri(&addr);
- if (grpc_tcp_trace.enabled()) {
- gpr_log(GPR_INFO, "SERVER_CONNECT: incoming external connection: %s",
+ if (grpc_tcp_trace.enabled()) {
+ gpr_log(GPR_INFO, "SERVER_CONNECT: incoming external connection: %s",
addr_str.c_str());
- }
+ }
TString name = y_absl::StrCat("tcp-server-connection:", addr_str);
grpc_fd* fdobj = grpc_fd_create(fd, name.c_str(), true);
- read_notifier_pollset =
+ read_notifier_pollset =
(*(s_->pollsets))[static_cast<size_t>(gpr_atm_no_barrier_fetch_add(
&s_->next_pollset_to_assign, 1)) %
s_->pollsets->size()];
- grpc_pollset_add_fd(read_notifier_pollset, fdobj);
- grpc_tcp_server_acceptor* acceptor =
- static_cast<grpc_tcp_server_acceptor*>(gpr_malloc(sizeof(*acceptor)));
- acceptor->from_server = s_;
- acceptor->port_index = -1;
- acceptor->fd_index = -1;
- acceptor->external_connection = true;
- acceptor->listener_fd = listener_fd;
- acceptor->pending_data = buf;
- s_->on_accept_cb(s_->on_accept_cb_arg,
+ grpc_pollset_add_fd(read_notifier_pollset, fdobj);
+ grpc_tcp_server_acceptor* acceptor =
+ static_cast<grpc_tcp_server_acceptor*>(gpr_malloc(sizeof(*acceptor)));
+ acceptor->from_server = s_;
+ acceptor->port_index = -1;
+ acceptor->fd_index = -1;
+ acceptor->external_connection = true;
+ acceptor->listener_fd = listener_fd;
+ acceptor->pending_data = buf;
+ s_->on_accept_cb(s_->on_accept_cb_arg,
grpc_tcp_create(fdobj, s_->channel_args, addr_str.c_str()),
- read_notifier_pollset, acceptor);
- }
-
- private:
- grpc_tcp_server* s_;
-};
-} // namespace
-
-static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
- grpc_tcp_server* s) {
- s->fd_handler = new ExternalConnectionHandler(s);
- return s->fd_handler;
-}
-
+ read_notifier_pollset, acceptor);
+ }
+
+ private:
+ grpc_tcp_server* s_;
+};
+} // namespace
+
+static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
+ grpc_tcp_server* s) {
+ s->fd_handler = new ExternalConnectionHandler(s);
+ return s->fd_handler;
+}
+
grpc_tcp_server_vtable grpc_posix_tcp_server_vtable = {
- tcp_server_create, tcp_server_start,
- tcp_server_add_port, tcp_server_create_fd_handler,
- tcp_server_port_fd_count, tcp_server_port_fd,
- tcp_server_ref, tcp_server_shutdown_starting_add,
- tcp_server_unref, tcp_server_shutdown_listeners};
-
+ tcp_server_create, tcp_server_start,
+ tcp_server_add_port, tcp_server_create_fd_handler,
+ tcp_server_port_fd_count, tcp_server_port_fd,
+ tcp_server_ref, tcp_server_shutdown_starting_add,
+ tcp_server_unref, tcp_server_shutdown_listeners};
+
#endif /* GRPC_POSIX_SOCKET_TCP_SERVER */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h
index 6b8a5f9f20..8a9bc261ca 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h
@@ -91,9 +91,9 @@ struct grpc_tcp_server {
/* channel args for this server */
grpc_channel_args* channel_args;
-
- /* a handler for external connections, owned */
- grpc_core::TcpServerFdHandler* fd_handler;
+
+ /* a handler for external connections, owned */
+ grpc_core::TcpServerFdHandler* fd_handler;
};
/* If successful, add a listener to \a s for \a addr, set \a dsmode for the
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc
index 46bc18e5a0..d3dd8f6128 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc
@@ -180,8 +180,8 @@ grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server* s, int fd,
err = grpc_set_socket_no_sigpipe_if_possible(fd);
if (err != GRPC_ERROR_NONE) goto error;
- err = grpc_apply_socket_mutator_in_args(fd, s->channel_args);
- if (err != GRPC_ERROR_NONE) goto error;
+ err = grpc_apply_socket_mutator_in_args(fd, s->channel_args);
+ if (err != GRPC_ERROR_NONE) goto error;
if (bind(fd, reinterpret_cast<grpc_sockaddr*>(const_cast<char*>(addr->addr)),
addr->len) < 0) {
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_windows.cc
index 13c17260dc..f29d36134f 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_windows.cc
@@ -140,12 +140,12 @@ static void destroy_server(void* arg, grpc_error* error) {
static void finish_shutdown_locked(grpc_tcp_server* s) {
if (s->shutdown_complete != NULL) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
+ GRPC_ERROR_NONE);
}
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
GRPC_CLOSURE_CREATE(destroy_server, s, grpc_schedule_on_exec_ctx),
GRPC_ERROR_NONE);
}
@@ -184,7 +184,7 @@ static void tcp_server_unref(grpc_tcp_server* s) {
if (gpr_unref(&s->refs)) {
grpc_tcp_server_shutdown_listeners(s);
gpr_mu_lock(&s->mu);
- grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
+ grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &s->shutdown_starting);
gpr_mu_unlock(&s->mu);
tcp_server_destroy(s);
}
@@ -261,7 +261,7 @@ static grpc_error* start_accept_locked(grpc_tcp_listener* port) {
}
sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
- grpc_get_default_wsa_socket_flags());
+ grpc_get_default_wsa_socket_flags());
if (sock == INVALID_SOCKET) {
error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
goto failure;
@@ -374,7 +374,7 @@ static void on_accept(void* arg, grpc_error* error) {
acceptor->from_server = sp->server;
acceptor->port_index = sp->port_index;
acceptor->fd_index = 0;
- acceptor->external_connection = false;
+ acceptor->external_connection = false;
sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, NULL, acceptor);
}
/* As we were notified from the IOCP of one and exactly one accept,
@@ -411,7 +411,7 @@ static grpc_error* add_socket_to_server(grpc_tcp_server* s, SOCKET sock,
gpr_log(GPR_ERROR, "on_connect error: %s", utf8_message);
gpr_free(utf8_message);
closesocket(sock);
- return GRPC_ERROR_NONE;
+ return GRPC_ERROR_NONE;
}
error = prepare_socket(sock, addr, &port);
@@ -496,7 +496,7 @@ static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
}
sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
- grpc_get_default_wsa_socket_flags());
+ grpc_get_default_wsa_socket_flags());
if (sock == INVALID_SOCKET) {
error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
goto done;
@@ -548,17 +548,17 @@ static int tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
return -1;
}
-static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
- grpc_tcp_server* s) {
- return nullptr;
-}
-
+static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
+ grpc_tcp_server* s) {
+ return nullptr;
+}
+
static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {}
grpc_tcp_server_vtable grpc_windows_tcp_server_vtable = {
- tcp_server_create, tcp_server_start,
- tcp_server_add_port, tcp_server_create_fd_handler,
- tcp_server_port_fd_count, tcp_server_port_fd,
- tcp_server_ref, tcp_server_shutdown_starting_add,
- tcp_server_unref, tcp_server_shutdown_listeners};
+ tcp_server_create, tcp_server_start,
+ tcp_server_add_port, tcp_server_create_fd_handler,
+ tcp_server_port_fd_count, tcp_server_port_fd,
+ tcp_server_ref, tcp_server_shutdown_starting_add,
+ tcp_server_unref, tcp_server_shutdown_listeners};
#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc
index 371b38c991..2ebc4d4f29 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc
@@ -53,7 +53,7 @@ typedef struct uv_socket_t {
char* read_buf;
size_t read_len;
- int pending_connections;
+ int pending_connections;
grpc_custom_socket* accept_socket;
grpc_error* accept_error;
@@ -206,7 +206,7 @@ static grpc_error* uv_socket_init_helper(uv_socket_t* uv_socket, int domain) {
// Node uses a garbage collector to call destructors, so we don't
// want to hold the uv loop open with active gRPC objects.
uv_unref((uv_handle_t*)uv_socket->handle);
- uv_socket->pending_connections = 0;
+ uv_socket->pending_connections = 0;
uv_socket->accept_socket = nullptr;
uv_socket->accept_error = GRPC_ERROR_NONE;
return GRPC_ERROR_NONE;
@@ -243,14 +243,14 @@ static grpc_error* uv_socket_getsockname(grpc_custom_socket* socket,
static void accept_new_connection(grpc_custom_socket* socket) {
uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- if (uv_socket->pending_connections == 0 || !uv_socket->accept_socket) {
+ if (uv_socket->pending_connections == 0 || !uv_socket->accept_socket) {
return;
}
grpc_custom_socket* new_socket = uv_socket->accept_socket;
grpc_error* error = uv_socket->accept_error;
uv_socket->accept_socket = nullptr;
uv_socket->accept_error = GRPC_ERROR_NONE;
- uv_socket->pending_connections -= 1;
+ uv_socket->pending_connections -= 1;
if (uv_socket->accept_error != GRPC_ERROR_NONE) {
uv_stream_t dummy_handle;
uv_accept((uv_stream_t*)uv_socket->handle, &dummy_handle);
@@ -279,7 +279,7 @@ static void uv_on_connect(uv_stream_t* server, int status) {
uv_socket->accept_error = tcp_error_create("accept failed", status);
}
}
- uv_socket->pending_connections += 1;
+ uv_socket->pending_connections += 1;
accept_new_connection(socket);
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc
index 3d410a2d3f..dbd7ce3707 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc
@@ -74,16 +74,16 @@ static grpc_error* set_dualstack(SOCKET sock) {
: GRPC_WSA_ERROR(WSAGetLastError(), "setsockopt(IPV6_V6ONLY)");
}
-static grpc_error* enable_socket_low_latency(SOCKET sock) {
+static grpc_error* enable_socket_low_latency(SOCKET sock) {
int status;
- BOOL param = TRUE;
- status = ::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
- reinterpret_cast<char*>(&param), sizeof(param));
+ BOOL param = TRUE;
+ status = ::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<char*>(&param), sizeof(param));
if (status == SOCKET_ERROR) {
status = WSAGetLastError();
}
- return status == 0 ? GRPC_ERROR_NONE
- : GRPC_WSA_ERROR(status, "setsockopt(TCP_NODELAY)");
+ return status == 0 ? GRPC_ERROR_NONE
+ : GRPC_WSA_ERROR(status, "setsockopt(TCP_NODELAY)");
}
grpc_error* grpc_tcp_prepare_socket(SOCKET sock) {
@@ -92,7 +92,7 @@ grpc_error* grpc_tcp_prepare_socket(SOCKET sock) {
if (err != GRPC_ERROR_NONE) return err;
err = set_dualstack(sock);
if (err != GRPC_ERROR_NONE) return err;
- err = enable_socket_low_latency(sock);
+ err = enable_socket_low_latency(sock);
if (err != GRPC_ERROR_NONE) return err;
return GRPC_ERROR_NONE;
}
@@ -196,17 +196,17 @@ static void on_read(void* tcpp, grpc_error* error) {
gpr_free(utf8_message);
grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
} else {
- if (info->bytes_transferred != 0 && !tcp->shutting_down) {
- GPR_ASSERT((size_t)info->bytes_transferred <= tcp->read_slices->length);
- if (static_cast<size_t>(info->bytes_transferred) !=
+ if (info->bytes_transferred != 0 && !tcp->shutting_down) {
+ GPR_ASSERT((size_t)info->bytes_transferred <= tcp->read_slices->length);
+ if (static_cast<size_t>(info->bytes_transferred) !=
tcp->read_slices->length) {
grpc_slice_buffer_trim_end(
tcp->read_slices,
tcp->read_slices->length -
- static_cast<size_t>(info->bytes_transferred),
+ static_cast<size_t>(info->bytes_transferred),
&tcp->last_read_buffer);
}
- GPR_ASSERT((size_t)info->bytes_transferred == tcp->read_slices->length);
+ GPR_ASSERT((size_t)info->bytes_transferred == tcp->read_slices->length);
if (grpc_tcp_trace.enabled()) {
size_t i;
@@ -233,13 +233,13 @@ static void on_read(void* tcpp, grpc_error* error) {
tcp->read_cb = NULL;
TCP_UNREF(tcp, "read");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
}
#define DEFAULT_TARGET_READ_SIZE 8192
#define MAX_WSABUF_COUNT 16
static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
- grpc_closure* cb, bool urgent) {
+ grpc_closure* cb, bool urgent) {
grpc_tcp* tcp = (grpc_tcp*)ep;
grpc_winsocket* handle = tcp->socket;
grpc_winsocket_callback_info* info = &handle->read_info;
@@ -254,10 +254,10 @@ static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
}
if (tcp->shutting_down) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, cb,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "TCP socket is shutting down", &tcp->shutdown_error, 1));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, cb,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "TCP socket is shutting down", &tcp->shutdown_error, 1));
return;
}
@@ -289,8 +289,8 @@ static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
/* Did we get data immediately ? Yay. */
if (info->wsa_error != WSAEWOULDBLOCK) {
- info->bytes_transferred = bytes_read;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, &tcp->on_read, GRPC_ERROR_NONE);
+ info->bytes_transferred = bytes_read;
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, &tcp->on_read, GRPC_ERROR_NONE);
return;
}
@@ -303,8 +303,8 @@ static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
int wsa_error = WSAGetLastError();
if (wsa_error != WSA_IO_PENDING) {
info->wsa_error = wsa_error;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, &tcp->on_read,
- GRPC_WSA_ERROR(info->wsa_error, "WSARecv"));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, &tcp->on_read,
+ GRPC_WSA_ERROR(info->wsa_error, "WSARecv"));
return;
}
}
@@ -334,12 +334,12 @@ static void on_write(void* tcpp, grpc_error* error) {
if (info->wsa_error != 0) {
error = GRPC_WSA_ERROR(info->wsa_error, "WSASend");
} else {
- GPR_ASSERT(info->bytes_transferred == tcp->write_slices->length);
+ GPR_ASSERT(info->bytes_transferred == tcp->write_slices->length);
}
}
TCP_UNREF(tcp, "write");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
}
/* Initiates a write. */
@@ -368,10 +368,10 @@ static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
}
if (tcp->shutting_down) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, cb,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "TCP socket is shutting down", &tcp->shutdown_error, 1));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, cb,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "TCP socket is shutting down", &tcp->shutdown_error, 1));
return;
}
@@ -402,7 +402,7 @@ static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
grpc_error* error = status == 0
? GRPC_ERROR_NONE
: GRPC_WSA_ERROR(info->wsa_error, "WSASend");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
if (allocated) gpr_free(allocated);
return;
}
@@ -420,8 +420,8 @@ static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
int wsa_error = WSAGetLastError();
if (wsa_error != WSA_IO_PENDING) {
TCP_UNREF(tcp, "write");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb,
- GRPC_WSA_ERROR(wsa_error, "WSASend"));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb,
+ GRPC_WSA_ERROR(wsa_error, "WSASend"));
return;
}
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer.h b/contrib/libs/grpc/src/core/lib/iomgr/timer.h
index 11da149652..4e475e25de 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer.h
@@ -29,8 +29,8 @@
typedef struct grpc_timer {
grpc_millis deadline;
- // Uninitialized if not using heap, or INVALID_HEAP_INDEX if not in heap.
- uint32_t heap_index;
+ // Uninitialized if not using heap, or INVALID_HEAP_INDEX if not in heap.
+ uint32_t heap_index;
bool pending;
struct grpc_timer* next;
struct grpc_timer* prev;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc
index c550d44122..3c144b5e51 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc
@@ -30,14 +30,14 @@
static grpc_custom_timer_vtable* custom_timer_impl;
-void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* /*error*/) {
+void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* /*error*/) {
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
grpc_timer* timer = t->original;
GPR_ASSERT(timer->pending);
timer->pending = 0;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure, GRPC_ERROR_NONE);
custom_timer_impl->stop(t);
gpr_free(t);
}
@@ -48,7 +48,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
grpc_millis now = grpc_core::ExecCtx::Get()->Now();
if (deadline <= grpc_core::ExecCtx::Get()->Now()) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
timer->pending = false;
return;
} else {
@@ -69,14 +69,14 @@ static void timer_cancel(grpc_timer* timer) {
grpc_custom_timer* tw = (grpc_custom_timer*)timer->custom_timer;
if (timer->pending) {
timer->pending = 0;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
- GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
+ GRPC_ERROR_CANCELLED);
custom_timer_impl->stop(tw);
gpr_free(tw);
}
}
-static grpc_timer_check_result timer_check(grpc_millis* /*next*/) {
+static grpc_timer_check_result timer_check(grpc_millis* /*next*/) {
return GRPC_TIMERS_NOT_CHECKED;
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc
index fb0e50c53c..8e4866a15c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc
@@ -363,7 +363,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
timer->hash_table_next = nullptr;
#endif
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
gpr_log(GPR_INFO, "TIMER %p: SET %" PRId64 " now %" PRId64 " call %p[%p]",
timer, deadline, grpc_core::ExecCtx::Get()->Now(), closure,
closure->cb);
@@ -371,10 +371,10 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
if (!g_shared_mutables.initialized) {
timer->pending = false;
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, timer->closure,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Attempt to create timer before initialization"));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, timer->closure,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Attempt to create timer before initialization"));
return;
}
@@ -383,7 +383,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
grpc_millis now = grpc_core::ExecCtx::Get()->Now();
if (deadline <= now) {
timer->pending = false;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure, GRPC_ERROR_NONE);
gpr_mu_unlock(&shard->mu);
/* early out */
return;
@@ -400,7 +400,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
timer->heap_index = INVALID_HEAP_INDEX;
list_join(&shard->list, timer);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
gpr_log(GPR_INFO,
" .. add to shard %d with queue_deadline_cap=%" PRId64
" => is_first_timer=%s",
@@ -422,7 +422,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
grpc_timer_check. */
if (is_first_timer) {
gpr_mu_lock(&g_shared_mutables.mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
gpr_log(GPR_INFO, " .. old shard min_deadline=%" PRId64,
shard->min_deadline);
}
@@ -466,7 +466,7 @@ static void timer_cancel(grpc_timer* timer) {
timer_shard* shard = &g_shards[GPR_HASH_POINTER(timer, g_num_shards)];
gpr_mu_lock(&shard->mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
gpr_log(GPR_INFO, "TIMER %p: CANCEL pending=%s", timer,
timer->pending ? "true" : "false");
}
@@ -474,8 +474,8 @@ static void timer_cancel(grpc_timer* timer) {
if (timer->pending) {
REMOVE_FROM_HASH_TABLE(timer);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
- GRPC_ERROR_CANCELLED);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
+ GRPC_ERROR_CANCELLED);
timer->pending = false;
if (timer->heap_index == INVALID_HEAP_INDEX) {
list_remove(timer);
@@ -491,7 +491,7 @@ static void timer_cancel(grpc_timer* timer) {
/* Rebalances the timer shard by computing a new 'queue_deadline_cap' and moving
all relevant timers in shard->list (i.e timers with deadlines earlier than
'queue_deadline_cap') into into shard->heap.
- Returns 'true' if shard->heap has at least ONE element
+ Returns 'true' if shard->heap has at least ONE element
REQUIRES: shard->mu locked */
static bool refill_heap(timer_shard* shard, grpc_millis now) {
/* Compute the new queue window width and bound by the limits: */
@@ -508,7 +508,7 @@ static bool refill_heap(timer_shard* shard, grpc_millis now) {
saturating_add(GPR_MAX(now, shard->queue_deadline_cap),
static_cast<grpc_millis>(deadline_delta * 1000.0));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, " .. shard[%d]->queue_deadline_cap --> %" PRId64,
static_cast<int>(shard - g_shards), shard->queue_deadline_cap);
}
@@ -516,7 +516,7 @@ static bool refill_heap(timer_shard* shard, grpc_millis now) {
next = timer->next;
if (timer->deadline < shard->queue_deadline_cap) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, " .. add timer with deadline %" PRId64 " to heap",
timer->deadline);
}
@@ -533,7 +533,7 @@ static bool refill_heap(timer_shard* shard, grpc_millis now) {
static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) {
grpc_timer* timer;
for (;;) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, " .. shard[%d]: heap_empty=%s",
static_cast<int>(shard - g_shards),
grpc_timer_heap_is_empty(&shard->heap) ? "true" : "false");
@@ -543,15 +543,15 @@ static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) {
if (!refill_heap(shard, now)) return nullptr;
}
timer = grpc_timer_heap_top(&shard->heap);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO,
" .. check top timer deadline=%" PRId64 " now=%" PRId64,
timer->deadline, now);
}
if (timer->deadline > now) return nullptr;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
- gpr_log(GPR_INFO, "TIMER %p: FIRE %" PRId64 "ms late", timer,
- now - timer->deadline);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
+ gpr_log(GPR_INFO, "TIMER %p: FIRE %" PRId64 "ms late", timer,
+ now - timer->deadline);
}
timer->pending = false;
grpc_timer_heap_pop(&shard->heap);
@@ -567,13 +567,13 @@ static size_t pop_timers(timer_shard* shard, grpc_millis now,
gpr_mu_lock(&shard->mu);
while ((timer = pop_one(shard, now))) {
REMOVE_FROM_HASH_TABLE(timer);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
+ GRPC_ERROR_REF(error));
n++;
}
*new_min_deadline = compute_min_deadline(shard);
gpr_mu_unlock(&shard->mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, " .. shard[%d] popped %" PRIdPTR,
static_cast<int>(shard - g_shards), n);
}
@@ -610,7 +610,7 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now,
gpr_mu_lock(&g_shared_mutables.mu);
result = GRPC_TIMERS_CHECKED_AND_EMPTY;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, " .. shard[%d]->min_deadline = %" PRId64,
static_cast<int>(g_shard_queue[0] - g_shards),
g_shard_queue[0]->min_deadline);
@@ -628,7 +628,7 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now,
result = GRPC_TIMERS_FIRED;
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO,
" .. result --> %d"
", shard[%d]->min_deadline %" PRId64 " --> %" PRId64
@@ -695,7 +695,7 @@ static grpc_timer_check_result timer_check(grpc_millis* next) {
if (next != nullptr) {
*next = GPR_MIN(*next, min_timer);
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "TIMER CHECK SKIP: now=%" PRId64 " min_timer=%" PRId64,
now, min_timer);
}
@@ -708,7 +708,7 @@ static grpc_timer_check_result timer_check(grpc_millis* next) {
: GRPC_ERROR_CREATE_FROM_STATIC_STRING("Shutting down timer system");
// tracing
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
TString next_str;
if (next == nullptr) {
next_str = "NULL";
@@ -731,7 +731,7 @@ static grpc_timer_check_result timer_check(grpc_millis* next) {
grpc_timer_check_result r =
run_some_expired_timers(now, next, shutdown_error);
// tracing
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
TString next_str;
if (next == nullptr) {
next_str = "NULL";
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc
index 96d502c510..e436c1eaa1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc
@@ -18,8 +18,8 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/iomgr/timer_manager.h"
-
+#include "src/core/lib/iomgr/timer_manager.h"
+
#include <inttypes.h>
#include <grpc/support/alloc.h>
@@ -59,8 +59,8 @@ static bool g_has_timed_waiter;
static grpc_millis g_timed_waiter_deadline;
// generation counter to track which thread is waiting for the next timer
static uint64_t g_timed_waiter_generation;
-// number of timer wakeups
-static uint64_t g_wakeups;
+// number of timer wakeups
+static uint64_t g_wakeups;
static void timer_thread(void* completed_thread_ptr);
@@ -84,7 +84,7 @@ static void start_timer_thread_and_unlock(void) {
++g_waiter_count;
++g_thread_count;
gpr_mu_unlock(&g_mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "Spawn timer thread");
}
completed_thread* ct =
@@ -120,7 +120,7 @@ static void run_some_timers() {
// if there's no thread waiting with a timeout, kick an existing untimed
// waiter so that the next deadline is not missed
if (!g_has_timed_waiter) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "kick untimed waiter");
}
gpr_cv_signal(&g_cv_wait);
@@ -128,7 +128,7 @@ static void run_some_timers() {
gpr_mu_unlock(&g_mu);
}
// without our lock, flush the exec_ctx
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "flush exec_ctx");
}
grpc_core::ExecCtx::Get()->Flush();
@@ -183,7 +183,7 @@ static bool wait_until(grpc_millis next) {
g_has_timed_waiter = true;
g_timed_waiter_deadline = next;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
grpc_millis wait_time = next - grpc_core::ExecCtx::Get()->Now();
gpr_log(GPR_INFO, "sleep for a %" PRId64 " milliseconds", wait_time);
}
@@ -192,15 +192,15 @@ static bool wait_until(grpc_millis next) {
}
}
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace) &&
- next == GRPC_MILLIS_INF_FUTURE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace) &&
+ next == GRPC_MILLIS_INF_FUTURE) {
gpr_log(GPR_INFO, "sleep until kicked");
}
gpr_cv_wait(&g_cv_wait, &g_mu,
grpc_millis_to_timespec(next, GPR_CLOCK_MONOTONIC));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "wait ended: was_timed:%d kicked:%d",
my_timed_waiter_generation == g_timed_waiter_generation,
g_kicked);
@@ -209,7 +209,7 @@ static bool wait_until(grpc_millis next) {
// that there's now no timed waiter... we'll look for a replacement if
// there's work to do after checking timers (code above)
if (my_timed_waiter_generation == g_timed_waiter_generation) {
- ++g_wakeups;
+ ++g_wakeups;
g_has_timed_waiter = false;
g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
}
@@ -246,7 +246,7 @@ static void timer_main_loop() {
Consequently, we can just sleep forever here and be happy at some
saved wakeup cycles. */
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "timers not checked: expect another thread to");
}
next = GRPC_MILLIS_INF_FUTURE;
@@ -272,7 +272,7 @@ static void timer_thread_cleanup(completed_thread* ct) {
ct->next = g_completed_threads;
g_completed_threads = ct;
gpr_mu_unlock(&g_mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "End timer thread");
}
}
@@ -313,24 +313,24 @@ void grpc_timer_manager_init(void) {
static void stop_threads(void) {
gpr_mu_lock(&g_mu);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "stop timer threads: threaded=%d", g_threaded);
}
if (g_threaded) {
g_threaded = false;
gpr_cv_broadcast(&g_cv_wait);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "num timer threads: %d", g_thread_count);
}
while (g_thread_count > 0) {
gpr_cv_wait(&g_cv_shutdown, &g_mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "num timer threads: %d", g_thread_count);
}
gc_completed_threads();
}
}
- g_wakeups = 0;
+ g_wakeups = 0;
gpr_mu_unlock(&g_mu);
}
@@ -359,5 +359,5 @@ void grpc_kick_poller(void) {
gpr_cv_signal(&g_cv_wait);
gpr_mu_unlock(&g_mu);
}
-
-uint64_t grpc_timer_manager_get_wakeups_testonly(void) { return g_wakeups; }
+
+uint64_t grpc_timer_manager_get_wakeups_testonly(void) { return g_wakeups; }
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h
index d407cbbc2b..e548fcaa4c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h
@@ -35,7 +35,7 @@ void grpc_timer_manager_set_threading(bool enabled);
/* explicitly perform one tick of the timer system - for when threading is
* disabled */
void grpc_timer_manager_tick(void);
-/* get global counter that tracks timer wakeups */
-uint64_t grpc_timer_manager_get_wakeups_testonly(void);
+/* get global counter that tracks timer wakeups */
+uint64_t grpc_timer_manager_get_wakeups_testonly(void);
#endif /* GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc
index 1e7734d681..64fe078015 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc
@@ -29,7 +29,7 @@
#include "src/core/lib/iomgr/port.h"
-#ifdef GRPC_POSIX_SOCKET_UDP_SERVER
+#ifdef GRPC_POSIX_SOCKET_UDP_SERVER
#include "src/core/lib/iomgr/udp_server.h"
@@ -208,7 +208,7 @@ static grpc_socket_factory* get_socket_factory(const grpc_channel_args* args) {
}
grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args) {
- grpc_udp_server* s = new grpc_udp_server();
+ grpc_udp_server* s = new grpc_udp_server();
gpr_mu_init(&s->mu);
s->socket_factory = get_socket_factory(args);
if (s->socket_factory) {
@@ -243,8 +243,8 @@ void GrpcUdpListener::shutdown_fd(void* args, grpc_error* error) {
static void finish_shutdown(grpc_udp_server* s) {
if (s->shutdown_complete != nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->shutdown_complete,
+ GRPC_ERROR_NONE);
}
gpr_mu_destroy(&s->mu);
@@ -258,10 +258,10 @@ static void finish_shutdown(grpc_udp_server* s) {
grpc_socket_factory_unref(s->socket_factory);
}
- delete s;
+ delete s;
}
-static void destroyed_port(void* server, grpc_error* /*error*/) {
+static void destroyed_port(void* server, grpc_error* /*error*/) {
grpc_udp_server* s = static_cast<grpc_udp_server*>(server);
gpr_mu_lock(&s->mu);
s->destroyed_ports++;
@@ -333,7 +333,7 @@ void GrpcUdpListener::OnFdAboutToOrphan() {
GRPC_CLOSURE_INIT(&destroyed_closure_, destroyed_port, server_,
grpc_schedule_on_exec_ctx);
if (!orphan_notified_ && udp_handler_ != nullptr) {
- /* Signals udp_handler that the FD is about to be closed and
+ /* Signals udp_handler that the FD is about to be closed and
* should no longer be used. */
GRPC_CLOSURE_INIT(&orphan_fd_closure_, shutdown_fd, this,
grpc_schedule_on_exec_ctx);
@@ -447,9 +447,9 @@ void GrpcUdpListener::do_read(void* arg, grpc_error* error) {
if (!sp->already_shutdown_ && sp->udp_handler_->Read()) {
/* There maybe more packets to read. Schedule read_more_cb_ closure to run
* after finishing this event loop. */
- grpc_core::Executor::Run(&sp->do_read_closure_, GRPC_ERROR_NONE,
- grpc_core::ExecutorType::DEFAULT,
- grpc_core::ExecutorJobType::LONG);
+ grpc_core::Executor::Run(&sp->do_read_closure_, GRPC_ERROR_NONE,
+ grpc_core::ExecutorType::DEFAULT,
+ grpc_core::ExecutorJobType::LONG);
} else {
/* Finish reading all the packets, re-arm the notification event so we can
* get another chance to read. Or fd already shutdown, re-arm to get a
@@ -482,10 +482,10 @@ void GrpcUdpListener::OnRead(grpc_error* error, void* do_read_arg) {
if (udp_handler_->Read()) {
/* There maybe more packets to read. Schedule read_more_cb_ closure to run
* after finishing this event loop. */
- GRPC_CLOSURE_INIT(&do_read_closure_, do_read, do_read_arg, nullptr);
- grpc_core::Executor::Run(&do_read_closure_, GRPC_ERROR_NONE,
- grpc_core::ExecutorType::DEFAULT,
- grpc_core::ExecutorJobType::LONG);
+ GRPC_CLOSURE_INIT(&do_read_closure_, do_read, do_read_arg, nullptr);
+ grpc_core::Executor::Run(&do_read_closure_, GRPC_ERROR_NONE,
+ grpc_core::ExecutorType::DEFAULT,
+ grpc_core::ExecutorJobType::LONG);
} else {
/* Finish reading all the packets, re-arm the notification event so we can
* get another chance to read. Or fd already shutdown, re-arm to get a
@@ -496,8 +496,8 @@ void GrpcUdpListener::OnRead(grpc_error* error, void* do_read_arg) {
// static
// Wrapper of grpc_fd_notify_on_write() with a grpc_closure callback interface.
-void GrpcUdpListener::fd_notify_on_write_wrapper(void* arg,
- grpc_error* /*error*/) {
+void GrpcUdpListener::fd_notify_on_write_wrapper(void* arg,
+ grpc_error* /*error*/) {
GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
gpr_mu_lock(sp->mutex());
if (!sp->notify_on_write_armed_) {
@@ -545,11 +545,11 @@ void GrpcUdpListener::OnCanWrite(grpc_error* error, void* do_write_arg) {
}
/* Schedule actual write in another thread. */
- GRPC_CLOSURE_INIT(&do_write_closure_, do_write, do_write_arg, nullptr);
+ GRPC_CLOSURE_INIT(&do_write_closure_, do_write, do_write_arg, nullptr);
- grpc_core::Executor::Run(&do_write_closure_, GRPC_ERROR_NONE,
- grpc_core::ExecutorType::DEFAULT,
- grpc_core::ExecutorJobType::LONG);
+ grpc_core::Executor::Run(&do_write_closure_, GRPC_ERROR_NONE,
+ grpc_core::ExecutorType::DEFAULT,
+ grpc_core::ExecutorJobType::LONG);
}
static int add_socket_to_server(grpc_udp_server* s, int fd,
@@ -645,7 +645,7 @@ int grpc_udp_server_add_port(grpc_udp_server* s,
grpc_sockaddr_set_port(addr, allocated_port1);
port = allocated_port1;
} else if (allocated_port1 >= 0) {
- /* The following successfully created socket should have same port as
+ /* The following successfully created socket should have same port as
* the first one. */
GPR_ASSERT(port == allocated_port1);
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.h b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.h
index 6cda332a5b..52687a3269 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.h
@@ -40,7 +40,7 @@ typedef struct grpc_udp_server grpc_udp_server;
* Its implementation should do the real IO work, e.g. read packet and write. */
class GrpcUdpHandler {
public:
- GrpcUdpHandler(grpc_fd* /* emfd */, void* /* user_data */) {}
+ GrpcUdpHandler(grpc_fd* /* emfd */, void* /* user_data */) {}
virtual ~GrpcUdpHandler() {}
// Interfaces to be implemented by subclasses to do the actual setup/tear down
@@ -48,16 +48,16 @@ class GrpcUdpHandler {
// Called when data is available to read from the socket. Returns true if
// there is more data to read after this call.
- virtual bool Read() = 0;
+ virtual bool Read() = 0;
// Called when socket becomes write unblocked. The given closure should be
// scheduled when the socket becomes blocked next time.
virtual void OnCanWrite(void* user_data,
- grpc_closure* notify_on_write_closure) = 0;
+ grpc_closure* notify_on_write_closure) = 0;
// Called before the gRPC FD is orphaned. Notify udp server to continue
// orphaning fd by scheduling the given closure, afterwards the associated fd
// will be closed.
virtual void OnFdAboutToOrphan(grpc_closure* orphan_fd_closure,
- void* user_data) = 0;
+ void* user_data) = 0;
};
class GrpcUdpHandlerFactory {
@@ -66,8 +66,8 @@ class GrpcUdpHandlerFactory {
/* Called when start to listen on a socket.
* Return an instance of the implementation of GrpcUdpHandler interface which
* will process I/O events for this socket from now on. */
- virtual GrpcUdpHandler* CreateUdpHandler(grpc_fd* emfd, void* user_data) = 0;
- virtual void DestroyUdpHandler(GrpcUdpHandler* handler) = 0;
+ virtual GrpcUdpHandler* CreateUdpHandler(grpc_fd* emfd, void* user_data) = 0;
+ virtual void DestroyUdpHandler(GrpcUdpHandler* handler) = 0;
};
/* Create a server, initially not bound to any ports */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.cc
index 3b66d6f34d..573de4d4db 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.cc
@@ -63,7 +63,7 @@ grpc_error* grpc_wakeup_fd_wakeup(grpc_wakeup_fd* fd_info) {
}
void grpc_wakeup_fd_destroy(grpc_wakeup_fd* fd_info) {
- wakeup_fd_vtable->destroy(fd_info);
+ wakeup_fd_vtable->destroy(fd_info);
}
#endif /* GRPC_POSIX_WAKEUP_FD */
diff --git a/contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc b/contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc
index 2056940f3a..d9e834b635 100644
--- a/contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc
+++ b/contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc
@@ -31,8 +31,8 @@
#include <stdio.h>
#include <string.h>
-#include "src/core/lib/gprpp/global_config.h"
-#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/profiling/timers.h"
typedef enum { BEGIN = '{', END = '}', MARK = '.' } marker_type;
@@ -75,16 +75,16 @@ static __thread int g_thread_id;
static int g_next_thread_id;
static int g_writing_enabled = 1;
-GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_latency_trace, "latency_trace.txt",
- "Output file name for latency trace")
-
+GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_latency_trace, "latency_trace.txt",
+ "Output file name for latency trace")
+
static const char* output_filename() {
if (output_filename_or_null == NULL) {
- grpc_core::UniquePtr<char> value =
- GPR_GLOBAL_CONFIG_GET(grpc_latency_trace);
- if (strlen(value.get()) > 0) {
- output_filename_or_null = value.release();
- } else {
+ grpc_core::UniquePtr<char> value =
+ GPR_GLOBAL_CONFIG_GET(grpc_latency_trace);
+ if (strlen(value.get()) > 0) {
+ output_filename_or_null = value.release();
+ } else {
output_filename_or_null = "latency_trace.txt";
}
}
@@ -287,7 +287,7 @@ void gpr_timers_global_init(void) {}
void gpr_timers_global_destroy(void) {}
-void gpr_timers_set_log_filename(const char* /*filename*/) {}
+void gpr_timers_set_log_filename(const char* /*filename*/) {}
-void gpr_timer_set_enabled(int /*enabled*/) {}
+void gpr_timer_set_enabled(int /*enabled*/) {}
#endif /* GRPC_BASIC_PROFILER */
diff --git a/contrib/libs/grpc/src/core/lib/security/context/security_context.cc b/contrib/libs/grpc/src/core/lib/security/context/security_context.cc
index ef60165899..daab200a4e 100644
--- a/contrib/libs/grpc/src/core/lib/security/context/security_context.cc
+++ b/contrib/libs/grpc/src/core/lib/security/context/security_context.cc
@@ -22,7 +22,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/arena.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/security/context/security_context.h"
@@ -102,9 +102,9 @@ grpc_client_security_context::~grpc_client_security_context() {
}
grpc_client_security_context* grpc_client_security_context_create(
- grpc_core::Arena* arena, grpc_call_credentials* creds) {
- return arena->New<grpc_client_security_context>(
- creds != nullptr ? creds->Ref() : nullptr);
+ grpc_core::Arena* arena, grpc_call_credentials* creds) {
+ return arena->New<grpc_client_security_context>(
+ creds != nullptr ? creds->Ref() : nullptr);
}
void grpc_client_security_context_destroy(void* ctx) {
@@ -123,8 +123,8 @@ grpc_server_security_context::~grpc_server_security_context() {
}
grpc_server_security_context* grpc_server_security_context_create(
- grpc_core::Arena* arena) {
- return arena->New<grpc_server_security_context>();
+ grpc_core::Arena* arena) {
+ return arena->New<grpc_server_security_context>();
}
void grpc_server_security_context_destroy(void* ctx) {
diff --git a/contrib/libs/grpc/src/core/lib/security/context/security_context.h b/contrib/libs/grpc/src/core/lib/security/context/security_context.h
index b1991089ae..b49f352ab5 100644
--- a/contrib/libs/grpc/src/core/lib/security/context/security_context.h
+++ b/contrib/libs/grpc/src/core/lib/security/context/security_context.h
@@ -21,7 +21,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/arena.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
@@ -120,7 +120,7 @@ struct grpc_client_security_context {
};
grpc_client_security_context* grpc_client_security_context_create(
- grpc_core::Arena* arena, grpc_call_credentials* creds);
+ grpc_core::Arena* arena, grpc_call_credentials* creds);
void grpc_client_security_context_destroy(void* ctx);
/* --- grpc_server_security_context ---
@@ -136,7 +136,7 @@ struct grpc_server_security_context {
};
grpc_server_security_context* grpc_server_security_context_create(
- grpc_core::Arena* arena);
+ grpc_core::Arena* arena);
void grpc_server_security_context_destroy(void* ctx);
/* --- Channel args for auth context --- */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc
index 1bc76d9c0c..bcf219981a 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc
@@ -40,9 +40,9 @@ grpc_alts_credentials::grpc_alts_credentials(
options_(grpc_alts_credentials_options_copy(options)),
handshaker_service_url_(handshaker_service_url == nullptr
? gpr_strdup(GRPC_ALTS_HANDSHAKER_SERVICE_URL)
- : gpr_strdup(handshaker_service_url)) {
- grpc_alts_set_rpc_protocol_versions(&options_->rpc_versions);
-}
+ : gpr_strdup(handshaker_service_url)) {
+ grpc_alts_set_rpc_protocol_versions(&options_->rpc_versions);
+}
grpc_alts_credentials::~grpc_alts_credentials() {
grpc_alts_credentials_options_destroy(options_);
@@ -52,8 +52,8 @@ grpc_alts_credentials::~grpc_alts_credentials() {
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_alts_credentials::create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
- const char* target_name, const grpc_channel_args* /*args*/,
- grpc_channel_args** /*new_args*/) {
+ const char* target_name, const grpc_channel_args* /*args*/,
+ grpc_channel_args** /*new_args*/) {
return grpc_alts_channel_security_connector_create(
this->Ref(), std::move(call_creds), target_name);
}
@@ -65,9 +65,9 @@ grpc_alts_server_credentials::grpc_alts_server_credentials(
options_(grpc_alts_credentials_options_copy(options)),
handshaker_service_url_(handshaker_service_url == nullptr
? gpr_strdup(GRPC_ALTS_HANDSHAKER_SERVICE_URL)
- : gpr_strdup(handshaker_service_url)) {
- grpc_alts_set_rpc_protocol_versions(&options_->rpc_versions);
-}
+ : gpr_strdup(handshaker_service_url)) {
+ grpc_alts_set_rpc_protocol_versions(&options_->rpc_versions);
+}
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_alts_server_credentials::create_security_connector() {
@@ -85,7 +85,7 @@ grpc_channel_credentials* grpc_alts_credentials_create_customized(
if (!enable_untrusted_alts && !grpc_alts_is_running_on_gcp()) {
return nullptr;
}
- return new grpc_alts_credentials(options, handshaker_service_url);
+ return new grpc_alts_credentials(options, handshaker_service_url);
}
grpc_server_credentials* grpc_alts_server_credentials_create_customized(
@@ -94,7 +94,7 @@ grpc_server_credentials* grpc_alts_server_credentials_create_customized(
if (!enable_untrusted_alts && !grpc_alts_is_running_on_gcp()) {
return nullptr;
}
- return new grpc_alts_server_credentials(options, handshaker_service_url);
+ return new grpc_alts_server_credentials(options, handshaker_service_url);
}
grpc_channel_credentials* grpc_alts_credentials_create(
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc
index 59432cff36..6da137ce1c 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc
@@ -34,65 +34,65 @@
namespace grpc_core {
namespace internal {
-bool check_bios_data(const char*) { return false; }
-
-bool check_windows_registry_product_name(HKEY root_key,
- const char* reg_key_path,
- const char* reg_key_name) {
- const size_t kProductNameBufferSize = 256;
- char const expected_substr[] = "Google";
-
- // Get the size of the string first to allocate our buffer. This includes
- // enough space for the trailing NUL character that will be included.
- DWORD buffer_size{};
- auto rc = ::RegGetValueA(
- root_key, reg_key_path, reg_key_name, RRF_RT_REG_SZ,
- nullptr, // We know the type will be REG_SZ.
- nullptr, // We're only fetching the size; no buffer given yet.
- &buffer_size); // Fetch the size in bytes of the value, if it exists.
- if (rc != 0) {
- return false;
- }
-
- if (buffer_size > kProductNameBufferSize) {
+bool check_bios_data(const char*) { return false; }
+
+bool check_windows_registry_product_name(HKEY root_key,
+ const char* reg_key_path,
+ const char* reg_key_name) {
+ const size_t kProductNameBufferSize = 256;
+ char const expected_substr[] = "Google";
+
+ // Get the size of the string first to allocate our buffer. This includes
+ // enough space for the trailing NUL character that will be included.
+ DWORD buffer_size{};
+ auto rc = ::RegGetValueA(
+ root_key, reg_key_path, reg_key_name, RRF_RT_REG_SZ,
+ nullptr, // We know the type will be REG_SZ.
+ nullptr, // We're only fetching the size; no buffer given yet.
+ &buffer_size); // Fetch the size in bytes of the value, if it exists.
+ if (rc != 0) {
+ return false;
+ }
+
+ if (buffer_size > kProductNameBufferSize) {
return false;
}
-
- // Retrieve the product name string.
- char buffer[kProductNameBufferSize];
- buffer_size = kProductNameBufferSize;
- rc = ::RegGetValueA(
- root_key, reg_key_path, reg_key_name, RRF_RT_REG_SZ,
- nullptr, // We know the type will be REG_SZ.
- static_cast<void*>(buffer), // Fetch the string value this time.
- &buffer_size); // The string size in bytes, not including trailing NUL.
- if (rc != 0) {
+
+ // Retrieve the product name string.
+ char buffer[kProductNameBufferSize];
+ buffer_size = kProductNameBufferSize;
+ rc = ::RegGetValueA(
+ root_key, reg_key_path, reg_key_name, RRF_RT_REG_SZ,
+ nullptr, // We know the type will be REG_SZ.
+ static_cast<void*>(buffer), // Fetch the string value this time.
+ &buffer_size); // The string size in bytes, not including trailing NUL.
+ if (rc != 0) {
return false;
}
-
- return strstr(buffer, expected_substr) != nullptr;
+
+ return strstr(buffer, expected_substr) != nullptr;
}
-} // namespace internal
-} // namespace grpc_core
-
-static bool g_compute_engine_detection_done = false;
-static bool g_is_on_compute_engine = false;
-static gpr_mu g_mu;
-static gpr_once g_once = GPR_ONCE_INIT;
-
-static void init_mu(void) { gpr_mu_init(&g_mu); }
-
+} // namespace internal
+} // namespace grpc_core
+
+static bool g_compute_engine_detection_done = false;
+static bool g_is_on_compute_engine = false;
+static gpr_mu g_mu;
+static gpr_once g_once = GPR_ONCE_INIT;
+
+static void init_mu(void) { gpr_mu_init(&g_mu); }
+
bool grpc_alts_is_running_on_gcp() {
- char const reg_key_path[] = "SYSTEM\\HardwareConfig\\Current\\";
- char const reg_key_name[] = "SystemProductName";
-
+ char const reg_key_path[] = "SYSTEM\\HardwareConfig\\Current\\";
+ char const reg_key_name[] = "SystemProductName";
+
gpr_once_init(&g_once, init_mu);
gpr_mu_lock(&g_mu);
if (!g_compute_engine_detection_done) {
g_is_on_compute_engine =
- grpc_core::internal::check_windows_registry_product_name(
- HKEY_LOCAL_MACHINE, reg_key_path, reg_key_name);
+ grpc_core::internal::check_windows_registry_product_name(
+ HKEY_LOCAL_MACHINE, reg_key_path, reg_key_name);
g_compute_engine_detection_done = true;
}
gpr_mu_unlock(&g_mu);
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc
index 72c654211f..a90d78b78a 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc
@@ -31,7 +31,7 @@ static grpc_alts_credentials_options* alts_server_options_copy(
const grpc_alts_credentials_options* options);
static void alts_server_options_destroy(
- grpc_alts_credentials_options* /*options*/) {}
+ grpc_alts_credentials_options* /*options*/) {}
static const grpc_alts_credentials_options_vtable vtable = {
alts_server_options_copy, alts_server_options_destroy};
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc
index a6c82d4774..3519f307a1 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc
@@ -83,9 +83,9 @@ static void composite_call_metadata_cb(void* arg, grpc_error* error) {
}
// We're done!
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, ctx->on_request_metadata,
- GRPC_ERROR_REF(error));
- delete ctx;
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, ctx->on_request_metadata,
+ GRPC_ERROR_REF(error));
+ delete ctx;
}
bool grpc_composite_call_credentials::get_request_metadata(
@@ -93,7 +93,7 @@ bool grpc_composite_call_credentials::get_request_metadata(
grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata,
grpc_error** error) {
grpc_composite_call_credentials_metadata_context* ctx;
- ctx = new grpc_composite_call_credentials_metadata_context(
+ ctx = new grpc_composite_call_credentials_metadata_context(
this, pollent, auth_md_context, md_array, on_request_metadata);
bool synchronous = true;
const CallCredentialsList& inner = ctx->composite_creds->inner();
@@ -107,7 +107,7 @@ bool grpc_composite_call_credentials::get_request_metadata(
break;
}
}
- if (synchronous) delete ctx;
+ if (synchronous) delete ctx;
return synchronous;
}
@@ -224,6 +224,6 @@ grpc_channel_credentials* grpc_composite_channel_credentials_create(
"grpc_composite_channel_credentials_create(channel_creds=%p, "
"call_creds=%p, reserved=%p)",
3, (channel_creds, call_creds, reserved));
- return new grpc_composite_channel_credentials(channel_creds->Ref(),
- call_creds->Ref());
+ return new grpc_composite_channel_credentials(channel_creds->Ref(),
+ call_creds->Ref());
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h
index 15a85cbd0b..cdee6fb2ee 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h
@@ -68,8 +68,8 @@ typedef enum {
#define GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH \
"/computeMetadata/v1/instance/service-accounts/default/token"
-#define GRPC_GOOGLE_OAUTH2_SERVICE_HOST "oauth2.googleapis.com"
-#define GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH "/token"
+#define GRPC_GOOGLE_OAUTH2_SERVICE_HOST "oauth2.googleapis.com"
+#define GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH "/token"
#define GRPC_SERVICE_ACCOUNT_POST_BODY_PREFIX \
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&" \
@@ -112,7 +112,7 @@ struct grpc_channel_credentials
create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
const char* target, const grpc_channel_args* args,
- grpc_channel_args** new_args) = 0;
+ grpc_channel_args** new_args) = 0;
// Creates a version of the channel credentials without any attached call
// credentials. This can be used in order to open a channel to a non-trusted
@@ -187,13 +187,13 @@ struct grpc_call_credentials
grpc_auth_metadata_context context,
grpc_credentials_mdelem_array* md_array,
grpc_closure* on_request_metadata,
- grpc_error** error) = 0;
+ grpc_error** error) = 0;
// Cancels a pending asynchronous operation started by
// grpc_call_credentials_get_request_metadata() with the corresponding
// value of \a md_array.
virtual void cancel_get_request_metadata(
- grpc_credentials_mdelem_array* md_array, grpc_error* error) = 0;
+ grpc_credentials_mdelem_array* md_array, grpc_error* error) = 0;
virtual grpc_security_level min_security_level() const {
return min_security_level_;
@@ -228,7 +228,7 @@ struct grpc_server_credentials
virtual ~grpc_server_credentials() { DestroyProcessor(); }
virtual grpc_core::RefCountedPtr<grpc_server_security_connector>
- create_security_connector() = 0;
+ create_security_connector() = 0;
const char* type() const { return type_; }
@@ -274,12 +274,12 @@ struct grpc_credentials_metadata_request {
inline grpc_credentials_metadata_request*
grpc_credentials_metadata_request_create(
grpc_core::RefCountedPtr<grpc_call_credentials> creds) {
- return new grpc_credentials_metadata_request(std::move(creds));
+ return new grpc_credentials_metadata_request(std::move(creds));
}
inline void grpc_credentials_metadata_request_destroy(
grpc_credentials_metadata_request* r) {
- delete r;
+ delete r;
}
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc
index 8fd0493ee4..20c02c0fb0 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc
@@ -45,7 +45,7 @@ class grpc_fake_channel_credentials final : public grpc_channel_credentials {
create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
const char* target, const grpc_channel_args* args,
- grpc_channel_args** /*new_args*/) override {
+ grpc_channel_args** /*new_args*/) override {
return grpc_fake_channel_security_connector_create(
this->Ref(), std::move(call_creds), target, args);
}
@@ -66,12 +66,12 @@ class grpc_fake_server_credentials final : public grpc_server_credentials {
} // namespace
grpc_channel_credentials* grpc_fake_transport_security_credentials_create() {
- return new grpc_fake_channel_credentials();
+ return new grpc_fake_channel_credentials();
}
grpc_server_credentials*
grpc_fake_transport_security_server_credentials_create() {
- return new grpc_fake_server_credentials();
+ return new grpc_fake_server_credentials();
}
grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets) {
@@ -89,24 +89,24 @@ const char* grpc_fake_transport_get_expected_targets(
/* -- Metadata-only test credentials. -- */
bool grpc_md_only_test_credentials::get_request_metadata(
- grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
+ grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata,
- grpc_error** /*error*/) {
+ grpc_error** /*error*/) {
grpc_credentials_mdelem_array_add(md_array, md_);
if (is_async_) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_request_metadata,
- GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_request_metadata,
+ GRPC_ERROR_NONE);
return false;
}
return true;
}
void grpc_md_only_test_credentials::cancel_get_request_metadata(
- grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
+ grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
grpc_call_credentials* grpc_md_only_test_credentials_create(
const char* md_key, const char* md_value, bool is_async) {
- return new grpc_md_only_test_credentials(md_key, md_value, is_async);
+ return new grpc_md_only_test_credentials(md_key, md_value, is_async);
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc
index 8f3ca009a5..cec0e055b1 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc
@@ -156,7 +156,7 @@ static void on_metadata_server_detection_http_response(void* user_data,
gpr_mu_unlock(g_polling_mu);
}
-static void destroy_pollset(void* p, grpc_error* /*e*/) {
+static void destroy_pollset(void* p, grpc_error* /*e*/) {
grpc_pollset_destroy(static_cast<grpc_pollset*>(p));
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc
index a03e4970b8..4bef77256a 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc
@@ -34,15 +34,15 @@ grpc_google_iam_credentials::~grpc_google_iam_credentials() {
}
bool grpc_google_iam_credentials::get_request_metadata(
- grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
- grpc_credentials_mdelem_array* md_array,
- grpc_closure* /*on_request_metadata*/, grpc_error** /*error*/) {
+ grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
+ grpc_credentials_mdelem_array* md_array,
+ grpc_closure* /*on_request_metadata*/, grpc_error** /*error*/) {
grpc_credentials_mdelem_array_append(md_array, &md_array_);
return true;
}
void grpc_google_iam_credentials::cancel_get_request_metadata(
- grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
+ grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.cc b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.cc
index c0c5b52782..b1231fa086 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/security/credentials/jwt/json_token.h"
#include <string.h>
@@ -72,7 +72,7 @@ grpc_auth_json_key grpc_auth_json_key_create_from_json(const Json& json) {
BIO* bio = nullptr;
const char* prop_value;
int success = 0;
- grpc_error* error = GRPC_ERROR_NONE;
+ grpc_error* error = GRPC_ERROR_NONE;
memset(&result, 0, sizeof(grpc_auth_json_key));
result.type = GRPC_AUTH_JSON_TYPE_INVALID;
@@ -81,8 +81,8 @@ grpc_auth_json_key grpc_auth_json_key_create_from_json(const Json& json) {
goto end;
}
- prop_value = grpc_json_get_string_property(json, "type", &error);
- GRPC_LOG_IF_ERROR("JSON key parsing", error);
+ prop_value = grpc_json_get_string_property(json, "type", &error);
+ GRPC_LOG_IF_ERROR("JSON key parsing", error);
if (prop_value == nullptr ||
strcmp(prop_value, GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT)) {
goto end;
@@ -97,8 +97,8 @@ grpc_auth_json_key grpc_auth_json_key_create_from_json(const Json& json) {
goto end;
}
- prop_value = grpc_json_get_string_property(json, "private_key", &error);
- GRPC_LOG_IF_ERROR("JSON key parsing", error);
+ prop_value = grpc_json_get_string_property(json, "private_key", &error);
+ GRPC_LOG_IF_ERROR("JSON key parsing", error);
if (prop_value == nullptr) {
goto end;
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.h b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.h
index b9a41c6b2b..9f0b11b793 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.h
@@ -28,7 +28,7 @@
/* --- Constants. --- */
-#define GRPC_JWT_OAUTH2_AUDIENCE "https://oauth2.googleapis.com/token"
+#define GRPC_JWT_OAUTH2_AUDIENCE "https://oauth2.googleapis.com/token"
/* --- auth_json_key parsing. --- */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc
index d5555c3aa1..00aedb935b 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc
@@ -57,9 +57,9 @@ grpc_service_account_jwt_access_credentials::
}
bool grpc_service_account_jwt_access_credentials::get_request_metadata(
- grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context context,
- grpc_credentials_mdelem_array* md_array,
- grpc_closure* /*on_request_metadata*/, grpc_error** error) {
+ grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context context,
+ grpc_credentials_mdelem_array* md_array,
+ grpc_closure* /*on_request_metadata*/, grpc_error** error) {
gpr_timespec refresh_threshold = gpr_time_from_seconds(
GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, GPR_TIMESPAN);
@@ -109,7 +109,7 @@ bool grpc_service_account_jwt_access_credentials::get_request_metadata(
}
void grpc_service_account_jwt_access_credentials::cancel_get_request_metadata(
- grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
+ grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
@@ -153,7 +153,7 @@ static char* redact_private_key(const char* json_key) {
grpc_call_credentials* grpc_service_account_jwt_access_credentials_create(
const char* json_key, gpr_timespec token_lifetime, void* reserved) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
char* clean_json = redact_private_key(json_key);
gpr_log(GPR_INFO,
"grpc_service_account_jwt_access_credentials_create("
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc
index 0c9e118826..a453e30ad4 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc
@@ -349,7 +349,7 @@ struct verifier_cb_ctx {
/* Takes ownership of the header, claims and signature. */
static verifier_cb_ctx* verifier_cb_ctx_create(
grpc_jwt_verifier* verifier, grpc_pollset* pollset, jose_header* header,
- grpc_jwt_claims* claims, const char* audience, const grpc_slice& signature,
+ grpc_jwt_claims* claims, const char* audience, const grpc_slice& signature,
const char* signed_jwt, size_t signed_jwt_len, void* user_data,
grpc_jwt_verification_done_cb cb) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
@@ -594,8 +594,8 @@ static EVP_PKEY* find_verification_key(const Json& json, const char* header_alg,
}
static int verify_jwt_signature(EVP_PKEY* key, const char* alg,
- const grpc_slice& signature,
- const grpc_slice& signed_data) {
+ const grpc_slice& signature,
+ const grpc_slice& signed_data) {
EVP_MD_CTX* md_ctx = EVP_MD_CTX_create();
const EVP_MD* md = evp_md_from_alg(alg);
int result = 0;
@@ -626,7 +626,7 @@ end:
return result;
}
-static void on_keys_retrieved(void* user_data, grpc_error* /*error*/) {
+static void on_keys_retrieved(void* user_data, grpc_error* /*error*/) {
verifier_cb_ctx* ctx = static_cast<verifier_cb_ctx*>(user_data);
Json json = json_from_http(&ctx->responses[HTTP_RESPONSE_KEYS]);
EVP_PKEY* verification_key = nullptr;
@@ -665,7 +665,7 @@ end:
verifier_cb_ctx_destroy(ctx);
}
-static void on_openid_config_retrieved(void* user_data, grpc_error* /*error*/) {
+static void on_openid_config_retrieved(void* user_data, grpc_error* /*error*/) {
verifier_cb_ctx* ctx = static_cast<verifier_cb_ctx*>(user_data);
const grpc_http_response* response = &ctx->responses[HTTP_RESPONSE_OPENID];
Json json = json_from_http(response);
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc
index 966a887baf..22dc8e717b 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc
@@ -33,7 +33,7 @@ grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_local_credentials::create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char* target_name, const grpc_channel_args* args,
- grpc_channel_args** /*new_args*/) {
+ grpc_channel_args** /*new_args*/) {
return grpc_local_channel_security_connector_create(
this->Ref(), std::move(request_metadata_creds), args, target_name);
}
@@ -50,7 +50,7 @@ grpc_local_credentials::grpc_local_credentials(
grpc_channel_credentials* grpc_local_credentials_create(
grpc_local_connect_type connect_type) {
- return new grpc_local_credentials(connect_type);
+ return new grpc_local_credentials(connect_type);
}
grpc_local_server_credentials::grpc_local_server_credentials(
@@ -60,5 +60,5 @@ grpc_local_server_credentials::grpc_local_server_credentials(
grpc_server_credentials* grpc_local_server_credentials_create(
grpc_local_connect_type connect_type) {
- return new grpc_local_server_credentials(connect_type);
+ return new grpc_local_server_credentials(connect_type);
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc
index 552ee37cfc..e079f16b42 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/json/json.h"
+#include "src/core/lib/json/json.h"
#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
#include <string.h>
@@ -28,21 +28,21 @@
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/grpc_security.h>
-#include <grpc/impl/codegen/slice.h>
-#include <grpc/slice.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string.h"
+#include <grpc/grpc_security.h>
+#include <grpc/impl/codegen/slice.h>
+#include <grpc/slice.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/load_file.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/security/util/json_util.h"
-#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/uri/uri_parser.h"
+#include "src/core/lib/uri/uri_parser.h"
using grpc_core::Json;
@@ -61,7 +61,7 @@ grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
grpc_auth_refresh_token result;
const char* prop_value;
int success = 0;
- grpc_error* error = GRPC_ERROR_NONE;
+ grpc_error* error = GRPC_ERROR_NONE;
memset(&result, 0, sizeof(grpc_auth_refresh_token));
result.type = GRPC_AUTH_JSON_TYPE_INVALID;
@@ -70,8 +70,8 @@ grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
goto end;
}
- prop_value = grpc_json_get_string_property(json, "type", &error);
- GRPC_LOG_IF_ERROR("Parsing refresh token", error);
+ prop_value = grpc_json_get_string_property(json, "type", &error);
+ GRPC_LOG_IF_ERROR("Parsing refresh token", error);
if (prop_value == nullptr ||
strcmp(prop_value, GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER)) {
goto end;
@@ -205,7 +205,7 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response(
*token_lifetime = strtol(expires_in, nullptr, 10) * GPR_MS_PER_SEC;
if (!GRPC_MDISNULL(*token_md)) GRPC_MDELEM_UNREF(*token_md);
*token_md = grpc_mdelem_from_slices(
- grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
+ grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_cpp_string(
y_absl::StrCat(token_type, " ", access_token)));
status = GRPC_CREDENTIALS_OK;
@@ -233,12 +233,12 @@ static void on_oauth2_token_fetcher_http_response(void* user_data,
void grpc_oauth2_token_fetcher_credentials::on_http_response(
grpc_credentials_metadata_request* r, grpc_error* error) {
grpc_mdelem access_token_md = GRPC_MDNULL;
- grpc_millis token_lifetime = 0;
+ grpc_millis token_lifetime = 0;
grpc_credentials_status status =
- error == GRPC_ERROR_NONE
- ? grpc_oauth2_token_fetcher_credentials_parse_server_response(
- &r->response, &access_token_md, &token_lifetime)
- : GRPC_CREDENTIALS_ERROR;
+ error == GRPC_ERROR_NONE
+ ? grpc_oauth2_token_fetcher_credentials_parse_server_response(
+ &r->response, &access_token_md, &token_lifetime)
+ : GRPC_CREDENTIALS_ERROR;
// Update cache and grab list of pending requests.
gpr_mu_lock(&mu_);
token_fetch_pending_ = false;
@@ -253,16 +253,16 @@ void grpc_oauth2_token_fetcher_credentials::on_http_response(
gpr_mu_unlock(&mu_);
// Invoke callbacks for all pending requests.
while (pending_request != nullptr) {
- grpc_error* new_error = GRPC_ERROR_NONE;
+ grpc_error* new_error = GRPC_ERROR_NONE;
if (status == GRPC_CREDENTIALS_OK) {
grpc_credentials_mdelem_array_add(pending_request->md_array,
access_token_md);
} else {
- new_error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ new_error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Error occurred when fetching oauth2 token.", &error, 1);
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- pending_request->on_request_metadata, new_error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ pending_request->on_request_metadata, new_error);
grpc_polling_entity_del_from_pollset_set(
pending_request->pollent, grpc_polling_entity_pollset_set(&pollent_));
grpc_oauth2_pending_get_request_metadata* prev = pending_request;
@@ -275,9 +275,9 @@ void grpc_oauth2_token_fetcher_credentials::on_http_response(
}
bool grpc_oauth2_token_fetcher_credentials::get_request_metadata(
- grpc_polling_entity* pollent, grpc_auth_metadata_context /*context*/,
+ grpc_polling_entity* pollent, grpc_auth_metadata_context /*context*/,
grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata,
- grpc_error** /*error*/) {
+ grpc_error** /*error*/) {
// Check if we can use the cached token.
grpc_millis refresh_threshold =
GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS * GPR_MS_PER_SEC;
@@ -338,9 +338,9 @@ void grpc_oauth2_token_fetcher_credentials::cancel_get_request_metadata(
pending_requests_ = pending_request->next;
}
// Invoke the callback immediately with an error.
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- pending_request->on_request_metadata,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ pending_request->on_request_metadata,
+ GRPC_ERROR_REF(error));
gpr_free(pending_request);
break;
}
@@ -382,8 +382,8 @@ class grpc_compute_engine_token_fetcher_credentials
grpc_polling_entity* pollent,
grpc_iomgr_cb_func response_cb,
grpc_millis deadline) override {
- grpc_http_header header = {const_cast<char*>("Metadata-Flavor"),
- const_cast<char*>("Google")};
+ grpc_http_header header = {const_cast<char*>("Metadata-Flavor"),
+ const_cast<char*>("Google")};
grpc_httpcli_request request;
memset(&request, 0, sizeof(grpc_httpcli_request));
request.host = (char*)GRPC_COMPUTE_ENGINE_METADATA_HOST;
@@ -396,20 +396,20 @@ class grpc_compute_engine_token_fetcher_credentials
grpc_resource_quota* resource_quota =
grpc_resource_quota_create("oauth2_credentials");
grpc_httpcli_get(http_context, pollent, resource_quota, &request, deadline,
- GRPC_CLOSURE_INIT(&http_get_cb_closure_, response_cb,
- metadata_req, grpc_schedule_on_exec_ctx),
+ GRPC_CLOSURE_INIT(&http_get_cb_closure_, response_cb,
+ metadata_req, grpc_schedule_on_exec_ctx),
&metadata_req->response);
grpc_resource_quota_unref_internal(resource_quota);
}
-
+
TString debug_string() override {
return y_absl::StrFormat(
"GoogleComputeEngineTokenFetcherCredentials{%s}",
grpc_oauth2_token_fetcher_credentials::debug_string());
}
- private:
- grpc_closure http_get_cb_closure_;
+ private:
+ grpc_closure http_get_cb_closure_;
};
} // namespace
@@ -437,9 +437,9 @@ void grpc_google_refresh_token_credentials::fetch_oauth2(
grpc_credentials_metadata_request* metadata_req,
grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent,
grpc_iomgr_cb_func response_cb, grpc_millis deadline) {
- grpc_http_header header = {
- const_cast<char*>("Content-Type"),
- const_cast<char*>("application/x-www-form-urlencoded")};
+ grpc_http_header header = {
+ const_cast<char*>("Content-Type"),
+ const_cast<char*>("application/x-www-form-urlencoded")};
grpc_httpcli_request request;
TString body = y_absl::StrFormat(
GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, refresh_token_.client_id,
@@ -457,9 +457,9 @@ void grpc_google_refresh_token_credentials::fetch_oauth2(
grpc_resource_quota_create("oauth2_credentials_refresh");
grpc_httpcli_post(httpcli_context, pollent, resource_quota, &request,
body.c_str(), body.size(), deadline,
- GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb,
- metadata_req, grpc_schedule_on_exec_ctx),
- &metadata_req->response);
+ GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb,
+ metadata_req, grpc_schedule_on_exec_ctx),
+ &metadata_req->response);
grpc_resource_quota_unref_internal(resource_quota);
}
@@ -499,7 +499,7 @@ grpc_call_credentials* grpc_google_refresh_token_credentials_create(
const char* json_refresh_token, void* reserved) {
grpc_auth_refresh_token token =
grpc_auth_refresh_token_create_from_string(json_refresh_token);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
gpr_log(GPR_INFO,
"grpc_refresh_token_credentials_create(json_refresh_token=%s, "
"reserved=%p)",
@@ -511,46 +511,46 @@ grpc_call_credentials* grpc_google_refresh_token_credentials_create(
}
//
-// STS credentials.
-//
-
-namespace grpc_core {
-
-namespace {
-
+// STS credentials.
+//
+
+namespace grpc_core {
+
+namespace {
+
void MaybeAddToBody(const char* field_name, const char* field,
std::vector<TString>* body) {
- if (field == nullptr || strlen(field) == 0) return;
+ if (field == nullptr || strlen(field) == 0) return;
body->push_back(y_absl::StrFormat("&%s=%s", field_name, field));
-}
-
-grpc_error* LoadTokenFile(const char* path, gpr_slice* token) {
- grpc_error* err = grpc_load_file(path, 1, token);
- if (err != GRPC_ERROR_NONE) return err;
- if (GRPC_SLICE_LENGTH(*token) == 0) {
- gpr_log(GPR_ERROR, "Token file %s is empty", path);
- err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Token file is empty.");
- }
- return err;
-}
-
-class StsTokenFetcherCredentials
- : public grpc_oauth2_token_fetcher_credentials {
- public:
- StsTokenFetcherCredentials(grpc_uri* sts_url, // Ownership transferred.
- const grpc_sts_credentials_options* options)
- : sts_url_(sts_url),
- resource_(gpr_strdup(options->resource)),
- audience_(gpr_strdup(options->audience)),
- scope_(gpr_strdup(options->scope)),
- requested_token_type_(gpr_strdup(options->requested_token_type)),
- subject_token_path_(gpr_strdup(options->subject_token_path)),
- subject_token_type_(gpr_strdup(options->subject_token_type)),
- actor_token_path_(gpr_strdup(options->actor_token_path)),
- actor_token_type_(gpr_strdup(options->actor_token_type)) {}
-
- ~StsTokenFetcherCredentials() override { grpc_uri_destroy(sts_url_); }
-
+}
+
+grpc_error* LoadTokenFile(const char* path, gpr_slice* token) {
+ grpc_error* err = grpc_load_file(path, 1, token);
+ if (err != GRPC_ERROR_NONE) return err;
+ if (GRPC_SLICE_LENGTH(*token) == 0) {
+ gpr_log(GPR_ERROR, "Token file %s is empty", path);
+ err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Token file is empty.");
+ }
+ return err;
+}
+
+class StsTokenFetcherCredentials
+ : public grpc_oauth2_token_fetcher_credentials {
+ public:
+ StsTokenFetcherCredentials(grpc_uri* sts_url, // Ownership transferred.
+ const grpc_sts_credentials_options* options)
+ : sts_url_(sts_url),
+ resource_(gpr_strdup(options->resource)),
+ audience_(gpr_strdup(options->audience)),
+ scope_(gpr_strdup(options->scope)),
+ requested_token_type_(gpr_strdup(options->requested_token_type)),
+ subject_token_path_(gpr_strdup(options->subject_token_path)),
+ subject_token_type_(gpr_strdup(options->subject_token_type)),
+ actor_token_path_(gpr_strdup(options->actor_token_path)),
+ actor_token_type_(gpr_strdup(options->actor_token_type)) {}
+
+ ~StsTokenFetcherCredentials() override { grpc_uri_destroy(sts_url_); }
+
TString debug_string() override {
return y_absl::StrFormat(
"StsTokenFetcherCredentials{Path:%s,Authority:%s,%s}", sts_url_->path,
@@ -558,71 +558,71 @@ class StsTokenFetcherCredentials
grpc_oauth2_token_fetcher_credentials::debug_string());
}
- private:
- void fetch_oauth2(grpc_credentials_metadata_request* metadata_req,
- grpc_httpcli_context* http_context,
- grpc_polling_entity* pollent,
- grpc_iomgr_cb_func response_cb,
- grpc_millis deadline) override {
- char* body = nullptr;
- size_t body_length = 0;
- grpc_error* err = FillBody(&body, &body_length);
- if (err != GRPC_ERROR_NONE) {
- response_cb(metadata_req, err);
- GRPC_ERROR_UNREF(err);
- return;
- }
- grpc_http_header header = {
- const_cast<char*>("Content-Type"),
- const_cast<char*>("application/x-www-form-urlencoded")};
- grpc_httpcli_request request;
- memset(&request, 0, sizeof(grpc_httpcli_request));
- request.host = (char*)sts_url_->authority;
- request.http.path = (char*)sts_url_->path;
- request.http.hdr_count = 1;
- request.http.hdrs = &header;
- request.handshaker = (strcmp(sts_url_->scheme, "https") == 0)
- ? &grpc_httpcli_ssl
- : &grpc_httpcli_plaintext;
- /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host
- channel. This would allow us to cancel an authentication query when under
- extreme memory pressure. */
- grpc_resource_quota* resource_quota =
- grpc_resource_quota_create("oauth2_credentials_refresh");
- grpc_httpcli_post(
- http_context, pollent, resource_quota, &request, body, body_length,
- deadline,
- GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb, metadata_req,
- grpc_schedule_on_exec_ctx),
- &metadata_req->response);
- grpc_resource_quota_unref_internal(resource_quota);
- gpr_free(body);
- }
-
- grpc_error* FillBody(char** body, size_t* body_length) {
- *body = nullptr;
+ private:
+ void fetch_oauth2(grpc_credentials_metadata_request* metadata_req,
+ grpc_httpcli_context* http_context,
+ grpc_polling_entity* pollent,
+ grpc_iomgr_cb_func response_cb,
+ grpc_millis deadline) override {
+ char* body = nullptr;
+ size_t body_length = 0;
+ grpc_error* err = FillBody(&body, &body_length);
+ if (err != GRPC_ERROR_NONE) {
+ response_cb(metadata_req, err);
+ GRPC_ERROR_UNREF(err);
+ return;
+ }
+ grpc_http_header header = {
+ const_cast<char*>("Content-Type"),
+ const_cast<char*>("application/x-www-form-urlencoded")};
+ grpc_httpcli_request request;
+ memset(&request, 0, sizeof(grpc_httpcli_request));
+ request.host = (char*)sts_url_->authority;
+ request.http.path = (char*)sts_url_->path;
+ request.http.hdr_count = 1;
+ request.http.hdrs = &header;
+ request.handshaker = (strcmp(sts_url_->scheme, "https") == 0)
+ ? &grpc_httpcli_ssl
+ : &grpc_httpcli_plaintext;
+ /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host
+ channel. This would allow us to cancel an authentication query when under
+ extreme memory pressure. */
+ grpc_resource_quota* resource_quota =
+ grpc_resource_quota_create("oauth2_credentials_refresh");
+ grpc_httpcli_post(
+ http_context, pollent, resource_quota, &request, body, body_length,
+ deadline,
+ GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb, metadata_req,
+ grpc_schedule_on_exec_ctx),
+ &metadata_req->response);
+ grpc_resource_quota_unref_internal(resource_quota);
+ gpr_free(body);
+ }
+
+ grpc_error* FillBody(char** body, size_t* body_length) {
+ *body = nullptr;
std::vector<TString> body_parts;
- grpc_slice subject_token = grpc_empty_slice();
- grpc_slice actor_token = grpc_empty_slice();
- grpc_error* err = GRPC_ERROR_NONE;
-
+ grpc_slice subject_token = grpc_empty_slice();
+ grpc_slice actor_token = grpc_empty_slice();
+ grpc_error* err = GRPC_ERROR_NONE;
+
auto cleanup = [&body, &body_length, &body_parts, &subject_token,
- &actor_token, &err]() {
- if (err == GRPC_ERROR_NONE) {
+ &actor_token, &err]() {
+ if (err == GRPC_ERROR_NONE) {
TString body_str = y_absl::StrJoin(body_parts, "");
*body = gpr_strdup(body_str.c_str());
*body_length = body_str.size();
- }
- grpc_slice_unref_internal(subject_token);
- grpc_slice_unref_internal(actor_token);
- return err;
- };
-
- err = LoadTokenFile(subject_token_path_.get(), &subject_token);
- if (err != GRPC_ERROR_NONE) return cleanup();
+ }
+ grpc_slice_unref_internal(subject_token);
+ grpc_slice_unref_internal(actor_token);
+ return err;
+ };
+
+ err = LoadTokenFile(subject_token_path_.get(), &subject_token);
+ if (err != GRPC_ERROR_NONE) return cleanup();
body_parts.push_back(y_absl::StrFormat(
GRPC_STS_POST_MINIMAL_BODY_FORMAT_STRING,
- reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(subject_token)),
+ reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(subject_token)),
subject_token_type_.get()));
MaybeAddToBody("resource", resource_.get(), &body_parts);
MaybeAddToBody("audience", audience_.get(), &body_parts);
@@ -630,91 +630,91 @@ class StsTokenFetcherCredentials
MaybeAddToBody("requested_token_type", requested_token_type_.get(),
&body_parts);
if ((actor_token_path_ != nullptr) && *actor_token_path_ != '\0') {
- err = LoadTokenFile(actor_token_path_.get(), &actor_token);
- if (err != GRPC_ERROR_NONE) return cleanup();
- MaybeAddToBody(
+ err = LoadTokenFile(actor_token_path_.get(), &actor_token);
+ if (err != GRPC_ERROR_NONE) return cleanup();
+ MaybeAddToBody(
"actor_token",
reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(actor_token)),
&body_parts);
MaybeAddToBody("actor_token_type", actor_token_type_.get(), &body_parts);
- }
- return cleanup();
- }
-
- grpc_uri* sts_url_;
- grpc_closure http_post_cb_closure_;
- grpc_core::UniquePtr<char> resource_;
- grpc_core::UniquePtr<char> audience_;
- grpc_core::UniquePtr<char> scope_;
- grpc_core::UniquePtr<char> requested_token_type_;
- grpc_core::UniquePtr<char> subject_token_path_;
- grpc_core::UniquePtr<char> subject_token_type_;
- grpc_core::UniquePtr<char> actor_token_path_;
- grpc_core::UniquePtr<char> actor_token_type_;
-};
-
-} // namespace
-
-grpc_error* ValidateStsCredentialsOptions(
- const grpc_sts_credentials_options* options, grpc_uri** sts_url_out) {
- struct GrpcUriDeleter {
- void operator()(grpc_uri* uri) { grpc_uri_destroy(uri); }
- };
- *sts_url_out = nullptr;
+ }
+ return cleanup();
+ }
+
+ grpc_uri* sts_url_;
+ grpc_closure http_post_cb_closure_;
+ grpc_core::UniquePtr<char> resource_;
+ grpc_core::UniquePtr<char> audience_;
+ grpc_core::UniquePtr<char> scope_;
+ grpc_core::UniquePtr<char> requested_token_type_;
+ grpc_core::UniquePtr<char> subject_token_path_;
+ grpc_core::UniquePtr<char> subject_token_type_;
+ grpc_core::UniquePtr<char> actor_token_path_;
+ grpc_core::UniquePtr<char> actor_token_type_;
+};
+
+} // namespace
+
+grpc_error* ValidateStsCredentialsOptions(
+ const grpc_sts_credentials_options* options, grpc_uri** sts_url_out) {
+ struct GrpcUriDeleter {
+ void operator()(grpc_uri* uri) { grpc_uri_destroy(uri); }
+ };
+ *sts_url_out = nullptr;
y_absl::InlinedVector<grpc_error*, 3> error_list;
- std::unique_ptr<grpc_uri, GrpcUriDeleter> sts_url(
- options->token_exchange_service_uri != nullptr
- ? grpc_uri_parse(options->token_exchange_service_uri, false)
- : nullptr);
- if (sts_url == nullptr) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Invalid or missing STS endpoint URL"));
- } else {
- if (strcmp(sts_url->scheme, "https") != 0 &&
- strcmp(sts_url->scheme, "http") != 0) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Invalid URI scheme, must be https to http."));
- }
- }
- if (options->subject_token_path == nullptr ||
- strlen(options->subject_token_path) == 0) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "subject_token needs to be specified"));
- }
- if (options->subject_token_type == nullptr ||
- strlen(options->subject_token_type) == 0) {
- error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "subject_token_type needs to be specified"));
- }
- if (error_list.empty()) {
- *sts_url_out = sts_url.release();
- return GRPC_ERROR_NONE;
- } else {
- return GRPC_ERROR_CREATE_FROM_VECTOR("Invalid STS Credentials Options",
- &error_list);
- }
-}
-
-} // namespace grpc_core
-
-grpc_call_credentials* grpc_sts_credentials_create(
- const grpc_sts_credentials_options* options, void* reserved) {
- GPR_ASSERT(reserved == nullptr);
- grpc_uri* sts_url;
- grpc_error* error =
- grpc_core::ValidateStsCredentialsOptions(options, &sts_url);
- if (error != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "STS Credentials creation failed. Error: %s.",
- grpc_error_string(error));
- GRPC_ERROR_UNREF(error);
- return nullptr;
- }
- return grpc_core::MakeRefCounted<grpc_core::StsTokenFetcherCredentials>(
- sts_url, options)
- .release();
-}
-
-//
+ std::unique_ptr<grpc_uri, GrpcUriDeleter> sts_url(
+ options->token_exchange_service_uri != nullptr
+ ? grpc_uri_parse(options->token_exchange_service_uri, false)
+ : nullptr);
+ if (sts_url == nullptr) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Invalid or missing STS endpoint URL"));
+ } else {
+ if (strcmp(sts_url->scheme, "https") != 0 &&
+ strcmp(sts_url->scheme, "http") != 0) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Invalid URI scheme, must be https to http."));
+ }
+ }
+ if (options->subject_token_path == nullptr ||
+ strlen(options->subject_token_path) == 0) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "subject_token needs to be specified"));
+ }
+ if (options->subject_token_type == nullptr ||
+ strlen(options->subject_token_type) == 0) {
+ error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "subject_token_type needs to be specified"));
+ }
+ if (error_list.empty()) {
+ *sts_url_out = sts_url.release();
+ return GRPC_ERROR_NONE;
+ } else {
+ return GRPC_ERROR_CREATE_FROM_VECTOR("Invalid STS Credentials Options",
+ &error_list);
+ }
+}
+
+} // namespace grpc_core
+
+grpc_call_credentials* grpc_sts_credentials_create(
+ const grpc_sts_credentials_options* options, void* reserved) {
+ GPR_ASSERT(reserved == nullptr);
+ grpc_uri* sts_url;
+ grpc_error* error =
+ grpc_core::ValidateStsCredentialsOptions(options, &sts_url);
+ if (error != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "STS Credentials creation failed. Error: %s.",
+ grpc_error_string(error));
+ GRPC_ERROR_UNREF(error);
+ return nullptr;
+ }
+ return grpc_core::MakeRefCounted<grpc_core::StsTokenFetcherCredentials>(
+ sts_url, options)
+ .release();
+}
+
+//
// Oauth2 Access Token credentials.
//
@@ -723,15 +723,15 @@ grpc_access_token_credentials::~grpc_access_token_credentials() {
}
bool grpc_access_token_credentials::get_request_metadata(
- grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
- grpc_credentials_mdelem_array* md_array,
- grpc_closure* /*on_request_metadata*/, grpc_error** /*error*/) {
+ grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
+ grpc_credentials_mdelem_array* md_array,
+ grpc_closure* /*on_request_metadata*/, grpc_error** /*error*/) {
grpc_credentials_mdelem_array_add(md_array, access_token_md_);
return true;
}
void grpc_access_token_credentials::cancel_get_request_metadata(
- grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
+ grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
@@ -740,7 +740,7 @@ grpc_access_token_credentials::grpc_access_token_credentials(
: grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) {
grpc_core::ExecCtx exec_ctx;
access_token_md_ = grpc_mdelem_from_slices(
- grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
+ grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_cpp_string(y_absl::StrCat("Bearer ", access_token)));
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h
index fd886405cf..241e3f1758 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h
@@ -23,16 +23,16 @@
#include <util/generic/string.h>
-#include <grpc/grpc_security.h>
+#include <grpc/grpc_security.h>
#include "src/core/lib/json/json.h"
#include "src/core/lib/security/credentials/credentials.h"
-#include "src/core/lib/uri/uri_parser.h"
-
-// Constants.
-#define GRPC_STS_POST_MINIMAL_BODY_FORMAT_STRING \
- "grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token=%" \
- "s&subject_token_type=%s"
+#include "src/core/lib/uri/uri_parser.h"
+// Constants.
+#define GRPC_STS_POST_MINIMAL_BODY_FORMAT_STRING \
+ "grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token=%" \
+ "s&subject_token_type=%s"
+
// auth_refresh_token parsing.
struct grpc_auth_refresh_token {
const char* type;
@@ -91,7 +91,7 @@ class grpc_oauth2_token_fetcher_credentials : public grpc_call_credentials {
virtual void fetch_oauth2(grpc_credentials_metadata_request* req,
grpc_httpcli_context* httpcli_context,
grpc_polling_entity* pollent, grpc_iomgr_cb_func cb,
- grpc_millis deadline) = 0;
+ grpc_millis deadline) = 0;
private:
gpr_mu mu_;
@@ -124,7 +124,7 @@ class grpc_google_refresh_token_credentials final
private:
grpc_auth_refresh_token refresh_token_;
- grpc_closure http_post_cb_closure_;
+ grpc_closure http_post_cb_closure_;
};
// Access token credentials.
@@ -160,12 +160,12 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response(
const struct grpc_http_response* response, grpc_mdelem* token_md,
grpc_millis* token_lifetime);
-namespace grpc_core {
-// Exposed for testing only. This function validates the options, ensuring that
-// the required fields are set, and outputs the parsed URL of the STS token
-// exchanged service.
-grpc_error* ValidateStsCredentialsOptions(
- const grpc_sts_credentials_options* options, grpc_uri** sts_url);
-} // namespace grpc_core
-
+namespace grpc_core {
+// Exposed for testing only. This function validates the options, ensuring that
+// the required fields are set, and outputs the parsed URL of the STS token
+// exchanged service.
+grpc_error* ValidateStsCredentialsOptions(
+ const grpc_sts_credentials_options* options, grpc_uri** sts_url);
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_OAUTH2_OAUTH2_CREDENTIALS_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc
index 40d8fec6e4..925dd56472 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc
@@ -98,7 +98,7 @@ static grpc_error* process_plugin_result(
grpc_validate_header_key_is_legal(md[i].key))) {
seen_illegal_header = true;
break;
- } else if (!grpc_is_binary_header_internal(md[i].key) &&
+ } else if (!grpc_is_binary_header_internal(md[i].key) &&
!GRPC_LOG_IF_ERROR(
"validate_metadata_from_plugin",
grpc_validate_header_nonbin_value_is_legal(md[i].value))) {
@@ -132,7 +132,7 @@ static void plugin_md_request_metadata_ready(void* request,
GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP);
grpc_plugin_credentials::pending_request* r =
static_cast<grpc_plugin_credentials::pending_request*>(request);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO,
"plugin_credentials[%p]: request %p: plugin returned "
"asynchronously",
@@ -144,8 +144,8 @@ static void plugin_md_request_metadata_ready(void* request,
if (!r->cancelled) {
grpc_error* error =
process_plugin_result(r, md, num_md, status, error_details);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_request_metadata, error);
- } else if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_request_metadata, error);
+ } else if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO,
"plugin_credentials[%p]: request %p: plugin was previously "
"cancelled",
@@ -155,7 +155,7 @@ static void plugin_md_request_metadata_ready(void* request,
}
bool grpc_plugin_credentials::get_request_metadata(
- grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context context,
+ grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context context,
grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata,
grpc_error** error) {
bool retval = true; // Synchronous return.
@@ -175,7 +175,7 @@ bool grpc_plugin_credentials::get_request_metadata(
pending_requests_ = request;
gpr_mu_unlock(&mu_);
// Invoke the plugin. The callback holds a ref to us.
- if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: invoking plugin",
this, request);
}
@@ -187,7 +187,7 @@ bool grpc_plugin_credentials::get_request_metadata(
if (!plugin_.get_metadata(
plugin_.state, context, plugin_md_request_metadata_ready, request,
creds_md, &num_creds_md, &status, &error_details)) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO,
"plugin_credentials[%p]: request %p: plugin will return "
"asynchronously",
@@ -202,7 +202,7 @@ bool grpc_plugin_credentials::get_request_metadata(
// asynchronously by plugin_cancel_get_request_metadata(), so return
// false. Otherwise, process the result.
if (request->cancelled) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO,
"plugin_credentials[%p]: request %p was cancelled, error "
"will be returned asynchronously",
@@ -210,7 +210,7 @@ bool grpc_plugin_credentials::get_request_metadata(
}
retval = false;
} else {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO,
"plugin_credentials[%p]: request %p: plugin returned "
"synchronously",
@@ -236,14 +236,14 @@ void grpc_plugin_credentials::cancel_get_request_metadata(
for (pending_request* pending_request = pending_requests_;
pending_request != nullptr; pending_request = pending_request->next) {
if (pending_request->md_array == md_array) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
gpr_log(GPR_INFO, "plugin_credentials[%p]: cancelling request %p", this,
pending_request);
}
pending_request->cancelled = true;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION,
- pending_request->on_request_metadata,
- GRPC_ERROR_REF(error));
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION,
+ pending_request->on_request_metadata,
+ GRPC_ERROR_REF(error));
pending_request_remove_locked(pending_request);
break;
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc
index 3bb7790f5c..0f7a00d0c1 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc
@@ -46,7 +46,7 @@ void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp,
grpc_ssl_credentials::grpc_ssl_credentials(
const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const grpc_ssl_verify_peer_options* verify_options)
+ const grpc_ssl_verify_peer_options* verify_options)
: grpc_channel_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) {
build_config(pem_root_certs, pem_key_cert_pair, verify_options);
}
@@ -94,7 +94,7 @@ grpc_ssl_credentials::create_security_connector(
void grpc_ssl_credentials::build_config(
const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const grpc_ssl_verify_peer_options* verify_options) {
+ const grpc_ssl_verify_peer_options* verify_options) {
config_.pem_root_certs = gpr_strdup(pem_root_certs);
if (pem_key_cert_pair != nullptr) {
GPR_ASSERT(pem_key_cert_pair->private_key != nullptr);
@@ -127,8 +127,8 @@ void grpc_ssl_credentials::set_max_tls_version(
config_.max_tls_version = max_tls_version;
}
-/* Deprecated in favor of grpc_ssl_credentials_create_ex. Will be removed
- * once all of its call sites are migrated to grpc_ssl_credentials_create_ex. */
+/* Deprecated in favor of grpc_ssl_credentials_create_ex. Will be removed
+ * once all of its call sites are migrated to grpc_ssl_credentials_create_ex. */
grpc_channel_credentials* grpc_ssl_credentials_create(
const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
const verify_peer_options* verify_options, void* reserved) {
@@ -140,26 +140,26 @@ grpc_channel_credentials* grpc_ssl_credentials_create(
4, (pem_root_certs, pem_key_cert_pair, verify_options, reserved));
GPR_ASSERT(reserved == nullptr);
- return new grpc_ssl_credentials(
- pem_root_certs, pem_key_cert_pair,
- reinterpret_cast<const grpc_ssl_verify_peer_options*>(verify_options));
-}
-
-grpc_channel_credentials* grpc_ssl_credentials_create_ex(
- const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const grpc_ssl_verify_peer_options* verify_options, void* reserved) {
- GRPC_API_TRACE(
- "grpc_ssl_credentials_create(pem_root_certs=%s, "
- "pem_key_cert_pair=%p, "
- "verify_options=%p, "
- "reserved=%p)",
- 4, (pem_root_certs, pem_key_cert_pair, verify_options, reserved));
- GPR_ASSERT(reserved == nullptr);
-
- return new grpc_ssl_credentials(pem_root_certs, pem_key_cert_pair,
- verify_options);
+ return new grpc_ssl_credentials(
+ pem_root_certs, pem_key_cert_pair,
+ reinterpret_cast<const grpc_ssl_verify_peer_options*>(verify_options));
}
+grpc_channel_credentials* grpc_ssl_credentials_create_ex(
+ const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
+ const grpc_ssl_verify_peer_options* verify_options, void* reserved) {
+ GRPC_API_TRACE(
+ "grpc_ssl_credentials_create(pem_root_certs=%s, "
+ "pem_key_cert_pair=%p, "
+ "verify_options=%p, "
+ "reserved=%p)",
+ 4, (pem_root_certs, pem_key_cert_pair, verify_options, reserved));
+ GPR_ASSERT(reserved == nullptr);
+
+ return new grpc_ssl_credentials(pem_root_certs, pem_key_cert_pair,
+ verify_options);
+}
+
//
// SSL Server Credentials.
//
@@ -368,7 +368,7 @@ grpc_server_credentials* grpc_ssl_server_credentials_create_with_options(
goto done;
}
- retval = new grpc_ssl_server_credentials(*options);
+ retval = new grpc_ssl_server_credentials(*options);
done:
grpc_ssl_server_credentials_options_destroy(options);
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h
index 4c90813f8d..b97e568d77 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h
@@ -28,7 +28,7 @@ class grpc_ssl_credentials : public grpc_channel_credentials {
public:
grpc_ssl_credentials(const char* pem_root_certs,
grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const grpc_ssl_verify_peer_options* verify_options);
+ const grpc_ssl_verify_peer_options* verify_options);
~grpc_ssl_credentials() override;
@@ -46,7 +46,7 @@ class grpc_ssl_credentials : public grpc_channel_credentials {
private:
void build_config(const char* pem_root_certs,
grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const grpc_ssl_verify_peer_options* verify_options);
+ const grpc_ssl_verify_peer_options* verify_options);
grpc_ssl_config config_;
};
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc
index 906a2f0209..656d68c758 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc
@@ -94,7 +94,7 @@ grpc_tls_server_authorization_check_config::
/** -- Wrapper APIs declared in grpc_security.h -- **/
grpc_tls_credentials_options* grpc_tls_credentials_options_create() {
- return new grpc_tls_credentials_options();
+ return new grpc_tls_credentials_options();
}
int grpc_tls_credentials_options_set_cert_request_type(
@@ -171,7 +171,7 @@ int grpc_tls_credentials_options_set_server_authorization_check_config(
}
grpc_tls_key_materials_config* grpc_tls_key_materials_config_create() {
- return new grpc_tls_key_materials_config();
+ return new grpc_tls_key_materials_config();
}
int grpc_tls_key_materials_config_set_key_materials(
@@ -187,29 +187,29 @@ int grpc_tls_key_materials_config_set_key_materials(
return 1;
}
-int grpc_tls_key_materials_config_set_version(
- grpc_tls_key_materials_config* config, int version) {
- if (config == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid arguments to "
- "grpc_tls_key_materials_config_set_version()");
- return 0;
- }
- config->set_version(version);
- return 1;
-}
-
-int grpc_tls_key_materials_config_get_version(
- grpc_tls_key_materials_config* config) {
- if (config == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid arguments to "
- "grpc_tls_key_materials_config_get_version()");
- return -1;
- }
- return config->version();
-}
-
+int grpc_tls_key_materials_config_set_version(
+ grpc_tls_key_materials_config* config, int version) {
+ if (config == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to "
+ "grpc_tls_key_materials_config_set_version()");
+ return 0;
+ }
+ config->set_version(version);
+ return 1;
+}
+
+int grpc_tls_key_materials_config_get_version(
+ grpc_tls_key_materials_config* config) {
+ if (config == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to "
+ "grpc_tls_key_materials_config_get_version()");
+ return -1;
+ }
+ return config->version();
+}
+
grpc_tls_credential_reload_config* grpc_tls_credential_reload_config_create(
const void* config_user_data,
int (*schedule)(void* config_user_data,
@@ -222,8 +222,8 @@ grpc_tls_credential_reload_config* grpc_tls_credential_reload_config_create(
"Schedule API is nullptr in creating TLS credential reload config.");
return nullptr;
}
- return new grpc_tls_credential_reload_config(config_user_data, schedule,
- cancel, destruct);
+ return new grpc_tls_credential_reload_config(config_user_data, schedule,
+ cancel, destruct);
}
grpc_tls_server_authorization_check_config*
@@ -240,6 +240,6 @@ grpc_tls_server_authorization_check_config_create(
"check config.");
return nullptr;
}
- return new grpc_tls_server_authorization_check_config(
+ return new grpc_tls_server_authorization_check_config(
config_user_data, schedule, cancel, destruct);
}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h
index 59411d4169..34511cd024 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h
@@ -52,22 +52,22 @@ struct grpc_tls_key_materials_config
const PemKeyCertPairList& pem_key_cert_pair_list() const {
return pem_key_cert_pair_list_;
}
- int version() const { return version_; }
+ int version() const { return version_; }
/** Setters for member fields. **/
// TODO(ZhenLian): Remove this function
- void set_pem_root_certs(grpc_core::UniquePtr<char> pem_root_certs) {
- pem_root_certs_ = std::move(pem_root_certs);
- }
+ void set_pem_root_certs(grpc_core::UniquePtr<char> pem_root_certs) {
+ pem_root_certs_ = std::move(pem_root_certs);
+ }
// The ownerships of |pem_root_certs| remain with the caller.
void set_pem_root_certs(const char* pem_root_certs) {
// make a copy of pem_root_certs.
grpc_core::UniquePtr<char> pem_root_ptr(gpr_strdup(pem_root_certs));
pem_root_certs_ = std::move(pem_root_ptr);
}
- void add_pem_key_cert_pair(grpc_core::PemKeyCertPair pem_key_cert_pair) {
- pem_key_cert_pair_list_.push_back(pem_key_cert_pair);
- }
+ void add_pem_key_cert_pair(grpc_core::PemKeyCertPair pem_key_cert_pair) {
+ pem_key_cert_pair_list_.push_back(pem_key_cert_pair);
+ }
// The ownerships of |pem_root_certs| and |pem_key_cert_pairs| remain with the
// caller.
void set_key_materials(const char* pem_root_certs,
@@ -77,10 +77,10 @@ struct grpc_tls_key_materials_config
// the caller.
void set_key_materials(const char* pem_root_certs,
const PemKeyCertPairList& pem_key_cert_pair_list);
- void set_version(int version) { version_ = version; }
+ void set_version(int version) { version_ = version; }
private:
- int version_ = 0;
+ int version_ = 0;
PemKeyCertPairList pem_key_cert_pair_list_;
grpc_core::UniquePtr<char> pem_root_certs_;
};
@@ -98,46 +98,46 @@ struct grpc_tls_credential_reload_config
void (*destruct)(void* config_user_data));
~grpc_tls_credential_reload_config();
- void* context() const { return context_; }
- void set_context(void* context) { context_ = context; }
-
+ void* context() const { return context_; }
+ void set_context(void* context) { context_ = context; }
+
int Schedule(grpc_tls_credential_reload_arg* arg) const {
- if (schedule_ == nullptr) {
- gpr_log(GPR_ERROR, "schedule API is nullptr");
- if (arg != nullptr) {
- arg->status = GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL;
+ if (schedule_ == nullptr) {
+ gpr_log(GPR_ERROR, "schedule API is nullptr");
+ if (arg != nullptr) {
+ arg->status = GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL;
arg->error_details->set_error_details(
"schedule API in credential reload config is nullptr");
- }
- return 1;
- }
- if (arg != nullptr) {
- arg->config = const_cast<grpc_tls_credential_reload_config*>(this);
- }
+ }
+ return 1;
+ }
+ if (arg != nullptr) {
+ arg->config = const_cast<grpc_tls_credential_reload_config*>(this);
+ }
return schedule_(config_user_data_, arg);
}
void Cancel(grpc_tls_credential_reload_arg* arg) const {
if (cancel_ == nullptr) {
gpr_log(GPR_ERROR, "cancel API is nullptr.");
- if (arg != nullptr) {
- arg->status = GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL;
+ if (arg != nullptr) {
+ arg->status = GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL;
arg->error_details->set_error_details(
"cancel API in credential reload config is nullptr");
- }
+ }
return;
}
- if (arg != nullptr) {
- arg->config = const_cast<grpc_tls_credential_reload_config*>(this);
- }
+ if (arg != nullptr) {
+ arg->config = const_cast<grpc_tls_credential_reload_config*>(this);
+ }
cancel_(config_user_data_, arg);
}
private:
- /** This is a pointer to the wrapped language implementation of
- * grpc_tls_credential_reload_config. It is necessary to implement the C
- * schedule and cancel functions, given the schedule or cancel function in a
- * wrapped language. **/
- void* context_ = nullptr;
+ /** This is a pointer to the wrapped language implementation of
+ * grpc_tls_credential_reload_config. It is necessary to implement the C
+ * schedule and cancel functions, given the schedule or cancel function in a
+ * wrapped language. **/
+ void* context_ = nullptr;
/** config-specific, read-only user data that works for all channels created
with a credential using the config. */
void* config_user_data_;
@@ -174,48 +174,48 @@ struct grpc_tls_server_authorization_check_config
void (*destruct)(void* config_user_data));
~grpc_tls_server_authorization_check_config();
- void* context() const { return context_; }
- void set_context(void* context) { context_ = context; }
-
+ void* context() const { return context_; }
+ void set_context(void* context) { context_ = context; }
+
int Schedule(grpc_tls_server_authorization_check_arg* arg) const {
- if (schedule_ == nullptr) {
- gpr_log(GPR_ERROR, "schedule API is nullptr");
- if (arg != nullptr) {
- arg->status = GRPC_STATUS_NOT_FOUND;
+ if (schedule_ == nullptr) {
+ gpr_log(GPR_ERROR, "schedule API is nullptr");
+ if (arg != nullptr) {
+ arg->status = GRPC_STATUS_NOT_FOUND;
arg->error_details->set_error_details(
- "schedule API in server authorization check config is nullptr");
- }
- return 1;
- }
- if (arg != nullptr && context_ != nullptr) {
- arg->config =
- const_cast<grpc_tls_server_authorization_check_config*>(this);
- }
+ "schedule API in server authorization check config is nullptr");
+ }
+ return 1;
+ }
+ if (arg != nullptr && context_ != nullptr) {
+ arg->config =
+ const_cast<grpc_tls_server_authorization_check_config*>(this);
+ }
return schedule_(config_user_data_, arg);
}
void Cancel(grpc_tls_server_authorization_check_arg* arg) const {
if (cancel_ == nullptr) {
gpr_log(GPR_ERROR, "cancel API is nullptr.");
- if (arg != nullptr) {
- arg->status = GRPC_STATUS_NOT_FOUND;
+ if (arg != nullptr) {
+ arg->status = GRPC_STATUS_NOT_FOUND;
arg->error_details->set_error_details(
- "schedule API in server authorization check config is nullptr");
- }
+ "schedule API in server authorization check config is nullptr");
+ }
return;
}
- if (arg != nullptr) {
- arg->config =
- const_cast<grpc_tls_server_authorization_check_config*>(this);
- }
+ if (arg != nullptr) {
+ arg->config =
+ const_cast<grpc_tls_server_authorization_check_config*>(this);
+ }
cancel_(config_user_data_, arg);
}
private:
- /** This is a pointer to the wrapped language implementation of
- * grpc_tls_server_authorization_check_config. It is necessary to implement
- * the C schedule and cancel functions, given the schedule or cancel function
- * in a wrapped language. **/
- void* context_ = nullptr;
+ /** This is a pointer to the wrapped language implementation of
+ * grpc_tls_server_authorization_check_config. It is necessary to implement
+ * the C schedule and cancel functions, given the schedule or cancel function
+ * in a wrapped language. **/
+ void* context_ = nullptr;
/** config-specific, read-only user data that works for all channels created
with a Credential using the config. */
void* config_user_data_;
@@ -266,13 +266,13 @@ struct grpc_tls_credentials_options
}
grpc_tls_version min_tls_version() const { return min_tls_version_; }
grpc_tls_version max_tls_version() const { return max_tls_version_; }
- grpc_tls_key_materials_config* key_materials_config() const {
+ grpc_tls_key_materials_config* key_materials_config() const {
return key_materials_config_.get();
}
- grpc_tls_credential_reload_config* credential_reload_config() const {
+ grpc_tls_credential_reload_config* credential_reload_config() const {
return credential_reload_config_.get();
}
- grpc_tls_server_authorization_check_config*
+ grpc_tls_server_authorization_check_config*
server_authorization_check_config() const {
return server_authorization_check_config_.get();
}
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc
index d0b532ae18..b8be6bb27d 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc
@@ -36,7 +36,7 @@
#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h"
#include "src/core/tsi/transport_security.h"
-void grpc_alts_set_rpc_protocol_versions(
+void grpc_alts_set_rpc_protocol_versions(
grpc_gcp_rpc_protocol_versions* rpc_versions) {
grpc_gcp_rpc_protocol_versions_set_max(rpc_versions,
GRPC_PROTOCOL_VERSION_MAX_MAJOR,
@@ -46,8 +46,8 @@ void grpc_alts_set_rpc_protocol_versions(
GRPC_PROTOCOL_VERSION_MIN_MINOR);
}
-namespace {
-
+namespace {
+
void alts_check_peer(tsi_peer peer,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) {
@@ -59,7 +59,7 @@ void alts_check_peer(tsi_peer peer,
? GRPC_ERROR_NONE
: GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Could not get ALTS auth context from TSI peer");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
class grpc_alts_channel_security_connector final
@@ -69,15 +69,15 @@ class grpc_alts_channel_security_connector final
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds,
const char* target_name)
- : grpc_channel_security_connector(GRPC_ALTS_URL_SCHEME,
+ : grpc_channel_security_connector(GRPC_ALTS_URL_SCHEME,
std::move(channel_creds),
std::move(request_metadata_creds)),
- target_name_(gpr_strdup(target_name)) {}
+ target_name_(gpr_strdup(target_name)) {}
~grpc_alts_channel_security_connector() override { gpr_free(target_name_); }
void add_handshakers(
- const grpc_channel_args* args, grpc_pollset_set* interested_parties,
+ const grpc_channel_args* args, grpc_pollset_set* interested_parties,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
const grpc_alts_credentials* creds =
@@ -94,10 +94,10 @@ class grpc_alts_channel_security_connector final
creds->handshaker_service_url(), true, interested_parties,
&handshaker, user_specified_max_frame_size) == TSI_OK);
handshake_manager->Add(
- grpc_core::SecurityHandshakerCreate(handshaker, this, args));
+ grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
- void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
+ void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
alts_check_peer(peer, auth_context, on_peer_checked);
@@ -112,17 +112,17 @@ class grpc_alts_channel_security_connector final
}
bool check_call_host(y_absl::string_view host,
- grpc_auth_context* /*auth_context*/,
- grpc_closure* /*on_call_host_checked*/,
+ grpc_auth_context* /*auth_context*/,
+ grpc_closure* /*on_call_host_checked*/,
grpc_error** error) override {
- if (host.empty() || host != target_name_) {
+ if (host.empty() || host != target_name_) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"ALTS call host does not match target name");
}
return true;
}
- void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
+ void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
@@ -136,13 +136,13 @@ class grpc_alts_server_security_connector final
public:
grpc_alts_server_security_connector(
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds)
- : grpc_server_security_connector(GRPC_ALTS_URL_SCHEME,
- std::move(server_creds)) {}
-
+ : grpc_server_security_connector(GRPC_ALTS_URL_SCHEME,
+ std::move(server_creds)) {}
+
~grpc_alts_server_security_connector() override = default;
void add_handshakers(
- const grpc_channel_args* args, grpc_pollset_set* interested_parties,
+ const grpc_channel_args* args, grpc_pollset_set* interested_parties,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
const grpc_alts_server_credentials* creds =
@@ -159,10 +159,10 @@ class grpc_alts_server_security_connector final
false, interested_parties, &handshaker,
user_specified_max_frame_size) == TSI_OK);
handshake_manager->Add(
- grpc_core::SecurityHandshakerCreate(handshaker, this, args));
+ grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
- void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
+ void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
alts_check_peer(peer, auth_context, on_peer_checked);
@@ -208,7 +208,7 @@ grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) {
return nullptr;
}
grpc_gcp_rpc_protocol_versions local_versions, peer_versions;
- grpc_alts_set_rpc_protocol_versions(&local_versions);
+ grpc_alts_set_rpc_protocol_versions(&local_versions);
grpc_slice slice = grpc_slice_from_copied_buffer(
rpc_versions_prop->value.data, rpc_versions_prop->value.length);
bool decode_result =
@@ -225,13 +225,13 @@ grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) {
gpr_log(GPR_ERROR, "Mismatch of local and peer rpc protocol versions.");
return nullptr;
}
- /* Validate ALTS Context. */
- const tsi_peer_property* alts_context_prop =
- tsi_peer_get_property_by_name(peer, TSI_ALTS_CONTEXT);
- if (alts_context_prop == nullptr) {
- gpr_log(GPR_ERROR, "Missing alts context property.");
- return nullptr;
- }
+ /* Validate ALTS Context. */
+ const tsi_peer_property* alts_context_prop =
+ tsi_peer_get_property_by_name(peer, TSI_ALTS_CONTEXT);
+ if (alts_context_prop == nullptr) {
+ gpr_log(GPR_ERROR, "Missing alts context property.");
+ return nullptr;
+ }
/* Create auth context. */
auto ctx = grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
grpc_auth_context_add_cstring_property(
@@ -248,12 +248,12 @@ grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) {
GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name(
ctx.get(), TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY) == 1);
}
- /* Add alts context to auth context. */
- if (strcmp(tsi_prop->name, TSI_ALTS_CONTEXT) == 0) {
- grpc_auth_context_add_property(ctx.get(), TSI_ALTS_CONTEXT,
- tsi_prop->value.data,
- tsi_prop->value.length);
- }
+ /* Add alts context to auth context. */
+ if (strcmp(tsi_prop->name, TSI_ALTS_CONTEXT) == 0) {
+ grpc_auth_context_add_property(ctx.get(), TSI_ALTS_CONTEXT,
+ tsi_prop->value.data,
+ tsi_prop->value.length);
+ }
/* Add security level to auth context. */
if (strcmp(tsi_prop->name, TSI_SECURITY_LEVEL_PEER_PROPERTY) == 0) {
grpc_auth_context_add_property(
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h
index 10c3fe9364..c7e0de2eb4 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h
@@ -25,7 +25,7 @@
#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
#define GRPC_ALTS_TRANSPORT_SECURITY_TYPE "alts"
-#define GRPC_ALTS_URL_SCHEME "https"
+#define GRPC_ALTS_URL_SCHEME "https"
/**
* This method creates an ALTS channel security connector.
@@ -58,10 +58,10 @@ grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_alts_server_security_connector_create(
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds);
-/* Initializes rpc_versions. */
-void grpc_alts_set_rpc_protocol_versions(
- grpc_gcp_rpc_protocol_versions* rpc_versions);
-
+/* Initializes rpc_versions. */
+void grpc_alts_set_rpc_protocol_versions(
+ grpc_gcp_rpc_protocol_versions* rpc_versions);
+
namespace grpc_core {
namespace internal {
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc
index efbf6d231c..52faa0c248 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc
@@ -28,13 +28,13 @@
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
#include "src/core/ext/transport/chttp2/alpn/alpn.h"
#include "src/core/ext/xds/xds_channel_args.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/handshaker.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/security/context/security_context.h"
#include "src/core/lib/security/credentials/credentials.h"
@@ -95,46 +95,46 @@ class grpc_fake_channel_security_connector final
return GPR_ICMP(is_lb_channel_, other->is_lb_channel_);
}
- void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* /*interested_parties*/,
+ void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_mgr) override {
handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(
- tsi_create_fake_handshaker(/*is_client=*/true), this, args));
+ tsi_create_fake_handshaker(/*is_client=*/true), this, args));
}
bool check_call_host(y_absl::string_view host,
- grpc_auth_context* /*auth_context*/,
- grpc_closure* /*on_call_host_checked*/,
- grpc_error** /*error*/) override {
+ grpc_auth_context* /*auth_context*/,
+ grpc_closure* /*on_call_host_checked*/,
+ grpc_error** /*error*/) override {
y_absl::string_view authority_hostname;
y_absl::string_view authority_ignored_port;
y_absl::string_view target_hostname;
y_absl::string_view target_ignored_port;
- grpc_core::SplitHostPort(host, &authority_hostname,
- &authority_ignored_port);
- grpc_core::SplitHostPort(target_, &target_hostname, &target_ignored_port);
+ grpc_core::SplitHostPort(host, &authority_hostname,
+ &authority_ignored_port);
+ grpc_core::SplitHostPort(target_, &target_hostname, &target_ignored_port);
if (target_name_override_ != nullptr) {
y_absl::string_view fake_security_target_name_override_hostname;
y_absl::string_view fake_security_target_name_override_ignored_port;
- grpc_core::SplitHostPort(
- target_name_override_, &fake_security_target_name_override_hostname,
- &fake_security_target_name_override_ignored_port);
- if (authority_hostname != fake_security_target_name_override_hostname) {
+ grpc_core::SplitHostPort(
+ target_name_override_, &fake_security_target_name_override_hostname,
+ &fake_security_target_name_override_ignored_port);
+ if (authority_hostname != fake_security_target_name_override_hostname) {
gpr_log(GPR_ERROR,
"Authority (host) '%s' != Fake Security Target override '%s'",
- host.data(),
- fake_security_target_name_override_hostname.data());
+ host.data(),
+ fake_security_target_name_override_hostname.data());
abort();
}
- } else if (authority_hostname != target_hostname) {
- gpr_log(GPR_ERROR, "Authority (host) '%s' != Target '%s'", host.data(),
- target_);
+ } else if (authority_hostname != target_hostname) {
+ gpr_log(GPR_ERROR, "Authority (host) '%s' != Target '%s'", host.data(),
+ target_);
abort();
}
return true;
}
- void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
+ void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
@@ -210,7 +210,7 @@ class grpc_fake_channel_security_connector final
};
static void fake_check_peer(
- grpc_security_connector* /*sc*/, tsi_peer peer,
+ grpc_security_connector* /*sc*/, tsi_peer peer,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) {
const char* prop_name;
@@ -260,12 +260,12 @@ static void fake_check_peer(
auth_context->get(), GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,
TSI_FAKE_SECURITY_LEVEL);
end:
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
tsi_peer_destruct(&peer);
}
void grpc_fake_channel_security_connector::check_peer(
- tsi_peer peer, grpc_endpoint* /*ep*/,
+ tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) {
fake_check_peer(this, peer, auth_context, on_peer_checked);
@@ -281,17 +281,17 @@ class grpc_fake_server_security_connector
std::move(server_creds)) {}
~grpc_fake_server_security_connector() override = default;
- void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
+ void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
fake_check_peer(this, peer, auth_context, on_peer_checked);
}
- void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* /*interested_parties*/,
+ void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_mgr) override {
handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(
- tsi_create_fake_handshaker(/*=is_client*/ false), this, args));
+ tsi_create_fake_handshaker(/*=is_client*/ false), this, args));
}
int cmp(const grpc_security_connector* other) const override {
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc
index c0b6d5d727..1b15fe325c 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc
@@ -42,12 +42,12 @@
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/load_file.h"
-GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_system_ssl_roots_dir, "",
- "Custom directory to SSL Roots");
-
+GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_system_ssl_roots_dir, "",
+ "Custom directory to SSL Roots");
+
namespace grpc_core {
namespace {
@@ -67,8 +67,8 @@ grpc_slice GetSystemRootCerts() {
grpc_load_file(kLinuxCertFiles[i], 1, &valid_bundle_slice);
if (error == GRPC_ERROR_NONE) {
return valid_bundle_slice;
- } else {
- GRPC_ERROR_UNREF(error);
+ } else {
+ GRPC_ERROR_UNREF(error);
}
}
return grpc_empty_slice();
@@ -145,10 +145,10 @@ grpc_slice CreateRootCertsBundle(const char* certs_directory) {
grpc_slice LoadSystemRootCerts() {
grpc_slice result = grpc_empty_slice();
// Prioritize user-specified custom directory if flag is set.
- grpc_core::UniquePtr<char> custom_dir =
- GPR_GLOBAL_CONFIG_GET(grpc_system_ssl_roots_dir);
- if (strlen(custom_dir.get()) > 0) {
- result = CreateRootCertsBundle(custom_dir.get());
+ grpc_core::UniquePtr<char> custom_dir =
+ GPR_GLOBAL_CONFIG_GET(grpc_system_ssl_roots_dir);
+ if (strlen(custom_dir.get()) > 0) {
+ result = CreateRootCertsBundle(custom_dir.get());
}
// If the custom directory is empty/invalid/not specified, fallback to
// distribution-specific directory.
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc
index 8f622d4c22..a90dc76a95 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc
@@ -107,7 +107,7 @@ void local_check_peer(tsi_peer peer, grpc_endpoint* ep,
if (!is_endpoint_local) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Endpoint is neither UDS or TCP loopback address.");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
return;
}
// Add TSI_SECURITY_LEVEL_PEER_PROPERTY type peer property.
@@ -137,7 +137,7 @@ void local_check_peer(tsi_peer peer, grpc_endpoint* ep,
error = *auth_context != nullptr ? GRPC_ERROR_NONE
: GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Could not create local auth context");
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
class grpc_local_channel_security_connector final
@@ -154,13 +154,13 @@ class grpc_local_channel_security_connector final
~grpc_local_channel_security_connector() override { gpr_free(target_name_); }
void add_handshakers(
- const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
+ const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
GPR_ASSERT(local_tsi_handshaker_create(true /* is_client */, &handshaker) ==
TSI_OK);
handshake_manager->Add(
- grpc_core::SecurityHandshakerCreate(handshaker, this, args));
+ grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
int cmp(const grpc_security_connector* other_sc) const override {
@@ -182,17 +182,17 @@ class grpc_local_channel_security_connector final
}
bool check_call_host(y_absl::string_view host,
- grpc_auth_context* /*auth_context*/,
- grpc_closure* /*on_call_host_checked*/,
+ grpc_auth_context* /*auth_context*/,
+ grpc_closure* /*on_call_host_checked*/,
grpc_error** error) override {
- if (host.empty() || host != target_name_) {
+ if (host.empty() || host != target_name_) {
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"local call host does not match target name");
}
return true;
}
- void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
+ void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
@@ -212,13 +212,13 @@ class grpc_local_server_security_connector final
~grpc_local_server_security_connector() override = default;
void add_handshakers(
- const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
+ const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_manager) override {
tsi_handshaker* handshaker = nullptr;
GPR_ASSERT(local_tsi_handshaker_create(false /* is_client */,
&handshaker) == TSI_OK);
handshake_manager->Add(
- grpc_core::SecurityHandshakerCreate(handshaker, this, args));
+ grpc_core::SecurityHandshakerCreate(handshaker, this, args));
}
void check_peer(tsi_peer peer, grpc_endpoint* ep,
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc
index 0400ad6fb8..4a60bcf2e0 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc
@@ -29,7 +29,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/handshaker.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/security/context/security_context.h"
#include "src/core/lib/security/credentials/credentials.h"
@@ -55,7 +55,7 @@ grpc_channel_security_connector::grpc_channel_security_connector(
: grpc_security_connector(url_scheme),
channel_creds_(std::move(channel_creds)),
request_metadata_creds_(std::move(request_metadata_creds)) {}
-
+
grpc_channel_security_connector::~grpc_channel_security_connector() {}
int grpc_security_connector_cmp(const grpc_security_connector* sc,
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h
index 74d04600b2..1a84437c1e 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h
@@ -58,10 +58,10 @@ class grpc_security_connector
virtual void check_peer(
tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
- grpc_closure* on_peer_checked) = 0;
+ grpc_closure* on_peer_checked) = 0;
/* Compares two security connectors. */
- virtual int cmp(const grpc_security_connector* other) const = 0;
+ virtual int cmp(const grpc_security_connector* other) const = 0;
const char* url_scheme() const { return url_scheme_; }
@@ -89,9 +89,9 @@ class grpc_channel_security_connector : public grpc_security_connector {
grpc_channel_security_connector(
const char* url_scheme,
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds,
- grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds
- /*,
- grpc_channel_args* channel_args = nullptr*/);
+ grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds
+ /*,
+ grpc_channel_args* channel_args = nullptr*/);
~grpc_channel_security_connector() override;
/// Checks that the host that will be set for a call is acceptable.
@@ -101,16 +101,16 @@ class grpc_channel_security_connector : public grpc_security_connector {
virtual bool check_call_host(y_absl::string_view host,
grpc_auth_context* auth_context,
grpc_closure* on_call_host_checked,
- grpc_error** error) = 0;
- /// Cancels a pending asynchronous call to
+ grpc_error** error) = 0;
+ /// Cancels a pending asynchronous call to
/// grpc_channel_security_connector_check_call_host() with
/// \a on_call_host_checked as its callback.
virtual void cancel_check_call_host(grpc_closure* on_call_host_checked,
- grpc_error* error) = 0;
+ grpc_error* error) = 0;
/// Registers handshakers with \a handshake_mgr.
- virtual void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* interested_parties,
- grpc_core::HandshakeManager* handshake_mgr) = 0;
+ virtual void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* interested_parties,
+ grpc_core::HandshakeManager* handshake_mgr) = 0;
const grpc_channel_credentials* channel_creds() const {
return channel_creds_.get();
@@ -130,15 +130,15 @@ class grpc_channel_security_connector : public grpc_security_connector {
int channel_security_connector_cmp(
const grpc_channel_security_connector* other) const;
- // grpc_channel_args* channel_args() const { return channel_args_.get(); }
- //// Should be called as soon as the channel args are not needed to reduce
- //// memory usage.
- // void clear_channel_arg() { channel_args_.reset(); }
-
+ // grpc_channel_args* channel_args() const { return channel_args_.get(); }
+ //// Should be called as soon as the channel args are not needed to reduce
+ //// memory usage.
+ // void clear_channel_arg() { channel_args_.reset(); }
+
private:
grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds_;
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds_;
- std::unique_ptr<grpc_channel_args> channel_args_;
+ std::unique_ptr<grpc_channel_args> channel_args_;
};
/* --- server_security_connector object. ---
@@ -153,9 +153,9 @@ class grpc_server_security_connector : public grpc_security_connector {
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds);
~grpc_server_security_connector() override;
- virtual void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* interested_parties,
- grpc_core::HandshakeManager* handshake_mgr) = 0;
+ virtual void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* interested_parties,
+ grpc_core::HandshakeManager* handshake_mgr) = 0;
const grpc_server_credentials* server_creds() const {
return server_creds_.get();
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc
index b5e78ddbbb..5770124bc8 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc
@@ -32,7 +32,7 @@
#include "src/core/ext/transport/chttp2/alpn/alpn.h"
#include "src/core/lib/channel/handshaker.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/security/context/security_context.h"
@@ -48,9 +48,9 @@ namespace {
grpc_error* ssl_check_peer(
const char* peer_name, const tsi_peer* peer,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context) {
- grpc_error* error = grpc_ssl_check_alpn(peer);
- if (error != GRPC_ERROR_NONE) {
- return error;
+ grpc_error* error = grpc_ssl_check_alpn(peer);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
}
/* Check the peer name if specified. */
if (peer_name != nullptr && !grpc_ssl_host_matches_name(peer, peer_name)) {
@@ -58,8 +58,8 @@ grpc_error* ssl_check_peer(
y_absl::StrCat("Peer name ", peer_name, " is not in peer certificate")
.c_str());
}
- *auth_context =
- grpc_ssl_peer_to_auth_context(peer, GRPC_SSL_TRANSPORT_SECURITY_TYPE);
+ *auth_context =
+ grpc_ssl_peer_to_auth_context(peer, GRPC_SSL_TRANSPORT_SECURITY_TYPE);
return GRPC_ERROR_NONE;
}
@@ -79,7 +79,7 @@ class grpc_ssl_channel_security_connector final
verify_options_(&config->verify_options) {
y_absl::string_view host;
y_absl::string_view port;
- grpc_core::SplitHostPort(target_name, &host, &port);
+ grpc_core::SplitHostPort(target_name, &host, &port);
target_name_ = TString(host);
}
@@ -120,8 +120,8 @@ class grpc_ssl_channel_security_connector final
return GRPC_SECURITY_OK;
}
- void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* /*interested_parties*/,
+ void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_mgr) override {
// Instantiate TSI handshaker.
tsi_handshaker* tsi_hs = nullptr;
@@ -136,10 +136,10 @@ class grpc_ssl_channel_security_connector final
return;
}
// Create handshakers.
- handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args));
+ handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args));
}
- void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
+ void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
const char* target_name = overridden_target_name_.empty()
@@ -169,7 +169,7 @@ class grpc_ssl_channel_security_connector final
}
}
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
tsi_peer_destruct(&peer);
}
@@ -184,14 +184,14 @@ class grpc_ssl_channel_security_connector final
}
bool check_call_host(y_absl::string_view host, grpc_auth_context* auth_context,
- grpc_closure* /*on_call_host_checked*/,
+ grpc_closure* /*on_call_host_checked*/,
grpc_error** error) override {
return grpc_ssl_check_call_host(host, target_name_.c_str(),
overridden_target_name_.c_str(),
auth_context, error);
}
- void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
+ void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
}
@@ -238,26 +238,26 @@ class grpc_ssl_server_security_connector
size_t num_alpn_protocols = 0;
const char** alpn_protocol_strings =
grpc_fill_alpn_protocol_strings(&num_alpn_protocols);
- tsi_ssl_server_handshaker_options options;
- options.pem_key_cert_pairs =
- server_credentials->config().pem_key_cert_pairs;
- options.num_key_cert_pairs =
- server_credentials->config().num_key_cert_pairs;
- options.pem_client_root_certs =
- server_credentials->config().pem_root_certs;
- options.client_certificate_request =
+ tsi_ssl_server_handshaker_options options;
+ options.pem_key_cert_pairs =
+ server_credentials->config().pem_key_cert_pairs;
+ options.num_key_cert_pairs =
+ server_credentials->config().num_key_cert_pairs;
+ options.pem_client_root_certs =
+ server_credentials->config().pem_root_certs;
+ options.client_certificate_request =
grpc_get_tsi_client_certificate_request_type(
- server_credentials->config().client_certificate_request);
- options.cipher_suites = grpc_get_ssl_cipher_suites();
- options.alpn_protocols = alpn_protocol_strings;
- options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
+ server_credentials->config().client_certificate_request);
+ options.cipher_suites = grpc_get_ssl_cipher_suites();
+ options.alpn_protocols = alpn_protocol_strings;
+ options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
options.min_tls_version = grpc_get_tsi_tls_version(
server_credentials->config().min_tls_version);
options.max_tls_version = grpc_get_tsi_tls_version(
server_credentials->config().max_tls_version);
- const tsi_result result =
- tsi_create_ssl_server_handshaker_factory_with_options(
- &options, &server_handshaker_factory_);
+ const tsi_result result =
+ tsi_create_ssl_server_handshaker_factory_with_options(
+ &options, &server_handshaker_factory_);
gpr_free((void*)alpn_protocol_strings);
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
@@ -268,8 +268,8 @@ class grpc_ssl_server_security_connector
return GRPC_SECURITY_OK;
}
- void add_handshakers(const grpc_channel_args* args,
- grpc_pollset_set* /*interested_parties*/,
+ void add_handshakers(const grpc_channel_args* args,
+ grpc_pollset_set* /*interested_parties*/,
grpc_core::HandshakeManager* handshake_mgr) override {
// Instantiate TSI handshaker.
try_fetch_ssl_server_credentials();
@@ -282,15 +282,15 @@ class grpc_ssl_server_security_connector
return;
}
// Create handshakers.
- handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args));
+ handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args));
}
- void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
+ void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) override {
grpc_error* error = ssl_check_peer(nullptr, &peer, auth_context);
tsi_peer_destruct(&peer);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
}
int cmp(const grpc_security_connector* other) const override {
@@ -301,7 +301,7 @@ class grpc_ssl_server_security_connector
private:
/* Attempts to fetch the server certificate config if a callback is available.
* Current certificate config will continue to be used if the callback returns
- * an error. Returns true if new credentials were successfully loaded. */
+ * an error. Returns true if new credentials were successfully loaded. */
bool try_fetch_ssl_server_credentials() {
grpc_ssl_server_certificate_config* certificate_config = nullptr;
bool status;
@@ -352,22 +352,22 @@ class grpc_ssl_server_security_connector
const grpc_ssl_server_credentials* server_creds =
static_cast<const grpc_ssl_server_credentials*>(this->server_creds());
GPR_DEBUG_ASSERT(config->pem_root_certs != nullptr);
- tsi_ssl_server_handshaker_options options;
- options.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs(
- config->pem_key_cert_pairs, config->num_key_cert_pairs);
- options.num_key_cert_pairs = config->num_key_cert_pairs;
- options.pem_client_root_certs = config->pem_root_certs;
- options.client_certificate_request =
+ tsi_ssl_server_handshaker_options options;
+ options.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs(
+ config->pem_key_cert_pairs, config->num_key_cert_pairs);
+ options.num_key_cert_pairs = config->num_key_cert_pairs;
+ options.pem_client_root_certs = config->pem_root_certs;
+ options.client_certificate_request =
grpc_get_tsi_client_certificate_request_type(
- server_creds->config().client_certificate_request);
- options.cipher_suites = grpc_get_ssl_cipher_suites();
- options.alpn_protocols = alpn_protocol_strings;
- options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
- tsi_result result = tsi_create_ssl_server_handshaker_factory_with_options(
- &options, &new_handshaker_factory);
- grpc_tsi_ssl_pem_key_cert_pairs_destroy(
- const_cast<tsi_ssl_pem_key_cert_pair*>(options.pem_key_cert_pairs),
- options.num_key_cert_pairs);
+ server_creds->config().client_certificate_request);
+ options.cipher_suites = grpc_get_ssl_cipher_suites();
+ options.alpn_protocols = alpn_protocol_strings;
+ options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
+ tsi_result result = tsi_create_ssl_server_handshaker_factory_with_options(
+ &options, &new_handshaker_factory);
+ grpc_tsi_ssl_pem_key_cert_pairs_destroy(
+ const_cast<tsi_ssl_pem_key_cert_pair*>(options.pem_key_cert_pairs),
+ options.num_key_cert_pairs);
gpr_free((void*)alpn_protocol_strings);
if (result != TSI_OK) {
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc
index 6c83968f8e..aed3610aa2 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc
@@ -31,12 +31,12 @@
#include "src/core/ext/transport/chttp2/alpn/alpn.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/host_port.h"
+#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/security/context/security_context.h"
#include "src/core/lib/security/security_connector/load_system_roots.h"
-#include "src/core/lib/security/security_connector/ssl_utils_config.h"
+#include "src/core/lib/security/security_connector/ssl_utils_config.h"
#include "src/core/tsi/ssl_transport_security.h"
#include "load_arcadia_root_certs.h"
@@ -67,22 +67,22 @@ void grpc_set_ssl_roots_override_callback(grpc_ssl_roots_override_callback cb) {
static gpr_once cipher_suites_once = GPR_ONCE_INIT;
static const char* cipher_suites = nullptr;
-// All cipher suites for default are compliant with HTTP2.
-GPR_GLOBAL_CONFIG_DEFINE_STRING(
- grpc_ssl_cipher_suites,
+// All cipher suites for default are compliant with HTTP2.
+GPR_GLOBAL_CONFIG_DEFINE_STRING(
+ grpc_ssl_cipher_suites,
"TLS_AES_128_GCM_SHA256:"
"TLS_AES_256_GCM_SHA384:"
"TLS_CHACHA20_POLY1305_SHA256:"
- "ECDHE-ECDSA-AES128-GCM-SHA256:"
- "ECDHE-ECDSA-AES256-GCM-SHA384:"
- "ECDHE-RSA-AES128-GCM-SHA256:"
- "ECDHE-RSA-AES256-GCM-SHA384",
- "A colon separated list of cipher suites to use with OpenSSL")
-
+ "ECDHE-ECDSA-AES128-GCM-SHA256:"
+ "ECDHE-ECDSA-AES256-GCM-SHA384:"
+ "ECDHE-RSA-AES128-GCM-SHA256:"
+ "ECDHE-RSA-AES256-GCM-SHA384",
+ "A colon separated list of cipher suites to use with OpenSSL")
+
static void init_cipher_suites(void) {
- grpc_core::UniquePtr<char> value =
- GPR_GLOBAL_CONFIG_GET(grpc_ssl_cipher_suites);
- cipher_suites = value.release();
+ grpc_core::UniquePtr<char> value =
+ GPR_GLOBAL_CONFIG_GET(grpc_ssl_cipher_suites);
+ cipher_suites = value.release();
}
/* --- Util --- */
@@ -152,56 +152,56 @@ tsi_tls_version grpc_get_tsi_tls_version(grpc_tls_version tls_version) {
}
}
-grpc_error* grpc_ssl_check_alpn(const tsi_peer* peer) {
-#if TSI_OPENSSL_ALPN_SUPPORT
- /* Check the ALPN if ALPN is supported. */
- const tsi_peer_property* p =
- tsi_peer_get_property_by_name(peer, TSI_SSL_ALPN_SELECTED_PROTOCOL);
- if (p == nullptr) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Cannot check peer: missing selected ALPN property.");
- }
- if (!grpc_chttp2_is_alpn_version_supported(p->value.data, p->value.length)) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Cannot check peer: invalid ALPN value.");
- }
-#endif /* TSI_OPENSSL_ALPN_SUPPORT */
- return GRPC_ERROR_NONE;
-}
-
+grpc_error* grpc_ssl_check_alpn(const tsi_peer* peer) {
+#if TSI_OPENSSL_ALPN_SUPPORT
+ /* Check the ALPN if ALPN is supported. */
+ const tsi_peer_property* p =
+ tsi_peer_get_property_by_name(peer, TSI_SSL_ALPN_SELECTED_PROTOCOL);
+ if (p == nullptr) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Cannot check peer: missing selected ALPN property.");
+ }
+ if (!grpc_chttp2_is_alpn_version_supported(p->value.data, p->value.length)) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Cannot check peer: invalid ALPN value.");
+ }
+#endif /* TSI_OPENSSL_ALPN_SUPPORT */
+ return GRPC_ERROR_NONE;
+}
+
grpc_error* grpc_ssl_check_peer_name(y_absl::string_view peer_name,
- const tsi_peer* peer) {
- /* Check the peer name if specified. */
- if (!peer_name.empty() && !grpc_ssl_host_matches_name(peer, peer_name)) {
+ const tsi_peer* peer) {
+ /* Check the peer name if specified. */
+ if (!peer_name.empty() && !grpc_ssl_host_matches_name(peer, peer_name)) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Peer name ", peer_name, " is not in peer certificate")
.c_str());
- }
- return GRPC_ERROR_NONE;
-}
-
+ }
+ return GRPC_ERROR_NONE;
+}
+
bool grpc_ssl_check_call_host(y_absl::string_view host,
y_absl::string_view target_name,
y_absl::string_view overridden_target_name,
- grpc_auth_context* auth_context,
- grpc_error** error) {
- grpc_security_status status = GRPC_SECURITY_ERROR;
- tsi_peer peer = grpc_shallow_peer_from_ssl_auth_context(auth_context);
- if (grpc_ssl_host_matches_name(&peer, host)) status = GRPC_SECURITY_OK;
+ grpc_auth_context* auth_context,
+ grpc_error** error) {
+ grpc_security_status status = GRPC_SECURITY_ERROR;
+ tsi_peer peer = grpc_shallow_peer_from_ssl_auth_context(auth_context);
+ if (grpc_ssl_host_matches_name(&peer, host)) status = GRPC_SECURITY_OK;
/* If the target name was overridden, then the original target_name was
'checked' transitively during the previous peer check at the end of the
handshake. */
- if (!overridden_target_name.empty() && host == target_name) {
- status = GRPC_SECURITY_OK;
- }
- if (status != GRPC_SECURITY_OK) {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "call host does not match SSL server name");
- }
- grpc_shallow_peer_destruct(&peer);
- return true;
-}
-
+ if (!overridden_target_name.empty() && host == target_name) {
+ status = GRPC_SECURITY_OK;
+ }
+ if (status != GRPC_SECURITY_OK) {
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "call host does not match SSL server name");
+ }
+ grpc_shallow_peer_destruct(&peer);
+ return true;
+}
+
const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols) {
GPR_ASSERT(num_alpn_protocols != nullptr);
*num_alpn_protocols = grpc_chttp2_num_alpn_versions();
@@ -213,27 +213,27 @@ const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols) {
return alpn_protocol_strings;
}
-int grpc_ssl_host_matches_name(const tsi_peer* peer,
+int grpc_ssl_host_matches_name(const tsi_peer* peer,
y_absl::string_view peer_name) {
y_absl::string_view allocated_name;
y_absl::string_view ignored_port;
- grpc_core::SplitHostPort(peer_name, &allocated_name, &ignored_port);
- if (allocated_name.empty()) return 0;
+ grpc_core::SplitHostPort(peer_name, &allocated_name, &ignored_port);
+ if (allocated_name.empty()) return 0;
// IPv6 zone-id should not be included in comparisons.
- const size_t zone_id = allocated_name.find('%');
+ const size_t zone_id = allocated_name.find('%');
if (zone_id != y_absl::string_view::npos) {
- allocated_name.remove_suffix(allocated_name.size() - zone_id);
- }
- return tsi_ssl_peer_matches_name(peer, allocated_name);
-}
+ allocated_name.remove_suffix(allocated_name.size() - zone_id);
+ }
+ return tsi_ssl_peer_matches_name(peer, allocated_name);
+}
int grpc_ssl_cmp_target_name(y_absl::string_view target_name,
y_absl::string_view other_target_name,
y_absl::string_view overridden_target_name,
y_absl::string_view other_overridden_target_name) {
int c = target_name.compare(other_target_name);
- if (c != 0) return c;
+ if (c != 0) return c;
return overridden_target_name.compare(other_overridden_target_name);
}
@@ -259,7 +259,7 @@ static bool IsSpiffeId(y_absl::string_view uri) {
}
grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context(
- const tsi_peer* peer, const char* transport_security_type) {
+ const tsi_peer* peer, const char* transport_security_type) {
size_t i;
const char* peer_identity_property_name = nullptr;
@@ -269,7 +269,7 @@ grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context(
grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
grpc_auth_context_add_cstring_property(
ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,
- transport_security_type);
+ transport_security_type);
const char* spiffe_data = nullptr;
size_t spiffe_length = 0;
int uri_count = 0;
@@ -389,87 +389,87 @@ void grpc_shallow_peer_destruct(tsi_peer* peer) {
if (peer->properties != nullptr) gpr_free(peer->properties);
}
-grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init(
- tsi_ssl_pem_key_cert_pair* pem_key_cert_pair, const char* pem_root_certs,
+grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init(
+ tsi_ssl_pem_key_cert_pair* pem_key_cert_pair, const char* pem_root_certs,
bool skip_server_certificate_verification, tsi_tls_version min_tls_version,
tsi_tls_version max_tls_version, tsi_ssl_session_cache* ssl_session_cache,
- tsi_ssl_client_handshaker_factory** handshaker_factory) {
- const char* root_certs;
- const tsi_ssl_root_certs_store* root_store;
- if (pem_root_certs == nullptr) {
- // Use default root certificates.
- root_certs = grpc_core::DefaultSslRootStore::GetPemRootCerts();
- if (root_certs == nullptr) {
- gpr_log(GPR_ERROR, "Could not get default pem root certs.");
- return GRPC_SECURITY_ERROR;
- }
- root_store = grpc_core::DefaultSslRootStore::GetRootStore();
- } else {
- root_certs = pem_root_certs;
- root_store = nullptr;
- }
- bool has_key_cert_pair = pem_key_cert_pair != nullptr &&
- pem_key_cert_pair->private_key != nullptr &&
- pem_key_cert_pair->cert_chain != nullptr;
- tsi_ssl_client_handshaker_options options;
- GPR_DEBUG_ASSERT(root_certs != nullptr);
- options.pem_root_certs = root_certs;
- options.root_store = root_store;
- options.alpn_protocols =
- grpc_fill_alpn_protocol_strings(&options.num_alpn_protocols);
- if (has_key_cert_pair) {
- options.pem_key_cert_pair = pem_key_cert_pair;
- }
- options.cipher_suites = grpc_get_ssl_cipher_suites();
- options.session_cache = ssl_session_cache;
+ tsi_ssl_client_handshaker_factory** handshaker_factory) {
+ const char* root_certs;
+ const tsi_ssl_root_certs_store* root_store;
+ if (pem_root_certs == nullptr) {
+ // Use default root certificates.
+ root_certs = grpc_core::DefaultSslRootStore::GetPemRootCerts();
+ if (root_certs == nullptr) {
+ gpr_log(GPR_ERROR, "Could not get default pem root certs.");
+ return GRPC_SECURITY_ERROR;
+ }
+ root_store = grpc_core::DefaultSslRootStore::GetRootStore();
+ } else {
+ root_certs = pem_root_certs;
+ root_store = nullptr;
+ }
+ bool has_key_cert_pair = pem_key_cert_pair != nullptr &&
+ pem_key_cert_pair->private_key != nullptr &&
+ pem_key_cert_pair->cert_chain != nullptr;
+ tsi_ssl_client_handshaker_options options;
+ GPR_DEBUG_ASSERT(root_certs != nullptr);
+ options.pem_root_certs = root_certs;
+ options.root_store = root_store;
+ options.alpn_protocols =
+ grpc_fill_alpn_protocol_strings(&options.num_alpn_protocols);
+ if (has_key_cert_pair) {
+ options.pem_key_cert_pair = pem_key_cert_pair;
+ }
+ options.cipher_suites = grpc_get_ssl_cipher_suites();
+ options.session_cache = ssl_session_cache;
options.skip_server_certificate_verification =
skip_server_certificate_verification;
options.min_tls_version = min_tls_version;
options.max_tls_version = max_tls_version;
- const tsi_result result =
- tsi_create_ssl_client_handshaker_factory_with_options(&options,
- handshaker_factory);
- gpr_free((void*)options.alpn_protocols);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
- tsi_result_to_string(result));
- return GRPC_SECURITY_ERROR;
- }
- return GRPC_SECURITY_OK;
-}
-
-grpc_security_status grpc_ssl_tsi_server_handshaker_factory_init(
- tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs,
- const char* pem_root_certs,
- grpc_ssl_client_certificate_request_type client_certificate_request,
+ const tsi_result result =
+ tsi_create_ssl_client_handshaker_factory_with_options(&options,
+ handshaker_factory);
+ gpr_free((void*)options.alpn_protocols);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
+ tsi_result_to_string(result));
+ return GRPC_SECURITY_ERROR;
+ }
+ return GRPC_SECURITY_OK;
+}
+
+grpc_security_status grpc_ssl_tsi_server_handshaker_factory_init(
+ tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs,
+ const char* pem_root_certs,
+ grpc_ssl_client_certificate_request_type client_certificate_request,
tsi_tls_version min_tls_version, tsi_tls_version max_tls_version,
- tsi_ssl_server_handshaker_factory** handshaker_factory) {
- size_t num_alpn_protocols = 0;
- const char** alpn_protocol_strings =
- grpc_fill_alpn_protocol_strings(&num_alpn_protocols);
- tsi_ssl_server_handshaker_options options;
- options.pem_key_cert_pairs = pem_key_cert_pairs;
- options.num_key_cert_pairs = num_key_cert_pairs;
- options.pem_client_root_certs = pem_root_certs;
- options.client_certificate_request =
- grpc_get_tsi_client_certificate_request_type(client_certificate_request);
- options.cipher_suites = grpc_get_ssl_cipher_suites();
- options.alpn_protocols = alpn_protocol_strings;
- options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
+ tsi_ssl_server_handshaker_factory** handshaker_factory) {
+ size_t num_alpn_protocols = 0;
+ const char** alpn_protocol_strings =
+ grpc_fill_alpn_protocol_strings(&num_alpn_protocols);
+ tsi_ssl_server_handshaker_options options;
+ options.pem_key_cert_pairs = pem_key_cert_pairs;
+ options.num_key_cert_pairs = num_key_cert_pairs;
+ options.pem_client_root_certs = pem_root_certs;
+ options.client_certificate_request =
+ grpc_get_tsi_client_certificate_request_type(client_certificate_request);
+ options.cipher_suites = grpc_get_ssl_cipher_suites();
+ options.alpn_protocols = alpn_protocol_strings;
+ options.num_alpn_protocols = static_cast<uint16_t>(num_alpn_protocols);
options.min_tls_version = min_tls_version;
options.max_tls_version = max_tls_version;
- const tsi_result result =
- tsi_create_ssl_server_handshaker_factory_with_options(&options,
- handshaker_factory);
- gpr_free((void*)alpn_protocol_strings);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
- tsi_result_to_string(result));
- return GRPC_SECURITY_ERROR;
- }
- return GRPC_SECURITY_OK;
-}
-
+ const tsi_result result =
+ tsi_create_ssl_server_handshaker_factory_with_options(&options,
+ handshaker_factory);
+ gpr_free((void*)alpn_protocol_strings);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
+ tsi_result_to_string(result));
+ return GRPC_SECURITY_ERROR;
+ }
+ return GRPC_SECURITY_OK;
+}
+
/* --- Ssl cache implementation. --- */
grpc_ssl_session_cache* grpc_ssl_session_cache_create_lru(size_t capacity) {
@@ -534,14 +534,14 @@ const char* DefaultSslRootStore::GetPemRootCerts() {
grpc_slice DefaultSslRootStore::ComputePemRootCerts() {
grpc_slice result = grpc_empty_slice();
- const bool not_use_system_roots =
- GPR_GLOBAL_CONFIG_GET(grpc_not_use_system_ssl_roots);
- // First try to load the roots from the configuration.
- grpc_core::UniquePtr<char> default_root_certs_path =
- GPR_GLOBAL_CONFIG_GET(grpc_default_ssl_roots_file_path);
- if (strlen(default_root_certs_path.get()) > 0) {
- GRPC_LOG_IF_ERROR(
- "load_file", grpc_load_file(default_root_certs_path.get(), 1, &result));
+ const bool not_use_system_roots =
+ GPR_GLOBAL_CONFIG_GET(grpc_not_use_system_ssl_roots);
+ // First try to load the roots from the configuration.
+ grpc_core::UniquePtr<char> default_root_certs_path =
+ GPR_GLOBAL_CONFIG_GET(grpc_default_ssl_roots_file_path);
+ if (strlen(default_root_certs_path.get()) > 0) {
+ GRPC_LOG_IF_ERROR(
+ "load_file", grpc_load_file(default_root_certs_path.get(), 1, &result));
}
// Try overridden roots if needed.
grpc_ssl_roots_override_result ovrd_res = GRPC_SSL_ROOTS_OVERRIDE_FAIL;
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h
index 6141f8d9cb..200fd88ce8 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h
@@ -29,37 +29,37 @@
#include <grpc/grpc_security.h>
#include <grpc/slice_buffer.h>
-#include "src/core/lib/gprpp/global_config.h"
+#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/security/security_connector/security_connector.h"
-#include "src/core/lib/security/security_connector/ssl_utils_config.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/security/security_connector/security_connector.h"
+#include "src/core/lib/security/security_connector/ssl_utils_config.h"
#include "src/core/tsi/ssl_transport_security.h"
-#include "src/core/tsi/transport_security.h"
+#include "src/core/tsi/transport_security.h"
#include "src/core/tsi/transport_security_interface.h"
-/* --- Util --- */
+/* --- Util --- */
/* --- URL schemes. --- */
#define GRPC_SSL_URL_SCHEME "https"
-/* Check ALPN information returned from SSL handshakes. */
-grpc_error* grpc_ssl_check_alpn(const tsi_peer* peer);
-
-/* Check peer name information returned from SSL handshakes. */
+/* Check ALPN information returned from SSL handshakes. */
+grpc_error* grpc_ssl_check_alpn(const tsi_peer* peer);
+
+/* Check peer name information returned from SSL handshakes. */
grpc_error* grpc_ssl_check_peer_name(y_absl::string_view peer_name,
- const tsi_peer* peer);
-/* Compare targer_name information extracted from SSL security connectors. */
+ const tsi_peer* peer);
+/* Compare targer_name information extracted from SSL security connectors. */
int grpc_ssl_cmp_target_name(y_absl::string_view target_name,
y_absl::string_view other_target_name,
y_absl::string_view overridden_target_name,
y_absl::string_view other_overridden_target_name);
-/* Check the host that will be set for a call is acceptable.*/
+/* Check the host that will be set for a call is acceptable.*/
bool grpc_ssl_check_call_host(y_absl::string_view host,
y_absl::string_view target_name,
y_absl::string_view overridden_target_name,
- grpc_auth_context* auth_context,
- grpc_error** error);
+ grpc_auth_context* auth_context,
+ grpc_error** error);
/* Return HTTP2-compliant cipher suites that gRPC accepts by default. */
const char* grpc_get_ssl_cipher_suites(void);
@@ -86,27 +86,27 @@ bool grpc_check_security_level(grpc_security_level channel_level,
/* Return an array of strings containing alpn protocols. */
const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols);
-/* Initialize TSI SSL server/client handshaker factory. */
-grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init(
- tsi_ssl_pem_key_cert_pair* key_cert_pair, const char* pem_root_certs,
+/* Initialize TSI SSL server/client handshaker factory. */
+grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init(
+ tsi_ssl_pem_key_cert_pair* key_cert_pair, const char* pem_root_certs,
bool skip_server_certificate_verification, tsi_tls_version min_tls_version,
tsi_tls_version max_tls_version, tsi_ssl_session_cache* ssl_session_cache,
- tsi_ssl_client_handshaker_factory** handshaker_factory);
-
-grpc_security_status grpc_ssl_tsi_server_handshaker_factory_init(
- tsi_ssl_pem_key_cert_pair* key_cert_pairs, size_t num_key_cert_pairs,
- const char* pem_root_certs,
- grpc_ssl_client_certificate_request_type client_certificate_request,
+ tsi_ssl_client_handshaker_factory** handshaker_factory);
+
+grpc_security_status grpc_ssl_tsi_server_handshaker_factory_init(
+ tsi_ssl_pem_key_cert_pair* key_cert_pairs, size_t num_key_cert_pairs,
+ const char* pem_root_certs,
+ grpc_ssl_client_certificate_request_type client_certificate_request,
tsi_tls_version min_tls_version, tsi_tls_version max_tls_version,
- tsi_ssl_server_handshaker_factory** handshaker_factory);
-
+ tsi_ssl_server_handshaker_factory** handshaker_factory);
+
/* Exposed for testing only. */
grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context(
- const tsi_peer* peer, const char* transport_security_type);
+ const tsi_peer* peer, const char* transport_security_type);
tsi_peer grpc_shallow_peer_from_ssl_auth_context(
const grpc_auth_context* auth_context);
void grpc_shallow_peer_destruct(tsi_peer* peer);
-int grpc_ssl_host_matches_name(const tsi_peer* peer,
+int grpc_ssl_host_matches_name(const tsi_peer* peer,
y_absl::string_view peer_name);
/* --- Default SSL Root Store. --- */
@@ -164,15 +164,15 @@ class PemKeyCertPair {
return *this;
}
- // Copyable.
- PemKeyCertPair(const PemKeyCertPair& other)
- : private_key_(gpr_strdup(other.private_key())),
- cert_chain_(gpr_strdup(other.cert_chain())) {}
- PemKeyCertPair& operator=(const PemKeyCertPair& other) {
- private_key_ = grpc_core::UniquePtr<char>(gpr_strdup(other.private_key()));
- cert_chain_ = grpc_core::UniquePtr<char>(gpr_strdup(other.cert_chain()));
- return *this;
- }
+ // Copyable.
+ PemKeyCertPair(const PemKeyCertPair& other)
+ : private_key_(gpr_strdup(other.private_key())),
+ cert_chain_(gpr_strdup(other.cert_chain())) {}
+ PemKeyCertPair& operator=(const PemKeyCertPair& other) {
+ private_key_ = grpc_core::UniquePtr<char>(gpr_strdup(other.private_key()));
+ cert_chain_ = grpc_core::UniquePtr<char>(gpr_strdup(other.cert_chain()));
+ return *this;
+ }
bool operator==(const PemKeyCertPair& other) const {
return std::strcmp(this->private_key(), other.private_key()) == 0 &&
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.cc
index 2d056a781f..de0a8042c0 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.cc
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.cc
@@ -1,32 +1,32 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/security_connector/ssl_utils_config.h"
-
-/** Config variable that points to the default SSL roots file. This file
- must be a PEM encoded file with all the roots such as the one that can be
- downloaded from https://pki.google.com/roots.pem. */
-GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_default_ssl_roots_file_path, "",
- "Path to the default SSL roots file.");
-
-/** Config variable used as a flag to enable/disable loading system root
- certificates from the OS trust store. */
-GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_not_use_system_ssl_roots, false,
- "Disable loading system root certificates.");
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/security/security_connector/ssl_utils_config.h"
+
+/** Config variable that points to the default SSL roots file. This file
+ must be a PEM encoded file with all the roots such as the one that can be
+ downloaded from https://pki.google.com/roots.pem. */
+GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_default_ssl_roots_file_path, "",
+ "Path to the default SSL roots file.");
+
+/** Config variable used as a flag to enable/disable loading system root
+ certificates from the OS trust store. */
+GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_not_use_system_ssl_roots, false,
+ "Disable loading system root certificates.");
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.h b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.h
index efaf497ab1..af0ed3b1f2 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.h
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils_config.h
@@ -1,30 +1,30 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_CONFIG_H
-#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_CONFIG_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gprpp/global_config.h"
-
-GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_default_ssl_roots_file_path);
-GPR_GLOBAL_CONFIG_DECLARE_BOOL(grpc_not_use_system_ssl_roots);
-
-#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_CONFIG_H \
- */
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_CONFIG_H
+#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_CONFIG_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gprpp/global_config.h"
+
+GPR_GLOBAL_CONFIG_DECLARE_STRING(grpc_default_ssl_roots_file_path);
+GPR_GLOBAL_CONFIG_DECLARE_BOOL(grpc_not_use_system_ssl_roots);
+
+#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_CONFIG_H \
+ */
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/auth_filters.h b/contrib/libs/grpc/src/core/lib/security/transport/auth_filters.h
index ae31b1d578..0fdc858985 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/auth_filters.h
+++ b/contrib/libs/grpc/src/core/lib/security/transport/auth_filters.h
@@ -28,8 +28,8 @@ extern const grpc_channel_filter grpc_client_auth_filter;
extern const grpc_channel_filter grpc_server_auth_filter;
void grpc_auth_metadata_context_build(
- const char* url_scheme, const grpc_slice& call_host,
- const grpc_slice& call_method, grpc_auth_context* auth_context,
+ const char* url_scheme, const grpc_slice& call_host,
+ const grpc_slice& call_method, grpc_auth_context* auth_context,
grpc_auth_metadata_context* auth_md_context);
#endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_AUTH_FILTERS_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc b/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc
index b1a9d3f938..0cccdf9039 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc
+++ b/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc
@@ -45,42 +45,42 @@
#define MAX_CREDENTIALS_METADATA_COUNT 4
namespace {
-
-/* We can have a per-channel credentials. */
-struct channel_data {
- channel_data(grpc_channel_security_connector* security_connector,
- grpc_auth_context* auth_context)
- : security_connector(
- security_connector->Ref(DEBUG_LOCATION, "client_auth_filter")),
- auth_context(auth_context->Ref(DEBUG_LOCATION, "client_auth_filter")) {}
- ~channel_data() {
- security_connector.reset(DEBUG_LOCATION, "client_auth_filter");
- auth_context.reset(DEBUG_LOCATION, "client_auth_filter");
- }
-
- grpc_core::RefCountedPtr<grpc_channel_security_connector> security_connector;
- grpc_core::RefCountedPtr<grpc_auth_context> auth_context;
-};
-
+
+/* We can have a per-channel credentials. */
+struct channel_data {
+ channel_data(grpc_channel_security_connector* security_connector,
+ grpc_auth_context* auth_context)
+ : security_connector(
+ security_connector->Ref(DEBUG_LOCATION, "client_auth_filter")),
+ auth_context(auth_context->Ref(DEBUG_LOCATION, "client_auth_filter")) {}
+ ~channel_data() {
+ security_connector.reset(DEBUG_LOCATION, "client_auth_filter");
+ auth_context.reset(DEBUG_LOCATION, "client_auth_filter");
+ }
+
+ grpc_core::RefCountedPtr<grpc_channel_security_connector> security_connector;
+ grpc_core::RefCountedPtr<grpc_auth_context> auth_context;
+};
+
/* We can have a per-call credentials. */
struct call_data {
call_data(grpc_call_element* elem, const grpc_call_element_args& args)
- : owning_call(args.call_stack), call_combiner(args.call_combiner) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- GPR_ASSERT(args.context != nullptr);
- if (args.context[GRPC_CONTEXT_SECURITY].value == nullptr) {
- args.context[GRPC_CONTEXT_SECURITY].value =
- grpc_client_security_context_create(args.arena, /*creds=*/nullptr);
- args.context[GRPC_CONTEXT_SECURITY].destroy =
- grpc_client_security_context_destroy;
- }
- grpc_client_security_context* sec_ctx =
- static_cast<grpc_client_security_context*>(
- args.context[GRPC_CONTEXT_SECURITY].value);
- sec_ctx->auth_context.reset(DEBUG_LOCATION, "client_auth_filter");
- sec_ctx->auth_context =
- chand->auth_context->Ref(DEBUG_LOCATION, "client_auth_filter");
- }
+ : owning_call(args.call_stack), call_combiner(args.call_combiner) {
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ GPR_ASSERT(args.context != nullptr);
+ if (args.context[GRPC_CONTEXT_SECURITY].value == nullptr) {
+ args.context[GRPC_CONTEXT_SECURITY].value =
+ grpc_client_security_context_create(args.arena, /*creds=*/nullptr);
+ args.context[GRPC_CONTEXT_SECURITY].destroy =
+ grpc_client_security_context_destroy;
+ }
+ grpc_client_security_context* sec_ctx =
+ static_cast<grpc_client_security_context*>(
+ args.context[GRPC_CONTEXT_SECURITY].value);
+ sec_ctx->auth_context.reset(DEBUG_LOCATION, "client_auth_filter");
+ sec_ctx->auth_context =
+ chand->auth_context->Ref(DEBUG_LOCATION, "client_auth_filter");
+ }
// This method is technically the dtor of this class. However, since
// `get_request_metadata_cancel_closure` can run in parallel to
@@ -96,7 +96,7 @@ struct call_data {
}
grpc_call_stack* owning_call;
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
grpc_core::RefCountedPtr<grpc_call_credentials> creds;
grpc_slice host = grpc_empty_slice();
grpc_slice method = grpc_empty_slice();
@@ -114,20 +114,20 @@ struct call_data {
grpc_closure get_request_metadata_cancel_closure;
};
-} // namespace
-
-void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from,
- grpc_auth_metadata_context* to) {
- grpc_auth_metadata_context_reset(to);
- to->channel_auth_context = from->channel_auth_context;
- if (to->channel_auth_context != nullptr) {
- const_cast<grpc_auth_context*>(to->channel_auth_context)
- ->Ref(DEBUG_LOCATION, "grpc_auth_metadata_context_copy")
- .release();
+} // namespace
+
+void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from,
+ grpc_auth_metadata_context* to) {
+ grpc_auth_metadata_context_reset(to);
+ to->channel_auth_context = from->channel_auth_context;
+ if (to->channel_auth_context != nullptr) {
+ const_cast<grpc_auth_context*>(to->channel_auth_context)
+ ->Ref(DEBUG_LOCATION, "grpc_auth_metadata_context_copy")
+ .release();
}
- to->service_url = gpr_strdup(from->service_url);
- to->method_name = gpr_strdup(from->method_name);
-}
+ to->service_url = gpr_strdup(from->service_url);
+ to->method_name = gpr_strdup(from->method_name);
+}
void grpc_auth_metadata_context_reset(
grpc_auth_metadata_context* auth_md_context) {
@@ -186,8 +186,8 @@ static void on_credentials_metadata(void* arg, grpc_error* input_error) {
}
void grpc_auth_metadata_context_build(
- const char* url_scheme, const grpc_slice& call_host,
- const grpc_slice& call_method, grpc_auth_context* auth_context,
+ const char* url_scheme, const grpc_slice& call_host,
+ const grpc_slice& call_method, grpc_auth_context* auth_context,
grpc_auth_metadata_context* auth_md_context) {
char* service = grpc_slice_to_c_string(call_method);
char* last_slash = strrchr(service, '/');
@@ -320,9 +320,9 @@ static void send_security_metadata(grpc_call_element* elem,
GRPC_ERROR_UNREF(error);
} else {
// Async return; register cancellation closure with call combiner.
- calld->call_combiner->SetNotifyOnCancel(GRPC_CLOSURE_INIT(
- &calld->get_request_metadata_cancel_closure,
- cancel_get_request_metadata, elem, grpc_schedule_on_exec_ctx));
+ calld->call_combiner->SetNotifyOnCancel(GRPC_CLOSURE_INIT(
+ &calld->get_request_metadata_cancel_closure,
+ cancel_get_request_metadata, elem, grpc_schedule_on_exec_ctx));
}
}
@@ -358,7 +358,7 @@ static void cancel_check_call_host(void* arg, grpc_error* error) {
}
}
-static void client_auth_start_transport_stream_op_batch(
+static void client_auth_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
GPR_TIMER_SCOPE("auth_start_transport_stream_op_batch", 0);
@@ -390,9 +390,9 @@ static void client_auth_start_transport_stream_op_batch(
GRPC_ERROR_UNREF(error);
} else {
// Async return; register cancellation closure with call combiner.
- calld->call_combiner->SetNotifyOnCancel(GRPC_CLOSURE_INIT(
- &calld->check_call_host_cancel_closure, cancel_check_call_host,
- elem, grpc_schedule_on_exec_ctx));
+ calld->call_combiner->SetNotifyOnCancel(GRPC_CLOSURE_INIT(
+ &calld->check_call_host_cancel_closure, cancel_check_call_host,
+ elem, grpc_schedule_on_exec_ctx));
}
return; /* early exit */
}
@@ -403,29 +403,29 @@ static void client_auth_start_transport_stream_op_batch(
}
/* Constructor for call_data */
-static grpc_error* client_auth_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* args) {
+static grpc_error* client_auth_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* args) {
new (elem->call_data) call_data(elem, *args);
return GRPC_ERROR_NONE;
}
-static void client_auth_set_pollset_or_pollset_set(
- grpc_call_element* elem, grpc_polling_entity* pollent) {
+static void client_auth_set_pollset_or_pollset_set(
+ grpc_call_element* elem, grpc_polling_entity* pollent) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->pollent = pollent;
}
/* Destructor for call_data */
-static void client_auth_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void client_auth_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->destroy();
}
/* Constructor for channel_data */
-static grpc_error* client_auth_init_channel_elem(
- grpc_channel_element* elem, grpc_channel_element_args* args) {
+static grpc_error* client_auth_init_channel_elem(
+ grpc_channel_element* elem, grpc_channel_element_args* args) {
/* The first and the last filters tend to be implemented differently to
handle the case that there's no 'next' filter to call on the up or down
path */
@@ -448,20 +448,20 @@ static grpc_error* client_auth_init_channel_elem(
}
/* Destructor for channel data */
-static void client_auth_destroy_channel_elem(grpc_channel_element* elem) {
+static void client_auth_destroy_channel_elem(grpc_channel_element* elem) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
chand->~channel_data();
}
const grpc_channel_filter grpc_client_auth_filter = {
- client_auth_start_transport_stream_op_batch,
+ client_auth_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- client_auth_init_call_elem,
- client_auth_set_pollset_or_pollset_set,
- client_auth_destroy_call_elem,
+ client_auth_init_call_elem,
+ client_auth_set_pollset_or_pollset_set,
+ client_auth_destroy_call_elem,
sizeof(channel_data),
- client_auth_init_channel_elem,
- client_auth_destroy_channel_elem,
+ client_auth_init_channel_elem,
+ client_auth_destroy_channel_elem,
grpc_channel_next_get_info,
"client-auth"};
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc b/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc
index e79184fac1..cf96fea82a 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc
+++ b/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc
@@ -104,7 +104,7 @@ struct secure_endpoint {
grpc_core::TraceFlag grpc_trace_secure_endpoint(false, "secure_endpoint");
-static void destroy(secure_endpoint* ep) { delete ep; }
+static void destroy(secure_endpoint* ep) { delete ep; }
#ifndef NDEBUG
#define SECURE_ENDPOINT_UNREF(ep, reason) \
@@ -113,7 +113,7 @@ static void destroy(secure_endpoint* ep) { delete ep; }
secure_endpoint_ref((ep), (reason), __FILE__, __LINE__)
static void secure_endpoint_unref(secure_endpoint* ep, const char* reason,
const char* file, int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
gpr_atm val = gpr_atm_no_barrier_load(&ep->ref.count);
gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
"SECENDP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, reason, val,
@@ -126,7 +126,7 @@ static void secure_endpoint_unref(secure_endpoint* ep, const char* reason,
static void secure_endpoint_ref(secure_endpoint* ep, const char* reason,
const char* file, int line) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
gpr_atm val = gpr_atm_no_barrier_load(&ep->ref.count);
gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
"SECENDP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, reason, val,
@@ -155,7 +155,7 @@ static void flush_read_staging_buffer(secure_endpoint* ep, uint8_t** cur,
}
static void call_read_cb(secure_endpoint* ep, grpc_error* error) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
size_t i;
for (i = 0; i < ep->read_buffer->count; i++) {
char* data = grpc_dump_slice(ep->read_buffer->slices[i],
@@ -165,7 +165,7 @@ static void call_read_cb(secure_endpoint* ep, grpc_error* error) {
}
}
ep->read_buffer = nullptr;
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, ep->read_cb, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, ep->read_cb, error);
SECURE_ENDPOINT_UNREF(ep, "read");
}
@@ -255,7 +255,7 @@ static void on_read(void* user_data, grpc_error* error) {
}
static void endpoint_read(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool urgent) {
+ grpc_closure* cb, bool urgent) {
secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
ep->read_cb = cb;
ep->read_buffer = slices;
@@ -269,7 +269,7 @@ static void endpoint_read(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
return;
}
- grpc_endpoint_read(ep->wrapped_ep, &ep->source_buffer, &ep->on_read, urgent);
+ grpc_endpoint_read(ep->wrapped_ep, &ep->source_buffer, &ep->on_read, urgent);
}
static void flush_write_staging_buffer(secure_endpoint* ep, uint8_t** cur,
@@ -292,7 +292,7 @@ static void endpoint_write(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
grpc_slice_buffer_reset_and_unref_internal(&ep->output_buffer);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_secure_endpoint)) {
for (i = 0; i < slices->count; i++) {
char* data =
grpc_dump_slice(slices->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII);
@@ -363,10 +363,10 @@ static void endpoint_write(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
if (result != TSI_OK) {
/* TODO(yangg) do different things according to the error type? */
grpc_slice_buffer_reset_and_unref_internal(&ep->output_buffer);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, cb,
- grpc_set_tsi_error_result(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Wrap failed"), result));
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, cb,
+ grpc_set_tsi_error_result(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Wrap failed"), result));
return;
}
@@ -445,8 +445,8 @@ grpc_endpoint* grpc_secure_endpoint_create(
struct tsi_zero_copy_grpc_protector* zero_copy_protector,
grpc_endpoint* transport, grpc_slice* leftover_slices,
size_t leftover_nslices) {
- secure_endpoint* ep =
- new secure_endpoint(&vtable, protector, zero_copy_protector, transport,
- leftover_slices, leftover_nslices);
+ secure_endpoint* ep =
+ new secure_endpoint(&vtable, protector, zero_copy_protector, transport,
+ leftover_slices, leftover_nslices);
return &ep->base;
}
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc
index 079b49c95a..62fb687948 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc
+++ b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc
@@ -22,7 +22,7 @@
#include <stdbool.h>
#include <string.h>
-#include <limits>
+#include <limits>
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
@@ -47,8 +47,8 @@ namespace {
class SecurityHandshaker : public Handshaker {
public:
SecurityHandshaker(tsi_handshaker* handshaker,
- grpc_security_connector* connector,
- const grpc_channel_args* args);
+ grpc_security_connector* connector,
+ const grpc_channel_args* args);
~SecurityHandshaker() override;
void Shutdown(grpc_error* why) override;
void DoHandshake(grpc_tcp_server_acceptor* acceptor,
@@ -68,10 +68,10 @@ class SecurityHandshaker : public Handshaker {
static void OnHandshakeDataReceivedFromPeerFn(void* arg, grpc_error* error);
static void OnHandshakeDataSentToPeerFn(void* arg, grpc_error* error);
- static void OnHandshakeDataReceivedFromPeerFnScheduler(void* arg,
- grpc_error* error);
- static void OnHandshakeDataSentToPeerFnScheduler(void* arg,
- grpc_error* error);
+ static void OnHandshakeDataReceivedFromPeerFnScheduler(void* arg,
+ grpc_error* error);
+ static void OnHandshakeDataSentToPeerFnScheduler(void* arg,
+ grpc_error* error);
static void OnHandshakeNextDoneGrpcWrapper(
tsi_result result, void* user_data, const unsigned char* bytes_to_send,
size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result);
@@ -103,23 +103,23 @@ class SecurityHandshaker : public Handshaker {
grpc_closure on_peer_checked_;
RefCountedPtr<grpc_auth_context> auth_context_;
tsi_handshaker_result* handshaker_result_ = nullptr;
- size_t max_frame_size_ = 0;
+ size_t max_frame_size_ = 0;
};
SecurityHandshaker::SecurityHandshaker(tsi_handshaker* handshaker,
- grpc_security_connector* connector,
- const grpc_channel_args* args)
+ grpc_security_connector* connector,
+ const grpc_channel_args* args)
: handshaker_(handshaker),
connector_(connector->Ref(DEBUG_LOCATION, "handshake")),
handshake_buffer_size_(GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE),
handshake_buffer_(
static_cast<uint8_t*>(gpr_malloc(handshake_buffer_size_))) {
- const grpc_arg* arg =
- grpc_channel_args_find(args, GRPC_ARG_TSI_MAX_FRAME_SIZE);
- if (arg != nullptr && arg->type == GRPC_ARG_INTEGER) {
- max_frame_size_ = grpc_channel_arg_get_integer(
- arg, {0, 0, std::numeric_limits<int>::max()});
- }
+ const grpc_arg* arg =
+ grpc_channel_args_find(args, GRPC_ARG_TSI_MAX_FRAME_SIZE);
+ if (arg != nullptr && arg->type == GRPC_ARG_INTEGER) {
+ max_frame_size_ = grpc_channel_arg_get_integer(
+ arg, {0, 0, std::numeric_limits<int>::max()});
+ }
gpr_mu_init(&mu_);
grpc_slice_buffer_init(&outgoing_);
GRPC_CLOSURE_INIT(&on_peer_checked_, &SecurityHandshaker::OnPeerCheckedFn,
@@ -152,11 +152,11 @@ size_t SecurityHandshaker::MoveReadBufferIntoHandshakeBuffer() {
}
size_t offset = 0;
while (args_->read_buffer->count > 0) {
- grpc_slice* next_slice = grpc_slice_buffer_peek_first(args_->read_buffer);
- memcpy(handshake_buffer_ + offset, GRPC_SLICE_START_PTR(*next_slice),
- GRPC_SLICE_LENGTH(*next_slice));
- offset += GRPC_SLICE_LENGTH(*next_slice);
- grpc_slice_buffer_remove_first(args_->read_buffer);
+ grpc_slice* next_slice = grpc_slice_buffer_peek_first(args_->read_buffer);
+ memcpy(handshake_buffer_ + offset, GRPC_SLICE_START_PTR(*next_slice),
+ GRPC_SLICE_LENGTH(*next_slice));
+ offset += GRPC_SLICE_LENGTH(*next_slice);
+ grpc_slice_buffer_remove_first(args_->read_buffer);
}
return bytes_in_read_buffer;
}
@@ -184,7 +184,7 @@ void SecurityHandshaker::HandshakeFailedLocked(grpc_error* error) {
gpr_log(GPR_DEBUG, "Security handshake failed: %s", msg);
if (!is_shutdown_) {
- tsi_handshaker_shutdown(handshaker_);
+ tsi_handshaker_shutdown(handshaker_);
// TODO(ctiller): It is currently necessary to shutdown endpoints
// before destroying them, even if we know that there are no
// pending read/write callbacks. This should be fixed, at which
@@ -198,20 +198,20 @@ void SecurityHandshaker::HandshakeFailedLocked(grpc_error* error) {
is_shutdown_ = true;
}
// Invoke callback.
- ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, error);
+ ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, error);
}
void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) {
MutexLock lock(&mu_);
if (error != GRPC_ERROR_NONE || is_shutdown_) {
- HandshakeFailedLocked(error);
+ HandshakeFailedLocked(error);
return;
}
// Create zero-copy frame protector, if implemented.
tsi_zero_copy_grpc_protector* zero_copy_protector = nullptr;
tsi_result result = tsi_handshaker_result_create_zero_copy_grpc_protector(
- handshaker_result_, max_frame_size_ == 0 ? nullptr : &max_frame_size_,
- &zero_copy_protector);
+ handshaker_result_, max_frame_size_ == 0 ? nullptr : &max_frame_size_,
+ &zero_copy_protector);
if (result != TSI_OK && result != TSI_UNIMPLEMENTED) {
error = grpc_set_tsi_error_result(
GRPC_ERROR_CREATE_FROM_STATIC_STRING(
@@ -223,9 +223,9 @@ void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) {
// Create frame protector if zero-copy frame protector is NULL.
tsi_frame_protector* protector = nullptr;
if (zero_copy_protector == nullptr) {
- result = tsi_handshaker_result_create_frame_protector(
- handshaker_result_, max_frame_size_ == 0 ? nullptr : &max_frame_size_,
- &protector);
+ result = tsi_handshaker_result_create_frame_protector(
+ handshaker_result_, max_frame_size_ == 0 ? nullptr : &max_frame_size_,
+ &protector);
if (result != TSI_OK) {
error = grpc_set_tsi_error_result(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Frame protector creation failed"),
@@ -258,7 +258,7 @@ void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) {
args_->args = grpc_channel_args_copy_and_add(tmp_args, &auth_context_arg, 1);
grpc_channel_args_destroy(tmp_args);
// Invoke callback.
- ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, GRPC_ERROR_NONE);
// Set shutdown to true so that subsequent calls to
// security_handshaker_shutdown() do nothing.
is_shutdown_ = true;
@@ -266,7 +266,7 @@ void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) {
void SecurityHandshaker::OnPeerCheckedFn(void* arg, grpc_error* error) {
RefCountedPtr<SecurityHandshaker>(static_cast<SecurityHandshaker*>(arg))
- ->OnPeerCheckedInner(GRPC_ERROR_REF(error));
+ ->OnPeerCheckedInner(GRPC_ERROR_REF(error));
}
grpc_error* SecurityHandshaker::CheckPeerLocked() {
@@ -293,13 +293,13 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked(
// Read more if we need to.
if (result == TSI_INCOMPLETE_DATA) {
GPR_ASSERT(bytes_to_send_size == 0);
- grpc_endpoint_read(
- args_->endpoint, args_->read_buffer,
- GRPC_CLOSURE_INIT(
- &on_handshake_data_received_from_peer_,
- &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
- this, grpc_schedule_on_exec_ctx),
- /*urgent=*/true);
+ grpc_endpoint_read(
+ args_->endpoint, args_->read_buffer,
+ GRPC_CLOSURE_INIT(
+ &on_handshake_data_received_from_peer_,
+ &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
+ this, grpc_schedule_on_exec_ctx),
+ /*urgent=*/true);
return error;
}
if (result != TSI_OK) {
@@ -317,22 +317,22 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked(
reinterpret_cast<const char*>(bytes_to_send), bytes_to_send_size);
grpc_slice_buffer_reset_and_unref_internal(&outgoing_);
grpc_slice_buffer_add(&outgoing_, to_send);
- grpc_endpoint_write(
- args_->endpoint, &outgoing_,
- GRPC_CLOSURE_INIT(
- &on_handshake_data_sent_to_peer_,
- &SecurityHandshaker::OnHandshakeDataSentToPeerFnScheduler, this,
- grpc_schedule_on_exec_ctx),
- nullptr);
+ grpc_endpoint_write(
+ args_->endpoint, &outgoing_,
+ GRPC_CLOSURE_INIT(
+ &on_handshake_data_sent_to_peer_,
+ &SecurityHandshaker::OnHandshakeDataSentToPeerFnScheduler, this,
+ grpc_schedule_on_exec_ctx),
+ nullptr);
} else if (handshaker_result == nullptr) {
// There is nothing to send, but need to read from peer.
- grpc_endpoint_read(
- args_->endpoint, args_->read_buffer,
- GRPC_CLOSURE_INIT(
- &on_handshake_data_received_from_peer_,
- &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
- this, grpc_schedule_on_exec_ctx),
- /*urgent=*/true);
+ grpc_endpoint_read(
+ args_->endpoint, args_->read_buffer,
+ GRPC_CLOSURE_INIT(
+ &on_handshake_data_received_from_peer_,
+ &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
+ this, grpc_schedule_on_exec_ctx),
+ /*urgent=*/true);
} else {
// Handshake has finished, check peer and so on.
error = CheckPeerLocked();
@@ -375,19 +375,19 @@ grpc_error* SecurityHandshaker::DoHandshakerNextLocked(
hs_result);
}
-// This callback might be run inline while we are still holding on to the mutex,
-// so schedule OnHandshakeDataReceivedFromPeerFn on ExecCtx to avoid a deadlock.
-void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler(
- void* arg, grpc_error* error) {
- SecurityHandshaker* h = static_cast<SecurityHandshaker*>(arg);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- GRPC_CLOSURE_INIT(&h->on_handshake_data_received_from_peer_,
- &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn,
- h, grpc_schedule_on_exec_ctx),
- GRPC_ERROR_REF(error));
-}
-
+// This callback might be run inline while we are still holding on to the mutex,
+// so schedule OnHandshakeDataReceivedFromPeerFn on ExecCtx to avoid a deadlock.
+void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler(
+ void* arg, grpc_error* error) {
+ SecurityHandshaker* h = static_cast<SecurityHandshaker*>(arg);
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ GRPC_CLOSURE_INIT(&h->on_handshake_data_received_from_peer_,
+ &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn,
+ h, grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_REF(error));
+}
+
void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn(void* arg,
grpc_error* error) {
RefCountedPtr<SecurityHandshaker> h(static_cast<SecurityHandshaker*>(arg));
@@ -409,19 +409,19 @@ void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn(void* arg,
}
}
-// This callback might be run inline while we are still holding on to the mutex,
-// so schedule OnHandshakeDataSentToPeerFn on ExecCtx to avoid a deadlock.
-void SecurityHandshaker::OnHandshakeDataSentToPeerFnScheduler(
- void* arg, grpc_error* error) {
- SecurityHandshaker* h = static_cast<SecurityHandshaker*>(arg);
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION,
- GRPC_CLOSURE_INIT(&h->on_handshake_data_sent_to_peer_,
- &SecurityHandshaker::OnHandshakeDataSentToPeerFn, h,
- grpc_schedule_on_exec_ctx),
- GRPC_ERROR_REF(error));
-}
-
+// This callback might be run inline while we are still holding on to the mutex,
+// so schedule OnHandshakeDataSentToPeerFn on ExecCtx to avoid a deadlock.
+void SecurityHandshaker::OnHandshakeDataSentToPeerFnScheduler(
+ void* arg, grpc_error* error) {
+ SecurityHandshaker* h = static_cast<SecurityHandshaker*>(arg);
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION,
+ GRPC_CLOSURE_INIT(&h->on_handshake_data_sent_to_peer_,
+ &SecurityHandshaker::OnHandshakeDataSentToPeerFn, h,
+ grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_REF(error));
+}
+
void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg,
grpc_error* error) {
RefCountedPtr<SecurityHandshaker> h(static_cast<SecurityHandshaker*>(arg));
@@ -433,13 +433,13 @@ void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg,
}
// We may be done.
if (h->handshaker_result_ == nullptr) {
- grpc_endpoint_read(
- h->args_->endpoint, h->args_->read_buffer,
- GRPC_CLOSURE_INIT(
- &h->on_handshake_data_received_from_peer_,
- &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
- h.get(), grpc_schedule_on_exec_ctx),
- /*urgent=*/true);
+ grpc_endpoint_read(
+ h->args_->endpoint, h->args_->read_buffer,
+ GRPC_CLOSURE_INIT(
+ &h->on_handshake_data_received_from_peer_,
+ &SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
+ h.get(), grpc_schedule_on_exec_ctx),
+ /*urgent=*/true);
} else {
error = h->CheckPeerLocked();
if (error != GRPC_ERROR_NONE) {
@@ -465,7 +465,7 @@ void SecurityHandshaker::Shutdown(grpc_error* why) {
GRPC_ERROR_UNREF(why);
}
-void SecurityHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
+void SecurityHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
grpc_closure* on_handshake_done,
HandshakerArgs* args) {
auto ref = Ref();
@@ -490,12 +490,12 @@ class FailHandshaker : public Handshaker {
public:
const char* name() const override { return "security_fail"; }
void Shutdown(grpc_error* why) override { GRPC_ERROR_UNREF(why); }
- void DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
+ void DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
grpc_closure* on_handshake_done,
- HandshakerArgs* /*args*/) override {
- ExecCtx::Run(DEBUG_LOCATION, on_handshake_done,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Failed to create security handshaker"));
+ HandshakerArgs* /*args*/) override {
+ ExecCtx::Run(DEBUG_LOCATION, on_handshake_done,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Failed to create security handshaker"));
}
private:
@@ -515,8 +515,8 @@ class ClientSecurityHandshakerFactory : public HandshakerFactory {
reinterpret_cast<grpc_channel_security_connector*>(
grpc_security_connector_find_in_args(args));
if (security_connector) {
- security_connector->add_handshakers(args, interested_parties,
- handshake_mgr);
+ security_connector->add_handshakers(args, interested_parties,
+ handshake_mgr);
}
}
~ClientSecurityHandshakerFactory() override = default;
@@ -531,8 +531,8 @@ class ServerSecurityHandshakerFactory : public HandshakerFactory {
reinterpret_cast<grpc_server_security_connector*>(
grpc_security_connector_find_in_args(args));
if (security_connector) {
- security_connector->add_handshakers(args, interested_parties,
- handshake_mgr);
+ security_connector->add_handshakers(args, interested_parties,
+ handshake_mgr);
}
}
~ServerSecurityHandshakerFactory() override = default;
@@ -545,14 +545,14 @@ class ServerSecurityHandshakerFactory : public HandshakerFactory {
//
RefCountedPtr<Handshaker> SecurityHandshakerCreate(
- tsi_handshaker* handshaker, grpc_security_connector* connector,
- const grpc_channel_args* args) {
+ tsi_handshaker* handshaker, grpc_security_connector* connector,
+ const grpc_channel_args* args) {
// If no TSI handshaker was created, return a handshaker that always fails.
// Otherwise, return a real security handshaker.
if (handshaker == nullptr) {
return MakeRefCounted<FailHandshaker>();
} else {
- return MakeRefCounted<SecurityHandshaker>(handshaker, connector, args);
+ return MakeRefCounted<SecurityHandshaker>(handshaker, connector, args);
}
}
@@ -568,7 +568,7 @@ void SecurityRegisterHandshakerFactories() {
} // namespace grpc_core
grpc_handshaker* grpc_security_handshaker_create(
- tsi_handshaker* handshaker, grpc_security_connector* connector,
- const grpc_channel_args* args) {
- return SecurityHandshakerCreate(handshaker, connector, args).release();
+ tsi_handshaker* handshaker, grpc_security_connector* connector,
+ const grpc_channel_args* args) {
+ return SecurityHandshakerCreate(handshaker, connector, args).release();
}
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h
index a9e1fe83d4..c3c2b63063 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h
+++ b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h
@@ -28,8 +28,8 @@ namespace grpc_core {
/// Creates a security handshaker using \a handshaker.
RefCountedPtr<Handshaker> SecurityHandshakerCreate(
- tsi_handshaker* handshaker, grpc_security_connector* connector,
- const grpc_channel_args* args);
+ tsi_handshaker* handshaker, grpc_security_connector* connector,
+ const grpc_channel_args* args);
/// Registers security handshaker factories.
void SecurityRegisterHandshakerFactories();
@@ -39,7 +39,7 @@ void SecurityRegisterHandshakerFactories();
// TODO(arjunroy): This is transitional to account for the new handshaker API
// and will eventually be removed entirely.
grpc_handshaker* grpc_security_handshaker_create(
- tsi_handshaker* handshaker, grpc_security_connector* connector,
- const grpc_channel_args* args);
+ tsi_handshaker* handshaker, grpc_security_connector* connector,
+ const grpc_channel_args* args);
#endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURITY_HANDSHAKER_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc b/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc
index 6f83a179b4..1eab17a2fd 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc
+++ b/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc
@@ -74,7 +74,7 @@ struct call_data {
~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); }
- grpc_core::CallCombiner* call_combiner;
+ grpc_core::CallCombiner* call_combiner;
grpc_call_stack* owning_call;
grpc_transport_stream_op_batch* recv_initial_metadata_batch;
grpc_closure* original_recv_initial_metadata_ready;
@@ -159,7 +159,7 @@ static void on_md_processing_done_inner(grpc_call_element* elem,
calld->recv_trailing_metadata_error,
"continue recv_trailing_metadata_ready");
}
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
}
// Called from application code.
@@ -219,7 +219,7 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
// to drop the call combiner early if we get cancelled.
GRPC_CLOSURE_INIT(&calld->cancel_closure, cancel_call, elem,
grpc_schedule_on_exec_ctx);
- calld->call_combiner->SetNotifyOnCancel(&calld->cancel_closure);
+ calld->call_combiner->SetNotifyOnCancel(&calld->cancel_closure);
GRPC_CALL_STACK_REF(calld->owning_call, "server_auth_metadata");
calld->md = metadata_batch_to_md_array(
batch->payload->recv_initial_metadata.recv_initial_metadata);
@@ -238,7 +238,7 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
calld->recv_trailing_metadata_error,
"continue recv_trailing_metadata_ready");
}
- grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error));
}
static void recv_trailing_metadata_ready(void* user_data, grpc_error* err) {
@@ -254,11 +254,11 @@ static void recv_trailing_metadata_ready(void* user_data, grpc_error* err) {
}
err = grpc_error_add_child(
GRPC_ERROR_REF(err), GRPC_ERROR_REF(calld->recv_initial_metadata_error));
- grpc_core::Closure::Run(DEBUG_LOCATION,
- calld->original_recv_trailing_metadata_ready, err);
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ calld->original_recv_trailing_metadata_ready, err);
}
-static void server_auth_start_transport_stream_op_batch(
+static void server_auth_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
call_data* calld = static_cast<call_data*>(elem->call_data);
if (batch->recv_initial_metadata) {
@@ -279,23 +279,23 @@ static void server_auth_start_transport_stream_op_batch(
}
/* Constructor for call_data */
-static grpc_error* server_auth_init_call_elem(
- grpc_call_element* elem, const grpc_call_element_args* args) {
+static grpc_error* server_auth_init_call_elem(
+ grpc_call_element* elem, const grpc_call_element_args* args) {
new (elem->call_data) call_data(elem, *args);
return GRPC_ERROR_NONE;
}
/* Destructor for call_data */
-static void server_auth_destroy_call_elem(
- grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*ignored*/) {
+static void server_auth_destroy_call_elem(
+ grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*ignored*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
}
/* Constructor for channel_data */
-static grpc_error* server_auth_init_channel_elem(
- grpc_channel_element* elem, grpc_channel_element_args* args) {
+static grpc_error* server_auth_init_channel_elem(
+ grpc_channel_element* elem, grpc_channel_element_args* args) {
GPR_ASSERT(!args->is_last);
grpc_auth_context* auth_context =
grpc_find_auth_context_in_args(args->channel_args);
@@ -307,20 +307,20 @@ static grpc_error* server_auth_init_channel_elem(
}
/* Destructor for channel data */
-static void server_auth_destroy_channel_elem(grpc_channel_element* elem) {
+static void server_auth_destroy_channel_elem(grpc_channel_element* elem) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
chand->~channel_data();
}
const grpc_channel_filter grpc_server_auth_filter = {
- server_auth_start_transport_stream_op_batch,
+ server_auth_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
- server_auth_init_call_elem,
+ server_auth_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- server_auth_destroy_call_elem,
+ server_auth_destroy_call_elem,
sizeof(channel_data),
- server_auth_init_channel_elem,
- server_auth_destroy_channel_elem,
+ server_auth_init_channel_elem,
+ server_auth_destroy_channel_elem,
grpc_channel_next_get_info,
"server-auth"};
diff --git a/contrib/libs/grpc/src/core/lib/security/util/json_util.cc b/contrib/libs/grpc/src/core/lib/security/util/json_util.cc
index 70ed064841..d7ca4b56c8 100644
--- a/contrib/libs/grpc/src/core/lib/security/util/json_util.cc
+++ b/contrib/libs/grpc/src/core/lib/security/util/json_util.cc
@@ -29,8 +29,8 @@
#include "src/core/lib/security/util/json_util.h"
const char* grpc_json_get_string_property(const grpc_core::Json& json,
- const char* prop_name,
- grpc_error** error) {
+ const char* prop_name,
+ grpc_error** error) {
if (json.type() != grpc_core::Json::Type::OBJECT) {
if (error != nullptr) {
*error =
@@ -40,11 +40,11 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
}
auto it = json.object_value().find(prop_name);
if (it == json.object_value().end()) {
- if (error != nullptr) {
+ if (error != nullptr) {
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Property ", prop_name, " not found in JSON object.")
.c_str());
- }
+ }
return nullptr;
}
if (it->second.type() != grpc_core::Json::Type::STRING) {
@@ -62,10 +62,10 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
bool grpc_copy_json_string_property(const grpc_core::Json& json,
const char* prop_name,
char** copied_value) {
- grpc_error* error = GRPC_ERROR_NONE;
- const char* prop_value =
- grpc_json_get_string_property(json, prop_name, &error);
- GRPC_LOG_IF_ERROR("Could not copy JSON property", error);
+ grpc_error* error = GRPC_ERROR_NONE;
+ const char* prop_value =
+ grpc_json_get_string_property(json, prop_name, &error);
+ GRPC_LOG_IF_ERROR("Could not copy JSON property", error);
if (prop_value == nullptr) return false;
*copied_value = gpr_strdup(prop_value);
return true;
diff --git a/contrib/libs/grpc/src/core/lib/security/util/json_util.h b/contrib/libs/grpc/src/core/lib/security/util/json_util.h
index 42f7005e00..2d2d0d0649 100644
--- a/contrib/libs/grpc/src/core/lib/security/util/json_util.h
+++ b/contrib/libs/grpc/src/core/lib/security/util/json_util.h
@@ -23,7 +23,7 @@
#include <stdbool.h>
-#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/json/json.h"
// Constants.
@@ -33,8 +33,8 @@
// Gets a child property from a json node.
const char* grpc_json_get_string_property(const grpc_core::Json& json,
- const char* prop_name,
- grpc_error** error);
+ const char* prop_name,
+ grpc_error** error);
// Copies the value of the json child property specified by prop_name.
// Returns false if the property was not found.
diff --git a/contrib/libs/grpc/src/core/lib/slice/b64.cc b/contrib/libs/grpc/src/core/lib/slice/b64.cc
index 0a06a05c93..7034d1ddd8 100644
--- a/contrib/libs/grpc/src/core/lib/slice/b64.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/b64.cc
@@ -59,13 +59,13 @@ static const char base64_url_safe_chars[] =
char* grpc_base64_encode(const void* vdata, size_t data_size, int url_safe,
int multiline) {
size_t result_projected_size =
- grpc_base64_estimate_encoded_size(data_size, multiline);
+ grpc_base64_estimate_encoded_size(data_size, multiline);
char* result = static_cast<char*>(gpr_malloc(result_projected_size));
grpc_base64_encode_core(result, vdata, data_size, url_safe, multiline);
return result;
}
-size_t grpc_base64_estimate_encoded_size(size_t data_size, int multiline) {
+size_t grpc_base64_estimate_encoded_size(size_t data_size, int multiline) {
size_t result_projected_size =
4 * ((data_size + 3) / 3) +
2 * (multiline ? (data_size / (3 * GRPC_BASE64_MULTILINE_NUM_BLOCKS))
@@ -80,7 +80,7 @@ void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size,
const char* base64_chars =
url_safe ? base64_url_safe_chars : base64_url_unsafe_chars;
const size_t result_projected_size =
- grpc_base64_estimate_encoded_size(data_size, multiline);
+ grpc_base64_estimate_encoded_size(data_size, multiline);
char* current = result;
size_t num_blocks = 0;
diff --git a/contrib/libs/grpc/src/core/lib/slice/b64.h b/contrib/libs/grpc/src/core/lib/slice/b64.h
index 65ba6622b2..782e892aea 100644
--- a/contrib/libs/grpc/src/core/lib/slice/b64.h
+++ b/contrib/libs/grpc/src/core/lib/slice/b64.h
@@ -23,7 +23,7 @@
#include <grpc/slice.h>
-/* Encodes data using base64. It is the caller's responsibility to free
+/* Encodes data using base64. It is the caller's responsibility to free
the returned char * using gpr_free. Returns NULL on NULL input.
TODO(makdharma) : change the flags to bool from int */
char* grpc_base64_encode(const void* data, size_t data_size, int url_safe,
@@ -31,10 +31,10 @@ char* grpc_base64_encode(const void* data, size_t data_size, int url_safe,
/* estimate the upper bound on size of base64 encoded data. The actual size
* is guaranteed to be less than or equal to the size returned here. */
-size_t grpc_base64_estimate_encoded_size(size_t data_size, int multiline);
+size_t grpc_base64_estimate_encoded_size(size_t data_size, int multiline);
/* Encodes data using base64 and write it to memory pointed to by result. It is
- * the caller's responsibility to allocate enough memory in |result| to fit the
+ * the caller's responsibility to allocate enough memory in |result| to fit the
* encoded data. */
void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size,
int url_safe, int multiline);
diff --git a/contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc b/contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc
index 79a4805bc9..841f0e0b4b 100644
--- a/contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc
@@ -38,7 +38,7 @@ static bool is_unreserved_character(uint8_t c,
return ((unreserved_bytes[c / 8] >> (c % 8)) & 1) != 0;
}
-grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
+grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
const uint8_t* unreserved_bytes) {
static const uint8_t hex[] = "0123456789ABCDEF";
@@ -86,7 +86,7 @@ static uint8_t dehex(uint8_t c) {
GPR_UNREACHABLE_CODE(return 255);
}
-bool grpc_strict_percent_decode_slice(const grpc_slice& slice_in,
+bool grpc_strict_percent_decode_slice(const grpc_slice& slice_in,
const uint8_t* unreserved_bytes,
grpc_slice* slice_out) {
const uint8_t* p = GRPC_SLICE_START_PTR(slice_in);
@@ -126,7 +126,7 @@ bool grpc_strict_percent_decode_slice(const grpc_slice& slice_in,
return true;
}
-grpc_slice grpc_permissive_percent_decode_slice(const grpc_slice& slice_in) {
+grpc_slice grpc_permissive_percent_decode_slice(const grpc_slice& slice_in) {
const uint8_t* p = GRPC_SLICE_START_PTR(slice_in);
const uint8_t* in_end = GRPC_SLICE_END_PTR(slice_in);
size_t out_length = 0;
diff --git a/contrib/libs/grpc/src/core/lib/slice/percent_encoding.h b/contrib/libs/grpc/src/core/lib/slice/percent_encoding.h
index 43b20f090f..2f5169ffd5 100644
--- a/contrib/libs/grpc/src/core/lib/slice/percent_encoding.h
+++ b/contrib/libs/grpc/src/core/lib/slice/percent_encoding.h
@@ -46,7 +46,7 @@ extern const uint8_t grpc_compatible_percent_encoding_unreserved_bytes[256 / 8];
/* Percent-encode a slice, returning the new slice (this cannot fail):
unreserved_bytes is a bitfield indicating which bytes are considered
unreserved and thus do not need percent encoding */
-grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
+grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
const uint8_t* unreserved_bytes);
/* Percent-decode a slice, strictly.
If the input is legal (contains no unreserved bytes, and legal % encodings),
@@ -54,12 +54,12 @@ grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
If the input is not legal, returns false and leaves *slice_out untouched.
unreserved_bytes is a bitfield indicating which bytes are considered
unreserved and thus do not need percent encoding */
-bool grpc_strict_percent_decode_slice(const grpc_slice& slice_in,
+bool grpc_strict_percent_decode_slice(const grpc_slice& slice_in,
const uint8_t* unreserved_bytes,
grpc_slice* slice_out);
/* Percent-decode a slice, permissively.
If a % triplet can not be decoded, pass it through verbatim.
This cannot fail. */
-grpc_slice grpc_permissive_percent_decode_slice(const grpc_slice& slice_in);
+grpc_slice grpc_permissive_percent_decode_slice(const grpc_slice& slice_in);
#endif /* GRPC_CORE_LIB_SLICE_PERCENT_ENCODING_H */
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice.cc b/contrib/libs/grpc/src/core/lib/slice/slice.cc
index 838cf4ba49..88ef8afca9 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice.cc
@@ -26,8 +26,8 @@
#include <string.h>
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/iomgr/exec_ctx.h"
char* grpc_slice_to_c_string(grpc_slice slice) {
@@ -37,7 +37,7 @@ char* grpc_slice_to_c_string(grpc_slice slice) {
return out;
}
-grpc_slice grpc_empty_slice(void) { return grpc_core::UnmanagedMemorySlice(); }
+grpc_slice grpc_empty_slice(void) { return grpc_core::UnmanagedMemorySlice(); }
grpc_slice grpc_slice_copy(grpc_slice s) {
grpc_slice out = GRPC_SLICE_MALLOC(GRPC_SLICE_LENGTH(s));
@@ -61,40 +61,40 @@ void grpc_slice_unref(grpc_slice slice) {
}
}
-namespace grpc_core {
-
+namespace grpc_core {
+
/* grpc_slice_from_static_string support structure - a refcount that does
nothing */
-grpc_slice_refcount kNoopRefcount(grpc_slice_refcount::Type::NOP);
-static_assert(std::is_trivially_destructible<decltype(kNoopRefcount)>::value,
- "kNoopRefcount must be trivially destructible.");
-
-/* grpc_slice_new support structures - we create a refcount object extended
- with the user provided data pointer & destroy function */
-class NewSliceRefcount {
- public:
- static void Destroy(void* arg) { delete static_cast<NewSliceRefcount*>(arg); }
-
- NewSliceRefcount(void (*destroy)(void*), void* user_data)
- : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
- &base_),
- user_destroy_(destroy),
- user_data_(user_data) {}
- ~NewSliceRefcount() { user_destroy_(user_data_); }
-
- grpc_slice_refcount* base_refcount() { return &base_; }
-
- private:
- grpc_slice_refcount base_;
- RefCount refs_;
- void (*user_destroy_)(void*);
- void* user_data_;
-};
-
-} // namespace grpc_core
-
+grpc_slice_refcount kNoopRefcount(grpc_slice_refcount::Type::NOP);
+static_assert(std::is_trivially_destructible<decltype(kNoopRefcount)>::value,
+ "kNoopRefcount must be trivially destructible.");
+
+/* grpc_slice_new support structures - we create a refcount object extended
+ with the user provided data pointer & destroy function */
+class NewSliceRefcount {
+ public:
+ static void Destroy(void* arg) { delete static_cast<NewSliceRefcount*>(arg); }
+
+ NewSliceRefcount(void (*destroy)(void*), void* user_data)
+ : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
+ &base_),
+ user_destroy_(destroy),
+ user_data_(user_data) {}
+ ~NewSliceRefcount() { user_destroy_(user_data_); }
+
+ grpc_slice_refcount* base_refcount() { return &base_; }
+
+ private:
+ grpc_slice_refcount base_;
+ RefCount refs_;
+ void (*user_destroy_)(void*);
+ void* user_data_;
+};
+
+} // namespace grpc_core
+
size_t grpc_slice_memory_usage(grpc_slice s) {
- if (s.refcount == nullptr || s.refcount == &grpc_core::kNoopRefcount) {
+ if (s.refcount == nullptr || s.refcount == &grpc_core::kNoopRefcount) {
return 0;
} else {
return s.data.refcounted.length;
@@ -102,19 +102,19 @@ size_t grpc_slice_memory_usage(grpc_slice s) {
}
grpc_slice grpc_slice_from_static_buffer(const void* s, size_t len) {
- return grpc_core::ExternallyManagedSlice(s, len);
+ return grpc_core::ExternallyManagedSlice(s, len);
}
grpc_slice grpc_slice_from_static_string(const char* s) {
- return grpc_core::ExternallyManagedSlice(s, strlen(s));
+ return grpc_core::ExternallyManagedSlice(s, strlen(s));
}
grpc_slice grpc_slice_new_with_user_data(void* p, size_t len,
void (*destroy)(void*),
void* user_data) {
grpc_slice slice;
- slice.refcount =
- (new grpc_core::NewSliceRefcount(destroy, user_data))->base_refcount();
+ slice.refcount =
+ (new grpc_core::NewSliceRefcount(destroy, user_data))->base_refcount();
slice.data.refcounted.bytes = static_cast<uint8_t*>(p);
slice.data.refcounted.length = len;
return slice;
@@ -125,53 +125,53 @@ grpc_slice grpc_slice_new(void* p, size_t len, void (*destroy)(void*)) {
return grpc_slice_new_with_user_data(p, len, destroy, p);
}
-namespace grpc_core {
+namespace grpc_core {
/* grpc_slice_new_with_len support structures - we create a refcount object
extended with the user provided data pointer & destroy function */
-class NewWithLenSliceRefcount {
- public:
- static void Destroy(void* arg) {
- delete static_cast<NewWithLenSliceRefcount*>(arg);
- }
-
- NewWithLenSliceRefcount(void (*destroy)(void*, size_t), void* user_data,
- size_t user_length)
- : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
- &base_),
- user_data_(user_data),
- user_length_(user_length),
- user_destroy_(destroy) {}
- ~NewWithLenSliceRefcount() { user_destroy_(user_data_, user_length_); }
-
- grpc_slice_refcount* base_refcount() { return &base_; }
-
- private:
- grpc_slice_refcount base_;
- RefCount refs_;
- void* user_data_;
- size_t user_length_;
- void (*user_destroy_)(void*, size_t);
-};
-
-/** grpc_slice_from_moved_(string|buffer) ref count .*/
-class MovedStringSliceRefCount {
- public:
+class NewWithLenSliceRefcount {
+ public:
+ static void Destroy(void* arg) {
+ delete static_cast<NewWithLenSliceRefcount*>(arg);
+ }
+
+ NewWithLenSliceRefcount(void (*destroy)(void*, size_t), void* user_data,
+ size_t user_length)
+ : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
+ &base_),
+ user_data_(user_data),
+ user_length_(user_length),
+ user_destroy_(destroy) {}
+ ~NewWithLenSliceRefcount() { user_destroy_(user_data_, user_length_); }
+
+ grpc_slice_refcount* base_refcount() { return &base_; }
+
+ private:
+ grpc_slice_refcount base_;
+ RefCount refs_;
+ void* user_data_;
+ size_t user_length_;
+ void (*user_destroy_)(void*, size_t);
+};
+
+/** grpc_slice_from_moved_(string|buffer) ref count .*/
+class MovedStringSliceRefCount {
+ public:
explicit MovedStringSliceRefCount(grpc_core::UniquePtr<char>&& str)
- : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
- &base_),
- str_(std::move(str)) {}
-
- grpc_slice_refcount* base_refcount() { return &base_; }
-
- private:
- static void Destroy(void* arg) {
- delete static_cast<MovedStringSliceRefCount*>(arg);
+ : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
+ &base_),
+ str_(std::move(str)) {}
+
+ grpc_slice_refcount* base_refcount() { return &base_; }
+
+ private:
+ static void Destroy(void* arg) {
+ delete static_cast<MovedStringSliceRefCount*>(arg);
}
- grpc_slice_refcount base_;
- grpc_core::RefCount refs_;
- grpc_core::UniquePtr<char> str_;
-};
+ grpc_slice_refcount base_;
+ grpc_core::RefCount refs_;
+ grpc_core::UniquePtr<char> str_;
+};
// grpc_slice_from_cpp_string() ref count.
class MovedCppStringSliceRefCount {
@@ -193,63 +193,63 @@ class MovedCppStringSliceRefCount {
TString str_;
};
-} // namespace grpc_core
-
+} // namespace grpc_core
+
grpc_slice grpc_slice_new_with_len(void* p, size_t len,
void (*destroy)(void*, size_t)) {
grpc_slice slice;
- slice.refcount = (new grpc_core::NewWithLenSliceRefcount(destroy, p, len))
- ->base_refcount();
+ slice.refcount = (new grpc_core::NewWithLenSliceRefcount(destroy, p, len))
+ ->base_refcount();
slice.data.refcounted.bytes = static_cast<uint8_t*>(p);
slice.data.refcounted.length = len;
return slice;
}
-grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(const char* source,
- size_t length) {
- if (length <= sizeof(data.inlined.bytes)) {
- refcount = nullptr;
- data.inlined.length = static_cast<uint8_t>(length);
- } else {
- HeapInit(length);
- }
- if (length > 0) {
- memcpy(GRPC_SLICE_START_PTR(*this), source, length);
- }
-}
-
-grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(const char* source)
- : grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(source,
- strlen(source)) {}
-
+grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(const char* source,
+ size_t length) {
+ if (length <= sizeof(data.inlined.bytes)) {
+ refcount = nullptr;
+ data.inlined.length = static_cast<uint8_t>(length);
+ } else {
+ HeapInit(length);
+ }
+ if (length > 0) {
+ memcpy(GRPC_SLICE_START_PTR(*this), source, length);
+ }
+}
+
+grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(const char* source)
+ : grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(source,
+ strlen(source)) {}
+
grpc_slice grpc_slice_from_copied_buffer(const char* source, size_t length) {
- return grpc_core::UnmanagedMemorySlice(source, length);
+ return grpc_core::UnmanagedMemorySlice(source, length);
}
grpc_slice grpc_slice_from_copied_string(const char* source) {
- return grpc_core::UnmanagedMemorySlice(source, strlen(source));
-}
-
-grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
- size_t len) {
- uint8_t* ptr = reinterpret_cast<uint8_t*>(p.get());
- grpc_slice slice;
- if (len <= sizeof(slice.data.inlined.bytes)) {
- slice.refcount = nullptr;
- slice.data.inlined.length = len;
- memcpy(GRPC_SLICE_START_PTR(slice), ptr, len);
- } else {
- slice.refcount = (new grpc_core::MovedStringSliceRefCount(std::move(p)))
- ->base_refcount();
- slice.data.refcounted.bytes = ptr;
- slice.data.refcounted.length = len;
- }
- return slice;
-}
-
-grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p) {
- const size_t len = strlen(p.get());
- return grpc_slice_from_moved_buffer(std::move(p), len);
+ return grpc_core::UnmanagedMemorySlice(source, strlen(source));
+}
+
+grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
+ size_t len) {
+ uint8_t* ptr = reinterpret_cast<uint8_t*>(p.get());
+ grpc_slice slice;
+ if (len <= sizeof(slice.data.inlined.bytes)) {
+ slice.refcount = nullptr;
+ slice.data.inlined.length = len;
+ memcpy(GRPC_SLICE_START_PTR(slice), ptr, len);
+ } else {
+ slice.refcount = (new grpc_core::MovedStringSliceRefCount(std::move(p)))
+ ->base_refcount();
+ slice.data.refcounted.bytes = ptr;
+ slice.data.refcounted.length = len;
+ }
+ return slice;
+}
+
+grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p) {
+ const size_t len = strlen(p.get());
+ return grpc_slice_from_moved_buffer(std::move(p), len);
}
grpc_slice grpc_slice_from_cpp_string(TString str) {
@@ -269,36 +269,36 @@ grpc_slice grpc_slice_from_cpp_string(TString str) {
return slice;
}
-namespace {
-
-class MallocRefCount {
- public:
- static void Destroy(void* arg) {
- MallocRefCount* r = static_cast<MallocRefCount*>(arg);
- r->~MallocRefCount();
+namespace {
+
+class MallocRefCount {
+ public:
+ static void Destroy(void* arg) {
+ MallocRefCount* r = static_cast<MallocRefCount*>(arg);
+ r->~MallocRefCount();
gpr_free(r);
}
- MallocRefCount()
- : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
- &base_) {}
- ~MallocRefCount() = default;
-
- grpc_slice_refcount* base_refcount() { return &base_; }
-
- private:
- grpc_slice_refcount base_;
- grpc_core::RefCount refs_;
-};
-
-} // namespace
-
+ MallocRefCount()
+ : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
+ &base_) {}
+ ~MallocRefCount() = default;
+
+ grpc_slice_refcount* base_refcount() { return &base_; }
+
+ private:
+ grpc_slice_refcount base_;
+ grpc_core::RefCount refs_;
+};
+
+} // namespace
+
grpc_slice grpc_slice_malloc_large(size_t length) {
- return grpc_core::UnmanagedMemorySlice(
- length, grpc_core::UnmanagedMemorySlice::ForceHeapAllocation());
-}
+ return grpc_core::UnmanagedMemorySlice(
+ length, grpc_core::UnmanagedMemorySlice::ForceHeapAllocation());
+}
-void grpc_core::UnmanagedMemorySlice::HeapInit(size_t length) {
+void grpc_core::UnmanagedMemorySlice::HeapInit(size_t length) {
/* Memory layout used by the slice created here:
+-----------+----------------------------------------------------------+
@@ -308,39 +308,39 @@ void grpc_core::UnmanagedMemorySlice::HeapInit(size_t length) {
refcount is a malloc_refcount
bytes is an array of bytes of the requested length
Both parts are placed in the same allocation returned from gpr_malloc */
- auto* rc =
- static_cast<MallocRefCount*>(gpr_malloc(sizeof(MallocRefCount) + length));
+ auto* rc =
+ static_cast<MallocRefCount*>(gpr_malloc(sizeof(MallocRefCount) + length));
/* Initial refcount on rc is 1 - and it's up to the caller to release
this reference. */
- new (rc) MallocRefCount();
+ new (rc) MallocRefCount();
/* Build up the slice to be returned. */
/* The slices refcount points back to the allocated block. */
- refcount = rc->base_refcount();
+ refcount = rc->base_refcount();
/* The data bytes are placed immediately after the refcount struct */
- data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
+ data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
/* And the length of the block is set to the requested length */
- data.refcounted.length = length;
+ data.refcounted.length = length;
}
grpc_slice grpc_slice_malloc(size_t length) {
- return grpc_core::UnmanagedMemorySlice(length);
-}
+ return grpc_core::UnmanagedMemorySlice(length);
+}
-grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(size_t length) {
- if (length > sizeof(data.inlined.bytes)) {
- HeapInit(length);
+grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(size_t length) {
+ if (length > sizeof(data.inlined.bytes)) {
+ HeapInit(length);
} else {
/* small slice: just inline the data */
- refcount = nullptr;
- data.inlined.length = static_cast<uint8_t>(length);
+ refcount = nullptr;
+ data.inlined.length = static_cast<uint8_t>(length);
}
}
-template <typename Slice>
-static Slice sub_no_ref(const Slice& source, size_t begin, size_t end) {
- Slice subset;
+template <typename Slice>
+static Slice sub_no_ref(const Slice& source, size_t begin, size_t end) {
+ Slice subset;
GPR_ASSERT(end >= begin);
@@ -349,7 +349,7 @@ static Slice sub_no_ref(const Slice& source, size_t begin, size_t end) {
GPR_ASSERT(source.data.refcounted.length >= end);
/* Build the result */
- subset.refcount = source.refcount->sub_refcount();
+ subset.refcount = source.refcount->sub_refcount();
/* Point into the source array */
subset.data.refcounted.bytes = source.data.refcounted.bytes + begin;
subset.data.refcounted.length = end - begin;
@@ -364,15 +364,15 @@ static Slice sub_no_ref(const Slice& source, size_t begin, size_t end) {
return subset;
}
-grpc_slice grpc_slice_sub_no_ref(grpc_slice source, size_t begin, size_t end) {
- return sub_no_ref(source, begin, end);
-}
-
-grpc_core::UnmanagedMemorySlice grpc_slice_sub_no_ref(
- const grpc_core::UnmanagedMemorySlice& source, size_t begin, size_t end) {
- return sub_no_ref(source, begin, end);
-}
-
+grpc_slice grpc_slice_sub_no_ref(grpc_slice source, size_t begin, size_t end) {
+ return sub_no_ref(source, begin, end);
+}
+
+grpc_core::UnmanagedMemorySlice grpc_slice_sub_no_ref(
+ const grpc_core::UnmanagedMemorySlice& source, size_t begin, size_t end) {
+ return sub_no_ref(source, begin, end);
+}
+
grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) {
grpc_slice subset;
@@ -384,7 +384,7 @@ grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) {
} else {
subset = grpc_slice_sub_no_ref(source, begin, end);
/* Bump the refcount */
- subset.refcount->Ref();
+ subset.refcount->Ref();
}
return subset;
}
@@ -412,23 +412,23 @@ grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* source, size_t split,
tail.data.inlined.length = static_cast<uint8_t>(tail_length);
memcpy(tail.data.inlined.bytes, source->data.refcounted.bytes + split,
tail_length);
- source->refcount = source->refcount->sub_refcount();
+ source->refcount = source->refcount->sub_refcount();
} else {
/* Build the result */
switch (ref_whom) {
case GRPC_SLICE_REF_TAIL:
- tail.refcount = source->refcount->sub_refcount();
- source->refcount = &grpc_core::kNoopRefcount;
+ tail.refcount = source->refcount->sub_refcount();
+ source->refcount = &grpc_core::kNoopRefcount;
break;
case GRPC_SLICE_REF_HEAD:
- tail.refcount = &grpc_core::kNoopRefcount;
- source->refcount = source->refcount->sub_refcount();
+ tail.refcount = &grpc_core::kNoopRefcount;
+ source->refcount = source->refcount->sub_refcount();
break;
case GRPC_SLICE_REF_BOTH:
- tail.refcount = source->refcount->sub_refcount();
- source->refcount = source->refcount->sub_refcount();
+ tail.refcount = source->refcount->sub_refcount();
+ source->refcount = source->refcount->sub_refcount();
/* Bump the refcount */
- tail.refcount->Ref();
+ tail.refcount->Ref();
break;
}
/* Point into the source array */
@@ -464,20 +464,20 @@ grpc_slice grpc_slice_split_head(grpc_slice* source, size_t split) {
head.refcount = nullptr;
head.data.inlined.length = static_cast<uint8_t>(split);
memcpy(head.data.inlined.bytes, source->data.refcounted.bytes, split);
- source->refcount = source->refcount->sub_refcount();
+ source->refcount = source->refcount->sub_refcount();
source->data.refcounted.bytes += split;
source->data.refcounted.length -= split;
} else {
GPR_ASSERT(source->data.refcounted.length >= split);
/* Build the result */
- head.refcount = source->refcount->sub_refcount();
+ head.refcount = source->refcount->sub_refcount();
/* Bump the refcount */
- head.refcount->Ref();
+ head.refcount->Ref();
/* Point into the source array */
head.data.refcounted.bytes = source->data.refcounted.bytes;
head.data.refcounted.length = split;
- source->refcount = source->refcount->sub_refcount();
+ source->refcount = source->refcount->sub_refcount();
source->data.refcounted.bytes += split;
source->data.refcounted.length -= split;
}
@@ -493,38 +493,38 @@ int grpc_slice_default_eq_impl(grpc_slice a, grpc_slice b) {
}
int grpc_slice_eq(grpc_slice a, grpc_slice b) {
- if (a.refcount && b.refcount &&
- a.refcount->GetType() == b.refcount->GetType()) {
- return a.refcount->Eq(a, b);
+ if (a.refcount && b.refcount &&
+ a.refcount->GetType() == b.refcount->GetType()) {
+ return a.refcount->Eq(a, b);
}
return grpc_slice_default_eq_impl(a, b);
}
-int grpc_slice_differs_refcounted(const grpc_slice& a,
- const grpc_slice& b_not_inline) {
- size_t a_len;
- const uint8_t* a_ptr;
- if (a.refcount) {
- a_len = a.data.refcounted.length;
- a_ptr = a.data.refcounted.bytes;
- } else {
- a_len = a.data.inlined.length;
- a_ptr = &a.data.inlined.bytes[0];
- }
- if (a_len != b_not_inline.data.refcounted.length) {
- return true;
- }
- if (a_len == 0) {
- return false;
- }
- // This check *must* occur after the a_len == 0 check
- // to retain compatibility with grpc_slice_eq.
- if (a_ptr == nullptr) {
- return true;
- }
- return memcmp(a_ptr, b_not_inline.data.refcounted.bytes, a_len);
-}
-
+int grpc_slice_differs_refcounted(const grpc_slice& a,
+ const grpc_slice& b_not_inline) {
+ size_t a_len;
+ const uint8_t* a_ptr;
+ if (a.refcount) {
+ a_len = a.data.refcounted.length;
+ a_ptr = a.data.refcounted.bytes;
+ } else {
+ a_len = a.data.inlined.length;
+ a_ptr = &a.data.inlined.bytes[0];
+ }
+ if (a_len != b_not_inline.data.refcounted.length) {
+ return true;
+ }
+ if (a_len == 0) {
+ return false;
+ }
+ // This check *must* occur after the a_len == 0 check
+ // to retain compatibility with grpc_slice_eq.
+ if (a_ptr == nullptr) {
+ return true;
+ }
+ return memcmp(a_ptr, b_not_inline.data.refcounted.bytes, a_len);
+}
+
int grpc_slice_cmp(grpc_slice a, grpc_slice b) {
int d = static_cast<int>(GRPC_SLICE_LENGTH(a) - GRPC_SLICE_LENGTH(b));
if (d != 0) return d;
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc b/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc
index 2d66694736..68c5085bc4 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc
@@ -32,45 +32,45 @@
/* grow a buffer; requires GRPC_SLICE_BUFFER_INLINE_ELEMENTS > 1 */
#define GROW(x) (3 * (x) / 2)
-/* Typically, we do not actually need to embiggen (by calling
- * memmove/malloc/realloc) - only if we were up against the full capacity of the
- * slice buffer. If do_embiggen is inlined, the compiler clobbers multiple
- * registers pointlessly in the common case. */
-static void GPR_ATTRIBUTE_NOINLINE do_embiggen(grpc_slice_buffer* sb,
- const size_t slice_count,
- const size_t slice_offset) {
- if (slice_offset != 0) {
- /* Make room by moving elements if there's still space unused */
- memmove(sb->base_slices, sb->slices, sb->count * sizeof(grpc_slice));
- sb->slices = sb->base_slices;
- } else {
- /* Allocate more memory if no more space is available */
- const size_t new_capacity = GROW(sb->capacity);
- sb->capacity = new_capacity;
- if (sb->base_slices == sb->inlined) {
- sb->base_slices = static_cast<grpc_slice*>(
- gpr_malloc(new_capacity * sizeof(grpc_slice)));
- memcpy(sb->base_slices, sb->inlined, slice_count * sizeof(grpc_slice));
- } else {
- sb->base_slices = static_cast<grpc_slice*>(
- gpr_realloc(sb->base_slices, new_capacity * sizeof(grpc_slice)));
- }
-
- sb->slices = sb->base_slices + slice_offset;
- }
-}
-
+/* Typically, we do not actually need to embiggen (by calling
+ * memmove/malloc/realloc) - only if we were up against the full capacity of the
+ * slice buffer. If do_embiggen is inlined, the compiler clobbers multiple
+ * registers pointlessly in the common case. */
+static void GPR_ATTRIBUTE_NOINLINE do_embiggen(grpc_slice_buffer* sb,
+ const size_t slice_count,
+ const size_t slice_offset) {
+ if (slice_offset != 0) {
+ /* Make room by moving elements if there's still space unused */
+ memmove(sb->base_slices, sb->slices, sb->count * sizeof(grpc_slice));
+ sb->slices = sb->base_slices;
+ } else {
+ /* Allocate more memory if no more space is available */
+ const size_t new_capacity = GROW(sb->capacity);
+ sb->capacity = new_capacity;
+ if (sb->base_slices == sb->inlined) {
+ sb->base_slices = static_cast<grpc_slice*>(
+ gpr_malloc(new_capacity * sizeof(grpc_slice)));
+ memcpy(sb->base_slices, sb->inlined, slice_count * sizeof(grpc_slice));
+ } else {
+ sb->base_slices = static_cast<grpc_slice*>(
+ gpr_realloc(sb->base_slices, new_capacity * sizeof(grpc_slice)));
+ }
+
+ sb->slices = sb->base_slices + slice_offset;
+ }
+}
+
static void maybe_embiggen(grpc_slice_buffer* sb) {
- if (sb->count == 0) {
- sb->slices = sb->base_slices;
- return;
- }
-
+ if (sb->count == 0) {
+ sb->slices = sb->base_slices;
+ return;
+ }
+
/* How far away from sb->base_slices is sb->slices pointer */
size_t slice_offset = static_cast<size_t>(sb->slices - sb->base_slices);
size_t slice_count = sb->count + slice_offset;
- if (GPR_UNLIKELY(slice_count == sb->capacity)) {
- do_embiggen(sb, slice_count, slice_offset);
+ if (GPR_UNLIKELY(slice_count == sb->capacity)) {
+ do_embiggen(sb, slice_count, slice_offset);
}
}
@@ -103,7 +103,7 @@ uint8_t* grpc_slice_buffer_tiny_add(grpc_slice_buffer* sb, size_t n) {
sb->length += n;
- if (sb->count == 0) goto add_first;
+ if (sb->count == 0) goto add_first;
back = &sb->slices[sb->count - 1];
if (back->refcount) goto add_new;
if ((back->data.inlined.length + n) > sizeof(back->data.inlined.bytes))
@@ -115,7 +115,7 @@ uint8_t* grpc_slice_buffer_tiny_add(grpc_slice_buffer* sb, size_t n) {
add_new:
maybe_embiggen(sb);
-add_first:
+add_first:
back = &sb->slices[sb->count];
sb->count++;
back->refcount = nullptr;
@@ -192,7 +192,7 @@ void grpc_slice_buffer_reset_and_unref_internal(grpc_slice_buffer* sb) {
sb->count = 0;
sb->length = 0;
- sb->slices = sb->base_slices;
+ sb->slices = sb->base_slices;
}
void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer* sb) {
@@ -263,9 +263,9 @@ void grpc_slice_buffer_move_into(grpc_slice_buffer* src,
src->length = 0;
}
-template <bool incref>
+template <bool incref>
static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer* src, size_t n,
- grpc_slice_buffer* dst) {
+ grpc_slice_buffer* dst) {
GPR_ASSERT(src->length >= n);
if (src->length == n) {
grpc_slice_buffer_move_into(src, dst);
@@ -305,12 +305,12 @@ static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer* src, size_t n,
void grpc_slice_buffer_move_first(grpc_slice_buffer* src, size_t n,
grpc_slice_buffer* dst) {
- slice_buffer_move_first_maybe_ref<true>(src, n, dst);
+ slice_buffer_move_first_maybe_ref<true>(src, n, dst);
}
void grpc_slice_buffer_move_first_no_ref(grpc_slice_buffer* src, size_t n,
grpc_slice_buffer* dst) {
- slice_buffer_move_first_maybe_ref<false>(src, n, dst);
+ slice_buffer_move_first_maybe_ref<false>(src, n, dst);
}
void grpc_slice_buffer_move_first_into_buffer(grpc_slice_buffer* src, size_t n,
@@ -386,24 +386,24 @@ grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer* sb) {
return slice;
}
-void grpc_slice_buffer_remove_first(grpc_slice_buffer* sb) {
- GPR_DEBUG_ASSERT(sb->count > 0);
- sb->length -= GRPC_SLICE_LENGTH(sb->slices[0]);
- grpc_slice_unref_internal(sb->slices[0]);
- sb->slices++;
- if (--sb->count == 0) {
- sb->slices = sb->base_slices;
- }
-}
-
-void grpc_slice_buffer_sub_first(grpc_slice_buffer* sb, size_t begin,
- size_t end) {
- // TODO(soheil): Introduce a ptr version for sub.
- sb->length -= GRPC_SLICE_LENGTH(sb->slices[0]);
- sb->slices[0] = grpc_slice_sub_no_ref(sb->slices[0], begin, end);
- sb->length += end - begin;
-}
-
+void grpc_slice_buffer_remove_first(grpc_slice_buffer* sb) {
+ GPR_DEBUG_ASSERT(sb->count > 0);
+ sb->length -= GRPC_SLICE_LENGTH(sb->slices[0]);
+ grpc_slice_unref_internal(sb->slices[0]);
+ sb->slices++;
+ if (--sb->count == 0) {
+ sb->slices = sb->base_slices;
+ }
+}
+
+void grpc_slice_buffer_sub_first(grpc_slice_buffer* sb, size_t begin,
+ size_t end) {
+ // TODO(soheil): Introduce a ptr version for sub.
+ sb->length -= GRPC_SLICE_LENGTH(sb->slices[0]);
+ sb->slices[0] = grpc_slice_sub_no_ref(sb->slices[0], begin, end);
+ sb->length += end - begin;
+}
+
void grpc_slice_buffer_undo_take_first(grpc_slice_buffer* sb,
grpc_slice slice) {
sb->slices--;
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_intern.cc b/contrib/libs/grpc/src/core/lib/slice/slice_intern.cc
index b41628c70b..e2d03c3358 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_intern.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_intern.cc
@@ -19,7 +19,7 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/slice/slice_utils.h"
#include <inttypes.h>
#include <string.h>
@@ -28,7 +28,7 @@
#include <grpc/support/log.h>
#include "src/core/lib/gpr/murmur_hash.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/iomgr_internal.h" /* for iomgr_abort_on_leaks() */
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_string_helpers.h"
@@ -41,11 +41,11 @@
#define TABLE_IDX(hash, capacity) (((hash) >> LOG2_SHARD_COUNT) % (capacity))
#define SHARD_IDX(hash) ((hash) & ((1 << LOG2_SHARD_COUNT) - 1))
-using grpc_core::InternedSliceRefcount;
+using grpc_core::InternedSliceRefcount;
typedef struct slice_shard {
gpr_mu mu;
- InternedSliceRefcount** strs;
+ InternedSliceRefcount** strs;
size_t count;
size_t capacity;
} slice_shard;
@@ -59,39 +59,39 @@ struct static_metadata_hash_ent {
static static_metadata_hash_ent
static_metadata_hash[4 * GRPC_STATIC_MDSTR_COUNT];
static uint32_t max_static_metadata_hash_probe;
-uint32_t grpc_static_metadata_hash_values[GRPC_STATIC_MDSTR_COUNT];
-
-namespace grpc_core {
-
-/* hash seed: decided at initialization time */
-uint32_t g_hash_seed;
-static bool g_forced_hash_seed = false;
-
-InternedSliceRefcount::~InternedSliceRefcount() {
- slice_shard* shard = &g_shards[SHARD_IDX(this->hash)];
- MutexLock lock(&shard->mu);
- InternedSliceRefcount** prev_next;
- InternedSliceRefcount* cur;
- for (prev_next = &shard->strs[TABLE_IDX(this->hash, shard->capacity)],
+uint32_t grpc_static_metadata_hash_values[GRPC_STATIC_MDSTR_COUNT];
+
+namespace grpc_core {
+
+/* hash seed: decided at initialization time */
+uint32_t g_hash_seed;
+static bool g_forced_hash_seed = false;
+
+InternedSliceRefcount::~InternedSliceRefcount() {
+ slice_shard* shard = &g_shards[SHARD_IDX(this->hash)];
+ MutexLock lock(&shard->mu);
+ InternedSliceRefcount** prev_next;
+ InternedSliceRefcount* cur;
+ for (prev_next = &shard->strs[TABLE_IDX(this->hash, shard->capacity)],
cur = *prev_next;
- cur != this; prev_next = &cur->bucket_next, cur = cur->bucket_next)
+ cur != this; prev_next = &cur->bucket_next, cur = cur->bucket_next)
;
*prev_next = cur->bucket_next;
shard->count--;
}
-} // namespace grpc_core
+} // namespace grpc_core
static void grow_shard(slice_shard* shard) {
GPR_TIMER_SCOPE("grow_strtab", 0);
size_t capacity = shard->capacity * 2;
size_t i;
- InternedSliceRefcount** strtab;
- InternedSliceRefcount *s, *next;
+ InternedSliceRefcount** strtab;
+ InternedSliceRefcount *s, *next;
- strtab = static_cast<InternedSliceRefcount**>(
- gpr_zalloc(sizeof(InternedSliceRefcount*) * capacity));
+ strtab = static_cast<InternedSliceRefcount**>(
+ gpr_zalloc(sizeof(InternedSliceRefcount*) * capacity));
for (i = 0; i < shard->capacity; i++) {
for (s = shard->strs[i]; s; s = next) {
@@ -106,26 +106,26 @@ static void grow_shard(slice_shard* shard) {
shard->capacity = capacity;
}
-grpc_core::InternedSlice::InternedSlice(InternedSliceRefcount* s) {
- refcount = &s->base;
- data.refcounted.bytes = reinterpret_cast<uint8_t*>(s + 1);
- data.refcounted.length = s->length;
+grpc_core::InternedSlice::InternedSlice(InternedSliceRefcount* s) {
+ refcount = &s->base;
+ data.refcounted.bytes = reinterpret_cast<uint8_t*>(s + 1);
+ data.refcounted.length = s->length;
}
uint32_t grpc_slice_default_hash_impl(grpc_slice s) {
return gpr_murmur_hash3(GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s),
- grpc_core::g_hash_seed);
+ grpc_core::g_hash_seed);
}
uint32_t grpc_static_slice_hash(grpc_slice s) {
- return grpc_static_metadata_hash_values[GRPC_STATIC_METADATA_INDEX(s)];
+ return grpc_static_metadata_hash_values[GRPC_STATIC_METADATA_INDEX(s)];
}
int grpc_static_slice_eq(grpc_slice a, grpc_slice b) {
return GRPC_STATIC_METADATA_INDEX(a) == GRPC_STATIC_METADATA_INDEX(b);
}
-uint32_t grpc_slice_hash(grpc_slice s) { return grpc_slice_hash_internal(s); }
+uint32_t grpc_slice_hash(grpc_slice s) { return grpc_slice_hash_internal(s); }
grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
bool* returned_slice_is_different) {
@@ -133,192 +133,192 @@ grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
return slice;
}
- uint32_t hash = grpc_slice_hash_internal(slice);
+ uint32_t hash = grpc_slice_hash_internal(slice);
for (uint32_t i = 0; i <= max_static_metadata_hash_probe; i++) {
static_metadata_hash_ent ent =
static_metadata_hash[(hash + i) % GPR_ARRAY_SIZE(static_metadata_hash)];
- const grpc_core::StaticMetadataSlice* static_slice_table =
- grpc_static_slice_table();
+ const grpc_core::StaticMetadataSlice* static_slice_table =
+ grpc_static_slice_table();
if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
- grpc_slice_eq_static_interned(slice, static_slice_table[ent.idx])) {
+ grpc_slice_eq_static_interned(slice, static_slice_table[ent.idx])) {
*returned_slice_is_different = true;
- return static_slice_table[ent.idx];
+ return static_slice_table[ent.idx];
}
}
return slice;
}
-grpc_slice grpc_slice_intern(grpc_slice slice) {
- /* TODO(arjunroy): At present, this is capable of returning either a static or
- an interned slice. This yields weirdness like the constructor for
- ManagedMemorySlice instantiating itself as an instance of a derived type
- (StaticMetadataSlice or InternedSlice). Should reexamine. */
- return grpc_core::ManagedMemorySlice(&slice);
+grpc_slice grpc_slice_intern(grpc_slice slice) {
+ /* TODO(arjunroy): At present, this is capable of returning either a static or
+ an interned slice. This yields weirdness like the constructor for
+ ManagedMemorySlice instantiating itself as an instance of a derived type
+ (StaticMetadataSlice or InternedSlice). Should reexamine. */
+ return grpc_core::ManagedMemorySlice(&slice);
}
-// Attempt to see if the provided slice or string matches a static slice.
-// SliceArgs is either a const grpc_slice& or const pair<const char*, size_t>&.
-// In either case, hash is the pre-computed hash value.
-//
-// Returns: a matching static slice, or null.
-template <typename SliceArgs>
-static const grpc_core::StaticMetadataSlice* MatchStaticSlice(
- uint32_t hash, const SliceArgs& args) {
+// Attempt to see if the provided slice or string matches a static slice.
+// SliceArgs is either a const grpc_slice& or const pair<const char*, size_t>&.
+// In either case, hash is the pre-computed hash value.
+//
+// Returns: a matching static slice, or null.
+template <typename SliceArgs>
+static const grpc_core::StaticMetadataSlice* MatchStaticSlice(
+ uint32_t hash, const SliceArgs& args) {
for (uint32_t i = 0; i <= max_static_metadata_hash_probe; i++) {
static_metadata_hash_ent ent =
static_metadata_hash[(hash + i) % GPR_ARRAY_SIZE(static_metadata_hash)];
- const grpc_core::StaticMetadataSlice* static_slice_table =
- grpc_static_slice_table();
+ const grpc_core::StaticMetadataSlice* static_slice_table =
+ grpc_static_slice_table();
if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
- static_slice_table[ent.idx] == args) {
- return &static_slice_table[ent.idx];
+ static_slice_table[ent.idx] == args) {
+ return &static_slice_table[ent.idx];
}
}
- return nullptr;
-}
-
-// Helper methods to enable us to select appropriately overloaded slice methods
-// whether we're dealing with a slice, or a buffer with length, when interning
-// strings. Helpers for FindOrCreateInternedSlice().
-static const char* GetBuffer(const std::pair<const char*, size_t>& buflen) {
- return buflen.first;
-}
-static size_t GetLength(const std::pair<const char*, size_t>& buflen) {
- return buflen.second;
-}
-static const void* GetBuffer(const grpc_slice& slice) {
- return GRPC_SLICE_START_PTR(slice);
-}
-static size_t GetLength(const grpc_slice& slice) {
- return GRPC_SLICE_LENGTH(slice);
-}
-
-// Creates an interned slice for a string that does not currently exist in the
-// intern table. SliceArgs is either a const grpc_slice& or a const
-// pair<const char*, size_t>&. Hash is the pre-computed hash value. We must
-// already hold the shard lock. Helper for FindOrCreateInternedSlice().
-//
-// Returns: a newly interned slice.
-template <typename SliceArgs>
-static InternedSliceRefcount* InternNewStringLocked(slice_shard* shard,
- size_t shard_idx,
- uint32_t hash,
- const SliceArgs& args) {
- /* string data goes after the internal_string header */
- size_t len = GetLength(args);
- const void* buffer = GetBuffer(args);
- InternedSliceRefcount* s =
- static_cast<InternedSliceRefcount*>(gpr_malloc(sizeof(*s) + len));
- new (s) grpc_core::InternedSliceRefcount(len, hash, shard->strs[shard_idx]);
- // TODO(arjunroy): Investigate why hpack tried to intern the nullptr string.
- // https://github.com/grpc/grpc/pull/20110#issuecomment-526729282
- if (len > 0) {
- memcpy(reinterpret_cast<char*>(s + 1), buffer, len);
- }
- shard->strs[shard_idx] = s;
- shard->count++;
- if (shard->count > shard->capacity * 2) {
- grow_shard(shard);
- }
- return s;
-}
-
-// Attempt to see if the provided slice or string matches an existing interned
-// slice. SliceArgs... is either a const grpc_slice& or a string and length. In
-// either case, hash is the pre-computed hash value. We must already hold the
-// shard lock. Helper for FindOrCreateInternedSlice().
-//
-// Returns: a pre-existing matching static slice, or null.
-template <typename SliceArgs>
-static InternedSliceRefcount* MatchInternedSliceLocked(uint32_t hash,
- size_t idx,
- const SliceArgs& args) {
- InternedSliceRefcount* s;
- slice_shard* shard = &g_shards[SHARD_IDX(hash)];
+ return nullptr;
+}
+
+// Helper methods to enable us to select appropriately overloaded slice methods
+// whether we're dealing with a slice, or a buffer with length, when interning
+// strings. Helpers for FindOrCreateInternedSlice().
+static const char* GetBuffer(const std::pair<const char*, size_t>& buflen) {
+ return buflen.first;
+}
+static size_t GetLength(const std::pair<const char*, size_t>& buflen) {
+ return buflen.second;
+}
+static const void* GetBuffer(const grpc_slice& slice) {
+ return GRPC_SLICE_START_PTR(slice);
+}
+static size_t GetLength(const grpc_slice& slice) {
+ return GRPC_SLICE_LENGTH(slice);
+}
+
+// Creates an interned slice for a string that does not currently exist in the
+// intern table. SliceArgs is either a const grpc_slice& or a const
+// pair<const char*, size_t>&. Hash is the pre-computed hash value. We must
+// already hold the shard lock. Helper for FindOrCreateInternedSlice().
+//
+// Returns: a newly interned slice.
+template <typename SliceArgs>
+static InternedSliceRefcount* InternNewStringLocked(slice_shard* shard,
+ size_t shard_idx,
+ uint32_t hash,
+ const SliceArgs& args) {
+ /* string data goes after the internal_string header */
+ size_t len = GetLength(args);
+ const void* buffer = GetBuffer(args);
+ InternedSliceRefcount* s =
+ static_cast<InternedSliceRefcount*>(gpr_malloc(sizeof(*s) + len));
+ new (s) grpc_core::InternedSliceRefcount(len, hash, shard->strs[shard_idx]);
+ // TODO(arjunroy): Investigate why hpack tried to intern the nullptr string.
+ // https://github.com/grpc/grpc/pull/20110#issuecomment-526729282
+ if (len > 0) {
+ memcpy(reinterpret_cast<char*>(s + 1), buffer, len);
+ }
+ shard->strs[shard_idx] = s;
+ shard->count++;
+ if (shard->count > shard->capacity * 2) {
+ grow_shard(shard);
+ }
+ return s;
+}
+
+// Attempt to see if the provided slice or string matches an existing interned
+// slice. SliceArgs... is either a const grpc_slice& or a string and length. In
+// either case, hash is the pre-computed hash value. We must already hold the
+// shard lock. Helper for FindOrCreateInternedSlice().
+//
+// Returns: a pre-existing matching static slice, or null.
+template <typename SliceArgs>
+static InternedSliceRefcount* MatchInternedSliceLocked(uint32_t hash,
+ size_t idx,
+ const SliceArgs& args) {
+ InternedSliceRefcount* s;
+ slice_shard* shard = &g_shards[SHARD_IDX(hash)];
/* search for an existing string */
for (s = shard->strs[idx]; s; s = s->bucket_next) {
- if (s->hash == hash && grpc_core::InternedSlice(s) == args) {
- if (s->refcnt.RefIfNonZero()) {
- return s;
+ if (s->hash == hash && grpc_core::InternedSlice(s) == args) {
+ if (s->refcnt.RefIfNonZero()) {
+ return s;
}
}
}
- return nullptr;
-}
-
-// Attempt to see if the provided slice or string matches an existing interned
-// slice, and failing that, create an interned slice with its contents. Returns
-// either the existing matching interned slice or the newly created one.
-// SliceArgs is either a const grpc_slice& or const pair<const char*, size_t>&.
-// In either case, hash is the pre-computed hash value. We do not hold the
-// shard lock here, but do take it.
-//
-// Returns: an interned slice, either pre-existing/matched or newly created.
-template <typename SliceArgs>
-static InternedSliceRefcount* FindOrCreateInternedSlice(uint32_t hash,
- const SliceArgs& args) {
- slice_shard* shard = &g_shards[SHARD_IDX(hash)];
- gpr_mu_lock(&shard->mu);
- const size_t idx = TABLE_IDX(hash, shard->capacity);
- InternedSliceRefcount* s = MatchInternedSliceLocked(hash, idx, args);
- if (s == nullptr) {
- s = InternNewStringLocked(shard, idx, hash, args);
- }
- gpr_mu_unlock(&shard->mu);
- return s;
-}
-
-grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string)
- : grpc_core::ManagedMemorySlice::ManagedMemorySlice(string,
- strlen(string)) {}
-
-grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string,
- size_t len) {
- GPR_TIMER_SCOPE("grpc_slice_intern", 0);
- const uint32_t hash = gpr_murmur_hash3(string, len, g_hash_seed);
- const StaticMetadataSlice* static_slice =
- MatchStaticSlice(hash, std::pair<const char*, size_t>(string, len));
- if (static_slice) {
- *this = *static_slice;
- } else {
- *this = grpc_core::InternedSlice(FindOrCreateInternedSlice(
- hash, std::pair<const char*, size_t>(string, len)));
- }
-}
-
-grpc_core::ManagedMemorySlice::ManagedMemorySlice(const grpc_slice* slice_ptr) {
- GPR_TIMER_SCOPE("grpc_slice_intern", 0);
- const grpc_slice& slice = *slice_ptr;
- if (GRPC_IS_STATIC_METADATA_STRING(slice)) {
- *this = static_cast<const grpc_core::StaticMetadataSlice&>(slice);
- return;
- }
- const uint32_t hash = grpc_slice_hash_internal(slice);
- const StaticMetadataSlice* static_slice = MatchStaticSlice(hash, slice);
- if (static_slice) {
- *this = *static_slice;
- } else {
- *this = grpc_core::InternedSlice(FindOrCreateInternedSlice(hash, slice));
+ return nullptr;
+}
+
+// Attempt to see if the provided slice or string matches an existing interned
+// slice, and failing that, create an interned slice with its contents. Returns
+// either the existing matching interned slice or the newly created one.
+// SliceArgs is either a const grpc_slice& or const pair<const char*, size_t>&.
+// In either case, hash is the pre-computed hash value. We do not hold the
+// shard lock here, but do take it.
+//
+// Returns: an interned slice, either pre-existing/matched or newly created.
+template <typename SliceArgs>
+static InternedSliceRefcount* FindOrCreateInternedSlice(uint32_t hash,
+ const SliceArgs& args) {
+ slice_shard* shard = &g_shards[SHARD_IDX(hash)];
+ gpr_mu_lock(&shard->mu);
+ const size_t idx = TABLE_IDX(hash, shard->capacity);
+ InternedSliceRefcount* s = MatchInternedSliceLocked(hash, idx, args);
+ if (s == nullptr) {
+ s = InternNewStringLocked(shard, idx, hash, args);
+ }
+ gpr_mu_unlock(&shard->mu);
+ return s;
+}
+
+grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string)
+ : grpc_core::ManagedMemorySlice::ManagedMemorySlice(string,
+ strlen(string)) {}
+
+grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string,
+ size_t len) {
+ GPR_TIMER_SCOPE("grpc_slice_intern", 0);
+ const uint32_t hash = gpr_murmur_hash3(string, len, g_hash_seed);
+ const StaticMetadataSlice* static_slice =
+ MatchStaticSlice(hash, std::pair<const char*, size_t>(string, len));
+ if (static_slice) {
+ *this = *static_slice;
+ } else {
+ *this = grpc_core::InternedSlice(FindOrCreateInternedSlice(
+ hash, std::pair<const char*, size_t>(string, len)));
}
+}
+
+grpc_core::ManagedMemorySlice::ManagedMemorySlice(const grpc_slice* slice_ptr) {
+ GPR_TIMER_SCOPE("grpc_slice_intern", 0);
+ const grpc_slice& slice = *slice_ptr;
+ if (GRPC_IS_STATIC_METADATA_STRING(slice)) {
+ *this = static_cast<const grpc_core::StaticMetadataSlice&>(slice);
+ return;
+ }
+ const uint32_t hash = grpc_slice_hash_internal(slice);
+ const StaticMetadataSlice* static_slice = MatchStaticSlice(hash, slice);
+ if (static_slice) {
+ *this = *static_slice;
+ } else {
+ *this = grpc_core::InternedSlice(FindOrCreateInternedSlice(hash, slice));
+ }
}
void grpc_test_only_set_slice_hash_seed(uint32_t seed) {
- grpc_core::g_hash_seed = seed;
- grpc_core::g_forced_hash_seed = true;
+ grpc_core::g_hash_seed = seed;
+ grpc_core::g_forced_hash_seed = true;
}
void grpc_slice_intern_init(void) {
- if (!grpc_core::g_forced_hash_seed) {
- grpc_core::g_hash_seed =
- static_cast<uint32_t>(gpr_now(GPR_CLOCK_REALTIME).tv_nsec);
+ if (!grpc_core::g_forced_hash_seed) {
+ grpc_core::g_hash_seed =
+ static_cast<uint32_t>(gpr_now(GPR_CLOCK_REALTIME).tv_nsec);
}
for (size_t i = 0; i < SHARD_COUNT; i++) {
slice_shard* shard = &g_shards[i];
gpr_mu_init(&shard->mu);
shard->count = 0;
shard->capacity = INITIAL_SHARD_CAPACITY;
- shard->strs = static_cast<InternedSliceRefcount**>(
+ shard->strs = static_cast<InternedSliceRefcount**>(
gpr_zalloc(sizeof(*shard->strs) * shard->capacity));
}
for (size_t i = 0; i < GPR_ARRAY_SIZE(static_metadata_hash); i++) {
@@ -326,16 +326,16 @@ void grpc_slice_intern_init(void) {
static_metadata_hash[i].idx = GRPC_STATIC_MDSTR_COUNT;
}
max_static_metadata_hash_probe = 0;
- const grpc_core::StaticMetadataSlice* static_slice_table =
- grpc_static_slice_table();
+ const grpc_core::StaticMetadataSlice* static_slice_table =
+ grpc_static_slice_table();
for (size_t i = 0; i < GRPC_STATIC_MDSTR_COUNT; i++) {
- grpc_static_metadata_hash_values[i] =
- grpc_slice_default_hash_internal(static_slice_table[i]);
+ grpc_static_metadata_hash_values[i] =
+ grpc_slice_default_hash_internal(static_slice_table[i]);
for (size_t j = 0; j < GPR_ARRAY_SIZE(static_metadata_hash); j++) {
- size_t slot = (grpc_static_metadata_hash_values[i] + j) %
+ size_t slot = (grpc_static_metadata_hash_values[i] + j) %
GPR_ARRAY_SIZE(static_metadata_hash);
if (static_metadata_hash[slot].idx == GRPC_STATIC_MDSTR_COUNT) {
- static_metadata_hash[slot].hash = grpc_static_metadata_hash_values[i];
+ static_metadata_hash[slot].hash = grpc_static_metadata_hash_values[i];
static_metadata_hash[slot].idx = static_cast<uint32_t>(i);
if (j > max_static_metadata_hash_probe) {
max_static_metadata_hash_probe = static_cast<uint32_t>(j);
@@ -344,10 +344,10 @@ void grpc_slice_intern_init(void) {
}
}
}
- // Handle KV hash for all static mdelems.
- for (size_t i = 0; i < GRPC_STATIC_MDELEM_COUNT; ++i) {
- grpc_static_mdelem_table()[i].HashInit();
- }
+ // Handle KV hash for all static mdelems.
+ for (size_t i = 0; i < GRPC_STATIC_MDELEM_COUNT; ++i) {
+ grpc_static_mdelem_table()[i].HashInit();
+ }
}
void grpc_slice_intern_shutdown(void) {
@@ -359,9 +359,9 @@ void grpc_slice_intern_shutdown(void) {
gpr_log(GPR_DEBUG, "WARNING: %" PRIuPTR " metadata strings were leaked",
shard->count);
for (size_t j = 0; j < shard->capacity; j++) {
- for (InternedSliceRefcount* s = shard->strs[j]; s; s = s->bucket_next) {
- char* text = grpc_dump_slice(grpc_core::InternedSlice(s),
- GPR_DUMP_HEX | GPR_DUMP_ASCII);
+ for (InternedSliceRefcount* s = shard->strs[j]; s; s = s->bucket_next) {
+ char* text = grpc_dump_slice(grpc_core::InternedSlice(s),
+ GPR_DUMP_HEX | GPR_DUMP_ASCII);
gpr_log(GPR_DEBUG, "LEAKED: %s", text);
gpr_free(text);
}
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_internal.h b/contrib/libs/grpc/src/core/lib/slice/slice_internal.h
index 8a17b6e72e..eccfb1bd37 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_internal.h
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_internal.h
@@ -21,293 +21,293 @@
#include <grpc/support/port_platform.h>
-#include <grpc/support/log.h>
-
+#include <grpc/support/log.h>
+
#include <grpc/slice.h>
#include <grpc/slice_buffer.h>
-#include <string.h>
-
-#include "src/core/lib/gpr/murmur_hash.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/slice/slice_utils.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-// Interned slices have specific fast-path operations for hashing. To inline
-// these operations, we need to forward declare them here.
-extern uint32_t grpc_static_metadata_hash_values[GRPC_STATIC_MDSTR_COUNT];
-
-// grpc_slice_refcount : A reference count for grpc_slice.
-//
-// Non-inlined grpc_slice objects are refcounted. Historically this was
-// implemented via grpc_slice_refcount, a C-style polymorphic class using a
-// manually managed vtable of operations. Subclasses would define their own
-// vtable; the 'virtual' methods (ref, unref, equals and hash) would simply call
-// the function pointers in the vtable as necessary.
-//
-// Unfortunately, this leads to some inefficiencies in the generated code that
-// can be improved upon. For example, equality checking for interned slices is a
-// simple equality check on the refcount pointer. With the vtable approach, this
-// would translate to roughly the following (high-level) instructions:
-//
-// grpc_slice_equals(slice1, slice2):
-// load vtable->eq -> eq_func
-// call eq_func(slice1, slice2)
-//
-// interned_slice_equals(slice1, slice2)
-// load slice1.ref -> r1
-// load slice2.ref -> r2
-// cmp r1, r2 -> retval
-// ret retval
-//
-// This leads to a function call for a function defined in another translation
-// unit, which imposes memory barriers, which reduces the compiler's ability to
-// optimize (in addition to the added overhead of call/ret). Additionally, it
-// may be harder to reason about branch prediction when we're jumping to
-// essentially arbitrarily provided function pointers.
-//
-// In addition, it is arguable that while virtualization was helpful for
-// Equals()/Hash() methods, that it was fundamentally unnecessary for
-// Ref()/Unref().
-//
-// Instead, grpc_slice_refcount provides the same functionality as the C-style
-// virtual class, but in a de-virtualized manner - Eq(), Hash(), Ref() and
-// Unref() are provided within this header file. Fastpaths for Eq()/Hash()
-// (interned and static metadata slices), as well as the Ref() operation, can
-// all be inlined without any memory barriers.
-//
-// It does this by:
-// 1. Using grpc_core::RefCount<> (header-only) for Ref/Unref. Two special cases
-// need support: No-op ref/unref (eg. static metadata slices) and stream
-// slice references (where all the slices share the streamref). This is in
-// addition to the normal case of '1 slice, 1 ref'.
-// To support these cases, we explicitly track a nullable pointer to the
-// underlying RefCount<>. No-op ref/unref is used by checking the pointer for
-// null, and doing nothing if it is. Both stream slice refs and 'normal'
-// slices use the same path for Ref/Unref (by targeting the non-null
-// pointer).
-//
-// 2. introducing the notion of grpc_slice_refcount::Type. This describes if a
-// slice ref is used by a static metadata slice, an interned slice, or other
-// slices. We switch on the slice ref type in order to provide fastpaths for
-// Equals() and Hash().
-//
-// In total, this saves us roughly 1-2% latency for unary calls, with smaller
-// calls benefitting. The effect is present, but not as useful, for larger calls
-// where the cost of sending the data dominates.
-// TODO(arjunroy): Investigate if this can be removed with strongly typed
-// grpc_slices.
-struct grpc_slice_refcount {
- public:
- enum class Type {
- STATIC, // Refcount for a static metadata slice.
- INTERNED, // Refcount for an interned slice.
- NOP, // No-Op
- REGULAR // Refcount for non-static-metadata, non-interned slices.
- };
- typedef void (*DestroyerFn)(void*);
-
- grpc_slice_refcount() = default;
-
- explicit grpc_slice_refcount(Type t) : ref_type_(t) {}
-
- explicit grpc_slice_refcount(grpc_slice_refcount* sub) : sub_refcount_(sub) {}
- // Regular constructor for grpc_slice_refcount.
- //
- // Parameters:
- // 1. grpc_slice_refcount::Type type
- // Whether we are the refcount for a static
- // metadata slice, an interned slice, or any other kind of slice.
- //
- // 2. RefCount* ref
- // The pointer to the actual underlying grpc_core::RefCount. Rather than
- // performing struct offset computations as in the original implementation to
- // get to the refcount, which requires a virtual method, we devirtualize by
- // using a nullable pointer to allow a single pair of Ref/Unref methods.
- //
- // 3. DestroyerFn destroyer_fn
- // Called when the refcount goes to 0, with destroyer_arg as parameter.
- //
- // 4. void* destroyer_arg
- // Argument for the virtualized destructor.
- //
- // 5. grpc_slice_refcount* sub
- // Argument used for interned slices.
- grpc_slice_refcount(grpc_slice_refcount::Type type, grpc_core::RefCount* ref,
- DestroyerFn destroyer_fn, void* destroyer_arg,
- grpc_slice_refcount* sub)
- : ref_(ref),
- ref_type_(type),
- sub_refcount_(sub),
- dest_fn_(destroyer_fn),
- destroy_fn_arg_(destroyer_arg) {}
- // Initializer for static refcounts.
- grpc_slice_refcount(grpc_slice_refcount* sub, Type type)
- : ref_type_(type), sub_refcount_(sub) {}
-
- Type GetType() const { return ref_type_; }
-
- int Eq(const grpc_slice& a, const grpc_slice& b);
-
- uint32_t Hash(const grpc_slice& slice);
- void Ref() {
- if (ref_ == nullptr) return;
- ref_->RefNonZero();
- }
- void Unref() {
- if (ref_ == nullptr) return;
- if (ref_->Unref()) {
- dest_fn_(destroy_fn_arg_);
- }
- }
-
- grpc_slice_refcount* sub_refcount() const { return sub_refcount_; }
-
- private:
- grpc_core::RefCount* ref_ = nullptr;
- const Type ref_type_ = Type::REGULAR;
- grpc_slice_refcount* sub_refcount_ = this;
- DestroyerFn dest_fn_ = nullptr;
- void* destroy_fn_arg_ = nullptr;
-};
-
-namespace grpc_core {
-
-struct StaticSliceRefcount {
- static grpc_slice_refcount kStaticSubRefcount;
-
- StaticSliceRefcount(uint32_t index)
- : base(&kStaticSubRefcount, grpc_slice_refcount::Type::STATIC),
- index(index) {}
-
- grpc_slice_refcount base;
- const uint32_t index;
-};
-
-extern grpc_slice_refcount kNoopRefcount;
-
-struct InternedSliceRefcount {
- static void Destroy(void* arg) {
- auto* rc = static_cast<InternedSliceRefcount*>(arg);
- rc->~InternedSliceRefcount();
- gpr_free(rc);
- }
-
- InternedSliceRefcount(size_t length, uint32_t hash,
- InternedSliceRefcount* bucket_next)
- : base(grpc_slice_refcount::Type::INTERNED, &refcnt, Destroy, this, &sub),
- sub(grpc_slice_refcount::Type::REGULAR, &refcnt, Destroy, this, &sub),
- length(length),
- hash(hash),
- bucket_next(bucket_next) {}
-
- ~InternedSliceRefcount();
-
- grpc_slice_refcount base;
- grpc_slice_refcount sub;
- const size_t length;
- RefCount refcnt;
- const uint32_t hash;
- InternedSliceRefcount* bucket_next;
-};
-
-} // namespace grpc_core
-
-inline size_t grpc_refcounted_slice_length(const grpc_slice& slice) {
- GPR_DEBUG_ASSERT(slice.refcount != nullptr);
- return slice.data.refcounted.length;
-}
-
-inline const uint8_t* grpc_refcounted_slice_data(const grpc_slice& slice) {
- GPR_DEBUG_ASSERT(slice.refcount != nullptr);
- return slice.data.refcounted.bytes;
-}
-
-inline int grpc_slice_refcount::Eq(const grpc_slice& a, const grpc_slice& b) {
- GPR_DEBUG_ASSERT(a.refcount != nullptr);
- GPR_DEBUG_ASSERT(a.refcount == this);
- switch (ref_type_) {
- case Type::STATIC:
- GPR_DEBUG_ASSERT(
- (GRPC_STATIC_METADATA_INDEX(a) == GRPC_STATIC_METADATA_INDEX(b)) ==
- (a.refcount == b.refcount));
- case Type::INTERNED:
- return a.refcount == b.refcount;
- case Type::NOP:
- case Type::REGULAR:
- break;
- }
- if (grpc_refcounted_slice_length(a) != GRPC_SLICE_LENGTH(b)) return false;
- if (grpc_refcounted_slice_length(a) == 0) return true;
- return 0 == memcmp(grpc_refcounted_slice_data(a), GRPC_SLICE_START_PTR(b),
- grpc_refcounted_slice_length(a));
-}
-
-inline uint32_t grpc_slice_refcount::Hash(const grpc_slice& slice) {
- GPR_DEBUG_ASSERT(slice.refcount != nullptr);
- GPR_DEBUG_ASSERT(slice.refcount == this);
- switch (ref_type_) {
- case Type::STATIC:
- return ::grpc_static_metadata_hash_values[GRPC_STATIC_METADATA_INDEX(
- slice)];
- case Type::INTERNED:
- return reinterpret_cast<grpc_core::InternedSliceRefcount*>(slice.refcount)
- ->hash;
- case Type::NOP:
- case Type::REGULAR:
- break;
- }
- return gpr_murmur_hash3(grpc_refcounted_slice_data(slice),
- grpc_refcounted_slice_length(slice),
- grpc_core::g_hash_seed);
-}
-
-inline const grpc_slice& grpc_slice_ref_internal(const grpc_slice& slice) {
- if (slice.refcount) {
- slice.refcount->Ref();
- }
- return slice;
-}
-
-inline void grpc_slice_unref_internal(const grpc_slice& slice) {
- if (slice.refcount) {
- slice.refcount->Unref();
- }
-}
-
+#include <string.h>
+
+#include "src/core/lib/gpr/murmur_hash.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+// Interned slices have specific fast-path operations for hashing. To inline
+// these operations, we need to forward declare them here.
+extern uint32_t grpc_static_metadata_hash_values[GRPC_STATIC_MDSTR_COUNT];
+
+// grpc_slice_refcount : A reference count for grpc_slice.
+//
+// Non-inlined grpc_slice objects are refcounted. Historically this was
+// implemented via grpc_slice_refcount, a C-style polymorphic class using a
+// manually managed vtable of operations. Subclasses would define their own
+// vtable; the 'virtual' methods (ref, unref, equals and hash) would simply call
+// the function pointers in the vtable as necessary.
+//
+// Unfortunately, this leads to some inefficiencies in the generated code that
+// can be improved upon. For example, equality checking for interned slices is a
+// simple equality check on the refcount pointer. With the vtable approach, this
+// would translate to roughly the following (high-level) instructions:
+//
+// grpc_slice_equals(slice1, slice2):
+// load vtable->eq -> eq_func
+// call eq_func(slice1, slice2)
+//
+// interned_slice_equals(slice1, slice2)
+// load slice1.ref -> r1
+// load slice2.ref -> r2
+// cmp r1, r2 -> retval
+// ret retval
+//
+// This leads to a function call for a function defined in another translation
+// unit, which imposes memory barriers, which reduces the compiler's ability to
+// optimize (in addition to the added overhead of call/ret). Additionally, it
+// may be harder to reason about branch prediction when we're jumping to
+// essentially arbitrarily provided function pointers.
+//
+// In addition, it is arguable that while virtualization was helpful for
+// Equals()/Hash() methods, that it was fundamentally unnecessary for
+// Ref()/Unref().
+//
+// Instead, grpc_slice_refcount provides the same functionality as the C-style
+// virtual class, but in a de-virtualized manner - Eq(), Hash(), Ref() and
+// Unref() are provided within this header file. Fastpaths for Eq()/Hash()
+// (interned and static metadata slices), as well as the Ref() operation, can
+// all be inlined without any memory barriers.
+//
+// It does this by:
+// 1. Using grpc_core::RefCount<> (header-only) for Ref/Unref. Two special cases
+// need support: No-op ref/unref (eg. static metadata slices) and stream
+// slice references (where all the slices share the streamref). This is in
+// addition to the normal case of '1 slice, 1 ref'.
+// To support these cases, we explicitly track a nullable pointer to the
+// underlying RefCount<>. No-op ref/unref is used by checking the pointer for
+// null, and doing nothing if it is. Both stream slice refs and 'normal'
+// slices use the same path for Ref/Unref (by targeting the non-null
+// pointer).
+//
+// 2. introducing the notion of grpc_slice_refcount::Type. This describes if a
+// slice ref is used by a static metadata slice, an interned slice, or other
+// slices. We switch on the slice ref type in order to provide fastpaths for
+// Equals() and Hash().
+//
+// In total, this saves us roughly 1-2% latency for unary calls, with smaller
+// calls benefitting. The effect is present, but not as useful, for larger calls
+// where the cost of sending the data dominates.
+// TODO(arjunroy): Investigate if this can be removed with strongly typed
+// grpc_slices.
+struct grpc_slice_refcount {
+ public:
+ enum class Type {
+ STATIC, // Refcount for a static metadata slice.
+ INTERNED, // Refcount for an interned slice.
+ NOP, // No-Op
+ REGULAR // Refcount for non-static-metadata, non-interned slices.
+ };
+ typedef void (*DestroyerFn)(void*);
+
+ grpc_slice_refcount() = default;
+
+ explicit grpc_slice_refcount(Type t) : ref_type_(t) {}
+
+ explicit grpc_slice_refcount(grpc_slice_refcount* sub) : sub_refcount_(sub) {}
+ // Regular constructor for grpc_slice_refcount.
+ //
+ // Parameters:
+ // 1. grpc_slice_refcount::Type type
+ // Whether we are the refcount for a static
+ // metadata slice, an interned slice, or any other kind of slice.
+ //
+ // 2. RefCount* ref
+ // The pointer to the actual underlying grpc_core::RefCount. Rather than
+ // performing struct offset computations as in the original implementation to
+ // get to the refcount, which requires a virtual method, we devirtualize by
+ // using a nullable pointer to allow a single pair of Ref/Unref methods.
+ //
+ // 3. DestroyerFn destroyer_fn
+ // Called when the refcount goes to 0, with destroyer_arg as parameter.
+ //
+ // 4. void* destroyer_arg
+ // Argument for the virtualized destructor.
+ //
+ // 5. grpc_slice_refcount* sub
+ // Argument used for interned slices.
+ grpc_slice_refcount(grpc_slice_refcount::Type type, grpc_core::RefCount* ref,
+ DestroyerFn destroyer_fn, void* destroyer_arg,
+ grpc_slice_refcount* sub)
+ : ref_(ref),
+ ref_type_(type),
+ sub_refcount_(sub),
+ dest_fn_(destroyer_fn),
+ destroy_fn_arg_(destroyer_arg) {}
+ // Initializer for static refcounts.
+ grpc_slice_refcount(grpc_slice_refcount* sub, Type type)
+ : ref_type_(type), sub_refcount_(sub) {}
+
+ Type GetType() const { return ref_type_; }
+
+ int Eq(const grpc_slice& a, const grpc_slice& b);
+
+ uint32_t Hash(const grpc_slice& slice);
+ void Ref() {
+ if (ref_ == nullptr) return;
+ ref_->RefNonZero();
+ }
+ void Unref() {
+ if (ref_ == nullptr) return;
+ if (ref_->Unref()) {
+ dest_fn_(destroy_fn_arg_);
+ }
+ }
+
+ grpc_slice_refcount* sub_refcount() const { return sub_refcount_; }
+
+ private:
+ grpc_core::RefCount* ref_ = nullptr;
+ const Type ref_type_ = Type::REGULAR;
+ grpc_slice_refcount* sub_refcount_ = this;
+ DestroyerFn dest_fn_ = nullptr;
+ void* destroy_fn_arg_ = nullptr;
+};
+
+namespace grpc_core {
+
+struct StaticSliceRefcount {
+ static grpc_slice_refcount kStaticSubRefcount;
+
+ StaticSliceRefcount(uint32_t index)
+ : base(&kStaticSubRefcount, grpc_slice_refcount::Type::STATIC),
+ index(index) {}
+
+ grpc_slice_refcount base;
+ const uint32_t index;
+};
+
+extern grpc_slice_refcount kNoopRefcount;
+
+struct InternedSliceRefcount {
+ static void Destroy(void* arg) {
+ auto* rc = static_cast<InternedSliceRefcount*>(arg);
+ rc->~InternedSliceRefcount();
+ gpr_free(rc);
+ }
+
+ InternedSliceRefcount(size_t length, uint32_t hash,
+ InternedSliceRefcount* bucket_next)
+ : base(grpc_slice_refcount::Type::INTERNED, &refcnt, Destroy, this, &sub),
+ sub(grpc_slice_refcount::Type::REGULAR, &refcnt, Destroy, this, &sub),
+ length(length),
+ hash(hash),
+ bucket_next(bucket_next) {}
+
+ ~InternedSliceRefcount();
+
+ grpc_slice_refcount base;
+ grpc_slice_refcount sub;
+ const size_t length;
+ RefCount refcnt;
+ const uint32_t hash;
+ InternedSliceRefcount* bucket_next;
+};
+
+} // namespace grpc_core
+
+inline size_t grpc_refcounted_slice_length(const grpc_slice& slice) {
+ GPR_DEBUG_ASSERT(slice.refcount != nullptr);
+ return slice.data.refcounted.length;
+}
+
+inline const uint8_t* grpc_refcounted_slice_data(const grpc_slice& slice) {
+ GPR_DEBUG_ASSERT(slice.refcount != nullptr);
+ return slice.data.refcounted.bytes;
+}
+
+inline int grpc_slice_refcount::Eq(const grpc_slice& a, const grpc_slice& b) {
+ GPR_DEBUG_ASSERT(a.refcount != nullptr);
+ GPR_DEBUG_ASSERT(a.refcount == this);
+ switch (ref_type_) {
+ case Type::STATIC:
+ GPR_DEBUG_ASSERT(
+ (GRPC_STATIC_METADATA_INDEX(a) == GRPC_STATIC_METADATA_INDEX(b)) ==
+ (a.refcount == b.refcount));
+ case Type::INTERNED:
+ return a.refcount == b.refcount;
+ case Type::NOP:
+ case Type::REGULAR:
+ break;
+ }
+ if (grpc_refcounted_slice_length(a) != GRPC_SLICE_LENGTH(b)) return false;
+ if (grpc_refcounted_slice_length(a) == 0) return true;
+ return 0 == memcmp(grpc_refcounted_slice_data(a), GRPC_SLICE_START_PTR(b),
+ grpc_refcounted_slice_length(a));
+}
+
+inline uint32_t grpc_slice_refcount::Hash(const grpc_slice& slice) {
+ GPR_DEBUG_ASSERT(slice.refcount != nullptr);
+ GPR_DEBUG_ASSERT(slice.refcount == this);
+ switch (ref_type_) {
+ case Type::STATIC:
+ return ::grpc_static_metadata_hash_values[GRPC_STATIC_METADATA_INDEX(
+ slice)];
+ case Type::INTERNED:
+ return reinterpret_cast<grpc_core::InternedSliceRefcount*>(slice.refcount)
+ ->hash;
+ case Type::NOP:
+ case Type::REGULAR:
+ break;
+ }
+ return gpr_murmur_hash3(grpc_refcounted_slice_data(slice),
+ grpc_refcounted_slice_length(slice),
+ grpc_core::g_hash_seed);
+}
+
+inline const grpc_slice& grpc_slice_ref_internal(const grpc_slice& slice) {
+ if (slice.refcount) {
+ slice.refcount->Ref();
+ }
+ return slice;
+}
+
+inline void grpc_slice_unref_internal(const grpc_slice& slice) {
+ if (slice.refcount) {
+ slice.refcount->Unref();
+ }
+}
+
void grpc_slice_buffer_reset_and_unref_internal(grpc_slice_buffer* sb);
void grpc_slice_buffer_partial_unref_internal(grpc_slice_buffer* sb,
size_t idx);
void grpc_slice_buffer_destroy_internal(grpc_slice_buffer* sb);
-// Returns a pointer to the first slice in the slice buffer without giving
-// ownership to or a reference count on that slice.
-inline grpc_slice* grpc_slice_buffer_peek_first(grpc_slice_buffer* sb) {
- GPR_DEBUG_ASSERT(sb->count > 0);
- return &sb->slices[0];
-}
-
-// Removes the first slice from the slice buffer.
-void grpc_slice_buffer_remove_first(grpc_slice_buffer* sb);
-
-// Calls grpc_slice_sub with the given parameters on the first slice.
-void grpc_slice_buffer_sub_first(grpc_slice_buffer* sb, size_t begin,
- size_t end);
-
+// Returns a pointer to the first slice in the slice buffer without giving
+// ownership to or a reference count on that slice.
+inline grpc_slice* grpc_slice_buffer_peek_first(grpc_slice_buffer* sb) {
+ GPR_DEBUG_ASSERT(sb->count > 0);
+ return &sb->slices[0];
+}
+
+// Removes the first slice from the slice buffer.
+void grpc_slice_buffer_remove_first(grpc_slice_buffer* sb);
+
+// Calls grpc_slice_sub with the given parameters on the first slice.
+void grpc_slice_buffer_sub_first(grpc_slice_buffer* sb, size_t begin,
+ size_t end);
+
/* Check if a slice is interned */
-bool grpc_slice_is_interned(const grpc_slice& slice);
-inline bool grpc_slice_is_interned(const grpc_slice& slice) {
- return (slice.refcount &&
- (slice.refcount->GetType() == grpc_slice_refcount::Type::INTERNED ||
- slice.refcount->GetType() == grpc_slice_refcount::Type::STATIC));
-}
-
-inline bool grpc_slice_static_interned_equal(const grpc_slice& a,
- const grpc_slice& b) {
- GPR_DEBUG_ASSERT(grpc_slice_is_interned(a) && grpc_slice_is_interned(b));
- return a.refcount == b.refcount;
-}
-
+bool grpc_slice_is_interned(const grpc_slice& slice);
+inline bool grpc_slice_is_interned(const grpc_slice& slice) {
+ return (slice.refcount &&
+ (slice.refcount->GetType() == grpc_slice_refcount::Type::INTERNED ||
+ slice.refcount->GetType() == grpc_slice_refcount::Type::STATIC));
+}
+
+inline bool grpc_slice_static_interned_equal(const grpc_slice& a,
+ const grpc_slice& b) {
+ GPR_DEBUG_ASSERT(grpc_slice_is_interned(a) && grpc_slice_is_interned(b));
+ return a.refcount == b.refcount;
+}
+
void grpc_slice_intern_init(void);
void grpc_slice_intern_shutdown(void);
void grpc_test_only_set_slice_hash_seed(uint32_t key);
@@ -320,34 +320,34 @@ grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
uint32_t grpc_static_slice_hash(grpc_slice s);
int grpc_static_slice_eq(grpc_slice a, grpc_slice b);
-inline uint32_t grpc_slice_hash_refcounted(const grpc_slice& s) {
- GPR_DEBUG_ASSERT(s.refcount != nullptr);
- return s.refcount->Hash(s);
-}
-
-inline uint32_t grpc_slice_default_hash_internal(const grpc_slice& s) {
- return gpr_murmur_hash3(GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s),
- grpc_core::g_hash_seed);
-}
-
-inline uint32_t grpc_slice_hash_internal(const grpc_slice& s) {
- return s.refcount == nullptr ? grpc_slice_default_hash_internal(s)
- : grpc_slice_hash_refcounted(s);
-}
-
-grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
- size_t len);
-grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p);
+inline uint32_t grpc_slice_hash_refcounted(const grpc_slice& s) {
+ GPR_DEBUG_ASSERT(s.refcount != nullptr);
+ return s.refcount->Hash(s);
+}
+
+inline uint32_t grpc_slice_default_hash_internal(const grpc_slice& s) {
+ return gpr_murmur_hash3(GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s),
+ grpc_core::g_hash_seed);
+}
+
+inline uint32_t grpc_slice_hash_internal(const grpc_slice& s) {
+ return s.refcount == nullptr ? grpc_slice_default_hash_internal(s)
+ : grpc_slice_hash_refcounted(s);
+}
+
+grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
+ size_t len);
+grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p);
grpc_slice grpc_slice_from_cpp_string(TString str);
-
+
// Returns the memory used by this slice, not counting the slice structure
// itself. This means that inlined and slices from static strings will return
// 0. All other slices will return the size of the allocated chars.
size_t grpc_slice_memory_usage(grpc_slice s);
-grpc_core::UnmanagedMemorySlice grpc_slice_sub_no_ref(
- const grpc_core::UnmanagedMemorySlice& source, size_t begin, size_t end);
-
+grpc_core::UnmanagedMemorySlice grpc_slice_sub_no_ref(
+ const grpc_core::UnmanagedMemorySlice& source, size_t begin, size_t end);
+
namespace grpc_core {
struct SliceHash {
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.cc b/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.cc
index 7887e0305f..4a58e861df 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.cc
@@ -25,22 +25,22 @@
#include <grpc/support/log.h>
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/slice/slice_internal.h"
-char* grpc_dump_slice(const grpc_slice& s, uint32_t flags) {
+char* grpc_dump_slice(const grpc_slice& s, uint32_t flags) {
return gpr_dump(reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s),
GRPC_SLICE_LENGTH(s), flags);
}
-grpc_slice grpc_dump_slice_to_slice(const grpc_slice& s, uint32_t flags) {
- size_t len;
- grpc_core::UniquePtr<char> ptr(
- gpr_dump_return_len(reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s),
- GRPC_SLICE_LENGTH(s), flags, &len));
- return grpc_slice_from_moved_buffer(std::move(ptr), len);
-}
-
+grpc_slice grpc_dump_slice_to_slice(const grpc_slice& s, uint32_t flags) {
+ size_t len;
+ grpc_core::UniquePtr<char> ptr(
+ gpr_dump_return_len(reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s),
+ GRPC_SLICE_LENGTH(s), flags, &len));
+ return grpc_slice_from_moved_buffer(std::move(ptr), len);
+}
+
/** Finds the initial (\a begin) and final (\a end) offsets of the next
* substring from \a str + \a read_offset until the next \a sep or the end of \a
* str.
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.h b/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.h
index 6551a6df75..eb54f69cd5 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.h
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.h
@@ -30,9 +30,9 @@
#include "src/core/lib/gpr/string.h"
/* Calls gpr_dump on a slice. */
-char* grpc_dump_slice(const grpc_slice& slice, uint32_t flags);
-/* Calls gpr_dump on a slice and returns the result as a slice. */
-grpc_slice grpc_dump_slice_to_slice(const grpc_slice& slice, uint32_t flags);
+char* grpc_dump_slice(const grpc_slice& slice, uint32_t flags);
+/* Calls gpr_dump on a slice and returns the result as a slice. */
+grpc_slice grpc_dump_slice_to_slice(const grpc_slice& slice, uint32_t flags);
/** Split \a str by the separator \a sep. Results are stored in \a dst, which
* should be a properly initialized instance. */
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_traits.h b/contrib/libs/grpc/src/core/lib/slice/slice_traits.h
index 07d13cd8b5..94b091907b 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_traits.h
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_traits.h
@@ -24,8 +24,8 @@
#include <grpc/slice.h>
#include <stdbool.h>
-bool grpc_slice_is_legal_header(const grpc_slice& s);
-bool grpc_slice_is_legal_nonbin_header(const grpc_slice& s);
-bool grpc_slice_is_bin_suffixed(const grpc_slice& s);
+bool grpc_slice_is_legal_header(const grpc_slice& s);
+bool grpc_slice_is_legal_nonbin_header(const grpc_slice& s);
+bool grpc_slice_is_bin_suffixed(const grpc_slice& s);
#endif /* GRPC_CORE_LIB_SLICE_SLICE_TRAITS_H */
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_utils.h b/contrib/libs/grpc/src/core/lib/slice/slice_utils.h
index 95cef73a4f..ba6825561c 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_utils.h
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_utils.h
@@ -1,193 +1,193 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_CORE_LIB_SLICE_SLICE_UTILS_H
-#define GRPC_CORE_LIB_SLICE_SLICE_UTILS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <cstring>
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SLICE_SLICE_UTILS_H
+#define GRPC_CORE_LIB_SLICE_SLICE_UTILS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <cstring>
+
#include "y_absl/strings/string_view.h"
-#include <grpc/slice.h>
-
-#include "src/core/lib/gpr/murmur_hash.h"
-
-namespace grpc_core {
-extern uint32_t g_hash_seed;
-} // namespace grpc_core
-
-// When we compare two slices, and we know the latter is not inlined, we can
-// short circuit our comparison operator. We specifically use differs()
-// semantics instead of equals() semantics due to more favourable code
-// generation when using differs(). Specifically, we may use the output of
-// grpc_slice_differs_refcounted for control flow. If we use differs()
-// semantics, we end with a tailcall to memcmp(). If we use equals() semantics,
-// we need to invert the result that memcmp provides us, which costs several
-// instructions to do so. If we're using the result for control flow (i.e.
-// branching based on the output) then we're just performing the extra
-// operations to invert the result pointlessly. Concretely, we save 6 ops on
-// x86-64/clang with differs().
-int grpc_slice_differs_refcounted(const grpc_slice& a,
- const grpc_slice& b_not_inline);
-
-// When we compare two slices, and we *know* that one of them is static or
-// interned, we can short circuit our slice equality function. The second slice
-// here must be static or interned; slice a can be any slice, inlined or not.
-inline bool grpc_slice_eq_static_interned(const grpc_slice& a,
- const grpc_slice& b_static_interned) {
- if (a.refcount == b_static_interned.refcount) {
- return true;
- }
- return !grpc_slice_differs_refcounted(a, b_static_interned);
-}
-
-// TODO(arjunroy): These type declarations ought to be in
-// src/core/lib/slice/slice_internal.h instead; they are here due to a circular
-// header depedency between slice_internal.h and
-// src/core/lib/transport/metadata.h. We need to fix this circular reference and
-// when we do, move these type declarations.
-//
-// Internal slice type declarations.
-// Externally, a grpc_slice is a grpc_slice is a grpc_slice.
-// Internally, we may have heap allocated slices, static slices, interned
-// slices, and inlined slices. If we know the specific type of slice
-// we're dealing with, we can save cycles (e.g. fast-paths when we know we don't
-// need to take a reference on a slice). Rather than introducing new methods
-// ad-hoc in these cases, we rely on type-system backed overloads to keep
-// internal APIs clean.
-//
-// For each overload, the definition and layout of the underlying slice does not
-// change; this is purely type-system information.
-namespace grpc_core {
-
-// There are two main types of slices: those that have their memory
-// managed by the slice library and those that do not.
-//
-// The following types of slices are not managed:
-// - inlined slices (i.e., refcount is null)
-// - slices that have a custom refcount type (i.e., not STATIC or INTERNED)
-// - slices where the memory is managed by some external agent. The slice is not
-// ref-counted by grpc, and the programmer is responsible for ensuring the
-// data is valid for the duration of the period that grpc may access it.
-//
-// The following types of slices are managed:
-// - static metadata slices (i.e., refcount type is STATIC)
-// - interned slices (i.e., refcount type is INTERNED)
-//
-// This categorization is reflected in the following hierarchy:
-//
-// - grpc_slice
-// > - UnmanagedMemorySlice
-// > - ExternallyManagedSlice
-// - ManagedMemorySlice
-// > - InternedSlice
-// - StaticMetadataSlice
-//
-struct ManagedMemorySlice : public grpc_slice {
- ManagedMemorySlice() {
- refcount = nullptr;
- data.refcounted.bytes = nullptr;
- data.refcounted.length = 0;
- }
- explicit ManagedMemorySlice(const char* string);
- ManagedMemorySlice(const char* buf, size_t len);
- explicit ManagedMemorySlice(const grpc_slice* slice);
- bool operator==(const grpc_slice& other) const {
- if (refcount == other.refcount) {
- return true;
- }
- return !grpc_slice_differs_refcounted(other, *this);
- }
- bool operator!=(const grpc_slice& other) const { return !(*this == other); }
- bool operator==(std::pair<const char*, size_t> buflen) const {
- return data.refcounted.length == buflen.second && buflen.first != nullptr &&
- memcmp(buflen.first, data.refcounted.bytes, buflen.second) == 0;
- }
-};
-struct UnmanagedMemorySlice : public grpc_slice {
- // TODO(arjunroy): Can we use a default=false param instead of this enum?
- enum class ForceHeapAllocation {};
- UnmanagedMemorySlice() {
- refcount = nullptr;
- data.inlined.length = 0;
- }
- explicit UnmanagedMemorySlice(const char* source);
- UnmanagedMemorySlice(const char* source, size_t length);
- // The first constructor creates a slice that may be heap allocated, or
- // inlined in the slice structure if length is small enough
- // (< GRPC_SLICE_INLINED_SIZE). The second constructor forces heap alloc.
- explicit UnmanagedMemorySlice(size_t length);
- explicit UnmanagedMemorySlice(size_t length, const ForceHeapAllocation&) {
- HeapInit(length);
- }
-
- private:
- void HeapInit(size_t length);
-};
-
-extern grpc_slice_refcount kNoopRefcount;
-
-struct ExternallyManagedSlice : public UnmanagedMemorySlice {
- ExternallyManagedSlice()
- : ExternallyManagedSlice(&kNoopRefcount, 0, nullptr) {}
- explicit ExternallyManagedSlice(const char* s)
- : ExternallyManagedSlice(s, strlen(s)) {}
- ExternallyManagedSlice(const void* s, size_t len)
- : ExternallyManagedSlice(
- &kNoopRefcount, len,
- reinterpret_cast<uint8_t*>(const_cast<void*>(s))) {}
- ExternallyManagedSlice(grpc_slice_refcount* ref, size_t length,
- uint8_t* bytes) {
- refcount = ref;
- data.refcounted.length = length;
- data.refcounted.bytes = bytes;
- }
- bool operator==(const grpc_slice& other) const {
- return data.refcounted.length == GRPC_SLICE_LENGTH(other) &&
- memcmp(data.refcounted.bytes, GRPC_SLICE_START_PTR(other),
- data.refcounted.length) == 0;
- }
- bool operator!=(const grpc_slice& other) const { return !(*this == other); }
- uint32_t Hash() {
- return gpr_murmur_hash3(data.refcounted.bytes, data.refcounted.length,
- g_hash_seed);
- }
-};
-
-struct StaticMetadataSlice : public ManagedMemorySlice {
- StaticMetadataSlice(grpc_slice_refcount* ref, size_t length,
- const uint8_t* bytes) {
- refcount = ref;
- data.refcounted.length = length;
- // NB: grpc_slice may or may not point to a static slice, but we are
- // definitely pointing to static data here. Since we are not changing
- // the underlying C-type, we need a const_cast here.
- data.refcounted.bytes = const_cast<uint8_t*>(bytes);
- }
-};
-
-struct InternedSliceRefcount;
-struct InternedSlice : public ManagedMemorySlice {
- explicit InternedSlice(InternedSliceRefcount* s);
-};
-
+#include <grpc/slice.h>
+
+#include "src/core/lib/gpr/murmur_hash.h"
+
+namespace grpc_core {
+extern uint32_t g_hash_seed;
+} // namespace grpc_core
+
+// When we compare two slices, and we know the latter is not inlined, we can
+// short circuit our comparison operator. We specifically use differs()
+// semantics instead of equals() semantics due to more favourable code
+// generation when using differs(). Specifically, we may use the output of
+// grpc_slice_differs_refcounted for control flow. If we use differs()
+// semantics, we end with a tailcall to memcmp(). If we use equals() semantics,
+// we need to invert the result that memcmp provides us, which costs several
+// instructions to do so. If we're using the result for control flow (i.e.
+// branching based on the output) then we're just performing the extra
+// operations to invert the result pointlessly. Concretely, we save 6 ops on
+// x86-64/clang with differs().
+int grpc_slice_differs_refcounted(const grpc_slice& a,
+ const grpc_slice& b_not_inline);
+
+// When we compare two slices, and we *know* that one of them is static or
+// interned, we can short circuit our slice equality function. The second slice
+// here must be static or interned; slice a can be any slice, inlined or not.
+inline bool grpc_slice_eq_static_interned(const grpc_slice& a,
+ const grpc_slice& b_static_interned) {
+ if (a.refcount == b_static_interned.refcount) {
+ return true;
+ }
+ return !grpc_slice_differs_refcounted(a, b_static_interned);
+}
+
+// TODO(arjunroy): These type declarations ought to be in
+// src/core/lib/slice/slice_internal.h instead; they are here due to a circular
+// header depedency between slice_internal.h and
+// src/core/lib/transport/metadata.h. We need to fix this circular reference and
+// when we do, move these type declarations.
+//
+// Internal slice type declarations.
+// Externally, a grpc_slice is a grpc_slice is a grpc_slice.
+// Internally, we may have heap allocated slices, static slices, interned
+// slices, and inlined slices. If we know the specific type of slice
+// we're dealing with, we can save cycles (e.g. fast-paths when we know we don't
+// need to take a reference on a slice). Rather than introducing new methods
+// ad-hoc in these cases, we rely on type-system backed overloads to keep
+// internal APIs clean.
+//
+// For each overload, the definition and layout of the underlying slice does not
+// change; this is purely type-system information.
+namespace grpc_core {
+
+// There are two main types of slices: those that have their memory
+// managed by the slice library and those that do not.
+//
+// The following types of slices are not managed:
+// - inlined slices (i.e., refcount is null)
+// - slices that have a custom refcount type (i.e., not STATIC or INTERNED)
+// - slices where the memory is managed by some external agent. The slice is not
+// ref-counted by grpc, and the programmer is responsible for ensuring the
+// data is valid for the duration of the period that grpc may access it.
+//
+// The following types of slices are managed:
+// - static metadata slices (i.e., refcount type is STATIC)
+// - interned slices (i.e., refcount type is INTERNED)
+//
+// This categorization is reflected in the following hierarchy:
+//
+// - grpc_slice
+// > - UnmanagedMemorySlice
+// > - ExternallyManagedSlice
+// - ManagedMemorySlice
+// > - InternedSlice
+// - StaticMetadataSlice
+//
+struct ManagedMemorySlice : public grpc_slice {
+ ManagedMemorySlice() {
+ refcount = nullptr;
+ data.refcounted.bytes = nullptr;
+ data.refcounted.length = 0;
+ }
+ explicit ManagedMemorySlice(const char* string);
+ ManagedMemorySlice(const char* buf, size_t len);
+ explicit ManagedMemorySlice(const grpc_slice* slice);
+ bool operator==(const grpc_slice& other) const {
+ if (refcount == other.refcount) {
+ return true;
+ }
+ return !grpc_slice_differs_refcounted(other, *this);
+ }
+ bool operator!=(const grpc_slice& other) const { return !(*this == other); }
+ bool operator==(std::pair<const char*, size_t> buflen) const {
+ return data.refcounted.length == buflen.second && buflen.first != nullptr &&
+ memcmp(buflen.first, data.refcounted.bytes, buflen.second) == 0;
+ }
+};
+struct UnmanagedMemorySlice : public grpc_slice {
+ // TODO(arjunroy): Can we use a default=false param instead of this enum?
+ enum class ForceHeapAllocation {};
+ UnmanagedMemorySlice() {
+ refcount = nullptr;
+ data.inlined.length = 0;
+ }
+ explicit UnmanagedMemorySlice(const char* source);
+ UnmanagedMemorySlice(const char* source, size_t length);
+ // The first constructor creates a slice that may be heap allocated, or
+ // inlined in the slice structure if length is small enough
+ // (< GRPC_SLICE_INLINED_SIZE). The second constructor forces heap alloc.
+ explicit UnmanagedMemorySlice(size_t length);
+ explicit UnmanagedMemorySlice(size_t length, const ForceHeapAllocation&) {
+ HeapInit(length);
+ }
+
+ private:
+ void HeapInit(size_t length);
+};
+
+extern grpc_slice_refcount kNoopRefcount;
+
+struct ExternallyManagedSlice : public UnmanagedMemorySlice {
+ ExternallyManagedSlice()
+ : ExternallyManagedSlice(&kNoopRefcount, 0, nullptr) {}
+ explicit ExternallyManagedSlice(const char* s)
+ : ExternallyManagedSlice(s, strlen(s)) {}
+ ExternallyManagedSlice(const void* s, size_t len)
+ : ExternallyManagedSlice(
+ &kNoopRefcount, len,
+ reinterpret_cast<uint8_t*>(const_cast<void*>(s))) {}
+ ExternallyManagedSlice(grpc_slice_refcount* ref, size_t length,
+ uint8_t* bytes) {
+ refcount = ref;
+ data.refcounted.length = length;
+ data.refcounted.bytes = bytes;
+ }
+ bool operator==(const grpc_slice& other) const {
+ return data.refcounted.length == GRPC_SLICE_LENGTH(other) &&
+ memcmp(data.refcounted.bytes, GRPC_SLICE_START_PTR(other),
+ data.refcounted.length) == 0;
+ }
+ bool operator!=(const grpc_slice& other) const { return !(*this == other); }
+ uint32_t Hash() {
+ return gpr_murmur_hash3(data.refcounted.bytes, data.refcounted.length,
+ g_hash_seed);
+ }
+};
+
+struct StaticMetadataSlice : public ManagedMemorySlice {
+ StaticMetadataSlice(grpc_slice_refcount* ref, size_t length,
+ const uint8_t* bytes) {
+ refcount = ref;
+ data.refcounted.length = length;
+ // NB: grpc_slice may or may not point to a static slice, but we are
+ // definitely pointing to static data here. Since we are not changing
+ // the underlying C-type, we need a const_cast here.
+ data.refcounted.bytes = const_cast<uint8_t*>(bytes);
+ }
+};
+
+struct InternedSliceRefcount;
+struct InternedSlice : public ManagedMemorySlice {
+ explicit InternedSlice(InternedSliceRefcount* s);
+};
+
// Converts grpc_slice to y_absl::string_view.
inline y_absl::string_view StringViewFromSlice(const grpc_slice& slice) {
return y_absl::string_view(
@@ -195,6 +195,6 @@ inline y_absl::string_view StringViewFromSlice(const grpc_slice& slice) {
GRPC_SLICE_LENGTH(slice));
}
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_SLICE_SLICE_UTILS_H */
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_SLICE_SLICE_UTILS_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/api_trace.h b/contrib/libs/grpc/src/core/lib/surface/api_trace.h
index 51d1f52223..a4f6358801 100644
--- a/contrib/libs/grpc/src/core/lib/surface/api_trace.h
+++ b/contrib/libs/grpc/src/core/lib/surface/api_trace.h
@@ -45,7 +45,7 @@ extern grpc_core::TraceFlag grpc_api_trace;
/* Due to the limitations of C89's preprocessor, the arity of the var-arg list
'nargs' must be specified. */
#define GRPC_API_TRACE(fmt, nargs, args) \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) { \
gpr_log(GPR_INFO, fmt GRPC_API_TRACE_UNWRAP##nargs args); \
}
diff --git a/contrib/libs/grpc/src/core/lib/surface/byte_buffer_reader.cc b/contrib/libs/grpc/src/core/lib/surface/byte_buffer_reader.cc
index 3689c79455..ed110f4c92 100644
--- a/contrib/libs/grpc/src/core/lib/surface/byte_buffer_reader.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/byte_buffer_reader.cc
@@ -46,23 +46,23 @@ void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader* reader) {
reader->buffer_out = nullptr;
}
-int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
- grpc_slice** slice) {
- switch (reader->buffer_in->type) {
- case GRPC_BB_RAW: {
- grpc_slice_buffer* slice_buffer;
- slice_buffer = &reader->buffer_out->data.raw.slice_buffer;
- if (reader->current.index < slice_buffer->count) {
- *slice = &slice_buffer->slices[reader->current.index];
- reader->current.index += 1;
- return 1;
- }
- break;
- }
- }
- return 0;
-}
-
+int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
+ grpc_slice** slice) {
+ switch (reader->buffer_in->type) {
+ case GRPC_BB_RAW: {
+ grpc_slice_buffer* slice_buffer;
+ slice_buffer = &reader->buffer_out->data.raw.slice_buffer;
+ if (reader->current.index < slice_buffer->count) {
+ *slice = &slice_buffer->slices[reader->current.index];
+ reader->current.index += 1;
+ return 1;
+ }
+ break;
+ }
+ }
+ return 0;
+}
+
int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader,
grpc_slice* slice) {
switch (reader->buffer_in->type) {
diff --git a/contrib/libs/grpc/src/core/lib/surface/call.cc b/contrib/libs/grpc/src/core/lib/surface/call.cc
index fe4c774c52..293bd5a226 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/call.cc
@@ -41,15 +41,15 @@
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/time_precise.h"
+#include "src/core/lib/gpr/time_precise.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/arena.h"
#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/slice/slice_utils.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/call_test_only.h"
@@ -82,7 +82,7 @@
#define ESTIMATED_MDELEM_COUNT 16
struct batch_control {
- batch_control() = default;
+ batch_control() = default;
grpc_call* call = nullptr;
grpc_transport_stream_op_batch op;
@@ -107,14 +107,14 @@ struct batch_control {
} completion_data;
grpc_closure start_batch;
grpc_closure finish_batch;
- grpc_core::Atomic<intptr_t> steps_to_complete;
+ grpc_core::Atomic<intptr_t> steps_to_complete;
gpr_atm batch_error = reinterpret_cast<gpr_atm>(GRPC_ERROR_NONE);
- void set_num_steps_to_complete(uintptr_t steps) {
- steps_to_complete.Store(steps, grpc_core::MemoryOrder::RELEASE);
- }
- bool completed_batch_step() {
- return steps_to_complete.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1;
- }
+ void set_num_steps_to_complete(uintptr_t steps) {
+ steps_to_complete.Store(steps, grpc_core::MemoryOrder::RELEASE);
+ }
+ bool completed_batch_step() {
+ return steps_to_complete.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1;
+ }
};
struct parent_call {
@@ -139,7 +139,7 @@ struct child_call {
#define RECV_INITIAL_METADATA_FIRST ((gpr_atm)1)
struct grpc_call {
- grpc_call(grpc_core::Arena* arena, const grpc_call_create_args& args)
+ grpc_call(grpc_core::Arena* arena, const grpc_call_create_args& args)
: arena(arena),
cq(args.cq),
channel(args.channel),
@@ -156,13 +156,13 @@ struct grpc_call {
gpr_free(static_cast<void*>(const_cast<char*>(final_info.error_string)));
}
- grpc_core::RefCount ext_ref;
- grpc_core::Arena* arena;
- grpc_core::CallCombiner call_combiner;
+ grpc_core::RefCount ext_ref;
+ grpc_core::Arena* arena;
+ grpc_core::CallCombiner call_combiner;
grpc_completion_queue* cq;
grpc_polling_entity pollent;
grpc_channel* channel;
- gpr_cycle_counter start_time = gpr_get_cycle_counter();
+ gpr_cycle_counter start_time = gpr_get_cycle_counter();
/* parent_call* */ gpr_atm parent_call_atm = 0;
child_call* child = nullptr;
@@ -306,13 +306,13 @@ static void add_init_error(grpc_error** composite, grpc_error* new_err) {
}
void* grpc_call_arena_alloc(grpc_call* call, size_t size) {
- return call->arena->Alloc(size);
+ return call->arena->Alloc(size);
}
static parent_call* get_or_create_parent_call(grpc_call* call) {
parent_call* p = (parent_call*)gpr_atm_acq_load(&call->parent_call_atm);
if (p == nullptr) {
- p = call->arena->New<parent_call>();
+ p = call->arena->New<parent_call>();
if (!gpr_atm_rel_cas(&call->parent_call_atm, (gpr_atm) nullptr,
(gpr_atm)p)) {
p->~parent_call();
@@ -337,23 +337,23 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args,
GRPC_CHANNEL_INTERNAL_REF(args->channel, "call");
- grpc_core::Arena* arena;
- grpc_call* call;
+ grpc_core::Arena* arena;
+ grpc_call* call;
grpc_error* error = GRPC_ERROR_NONE;
grpc_channel_stack* channel_stack =
grpc_channel_get_channel_stack(args->channel);
size_t initial_size = grpc_channel_get_call_size_estimate(args->channel);
GRPC_STATS_INC_CALL_INITIAL_SIZE(initial_size);
- size_t call_and_stack_size =
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)) +
- channel_stack->call_stack_size;
- size_t call_alloc_size =
- call_and_stack_size + (args->parent ? sizeof(child_call) : 0);
-
- std::pair<grpc_core::Arena*, void*> arena_with_call =
- grpc_core::Arena::CreateWithAlloc(initial_size, call_alloc_size);
- arena = arena_with_call.first;
- call = new (arena_with_call.second) grpc_call(arena, *args);
+ size_t call_and_stack_size =
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)) +
+ channel_stack->call_stack_size;
+ size_t call_alloc_size =
+ call_and_stack_size + (args->parent ? sizeof(child_call) : 0);
+
+ std::pair<grpc_core::Arena*, void*> arena_with_call =
+ grpc_core::Arena::CreateWithAlloc(initial_size, call_alloc_size);
+ arena = arena_with_call.first;
+ call = new (arena_with_call.second) grpc_call(arena, *args);
*out_call = call;
grpc_slice path = grpc_empty_slice();
if (call->is_client) {
@@ -365,8 +365,8 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args,
MAX_SEND_EXTRA_METADATA_COUNT);
for (size_t i = 0; i < args->add_initial_metadata_count; i++) {
call->send_extra_metadata[i].md = args->add_initial_metadata[i];
- if (grpc_slice_eq_static_interned(
- GRPC_MDKEY(args->add_initial_metadata[i]), GRPC_MDSTR_PATH)) {
+ if (grpc_slice_eq_static_interned(
+ GRPC_MDKEY(args->add_initial_metadata[i]), GRPC_MDSTR_PATH)) {
path = grpc_slice_ref_internal(
GRPC_MDVALUE(args->add_initial_metadata[i]));
}
@@ -385,8 +385,8 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args,
bool immediately_cancel = false;
if (args->parent != nullptr) {
- call->child = new (reinterpret_cast<char*>(arena_with_call.second) +
- call_and_stack_size) child_call(args->parent);
+ call->child = new (reinterpret_cast<char*>(arena_with_call.second) +
+ call_and_stack_size) child_call(args->parent);
GRPC_CALL_INTERNAL_REF(args->parent, "child");
GPR_ASSERT(call->is_client);
@@ -520,16 +520,16 @@ void grpc_call_internal_unref(grpc_call* c REF_ARG) {
GRPC_CALL_STACK_UNREF(CALL_STACK_FROM_CALL(c), REF_REASON);
}
-static void release_call(void* call, grpc_error* /*error*/) {
+static void release_call(void* call, grpc_error* /*error*/) {
grpc_call* c = static_cast<grpc_call*>(call);
grpc_channel* channel = c->channel;
- grpc_core::Arena* arena = c->arena;
+ grpc_core::Arena* arena = c->arena;
c->~grpc_call();
- grpc_channel_update_call_size_estimate(channel, arena->Destroy());
+ grpc_channel_update_call_size_estimate(channel, arena->Destroy());
GRPC_CHANNEL_INTERNAL_UNREF(channel, "call");
}
-static void destroy_call(void* call, grpc_error* /*error*/) {
+static void destroy_call(void* call, grpc_error* /*error*/) {
GPR_TIMER_SCOPE("destroy_call", 0);
size_t i;
int ii;
@@ -562,16 +562,16 @@ static void destroy_call(void* call, grpc_error* /*error*/) {
&(c->final_info.error_string));
GRPC_ERROR_UNREF(status_error);
c->final_info.stats.latency =
- gpr_cycle_counter_sub(gpr_get_cycle_counter(), c->start_time);
+ gpr_cycle_counter_sub(gpr_get_cycle_counter(), c->start_time);
grpc_call_stack_destroy(CALL_STACK_FROM_CALL(c), &c->final_info,
GRPC_CLOSURE_INIT(&c->release_call, release_call, c,
grpc_schedule_on_exec_ctx));
}
-void grpc_call_ref(grpc_call* c) { c->ext_ref.Ref(); }
+void grpc_call_ref(grpc_call* c) { c->ext_ref.Ref(); }
void grpc_call_unref(grpc_call* c) {
- if (GPR_LIKELY(!c->ext_ref.Unref())) return;
+ if (GPR_LIKELY(!c->ext_ref.Unref())) return;
GPR_TIMER_SCOPE("grpc_call_unref", 0);
@@ -609,7 +609,7 @@ void grpc_call_unref(grpc_call* c) {
// holding to the call stack. Also flush the closures on exec_ctx so that
// filters that schedule cancel notification closures on exec_ctx do not
// need to take a ref of the call stack to guarantee closure liveness.
- c->call_combiner.SetNotifyOnCancel(nullptr);
+ c->call_combiner.SetNotifyOnCancel(nullptr);
grpc_core::ExecCtx::Get()->Flush();
}
GRPC_CALL_INTERNAL_UNREF(c, "destroy");
@@ -626,7 +626,7 @@ grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved) {
// This is called via the call combiner to start sending a batch down
// the filter stack.
-static void execute_batch_in_call_combiner(void* arg, grpc_error* /*ignored*/) {
+static void execute_batch_in_call_combiner(void* arg, grpc_error* /*ignored*/) {
GPR_TIMER_SCOPE("execute_batch_in_call_combiner", 0);
grpc_transport_stream_op_batch* batch =
static_cast<grpc_transport_stream_op_batch*>(arg);
@@ -686,7 +686,7 @@ struct cancel_state {
};
// The on_complete callback used when sending a cancel_stream batch down
// the filter stack. Yields the call combiner when the batch is done.
-static void done_termination(void* arg, grpc_error* /*error*/) {
+static void done_termination(void* arg, grpc_error* /*error*/) {
cancel_state* state = static_cast<cancel_state*>(arg);
GRPC_CALL_COMBINER_STOP(&state->call->call_combiner,
"on_complete for cancel_stream op");
@@ -704,7 +704,7 @@ static void cancel_with_error(grpc_call* c, grpc_error* error) {
// any in-flight asynchronous actions that may be holding the call
// combiner. This ensures that the cancel_stream batch can be sent
// down the filter stack in a timely manner.
- c->call_combiner.Cancel(GRPC_ERROR_REF(error));
+ c->call_combiner.Cancel(GRPC_ERROR_REF(error));
cancel_state* state = static_cast<cancel_state*>(gpr_malloc(sizeof(*state)));
state->call = c;
GRPC_CLOSURE_INIT(&state->finish_batch, done_termination, state,
@@ -737,7 +737,7 @@ static void cancel_with_status(grpc_call* c, grpc_status_code status,
}
static void set_final_status(grpc_call* call, grpc_error* error) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_call_error_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_call_error_trace)) {
gpr_log(GPR_DEBUG, "set_final_status %s", call->is_client ? "CLI" : "SVR");
gpr_log(GPR_DEBUG, "%s", grpc_error_string(error));
}
@@ -813,10 +813,10 @@ uint32_t grpc_call_test_only_get_message_flags(grpc_call* call) {
return flags;
}
-static void destroy_encodings_accepted_by_peer(void* /*p*/) { return; }
+static void destroy_encodings_accepted_by_peer(void* /*p*/) { return; }
-static void set_encodings_accepted_by_peer(grpc_call* /*call*/,
- grpc_mdelem mdel,
+static void set_encodings_accepted_by_peer(grpc_call* /*call*/,
+ grpc_mdelem mdel,
uint32_t* encodings_accepted_by_peer,
bool stream_encoding) {
size_t i;
@@ -914,14 +914,14 @@ static int prepare_application_metadata(grpc_call* call, int count,
if (!GRPC_LOG_IF_ERROR("validate_metadata",
grpc_validate_header_key_is_legal(md->key))) {
break;
- } else if (!grpc_is_binary_header_internal(md->key) &&
+ } else if (!grpc_is_binary_header_internal(md->key) &&
!GRPC_LOG_IF_ERROR(
"validate_metadata",
grpc_validate_header_nonbin_value_is_legal(md->value))) {
break;
- } else if (GRPC_SLICE_LENGTH(md->value) >= UINT32_MAX) {
- // HTTP2 hpack encoding has a maximum limit.
- break;
+ } else if (GRPC_SLICE_LENGTH(md->value) >= UINT32_MAX) {
+ // HTTP2 hpack encoding has a maximum limit.
+ break;
}
l->md = grpc_mdelem_from_grpc_metadata(const_cast<grpc_metadata*>(md));
}
@@ -1019,13 +1019,13 @@ static void recv_initial_filter(grpc_call* call, grpc_metadata_batch* b) {
GPR_TIMER_SCOPE("incoming_stream_compression_algorithm", 0);
set_incoming_stream_compression_algorithm(
call, decode_stream_compression(b->idx.named.content_encoding->md));
- grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_ENCODING);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_ENCODING);
}
if (b->idx.named.grpc_encoding != nullptr) {
GPR_TIMER_SCOPE("incoming_message_compression_algorithm", 0);
set_incoming_message_compression_algorithm(
call, decode_message_compression(b->idx.named.grpc_encoding->md));
- grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_ENCODING);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_ENCODING);
}
uint32_t message_encodings_accepted_by_peer = 1u;
uint32_t stream_encodings_accepted_by_peer = 1u;
@@ -1033,13 +1033,13 @@ static void recv_initial_filter(grpc_call* call, grpc_metadata_batch* b) {
GPR_TIMER_SCOPE("encodings_accepted_by_peer", 0);
set_encodings_accepted_by_peer(call, b->idx.named.grpc_accept_encoding->md,
&message_encodings_accepted_by_peer, false);
- grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_ACCEPT_ENCODING);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_ACCEPT_ENCODING);
}
if (b->idx.named.accept_encoding != nullptr) {
GPR_TIMER_SCOPE("stream_encodings_accepted_by_peer", 0);
set_encodings_accepted_by_peer(call, b->idx.named.accept_encoding->md,
&stream_encodings_accepted_by_peer, true);
- grpc_metadata_batch_remove(b, GRPC_BATCH_ACCEPT_ENCODING);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_ACCEPT_ENCODING);
}
call->encodings_accepted_by_peer =
grpc_compression_bitset_from_message_stream_compression_bitset(
@@ -1058,24 +1058,24 @@ static void recv_trailing_filter(void* args, grpc_metadata_batch* b,
grpc_get_status_code_from_metadata(b->idx.named.grpc_status->md);
grpc_error* error = GRPC_ERROR_NONE;
if (status_code != GRPC_STATUS_OK) {
- char* peer = grpc_call_get_peer(call);
+ char* peer = grpc_call_get_peer(call);
error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Error received from peer ", peer).c_str()),
GRPC_ERROR_INT_GRPC_STATUS, static_cast<intptr_t>(status_code));
- gpr_free(peer);
+ gpr_free(peer);
}
if (b->idx.named.grpc_message != nullptr) {
error = grpc_error_set_str(
error, GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_slice_ref_internal(GRPC_MDVALUE(b->idx.named.grpc_message->md)));
- grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_MESSAGE);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_MESSAGE);
} else if (error != GRPC_ERROR_NONE) {
error = grpc_error_set_str(error, GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_empty_slice());
}
set_final_status(call, GRPC_ERROR_REF(error));
- grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_STATUS);
+ grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_STATUS);
GRPC_ERROR_UNREF(error);
} else if (!call->is_client) {
set_final_status(call, GRPC_ERROR_NONE);
@@ -1090,7 +1090,7 @@ static void recv_trailing_filter(void* args, grpc_metadata_batch* b,
publish_app_metadata(call, b, true);
}
-grpc_core::Arena* grpc_call_get_arena(grpc_call* call) { return call->arena; }
+grpc_core::Arena* grpc_call_get_arena(grpc_call* call) { return call->arena; }
grpc_call_stack* grpc_call_get_call_stack(grpc_call* call) {
return CALL_STACK_FROM_CALL(call);
@@ -1138,7 +1138,7 @@ static size_t batch_slot_for_op(grpc_op_type type) {
}
static batch_control* reuse_or_allocate_batch_control(grpc_call* call,
- const grpc_op* ops) {
+ const grpc_op* ops) {
size_t slot_idx = batch_slot_for_op(ops[0].op);
batch_control** pslot = &call->active_batches[slot_idx];
batch_control* bctl;
@@ -1150,7 +1150,7 @@ static batch_control* reuse_or_allocate_batch_control(grpc_call* call,
bctl->~batch_control();
bctl->op = {};
} else {
- bctl = call->arena->New<batch_control>();
+ bctl = call->arena->New<batch_control>();
*pslot = bctl;
}
bctl->call = call;
@@ -1159,7 +1159,7 @@ static batch_control* reuse_or_allocate_batch_control(grpc_call* call,
}
static void finish_batch_completion(void* user_data,
- grpc_cq_completion* /*storage*/) {
+ grpc_cq_completion* /*storage*/) {
batch_control* bctl = static_cast<batch_control*>(user_data);
grpc_call* call = bctl->call;
bctl->call = nullptr;
@@ -1184,12 +1184,12 @@ static void post_batch_completion(batch_control* bctl) {
&call->metadata_batch[0 /* is_receiving */][0 /* is_trailing */]);
}
if (bctl->op.send_message) {
- if (bctl->op.payload->send_message.stream_write_closed &&
- error == GRPC_ERROR_NONE) {
- error = grpc_error_add_child(
- error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Attempt to send message after stream was closed."));
- }
+ if (bctl->op.payload->send_message.stream_write_closed &&
+ error == GRPC_ERROR_NONE) {
+ error = grpc_error_add_child(
+ error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Attempt to send message after stream was closed."));
+ }
call->sending_message = false;
}
if (bctl->op.send_trailing_metadata) {
@@ -1230,9 +1230,9 @@ static void post_batch_completion(batch_control* bctl) {
if (bctl->completion_data.notify_tag.is_closure) {
/* unrefs error */
bctl->call = nullptr;
- grpc_core::Closure::Run(DEBUG_LOCATION,
- (grpc_closure*)bctl->completion_data.notify_tag.tag,
- error);
+ grpc_core::Closure::Run(DEBUG_LOCATION,
+ (grpc_closure*)bctl->completion_data.notify_tag.tag,
+ error);
GRPC_CALL_INTERNAL_UNREF(call, "completion");
} else {
/* unrefs error */
@@ -1243,7 +1243,7 @@ static void post_batch_completion(batch_control* bctl) {
}
static void finish_batch_step(batch_control* bctl) {
- if (GPR_UNLIKELY(bctl->completed_batch_step())) {
+ if (GPR_UNLIKELY(bctl->completed_batch_step())) {
post_batch_completion(bctl);
}
}
@@ -1271,7 +1271,7 @@ static void continue_receiving_slices(batch_control* bctl) {
*call->receiving_buffer = nullptr;
call->receiving_message = 0;
finish_batch_step(bctl);
- GRPC_ERROR_UNREF(error);
+ GRPC_ERROR_UNREF(error);
return;
}
} else {
@@ -1299,7 +1299,7 @@ static void receiving_slice_ready(void* bctlp, grpc_error* error) {
}
if (error != GRPC_ERROR_NONE) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures)) {
GRPC_LOG_IF_ERROR("receiving_slice_ready", GRPC_ERROR_REF(error));
}
call->receiving_stream.reset();
@@ -1372,8 +1372,8 @@ static void receiving_stream_ready_in_call_combiner(void* bctlp,
receiving_stream_ready(bctlp, error);
}
-static void GPR_ATTRIBUTE_NOINLINE
-handle_both_stream_and_msg_compression_set(grpc_call* call) {
+static void GPR_ATTRIBUTE_NOINLINE
+handle_both_stream_and_msg_compression_set(grpc_call* call) {
TString error_msg = y_absl::StrFormat(
"Incoming stream has both stream compression (%d) and message "
"compression (%d).",
@@ -1381,78 +1381,78 @@ handle_both_stream_and_msg_compression_set(grpc_call* call) {
call->incoming_message_compression_algorithm);
gpr_log(GPR_ERROR, "%s", error_msg.c_str());
cancel_with_status(call, GRPC_STATUS_INTERNAL, error_msg.c_str());
-}
-
-static void GPR_ATTRIBUTE_NOINLINE
-handle_error_parsing_compression_algorithm(grpc_call* call) {
+}
+
+static void GPR_ATTRIBUTE_NOINLINE
+handle_error_parsing_compression_algorithm(grpc_call* call) {
TString error_msg = y_absl::StrFormat(
"Error in incoming message compression (%d) or stream "
"compression (%d).",
call->incoming_stream_compression_algorithm,
call->incoming_message_compression_algorithm);
cancel_with_status(call, GRPC_STATUS_INTERNAL, error_msg.c_str());
-}
-
-static void GPR_ATTRIBUTE_NOINLINE handle_invalid_compression(
- grpc_call* call, grpc_compression_algorithm compression_algorithm) {
+}
+
+static void GPR_ATTRIBUTE_NOINLINE handle_invalid_compression(
+ grpc_call* call, grpc_compression_algorithm compression_algorithm) {
TString error_msg = y_absl::StrFormat(
"Invalid compression algorithm value '%d'.", compression_algorithm);
gpr_log(GPR_ERROR, "%s", error_msg.c_str());
cancel_with_status(call, GRPC_STATUS_UNIMPLEMENTED, error_msg.c_str());
-}
-
-static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_disabled(
- grpc_call* call, grpc_compression_algorithm compression_algorithm) {
- const char* algo_name = nullptr;
- grpc_compression_algorithm_name(compression_algorithm, &algo_name);
+}
+
+static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_disabled(
+ grpc_call* call, grpc_compression_algorithm compression_algorithm) {
+ const char* algo_name = nullptr;
+ grpc_compression_algorithm_name(compression_algorithm, &algo_name);
TString error_msg =
y_absl::StrFormat("Compression algorithm '%s' is disabled.", algo_name);
gpr_log(GPR_ERROR, "%s", error_msg.c_str());
cancel_with_status(call, GRPC_STATUS_UNIMPLEMENTED, error_msg.c_str());
-}
-
-static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_not_accepted(
- grpc_call* call, grpc_compression_algorithm compression_algorithm) {
- const char* algo_name = nullptr;
- grpc_compression_algorithm_name(compression_algorithm, &algo_name);
- gpr_log(GPR_ERROR,
- "Compression algorithm ('%s') not present in the bitset of "
- "accepted encodings ('0x%x')",
- algo_name, call->encodings_accepted_by_peer);
-}
-
+}
+
+static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_not_accepted(
+ grpc_call* call, grpc_compression_algorithm compression_algorithm) {
+ const char* algo_name = nullptr;
+ grpc_compression_algorithm_name(compression_algorithm, &algo_name);
+ gpr_log(GPR_ERROR,
+ "Compression algorithm ('%s') not present in the bitset of "
+ "accepted encodings ('0x%x')",
+ algo_name, call->encodings_accepted_by_peer);
+}
+
static void validate_filtered_metadata(batch_control* bctl) {
grpc_compression_algorithm compression_algorithm;
grpc_call* call = bctl->call;
- if (GPR_UNLIKELY(call->incoming_stream_compression_algorithm !=
- GRPC_STREAM_COMPRESS_NONE &&
- call->incoming_message_compression_algorithm !=
- GRPC_MESSAGE_COMPRESS_NONE)) {
- handle_both_stream_and_msg_compression_set(call);
+ if (GPR_UNLIKELY(call->incoming_stream_compression_algorithm !=
+ GRPC_STREAM_COMPRESS_NONE &&
+ call->incoming_message_compression_algorithm !=
+ GRPC_MESSAGE_COMPRESS_NONE)) {
+ handle_both_stream_and_msg_compression_set(call);
} else if (
- GPR_UNLIKELY(
- grpc_compression_algorithm_from_message_stream_compression_algorithm(
- &compression_algorithm,
- call->incoming_message_compression_algorithm,
- call->incoming_stream_compression_algorithm) == 0)) {
- handle_error_parsing_compression_algorithm(call);
+ GPR_UNLIKELY(
+ grpc_compression_algorithm_from_message_stream_compression_algorithm(
+ &compression_algorithm,
+ call->incoming_message_compression_algorithm,
+ call->incoming_stream_compression_algorithm) == 0)) {
+ handle_error_parsing_compression_algorithm(call);
} else {
const grpc_compression_options compression_options =
grpc_channel_compression_options(call->channel);
- if (GPR_UNLIKELY(compression_algorithm >= GRPC_COMPRESS_ALGORITHMS_COUNT)) {
- handle_invalid_compression(call, compression_algorithm);
- } else if (GPR_UNLIKELY(
- grpc_compression_options_is_algorithm_enabled_internal(
- &compression_options, compression_algorithm) == 0)) {
+ if (GPR_UNLIKELY(compression_algorithm >= GRPC_COMPRESS_ALGORITHMS_COUNT)) {
+ handle_invalid_compression(call, compression_algorithm);
+ } else if (GPR_UNLIKELY(
+ grpc_compression_options_is_algorithm_enabled_internal(
+ &compression_options, compression_algorithm) == 0)) {
/* check if algorithm is supported by current channel config */
- handle_compression_algorithm_disabled(call, compression_algorithm);
+ handle_compression_algorithm_disabled(call, compression_algorithm);
}
- /* GRPC_COMPRESS_NONE is always set. */
- GPR_DEBUG_ASSERT(call->encodings_accepted_by_peer != 0);
- if (GPR_UNLIKELY(!GPR_BITGET(call->encodings_accepted_by_peer,
- compression_algorithm))) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
- handle_compression_algorithm_not_accepted(call, compression_algorithm);
+ /* GRPC_COMPRESS_NONE is always set. */
+ GPR_DEBUG_ASSERT(call->encodings_accepted_by_peer != 0);
+ if (GPR_UNLIKELY(!GPR_BITGET(call->encodings_accepted_by_peer,
+ compression_algorithm))) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
+ handle_compression_algorithm_not_accepted(call, compression_algorithm);
}
}
}
@@ -1510,8 +1510,8 @@ static void receiving_initial_metadata_ready(void* bctlp, grpc_error* error) {
}
}
if (saved_rsr_closure != nullptr) {
- grpc_core::Closure::Run(DEBUG_LOCATION, saved_rsr_closure,
- GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION, saved_rsr_closure,
+ GRPC_ERROR_REF(error));
}
finish_batch_step(bctl);
@@ -1542,7 +1542,7 @@ static void finish_batch(void* bctlp, grpc_error* error) {
finish_batch_step(bctl);
}
-static void free_no_op_completion(void* /*p*/, grpc_cq_completion* completion) {
+static void free_no_op_completion(void* /*p*/, grpc_cq_completion* completion) {
gpr_free(completion);
}
@@ -1560,7 +1560,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
grpc_transport_stream_op_batch* stream_op;
grpc_transport_stream_op_batch_payload* stream_op_payload;
- GRPC_CALL_LOG_BATCH(GPR_INFO, ops, nops);
+ GRPC_CALL_LOG_BATCH(GPR_INFO, ops, nops);
if (nops == 0) {
if (!is_notify_tag_closure) {
@@ -1570,14 +1570,14 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
static_cast<grpc_cq_completion*>(
gpr_malloc(sizeof(grpc_cq_completion))));
} else {
- grpc_core::Closure::Run(DEBUG_LOCATION, (grpc_closure*)notify_tag,
- GRPC_ERROR_NONE);
+ grpc_core::Closure::Run(DEBUG_LOCATION, (grpc_closure*)notify_tag,
+ GRPC_ERROR_NONE);
}
error = GRPC_CALL_OK;
goto done;
}
- bctl = reuse_or_allocate_batch_control(call, ops);
+ bctl = reuse_or_allocate_batch_control(call, ops);
if (bctl == nullptr) {
return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
}
@@ -1606,15 +1606,15 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
goto done_with_error;
}
- // TODO(juanlishen): If the user has already specified a compression
- // algorithm by setting the initial metadata with key of
- // GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, we shouldn't override that
- // with the compression algorithm mapped from compression level.
+ // TODO(juanlishen): If the user has already specified a compression
+ // algorithm by setting the initial metadata with key of
+ // GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, we shouldn't override that
+ // with the compression algorithm mapped from compression level.
/* process compression level */
- grpc_metadata& compression_md = call->compression_md;
- compression_md.key = grpc_empty_slice();
- compression_md.value = grpc_empty_slice();
- compression_md.flags = 0;
+ grpc_metadata& compression_md = call->compression_md;
+ compression_md.key = grpc_empty_slice();
+ compression_md.value = grpc_empty_slice();
+ compression_md.flags = 0;
size_t additional_metadata_count = 0;
grpc_compression_level effective_compression_level =
GRPC_COMPRESS_LEVEL_NONE;
@@ -1631,16 +1631,16 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
effective_compression_level = copts.default_level.level;
}
}
- // Currently, only server side supports compression level setting.
+ // Currently, only server side supports compression level setting.
if (level_set && !call->is_client) {
const grpc_compression_algorithm calgo =
compression_algorithm_for_level_locked(
call, effective_compression_level);
- // The following metadata will be checked and removed by the message
- // compression filter. It will be used as the call's compression
- // algorithm.
- compression_md.key = GRPC_MDSTR_GRPC_INTERNAL_ENCODING_REQUEST;
- compression_md.value = grpc_compression_algorithm_slice(calgo);
+ // The following metadata will be checked and removed by the message
+ // compression filter. It will be used as the call's compression
+ // algorithm.
+ compression_md.key = GRPC_MDSTR_GRPC_INTERNAL_ENCODING_REQUEST;
+ compression_md.value = grpc_compression_algorithm_slice(calgo);
additional_metadata_count++;
}
if (op->data.send_initial_metadata.count + additional_metadata_count >
@@ -1653,7 +1653,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
if (!prepare_application_metadata(
call, static_cast<int>(op->data.send_initial_metadata.count),
op->data.send_initial_metadata.metadata, 0, call->is_client,
- &compression_md, static_cast<int>(additional_metadata_count))) {
+ &compression_md, static_cast<int>(additional_metadata_count))) {
error = GRPC_CALL_ERROR_INVALID_METADATA;
goto done_with_error;
}
@@ -1746,8 +1746,8 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
call->sent_final_op = true;
GPR_ASSERT(call->send_extra_metadata_count == 0);
call->send_extra_metadata_count = 1;
- call->send_extra_metadata[0].md = grpc_get_reffed_status_elem(
- op->data.send_status_from_server.status);
+ call->send_extra_metadata[0].md = grpc_get_reffed_status_elem(
+ op->data.send_status_from_server.status);
grpc_error* status_error =
op->data.send_status_from_server.status == GRPC_STATUS_OK
? GRPC_ERROR_NONE
@@ -1917,7 +1917,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
if (!is_notify_tag_closure) {
Y_VERIFY(grpc_cq_begin_op(call->cq, notify_tag));
}
- bctl->set_num_steps_to_complete((has_send_ops ? 1 : 0) + num_recv_ops);
+ bctl->set_num_steps_to_complete((has_send_ops ? 1 : 0) + num_recv_ops);
if (has_send_ops) {
GRPC_CLOSURE_INIT(&bctl->finish_batch, finish_batch, bctl,
diff --git a/contrib/libs/grpc/src/core/lib/surface/call.h b/contrib/libs/grpc/src/core/lib/surface/call.h
index 34d01db902..bbcad27899 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call.h
+++ b/contrib/libs/grpc/src/core/lib/surface/call.h
@@ -23,7 +23,7 @@
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/context.h"
-#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/arena.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/server.h"
@@ -74,7 +74,7 @@ void grpc_call_internal_unref(grpc_call* call);
#define GRPC_CALL_INTERNAL_UNREF(call, reason) grpc_call_internal_unref(call)
#endif
-grpc_core::Arena* grpc_call_get_arena(grpc_call* call);
+grpc_core::Arena* grpc_call_get_arena(grpc_call* call);
grpc_call_stack* grpc_call_get_call_stack(grpc_call* call);
@@ -91,7 +91,7 @@ void grpc_call_cancel_internal(grpc_call* call);
grpc_call* grpc_call_from_top_element(grpc_call_element* surface_element);
void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity,
- const grpc_op* ops, size_t nops);
+ const grpc_op* ops, size_t nops);
/* Set a context pointer.
No thread safety guarantees are made wrt this value. */
@@ -101,12 +101,12 @@ void grpc_call_context_set(grpc_call* call, grpc_context_index elem,
/* Get a context pointer. */
void* grpc_call_context_get(grpc_call* call, grpc_context_index elem);
-#define GRPC_CALL_LOG_BATCH(sev, ops, nops) \
- do { \
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) { \
- grpc_call_log_batch(sev, ops, nops); \
- } \
- } while (0)
+#define GRPC_CALL_LOG_BATCH(sev, ops, nops) \
+ do { \
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) { \
+ grpc_call_log_batch(sev, ops, nops); \
+ } \
+ } while (0)
uint8_t grpc_call_is_client(grpc_call* call);
diff --git a/contrib/libs/grpc/src/core/lib/surface/call_log_batch.cc b/contrib/libs/grpc/src/core/lib/surface/call_log_batch.cc
index c4f78821ab..4b986d9d7d 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call_log_batch.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/call_log_batch.cc
@@ -103,7 +103,7 @@ static TString grpc_op_string(const grpc_op* op) {
}
void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity,
- const grpc_op* ops, size_t nops) {
+ const grpc_op* ops, size_t nops) {
for (size_t i = 0; i < nops; i++) {
gpr_log(file, line, severity, "ops[%" PRIuPTR "]: %s", i,
grpc_op_string(&ops[i]).c_str());
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel.cc b/contrib/libs/grpc/src/core/lib/surface/channel.cc
index 28df8e61ee..1b13295f9d 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/channel.cc
@@ -33,7 +33,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_trace.h"
#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/channel/channelz_registry.h"
+#include "src/core/lib/channel/channelz_registry.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/manual_constructor.h"
@@ -114,16 +114,16 @@ grpc_channel* grpc_channel_create_with_builder(
channel->compression_options.enabled_algorithms_bitset =
static_cast<uint32_t>(args->args[i].value.integer) |
0x1; /* always support no compression */
- } else if (0 == strcmp(args->args[i].key, GRPC_ARG_CHANNELZ_CHANNEL_NODE)) {
- if (args->args[i].type == GRPC_ARG_POINTER) {
- GPR_ASSERT(args->args[i].value.pointer.p != nullptr);
- channel->channelz_node = static_cast<grpc_core::channelz::ChannelNode*>(
- args->args[i].value.pointer.p)
- ->Ref();
- } else {
- gpr_log(GPR_DEBUG,
- GRPC_ARG_CHANNELZ_CHANNEL_NODE " should be a pointer");
- }
+ } else if (0 == strcmp(args->args[i].key, GRPC_ARG_CHANNELZ_CHANNEL_NODE)) {
+ if (args->args[i].type == GRPC_ARG_POINTER) {
+ GPR_ASSERT(args->args[i].value.pointer.p != nullptr);
+ channel->channelz_node = static_cast<grpc_core::channelz::ChannelNode*>(
+ args->args[i].value.pointer.p)
+ ->Ref();
+ } else {
+ gpr_log(GPR_DEBUG,
+ GRPC_ARG_CHANNELZ_CHANNEL_NODE " should be a pointer");
+ }
}
}
@@ -162,93 +162,93 @@ static grpc_channel_args* build_channel_args(
return grpc_channel_args_copy_and_add(input_args, new_args, num_new_args);
}
-namespace {
-
-void* channelz_node_copy(void* p) {
- grpc_core::channelz::ChannelNode* node =
- static_cast<grpc_core::channelz::ChannelNode*>(p);
- node->Ref().release();
- return p;
-}
-void channelz_node_destroy(void* p) {
- grpc_core::channelz::ChannelNode* node =
- static_cast<grpc_core::channelz::ChannelNode*>(p);
- node->Unref();
+namespace {
+
+void* channelz_node_copy(void* p) {
+ grpc_core::channelz::ChannelNode* node =
+ static_cast<grpc_core::channelz::ChannelNode*>(p);
+ node->Ref().release();
+ return p;
}
-int channelz_node_cmp(void* p1, void* p2) { return GPR_ICMP(p1, p2); }
-const grpc_arg_pointer_vtable channelz_node_arg_vtable = {
- channelz_node_copy, channelz_node_destroy, channelz_node_cmp};
-
-void CreateChannelzNode(grpc_channel_stack_builder* builder) {
- const grpc_channel_args* args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- // Check whether channelz is enabled.
+void channelz_node_destroy(void* p) {
+ grpc_core::channelz::ChannelNode* node =
+ static_cast<grpc_core::channelz::ChannelNode*>(p);
+ node->Unref();
+}
+int channelz_node_cmp(void* p1, void* p2) { return GPR_ICMP(p1, p2); }
+const grpc_arg_pointer_vtable channelz_node_arg_vtable = {
+ channelz_node_copy, channelz_node_destroy, channelz_node_cmp};
+
+void CreateChannelzNode(grpc_channel_stack_builder* builder) {
+ const grpc_channel_args* args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ // Check whether channelz is enabled.
const bool channelz_enabled = grpc_channel_args_find_bool(
args, GRPC_ARG_ENABLE_CHANNELZ, GRPC_ENABLE_CHANNELZ_DEFAULT);
- if (!channelz_enabled) return;
- // Get parameters needed to create the channelz node.
+ if (!channelz_enabled) return;
+ // Get parameters needed to create the channelz node.
const size_t channel_tracer_max_memory = grpc_channel_args_find_integer(
args, GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE,
- {GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT, 0, INT_MAX});
+ {GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT, 0, INT_MAX});
const bool is_internal_channel = grpc_channel_args_find_bool(
args, GRPC_ARG_CHANNELZ_IS_INTERNAL_CHANNEL, false);
- // Create the channelz node.
- const char* target = grpc_channel_stack_builder_get_target(builder);
- grpc_core::RefCountedPtr<grpc_core::channelz::ChannelNode> channelz_node =
- grpc_core::MakeRefCounted<grpc_core::channelz::ChannelNode>(
- target != nullptr ? target : "", channel_tracer_max_memory,
+ // Create the channelz node.
+ const char* target = grpc_channel_stack_builder_get_target(builder);
+ grpc_core::RefCountedPtr<grpc_core::channelz::ChannelNode> channelz_node =
+ grpc_core::MakeRefCounted<grpc_core::channelz::ChannelNode>(
+ target != nullptr ? target : "", channel_tracer_max_memory,
is_internal_channel);
- channelz_node->AddTraceEvent(
- grpc_core::channelz::ChannelTrace::Severity::Info,
- grpc_slice_from_static_string("Channel created"));
- // Add channelz node to channel args.
+ channelz_node->AddTraceEvent(
+ grpc_core::channelz::ChannelTrace::Severity::Info,
+ grpc_slice_from_static_string("Channel created"));
+ // Add channelz node to channel args.
// We remove the is_internal_channel arg, since we no longer need it.
- grpc_arg new_arg = grpc_channel_arg_pointer_create(
- const_cast<char*>(GRPC_ARG_CHANNELZ_CHANNEL_NODE), channelz_node.get(),
- &channelz_node_arg_vtable);
+ grpc_arg new_arg = grpc_channel_arg_pointer_create(
+ const_cast<char*>(GRPC_ARG_CHANNELZ_CHANNEL_NODE), channelz_node.get(),
+ &channelz_node_arg_vtable);
const char* args_to_remove[] = {GRPC_ARG_CHANNELZ_IS_INTERNAL_CHANNEL};
- grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
- args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
- grpc_channel_stack_builder_set_channel_arguments(builder, new_args);
- grpc_channel_args_destroy(new_args);
-}
-
-} // namespace
-
+ grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
+ args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
+ grpc_channel_stack_builder_set_channel_arguments(builder, new_args);
+ grpc_channel_args_destroy(new_args);
+}
+
+} // namespace
+
grpc_channel* grpc_channel_create(const char* target,
const grpc_channel_args* input_args,
grpc_channel_stack_type channel_stack_type,
grpc_transport* optional_transport,
grpc_resource_user* resource_user) {
- // We need to make sure that grpc_shutdown() does not shut things down
- // until after the channel is destroyed. However, the channel may not
- // actually be destroyed by the time grpc_channel_destroy() returns,
- // since there may be other existing refs to the channel. If those
- // refs are held by things that are visible to the wrapped language
- // (such as outstanding calls on the channel), then the wrapped
- // language can be responsible for making sure that grpc_shutdown()
- // does not run until after those refs are released. However, the
- // channel may also have refs to itself held internally for various
- // things that need to be cleaned up at channel destruction (e.g.,
- // LB policies, subchannels, etc), and because these refs are not
- // visible to the wrapped language, it cannot be responsible for
- // deferring grpc_shutdown() until after they are released. To
- // accommodate that, we call grpc_init() here and then call
- // grpc_shutdown() when the channel is actually destroyed, thus
- // ensuring that shutdown is deferred until that point.
- grpc_init();
+ // We need to make sure that grpc_shutdown() does not shut things down
+ // until after the channel is destroyed. However, the channel may not
+ // actually be destroyed by the time grpc_channel_destroy() returns,
+ // since there may be other existing refs to the channel. If those
+ // refs are held by things that are visible to the wrapped language
+ // (such as outstanding calls on the channel), then the wrapped
+ // language can be responsible for making sure that grpc_shutdown()
+ // does not run until after those refs are released. However, the
+ // channel may also have refs to itself held internally for various
+ // things that need to be cleaned up at channel destruction (e.g.,
+ // LB policies, subchannels, etc), and because these refs are not
+ // visible to the wrapped language, it cannot be responsible for
+ // deferring grpc_shutdown() until after they are released. To
+ // accommodate that, we call grpc_init() here and then call
+ // grpc_shutdown() when the channel is actually destroyed, thus
+ // ensuring that shutdown is deferred until that point.
+ grpc_init();
grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create();
const grpc_core::UniquePtr<char> default_authority =
get_default_authority(input_args);
grpc_channel_args* args =
build_channel_args(input_args, default_authority.get());
- if (grpc_channel_stack_type_is_client(channel_stack_type)) {
- auto channel_args_mutator =
- grpc_channel_args_get_client_channel_creation_mutator();
- if (channel_args_mutator != nullptr) {
- args = channel_args_mutator(target, args, channel_stack_type);
- }
- }
+ if (grpc_channel_stack_type_is_client(channel_stack_type)) {
+ auto channel_args_mutator =
+ grpc_channel_args_get_client_channel_creation_mutator();
+ if (channel_args_mutator != nullptr) {
+ args = channel_args_mutator(target, args, channel_stack_type);
+ }
+ }
grpc_channel_stack_builder_set_channel_arguments(builder, args);
grpc_channel_args_destroy(args);
grpc_channel_stack_builder_set_target(builder, target);
@@ -259,19 +259,19 @@ grpc_channel* grpc_channel_create(const char* target,
if (resource_user != nullptr) {
grpc_resource_user_free(resource_user, GRPC_RESOURCE_QUOTA_CHANNEL_SIZE);
}
- grpc_shutdown(); // Since we won't call destroy_channel().
+ grpc_shutdown(); // Since we won't call destroy_channel().
return nullptr;
}
- // We only need to do this for clients here. For servers, this will be
- // done in src/core/lib/surface/server.cc.
- if (grpc_channel_stack_type_is_client(channel_stack_type)) {
- CreateChannelzNode(builder);
- }
+ // We only need to do this for clients here. For servers, this will be
+ // done in src/core/lib/surface/server.cc.
+ if (grpc_channel_stack_type_is_client(channel_stack_type)) {
+ CreateChannelzNode(builder);
+ }
grpc_channel* channel =
grpc_channel_create_with_builder(builder, channel_stack_type);
- if (channel == nullptr) {
- grpc_shutdown(); // Since we won't call destroy_channel().
- }
+ if (channel == nullptr) {
+ grpc_shutdown(); // Since we won't call destroy_channel().
+ }
return channel;
}
@@ -491,13 +491,13 @@ grpc_call* grpc_channel_create_registered_call(
return call;
}
-static void destroy_channel(void* arg, grpc_error* /*error*/) {
+static void destroy_channel(void* arg, grpc_error* /*error*/) {
grpc_channel* channel = static_cast<grpc_channel*>(arg);
- if (channel->channelz_node != nullptr) {
- channel->channelz_node->AddTraceEvent(
+ if (channel->channelz_node != nullptr) {
+ channel->channelz_node->AddTraceEvent(
grpc_core::channelz::ChannelTrace::Severity::Info,
grpc_slice_from_static_string("Channel destroyed"));
- channel->channelz_node.reset();
+ channel->channelz_node.reset();
}
grpc_channel_stack_destroy(CHANNEL_STACK_FROM_CHANNEL(channel));
channel->registration_table.Destroy();
@@ -507,11 +507,11 @@ static void destroy_channel(void* arg, grpc_error* /*error*/) {
}
gpr_free(channel->target);
gpr_free(channel);
- // See comment in grpc_channel_create() for why we do this.
- grpc_shutdown();
+ // See comment in grpc_channel_create() for why we do this.
+ grpc_shutdown();
}
-void grpc_channel_destroy_internal(grpc_channel* channel) {
+void grpc_channel_destroy_internal(grpc_channel* channel) {
grpc_transport_op* op = grpc_make_transport_op(nullptr);
grpc_channel_element* elem;
GRPC_API_TRACE("grpc_channel_destroy(channel=%p)", 1, (channel));
@@ -522,8 +522,8 @@ void grpc_channel_destroy_internal(grpc_channel* channel) {
GRPC_CHANNEL_INTERNAL_UNREF(channel, "channel");
}
-void grpc_channel_destroy(grpc_channel* channel) {
+void grpc_channel_destroy(grpc_channel* channel) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_channel_destroy_internal(channel);
+ grpc_core::ExecCtx exec_ctx;
+ grpc_channel_destroy_internal(channel);
}
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel.h b/contrib/libs/grpc/src/core/lib/surface/channel.h
index e49b9261f7..22beacfd68 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel.h
+++ b/contrib/libs/grpc/src/core/lib/surface/channel.h
@@ -36,10 +36,10 @@ grpc_channel* grpc_channel_create(const char* target,
grpc_transport* optional_transport,
grpc_resource_user* resource_user = nullptr);
-/** The same as grpc_channel_destroy, but doesn't create an ExecCtx, and so
- * is safe to use from within core. */
-void grpc_channel_destroy_internal(grpc_channel* channel);
-
+/** The same as grpc_channel_destroy, but doesn't create an ExecCtx, and so
+ * is safe to use from within core. */
+void grpc_channel_destroy_internal(grpc_channel* channel);
+
grpc_channel* grpc_channel_create_with_builder(
grpc_channel_stack_builder* builder,
grpc_channel_stack_type channel_stack_type);
@@ -100,13 +100,13 @@ struct CallRegistrationTable {
} // namespace grpc_core
-struct grpc_channel {
- int is_client;
- grpc_compression_options compression_options;
-
- gpr_atm call_size_estimate;
- grpc_resource_user* resource_user;
-
+struct grpc_channel {
+ int is_client;
+ grpc_compression_options compression_options;
+
+ gpr_atm call_size_estimate;
+ grpc_resource_user* resource_user;
+
// TODO(vjpai): Once the grpc_channel is allocated via new rather than malloc,
// expand the members of the CallRegistrationTable directly into
// the grpc_channel. For now it is kept separate so that all the
@@ -114,47 +114,47 @@ struct grpc_channel {
// a separate manual construction for each field.
grpc_core::ManualConstructor<grpc_core::CallRegistrationTable>
registration_table;
- grpc_core::RefCountedPtr<grpc_core::channelz::ChannelNode> channelz_node;
-
- char* target;
-};
-#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack*)((c) + 1))
-
-inline grpc_compression_options grpc_channel_compression_options(
- const grpc_channel* channel) {
- return channel->compression_options;
-}
-
-inline grpc_channel_stack* grpc_channel_get_channel_stack(
- grpc_channel* channel) {
- return CHANNEL_STACK_FROM_CHANNEL(channel);
-}
-
-inline grpc_core::channelz::ChannelNode* grpc_channel_get_channelz_node(
- grpc_channel* channel) {
- return channel->channelz_node.get();
-}
-
+ grpc_core::RefCountedPtr<grpc_core::channelz::ChannelNode> channelz_node;
+
+ char* target;
+};
+#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack*)((c) + 1))
+
+inline grpc_compression_options grpc_channel_compression_options(
+ const grpc_channel* channel) {
+ return channel->compression_options;
+}
+
+inline grpc_channel_stack* grpc_channel_get_channel_stack(
+ grpc_channel* channel) {
+ return CHANNEL_STACK_FROM_CHANNEL(channel);
+}
+
+inline grpc_core::channelz::ChannelNode* grpc_channel_get_channelz_node(
+ grpc_channel* channel) {
+ return channel->channelz_node.get();
+}
+
#ifndef NDEBUG
-inline void grpc_channel_internal_ref(grpc_channel* channel,
- const char* reason) {
- GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CHANNEL(channel), reason);
-}
-inline void grpc_channel_internal_unref(grpc_channel* channel,
- const char* reason) {
- GRPC_CHANNEL_STACK_UNREF(CHANNEL_STACK_FROM_CHANNEL(channel), reason);
-}
+inline void grpc_channel_internal_ref(grpc_channel* channel,
+ const char* reason) {
+ GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CHANNEL(channel), reason);
+}
+inline void grpc_channel_internal_unref(grpc_channel* channel,
+ const char* reason) {
+ GRPC_CHANNEL_STACK_UNREF(CHANNEL_STACK_FROM_CHANNEL(channel), reason);
+}
#define GRPC_CHANNEL_INTERNAL_REF(channel, reason) \
grpc_channel_internal_ref(channel, reason)
#define GRPC_CHANNEL_INTERNAL_UNREF(channel, reason) \
grpc_channel_internal_unref(channel, reason)
#else
-inline void grpc_channel_internal_ref(grpc_channel* channel) {
- GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CHANNEL(channel), "unused");
-}
-inline void grpc_channel_internal_unref(grpc_channel* channel) {
- GRPC_CHANNEL_STACK_UNREF(CHANNEL_STACK_FROM_CHANNEL(channel), "unused");
-}
+inline void grpc_channel_internal_ref(grpc_channel* channel) {
+ GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CHANNEL(channel), "unused");
+}
+inline void grpc_channel_internal_unref(grpc_channel* channel) {
+ GRPC_CHANNEL_STACK_UNREF(CHANNEL_STACK_FROM_CHANNEL(channel), "unused");
+}
#define GRPC_CHANNEL_INTERNAL_REF(channel, reason) \
grpc_channel_internal_ref(channel)
#define GRPC_CHANNEL_INTERNAL_UNREF(channel, reason) \
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel_ping.cc b/contrib/libs/grpc/src/core/lib/surface/channel_ping.cc
index 82e552194b..da39db955c 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel_ping.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/channel_ping.cc
@@ -34,7 +34,7 @@ struct ping_result {
grpc_completion_queue* cq;
grpc_cq_completion completion_storage;
};
-static void ping_destroy(void* arg, grpc_cq_completion* /*storage*/) {
+static void ping_destroy(void* arg, grpc_cq_completion* /*storage*/) {
gpr_free(arg);
}
diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc b/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc
index 0f50906734..a9d6178d0d 100644
--- a/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc
@@ -38,8 +38,8 @@
#include "src/core/lib/gpr/spinlock.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/profiling/timers.h"
@@ -51,8 +51,8 @@ grpc_core::TraceFlag grpc_trace_operation_failures(false, "op_failure");
grpc_core::DebugOnlyTraceFlag grpc_trace_pending_tags(false, "pending_tags");
grpc_core::DebugOnlyTraceFlag grpc_trace_cq_refcount(false, "cq_refcount");
-namespace {
-
+namespace {
+
// Specifies a cq thread local cache.
// The first event that occurs on a thread
// with a cq cache will go into that cache, and
@@ -90,22 +90,22 @@ struct non_polling_poller {
non_polling_worker* root;
grpc_closure* shutdown;
};
-size_t non_polling_poller_size(void) { return sizeof(non_polling_poller); }
+size_t non_polling_poller_size(void) { return sizeof(non_polling_poller); }
-void non_polling_poller_init(grpc_pollset* pollset, gpr_mu** mu) {
+void non_polling_poller_init(grpc_pollset* pollset, gpr_mu** mu) {
non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
gpr_mu_init(&npp->mu);
*mu = &npp->mu;
}
-void non_polling_poller_destroy(grpc_pollset* pollset) {
+void non_polling_poller_destroy(grpc_pollset* pollset) {
non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
gpr_mu_destroy(&npp->mu);
}
-grpc_error* non_polling_poller_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker,
- grpc_millis deadline) {
+grpc_error* non_polling_poller_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker,
+ grpc_millis deadline) {
non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
if (npp->shutdown) return GRPC_ERROR_NONE;
if (npp->kicked_without_poller) {
@@ -133,7 +133,7 @@ grpc_error* non_polling_poller_work(grpc_pollset* pollset,
npp->root = w.next;
if (&w == npp->root) {
if (npp->shutdown) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, npp->shutdown, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, npp->shutdown, GRPC_ERROR_NONE);
}
npp->root = nullptr;
}
@@ -145,8 +145,8 @@ grpc_error* non_polling_poller_work(grpc_pollset* pollset,
return GRPC_ERROR_NONE;
}
-grpc_error* non_polling_poller_kick(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker) {
+grpc_error* non_polling_poller_kick(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker) {
non_polling_poller* p = reinterpret_cast<non_polling_poller*>(pollset);
if (specific_worker == nullptr)
specific_worker = reinterpret_cast<grpc_pollset_worker*>(p->root);
@@ -163,12 +163,12 @@ grpc_error* non_polling_poller_kick(grpc_pollset* pollset,
return GRPC_ERROR_NONE;
}
-void non_polling_poller_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
+void non_polling_poller_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
non_polling_poller* p = reinterpret_cast<non_polling_poller*>(pollset);
GPR_ASSERT(closure != nullptr);
p->shutdown = closure;
if (p->root == nullptr) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
} else {
non_polling_worker* w = p->root;
do {
@@ -178,7 +178,7 @@ void non_polling_poller_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
}
}
-const cq_poller_vtable g_poller_vtable_by_poller_type[] = {
+const cq_poller_vtable g_poller_vtable_by_poller_type[] = {
/* GRPC_CQ_DEFAULT_POLLING */
{true, true, grpc_pollset_size, grpc_pollset_init, grpc_pollset_kick,
grpc_pollset_work, grpc_pollset_shutdown, grpc_pollset_destroy},
@@ -191,9 +191,9 @@ const cq_poller_vtable g_poller_vtable_by_poller_type[] = {
non_polling_poller_shutdown, non_polling_poller_destroy},
};
-} // namespace
-
-struct cq_vtable {
+} // namespace
+
+struct cq_vtable {
grpc_cq_completion_type cq_completion_type;
size_t data_size;
void (*init)(void* data,
@@ -203,46 +203,46 @@ struct cq_vtable {
bool (*begin_op)(grpc_completion_queue* cq, void* tag);
void (*end_op)(grpc_completion_queue* cq, void* tag, grpc_error* error,
void (*done)(void* done_arg, grpc_cq_completion* storage),
- void* done_arg, grpc_cq_completion* storage, bool internal);
+ void* done_arg, grpc_cq_completion* storage, bool internal);
grpc_event (*next)(grpc_completion_queue* cq, gpr_timespec deadline,
void* reserved);
grpc_event (*pluck)(grpc_completion_queue* cq, void* tag,
gpr_timespec deadline, void* reserved);
-};
+};
-namespace {
-
-/* Queue that holds the cq_completion_events. Internally uses
- * MultiProducerSingleConsumerQueue (a lockfree multiproducer single consumer
- * queue). It uses a queue_lock to support multiple consumers.
+namespace {
+
+/* Queue that holds the cq_completion_events. Internally uses
+ * MultiProducerSingleConsumerQueue (a lockfree multiproducer single consumer
+ * queue). It uses a queue_lock to support multiple consumers.
* Only used in completion queues whose completion_type is GRPC_CQ_NEXT */
-class CqEventQueue {
- public:
- CqEventQueue() = default;
- ~CqEventQueue() = default;
-
- /* Note: The counter is not incremented/decremented atomically with push/pop.
- * The count is only eventually consistent */
- intptr_t num_items() const {
- return num_queue_items_.Load(grpc_core::MemoryOrder::RELAXED);
- }
-
- bool Push(grpc_cq_completion* c);
- grpc_cq_completion* Pop();
-
- private:
+class CqEventQueue {
+ public:
+ CqEventQueue() = default;
+ ~CqEventQueue() = default;
+
+ /* Note: The counter is not incremented/decremented atomically with push/pop.
+ * The count is only eventually consistent */
+ intptr_t num_items() const {
+ return num_queue_items_.Load(grpc_core::MemoryOrder::RELAXED);
+ }
+
+ bool Push(grpc_cq_completion* c);
+ grpc_cq_completion* Pop();
+
+ private:
/* Spinlock to serialize consumers i.e pop() operations */
- gpr_spinlock queue_lock_ = GPR_SPINLOCK_INITIALIZER;
+ gpr_spinlock queue_lock_ = GPR_SPINLOCK_INITIALIZER;
- grpc_core::MultiProducerSingleConsumerQueue queue_;
+ grpc_core::MultiProducerSingleConsumerQueue queue_;
/* A lazy counter of number of items in the queue. This is NOT atomically
incremented/decremented along with push/pop operations and hence is only
eventually consistent */
- grpc_core::Atomic<intptr_t> num_queue_items_{0};
-};
+ grpc_core::Atomic<intptr_t> num_queue_items_{0};
+};
-struct cq_next_data {
+struct cq_next_data {
~cq_next_data() {
GPR_ASSERT(queue.num_items() == 0);
#ifndef NDEBUG
@@ -251,67 +251,67 @@ struct cq_next_data {
}
#endif
}
-
+
/** Completed events for completion-queues of type GRPC_CQ_NEXT */
- CqEventQueue queue;
+ CqEventQueue queue;
/** Counter of how many things have ever been queued on this completion queue
useful for avoiding locks to check the queue */
- grpc_core::Atomic<intptr_t> things_queued_ever{0};
+ grpc_core::Atomic<intptr_t> things_queued_ever{0};
- /** Number of outstanding events (+1 if not shut down)
- Initial count is dropped by grpc_completion_queue_shutdown */
- grpc_core::Atomic<intptr_t> pending_events{1};
+ /** Number of outstanding events (+1 if not shut down)
+ Initial count is dropped by grpc_completion_queue_shutdown */
+ grpc_core::Atomic<intptr_t> pending_events{1};
/** 0 initially. 1 once we initiated shutdown */
- bool shutdown_called = false;
-};
-
-struct cq_pluck_data {
- cq_pluck_data() {
- completed_tail = &completed_head;
- completed_head.next = reinterpret_cast<uintptr_t>(completed_tail);
- }
-
- ~cq_pluck_data() {
- GPR_ASSERT(completed_head.next ==
- reinterpret_cast<uintptr_t>(&completed_head));
+ bool shutdown_called = false;
+};
+
+struct cq_pluck_data {
+ cq_pluck_data() {
+ completed_tail = &completed_head;
+ completed_head.next = reinterpret_cast<uintptr_t>(completed_tail);
+ }
+
+ ~cq_pluck_data() {
+ GPR_ASSERT(completed_head.next ==
+ reinterpret_cast<uintptr_t>(&completed_head));
#ifndef NDEBUG
if (pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) != 0) {
gpr_log(GPR_ERROR, "Destroying CQ without draining it fully.");
}
#endif
- }
-
+ }
+
/** Completed events for completion-queues of type GRPC_CQ_PLUCK */
grpc_cq_completion completed_head;
grpc_cq_completion* completed_tail;
- /** Number of pending events (+1 if we're not shutdown).
- Initial count is dropped by grpc_completion_queue_shutdown. */
- grpc_core::Atomic<intptr_t> pending_events{1};
+ /** Number of pending events (+1 if we're not shutdown).
+ Initial count is dropped by grpc_completion_queue_shutdown. */
+ grpc_core::Atomic<intptr_t> pending_events{1};
/** Counter of how many things have ever been queued on this completion queue
useful for avoiding locks to check the queue */
- grpc_core::Atomic<intptr_t> things_queued_ever{0};
+ grpc_core::Atomic<intptr_t> things_queued_ever{0};
/** 0 initially. 1 once we completed shutting */
/* TODO: (sreek) This is not needed since (shutdown == 1) if and only if
* (pending_events == 0). So consider removing this in future and use
* pending_events */
- grpc_core::Atomic<bool> shutdown{false};
+ grpc_core::Atomic<bool> shutdown{false};
/** 0 initially. 1 once we initiated shutdown */
- bool shutdown_called = false;
+ bool shutdown_called = false;
- int num_pluckers = 0;
+ int num_pluckers = 0;
plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS];
-};
+};
-struct cq_callback_data {
- cq_callback_data(
- grpc_experimental_completion_queue_functor* shutdown_callback)
- : shutdown_callback(shutdown_callback) {}
+struct cq_callback_data {
+ cq_callback_data(
+ grpc_experimental_completion_queue_functor* shutdown_callback)
+ : shutdown_callback(shutdown_callback) {}
~cq_callback_data() {
#ifndef NDEBUG
@@ -323,23 +323,23 @@ struct cq_callback_data {
/** No actual completed events queue, unlike other types */
- /** Number of pending events (+1 if we're not shutdown).
- Initial count is dropped by grpc_completion_queue_shutdown. */
- grpc_core::Atomic<intptr_t> pending_events{1};
+ /** Number of pending events (+1 if we're not shutdown).
+ Initial count is dropped by grpc_completion_queue_shutdown. */
+ grpc_core::Atomic<intptr_t> pending_events{1};
/** 0 initially. 1 once we initiated shutdown */
- bool shutdown_called = false;
+ bool shutdown_called = false;
/** A callback that gets invoked when the CQ completes shutdown */
grpc_experimental_completion_queue_functor* shutdown_callback;
-};
-
-} // namespace
+};
+} // namespace
+
/* Completion queue structure */
struct grpc_completion_queue {
/** Once owning_refs drops to zero, we will destroy the cq */
- grpc_core::RefCount owning_refs;
+ grpc_core::RefCount owning_refs;
gpr_mu* mu;
@@ -374,20 +374,20 @@ static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* tag);
// queue. The done argument is a callback that will be invoked when it is
// safe to free up that storage. The storage MUST NOT be freed until the
// done callback is invoked.
-static void cq_end_op_for_next(
- grpc_completion_queue* cq, void* tag, grpc_error* error,
- void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
- grpc_cq_completion* storage, bool internal);
+static void cq_end_op_for_next(
+ grpc_completion_queue* cq, void* tag, grpc_error* error,
+ void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
+ grpc_cq_completion* storage, bool internal);
-static void cq_end_op_for_pluck(
- grpc_completion_queue* cq, void* tag, grpc_error* error,
- void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
- grpc_cq_completion* storage, bool internal);
+static void cq_end_op_for_pluck(
+ grpc_completion_queue* cq, void* tag, grpc_error* error,
+ void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
+ grpc_cq_completion* storage, bool internal);
-static void cq_end_op_for_callback(
- grpc_completion_queue* cq, void* tag, grpc_error* error,
- void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
- grpc_cq_completion* storage, bool internal);
+static void cq_end_op_for_callback(
+ grpc_completion_queue* cq, void* tag, grpc_error* error,
+ void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
+ grpc_cq_completion* storage, bool internal);
static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
void* reserved);
@@ -436,7 +436,7 @@ grpc_core::TraceFlag grpc_cq_pluck_trace(false, "queue_pluck");
gpr_log(GPR_INFO, "RETURN_EVENT[%p]: %s", cq, \
grpc_event_string(event).c_str()); \
} \
- } while (0)
+ } while (0)
static void on_pollset_shutdown_done(void* cq, grpc_error* error);
@@ -465,7 +465,7 @@ int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue* cq,
storage->done(storage->done_arg, storage);
ret = 1;
cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
gpr_mu_lock(cq->mu);
cq_finish_shutdown_next(cq);
@@ -479,21 +479,21 @@ int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue* cq,
return ret;
}
-bool CqEventQueue::Push(grpc_cq_completion* c) {
- queue_.Push(
- reinterpret_cast<grpc_core::MultiProducerSingleConsumerQueue::Node*>(c));
- return num_queue_items_.FetchAdd(1, grpc_core::MemoryOrder::RELAXED) == 0;
+bool CqEventQueue::Push(grpc_cq_completion* c) {
+ queue_.Push(
+ reinterpret_cast<grpc_core::MultiProducerSingleConsumerQueue::Node*>(c));
+ return num_queue_items_.FetchAdd(1, grpc_core::MemoryOrder::RELAXED) == 0;
}
-grpc_cq_completion* CqEventQueue::Pop() {
+grpc_cq_completion* CqEventQueue::Pop() {
grpc_cq_completion* c = nullptr;
- if (gpr_spinlock_trylock(&queue_lock_)) {
+ if (gpr_spinlock_trylock(&queue_lock_)) {
GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES();
bool is_empty = false;
- c = reinterpret_cast<grpc_cq_completion*>(queue_.PopAndCheckEnd(&is_empty));
- gpr_spinlock_unlock(&queue_lock_);
+ c = reinterpret_cast<grpc_cq_completion*>(queue_.PopAndCheckEnd(&is_empty));
+ gpr_spinlock_unlock(&queue_lock_);
if (c == nullptr && !is_empty) {
GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES();
@@ -503,7 +503,7 @@ grpc_cq_completion* CqEventQueue::Pop() {
}
if (c) {
- num_queue_items_.FetchSub(1, grpc_core::MemoryOrder::RELAXED);
+ num_queue_items_.FetchSub(1, grpc_core::MemoryOrder::RELAXED);
}
return c;
@@ -536,7 +536,7 @@ grpc_completion_queue* grpc_completion_queue_create_internal(
cq->poller_vtable = poller_vtable;
/* One for destroy(), one for pollset_shutdown */
- new (&cq->owning_refs) grpc_core::RefCount(2);
+ new (&cq->owning_refs) grpc_core::RefCount(2);
poller_vtable->init(POLLSET_FROM_CQ(cq), &cq->mu);
vtable->init(DATA_FROM_CQ(cq), shutdown_callback);
@@ -547,35 +547,35 @@ grpc_completion_queue* grpc_completion_queue_create_internal(
}
static void cq_init_next(
- void* data,
- grpc_experimental_completion_queue_functor* /*shutdown_callback*/) {
- new (data) cq_next_data();
+ void* data,
+ grpc_experimental_completion_queue_functor* /*shutdown_callback*/) {
+ new (data) cq_next_data();
}
static void cq_destroy_next(void* data) {
cq_next_data* cqd = static_cast<cq_next_data*>(data);
- cqd->~cq_next_data();
+ cqd->~cq_next_data();
}
static void cq_init_pluck(
- void* data,
- grpc_experimental_completion_queue_functor* /*shutdown_callback*/) {
- new (data) cq_pluck_data();
+ void* data,
+ grpc_experimental_completion_queue_functor* /*shutdown_callback*/) {
+ new (data) cq_pluck_data();
}
static void cq_destroy_pluck(void* data) {
cq_pluck_data* cqd = static_cast<cq_pluck_data*>(data);
- cqd->~cq_pluck_data();
+ cqd->~cq_pluck_data();
}
static void cq_init_callback(
void* data, grpc_experimental_completion_queue_functor* shutdown_callback) {
- new (data) cq_callback_data(shutdown_callback);
-}
-
-static void cq_destroy_callback(void* data) {
+ new (data) cq_callback_data(shutdown_callback);
+}
+
+static void cq_destroy_callback(void* data) {
cq_callback_data* cqd = static_cast<cq_callback_data*>(data);
- cqd->~cq_callback_data();
+ cqd->~cq_callback_data();
}
grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cq) {
@@ -593,16 +593,16 @@ int grpc_get_cq_poll_num(grpc_completion_queue* cq) {
#ifndef NDEBUG
void grpc_cq_internal_ref(grpc_completion_queue* cq, const char* reason,
const char* file, int line) {
- grpc_core::DebugLocation debug_location(file, line);
+ grpc_core::DebugLocation debug_location(file, line);
#else
void grpc_cq_internal_ref(grpc_completion_queue* cq) {
- grpc_core::DebugLocation debug_location;
- const char* reason = nullptr;
+ grpc_core::DebugLocation debug_location;
+ const char* reason = nullptr;
#endif
- cq->owning_refs.Ref(debug_location, reason);
+ cq->owning_refs.Ref(debug_location, reason);
}
-static void on_pollset_shutdown_done(void* arg, grpc_error* /*error*/) {
+static void on_pollset_shutdown_done(void* arg, grpc_error* /*error*/) {
grpc_completion_queue* cq = static_cast<grpc_completion_queue*>(arg);
GRPC_CQ_INTERNAL_UNREF(cq, "pollset_destroy");
}
@@ -610,13 +610,13 @@ static void on_pollset_shutdown_done(void* arg, grpc_error* /*error*/) {
#ifndef NDEBUG
void grpc_cq_internal_unref(grpc_completion_queue* cq, const char* reason,
const char* file, int line) {
- grpc_core::DebugLocation debug_location(file, line);
+ grpc_core::DebugLocation debug_location(file, line);
#else
void grpc_cq_internal_unref(grpc_completion_queue* cq) {
- grpc_core::DebugLocation debug_location;
- const char* reason = nullptr;
+ grpc_core::DebugLocation debug_location;
+ const char* reason = nullptr;
#endif
- if (GPR_UNLIKELY(cq->owning_refs.Unref(debug_location, reason))) {
+ if (GPR_UNLIKELY(cq->owning_refs.Unref(debug_location, reason))) {
cq->vtable->destroy(DATA_FROM_CQ(cq));
cq->poller_vtable->destroy(POLLSET_FROM_CQ(cq));
#ifndef NDEBUG
@@ -650,23 +650,23 @@ static void cq_check_tag(grpc_completion_queue* cq, void* tag, bool lock_cq) {
GPR_ASSERT(found);
}
#else
-static void cq_check_tag(grpc_completion_queue* /*cq*/, void* /*tag*/,
- bool /*lock_cq*/) {}
+static void cq_check_tag(grpc_completion_queue* /*cq*/, void* /*tag*/,
+ bool /*lock_cq*/) {}
#endif
-static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* /*tag*/) {
+static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* /*tag*/) {
cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
- return cqd->pending_events.IncrementIfNonzero();
+ return cqd->pending_events.IncrementIfNonzero();
}
-static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* /*tag*/) {
+static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* /*tag*/) {
cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
- return cqd->pending_events.IncrementIfNonzero();
+ return cqd->pending_events.IncrementIfNonzero();
}
-static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* /*tag*/) {
+static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* /*tag*/) {
cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
- return cqd->pending_events.IncrementIfNonzero();
+ return cqd->pending_events.IncrementIfNonzero();
}
bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) {
@@ -687,22 +687,22 @@ bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) {
/* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a
* completion
* type of GRPC_CQ_NEXT) */
-static void cq_end_op_for_next(
- grpc_completion_queue* cq, void* tag, grpc_error* error,
- void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
- grpc_cq_completion* storage, bool /*internal*/) {
+static void cq_end_op_for_next(
+ grpc_completion_queue* cq, void* tag, grpc_error* error,
+ void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
+ grpc_cq_completion* storage, bool /*internal*/) {
GPR_TIMER_SCOPE("cq_end_op_for_next", 0);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
- (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
- error != GRPC_ERROR_NONE)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
+ (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
+ error != GRPC_ERROR_NONE)) {
const char* errmsg = grpc_error_string(error);
GRPC_API_TRACE(
"cq_end_op_for_next(cq=%p, tag=%p, error=%s, "
"done=%p, done_arg=%p, storage=%p)",
6, (cq, tag, errmsg, done, done_arg, storage));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
- error != GRPC_ERROR_NONE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
+ error != GRPC_ERROR_NONE) {
gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
}
}
@@ -721,14 +721,14 @@ static void cq_end_op_for_next(
gpr_tls_set(&g_cached_event, (intptr_t)storage);
} else {
/* Add the completion to the queue */
- bool is_first = cqd->queue.Push(storage);
- cqd->things_queued_ever.FetchAdd(1, grpc_core::MemoryOrder::RELAXED);
+ bool is_first = cqd->queue.Push(storage);
+ cqd->things_queued_ever.FetchAdd(1, grpc_core::MemoryOrder::RELAXED);
/* Since we do not hold the cq lock here, it is important to do an 'acquire'
load here (instead of a 'no_barrier' load) to match with the release
store
- (done via pending_events.FetchSub(1, ACQ_REL)) in cq_shutdown_next
+ (done via pending_events.FetchSub(1, ACQ_REL)) in cq_shutdown_next
*/
- if (cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) != 1) {
+ if (cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) != 1) {
/* Only kick if this is the first item queued */
if (is_first) {
gpr_mu_lock(cq->mu);
@@ -742,8 +742,8 @@ static void cq_end_op_for_next(
GRPC_ERROR_UNREF(kick_error);
}
}
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) ==
- 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) ==
+ 1) {
GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
gpr_mu_lock(cq->mu);
cq_finish_shutdown_next(cq);
@@ -752,7 +752,7 @@ static void cq_end_op_for_next(
}
} else {
GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
- cqd->pending_events.Store(0, grpc_core::MemoryOrder::RELEASE);
+ cqd->pending_events.Store(0, grpc_core::MemoryOrder::RELEASE);
gpr_mu_lock(cq->mu);
cq_finish_shutdown_next(cq);
gpr_mu_unlock(cq->mu);
@@ -766,25 +766,25 @@ static void cq_end_op_for_next(
/* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a
* completion
* type of GRPC_CQ_PLUCK) */
-static void cq_end_op_for_pluck(
- grpc_completion_queue* cq, void* tag, grpc_error* error,
- void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
- grpc_cq_completion* storage, bool /*internal*/) {
+static void cq_end_op_for_pluck(
+ grpc_completion_queue* cq, void* tag, grpc_error* error,
+ void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
+ grpc_cq_completion* storage, bool /*internal*/) {
GPR_TIMER_SCOPE("cq_end_op_for_pluck", 0);
cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
int is_success = (error == GRPC_ERROR_NONE);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
- (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
- error != GRPC_ERROR_NONE)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
+ (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
+ error != GRPC_ERROR_NONE)) {
const char* errmsg = grpc_error_string(error);
GRPC_API_TRACE(
"cq_end_op_for_pluck(cq=%p, tag=%p, error=%s, "
"done=%p, done_arg=%p, storage=%p)",
6, (cq, tag, errmsg, done, done_arg, storage));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
- error != GRPC_ERROR_NONE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
+ error != GRPC_ERROR_NONE) {
gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
}
}
@@ -799,12 +799,12 @@ static void cq_end_op_for_pluck(
cq_check_tag(cq, tag, false); /* Used in debug builds only */
/* Add to the list of completions */
- cqd->things_queued_ever.FetchAdd(1, grpc_core::MemoryOrder::RELAXED);
+ cqd->things_queued_ever.FetchAdd(1, grpc_core::MemoryOrder::RELAXED);
cqd->completed_tail->next =
((uintptr_t)storage) | (1u & cqd->completed_tail->next);
cqd->completed_tail = storage;
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
cq_finish_shutdown_pluck(cq);
gpr_mu_unlock(cq->mu);
} else {
@@ -832,30 +832,30 @@ static void cq_end_op_for_pluck(
GRPC_ERROR_UNREF(error);
}
-static void functor_callback(void* arg, grpc_error* error) {
- auto* functor = static_cast<grpc_experimental_completion_queue_functor*>(arg);
- functor->functor_run(functor, error == GRPC_ERROR_NONE);
-}
-
+static void functor_callback(void* arg, grpc_error* error) {
+ auto* functor = static_cast<grpc_experimental_completion_queue_functor*>(arg);
+ functor->functor_run(functor, error == GRPC_ERROR_NONE);
+}
+
/* Complete an event on a completion queue of type GRPC_CQ_CALLBACK */
static void cq_end_op_for_callback(
grpc_completion_queue* cq, void* tag, grpc_error* error,
void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
- grpc_cq_completion* storage, bool internal) {
+ grpc_cq_completion* storage, bool internal) {
GPR_TIMER_SCOPE("cq_end_op_for_callback", 0);
cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
- (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
- error != GRPC_ERROR_NONE)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
+ (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
+ error != GRPC_ERROR_NONE)) {
const char* errmsg = grpc_error_string(error);
GRPC_API_TRACE(
"cq_end_op_for_callback(cq=%p, tag=%p, error=%s, "
"done=%p, done_arg=%p, storage=%p)",
6, (cq, tag, errmsg, done, done_arg, storage));
- if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
- error != GRPC_ERROR_NONE) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) &&
+ error != GRPC_ERROR_NONE) {
gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
}
}
@@ -866,7 +866,7 @@ static void cq_end_op_for_callback(
cq_check_tag(cq, tag, true); /* Used in debug builds only */
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
cq_finish_shutdown_callback(cq);
}
@@ -876,27 +876,27 @@ static void cq_end_op_for_callback(
// 2. The callback is marked inlineable and there is an ACEC available
// 3. We are already running in a background poller thread (which always has
// an ACEC available at the base of the stack).
- auto* functor = static_cast<grpc_experimental_completion_queue_functor*>(tag);
+ auto* functor = static_cast<grpc_experimental_completion_queue_functor*>(tag);
if (((internal || functor->inlineable) &&
grpc_core::ApplicationCallbackExecCtx::Available()) ||
- grpc_iomgr_is_any_background_poller_thread()) {
- grpc_core::ApplicationCallbackExecCtx::Enqueue(functor,
- (error == GRPC_ERROR_NONE));
- GRPC_ERROR_UNREF(error);
- return;
- }
-
- // Schedule the callback on a closure if not internal or triggered
- // from a background poller thread.
- grpc_core::Executor::Run(
- GRPC_CLOSURE_CREATE(functor_callback, functor, nullptr), error);
+ grpc_iomgr_is_any_background_poller_thread()) {
+ grpc_core::ApplicationCallbackExecCtx::Enqueue(functor,
+ (error == GRPC_ERROR_NONE));
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
+
+ // Schedule the callback on a closure if not internal or triggered
+ // from a background poller thread.
+ grpc_core::Executor::Run(
+ GRPC_CLOSURE_CREATE(functor_callback, functor, nullptr), error);
}
void grpc_cq_end_op(grpc_completion_queue* cq, void* tag, grpc_error* error,
void (*done)(void* done_arg, grpc_cq_completion* storage),
- void* done_arg, grpc_cq_completion* storage,
- bool internal) {
- cq->vtable->end_op(cq, tag, error, done, done_arg, storage, internal);
+ void* done_arg, grpc_cq_completion* storage,
+ bool internal) {
+ cq->vtable->end_op(cq, tag, error, done, done_arg, storage, internal);
}
struct cq_is_finished_arg {
@@ -918,20 +918,20 @@ class ExecCtxNext : public grpc_core::ExecCtx {
cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
GPR_ASSERT(a->stolen_completion == nullptr);
- intptr_t current_last_seen_things_queued_ever =
- cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
+ intptr_t current_last_seen_things_queued_ever =
+ cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
if (current_last_seen_things_queued_ever !=
a->last_seen_things_queued_ever) {
a->last_seen_things_queued_ever =
- cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
+ cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
/* Pop a cq_completion from the queue. Returns NULL if the queue is empty
* might return NULL in some cases even if the queue is not empty; but
* that
* is ok and doesn't affect correctness. Might effect the tail latencies a
* bit) */
- a->stolen_completion = cqd->queue.Pop();
+ a->stolen_completion = cqd->queue.Pop();
if (a->stolen_completion != nullptr) {
return true;
}
@@ -945,7 +945,7 @@ class ExecCtxNext : public grpc_core::ExecCtx {
#ifndef NDEBUG
static void dump_pending_tags(grpc_completion_queue* cq) {
- if (!GRPC_TRACE_FLAG_ENABLED(grpc_trace_pending_tags)) return;
+ if (!GRPC_TRACE_FLAG_ENABLED(grpc_trace_pending_tags)) return;
std::vector<TString> parts;
parts.push_back("PENDING TAGS:");
gpr_mu_lock(cq->mu);
@@ -956,7 +956,7 @@ static void dump_pending_tags(grpc_completion_queue* cq) {
gpr_log(GPR_DEBUG, "%s", y_absl::StrJoin(parts, "").c_str());
}
#else
-static void dump_pending_tags(grpc_completion_queue* /*cq*/) {}
+static void dump_pending_tags(grpc_completion_queue* /*cq*/) {}
#endif
static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
@@ -983,7 +983,7 @@ static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
grpc_millis deadline_millis = grpc_timespec_to_millis_round_up(deadline);
cq_is_finished_arg is_finished_arg = {
- cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED),
+ cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED),
cq,
deadline_millis,
nullptr,
@@ -1003,7 +1003,7 @@ static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
break;
}
- grpc_cq_completion* c = cqd->queue.Pop();
+ grpc_cq_completion* c = cqd->queue.Pop();
if (c != nullptr) {
ret.type = GRPC_OP_COMPLETE;
@@ -1017,17 +1017,17 @@ static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
so that the thread comes back quickly from poll to make a second
attempt at popping. Not doing this can potentially deadlock this
thread forever (if the deadline is infinity) */
- if (cqd->queue.num_items() > 0) {
+ if (cqd->queue.num_items() > 0) {
iteration_deadline = 0;
}
}
- if (cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) == 0) {
+ if (cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) == 0) {
/* Before returning, check if the queue has any items left over (since
- MultiProducerSingleConsumerQueue::Pop() can sometimes return NULL
- even if the queue is not empty. If so, keep retrying but do not
- return GRPC_QUEUE_SHUTDOWN */
- if (cqd->queue.num_items() > 0) {
+ MultiProducerSingleConsumerQueue::Pop() can sometimes return NULL
+ even if the queue is not empty. If so, keep retrying but do not
+ return GRPC_QUEUE_SHUTDOWN */
+ if (cqd->queue.num_items() > 0) {
/* Go to the beginning of the loop. No point doing a poll because
(cq->shutdown == true) is only possible when there is no pending
work (i.e cq->pending_events == 0) and any outstanding completion
@@ -1036,14 +1036,14 @@ static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
}
ret.type = GRPC_QUEUE_SHUTDOWN;
- ret.success = 0;
+ ret.success = 0;
break;
}
if (!is_finished_arg.first_loop &&
grpc_core::ExecCtx::Get()->Now() >= deadline_millis) {
ret.type = GRPC_QUEUE_TIMEOUT;
- ret.success = 0;
+ ret.success = 0;
dump_pending_tags(cq);
break;
}
@@ -1061,15 +1061,15 @@ static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
GRPC_ERROR_UNREF(err);
ret.type = GRPC_QUEUE_TIMEOUT;
- ret.success = 0;
+ ret.success = 0;
dump_pending_tags(cq);
break;
}
is_finished_arg.first_loop = false;
}
- if (cqd->queue.num_items() > 0 &&
- cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) > 0) {
+ if (cqd->queue.num_items() > 0 &&
+ cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) > 0) {
gpr_mu_lock(cq->mu);
cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
gpr_mu_unlock(cq->mu);
@@ -1093,7 +1093,7 @@ static void cq_finish_shutdown_next(grpc_completion_queue* cq) {
cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
GPR_ASSERT(cqd->shutdown_called);
- GPR_ASSERT(cqd->pending_events.Load(grpc_core::MemoryOrder::RELAXED) == 0);
+ GPR_ASSERT(cqd->pending_events.Load(grpc_core::MemoryOrder::RELAXED) == 0);
cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
}
@@ -1115,10 +1115,10 @@ static void cq_shutdown_next(grpc_completion_queue* cq) {
return;
}
cqd->shutdown_called = true;
- /* Doing acq/release FetchSub here to match with
- * cq_begin_op_for_next and cq_end_op_for_next functions which read/write
+ /* Doing acq/release FetchSub here to match with
+ * cq_begin_op_for_next and cq_end_op_for_next functions which read/write
* on this counter without necessarily holding a lock on cq */
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
cq_finish_shutdown_next(cq);
}
gpr_mu_unlock(cq->mu);
@@ -1167,12 +1167,12 @@ class ExecCtxPluck : public grpc_core::ExecCtx {
GPR_ASSERT(a->stolen_completion == nullptr);
gpr_atm current_last_seen_things_queued_ever =
- cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
+ cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
if (current_last_seen_things_queued_ever !=
a->last_seen_things_queued_ever) {
gpr_mu_lock(cq->mu);
a->last_seen_things_queued_ever =
- cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
+ cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED);
grpc_cq_completion* c;
grpc_cq_completion* prev = &cqd->completed_head;
while ((c = (grpc_cq_completion*)(prev->next &
@@ -1209,7 +1209,7 @@ static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
grpc_pollset_worker* worker = nullptr;
cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_cq_pluck_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_cq_pluck_trace)) {
GRPC_API_TRACE(
"grpc_completion_queue_pluck("
"cq=%p, tag=%p, "
@@ -1228,7 +1228,7 @@ static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
gpr_mu_lock(cq->mu);
grpc_millis deadline_millis = grpc_timespec_to_millis_round_up(deadline);
cq_is_finished_arg is_finished_arg = {
- cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED),
+ cqd->things_queued_ever.Load(grpc_core::MemoryOrder::RELAXED),
cq,
deadline_millis,
nullptr,
@@ -1265,10 +1265,10 @@ static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
}
prev = c;
}
- if (cqd->shutdown.Load(grpc_core::MemoryOrder::RELAXED)) {
+ if (cqd->shutdown.Load(grpc_core::MemoryOrder::RELAXED)) {
gpr_mu_unlock(cq->mu);
ret.type = GRPC_QUEUE_SHUTDOWN;
- ret.success = 0;
+ ret.success = 0;
break;
}
if (!add_plucker(cq, tag, &worker)) {
@@ -1279,7 +1279,7 @@ static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
gpr_mu_unlock(cq->mu);
/* TODO(ctiller): should we use a different result here */
ret.type = GRPC_QUEUE_TIMEOUT;
- ret.success = 0;
+ ret.success = 0;
dump_pending_tags(cq);
break;
}
@@ -1288,7 +1288,7 @@ static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
del_plucker(cq, tag, &worker);
gpr_mu_unlock(cq->mu);
ret.type = GRPC_QUEUE_TIMEOUT;
- ret.success = 0;
+ ret.success = 0;
dump_pending_tags(cq);
break;
}
@@ -1303,7 +1303,7 @@ static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
GRPC_ERROR_UNREF(err);
ret.type = GRPC_QUEUE_TIMEOUT;
- ret.success = 0;
+ ret.success = 0;
dump_pending_tags(cq);
break;
}
@@ -1328,8 +1328,8 @@ static void cq_finish_shutdown_pluck(grpc_completion_queue* cq) {
cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
GPR_ASSERT(cqd->shutdown_called);
- GPR_ASSERT(!cqd->shutdown.Load(grpc_core::MemoryOrder::RELAXED));
- cqd->shutdown.Store(1, grpc_core::MemoryOrder::RELAXED);
+ GPR_ASSERT(!cqd->shutdown.Load(grpc_core::MemoryOrder::RELAXED));
+ cqd->shutdown.Store(1, grpc_core::MemoryOrder::RELAXED);
cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
}
@@ -1353,7 +1353,7 @@ static void cq_shutdown_pluck(grpc_completion_queue* cq) {
return;
}
cqd->shutdown_called = true;
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
cq_finish_shutdown_pluck(cq);
}
gpr_mu_unlock(cq->mu);
@@ -1367,16 +1367,16 @@ static void cq_finish_shutdown_callback(grpc_completion_queue* cq) {
GPR_ASSERT(cqd->shutdown_called);
cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
- if (grpc_iomgr_is_any_background_poller_thread()) {
- grpc_core::ApplicationCallbackExecCtx::Enqueue(callback, true);
- return;
- }
-
- // Schedule the callback on a closure if not internal or triggered
- // from a background poller thread.
- grpc_core::Executor::Run(
- GRPC_CLOSURE_CREATE(functor_callback, callback, nullptr),
- GRPC_ERROR_NONE);
+ if (grpc_iomgr_is_any_background_poller_thread()) {
+ grpc_core::ApplicationCallbackExecCtx::Enqueue(callback, true);
+ return;
+ }
+
+ // Schedule the callback on a closure if not internal or triggered
+ // from a background poller thread.
+ grpc_core::Executor::Run(
+ GRPC_CLOSURE_CREATE(functor_callback, callback, nullptr),
+ GRPC_ERROR_NONE);
}
static void cq_shutdown_callback(grpc_completion_queue* cq) {
@@ -1396,7 +1396,7 @@ static void cq_shutdown_callback(grpc_completion_queue* cq) {
return;
}
cqd->shutdown_called = true;
- if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
+ if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
gpr_mu_unlock(cq->mu);
cq_finish_shutdown_callback(cq);
} else {
diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue.h b/contrib/libs/grpc/src/core/lib/surface/completion_queue.h
index 4a114be828..9bca20c2c9 100644
--- a/contrib/libs/grpc/src/core/lib/surface/completion_queue.h
+++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue.h
@@ -24,9 +24,9 @@
#include <grpc/support/port_platform.h>
#include <grpc/grpc.h>
-
+
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/iomgr/pollset.h"
/* These trace flags default to 1. The corresponding lines are only traced
@@ -37,8 +37,8 @@ extern grpc_core::DebugOnlyTraceFlag grpc_trace_pending_tags;
extern grpc_core::DebugOnlyTraceFlag grpc_trace_cq_refcount;
typedef struct grpc_cq_completion {
- grpc_core::ManualConstructor<grpc_core::MultiProducerSingleConsumerQueue>
- node;
+ grpc_core::ManualConstructor<grpc_core::MultiProducerSingleConsumerQueue>
+ node;
/** user supplied tag */
void* tag;
@@ -79,8 +79,8 @@ bool grpc_cq_begin_op(grpc_completion_queue* cc, void* tag);
grpc_cq_begin_op */
void grpc_cq_end_op(grpc_completion_queue* cc, void* tag, grpc_error* error,
void (*done)(void* done_arg, grpc_cq_completion* storage),
- void* done_arg, grpc_cq_completion* storage,
- bool internal = false);
+ void* done_arg, grpc_cq_completion* storage,
+ bool internal = false);
grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cc);
diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc b/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc
index 72aa03adfd..62a8ca629d 100644
--- a/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc
@@ -28,7 +28,7 @@
*/
static grpc_completion_queue* default_create(
- const grpc_completion_queue_factory* /*factory*/,
+ const grpc_completion_queue_factory* /*factory*/,
const grpc_completion_queue_attributes* attr) {
return grpc_completion_queue_create_internal(
attr->cq_completion_type, attr->cq_polling_type, attr->cq_shutdown_cb);
diff --git a/contrib/libs/grpc/src/core/lib/surface/init.cc b/contrib/libs/grpc/src/core/lib/surface/init.cc
index 7b79ba426b..a0126b7139 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/init.cc
@@ -36,7 +36,7 @@
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/fork.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/combiner.h"
@@ -65,19 +65,19 @@ extern void grpc_register_built_in_plugins(void);
static gpr_once g_basic_init = GPR_ONCE_INIT;
static gpr_mu g_init_mu;
static int g_initializations;
-static gpr_cv* g_shutting_down_cv;
-static bool g_shutting_down;
+static gpr_cv* g_shutting_down_cv;
+static bool g_shutting_down;
static void do_basic_init(void) {
gpr_log_verbosity_init();
gpr_mu_init(&g_init_mu);
- g_shutting_down_cv = static_cast<gpr_cv*>(malloc(sizeof(gpr_cv)));
- gpr_cv_init(g_shutting_down_cv);
- g_shutting_down = false;
+ g_shutting_down_cv = static_cast<gpr_cv*>(malloc(sizeof(gpr_cv)));
+ gpr_cv_init(g_shutting_down_cv);
+ g_shutting_down = false;
grpc_register_built_in_plugins();
grpc_cq_global_init();
- grpc_core::grpc_executor_global_init();
- gpr_time_init();
+ grpc_core::grpc_executor_global_init();
+ gpr_time_init();
g_initializations = 0;
}
@@ -129,16 +129,16 @@ void grpc_init(void) {
int i;
gpr_once_init(&g_basic_init, do_basic_init);
- grpc_core::MutexLock lock(&g_init_mu);
+ grpc_core::MutexLock lock(&g_init_mu);
if (++g_initializations == 1) {
- if (g_shutting_down) {
- g_shutting_down = false;
- gpr_cv_broadcast(g_shutting_down_cv);
- }
+ if (g_shutting_down) {
+ g_shutting_down = false;
+ gpr_cv_broadcast(g_shutting_down_cv);
+ }
grpc_core::Fork::GlobalInit();
grpc_fork_handlers_auto_register();
grpc_stats_init();
- grpc_init_static_metadata_ctx();
+ grpc_init_static_metadata_ctx();
grpc_slice_intern_init();
grpc_mdctx_global_init();
grpc_channel_init_init();
@@ -159,7 +159,7 @@ void grpc_init(void) {
* at the appropriate time */
grpc_register_security_filters();
register_builtin_channel_init();
- grpc_tracer_init();
+ grpc_tracer_init();
/* no more changes to channel init pipelines */
grpc_channel_init_finalize();
grpc_iomgr_start();
@@ -168,54 +168,54 @@ void grpc_init(void) {
GRPC_API_TRACE("grpc_init(void)", 0, ());
}
-void grpc_shutdown_internal_locked(void) {
+void grpc_shutdown_internal_locked(void) {
int i;
- {
- grpc_core::ExecCtx exec_ctx(0);
- grpc_iomgr_shutdown_background_closure();
+ {
+ grpc_core::ExecCtx exec_ctx(0);
+ grpc_iomgr_shutdown_background_closure();
{
- grpc_timer_manager_set_threading(false); // shutdown timer_manager thread
- grpc_core::Executor::ShutdownAll();
- for (i = g_number_of_plugins; i >= 0; i--) {
- if (g_all_of_the_plugins[i].destroy != nullptr) {
- g_all_of_the_plugins[i].destroy();
+ grpc_timer_manager_set_threading(false); // shutdown timer_manager thread
+ grpc_core::Executor::ShutdownAll();
+ for (i = g_number_of_plugins; i >= 0; i--) {
+ if (g_all_of_the_plugins[i].destroy != nullptr) {
+ g_all_of_the_plugins[i].destroy();
}
}
}
- grpc_iomgr_shutdown();
- gpr_timers_global_destroy();
- grpc_tracer_shutdown();
- grpc_mdctx_global_shutdown();
- grpc_core::HandshakerRegistry::Shutdown();
- grpc_slice_intern_shutdown();
- grpc_core::channelz::ChannelzRegistry::Shutdown();
- grpc_stats_shutdown();
+ grpc_iomgr_shutdown();
+ gpr_timers_global_destroy();
+ grpc_tracer_shutdown();
+ grpc_mdctx_global_shutdown();
+ grpc_core::HandshakerRegistry::Shutdown();
+ grpc_slice_intern_shutdown();
+ grpc_core::channelz::ChannelzRegistry::Shutdown();
+ grpc_stats_shutdown();
}
grpc_core::Fork::GlobalShutdown();
- grpc_core::ExecCtx::GlobalShutdown();
- grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
- g_shutting_down = false;
- gpr_cv_broadcast(g_shutting_down_cv);
- // Absolute last action will be to delete static metadata context.
- grpc_destroy_static_metadata_ctx();
-}
-
-void grpc_shutdown_internal(void* /*ignored*/) {
- GRPC_API_TRACE("grpc_shutdown_internal", 0, ());
- grpc_core::MutexLock lock(&g_init_mu);
- // We have released lock from the shutdown thread and it is possible that
- // another grpc_init has been called, and do nothing if that is the case.
- if (--g_initializations != 0) {
- return;
- }
- grpc_shutdown_internal_locked();
+ grpc_core::ExecCtx::GlobalShutdown();
+ grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
+ g_shutting_down = false;
+ gpr_cv_broadcast(g_shutting_down_cv);
+ // Absolute last action will be to delete static metadata context.
+ grpc_destroy_static_metadata_ctx();
}
-void grpc_shutdown(void) {
- GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
- grpc_core::MutexLock lock(&g_init_mu);
+void grpc_shutdown_internal(void* /*ignored*/) {
+ GRPC_API_TRACE("grpc_shutdown_internal", 0, ());
+ grpc_core::MutexLock lock(&g_init_mu);
+ // We have released lock from the shutdown thread and it is possible that
+ // another grpc_init has been called, and do nothing if that is the case.
+ if (--g_initializations != 0) {
+ return;
+ }
+ grpc_shutdown_internal_locked();
+}
+
+void grpc_shutdown(void) {
+ GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
+ grpc_core::MutexLock lock(&g_init_mu);
- if (--g_initializations == 0) {
+ if (--g_initializations == 0) {
grpc_core::ApplicationCallbackExecCtx* acec =
grpc_core::ApplicationCallbackExecCtx::Get();
if (!grpc_iomgr_is_any_background_poller_thread() &&
@@ -237,31 +237,31 @@ void grpc_shutdown(void) {
grpc_core::Thread::Options().set_joinable(false).set_tracked(false));
cleanup_thread.Start();
}
- }
-}
-
-void grpc_shutdown_blocking(void) {
- GRPC_API_TRACE("grpc_shutdown_blocking(void)", 0, ());
- grpc_core::MutexLock lock(&g_init_mu);
- if (--g_initializations == 0) {
- g_shutting_down = true;
- grpc_shutdown_internal_locked();
- }
-}
-
+ }
+}
+
+void grpc_shutdown_blocking(void) {
+ GRPC_API_TRACE("grpc_shutdown_blocking(void)", 0, ());
+ grpc_core::MutexLock lock(&g_init_mu);
+ if (--g_initializations == 0) {
+ g_shutting_down = true;
+ grpc_shutdown_internal_locked();
+ }
+}
+
int grpc_is_initialized(void) {
int r;
gpr_once_init(&g_basic_init, do_basic_init);
- grpc_core::MutexLock lock(&g_init_mu);
+ grpc_core::MutexLock lock(&g_init_mu);
r = g_initializations > 0;
return r;
}
-
-void grpc_maybe_wait_for_async_shutdown(void) {
- gpr_once_init(&g_basic_init, do_basic_init);
- grpc_core::MutexLock lock(&g_init_mu);
- while (g_shutting_down) {
- gpr_cv_wait(g_shutting_down_cv, &g_init_mu,
- gpr_inf_future(GPR_CLOCK_REALTIME));
- }
-}
+
+void grpc_maybe_wait_for_async_shutdown(void) {
+ gpr_once_init(&g_basic_init, do_basic_init);
+ grpc_core::MutexLock lock(&g_init_mu);
+ while (g_shutting_down) {
+ gpr_cv_wait(g_shutting_down_cv, &g_init_mu,
+ gpr_inf_future(GPR_CLOCK_REALTIME));
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/init.h b/contrib/libs/grpc/src/core/lib/surface/init.h
index 6eaa488d05..442816a6a7 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init.h
+++ b/contrib/libs/grpc/src/core/lib/surface/init.h
@@ -22,6 +22,6 @@
void grpc_register_security_filters(void);
void grpc_security_pre_init(void);
void grpc_security_init(void);
-void grpc_maybe_wait_for_async_shutdown(void);
+void grpc_maybe_wait_for_async_shutdown(void);
#endif /* GRPC_CORE_LIB_SURFACE_INIT_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/init_secure.cc b/contrib/libs/grpc/src/core/lib/surface/init_secure.cc
index 428c5815c9..f05c858904 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init_secure.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/init_secure.cc
@@ -37,7 +37,7 @@
void grpc_security_pre_init(void) {}
static bool maybe_prepend_client_auth_filter(
- grpc_channel_stack_builder* builder, void* /*arg*/) {
+ grpc_channel_stack_builder* builder, void* /*arg*/) {
const grpc_channel_args* args =
grpc_channel_stack_builder_get_channel_arguments(builder);
if (args) {
@@ -52,7 +52,7 @@ static bool maybe_prepend_client_auth_filter(
}
static bool maybe_prepend_server_auth_filter(
- grpc_channel_stack_builder* builder, void* /*arg*/) {
+ grpc_channel_stack_builder* builder, void* /*arg*/) {
const grpc_channel_args* args =
grpc_channel_stack_builder_get_channel_arguments(builder);
if (args) {
diff --git a/contrib/libs/grpc/src/core/lib/surface/lame_client.cc b/contrib/libs/grpc/src/core/lib/surface/lame_client.cc
index a9f5c9c779..ae459a5715 100644
--- a/contrib/libs/grpc/src/core/lib/surface/lame_client.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/lame_client.cc
@@ -27,12 +27,12 @@
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/lame_client.h"
-#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/static_metadata.h"
namespace grpc_core {
@@ -40,36 +40,36 @@ namespace grpc_core {
namespace {
struct CallData {
- CallCombiner* call_combiner;
+ CallCombiner* call_combiner;
grpc_linked_mdelem status;
grpc_linked_mdelem details;
- Atomic<bool> filled_metadata;
+ Atomic<bool> filled_metadata;
};
struct ChannelData {
- ChannelData() : state_tracker("lame_channel", GRPC_CHANNEL_SHUTDOWN) {}
-
+ ChannelData() : state_tracker("lame_channel", GRPC_CHANNEL_SHUTDOWN) {}
+
grpc_status_code error_code;
const char* error_message;
- Mutex mu;
- ConnectivityStateTracker state_tracker;
+ Mutex mu;
+ ConnectivityStateTracker state_tracker;
};
static void fill_metadata(grpc_call_element* elem, grpc_metadata_batch* mdb) {
CallData* calld = static_cast<CallData*>(elem->call_data);
bool expected = false;
- if (!calld->filled_metadata.CompareExchangeStrong(
- &expected, true, MemoryOrder::RELAXED, MemoryOrder::RELAXED)) {
+ if (!calld->filled_metadata.CompareExchangeStrong(
+ &expected, true, MemoryOrder::RELAXED, MemoryOrder::RELAXED)) {
return;
}
ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
char tmp[GPR_LTOA_MIN_BUFSIZE];
gpr_ltoa(chand->error_code, tmp);
calld->status.md = grpc_mdelem_from_slices(
- GRPC_MDSTR_GRPC_STATUS, grpc_core::UnmanagedMemorySlice(tmp));
+ GRPC_MDSTR_GRPC_STATUS, grpc_core::UnmanagedMemorySlice(tmp));
calld->details.md = grpc_mdelem_from_slices(
GRPC_MDSTR_GRPC_MESSAGE,
- grpc_core::UnmanagedMemorySlice(chand->error_message));
+ grpc_core::UnmanagedMemorySlice(chand->error_message));
calld->status.prev = calld->details.next = nullptr;
calld->status.next = &calld->details;
calld->details.prev = &calld->status;
@@ -94,61 +94,61 @@ static void lame_start_transport_stream_op_batch(
calld->call_combiner);
}
-static void lame_get_channel_info(grpc_channel_element* /*elem*/,
- const grpc_channel_info* /*channel_info*/) {}
+static void lame_get_channel_info(grpc_channel_element* /*elem*/,
+ const grpc_channel_info* /*channel_info*/) {}
static void lame_start_transport_op(grpc_channel_element* elem,
grpc_transport_op* op) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- {
- MutexLock lock(&chand->mu);
- if (op->start_connectivity_watch != nullptr) {
- chand->state_tracker.AddWatcher(op->start_connectivity_watch_state,
- std::move(op->start_connectivity_watch));
- }
- if (op->stop_connectivity_watch != nullptr) {
- chand->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
- }
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ {
+ MutexLock lock(&chand->mu);
+ if (op->start_connectivity_watch != nullptr) {
+ chand->state_tracker.AddWatcher(op->start_connectivity_watch_state,
+ std::move(op->start_connectivity_watch));
+ }
+ if (op->stop_connectivity_watch != nullptr) {
+ chand->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
+ }
}
if (op->send_ping.on_initiate != nullptr) {
- ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_initiate,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel"));
+ ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_initiate,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel"));
}
if (op->send_ping.on_ack != nullptr) {
- ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_ack,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel"));
+ ExecCtx::Run(DEBUG_LOCATION, op->send_ping.on_ack,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel"));
}
GRPC_ERROR_UNREF(op->disconnect_with_error);
if (op->on_consumed != nullptr) {
- ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
+ ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE);
}
}
-static grpc_error* lame_init_call_elem(grpc_call_element* elem,
- const grpc_call_element_args* args) {
+static grpc_error* lame_init_call_elem(grpc_call_element* elem,
+ const grpc_call_element_args* args) {
CallData* calld = static_cast<CallData*>(elem->call_data);
calld->call_combiner = args->call_combiner;
return GRPC_ERROR_NONE;
}
-static void lame_destroy_call_elem(grpc_call_element* /*elem*/,
- const grpc_call_final_info* /*final_info*/,
- grpc_closure* then_schedule_closure) {
- ExecCtx::Run(DEBUG_LOCATION, then_schedule_closure, GRPC_ERROR_NONE);
+static void lame_destroy_call_elem(grpc_call_element* /*elem*/,
+ const grpc_call_final_info* /*final_info*/,
+ grpc_closure* then_schedule_closure) {
+ ExecCtx::Run(DEBUG_LOCATION, then_schedule_closure, GRPC_ERROR_NONE);
}
-static grpc_error* lame_init_channel_elem(grpc_channel_element* elem,
- grpc_channel_element_args* args) {
+static grpc_error* lame_init_channel_elem(grpc_channel_element* elem,
+ grpc_channel_element_args* args) {
GPR_ASSERT(args->is_first);
GPR_ASSERT(args->is_last);
- new (elem->channel_data) ChannelData;
+ new (elem->channel_data) ChannelData;
return GRPC_ERROR_NONE;
}
-static void lame_destroy_channel_elem(grpc_channel_element* elem) {
- ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- chand->~ChannelData();
-}
+static void lame_destroy_channel_elem(grpc_channel_element* elem) {
+ ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
+ chand->~ChannelData();
+}
} // namespace
@@ -158,12 +158,12 @@ const grpc_channel_filter grpc_lame_filter = {
grpc_core::lame_start_transport_stream_op_batch,
grpc_core::lame_start_transport_op,
sizeof(grpc_core::CallData),
- grpc_core::lame_init_call_elem,
+ grpc_core::lame_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
- grpc_core::lame_destroy_call_elem,
+ grpc_core::lame_destroy_call_elem,
sizeof(grpc_core::ChannelData),
- grpc_core::lame_init_channel_elem,
- grpc_core::lame_destroy_channel_elem,
+ grpc_core::lame_init_channel_elem,
+ grpc_core::lame_destroy_channel_elem,
grpc_core::lame_get_channel_info,
"lame-client",
};
diff --git a/contrib/libs/grpc/src/core/lib/surface/server.cc b/contrib/libs/grpc/src/core/lib/surface/server.cc
index 0775c6ee4c..fe6cb6a3de 100644
--- a/contrib/libs/grpc/src/core/lib/surface/server.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/server.cc
@@ -37,12 +37,12 @@
#include <grpc/support/string_util.h>
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channelz.h"
+#include "src/core/lib/channel/channelz.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/spinlock.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/mpscq.h"
+#include "src/core/lib/gprpp/mpscq.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/slice/slice_internal.h"
@@ -57,7 +57,7 @@
namespace grpc_core {
TraceFlag grpc_server_channel_trace(false, "server_channel");
-
+
//
// Server::RequestedCall
//
diff --git a/contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc b/contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc
index 138f5745e5..4ee3bc5b6d 100644
--- a/contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc
@@ -24,14 +24,14 @@
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/surface/validate_metadata.h"
-static grpc_error* conforms_to(const grpc_slice& slice,
- const uint8_t* legal_bits,
+static grpc_error* conforms_to(const grpc_slice& slice,
+ const uint8_t* legal_bits,
const char* err_desc) {
const uint8_t* p = GRPC_SLICE_START_PTR(slice);
const uint8_t* e = GRPC_SLICE_END_PTR(slice);
@@ -44,8 +44,8 @@ static grpc_error* conforms_to(const grpc_slice& slice,
grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_desc),
GRPC_ERROR_INT_OFFSET,
p - GRPC_SLICE_START_PTR(slice)),
- GRPC_ERROR_STR_RAW_BYTES,
- grpc_dump_slice_to_slice(slice, GPR_DUMP_HEX | GPR_DUMP_ASCII));
+ GRPC_ERROR_STR_RAW_BYTES,
+ grpc_dump_slice_to_slice(slice, GPR_DUMP_HEX | GPR_DUMP_ASCII));
return error;
}
}
@@ -58,7 +58,7 @@ static int error2int(grpc_error* error) {
return r;
}
-grpc_error* grpc_validate_header_key_is_legal(const grpc_slice& slice) {
+grpc_error* grpc_validate_header_key_is_legal(const grpc_slice& slice) {
static const uint8_t legal_header_bits[256 / 8] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0x00, 0x00, 0x00,
0x80, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -67,10 +67,10 @@ grpc_error* grpc_validate_header_key_is_legal(const grpc_slice& slice) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Metadata keys cannot be zero length");
}
- if (GRPC_SLICE_LENGTH(slice) > UINT32_MAX) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Metadata keys cannot be larger than UINT32_MAX");
- }
+ if (GRPC_SLICE_LENGTH(slice) > UINT32_MAX) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Metadata keys cannot be larger than UINT32_MAX");
+ }
if (GRPC_SLICE_START_PTR(slice)[0] == ':') {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Metadata keys cannot start with :");
@@ -82,8 +82,8 @@ int grpc_header_key_is_legal(grpc_slice slice) {
return error2int(grpc_validate_header_key_is_legal(slice));
}
-grpc_error* grpc_validate_header_nonbin_value_is_legal(
- const grpc_slice& slice) {
+grpc_error* grpc_validate_header_nonbin_value_is_legal(
+ const grpc_slice& slice) {
static const uint8_t legal_header_bits[256 / 8] = {
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -95,11 +95,11 @@ int grpc_header_nonbin_value_is_legal(grpc_slice slice) {
return error2int(grpc_validate_header_nonbin_value_is_legal(slice));
}
-int grpc_is_binary_header_internal(const grpc_slice& slice) {
- return grpc_key_is_binary_header(GRPC_SLICE_START_PTR(slice),
- GRPC_SLICE_LENGTH(slice));
-}
-
+int grpc_is_binary_header_internal(const grpc_slice& slice) {
+ return grpc_key_is_binary_header(GRPC_SLICE_START_PTR(slice),
+ GRPC_SLICE_LENGTH(slice));
+}
+
int grpc_is_binary_header(grpc_slice slice) {
- return grpc_is_binary_header_internal(slice);
+ return grpc_is_binary_header_internal(slice);
}
diff --git a/contrib/libs/grpc/src/core/lib/surface/validate_metadata.h b/contrib/libs/grpc/src/core/lib/surface/validate_metadata.h
index db3be684c1..ecb96a4805 100644
--- a/contrib/libs/grpc/src/core/lib/surface/validate_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/surface/validate_metadata.h
@@ -24,18 +24,18 @@
#include <grpc/slice.h>
#include "src/core/lib/iomgr/error.h"
-grpc_error* grpc_validate_header_key_is_legal(const grpc_slice& slice);
-grpc_error* grpc_validate_header_nonbin_value_is_legal(const grpc_slice& slice);
-
-int grpc_is_binary_header_internal(const grpc_slice& slice);
-inline int grpc_key_is_binary_header(const uint8_t* buf, size_t length) {
- if (length < 5) return 0;
- return 0 == memcmp(buf + length - 4, "-bin", 4);
-}
-inline int grpc_is_refcounted_slice_binary_header(const grpc_slice& slice) {
- GPR_DEBUG_ASSERT(slice.refcount != nullptr);
- return grpc_key_is_binary_header(slice.data.refcounted.bytes,
- slice.data.refcounted.length);
-}
+grpc_error* grpc_validate_header_key_is_legal(const grpc_slice& slice);
+grpc_error* grpc_validate_header_nonbin_value_is_legal(const grpc_slice& slice);
+int grpc_is_binary_header_internal(const grpc_slice& slice);
+inline int grpc_key_is_binary_header(const uint8_t* buf, size_t length) {
+ if (length < 5) return 0;
+ return 0 == memcmp(buf + length - 4, "-bin", 4);
+}
+inline int grpc_is_refcounted_slice_binary_header(const grpc_slice& slice) {
+ GPR_DEBUG_ASSERT(slice.refcount != nullptr);
+ return grpc_key_is_binary_header(slice.data.refcounted.bytes,
+ slice.data.refcounted.length);
+}
+
#endif /* GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc b/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc
index 8835e32bcf..584ca4cb1a 100644
--- a/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc
@@ -46,7 +46,7 @@ grpc_millis BdpEstimator::CompletePing() {
1e-9 * static_cast<double>(dt_ts.tv_nsec);
double bw = dt > 0 ? (static_cast<double>(accumulator_) / dt) : 0;
int start_inter_ping_delay = inter_ping_delay_;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
gpr_log(GPR_INFO,
"bdp[%s]:complete acc=%" PRId64 " est=%" PRId64
" dt=%lf bw=%lfMbs bw_est=%lfMbs",
@@ -57,7 +57,7 @@ grpc_millis BdpEstimator::CompletePing() {
if (accumulator_ > 2 * estimate_ / 3 && bw > bw_est_) {
estimate_ = GPR_MAX(accumulator_, estimate_ * 2);
bw_est_ = bw;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
gpr_log(GPR_INFO, "bdp[%s]: estimate increased to %" PRId64, name_,
estimate_);
}
@@ -74,7 +74,7 @@ grpc_millis BdpEstimator::CompletePing() {
}
if (start_inter_ping_delay != inter_ping_delay_) {
stable_estimate_count_ = 0;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
gpr_log(GPR_INFO, "bdp[%s]:update_inter_time to %dms", name_,
inter_ping_delay_);
}
diff --git a/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h b/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h
index 7eb336d8bb..2b1f64195b 100644
--- a/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h
+++ b/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h
@@ -49,7 +49,7 @@ class BdpEstimator {
// grpc_bdp_estimator_add_incoming_bytes once a ping has been scheduled by a
// transport (but not necessarily started)
void SchedulePing() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
gpr_log(GPR_INFO, "bdp[%s]:sched acc=%" PRId64 " est=%" PRId64, name_,
accumulator_, estimate_);
}
@@ -62,7 +62,7 @@ class BdpEstimator {
// once
// the ping is on the wire
void StartPing() {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
gpr_log(GPR_INFO, "bdp[%s]:start acc=%" PRId64 " est=%" PRId64, name_,
accumulator_, estimate_);
}
diff --git a/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc b/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc
index 82f34ca150..9872fc2e6d 100644
--- a/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc
@@ -53,17 +53,17 @@ void SliceBufferByteStream::Orphan() {
// filter stack.
}
-bool SliceBufferByteStream::Next(size_t /*max_size_hint*/,
- grpc_closure* /*on_complete*/) {
- GPR_DEBUG_ASSERT(backing_buffer_.count > 0);
+bool SliceBufferByteStream::Next(size_t /*max_size_hint*/,
+ grpc_closure* /*on_complete*/) {
+ GPR_DEBUG_ASSERT(backing_buffer_.count > 0);
return true;
}
grpc_error* SliceBufferByteStream::Pull(grpc_slice* slice) {
- if (GPR_UNLIKELY(shutdown_error_ != GRPC_ERROR_NONE)) {
+ if (GPR_UNLIKELY(shutdown_error_ != GRPC_ERROR_NONE)) {
return GRPC_ERROR_REF(shutdown_error_);
}
- *slice = grpc_slice_buffer_take_first(&backing_buffer_);
+ *slice = grpc_slice_buffer_take_first(&backing_buffer_);
return GRPC_ERROR_NONE;
}
diff --git a/contrib/libs/grpc/src/core/lib/transport/byte_stream.h b/contrib/libs/grpc/src/core/lib/transport/byte_stream.h
index ecb605ad9b..59b575a7f3 100644
--- a/contrib/libs/grpc/src/core/lib/transport/byte_stream.h
+++ b/contrib/libs/grpc/src/core/lib/transport/byte_stream.h
@@ -45,18 +45,18 @@ class ByteStream : public Orphanable {
// Returns true if the bytes are available immediately (in which case
// on_complete will not be called), or false if the bytes will be available
// asynchronously (in which case on_complete will be called when they
- // are available). Should not be called if there is no data left on the
- // stream.
+ // are available). Should not be called if there is no data left on the
+ // stream.
//
// max_size_hint can be set as a hint as to the maximum number
// of bytes that would be acceptable to read.
- virtual bool Next(size_t max_size_hint, grpc_closure* on_complete) = 0;
+ virtual bool Next(size_t max_size_hint, grpc_closure* on_complete) = 0;
// Returns the next slice in the byte stream when it is available, as
// indicated by Next().
//
// Once a slice is returned into *slice, it is owned by the caller.
- virtual grpc_error* Pull(grpc_slice* slice) = 0;
+ virtual grpc_error* Pull(grpc_slice* slice) = 0;
// Shuts down the byte stream.
//
@@ -65,7 +65,7 @@ class ByteStream : public Orphanable {
//
// The next call to Pull() (if any) will return the error passed to
// Shutdown().
- virtual void Shutdown(grpc_error* error) = 0;
+ virtual void Shutdown(grpc_error* error) = 0;
uint32_t length() const { return length_; }
uint32_t flags() const { return flags_; }
@@ -101,7 +101,7 @@ class SliceBufferByteStream : public ByteStream {
void Shutdown(grpc_error* error) override;
private:
- grpc_error* shutdown_error_ = GRPC_ERROR_NONE;
+ grpc_error* shutdown_error_ = GRPC_ERROR_NONE;
grpc_slice_buffer backing_buffer_;
};
diff --git a/contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc b/contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc
index 7b13049017..25e78b9b4b 100644
--- a/contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc
@@ -26,14 +26,14 @@
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
-#include "src/core/lib/iomgr/combiner.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-
-namespace grpc_core {
-
-TraceFlag grpc_connectivity_state_trace(false, "connectivity_state");
-
-const char* ConnectivityStateName(grpc_connectivity_state state) {
+#include "src/core/lib/iomgr/combiner.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+namespace grpc_core {
+
+TraceFlag grpc_connectivity_state_trace(false, "connectivity_state");
+
+const char* ConnectivityStateName(grpc_connectivity_state state) {
switch (state) {
case GRPC_CHANNEL_IDLE:
return "IDLE";
@@ -49,15 +49,15 @@ const char* ConnectivityStateName(grpc_connectivity_state state) {
GPR_UNREACHABLE_CODE(return "UNKNOWN");
}
-//
-// AsyncConnectivityStateWatcherInterface
-//
+//
+// AsyncConnectivityStateWatcherInterface
+//
-// A fire-and-forget class to asynchronously deliver a connectivity
-// state notification to a watcher.
-class AsyncConnectivityStateWatcherInterface::Notifier {
- public:
- Notifier(RefCountedPtr<AsyncConnectivityStateWatcherInterface> watcher,
+// A fire-and-forget class to asynchronously deliver a connectivity
+// state notification to a watcher.
+class AsyncConnectivityStateWatcherInterface::Notifier {
+ public:
+ Notifier(RefCountedPtr<AsyncConnectivityStateWatcherInterface> watcher,
grpc_connectivity_state state, const y_absl::Status& status,
const std::shared_ptr<WorkSerializer>& work_serializer)
: watcher_(std::move(watcher)), state_(state), status_(status) {
@@ -66,120 +66,120 @@ class AsyncConnectivityStateWatcherInterface::Notifier {
[this]() { SendNotification(this, GRPC_ERROR_NONE); },
DEBUG_LOCATION);
} else {
- GRPC_CLOSURE_INIT(&closure_, SendNotification, this,
- grpc_schedule_on_exec_ctx);
- ExecCtx::Run(DEBUG_LOCATION, &closure_, GRPC_ERROR_NONE);
+ GRPC_CLOSURE_INIT(&closure_, SendNotification, this,
+ grpc_schedule_on_exec_ctx);
+ ExecCtx::Run(DEBUG_LOCATION, &closure_, GRPC_ERROR_NONE);
}
}
-
- private:
- static void SendNotification(void* arg, grpc_error* /*ignored*/) {
- Notifier* self = static_cast<Notifier*>(arg);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+
+ private:
+ static void SendNotification(void* arg, grpc_error* /*ignored*/) {
+ Notifier* self = static_cast<Notifier*>(arg);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
gpr_log(GPR_INFO, "watcher %p: delivering async notification for %s (%s)",
self->watcher_.get(), ConnectivityStateName(self->state_),
self->status_.ToString().c_str());
- }
+ }
self->watcher_->OnConnectivityStateChange(self->state_, self->status_);
- delete self;
- }
-
- RefCountedPtr<AsyncConnectivityStateWatcherInterface> watcher_;
- const grpc_connectivity_state state_;
+ delete self;
+ }
+
+ RefCountedPtr<AsyncConnectivityStateWatcherInterface> watcher_;
+ const grpc_connectivity_state state_;
const y_absl::Status status_;
- grpc_closure closure_;
-};
-
-void AsyncConnectivityStateWatcherInterface::Notify(
+ grpc_closure closure_;
+};
+
+void AsyncConnectivityStateWatcherInterface::Notify(
grpc_connectivity_state state, const y_absl::Status& status) {
new Notifier(Ref(), state, status,
work_serializer_); // Deletes itself when done.
}
-//
-// ConnectivityStateTracker
-//
-
-ConnectivityStateTracker::~ConnectivityStateTracker() {
- grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
- if (current_state == GRPC_CHANNEL_SHUTDOWN) return;
- for (const auto& p : watchers_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
- gpr_log(GPR_INFO,
- "ConnectivityStateTracker %s[%p]: notifying watcher %p: %s -> %s",
- name_, this, p.first, ConnectivityStateName(current_state),
- ConnectivityStateName(GRPC_CHANNEL_SHUTDOWN));
- }
+//
+// ConnectivityStateTracker
+//
+
+ConnectivityStateTracker::~ConnectivityStateTracker() {
+ grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
+ if (current_state == GRPC_CHANNEL_SHUTDOWN) return;
+ for (const auto& p : watchers_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ gpr_log(GPR_INFO,
+ "ConnectivityStateTracker %s[%p]: notifying watcher %p: %s -> %s",
+ name_, this, p.first, ConnectivityStateName(current_state),
+ ConnectivityStateName(GRPC_CHANNEL_SHUTDOWN));
+ }
p.second->Notify(GRPC_CHANNEL_SHUTDOWN, y_absl::Status());
}
}
-void ConnectivityStateTracker::AddWatcher(
- grpc_connectivity_state initial_state,
- OrphanablePtr<ConnectivityStateWatcherInterface> watcher) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
- gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: add watcher %p", name_,
- this, watcher.get());
+void ConnectivityStateTracker::AddWatcher(
+ grpc_connectivity_state initial_state,
+ OrphanablePtr<ConnectivityStateWatcherInterface> watcher) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: add watcher %p", name_,
+ this, watcher.get());
}
- grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
- if (initial_state != current_state) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
- gpr_log(GPR_INFO,
- "ConnectivityStateTracker %s[%p]: notifying watcher %p: %s -> %s",
- name_, this, watcher.get(), ConnectivityStateName(initial_state),
- ConnectivityStateName(current_state));
- }
+ grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
+ if (initial_state != current_state) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ gpr_log(GPR_INFO,
+ "ConnectivityStateTracker %s[%p]: notifying watcher %p: %s -> %s",
+ name_, this, watcher.get(), ConnectivityStateName(initial_state),
+ ConnectivityStateName(current_state));
+ }
watcher->Notify(current_state, status_);
}
- // If we're in state SHUTDOWN, don't add the watcher, so that it will
- // be orphaned immediately.
- if (current_state != GRPC_CHANNEL_SHUTDOWN) {
- watchers_.insert(std::make_pair(watcher.get(), std::move(watcher)));
- }
+ // If we're in state SHUTDOWN, don't add the watcher, so that it will
+ // be orphaned immediately.
+ if (current_state != GRPC_CHANNEL_SHUTDOWN) {
+ watchers_.insert(std::make_pair(watcher.get(), std::move(watcher)));
+ }
}
-void ConnectivityStateTracker::RemoveWatcher(
- ConnectivityStateWatcherInterface* watcher) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
- gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: remove watcher %p",
- name_, this, watcher);
- }
- watchers_.erase(watcher);
+void ConnectivityStateTracker::RemoveWatcher(
+ ConnectivityStateWatcherInterface* watcher) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: remove watcher %p",
+ name_, this, watcher);
+ }
+ watchers_.erase(watcher);
}
-void ConnectivityStateTracker::SetState(grpc_connectivity_state state,
+void ConnectivityStateTracker::SetState(grpc_connectivity_state state,
const y_absl::Status& status,
- const char* reason) {
- grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
- if (state == current_state) return;
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ const char* reason) {
+ grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
+ if (state == current_state) return;
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: %s -> %s (%s, %s)",
name_, this, ConnectivityStateName(current_state),
ConnectivityStateName(state), reason, status.ToString().c_str());
}
- state_.Store(state, MemoryOrder::RELAXED);
+ state_.Store(state, MemoryOrder::RELAXED);
status_ = status;
- for (const auto& p : watchers_) {
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
- gpr_log(GPR_INFO,
- "ConnectivityStateTracker %s[%p]: notifying watcher %p: %s -> %s",
- name_, this, p.first, ConnectivityStateName(current_state),
- ConnectivityStateName(state));
+ for (const auto& p : watchers_) {
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ gpr_log(GPR_INFO,
+ "ConnectivityStateTracker %s[%p]: notifying watcher %p: %s -> %s",
+ name_, this, p.first, ConnectivityStateName(current_state),
+ ConnectivityStateName(state));
}
p.second->Notify(state, status);
}
- // If the new state is SHUTDOWN, orphan all of the watchers. This
- // avoids the need for the callers to explicitly cancel them.
- if (state == GRPC_CHANNEL_SHUTDOWN) watchers_.clear();
+ // If the new state is SHUTDOWN, orphan all of the watchers. This
+ // avoids the need for the callers to explicitly cancel them.
+ if (state == GRPC_CHANNEL_SHUTDOWN) watchers_.clear();
}
-grpc_connectivity_state ConnectivityStateTracker::state() const {
- grpc_connectivity_state state = state_.Load(MemoryOrder::RELAXED);
- if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
- gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: get current state: %s",
- name_, this, ConnectivityStateName(state));
+grpc_connectivity_state ConnectivityStateTracker::state() const {
+ grpc_connectivity_state state = state_.Load(MemoryOrder::RELAXED);
+ if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
+ gpr_log(GPR_INFO, "ConnectivityStateTracker %s[%p]: get current state: %s",
+ name_, this, ConnectivityStateName(state));
}
- return state;
+ return state;
}
-
-} // namespace grpc_core
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/transport/connectivity_state.h b/contrib/libs/grpc/src/core/lib/transport/connectivity_state.h
index 9e34c646c7..ee4ed854b5 100644
--- a/contrib/libs/grpc/src/core/lib/transport/connectivity_state.h
+++ b/contrib/libs/grpc/src/core/lib/transport/connectivity_state.h
@@ -24,54 +24,54 @@
#include "y_absl/status/status.h"
#include <grpc/grpc.h>
-
+
#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/gprpp/map.h"
-#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/map.h"
+#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/work_serializer.h"
-namespace grpc_core {
+namespace grpc_core {
-extern TraceFlag grpc_connectivity_state_trace;
+extern TraceFlag grpc_connectivity_state_trace;
-// Enum to string conversion.
-const char* ConnectivityStateName(grpc_connectivity_state state);
+// Enum to string conversion.
+const char* ConnectivityStateName(grpc_connectivity_state state);
-// Interface for watching connectivity state.
-// Subclasses must implement the Notify() method.
-//
-// Note: Most callers will want to use
-// AsyncConnectivityStateWatcherInterface instead.
-class ConnectivityStateWatcherInterface
- : public InternallyRefCounted<ConnectivityStateWatcherInterface> {
- public:
- virtual ~ConnectivityStateWatcherInterface() = default;
+// Interface for watching connectivity state.
+// Subclasses must implement the Notify() method.
+//
+// Note: Most callers will want to use
+// AsyncConnectivityStateWatcherInterface instead.
+class ConnectivityStateWatcherInterface
+ : public InternallyRefCounted<ConnectivityStateWatcherInterface> {
+ public:
+ virtual ~ConnectivityStateWatcherInterface() = default;
- // Notifies the watcher that the state has changed to new_state.
+ // Notifies the watcher that the state has changed to new_state.
virtual void Notify(grpc_connectivity_state new_state,
const y_absl::Status& status) = 0;
- void Orphan() override { Unref(); }
-};
+ void Orphan() override { Unref(); }
+};
-// An alternative watcher interface that performs notifications via an
-// asynchronous callback scheduled on the ExecCtx.
-// Subclasses must implement the OnConnectivityStateChange() method.
-class AsyncConnectivityStateWatcherInterface
- : public ConnectivityStateWatcherInterface {
- public:
- virtual ~AsyncConnectivityStateWatcherInterface() = default;
+// An alternative watcher interface that performs notifications via an
+// asynchronous callback scheduled on the ExecCtx.
+// Subclasses must implement the OnConnectivityStateChange() method.
+class AsyncConnectivityStateWatcherInterface
+ : public ConnectivityStateWatcherInterface {
+ public:
+ virtual ~AsyncConnectivityStateWatcherInterface() = default;
- // Schedules a closure on the ExecCtx to invoke
- // OnConnectivityStateChange() asynchronously.
+ // Schedules a closure on the ExecCtx to invoke
+ // OnConnectivityStateChange() asynchronously.
void Notify(grpc_connectivity_state new_state,
const y_absl::Status& status) override final;
- protected:
- class Notifier;
+ protected:
+ class Notifier;
// If \a work_serializer is nullptr, then the notification will be scheduled
// on the ExecCtx.
@@ -79,65 +79,65 @@ class AsyncConnectivityStateWatcherInterface
std::shared_ptr<WorkSerializer> work_serializer = nullptr)
: work_serializer_(std::move(work_serializer)) {}
- // Invoked asynchronously when Notify() is called.
+ // Invoked asynchronously when Notify() is called.
virtual void OnConnectivityStateChange(grpc_connectivity_state new_state,
const y_absl::Status& status) = 0;
-
- private:
+
+ private:
std::shared_ptr<WorkSerializer> work_serializer_;
-};
-
-// Tracks connectivity state. Maintains a list of watchers that are
-// notified whenever the state changes.
-//
-// Note that once the state becomes SHUTDOWN, watchers will be notified
-// and then automatically orphaned (i.e., RemoveWatcher() does not need
-// to be called).
-class ConnectivityStateTracker {
- public:
- ConnectivityStateTracker(const char* name,
+};
+
+// Tracks connectivity state. Maintains a list of watchers that are
+// notified whenever the state changes.
+//
+// Note that once the state becomes SHUTDOWN, watchers will be notified
+// and then automatically orphaned (i.e., RemoveWatcher() does not need
+// to be called).
+class ConnectivityStateTracker {
+ public:
+ ConnectivityStateTracker(const char* name,
grpc_connectivity_state state = GRPC_CHANNEL_IDLE,
const y_absl::Status& status = y_absl::Status())
: name_(name), state_(state), status_(status) {}
-
- ~ConnectivityStateTracker();
-
- // Adds a watcher.
- // If the current state is different than initial_state, the watcher
- // will be notified immediately. Otherwise, it will be notified
- // whenever the state changes.
- // Not thread safe; access must be serialized with an external lock.
- void AddWatcher(grpc_connectivity_state initial_state,
- OrphanablePtr<ConnectivityStateWatcherInterface> watcher);
-
- // Removes a watcher. The watcher will be orphaned.
- // Not thread safe; access must be serialized with an external lock.
- void RemoveWatcher(ConnectivityStateWatcherInterface* watcher);
-
- // Sets connectivity state.
- // Not thread safe; access must be serialized with an external lock.
+
+ ~ConnectivityStateTracker();
+
+ // Adds a watcher.
+ // If the current state is different than initial_state, the watcher
+ // will be notified immediately. Otherwise, it will be notified
+ // whenever the state changes.
+ // Not thread safe; access must be serialized with an external lock.
+ void AddWatcher(grpc_connectivity_state initial_state,
+ OrphanablePtr<ConnectivityStateWatcherInterface> watcher);
+
+ // Removes a watcher. The watcher will be orphaned.
+ // Not thread safe; access must be serialized with an external lock.
+ void RemoveWatcher(ConnectivityStateWatcherInterface* watcher);
+
+ // Sets connectivity state.
+ // Not thread safe; access must be serialized with an external lock.
void SetState(grpc_connectivity_state state, const y_absl::Status& status,
const char* reason);
-
- // Gets the current state.
- // Thread safe; no need to use an external lock.
- grpc_connectivity_state state() const;
-
+
+ // Gets the current state.
+ // Thread safe; no need to use an external lock.
+ grpc_connectivity_state state() const;
+
// Get the current status.
// Not thread safe; access must be serialized with an external lock.
y_absl::Status status() const { return status_; }
- private:
- const char* name_;
- Atomic<grpc_connectivity_state> state_;
+ private:
+ const char* name_;
+ Atomic<grpc_connectivity_state> state_;
y_absl::Status status_;
- // TODO(roth): Once we can use C++-14 heterogeneous lookups, this can
- // be a set instead of a map.
- std::map<ConnectivityStateWatcherInterface*,
- OrphanablePtr<ConnectivityStateWatcherInterface>>
- watchers_;
-};
-
-} // namespace grpc_core
-
+ // TODO(roth): Once we can use C++-14 heterogeneous lookups, this can
+ // be a set instead of a map.
+ std::map<ConnectivityStateWatcherInterface*,
+ OrphanablePtr<ConnectivityStateWatcherInterface>>
+ watchers_;
+};
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_TRANSPORT_CONNECTIVITY_STATE_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/error_utils.cc b/contrib/libs/grpc/src/core/lib/transport/error_utils.cc
index 9634f09ad1..043564b5db 100644
--- a/contrib/libs/grpc/src/core/lib/transport/error_utils.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/error_utils.cc
@@ -22,7 +22,7 @@
#include <grpc/support/string_util.h>
#include "src/core/lib/iomgr/error_internal.h"
-#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/transport/status_conversion.h"
static grpc_error* recursively_find_error_with_field(grpc_error* error,
@@ -49,26 +49,26 @@ void grpc_error_get_status(grpc_error* error, grpc_millis deadline,
grpc_status_code* code, grpc_slice* slice,
grpc_http2_error_code* http_error,
const char** error_string) {
- // Fast path: We expect no error.
- if (GPR_LIKELY(error == GRPC_ERROR_NONE)) {
- if (code != nullptr) *code = GRPC_STATUS_OK;
- if (slice != nullptr) {
- // Normally, we call grpc_error_get_str(
- // error, GRPC_ERROR_STR_GRPC_MESSAGE, slice).
- // We can fastpath since we know that:
- // 1) Error is null
- // 2) which == GRPC_ERROR_STR_GRPC_MESSAGE
- // 3) The resulting slice is statically known.
- // 4) Said resulting slice is of length 0 ("").
- // This means 3 movs, instead of 10s of instructions and a strlen.
- *slice = grpc_core::ExternallyManagedSlice("");
- }
- if (http_error != nullptr) {
- *http_error = GRPC_HTTP2_NO_ERROR;
- }
- return;
- }
-
+ // Fast path: We expect no error.
+ if (GPR_LIKELY(error == GRPC_ERROR_NONE)) {
+ if (code != nullptr) *code = GRPC_STATUS_OK;
+ if (slice != nullptr) {
+ // Normally, we call grpc_error_get_str(
+ // error, GRPC_ERROR_STR_GRPC_MESSAGE, slice).
+ // We can fastpath since we know that:
+ // 1) Error is null
+ // 2) which == GRPC_ERROR_STR_GRPC_MESSAGE
+ // 3) The resulting slice is statically known.
+ // 4) Said resulting slice is of length 0 ("").
+ // This means 3 movs, instead of 10s of instructions and a strlen.
+ *slice = grpc_core::ExternallyManagedSlice("");
+ }
+ if (http_error != nullptr) {
+ *http_error = GRPC_HTTP2_NO_ERROR;
+ }
+ return;
+ }
+
// Start with the parent error and recurse through the tree of children
// until we find the first one that has a status code.
grpc_error* found_error =
diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata.cc b/contrib/libs/grpc/src/core/lib/transport/metadata.cc
index 33d4d5ac70..02fcebf743 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata.cc
@@ -41,11 +41,11 @@
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/transport/static_metadata.h"
-using grpc_core::AllocatedMetadata;
-using grpc_core::InternedMetadata;
-using grpc_core::StaticMetadata;
-using grpc_core::UserData;
-
+using grpc_core::AllocatedMetadata;
+using grpc_core::InternedMetadata;
+using grpc_core::StaticMetadata;
+using grpc_core::UserData;
+
/* There are two kinds of mdelem and mdstr instances.
* Static instances are declared in static_metadata.{h,c} and
* are initialized by grpc_mdctx_global_init().
@@ -59,40 +59,40 @@ grpc_core::DebugOnlyTraceFlag grpc_trace_metadata(false, "metadata");
#ifndef NDEBUG
#define DEBUG_ARGS , const char *file, int line
-#define FWD_DEBUG_ARGS file, line
-
-void grpc_mdelem_trace_ref(void* md, const grpc_slice& key,
- const grpc_slice& value, intptr_t refcnt,
- const char* file, int line) {
- if (grpc_trace_metadata.enabled()) {
- char* key_str = grpc_slice_to_c_string(key);
- char* value_str = grpc_slice_to_c_string(value);
- gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
- "mdelem REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", md,
- refcnt, refcnt + 1, key_str, value_str);
- gpr_free(key_str);
- gpr_free(value_str);
- }
-}
-
-void grpc_mdelem_trace_unref(void* md, const grpc_slice& key,
- const grpc_slice& value, intptr_t refcnt,
- const char* file, int line) {
- if (grpc_trace_metadata.enabled()) {
- char* key_str = grpc_slice_to_c_string(key);
- char* value_str = grpc_slice_to_c_string(value);
- gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
- "mdelem UNREF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", md,
- refcnt, refcnt - 1, key_str, value_str);
- gpr_free(key_str);
- gpr_free(value_str);
- }
-}
-
-#else // ifndef NDEBUG
+#define FWD_DEBUG_ARGS file, line
+
+void grpc_mdelem_trace_ref(void* md, const grpc_slice& key,
+ const grpc_slice& value, intptr_t refcnt,
+ const char* file, int line) {
+ if (grpc_trace_metadata.enabled()) {
+ char* key_str = grpc_slice_to_c_string(key);
+ char* value_str = grpc_slice_to_c_string(value);
+ gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
+ "mdelem REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", md,
+ refcnt, refcnt + 1, key_str, value_str);
+ gpr_free(key_str);
+ gpr_free(value_str);
+ }
+}
+
+void grpc_mdelem_trace_unref(void* md, const grpc_slice& key,
+ const grpc_slice& value, intptr_t refcnt,
+ const char* file, int line) {
+ if (grpc_trace_metadata.enabled()) {
+ char* key_str = grpc_slice_to_c_string(key);
+ char* value_str = grpc_slice_to_c_string(value);
+ gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
+ "mdelem UNREF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", md,
+ refcnt, refcnt - 1, key_str, value_str);
+ gpr_free(key_str);
+ gpr_free(value_str);
+ }
+}
+
+#else // ifndef NDEBUG
#define DEBUG_ARGS
#define FWD_DEBUG_ARGS
-#endif // ifndef NDEBUG
+#endif // ifndef NDEBUG
#define INITIAL_SHARD_CAPACITY 8
#define LOG2_SHARD_COUNT 4
@@ -101,124 +101,124 @@ void grpc_mdelem_trace_unref(void* md, const grpc_slice& key,
#define TABLE_IDX(hash, capacity) (((hash) >> (LOG2_SHARD_COUNT)) % (capacity))
#define SHARD_IDX(hash) ((hash) & ((1 << (LOG2_SHARD_COUNT)) - 1))
-void StaticMetadata::HashInit() {
- uint32_t k_hash = grpc_slice_hash_internal(kv_.key);
- uint32_t v_hash = grpc_slice_hash_internal(kv_.value);
- hash_ = GRPC_MDSTR_KV_HASH(k_hash, v_hash);
-}
-
-AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
- const grpc_slice& value)
- : RefcountedMdBase(grpc_slice_ref_internal(key),
- grpc_slice_ref_internal(value)) {
-#ifndef NDEBUG
- TraceAtStart("ALLOC_MD");
-#endif
-}
-
-AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
- const grpc_slice& value, const NoRefKey*)
- : RefcountedMdBase(key, grpc_slice_ref_internal(value)) {
-#ifndef NDEBUG
- TraceAtStart("ALLOC_MD_NOREF_KEY");
-#endif
-}
-
-AllocatedMetadata::AllocatedMetadata(
- const grpc_core::ManagedMemorySlice& key,
- const grpc_core::UnmanagedMemorySlice& value)
- : RefcountedMdBase(key, value) {
-#ifndef NDEBUG
- TraceAtStart("ALLOC_MD_NOREF_KEY_VAL");
-#endif
-}
-
-AllocatedMetadata::AllocatedMetadata(
- const grpc_core::ExternallyManagedSlice& key,
- const grpc_core::UnmanagedMemorySlice& value)
- : RefcountedMdBase(key, value) {
-#ifndef NDEBUG
- TraceAtStart("ALLOC_MD_NOREF_KEY_VAL");
-#endif
-}
-
-AllocatedMetadata::~AllocatedMetadata() {
- grpc_slice_unref_internal(key());
- grpc_slice_unref_internal(value());
- void* user_data = user_data_.data.Load(grpc_core::MemoryOrder::RELAXED);
- if (user_data) {
- destroy_user_data_func destroy_user_data =
- user_data_.destroy_user_data.Load(grpc_core::MemoryOrder::RELAXED);
- destroy_user_data(user_data);
- }
-}
-
-#ifndef NDEBUG
-void grpc_core::RefcountedMdBase::TraceAtStart(const char* tag) {
- if (grpc_trace_metadata.enabled()) {
- char* key_str = grpc_slice_to_c_string(key());
- char* value_str = grpc_slice_to_c_string(value());
- gpr_log(GPR_DEBUG, "mdelem %s:%p:%" PRIdPTR ": '%s' = '%s'", tag, this,
- RefValue(), key_str, value_str);
- gpr_free(key_str);
- gpr_free(value_str);
- }
-}
-#endif
-
-InternedMetadata::InternedMetadata(const grpc_slice& key,
- const grpc_slice& value, uint32_t hash,
- InternedMetadata* next)
- : RefcountedMdBase(grpc_slice_ref_internal(key),
- grpc_slice_ref_internal(value), hash),
- link_(next) {
-#ifndef NDEBUG
- TraceAtStart("INTERNED_MD");
-#endif
-}
-
-InternedMetadata::InternedMetadata(const grpc_slice& key,
- const grpc_slice& value, uint32_t hash,
- InternedMetadata* next, const NoRefKey*)
- : RefcountedMdBase(key, grpc_slice_ref_internal(value), hash), link_(next) {
-#ifndef NDEBUG
- TraceAtStart("INTERNED_MD_NOREF_KEY");
-#endif
-}
-
-InternedMetadata::~InternedMetadata() {
- grpc_slice_unref_internal(key());
- grpc_slice_unref_internal(value());
- void* user_data = user_data_.data.Load(grpc_core::MemoryOrder::RELAXED);
- if (user_data) {
- destroy_user_data_func destroy_user_data =
- user_data_.destroy_user_data.Load(grpc_core::MemoryOrder::RELAXED);
- destroy_user_data(user_data);
- }
-}
-
-size_t InternedMetadata::CleanupLinkedMetadata(
- InternedMetadata::BucketLink* head) {
- size_t num_freed = 0;
- InternedMetadata::BucketLink* prev_next = head;
- InternedMetadata *md, *next;
-
- for (md = head->next; md; md = next) {
- next = md->link_.next;
- if (md->AllRefsDropped()) {
- prev_next->next = next;
- delete md;
- num_freed++;
- } else {
- prev_next = &md->link_;
- }
- }
- return num_freed;
-}
-
+void StaticMetadata::HashInit() {
+ uint32_t k_hash = grpc_slice_hash_internal(kv_.key);
+ uint32_t v_hash = grpc_slice_hash_internal(kv_.value);
+ hash_ = GRPC_MDSTR_KV_HASH(k_hash, v_hash);
+}
+
+AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
+ const grpc_slice& value)
+ : RefcountedMdBase(grpc_slice_ref_internal(key),
+ grpc_slice_ref_internal(value)) {
+#ifndef NDEBUG
+ TraceAtStart("ALLOC_MD");
+#endif
+}
+
+AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
+ const grpc_slice& value, const NoRefKey*)
+ : RefcountedMdBase(key, grpc_slice_ref_internal(value)) {
+#ifndef NDEBUG
+ TraceAtStart("ALLOC_MD_NOREF_KEY");
+#endif
+}
+
+AllocatedMetadata::AllocatedMetadata(
+ const grpc_core::ManagedMemorySlice& key,
+ const grpc_core::UnmanagedMemorySlice& value)
+ : RefcountedMdBase(key, value) {
+#ifndef NDEBUG
+ TraceAtStart("ALLOC_MD_NOREF_KEY_VAL");
+#endif
+}
+
+AllocatedMetadata::AllocatedMetadata(
+ const grpc_core::ExternallyManagedSlice& key,
+ const grpc_core::UnmanagedMemorySlice& value)
+ : RefcountedMdBase(key, value) {
+#ifndef NDEBUG
+ TraceAtStart("ALLOC_MD_NOREF_KEY_VAL");
+#endif
+}
+
+AllocatedMetadata::~AllocatedMetadata() {
+ grpc_slice_unref_internal(key());
+ grpc_slice_unref_internal(value());
+ void* user_data = user_data_.data.Load(grpc_core::MemoryOrder::RELAXED);
+ if (user_data) {
+ destroy_user_data_func destroy_user_data =
+ user_data_.destroy_user_data.Load(grpc_core::MemoryOrder::RELAXED);
+ destroy_user_data(user_data);
+ }
+}
+
+#ifndef NDEBUG
+void grpc_core::RefcountedMdBase::TraceAtStart(const char* tag) {
+ if (grpc_trace_metadata.enabled()) {
+ char* key_str = grpc_slice_to_c_string(key());
+ char* value_str = grpc_slice_to_c_string(value());
+ gpr_log(GPR_DEBUG, "mdelem %s:%p:%" PRIdPTR ": '%s' = '%s'", tag, this,
+ RefValue(), key_str, value_str);
+ gpr_free(key_str);
+ gpr_free(value_str);
+ }
+}
+#endif
+
+InternedMetadata::InternedMetadata(const grpc_slice& key,
+ const grpc_slice& value, uint32_t hash,
+ InternedMetadata* next)
+ : RefcountedMdBase(grpc_slice_ref_internal(key),
+ grpc_slice_ref_internal(value), hash),
+ link_(next) {
+#ifndef NDEBUG
+ TraceAtStart("INTERNED_MD");
+#endif
+}
+
+InternedMetadata::InternedMetadata(const grpc_slice& key,
+ const grpc_slice& value, uint32_t hash,
+ InternedMetadata* next, const NoRefKey*)
+ : RefcountedMdBase(key, grpc_slice_ref_internal(value), hash), link_(next) {
+#ifndef NDEBUG
+ TraceAtStart("INTERNED_MD_NOREF_KEY");
+#endif
+}
+
+InternedMetadata::~InternedMetadata() {
+ grpc_slice_unref_internal(key());
+ grpc_slice_unref_internal(value());
+ void* user_data = user_data_.data.Load(grpc_core::MemoryOrder::RELAXED);
+ if (user_data) {
+ destroy_user_data_func destroy_user_data =
+ user_data_.destroy_user_data.Load(grpc_core::MemoryOrder::RELAXED);
+ destroy_user_data(user_data);
+ }
+}
+
+size_t InternedMetadata::CleanupLinkedMetadata(
+ InternedMetadata::BucketLink* head) {
+ size_t num_freed = 0;
+ InternedMetadata::BucketLink* prev_next = head;
+ InternedMetadata *md, *next;
+
+ for (md = head->next; md; md = next) {
+ next = md->link_.next;
+ if (md->AllRefsDropped()) {
+ prev_next->next = next;
+ delete md;
+ num_freed++;
+ } else {
+ prev_next = &md->link_;
+ }
+ }
+ return num_freed;
+}
+
typedef struct mdtab_shard {
gpr_mu mu;
- InternedMetadata::BucketLink* elems;
+ InternedMetadata::BucketLink* elems;
size_t count;
size_t capacity;
/** Estimate of the number of unreferenced mdelems in the hash table.
@@ -239,7 +239,7 @@ void grpc_mdctx_global_init(void) {
shard->count = 0;
gpr_atm_no_barrier_store(&shard->free_estimate, 0);
shard->capacity = INITIAL_SHARD_CAPACITY;
- shard->elems = static_cast<InternedMetadata::BucketLink*>(
+ shard->elems = static_cast<InternedMetadata::BucketLink*>(
gpr_zalloc(sizeof(*shard->elems) * shard->capacity));
}
}
@@ -269,50 +269,50 @@ void grpc_mdctx_global_shutdown() {
// For ASAN builds, we don't want to crash here, because that will
// prevent ASAN from providing leak detection information, which is
// far more useful than this simple assertion.
-#ifndef GRPC_ASAN_ENABLED
- GPR_DEBUG_ASSERT(shard->count == 0);
-#endif
+#ifndef GRPC_ASAN_ENABLED
+ GPR_DEBUG_ASSERT(shard->count == 0);
+#endif
gpr_free(shard->elems);
}
}
-#ifndef NDEBUG
+#ifndef NDEBUG
static int is_mdelem_static(grpc_mdelem e) {
- return reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(e)) >=
- &grpc_static_mdelem_table()[0] &&
- reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(e)) <
- &grpc_static_mdelem_table()[GRPC_STATIC_MDELEM_COUNT];
+ return reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(e)) >=
+ &grpc_static_mdelem_table()[0] &&
+ reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(e)) <
+ &grpc_static_mdelem_table()[GRPC_STATIC_MDELEM_COUNT];
}
-#endif
+#endif
-void InternedMetadata::RefWithShardLocked(mdtab_shard* shard) {
+void InternedMetadata::RefWithShardLocked(mdtab_shard* shard) {
#ifndef NDEBUG
if (grpc_trace_metadata.enabled()) {
- char* key_str = grpc_slice_to_c_string(key());
- char* value_str = grpc_slice_to_c_string(value());
- intptr_t value = RefValue();
- gpr_log(__FILE__, __LINE__, GPR_LOG_SEVERITY_DEBUG,
- "mdelem REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", this,
- value, value + 1, key_str, value_str);
+ char* key_str = grpc_slice_to_c_string(key());
+ char* value_str = grpc_slice_to_c_string(value());
+ intptr_t value = RefValue();
+ gpr_log(__FILE__, __LINE__, GPR_LOG_SEVERITY_DEBUG,
+ "mdelem REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", this,
+ value, value + 1, key_str, value_str);
gpr_free(key_str);
gpr_free(value_str);
}
#endif
- if (FirstRef()) {
+ if (FirstRef()) {
gpr_atm_no_barrier_fetch_add(&shard->free_estimate, -1);
}
}
static void gc_mdtab(mdtab_shard* shard) {
GPR_TIMER_SCOPE("gc_mdtab", 0);
- size_t num_freed = 0;
- for (size_t i = 0; i < shard->capacity; ++i) {
- intptr_t freed = InternedMetadata::CleanupLinkedMetadata(&shard->elems[i]);
- num_freed += freed;
- shard->count -= freed;
+ size_t num_freed = 0;
+ for (size_t i = 0; i < shard->capacity; ++i) {
+ intptr_t freed = InternedMetadata::CleanupLinkedMetadata(&shard->elems[i]);
+ num_freed += freed;
+ shard->count -= freed;
}
- gpr_atm_no_barrier_fetch_add(&shard->free_estimate,
- -static_cast<intptr_t>(num_freed));
+ gpr_atm_no_barrier_fetch_add(&shard->free_estimate,
+ -static_cast<intptr_t>(num_freed));
}
static void grow_mdtab(mdtab_shard* shard) {
@@ -320,21 +320,21 @@ static void grow_mdtab(mdtab_shard* shard) {
size_t capacity = shard->capacity * 2;
size_t i;
- InternedMetadata::BucketLink* mdtab;
- InternedMetadata *md, *next;
+ InternedMetadata::BucketLink* mdtab;
+ InternedMetadata *md, *next;
uint32_t hash;
- mdtab = static_cast<InternedMetadata::BucketLink*>(
- gpr_zalloc(sizeof(InternedMetadata::BucketLink) * capacity));
+ mdtab = static_cast<InternedMetadata::BucketLink*>(
+ gpr_zalloc(sizeof(InternedMetadata::BucketLink) * capacity));
for (i = 0; i < shard->capacity; i++) {
- for (md = shard->elems[i].next; md; md = next) {
+ for (md = shard->elems[i].next; md; md = next) {
size_t idx;
- hash = md->hash();
- next = md->bucket_next();
+ hash = md->hash();
+ next = md->bucket_next();
idx = TABLE_IDX(hash, capacity);
- md->set_bucket_next(mdtab[idx].next);
- mdtab[idx].next = md;
+ md->set_bucket_next(mdtab[idx].next);
+ mdtab[idx].next = md;
}
}
gpr_free(shard->elems);
@@ -351,100 +351,100 @@ static void rehash_mdtab(mdtab_shard* shard) {
}
}
-template <bool key_definitely_static, bool value_definitely_static = false>
-static grpc_mdelem md_create_maybe_static(const grpc_slice& key,
- const grpc_slice& value);
-template <bool key_definitely_static>
-static grpc_mdelem md_create_must_intern(const grpc_slice& key,
- const grpc_slice& value,
- uint32_t hash);
-
-template <bool key_definitely_static, bool value_definitely_static = false>
-static grpc_mdelem md_create(
+template <bool key_definitely_static, bool value_definitely_static = false>
+static grpc_mdelem md_create_maybe_static(const grpc_slice& key,
+ const grpc_slice& value);
+template <bool key_definitely_static>
+static grpc_mdelem md_create_must_intern(const grpc_slice& key,
+ const grpc_slice& value,
+ uint32_t hash);
+
+template <bool key_definitely_static, bool value_definitely_static = false>
+static grpc_mdelem md_create(
const grpc_slice& key, const grpc_slice& value,
grpc_mdelem_data* compatible_external_backing_store) {
- // Ensure slices are, in fact, static if we claimed they were.
- GPR_DEBUG_ASSERT(!key_definitely_static ||
- GRPC_IS_STATIC_METADATA_STRING(key));
- GPR_DEBUG_ASSERT(!value_definitely_static ||
- GRPC_IS_STATIC_METADATA_STRING(value));
- const bool key_is_interned =
- key_definitely_static || grpc_slice_is_interned(key);
- const bool value_is_interned =
- value_definitely_static || grpc_slice_is_interned(value);
- // External storage if either slice is not interned and the caller already
- // created a backing store. If no backing store, we allocate one.
- if (!key_is_interned || !value_is_interned) {
+ // Ensure slices are, in fact, static if we claimed they were.
+ GPR_DEBUG_ASSERT(!key_definitely_static ||
+ GRPC_IS_STATIC_METADATA_STRING(key));
+ GPR_DEBUG_ASSERT(!value_definitely_static ||
+ GRPC_IS_STATIC_METADATA_STRING(value));
+ const bool key_is_interned =
+ key_definitely_static || grpc_slice_is_interned(key);
+ const bool value_is_interned =
+ value_definitely_static || grpc_slice_is_interned(value);
+ // External storage if either slice is not interned and the caller already
+ // created a backing store. If no backing store, we allocate one.
+ if (!key_is_interned || !value_is_interned) {
if (compatible_external_backing_store != nullptr) {
- // Caller provided backing store.
+ // Caller provided backing store.
return GRPC_MAKE_MDELEM(compatible_external_backing_store,
GRPC_MDELEM_STORAGE_EXTERNAL);
- } else {
- // We allocate backing store.
- return key_definitely_static
- ? GRPC_MAKE_MDELEM(
- new AllocatedMetadata(
- key, value,
- static_cast<const AllocatedMetadata::NoRefKey*>(
- nullptr)),
- GRPC_MDELEM_STORAGE_ALLOCATED)
- : GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
- GRPC_MDELEM_STORAGE_ALLOCATED);
+ } else {
+ // We allocate backing store.
+ return key_definitely_static
+ ? GRPC_MAKE_MDELEM(
+ new AllocatedMetadata(
+ key, value,
+ static_cast<const AllocatedMetadata::NoRefKey*>(
+ nullptr)),
+ GRPC_MDELEM_STORAGE_ALLOCATED)
+ : GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
+ GRPC_MDELEM_STORAGE_ALLOCATED);
}
}
- return md_create_maybe_static<key_definitely_static, value_definitely_static>(
- key, value);
-}
-
-template <bool key_definitely_static, bool value_definitely_static>
-static grpc_mdelem md_create_maybe_static(const grpc_slice& key,
- const grpc_slice& value) {
- // Ensure slices are, in fact, static if we claimed they were.
- GPR_DEBUG_ASSERT(!key_definitely_static ||
- GRPC_IS_STATIC_METADATA_STRING(key));
- GPR_DEBUG_ASSERT(!value_definitely_static ||
- GRPC_IS_STATIC_METADATA_STRING(value));
- GPR_DEBUG_ASSERT(key.refcount != nullptr);
- GPR_DEBUG_ASSERT(value.refcount != nullptr);
-
- const bool key_is_static_mdstr =
- key_definitely_static ||
- key.refcount->GetType() == grpc_slice_refcount::Type::STATIC;
- const bool value_is_static_mdstr =
- value_definitely_static ||
- value.refcount->GetType() == grpc_slice_refcount::Type::STATIC;
-
- const intptr_t kidx = GRPC_STATIC_METADATA_INDEX(key);
-
- // Not all static slice input yields a statically stored metadata element.
- if (key_is_static_mdstr && value_is_static_mdstr) {
+ return md_create_maybe_static<key_definitely_static, value_definitely_static>(
+ key, value);
+}
+
+template <bool key_definitely_static, bool value_definitely_static>
+static grpc_mdelem md_create_maybe_static(const grpc_slice& key,
+ const grpc_slice& value) {
+ // Ensure slices are, in fact, static if we claimed they were.
+ GPR_DEBUG_ASSERT(!key_definitely_static ||
+ GRPC_IS_STATIC_METADATA_STRING(key));
+ GPR_DEBUG_ASSERT(!value_definitely_static ||
+ GRPC_IS_STATIC_METADATA_STRING(value));
+ GPR_DEBUG_ASSERT(key.refcount != nullptr);
+ GPR_DEBUG_ASSERT(value.refcount != nullptr);
+
+ const bool key_is_static_mdstr =
+ key_definitely_static ||
+ key.refcount->GetType() == grpc_slice_refcount::Type::STATIC;
+ const bool value_is_static_mdstr =
+ value_definitely_static ||
+ value.refcount->GetType() == grpc_slice_refcount::Type::STATIC;
+
+ const intptr_t kidx = GRPC_STATIC_METADATA_INDEX(key);
+
+ // Not all static slice input yields a statically stored metadata element.
+ if (key_is_static_mdstr && value_is_static_mdstr) {
grpc_mdelem static_elem = grpc_static_mdelem_for_static_strings(
- kidx, GRPC_STATIC_METADATA_INDEX(value));
+ kidx, GRPC_STATIC_METADATA_INDEX(value));
if (!GRPC_MDISNULL(static_elem)) {
return static_elem;
}
}
- uint32_t khash = key_definitely_static
- ? grpc_static_metadata_hash_values[kidx]
- : grpc_slice_hash_refcounted(key);
-
- uint32_t hash = GRPC_MDSTR_KV_HASH(khash, grpc_slice_hash_refcounted(value));
- return md_create_must_intern<key_definitely_static>(key, value, hash);
-}
-
-template <bool key_definitely_static>
-static grpc_mdelem md_create_must_intern(const grpc_slice& key,
- const grpc_slice& value,
- uint32_t hash) {
- // Here, we know both key and value are both at least interned, and both
- // possibly static. We know that anything inside the shared interned table is
- // also at least interned (and maybe static). Note that equality for a static
- // and interned slice implies that they are both the same exact slice.
- // The same applies to a pair of interned slices, or a pair of static slices.
- // Rather than run the full equality check, we can therefore just do a pointer
- // comparison of the refcounts.
- InternedMetadata* md;
+ uint32_t khash = key_definitely_static
+ ? grpc_static_metadata_hash_values[kidx]
+ : grpc_slice_hash_refcounted(key);
+
+ uint32_t hash = GRPC_MDSTR_KV_HASH(khash, grpc_slice_hash_refcounted(value));
+ return md_create_must_intern<key_definitely_static>(key, value, hash);
+}
+
+template <bool key_definitely_static>
+static grpc_mdelem md_create_must_intern(const grpc_slice& key,
+ const grpc_slice& value,
+ uint32_t hash) {
+ // Here, we know both key and value are both at least interned, and both
+ // possibly static. We know that anything inside the shared interned table is
+ // also at least interned (and maybe static). Note that equality for a static
+ // and interned slice implies that they are both the same exact slice.
+ // The same applies to a pair of interned slices, or a pair of static slices.
+ // Rather than run the full equality check, we can therefore just do a pointer
+ // comparison of the refcounts.
+ InternedMetadata* md;
mdtab_shard* shard = &g_shards[SHARD_IDX(hash)];
size_t idx;
@@ -454,22 +454,22 @@ static grpc_mdelem md_create_must_intern(const grpc_slice& key,
idx = TABLE_IDX(hash, shard->capacity);
/* search for an existing pair */
- for (md = shard->elems[idx].next; md; md = md->bucket_next()) {
- if (grpc_slice_static_interned_equal(key, md->key()) &&
- grpc_slice_static_interned_equal(value, md->value())) {
- md->RefWithShardLocked(shard);
+ for (md = shard->elems[idx].next; md; md = md->bucket_next()) {
+ if (grpc_slice_static_interned_equal(key, md->key()) &&
+ grpc_slice_static_interned_equal(value, md->value())) {
+ md->RefWithShardLocked(shard);
gpr_mu_unlock(&shard->mu);
return GRPC_MAKE_MDELEM(md, GRPC_MDELEM_STORAGE_INTERNED);
}
}
/* not found: create a new pair */
- md = key_definitely_static
- ? new InternedMetadata(
- key, value, hash, shard->elems[idx].next,
- static_cast<const InternedMetadata::NoRefKey*>(nullptr))
- : new InternedMetadata(key, value, hash, shard->elems[idx].next);
- shard->elems[idx].next = md;
+ md = key_definitely_static
+ ? new InternedMetadata(
+ key, value, hash, shard->elems[idx].next,
+ static_cast<const InternedMetadata::NoRefKey*>(nullptr))
+ : new InternedMetadata(key, value, hash, shard->elems[idx].next);
+ shard->elems[idx].next = md;
shard->count++;
if (shard->count > shard->capacity * 2) {
@@ -481,68 +481,68 @@ static grpc_mdelem md_create_must_intern(const grpc_slice& key,
return GRPC_MAKE_MDELEM(md, GRPC_MDELEM_STORAGE_INTERNED);
}
-grpc_mdelem grpc_mdelem_create(
- const grpc_slice& key, const grpc_slice& value,
- grpc_mdelem_data* compatible_external_backing_store) {
- return md_create<false>(key, value, compatible_external_backing_store);
-}
-
-grpc_mdelem grpc_mdelem_create(
- const grpc_core::StaticMetadataSlice& key, const grpc_slice& value,
- grpc_mdelem_data* compatible_external_backing_store) {
- return md_create<true>(key, value, compatible_external_backing_store);
-}
-
-/* Create grpc_mdelem from provided slices. We specify via template parameter
- whether we know that the input key is static or not. If it is, we short
- circuit various comparisons and a no-op unref. */
-template <bool key_definitely_static>
-static grpc_mdelem md_from_slices(const grpc_slice& key,
- const grpc_slice& value) {
- // Ensure key is, in fact, static if we claimed it was.
- GPR_DEBUG_ASSERT(!key_definitely_static ||
- GRPC_IS_STATIC_METADATA_STRING(key));
- grpc_mdelem out = md_create<key_definitely_static>(key, value, nullptr);
- if (!key_definitely_static) {
- grpc_slice_unref_internal(key);
- }
- grpc_slice_unref_internal(value);
- return out;
-}
-
+grpc_mdelem grpc_mdelem_create(
+ const grpc_slice& key, const grpc_slice& value,
+ grpc_mdelem_data* compatible_external_backing_store) {
+ return md_create<false>(key, value, compatible_external_backing_store);
+}
+
+grpc_mdelem grpc_mdelem_create(
+ const grpc_core::StaticMetadataSlice& key, const grpc_slice& value,
+ grpc_mdelem_data* compatible_external_backing_store) {
+ return md_create<true>(key, value, compatible_external_backing_store);
+}
+
+/* Create grpc_mdelem from provided slices. We specify via template parameter
+ whether we know that the input key is static or not. If it is, we short
+ circuit various comparisons and a no-op unref. */
+template <bool key_definitely_static>
+static grpc_mdelem md_from_slices(const grpc_slice& key,
+ const grpc_slice& value) {
+ // Ensure key is, in fact, static if we claimed it was.
+ GPR_DEBUG_ASSERT(!key_definitely_static ||
+ GRPC_IS_STATIC_METADATA_STRING(key));
+ grpc_mdelem out = md_create<key_definitely_static>(key, value, nullptr);
+ if (!key_definitely_static) {
+ grpc_slice_unref_internal(key);
+ }
+ grpc_slice_unref_internal(value);
+ return out;
+}
+
grpc_mdelem grpc_mdelem_from_slices(const grpc_slice& key,
const grpc_slice& value) {
- return md_from_slices</*key_definitely_static=*/false>(key, value);
-}
-
-grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
- const grpc_slice& value) {
- return md_from_slices</*key_definitely_static=*/true>(key, value);
-}
-
-grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::StaticMetadataSlice& key,
- const grpc_core::StaticMetadataSlice& value) {
- grpc_mdelem out = md_create_maybe_static<true, true>(key, value);
- return out;
-}
-
-grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::StaticMetadataSlice& key,
- const grpc_core::ManagedMemorySlice& value) {
- // TODO(arjunroy): We can save the unref if md_create_maybe_static ended up
- // creating a new interned metadata. But otherwise - we need this here.
- grpc_mdelem out = md_create_maybe_static<true>(key, value);
- grpc_slice_unref_internal(value);
- return out;
-}
-
-grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::ManagedMemorySlice& key,
- const grpc_core::ManagedMemorySlice& value) {
- grpc_mdelem out = md_create_maybe_static<false>(key, value);
- // TODO(arjunroy): We can save the unref if md_create_maybe_static ended up
- // creating a new interned metadata. But otherwise - we need this here.
+ return md_from_slices</*key_definitely_static=*/false>(key, value);
+}
+
+grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
+ const grpc_slice& value) {
+ return md_from_slices</*key_definitely_static=*/true>(key, value);
+}
+
+grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::StaticMetadataSlice& key,
+ const grpc_core::StaticMetadataSlice& value) {
+ grpc_mdelem out = md_create_maybe_static<true, true>(key, value);
+ return out;
+}
+
+grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::StaticMetadataSlice& key,
+ const grpc_core::ManagedMemorySlice& value) {
+ // TODO(arjunroy): We can save the unref if md_create_maybe_static ended up
+ // creating a new interned metadata. But otherwise - we need this here.
+ grpc_mdelem out = md_create_maybe_static<true>(key, value);
+ grpc_slice_unref_internal(value);
+ return out;
+}
+
+grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::ManagedMemorySlice& key,
+ const grpc_core::ManagedMemorySlice& value) {
+ grpc_mdelem out = md_create_maybe_static<false>(key, value);
+ // TODO(arjunroy): We can save the unref if md_create_maybe_static ended up
+ // creating a new interned metadata. But otherwise - we need this here.
grpc_slice_unref_internal(key);
grpc_slice_unref_internal(value);
return out;
@@ -559,131 +559,131 @@ grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_metadata* metadata) {
changed ? nullptr : reinterpret_cast<grpc_mdelem_data*>(metadata));
}
-static void* get_user_data(UserData* user_data, void (*destroy_func)(void*)) {
- if (user_data->destroy_user_data.Load(grpc_core::MemoryOrder::ACQUIRE) ==
- destroy_func) {
- return user_data->data.Load(grpc_core::MemoryOrder::RELAXED);
- } else {
- return nullptr;
- }
-}
-
-void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*destroy_func)(void*)) {
- switch (GRPC_MDELEM_STORAGE(md)) {
+static void* get_user_data(UserData* user_data, void (*destroy_func)(void*)) {
+ if (user_data->destroy_user_data.Load(grpc_core::MemoryOrder::ACQUIRE) ==
+ destroy_func) {
+ return user_data->data.Load(grpc_core::MemoryOrder::RELAXED);
+ } else {
+ return nullptr;
+ }
+}
+
+void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*destroy_func)(void*)) {
+ switch (GRPC_MDELEM_STORAGE(md)) {
case GRPC_MDELEM_STORAGE_EXTERNAL:
- return nullptr;
+ return nullptr;
case GRPC_MDELEM_STORAGE_STATIC:
- return reinterpret_cast<void*>(
- grpc_static_mdelem_user_data
- [reinterpret_cast<grpc_core::StaticMetadata*>(
- GRPC_MDELEM_DATA(md)) -
- grpc_static_mdelem_table()]);
- case GRPC_MDELEM_STORAGE_ALLOCATED: {
- auto* am = reinterpret_cast<AllocatedMetadata*>(GRPC_MDELEM_DATA(md));
- return get_user_data(am->user_data(), destroy_func);
- }
+ return reinterpret_cast<void*>(
+ grpc_static_mdelem_user_data
+ [reinterpret_cast<grpc_core::StaticMetadata*>(
+ GRPC_MDELEM_DATA(md)) -
+ grpc_static_mdelem_table()]);
+ case GRPC_MDELEM_STORAGE_ALLOCATED: {
+ auto* am = reinterpret_cast<AllocatedMetadata*>(GRPC_MDELEM_DATA(md));
+ return get_user_data(am->user_data(), destroy_func);
+ }
case GRPC_MDELEM_STORAGE_INTERNED: {
- auto* im = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(md);
- return get_user_data(im->user_data(), destroy_func);
+ auto* im = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(md);
+ return get_user_data(im->user_data(), destroy_func);
}
- }
- GPR_UNREACHABLE_CODE(return nullptr);
-}
-
-static void* set_user_data(UserData* ud, void (*destroy_func)(void*),
- void* data) {
- GPR_ASSERT((data == nullptr) == (destroy_func == nullptr));
- grpc_core::ReleasableMutexLock lock(&ud->mu_user_data);
- if (ud->destroy_user_data.Load(grpc_core::MemoryOrder::RELAXED)) {
- /* user data can only be set once */
- lock.Unlock();
- if (destroy_func != nullptr) {
- destroy_func(data);
- }
- return ud->data.Load(grpc_core::MemoryOrder::RELAXED);
- }
- ud->data.Store(data, grpc_core::MemoryOrder::RELAXED);
- ud->destroy_user_data.Store(destroy_func, grpc_core::MemoryOrder::RELEASE);
- return data;
-}
-
-void* grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void*),
- void* data) {
- switch (GRPC_MDELEM_STORAGE(md)) {
- case GRPC_MDELEM_STORAGE_EXTERNAL:
- destroy_func(data);
- return nullptr;
- case GRPC_MDELEM_STORAGE_STATIC:
- destroy_func(data);
- return reinterpret_cast<void*>(
- grpc_static_mdelem_user_data
- [reinterpret_cast<grpc_core::StaticMetadata*>(
- GRPC_MDELEM_DATA(md)) -
- grpc_static_mdelem_table()]);
+ }
+ GPR_UNREACHABLE_CODE(return nullptr);
+}
+
+static void* set_user_data(UserData* ud, void (*destroy_func)(void*),
+ void* data) {
+ GPR_ASSERT((data == nullptr) == (destroy_func == nullptr));
+ grpc_core::ReleasableMutexLock lock(&ud->mu_user_data);
+ if (ud->destroy_user_data.Load(grpc_core::MemoryOrder::RELAXED)) {
+ /* user data can only be set once */
+ lock.Unlock();
+ if (destroy_func != nullptr) {
+ destroy_func(data);
+ }
+ return ud->data.Load(grpc_core::MemoryOrder::RELAXED);
+ }
+ ud->data.Store(data, grpc_core::MemoryOrder::RELAXED);
+ ud->destroy_user_data.Store(destroy_func, grpc_core::MemoryOrder::RELEASE);
+ return data;
+}
+
+void* grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void*),
+ void* data) {
+ switch (GRPC_MDELEM_STORAGE(md)) {
+ case GRPC_MDELEM_STORAGE_EXTERNAL:
+ destroy_func(data);
+ return nullptr;
+ case GRPC_MDELEM_STORAGE_STATIC:
+ destroy_func(data);
+ return reinterpret_cast<void*>(
+ grpc_static_mdelem_user_data
+ [reinterpret_cast<grpc_core::StaticMetadata*>(
+ GRPC_MDELEM_DATA(md)) -
+ grpc_static_mdelem_table()]);
case GRPC_MDELEM_STORAGE_ALLOCATED: {
- auto* am = reinterpret_cast<AllocatedMetadata*>(GRPC_MDELEM_DATA(md));
- return set_user_data(am->user_data(), destroy_func, data);
- }
- case GRPC_MDELEM_STORAGE_INTERNED: {
- auto* im = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(md);
- GPR_DEBUG_ASSERT(!is_mdelem_static(md));
- return set_user_data(im->user_data(), destroy_func, data);
+ auto* am = reinterpret_cast<AllocatedMetadata*>(GRPC_MDELEM_DATA(md));
+ return set_user_data(am->user_data(), destroy_func, data);
}
+ case GRPC_MDELEM_STORAGE_INTERNED: {
+ auto* im = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(md);
+ GPR_DEBUG_ASSERT(!is_mdelem_static(md));
+ return set_user_data(im->user_data(), destroy_func, data);
+ }
}
- GPR_UNREACHABLE_CODE(return nullptr);
-}
-
-bool grpc_mdelem_eq(grpc_mdelem a, grpc_mdelem b) {
- if (a.payload == b.payload) return true;
- if (GRPC_MDELEM_IS_INTERNED(a) && GRPC_MDELEM_IS_INTERNED(b)) return false;
- if (GRPC_MDISNULL(a) || GRPC_MDISNULL(b)) return false;
- return grpc_slice_eq(GRPC_MDKEY(a), GRPC_MDKEY(b)) &&
- grpc_slice_eq(GRPC_MDVALUE(a), GRPC_MDVALUE(b));
-}
-
-static void note_disposed_interned_metadata(uint32_t hash) {
- mdtab_shard* shard = &g_shards[SHARD_IDX(hash)];
- gpr_atm_no_barrier_fetch_add(&shard->free_estimate, 1);
-}
-
-void grpc_mdelem_do_unref(grpc_mdelem gmd DEBUG_ARGS) {
+ GPR_UNREACHABLE_CODE(return nullptr);
+}
+
+bool grpc_mdelem_eq(grpc_mdelem a, grpc_mdelem b) {
+ if (a.payload == b.payload) return true;
+ if (GRPC_MDELEM_IS_INTERNED(a) && GRPC_MDELEM_IS_INTERNED(b)) return false;
+ if (GRPC_MDISNULL(a) || GRPC_MDISNULL(b)) return false;
+ return grpc_slice_eq(GRPC_MDKEY(a), GRPC_MDKEY(b)) &&
+ grpc_slice_eq(GRPC_MDVALUE(a), GRPC_MDVALUE(b));
+}
+
+static void note_disposed_interned_metadata(uint32_t hash) {
+ mdtab_shard* shard = &g_shards[SHARD_IDX(hash)];
+ gpr_atm_no_barrier_fetch_add(&shard->free_estimate, 1);
+}
+
+void grpc_mdelem_do_unref(grpc_mdelem gmd DEBUG_ARGS) {
switch (GRPC_MDELEM_STORAGE(gmd)) {
case GRPC_MDELEM_STORAGE_EXTERNAL:
case GRPC_MDELEM_STORAGE_STATIC:
- return;
+ return;
case GRPC_MDELEM_STORAGE_INTERNED: {
- auto* md = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(gmd);
- uint32_t hash = md->hash();
- if (GPR_UNLIKELY(md->Unref(FWD_DEBUG_ARGS))) {
+ auto* md = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(gmd);
+ uint32_t hash = md->hash();
+ if (GPR_UNLIKELY(md->Unref(FWD_DEBUG_ARGS))) {
/* once the refcount hits zero, some other thread can come along and
free md at any time: it's unsafe from this point on to access it */
- note_disposed_interned_metadata(hash);
+ note_disposed_interned_metadata(hash);
}
break;
}
case GRPC_MDELEM_STORAGE_ALLOCATED: {
- auto* md = reinterpret_cast<AllocatedMetadata*> GRPC_MDELEM_DATA(gmd);
- if (GPR_UNLIKELY(md->Unref(FWD_DEBUG_ARGS))) {
- delete md;
+ auto* md = reinterpret_cast<AllocatedMetadata*> GRPC_MDELEM_DATA(gmd);
+ if (GPR_UNLIKELY(md->Unref(FWD_DEBUG_ARGS))) {
+ delete md;
}
break;
}
}
}
-void grpc_mdelem_on_final_unref(grpc_mdelem_data_storage storage, void* ptr,
- uint32_t hash DEBUG_ARGS) {
- switch (storage) {
+void grpc_mdelem_on_final_unref(grpc_mdelem_data_storage storage, void* ptr,
+ uint32_t hash DEBUG_ARGS) {
+ switch (storage) {
case GRPC_MDELEM_STORAGE_EXTERNAL:
case GRPC_MDELEM_STORAGE_STATIC:
- return;
+ return;
case GRPC_MDELEM_STORAGE_INTERNED: {
- note_disposed_interned_metadata(hash);
- break;
+ note_disposed_interned_metadata(hash);
+ break;
}
- case GRPC_MDELEM_STORAGE_ALLOCATED: {
- delete reinterpret_cast<AllocatedMetadata*>(ptr);
- break;
+ case GRPC_MDELEM_STORAGE_ALLOCATED: {
+ delete reinterpret_cast<AllocatedMetadata*>(ptr);
+ break;
}
}
}
diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata.h b/contrib/libs/grpc/src/core/lib/transport/metadata.h
index 4bb8d64dd0..b2436f1204 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata.h
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata.h
@@ -21,24 +21,24 @@
#include <grpc/support/port_platform.h>
-#include <grpc/impl/codegen/log.h>
-
+#include <grpc/impl/codegen/log.h>
+
#include <grpc/grpc.h>
#include <grpc/slice.h>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/atomic.h"
-#include "src/core/lib/gprpp/sync.h"
-#include "src/core/lib/slice/slice_utils.h"
+#include "src/core/lib/gprpp/atomic.h"
+#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/slice/slice_utils.h"
extern grpc_core::DebugOnlyTraceFlag grpc_trace_metadata;
/* This file provides a mechanism for tracking metadata through the grpc stack.
It's not intended for consumption outside of the library.
- Metadata is tracked in the context of a sharded global grpc_mdctx. The
- context tracks unique strings (grpc_mdstr) and pairs of strings
+ Metadata is tracked in the context of a sharded global grpc_mdctx. The
+ context tracks unique strings (grpc_mdstr) and pairs of strings
(grpc_mdelem). Any of these objects can be checked for equality by comparing
their pointers. These objects are reference counted.
@@ -65,7 +65,7 @@ extern grpc_core::DebugOnlyTraceFlag grpc_trace_metadata;
typedef struct grpc_mdelem grpc_mdelem;
/* if changing this, make identical changes in:
- - grpc_core::{InternedMetadata, AllocatedMetadata}
+ - grpc_core::{InternedMetadata, AllocatedMetadata}
- grpc_metadata in grpc_types.h */
typedef struct grpc_mdelem_data {
const grpc_slice key;
@@ -77,22 +77,22 @@ typedef struct grpc_mdelem_data {
this bit set in their integer value */
#define GRPC_MDELEM_STORAGE_INTERNED_BIT 1
-/* External and static storage metadata has no refcount to ref/unref. Allocated
- * and interned metadata do have a refcount. Metadata ref and unref methods use
- * a switch statement on this enum to determine which behaviour to execute.
- * Keeping the no-ref cases together and the ref-cases together leads to
- * slightly better code generation (9 inlined instructions rather than 10). */
+/* External and static storage metadata has no refcount to ref/unref. Allocated
+ * and interned metadata do have a refcount. Metadata ref and unref methods use
+ * a switch statement on this enum to determine which behaviour to execute.
+ * Keeping the no-ref cases together and the ref-cases together leads to
+ * slightly better code generation (9 inlined instructions rather than 10). */
typedef enum {
/* memory pointed to by grpc_mdelem::payload is owned by an external system */
GRPC_MDELEM_STORAGE_EXTERNAL = 0,
- /* memory is in the static metadata table */
- GRPC_MDELEM_STORAGE_STATIC = GRPC_MDELEM_STORAGE_INTERNED_BIT,
+ /* memory is in the static metadata table */
+ GRPC_MDELEM_STORAGE_STATIC = GRPC_MDELEM_STORAGE_INTERNED_BIT,
/* memory pointed to by grpc_mdelem::payload is allocated by the metadata
system */
GRPC_MDELEM_STORAGE_ALLOCATED = 2,
- /* memory pointed to by grpc_mdelem::payload is interned by the metadata
- system */
- GRPC_MDELEM_STORAGE_INTERNED = 2 | GRPC_MDELEM_STORAGE_INTERNED_BIT,
+ /* memory pointed to by grpc_mdelem::payload is interned by the metadata
+ system */
+ GRPC_MDELEM_STORAGE_INTERNED = 2 | GRPC_MDELEM_STORAGE_INTERNED_BIT,
} grpc_mdelem_data_storage;
struct grpc_mdelem {
@@ -115,31 +115,31 @@ struct grpc_mdelem {
((grpc_mdelem_data_storage)((md).payload & \
(uintptr_t)GRPC_MDELEM_STORAGE_INTERNED_BIT))
-/* Given arbitrary input slices, create a grpc_mdelem object. The caller refs
- * the input slices; we unref them. This method is always safe to call; however,
- * if we know data about the slices in question (e.g. if we knew our key was
- * static) we can call specializations that save on cycle count. */
+/* Given arbitrary input slices, create a grpc_mdelem object. The caller refs
+ * the input slices; we unref them. This method is always safe to call; however,
+ * if we know data about the slices in question (e.g. if we knew our key was
+ * static) we can call specializations that save on cycle count. */
grpc_mdelem grpc_mdelem_from_slices(const grpc_slice& key,
const grpc_slice& value);
-/* Like grpc_mdelem_from_slices, but we know that key is a static slice. This
- saves us a few branches and a no-op call to md_unref() for the key. */
-grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
- const grpc_slice& value);
-
-/* Like grpc_mdelem_from_slices, but key is static and val is static. */
-grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::StaticMetadataSlice& key,
- const grpc_core::StaticMetadataSlice& value);
-
-/* Like grpc_mdelem_from_slices, but key is static and val is interned. */
-grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
- const grpc_core::ManagedMemorySlice& value);
-
-/* Like grpc_mdelem_from_slices, but key and val are interned. */
-grpc_mdelem grpc_mdelem_from_slices(const grpc_core::ManagedMemorySlice& key,
- const grpc_core::ManagedMemorySlice& value);
-
+/* Like grpc_mdelem_from_slices, but we know that key is a static slice. This
+ saves us a few branches and a no-op call to md_unref() for the key. */
+grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
+ const grpc_slice& value);
+
+/* Like grpc_mdelem_from_slices, but key is static and val is static. */
+grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::StaticMetadataSlice& key,
+ const grpc_core::StaticMetadataSlice& value);
+
+/* Like grpc_mdelem_from_slices, but key is static and val is interned. */
+grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
+ const grpc_core::ManagedMemorySlice& value);
+
+/* Like grpc_mdelem_from_slices, but key and val are interned. */
+grpc_mdelem grpc_mdelem_from_slices(const grpc_core::ManagedMemorySlice& key,
+ const grpc_core::ManagedMemorySlice& value);
+
/* Cheaply convert a grpc_metadata to a grpc_mdelem; may use the grpc_metadata
object as backing storage (so lifetimes should align) */
grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_metadata* metadata);
@@ -152,253 +152,253 @@ grpc_mdelem grpc_mdelem_create(
const grpc_slice& key, const grpc_slice& value,
grpc_mdelem_data* compatible_external_backing_store);
-/* Like grpc_mdelem_create, but we know that key is static. */
-grpc_mdelem grpc_mdelem_create(
- const grpc_core::StaticMetadataSlice& key, const grpc_slice& value,
- grpc_mdelem_data* compatible_external_backing_store);
-
-#define GRPC_MDKEY(md) (GRPC_MDELEM_DATA(md)->key)
-#define GRPC_MDVALUE(md) (GRPC_MDELEM_DATA(md)->value)
-
+/* Like grpc_mdelem_create, but we know that key is static. */
+grpc_mdelem grpc_mdelem_create(
+ const grpc_core::StaticMetadataSlice& key, const grpc_slice& value,
+ grpc_mdelem_data* compatible_external_backing_store);
+
+#define GRPC_MDKEY(md) (GRPC_MDELEM_DATA(md)->key)
+#define GRPC_MDVALUE(md) (GRPC_MDELEM_DATA(md)->value)
+
bool grpc_mdelem_eq(grpc_mdelem a, grpc_mdelem b);
-/* Often we compare metadata where we know a-priori that the second parameter is
- * static, and that the keys match. This most commonly happens when processing
- * metadata batch callouts in initial/trailing filters. In this case, fastpath
- * grpc_mdelem_eq and remove unnecessary checks. */
-inline bool grpc_mdelem_static_value_eq(grpc_mdelem a, grpc_mdelem b_static) {
- if (a.payload == b_static.payload) return true;
- return grpc_slice_eq_static_interned(GRPC_MDVALUE(a), GRPC_MDVALUE(b_static));
-}
-#define GRPC_MDISNULL(md) (GRPC_MDELEM_DATA(md) == NULL)
-
-inline bool grpc_mdelem_both_interned_eq(grpc_mdelem a_interned,
- grpc_mdelem b_interned) {
- GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(a_interned) ||
- GRPC_MDISNULL(a_interned));
- GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(b_interned) ||
- GRPC_MDISNULL(b_interned));
- return a_interned.payload == b_interned.payload;
-}
-
+/* Often we compare metadata where we know a-priori that the second parameter is
+ * static, and that the keys match. This most commonly happens when processing
+ * metadata batch callouts in initial/trailing filters. In this case, fastpath
+ * grpc_mdelem_eq and remove unnecessary checks. */
+inline bool grpc_mdelem_static_value_eq(grpc_mdelem a, grpc_mdelem b_static) {
+ if (a.payload == b_static.payload) return true;
+ return grpc_slice_eq_static_interned(GRPC_MDVALUE(a), GRPC_MDVALUE(b_static));
+}
+#define GRPC_MDISNULL(md) (GRPC_MDELEM_DATA(md) == NULL)
+
+inline bool grpc_mdelem_both_interned_eq(grpc_mdelem a_interned,
+ grpc_mdelem b_interned) {
+ GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(a_interned) ||
+ GRPC_MDISNULL(a_interned));
+ GPR_DEBUG_ASSERT(GRPC_MDELEM_IS_INTERNED(b_interned) ||
+ GRPC_MDISNULL(b_interned));
+ return a_interned.payload == b_interned.payload;
+}
+
/* Mutator and accessor for grpc_mdelem user data. The destructor function
is used as a type tag and is checked during user_data fetch. */
void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*if_destroy_func)(void*));
void* grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void*),
- void* data);
-
-// Defined in metadata.cc.
-struct mdtab_shard;
-
-#ifndef NDEBUG
-void grpc_mdelem_trace_ref(void* md, const grpc_slice& key,
- const grpc_slice& value, intptr_t refcnt,
- const char* file, int line);
-void grpc_mdelem_trace_unref(void* md, const grpc_slice& key,
- const grpc_slice& value, intptr_t refcnt,
- const char* file, int line);
-#endif
-namespace grpc_core {
-
-typedef void (*destroy_user_data_func)(void* data);
-
-struct UserData {
- Mutex mu_user_data;
- grpc_core::Atomic<destroy_user_data_func> destroy_user_data;
- grpc_core::Atomic<void*> data;
-};
-
-class StaticMetadata {
- public:
- StaticMetadata(const grpc_slice& key, const grpc_slice& value, uintptr_t idx)
- : kv_({key, value}), hash_(0), static_idx_(idx) {}
-
- const grpc_mdelem_data& data() const { return kv_; }
-
- void HashInit();
- uint32_t hash() { return hash_; }
- uintptr_t StaticIndex() { return static_idx_; }
-
- private:
- grpc_mdelem_data kv_;
-
- /* private only data */
- uint32_t hash_;
- uintptr_t static_idx_;
-};
-
-class RefcountedMdBase {
- public:
- RefcountedMdBase(const grpc_slice& key, const grpc_slice& value)
- : key_(key), value_(value), refcnt_(1) {}
- RefcountedMdBase(const grpc_slice& key, const grpc_slice& value,
- uint32_t hash)
- : key_(key), value_(value), refcnt_(1), hash_(hash) {}
-
- const grpc_slice& key() const { return key_; }
- const grpc_slice& value() const { return value_; }
- uint32_t hash() { return hash_; }
-
-#ifndef NDEBUG
- void Ref(const char* file, int line) {
- grpc_mdelem_trace_ref(this, key_, value_, RefValue(), file, line);
- const intptr_t prior = refcnt_.FetchAdd(1, MemoryOrder::RELAXED);
- GPR_ASSERT(prior > 0);
- }
- bool Unref(const char* file, int line) {
- grpc_mdelem_trace_unref(this, key_, value_, RefValue(), file, line);
- return Unref();
- }
-#endif
- void Ref() {
- /* we can assume the ref count is >= 1 as the application is calling
- this function - meaning that no adjustment to mdtab_free is necessary,
- simplifying the logic here to be just an atomic increment */
- refcnt_.FetchAdd(1, MemoryOrder::RELAXED);
- }
- bool Unref() {
- const intptr_t prior = refcnt_.FetchSub(1, MemoryOrder::ACQ_REL);
- GPR_DEBUG_ASSERT(prior > 0);
- return prior == 1;
- }
-
- protected:
-#ifndef NDEBUG
- void TraceAtStart(const char* tag);
-#endif
-
- intptr_t RefValue() { return refcnt_.Load(MemoryOrder::RELAXED); }
- bool AllRefsDropped() { return refcnt_.Load(MemoryOrder::ACQUIRE) == 0; }
- bool FirstRef() { return refcnt_.FetchAdd(1, MemoryOrder::RELAXED) == 0; }
-
- private:
- /* must be byte compatible with grpc_mdelem_data */
- grpc_slice key_;
- grpc_slice value_;
- grpc_core::Atomic<intptr_t> refcnt_;
- uint32_t hash_ = 0;
-};
-
-class InternedMetadata : public RefcountedMdBase {
- public:
- // TODO(arjunroy): Change to use strongly typed slices instead.
- struct NoRefKey {};
- struct BucketLink {
- explicit BucketLink(InternedMetadata* md) : next(md) {}
-
- InternedMetadata* next = nullptr;
- };
- InternedMetadata(const grpc_slice& key, const grpc_slice& value,
- uint32_t hash, InternedMetadata* next);
- InternedMetadata(const grpc_slice& key, const grpc_slice& value,
- uint32_t hash, InternedMetadata* next, const NoRefKey*);
-
- ~InternedMetadata();
- void RefWithShardLocked(mdtab_shard* shard);
- UserData* user_data() { return &user_data_; }
- InternedMetadata* bucket_next() { return link_.next; }
- void set_bucket_next(InternedMetadata* md) { link_.next = md; }
-
- static size_t CleanupLinkedMetadata(BucketLink* head);
-
- private:
- UserData user_data_;
- BucketLink link_;
-};
-
-/* Shadow structure for grpc_mdelem_data for allocated elements */
-class AllocatedMetadata : public RefcountedMdBase {
- public:
- // TODO(arjunroy): Change to use strongly typed slices instead.
- struct NoRefKey {};
- AllocatedMetadata(const grpc_slice& key, const grpc_slice& value);
- AllocatedMetadata(const grpc_core::ManagedMemorySlice& key,
- const grpc_core::UnmanagedMemorySlice& value);
- AllocatedMetadata(const grpc_core::ExternallyManagedSlice& key,
- const grpc_core::UnmanagedMemorySlice& value);
- AllocatedMetadata(const grpc_slice& key, const grpc_slice& value,
- const NoRefKey*);
- ~AllocatedMetadata();
-
- UserData* user_data() { return &user_data_; }
-
- private:
- UserData user_data_;
-};
-
-} // namespace grpc_core
+ void* data);
+// Defined in metadata.cc.
+struct mdtab_shard;
+
#ifndef NDEBUG
+void grpc_mdelem_trace_ref(void* md, const grpc_slice& key,
+ const grpc_slice& value, intptr_t refcnt,
+ const char* file, int line);
+void grpc_mdelem_trace_unref(void* md, const grpc_slice& key,
+ const grpc_slice& value, intptr_t refcnt,
+ const char* file, int line);
+#endif
+namespace grpc_core {
+
+typedef void (*destroy_user_data_func)(void* data);
+
+struct UserData {
+ Mutex mu_user_data;
+ grpc_core::Atomic<destroy_user_data_func> destroy_user_data;
+ grpc_core::Atomic<void*> data;
+};
+
+class StaticMetadata {
+ public:
+ StaticMetadata(const grpc_slice& key, const grpc_slice& value, uintptr_t idx)
+ : kv_({key, value}), hash_(0), static_idx_(idx) {}
+
+ const grpc_mdelem_data& data() const { return kv_; }
+
+ void HashInit();
+ uint32_t hash() { return hash_; }
+ uintptr_t StaticIndex() { return static_idx_; }
+
+ private:
+ grpc_mdelem_data kv_;
+
+ /* private only data */
+ uint32_t hash_;
+ uintptr_t static_idx_;
+};
+
+class RefcountedMdBase {
+ public:
+ RefcountedMdBase(const grpc_slice& key, const grpc_slice& value)
+ : key_(key), value_(value), refcnt_(1) {}
+ RefcountedMdBase(const grpc_slice& key, const grpc_slice& value,
+ uint32_t hash)
+ : key_(key), value_(value), refcnt_(1), hash_(hash) {}
+
+ const grpc_slice& key() const { return key_; }
+ const grpc_slice& value() const { return value_; }
+ uint32_t hash() { return hash_; }
+
+#ifndef NDEBUG
+ void Ref(const char* file, int line) {
+ grpc_mdelem_trace_ref(this, key_, value_, RefValue(), file, line);
+ const intptr_t prior = refcnt_.FetchAdd(1, MemoryOrder::RELAXED);
+ GPR_ASSERT(prior > 0);
+ }
+ bool Unref(const char* file, int line) {
+ grpc_mdelem_trace_unref(this, key_, value_, RefValue(), file, line);
+ return Unref();
+ }
+#endif
+ void Ref() {
+ /* we can assume the ref count is >= 1 as the application is calling
+ this function - meaning that no adjustment to mdtab_free is necessary,
+ simplifying the logic here to be just an atomic increment */
+ refcnt_.FetchAdd(1, MemoryOrder::RELAXED);
+ }
+ bool Unref() {
+ const intptr_t prior = refcnt_.FetchSub(1, MemoryOrder::ACQ_REL);
+ GPR_DEBUG_ASSERT(prior > 0);
+ return prior == 1;
+ }
+
+ protected:
+#ifndef NDEBUG
+ void TraceAtStart(const char* tag);
+#endif
+
+ intptr_t RefValue() { return refcnt_.Load(MemoryOrder::RELAXED); }
+ bool AllRefsDropped() { return refcnt_.Load(MemoryOrder::ACQUIRE) == 0; }
+ bool FirstRef() { return refcnt_.FetchAdd(1, MemoryOrder::RELAXED) == 0; }
+
+ private:
+ /* must be byte compatible with grpc_mdelem_data */
+ grpc_slice key_;
+ grpc_slice value_;
+ grpc_core::Atomic<intptr_t> refcnt_;
+ uint32_t hash_ = 0;
+};
+
+class InternedMetadata : public RefcountedMdBase {
+ public:
+ // TODO(arjunroy): Change to use strongly typed slices instead.
+ struct NoRefKey {};
+ struct BucketLink {
+ explicit BucketLink(InternedMetadata* md) : next(md) {}
+
+ InternedMetadata* next = nullptr;
+ };
+ InternedMetadata(const grpc_slice& key, const grpc_slice& value,
+ uint32_t hash, InternedMetadata* next);
+ InternedMetadata(const grpc_slice& key, const grpc_slice& value,
+ uint32_t hash, InternedMetadata* next, const NoRefKey*);
+
+ ~InternedMetadata();
+ void RefWithShardLocked(mdtab_shard* shard);
+ UserData* user_data() { return &user_data_; }
+ InternedMetadata* bucket_next() { return link_.next; }
+ void set_bucket_next(InternedMetadata* md) { link_.next = md; }
+
+ static size_t CleanupLinkedMetadata(BucketLink* head);
+
+ private:
+ UserData user_data_;
+ BucketLink link_;
+};
+
+/* Shadow structure for grpc_mdelem_data for allocated elements */
+class AllocatedMetadata : public RefcountedMdBase {
+ public:
+ // TODO(arjunroy): Change to use strongly typed slices instead.
+ struct NoRefKey {};
+ AllocatedMetadata(const grpc_slice& key, const grpc_slice& value);
+ AllocatedMetadata(const grpc_core::ManagedMemorySlice& key,
+ const grpc_core::UnmanagedMemorySlice& value);
+ AllocatedMetadata(const grpc_core::ExternallyManagedSlice& key,
+ const grpc_core::UnmanagedMemorySlice& value);
+ AllocatedMetadata(const grpc_slice& key, const grpc_slice& value,
+ const NoRefKey*);
+ ~AllocatedMetadata();
+
+ UserData* user_data() { return &user_data_; }
+
+ private:
+ UserData user_data_;
+};
+
+} // namespace grpc_core
+
+#ifndef NDEBUG
#define GRPC_MDELEM_REF(s) grpc_mdelem_ref((s), __FILE__, __LINE__)
-inline grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd, const char* file,
- int line) {
-#else // ifndef NDEBUG
-#define GRPC_MDELEM_REF(s) grpc_mdelem_ref((s))
-inline grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd) {
-#endif // ifndef NDEBUG
- switch (GRPC_MDELEM_STORAGE(gmd)) {
- case GRPC_MDELEM_STORAGE_EXTERNAL:
- case GRPC_MDELEM_STORAGE_STATIC:
- break;
- case GRPC_MDELEM_STORAGE_INTERNED: {
- auto* md =
- reinterpret_cast<grpc_core::InternedMetadata*> GRPC_MDELEM_DATA(gmd);
- /* use C assert to have this removed in opt builds */
-#ifndef NDEBUG
- md->Ref(file, line);
-#else
- md->Ref();
-#endif
- break;
- }
- case GRPC_MDELEM_STORAGE_ALLOCATED: {
- auto* md =
- reinterpret_cast<grpc_core::AllocatedMetadata*> GRPC_MDELEM_DATA(gmd);
-#ifndef NDEBUG
- md->Ref(file, line);
-#else
- md->Ref();
-#endif
- break;
- }
- }
- return gmd;
-}
-
-#ifndef NDEBUG
+inline grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd, const char* file,
+ int line) {
+#else // ifndef NDEBUG
+#define GRPC_MDELEM_REF(s) grpc_mdelem_ref((s))
+inline grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd) {
+#endif // ifndef NDEBUG
+ switch (GRPC_MDELEM_STORAGE(gmd)) {
+ case GRPC_MDELEM_STORAGE_EXTERNAL:
+ case GRPC_MDELEM_STORAGE_STATIC:
+ break;
+ case GRPC_MDELEM_STORAGE_INTERNED: {
+ auto* md =
+ reinterpret_cast<grpc_core::InternedMetadata*> GRPC_MDELEM_DATA(gmd);
+ /* use C assert to have this removed in opt builds */
+#ifndef NDEBUG
+ md->Ref(file, line);
+#else
+ md->Ref();
+#endif
+ break;
+ }
+ case GRPC_MDELEM_STORAGE_ALLOCATED: {
+ auto* md =
+ reinterpret_cast<grpc_core::AllocatedMetadata*> GRPC_MDELEM_DATA(gmd);
+#ifndef NDEBUG
+ md->Ref(file, line);
+#else
+ md->Ref();
+#endif
+ break;
+ }
+ }
+ return gmd;
+}
+
+#ifndef NDEBUG
#define GRPC_MDELEM_UNREF(s) grpc_mdelem_unref((s), __FILE__, __LINE__)
-void grpc_mdelem_on_final_unref(grpc_mdelem_data_storage storage, void* ptr,
- uint32_t hash, const char* file, int line);
-inline void grpc_mdelem_unref(grpc_mdelem gmd, const char* file, int line) {
+void grpc_mdelem_on_final_unref(grpc_mdelem_data_storage storage, void* ptr,
+ uint32_t hash, const char* file, int line);
+inline void grpc_mdelem_unref(grpc_mdelem gmd, const char* file, int line) {
#else
#define GRPC_MDELEM_UNREF(s) grpc_mdelem_unref((s))
-void grpc_mdelem_on_final_unref(grpc_mdelem_data_storage storage, void* ptr,
- uint32_t hash);
-inline void grpc_mdelem_unref(grpc_mdelem gmd) {
-#endif
- const grpc_mdelem_data_storage storage = GRPC_MDELEM_STORAGE(gmd);
- switch (storage) {
- case GRPC_MDELEM_STORAGE_EXTERNAL:
- case GRPC_MDELEM_STORAGE_STATIC:
- return;
- case GRPC_MDELEM_STORAGE_INTERNED:
- case GRPC_MDELEM_STORAGE_ALLOCATED:
- auto* md =
- reinterpret_cast<grpc_core::RefcountedMdBase*> GRPC_MDELEM_DATA(gmd);
- /* once the refcount hits zero, some other thread can come along and
- free an interned md at any time: it's unsafe from this point on to
- access it so we read the hash now. */
- uint32_t hash = md->hash();
-#ifndef NDEBUG
- if (GPR_UNLIKELY(md->Unref(file, line))) {
- grpc_mdelem_on_final_unref(storage, md, hash, file, line);
-#else
- if (GPR_UNLIKELY(md->Unref())) {
- grpc_mdelem_on_final_unref(storage, md, hash);
+void grpc_mdelem_on_final_unref(grpc_mdelem_data_storage storage, void* ptr,
+ uint32_t hash);
+inline void grpc_mdelem_unref(grpc_mdelem gmd) {
#endif
- }
- return;
- }
-}
+ const grpc_mdelem_data_storage storage = GRPC_MDELEM_STORAGE(gmd);
+ switch (storage) {
+ case GRPC_MDELEM_STORAGE_EXTERNAL:
+ case GRPC_MDELEM_STORAGE_STATIC:
+ return;
+ case GRPC_MDELEM_STORAGE_INTERNED:
+ case GRPC_MDELEM_STORAGE_ALLOCATED:
+ auto* md =
+ reinterpret_cast<grpc_core::RefcountedMdBase*> GRPC_MDELEM_DATA(gmd);
+ /* once the refcount hits zero, some other thread can come along and
+ free an interned md at any time: it's unsafe from this point on to
+ access it so we read the hash now. */
+ uint32_t hash = md->hash();
+#ifndef NDEBUG
+ if (GPR_UNLIKELY(md->Unref(file, line))) {
+ grpc_mdelem_on_final_unref(storage, md, hash, file, line);
+#else
+ if (GPR_UNLIKELY(md->Unref())) {
+ grpc_mdelem_on_final_unref(storage, md, hash);
+#endif
+ }
+ return;
+ }
+}
#define GRPC_MDNULL GRPC_MAKE_MDELEM(NULL, GRPC_MDELEM_STORAGE_EXTERNAL)
@@ -412,35 +412,35 @@ inline void grpc_mdelem_unref(grpc_mdelem gmd) {
void grpc_mdctx_global_init(void);
void grpc_mdctx_global_shutdown();
-/* Like grpc_mdelem_from_slices, but we know that key is a static or interned
- slice and value is not static or interned. This gives us an inlinable
- fastpath - we know we must allocate metadata now, and that we do not need to
- unref the value (rather, we just transfer the ref). We can avoid a ref since:
- 1) the key slice is passed in already ref'd
- 2) We're guaranteed to create a new Allocated slice, thus meaning the
- ref can be considered 'transferred'.*/
-inline grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::ManagedMemorySlice& key,
- const grpc_core::UnmanagedMemorySlice& value) {
- using grpc_core::AllocatedMetadata;
- return GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
- GRPC_MDELEM_STORAGE_ALLOCATED);
-}
-
-inline grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::ExternallyManagedSlice& key,
- const grpc_core::UnmanagedMemorySlice& value) {
- using grpc_core::AllocatedMetadata;
- return GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
- GRPC_MDELEM_STORAGE_ALLOCATED);
-}
-
-inline grpc_mdelem grpc_mdelem_from_slices(
- const grpc_core::StaticMetadataSlice& key,
- const grpc_core::UnmanagedMemorySlice& value) {
- using grpc_core::AllocatedMetadata;
- return GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
- GRPC_MDELEM_STORAGE_ALLOCATED);
-}
-
+/* Like grpc_mdelem_from_slices, but we know that key is a static or interned
+ slice and value is not static or interned. This gives us an inlinable
+ fastpath - we know we must allocate metadata now, and that we do not need to
+ unref the value (rather, we just transfer the ref). We can avoid a ref since:
+ 1) the key slice is passed in already ref'd
+ 2) We're guaranteed to create a new Allocated slice, thus meaning the
+ ref can be considered 'transferred'.*/
+inline grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::ManagedMemorySlice& key,
+ const grpc_core::UnmanagedMemorySlice& value) {
+ using grpc_core::AllocatedMetadata;
+ return GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
+ GRPC_MDELEM_STORAGE_ALLOCATED);
+}
+
+inline grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::ExternallyManagedSlice& key,
+ const grpc_core::UnmanagedMemorySlice& value) {
+ using grpc_core::AllocatedMetadata;
+ return GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
+ GRPC_MDELEM_STORAGE_ALLOCATED);
+}
+
+inline grpc_mdelem grpc_mdelem_from_slices(
+ const grpc_core::StaticMetadataSlice& key,
+ const grpc_core::UnmanagedMemorySlice& value) {
+ using grpc_core::AllocatedMetadata;
+ return GRPC_MAKE_MDELEM(new AllocatedMetadata(key, value),
+ GRPC_MDELEM_STORAGE_ALLOCATED);
+}
+
#endif /* GRPC_CORE_LIB_TRANSPORT_METADATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc
index 66749b671c..242c256dc4 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc
@@ -50,9 +50,9 @@ static void assert_valid_list(grpc_mdelem_list* list) {
verified_count++;
}
GPR_ASSERT(list->count == verified_count);
-#else
- // Avoid unused-parameter warning for debug-only parameter
- (void)list;
+#else
+ // Avoid unused-parameter warning for debug-only parameter
+ (void)list;
#endif /* NDEBUG */
}
@@ -67,9 +67,9 @@ static void assert_valid_callouts(grpc_metadata_batch* batch) {
}
grpc_slice_unref_internal(key_interned);
}
-#else
- // Avoid unused-parameter warning for debug-only parameter
- (void)batch;
+#else
+ // Avoid unused-parameter warning for debug-only parameter
+ (void)batch;
#endif
}
@@ -99,23 +99,23 @@ grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md) {
return out;
}
-static grpc_error* GPR_ATTRIBUTE_NOINLINE error_with_md(grpc_mdelem md) {
- return grpc_attach_md_to_error(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Unallowed duplicate metadata"), md);
-}
-
-static grpc_error* link_callout(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) {
- GPR_DEBUG_ASSERT(idx >= 0 && idx < GRPC_BATCH_CALLOUTS_COUNT);
- if (GPR_LIKELY(batch->idx.array[idx] == nullptr)) {
- ++batch->list.default_count;
- batch->idx.array[idx] = storage;
- return GRPC_ERROR_NONE;
- }
- return error_with_md(storage->md);
-}
-
+static grpc_error* GPR_ATTRIBUTE_NOINLINE error_with_md(grpc_mdelem md) {
+ return grpc_attach_md_to_error(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Unallowed duplicate metadata"), md);
+}
+
+static grpc_error* link_callout(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) {
+ GPR_DEBUG_ASSERT(idx >= 0 && idx < GRPC_BATCH_CALLOUTS_COUNT);
+ if (GPR_LIKELY(batch->idx.array[idx] == nullptr)) {
+ ++batch->list.default_count;
+ batch->idx.array[idx] = storage;
+ return GRPC_ERROR_NONE;
+ }
+ return error_with_md(storage->md);
+}
+
static grpc_error* maybe_link_callout(grpc_metadata_batch* batch,
grpc_linked_mdelem* storage)
GRPC_MUST_USE_RESULT;
@@ -127,7 +127,7 @@ static grpc_error* maybe_link_callout(grpc_metadata_batch* batch,
if (idx == GRPC_BATCH_CALLOUTS_COUNT) {
return GRPC_ERROR_NONE;
}
- return link_callout(batch, storage, idx);
+ return link_callout(batch, storage, idx);
}
static void maybe_unlink_callout(grpc_metadata_batch* batch,
@@ -138,21 +138,21 @@ static void maybe_unlink_callout(grpc_metadata_batch* batch,
return;
}
--batch->list.default_count;
- GPR_DEBUG_ASSERT(batch->idx.array[idx] != nullptr);
+ GPR_DEBUG_ASSERT(batch->idx.array[idx] != nullptr);
batch->idx.array[idx] = nullptr;
}
grpc_error* grpc_metadata_batch_add_head(grpc_metadata_batch* batch,
grpc_linked_mdelem* storage,
grpc_mdelem elem_to_add) {
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
storage->md = elem_to_add;
return grpc_metadata_batch_link_head(batch, storage);
}
static void link_head(grpc_mdelem_list* list, grpc_linked_mdelem* storage) {
assert_valid_list(list);
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(storage->md));
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(storage->md));
storage->prev = nullptr;
storage->next = list->head;
storage->reserved = nullptr;
@@ -179,35 +179,35 @@ grpc_error* grpc_metadata_batch_link_head(grpc_metadata_batch* batch,
return GRPC_ERROR_NONE;
}
-// TODO(arjunroy): Need to revisit this and see what guarantees exist between
-// C-core and the internal-metadata subsystem. E.g. can we ensure a particular
-// metadata is never added twice, even in the presence of user supplied data?
-grpc_error* grpc_metadata_batch_link_head(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) {
- GPR_DEBUG_ASSERT(GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md)) == idx);
- assert_valid_callouts(batch);
- grpc_error* err = link_callout(batch, storage, idx);
- if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) {
- assert_valid_callouts(batch);
- return err;
- }
- link_head(&batch->list, storage);
- assert_valid_callouts(batch);
- return GRPC_ERROR_NONE;
-}
-
+// TODO(arjunroy): Need to revisit this and see what guarantees exist between
+// C-core and the internal-metadata subsystem. E.g. can we ensure a particular
+// metadata is never added twice, even in the presence of user supplied data?
+grpc_error* grpc_metadata_batch_link_head(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) {
+ GPR_DEBUG_ASSERT(GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md)) == idx);
+ assert_valid_callouts(batch);
+ grpc_error* err = link_callout(batch, storage, idx);
+ if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) {
+ assert_valid_callouts(batch);
+ return err;
+ }
+ link_head(&batch->list, storage);
+ assert_valid_callouts(batch);
+ return GRPC_ERROR_NONE;
+}
+
grpc_error* grpc_metadata_batch_add_tail(grpc_metadata_batch* batch,
grpc_linked_mdelem* storage,
grpc_mdelem elem_to_add) {
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
storage->md = elem_to_add;
return grpc_metadata_batch_link_tail(batch, storage);
}
static void link_tail(grpc_mdelem_list* list, grpc_linked_mdelem* storage) {
assert_valid_list(list);
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(storage->md));
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(storage->md));
storage->prev = list->tail;
storage->next = nullptr;
storage->reserved = nullptr;
@@ -234,21 +234,21 @@ grpc_error* grpc_metadata_batch_link_tail(grpc_metadata_batch* batch,
return GRPC_ERROR_NONE;
}
-grpc_error* grpc_metadata_batch_link_tail(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) {
- GPR_DEBUG_ASSERT(GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md)) == idx);
- assert_valid_callouts(batch);
- grpc_error* err = link_callout(batch, storage, idx);
- if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) {
- assert_valid_callouts(batch);
- return err;
- }
- link_tail(&batch->list, storage);
- assert_valid_callouts(batch);
- return GRPC_ERROR_NONE;
-}
-
+grpc_error* grpc_metadata_batch_link_tail(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) {
+ GPR_DEBUG_ASSERT(GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md)) == idx);
+ assert_valid_callouts(batch);
+ grpc_error* err = link_callout(batch, storage, idx);
+ if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) {
+ assert_valid_callouts(batch);
+ return err;
+ }
+ link_tail(&batch->list, storage);
+ assert_valid_callouts(batch);
+ return GRPC_ERROR_NONE;
+}
+
static void unlink_storage(grpc_mdelem_list* list,
grpc_linked_mdelem* storage) {
assert_valid_list(list);
@@ -275,20 +275,20 @@ void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
assert_valid_callouts(batch);
}
-void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
- grpc_metadata_batch_callouts_index idx) {
- assert_valid_callouts(batch);
- grpc_linked_mdelem* storage = batch->idx.array[idx];
- GPR_DEBUG_ASSERT(storage != nullptr);
- --batch->list.default_count;
- batch->idx.array[idx] = nullptr;
- unlink_storage(&batch->list, storage);
- GRPC_MDELEM_UNREF(storage->md);
- assert_valid_callouts(batch);
-}
-
+void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
+ grpc_metadata_batch_callouts_index idx) {
+ assert_valid_callouts(batch);
+ grpc_linked_mdelem* storage = batch->idx.array[idx];
+ GPR_DEBUG_ASSERT(storage != nullptr);
+ --batch->list.default_count;
+ batch->idx.array[idx] = nullptr;
+ unlink_storage(&batch->list, storage);
+ GRPC_MDELEM_UNREF(storage->md);
+ assert_valid_callouts(batch);
+}
+
void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
- const grpc_slice& value) {
+ const grpc_slice& value) {
grpc_mdelem old_mdelem = storage->md;
grpc_mdelem new_mdelem = grpc_mdelem_from_slices(
grpc_slice_ref_internal(GRPC_MDKEY(old_mdelem)), value);
@@ -374,14 +374,14 @@ void grpc_metadata_batch_copy(grpc_metadata_batch* src,
size_t i = 0;
for (grpc_linked_mdelem* elem = src->list.head; elem != nullptr;
elem = elem->next) {
- // Error unused in non-debug builds.
- grpc_error* GRPC_UNUSED error = grpc_metadata_batch_add_tail(
- dst, &storage[i++], GRPC_MDELEM_REF(elem->md));
+ // Error unused in non-debug builds.
+ grpc_error* GRPC_UNUSED error = grpc_metadata_batch_add_tail(
+ dst, &storage[i++], GRPC_MDELEM_REF(elem->md));
// The only way that grpc_metadata_batch_add_tail() can fail is if
// there's a duplicate entry for a callout. However, that can't be
// the case here, because we would not have been allowed to create
// a source batch that had that kind of conflict.
- GPR_DEBUG_ASSERT(error == GRPC_ERROR_NONE);
+ GPR_DEBUG_ASSERT(error == GRPC_ERROR_NONE);
}
}
diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h
index 3101f485a2..04aa25f215 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h
@@ -67,8 +67,8 @@ size_t grpc_metadata_batch_size(grpc_metadata_batch* batch);
/** Remove \a storage from the batch, unreffing the mdelem contained */
void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
grpc_linked_mdelem* storage);
-void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
- grpc_metadata_batch_callouts_index idx);
+void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
+ grpc_metadata_batch_callouts_index idx);
/** Substitute a new mdelem for an old value */
grpc_error* grpc_metadata_batch_substitute(grpc_metadata_batch* batch,
@@ -76,7 +76,7 @@ grpc_error* grpc_metadata_batch_substitute(grpc_metadata_batch* batch,
grpc_mdelem new_value);
void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
- const grpc_slice& value);
+ const grpc_slice& value);
/** Add \a storage to the beginning of \a batch. storage->md is
assumed to be valid.
@@ -86,9 +86,9 @@ void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
grpc_error* grpc_metadata_batch_link_head(grpc_metadata_batch* batch,
grpc_linked_mdelem* storage)
GRPC_MUST_USE_RESULT;
-grpc_error* grpc_metadata_batch_link_head(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) GRPC_MUST_USE_RESULT;
+grpc_error* grpc_metadata_batch_link_head(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) GRPC_MUST_USE_RESULT;
/** Add \a storage to the end of \a batch. storage->md is
assumed to be valid.
@@ -98,9 +98,9 @@ grpc_error* grpc_metadata_batch_link_head(
grpc_error* grpc_metadata_batch_link_tail(grpc_metadata_batch* batch,
grpc_linked_mdelem* storage)
GRPC_MUST_USE_RESULT;
-grpc_error* grpc_metadata_batch_link_tail(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) GRPC_MUST_USE_RESULT;
+grpc_error* grpc_metadata_batch_link_tail(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) GRPC_MUST_USE_RESULT;
/** Add \a elem_to_add as the first element in \a batch, using
\a storage as backing storage for the linked list element.
@@ -112,22 +112,22 @@ grpc_error* grpc_metadata_batch_add_head(
grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT;
-// TODO(arjunroy, roth): Remove redundant methods.
-// add/link_head/tail are almost identical.
-inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_head(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) {
- return grpc_metadata_batch_link_head(batch, storage, idx);
-}
-
-inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_head(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_mdelem elem_to_add, grpc_metadata_batch_callouts_index idx) {
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
- storage->md = elem_to_add;
- return grpc_metadata_batch_add_head(batch, storage, idx);
-}
-
+// TODO(arjunroy, roth): Remove redundant methods.
+// add/link_head/tail are almost identical.
+inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_head(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) {
+ return grpc_metadata_batch_link_head(batch, storage, idx);
+}
+
+inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_head(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_mdelem elem_to_add, grpc_metadata_batch_callouts_index idx) {
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
+ storage->md = elem_to_add;
+ return grpc_metadata_batch_add_head(batch, storage, idx);
+}
+
/** Add \a elem_to_add as the last element in \a batch, using
\a storage as backing storage for the linked list element.
\a storage is owned by the caller and must survive for the
@@ -138,20 +138,20 @@ grpc_error* grpc_metadata_batch_add_tail(
grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT;
-inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_tail(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_metadata_batch_callouts_index idx) {
- return grpc_metadata_batch_link_tail(batch, storage, idx);
-}
-
-inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_tail(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_mdelem elem_to_add, grpc_metadata_batch_callouts_index idx) {
- GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
- storage->md = elem_to_add;
- return grpc_metadata_batch_add_tail(batch, storage, idx);
-}
-
+inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_tail(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_metadata_batch_callouts_index idx) {
+ return grpc_metadata_batch_link_tail(batch, storage, idx);
+}
+
+inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_tail(
+ grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
+ grpc_mdelem elem_to_add, grpc_metadata_batch_callouts_index idx) {
+ GPR_DEBUG_ASSERT(!GRPC_MDISNULL(elem_to_add));
+ storage->md = elem_to_add;
+ return grpc_metadata_batch_add_tail(batch, storage, idx);
+}
+
grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md);
struct grpc_filtered_mdelem {
diff --git a/contrib/libs/grpc/src/core/lib/transport/static_metadata.cc b/contrib/libs/grpc/src/core/lib/transport/static_metadata.cc
index e027c00d39..758f5227a6 100644
--- a/contrib/libs/grpc/src/core/lib/transport/static_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/static_metadata.cc
@@ -30,7 +30,7 @@
#include "src/core/lib/slice/slice_internal.h"
-static constexpr uint8_t g_bytes[] = {
+static constexpr uint8_t g_bytes[] = {
58, 112, 97, 116, 104, 58, 109, 101, 116, 104, 111, 100, 58, 115, 116,
97, 116, 117, 115, 58, 97, 117, 116, 104, 111, 114, 105, 116, 121, 58,
115, 99, 104, 101, 109, 101, 116, 101, 103, 114, 112, 99, 45, 109, 101,
@@ -49,25 +49,25 @@ static constexpr uint8_t g_bytes[] = {
101, 113, 117, 101, 115, 116, 103, 114, 112, 99, 45, 105, 110, 116, 101,
114, 110, 97, 108, 45, 115, 116, 114, 101, 97, 109, 45, 101, 110, 99,
111, 100, 105, 110, 103, 45, 114, 101, 113, 117, 101, 115, 116, 117, 115,
- 101, 114, 45, 97, 103, 101, 110, 116, 104, 111, 115, 116, 103, 114, 112,
- 99, 45, 112, 114, 101, 118, 105, 111, 117, 115, 45, 114, 112, 99, 45,
- 97, 116, 116, 101, 109, 112, 116, 115, 103, 114, 112, 99, 45, 114, 101,
- 116, 114, 121, 45, 112, 117, 115, 104, 98, 97, 99, 107, 45, 109, 115,
- 120, 45, 101, 110, 100, 112, 111, 105, 110, 116, 45, 108, 111, 97, 100,
- 45, 109, 101, 116, 114, 105, 99, 115, 45, 98, 105, 110, 103, 114, 112,
- 99, 45, 116, 105, 109, 101, 111, 117, 116, 49, 50, 51, 52, 103, 114,
- 112, 99, 46, 119, 97, 105, 116, 95, 102, 111, 114, 95, 114, 101, 97,
- 100, 121, 103, 114, 112, 99, 46, 116, 105, 109, 101, 111, 117, 116, 103,
- 114, 112, 99, 46, 109, 97, 120, 95, 114, 101, 113, 117, 101, 115, 116,
- 95, 109, 101, 115, 115, 97, 103, 101, 95, 98, 121, 116, 101, 115, 103,
- 114, 112, 99, 46, 109, 97, 120, 95, 114, 101, 115, 112, 111, 110, 115,
- 101, 95, 109, 101, 115, 115, 97, 103, 101, 95, 98, 121, 116, 101, 115,
- 47, 103, 114, 112, 99, 46, 108, 98, 46, 118, 49, 46, 76, 111, 97,
- 100, 66, 97, 108, 97, 110, 99, 101, 114, 47, 66, 97, 108, 97, 110,
- 99, 101, 76, 111, 97, 100, 47, 101, 110, 118, 111, 121, 46, 115, 101,
- 114, 118, 105, 99, 101, 46, 108, 111, 97, 100, 95, 115, 116, 97, 116,
- 115, 46, 118, 50, 46, 76, 111, 97, 100, 82, 101, 112, 111, 114, 116,
- 105, 110, 103, 83, 101, 114, 118, 105, 99, 101, 47, 83, 116, 114, 101,
+ 101, 114, 45, 97, 103, 101, 110, 116, 104, 111, 115, 116, 103, 114, 112,
+ 99, 45, 112, 114, 101, 118, 105, 111, 117, 115, 45, 114, 112, 99, 45,
+ 97, 116, 116, 101, 109, 112, 116, 115, 103, 114, 112, 99, 45, 114, 101,
+ 116, 114, 121, 45, 112, 117, 115, 104, 98, 97, 99, 107, 45, 109, 115,
+ 120, 45, 101, 110, 100, 112, 111, 105, 110, 116, 45, 108, 111, 97, 100,
+ 45, 109, 101, 116, 114, 105, 99, 115, 45, 98, 105, 110, 103, 114, 112,
+ 99, 45, 116, 105, 109, 101, 111, 117, 116, 49, 50, 51, 52, 103, 114,
+ 112, 99, 46, 119, 97, 105, 116, 95, 102, 111, 114, 95, 114, 101, 97,
+ 100, 121, 103, 114, 112, 99, 46, 116, 105, 109, 101, 111, 117, 116, 103,
+ 114, 112, 99, 46, 109, 97, 120, 95, 114, 101, 113, 117, 101, 115, 116,
+ 95, 109, 101, 115, 115, 97, 103, 101, 95, 98, 121, 116, 101, 115, 103,
+ 114, 112, 99, 46, 109, 97, 120, 95, 114, 101, 115, 112, 111, 110, 115,
+ 101, 95, 109, 101, 115, 115, 97, 103, 101, 95, 98, 121, 116, 101, 115,
+ 47, 103, 114, 112, 99, 46, 108, 98, 46, 118, 49, 46, 76, 111, 97,
+ 100, 66, 97, 108, 97, 110, 99, 101, 114, 47, 66, 97, 108, 97, 110,
+ 99, 101, 76, 111, 97, 100, 47, 101, 110, 118, 111, 121, 46, 115, 101,
+ 114, 118, 105, 99, 101, 46, 108, 111, 97, 100, 95, 115, 116, 97, 116,
+ 115, 46, 118, 50, 46, 76, 111, 97, 100, 82, 101, 112, 111, 114, 116,
+ 105, 110, 103, 83, 101, 114, 118, 105, 99, 101, 47, 83, 116, 114, 101,
97, 109, 76, 111, 97, 100, 83, 116, 97, 116, 115, 47, 101, 110, 118,
111, 121, 46, 115, 101, 114, 118, 105, 99, 101, 46, 108, 111, 97, 100,
95, 115, 116, 97, 116, 115, 46, 118, 51, 46, 76, 111, 97, 100, 82,
@@ -131,110 +131,110 @@ static constexpr uint8_t g_bytes[] = {
97, 116, 101, 44, 103, 122, 105, 112, 105, 100, 101, 110, 116, 105, 116,
121, 44, 100, 101, 102, 108, 97, 116, 101, 44, 103, 122, 105, 112};
-grpc_slice_refcount grpc_core::StaticSliceRefcount::kStaticSubRefcount;
+grpc_slice_refcount grpc_core::StaticSliceRefcount::kStaticSubRefcount;
-namespace grpc_core {
-struct StaticMetadataCtx {
-#ifndef NDEBUG
- const uint64_t init_canary = kGrpcStaticMetadataInitCanary;
-#endif
- StaticSliceRefcount refcounts[GRPC_STATIC_MDSTR_COUNT] = {
-
- StaticSliceRefcount(0), StaticSliceRefcount(1),
- StaticSliceRefcount(2), StaticSliceRefcount(3),
- StaticSliceRefcount(4), StaticSliceRefcount(5),
- StaticSliceRefcount(6), StaticSliceRefcount(7),
- StaticSliceRefcount(8), StaticSliceRefcount(9),
- StaticSliceRefcount(10), StaticSliceRefcount(11),
- StaticSliceRefcount(12), StaticSliceRefcount(13),
- StaticSliceRefcount(14), StaticSliceRefcount(15),
- StaticSliceRefcount(16), StaticSliceRefcount(17),
- StaticSliceRefcount(18), StaticSliceRefcount(19),
- StaticSliceRefcount(20), StaticSliceRefcount(21),
- StaticSliceRefcount(22), StaticSliceRefcount(23),
- StaticSliceRefcount(24), StaticSliceRefcount(25),
- StaticSliceRefcount(26), StaticSliceRefcount(27),
- StaticSliceRefcount(28), StaticSliceRefcount(29),
- StaticSliceRefcount(30), StaticSliceRefcount(31),
- StaticSliceRefcount(32), StaticSliceRefcount(33),
- StaticSliceRefcount(34), StaticSliceRefcount(35),
- StaticSliceRefcount(36), StaticSliceRefcount(37),
- StaticSliceRefcount(38), StaticSliceRefcount(39),
- StaticSliceRefcount(40), StaticSliceRefcount(41),
- StaticSliceRefcount(42), StaticSliceRefcount(43),
- StaticSliceRefcount(44), StaticSliceRefcount(45),
- StaticSliceRefcount(46), StaticSliceRefcount(47),
- StaticSliceRefcount(48), StaticSliceRefcount(49),
- StaticSliceRefcount(50), StaticSliceRefcount(51),
- StaticSliceRefcount(52), StaticSliceRefcount(53),
- StaticSliceRefcount(54), StaticSliceRefcount(55),
- StaticSliceRefcount(56), StaticSliceRefcount(57),
- StaticSliceRefcount(58), StaticSliceRefcount(59),
- StaticSliceRefcount(60), StaticSliceRefcount(61),
- StaticSliceRefcount(62), StaticSliceRefcount(63),
- StaticSliceRefcount(64), StaticSliceRefcount(65),
- StaticSliceRefcount(66), StaticSliceRefcount(67),
- StaticSliceRefcount(68), StaticSliceRefcount(69),
- StaticSliceRefcount(70), StaticSliceRefcount(71),
- StaticSliceRefcount(72), StaticSliceRefcount(73),
- StaticSliceRefcount(74), StaticSliceRefcount(75),
- StaticSliceRefcount(76), StaticSliceRefcount(77),
- StaticSliceRefcount(78), StaticSliceRefcount(79),
- StaticSliceRefcount(80), StaticSliceRefcount(81),
- StaticSliceRefcount(82), StaticSliceRefcount(83),
- StaticSliceRefcount(84), StaticSliceRefcount(85),
- StaticSliceRefcount(86), StaticSliceRefcount(87),
- StaticSliceRefcount(88), StaticSliceRefcount(89),
- StaticSliceRefcount(90), StaticSliceRefcount(91),
- StaticSliceRefcount(92), StaticSliceRefcount(93),
- StaticSliceRefcount(94), StaticSliceRefcount(95),
- StaticSliceRefcount(96), StaticSliceRefcount(97),
- StaticSliceRefcount(98), StaticSliceRefcount(99),
- StaticSliceRefcount(100), StaticSliceRefcount(101),
- StaticSliceRefcount(102), StaticSliceRefcount(103),
- StaticSliceRefcount(104), StaticSliceRefcount(105),
- StaticSliceRefcount(106), StaticSliceRefcount(107),
+namespace grpc_core {
+struct StaticMetadataCtx {
+#ifndef NDEBUG
+ const uint64_t init_canary = kGrpcStaticMetadataInitCanary;
+#endif
+ StaticSliceRefcount refcounts[GRPC_STATIC_MDSTR_COUNT] = {
+
+ StaticSliceRefcount(0), StaticSliceRefcount(1),
+ StaticSliceRefcount(2), StaticSliceRefcount(3),
+ StaticSliceRefcount(4), StaticSliceRefcount(5),
+ StaticSliceRefcount(6), StaticSliceRefcount(7),
+ StaticSliceRefcount(8), StaticSliceRefcount(9),
+ StaticSliceRefcount(10), StaticSliceRefcount(11),
+ StaticSliceRefcount(12), StaticSliceRefcount(13),
+ StaticSliceRefcount(14), StaticSliceRefcount(15),
+ StaticSliceRefcount(16), StaticSliceRefcount(17),
+ StaticSliceRefcount(18), StaticSliceRefcount(19),
+ StaticSliceRefcount(20), StaticSliceRefcount(21),
+ StaticSliceRefcount(22), StaticSliceRefcount(23),
+ StaticSliceRefcount(24), StaticSliceRefcount(25),
+ StaticSliceRefcount(26), StaticSliceRefcount(27),
+ StaticSliceRefcount(28), StaticSliceRefcount(29),
+ StaticSliceRefcount(30), StaticSliceRefcount(31),
+ StaticSliceRefcount(32), StaticSliceRefcount(33),
+ StaticSliceRefcount(34), StaticSliceRefcount(35),
+ StaticSliceRefcount(36), StaticSliceRefcount(37),
+ StaticSliceRefcount(38), StaticSliceRefcount(39),
+ StaticSliceRefcount(40), StaticSliceRefcount(41),
+ StaticSliceRefcount(42), StaticSliceRefcount(43),
+ StaticSliceRefcount(44), StaticSliceRefcount(45),
+ StaticSliceRefcount(46), StaticSliceRefcount(47),
+ StaticSliceRefcount(48), StaticSliceRefcount(49),
+ StaticSliceRefcount(50), StaticSliceRefcount(51),
+ StaticSliceRefcount(52), StaticSliceRefcount(53),
+ StaticSliceRefcount(54), StaticSliceRefcount(55),
+ StaticSliceRefcount(56), StaticSliceRefcount(57),
+ StaticSliceRefcount(58), StaticSliceRefcount(59),
+ StaticSliceRefcount(60), StaticSliceRefcount(61),
+ StaticSliceRefcount(62), StaticSliceRefcount(63),
+ StaticSliceRefcount(64), StaticSliceRefcount(65),
+ StaticSliceRefcount(66), StaticSliceRefcount(67),
+ StaticSliceRefcount(68), StaticSliceRefcount(69),
+ StaticSliceRefcount(70), StaticSliceRefcount(71),
+ StaticSliceRefcount(72), StaticSliceRefcount(73),
+ StaticSliceRefcount(74), StaticSliceRefcount(75),
+ StaticSliceRefcount(76), StaticSliceRefcount(77),
+ StaticSliceRefcount(78), StaticSliceRefcount(79),
+ StaticSliceRefcount(80), StaticSliceRefcount(81),
+ StaticSliceRefcount(82), StaticSliceRefcount(83),
+ StaticSliceRefcount(84), StaticSliceRefcount(85),
+ StaticSliceRefcount(86), StaticSliceRefcount(87),
+ StaticSliceRefcount(88), StaticSliceRefcount(89),
+ StaticSliceRefcount(90), StaticSliceRefcount(91),
+ StaticSliceRefcount(92), StaticSliceRefcount(93),
+ StaticSliceRefcount(94), StaticSliceRefcount(95),
+ StaticSliceRefcount(96), StaticSliceRefcount(97),
+ StaticSliceRefcount(98), StaticSliceRefcount(99),
+ StaticSliceRefcount(100), StaticSliceRefcount(101),
+ StaticSliceRefcount(102), StaticSliceRefcount(103),
+ StaticSliceRefcount(104), StaticSliceRefcount(105),
+ StaticSliceRefcount(106), StaticSliceRefcount(107),
StaticSliceRefcount(108), StaticSliceRefcount(109),
- };
-
- const StaticMetadataSlice slices[GRPC_STATIC_MDSTR_COUNT] = {
-
- grpc_core::StaticMetadataSlice(&refcounts[0].base, 5, g_bytes + 0),
- grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
- grpc_core::StaticMetadataSlice(&refcounts[3].base, 10, g_bytes + 19),
- grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
- grpc_core::StaticMetadataSlice(&refcounts[5].base, 2, g_bytes + 36),
- grpc_core::StaticMetadataSlice(&refcounts[6].base, 12, g_bytes + 38),
- grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
- grpc_core::StaticMetadataSlice(&refcounts[8].base, 16, g_bytes + 61),
- grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
- grpc_core::StaticMetadataSlice(&refcounts[11].base, 21, g_bytes + 110),
- grpc_core::StaticMetadataSlice(&refcounts[12].base, 13, g_bytes + 131),
- grpc_core::StaticMetadataSlice(&refcounts[13].base, 14, g_bytes + 144),
- grpc_core::StaticMetadataSlice(&refcounts[14].base, 12, g_bytes + 158),
- grpc_core::StaticMetadataSlice(&refcounts[15].base, 16, g_bytes + 170),
- grpc_core::StaticMetadataSlice(&refcounts[16].base, 15, g_bytes + 186),
- grpc_core::StaticMetadataSlice(&refcounts[17].base, 30, g_bytes + 201),
- grpc_core::StaticMetadataSlice(&refcounts[18].base, 37, g_bytes + 231),
- grpc_core::StaticMetadataSlice(&refcounts[19].base, 10, g_bytes + 268),
- grpc_core::StaticMetadataSlice(&refcounts[20].base, 4, g_bytes + 278),
- grpc_core::StaticMetadataSlice(&refcounts[21].base, 26, g_bytes + 282),
- grpc_core::StaticMetadataSlice(&refcounts[22].base, 22, g_bytes + 308),
- grpc_core::StaticMetadataSlice(&refcounts[23].base, 27, g_bytes + 330),
- grpc_core::StaticMetadataSlice(&refcounts[24].base, 12, g_bytes + 357),
- grpc_core::StaticMetadataSlice(&refcounts[25].base, 1, g_bytes + 369),
- grpc_core::StaticMetadataSlice(&refcounts[26].base, 1, g_bytes + 370),
- grpc_core::StaticMetadataSlice(&refcounts[27].base, 1, g_bytes + 371),
- grpc_core::StaticMetadataSlice(&refcounts[28].base, 1, g_bytes + 372),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- grpc_core::StaticMetadataSlice(&refcounts[30].base, 19, g_bytes + 373),
- grpc_core::StaticMetadataSlice(&refcounts[31].base, 12, g_bytes + 392),
- grpc_core::StaticMetadataSlice(&refcounts[32].base, 30, g_bytes + 404),
- grpc_core::StaticMetadataSlice(&refcounts[33].base, 31, g_bytes + 434),
- grpc_core::StaticMetadataSlice(&refcounts[34].base, 36, g_bytes + 465),
- grpc_core::StaticMetadataSlice(&refcounts[35].base, 65, g_bytes + 501),
+ };
+
+ const StaticMetadataSlice slices[GRPC_STATIC_MDSTR_COUNT] = {
+
+ grpc_core::StaticMetadataSlice(&refcounts[0].base, 5, g_bytes + 0),
+ grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ grpc_core::StaticMetadataSlice(&refcounts[3].base, 10, g_bytes + 19),
+ grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
+ grpc_core::StaticMetadataSlice(&refcounts[5].base, 2, g_bytes + 36),
+ grpc_core::StaticMetadataSlice(&refcounts[6].base, 12, g_bytes + 38),
+ grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
+ grpc_core::StaticMetadataSlice(&refcounts[8].base, 16, g_bytes + 61),
+ grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ grpc_core::StaticMetadataSlice(&refcounts[11].base, 21, g_bytes + 110),
+ grpc_core::StaticMetadataSlice(&refcounts[12].base, 13, g_bytes + 131),
+ grpc_core::StaticMetadataSlice(&refcounts[13].base, 14, g_bytes + 144),
+ grpc_core::StaticMetadataSlice(&refcounts[14].base, 12, g_bytes + 158),
+ grpc_core::StaticMetadataSlice(&refcounts[15].base, 16, g_bytes + 170),
+ grpc_core::StaticMetadataSlice(&refcounts[16].base, 15, g_bytes + 186),
+ grpc_core::StaticMetadataSlice(&refcounts[17].base, 30, g_bytes + 201),
+ grpc_core::StaticMetadataSlice(&refcounts[18].base, 37, g_bytes + 231),
+ grpc_core::StaticMetadataSlice(&refcounts[19].base, 10, g_bytes + 268),
+ grpc_core::StaticMetadataSlice(&refcounts[20].base, 4, g_bytes + 278),
+ grpc_core::StaticMetadataSlice(&refcounts[21].base, 26, g_bytes + 282),
+ grpc_core::StaticMetadataSlice(&refcounts[22].base, 22, g_bytes + 308),
+ grpc_core::StaticMetadataSlice(&refcounts[23].base, 27, g_bytes + 330),
+ grpc_core::StaticMetadataSlice(&refcounts[24].base, 12, g_bytes + 357),
+ grpc_core::StaticMetadataSlice(&refcounts[25].base, 1, g_bytes + 369),
+ grpc_core::StaticMetadataSlice(&refcounts[26].base, 1, g_bytes + 370),
+ grpc_core::StaticMetadataSlice(&refcounts[27].base, 1, g_bytes + 371),
+ grpc_core::StaticMetadataSlice(&refcounts[28].base, 1, g_bytes + 372),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ grpc_core::StaticMetadataSlice(&refcounts[30].base, 19, g_bytes + 373),
+ grpc_core::StaticMetadataSlice(&refcounts[31].base, 12, g_bytes + 392),
+ grpc_core::StaticMetadataSlice(&refcounts[32].base, 30, g_bytes + 404),
+ grpc_core::StaticMetadataSlice(&refcounts[33].base, 31, g_bytes + 434),
+ grpc_core::StaticMetadataSlice(&refcounts[34].base, 36, g_bytes + 465),
+ grpc_core::StaticMetadataSlice(&refcounts[35].base, 65, g_bytes + 501),
grpc_core::StaticMetadataSlice(&refcounts[36].base, 65, g_bytes + 566),
grpc_core::StaticMetadataSlice(&refcounts[37].base, 28, g_bytes + 631),
grpc_core::StaticMetadataSlice(&refcounts[38].base, 80, g_bytes + 659),
@@ -309,890 +309,890 @@ struct StaticMetadataCtx {
grpc_core::StaticMetadataSlice(&refcounts[107].base, 13, g_bytes + 1438),
grpc_core::StaticMetadataSlice(&refcounts[108].base, 12, g_bytes + 1451),
grpc_core::StaticMetadataSlice(&refcounts[109].base, 21, g_bytes + 1463),
- };
- StaticMetadata static_mdelem_table[GRPC_STATIC_MDELEM_COUNT] = {
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[3].base, 10, g_bytes + 19),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 0),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
+ };
+ StaticMetadata static_mdelem_table[GRPC_STATIC_MDELEM_COUNT] = {
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[3].base, 10, g_bytes + 19),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 0),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
grpc_core::StaticMetadataSlice(&refcounts[43].base, 3, g_bytes + 841),
- 1),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
+ 1),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
grpc_core::StaticMetadataSlice(&refcounts[44].base, 4, g_bytes + 844),
- 2),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[0].base, 5, g_bytes + 0),
+ 2),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[0].base, 5, g_bytes + 0),
grpc_core::StaticMetadataSlice(&refcounts[45].base, 1, g_bytes + 848),
- 3),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[0].base, 5, g_bytes + 0),
+ 3),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[0].base, 5, g_bytes + 0),
grpc_core::StaticMetadataSlice(&refcounts[46].base, 11,
g_bytes + 849),
- 4),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
+ 4),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
grpc_core::StaticMetadataSlice(&refcounts[47].base, 4, g_bytes + 860),
- 5),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
+ 5),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
grpc_core::StaticMetadataSlice(&refcounts[48].base, 5, g_bytes + 864),
- 6),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 6),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[49].base, 3, g_bytes + 869),
- 7),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 7),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[50].base, 3, g_bytes + 872),
- 8),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 8),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[51].base, 3, g_bytes + 875),
- 9),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 9),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[52].base, 3, g_bytes + 878),
- 10),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 10),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[53].base, 3, g_bytes + 881),
- 11),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 11),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[54].base, 3, g_bytes + 884),
- 12),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
+ 12),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[2].base, 7, g_bytes + 12),
grpc_core::StaticMetadataSlice(&refcounts[55].base, 3, g_bytes + 887),
- 13),
- StaticMetadata(
+ 13),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[56].base, 14,
g_bytes + 890),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 14),
- StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
- g_bytes + 186),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 14),
+ StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
+ g_bytes + 186),
grpc_core::StaticMetadataSlice(&refcounts[57].base, 13,
g_bytes + 904),
- 15),
- StaticMetadata(
+ 15),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[58].base, 15,
g_bytes + 917),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 16),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 16),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[59].base, 13,
g_bytes + 932),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 17),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 17),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[60].base, 6, g_bytes + 945),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 18),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 18),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[61].base, 27,
g_bytes + 951),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 19),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 19),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[62].base, 3, g_bytes + 978),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 20),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 20),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[63].base, 5, g_bytes + 981),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 21),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 21),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[64].base, 13,
g_bytes + 986),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 22),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 22),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[65].base, 13,
g_bytes + 999),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 23),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 23),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[66].base, 19,
g_bytes + 1012),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 24),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[15].base, 16,
- g_bytes + 170),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 25),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 24),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[15].base, 16,
+ g_bytes + 170),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 25),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[67].base, 16,
g_bytes + 1031),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 26),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 26),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[68].base, 14,
g_bytes + 1047),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 27),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 27),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[69].base, 16,
g_bytes + 1061),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 28),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 28),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[70].base, 13,
g_bytes + 1077),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 29),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[14].base, 12,
- g_bytes + 158),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 30),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 29),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[14].base, 12,
+ g_bytes + 158),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 30),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[71].base, 6,
g_bytes + 1090),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 31),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 31),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[72].base, 4,
g_bytes + 1096),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 32),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 32),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[73].base, 4,
g_bytes + 1100),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 33),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 33),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[74].base, 6,
g_bytes + 1104),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 34),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 34),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[75].base, 7,
g_bytes + 1110),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 35),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 35),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[76].base, 4,
g_bytes + 1117),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 36),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[20].base, 4, g_bytes + 278),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 37),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 36),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[20].base, 4, g_bytes + 278),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 37),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[77].base, 8,
g_bytes + 1121),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 38),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 38),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[78].base, 17,
g_bytes + 1129),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 39),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 39),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[79].base, 13,
g_bytes + 1146),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 40),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 40),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[80].base, 8,
g_bytes + 1159),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 41),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 41),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[81].base, 19,
g_bytes + 1167),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 42),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 42),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[82].base, 13,
g_bytes + 1186),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 43),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 43),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[83].base, 4,
g_bytes + 1199),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 44),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 44),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[84].base, 8,
g_bytes + 1203),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 45),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 45),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[85].base, 12,
g_bytes + 1211),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 46),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 46),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[86].base, 18,
g_bytes + 1223),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 47),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 47),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[87].base, 19,
g_bytes + 1241),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 48),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 48),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[88].base, 5,
g_bytes + 1260),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 49),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 49),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[89].base, 7,
g_bytes + 1265),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 50),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 50),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[90].base, 7,
g_bytes + 1272),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 51),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 51),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[91].base, 11,
g_bytes + 1279),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 52),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 52),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[92].base, 6,
g_bytes + 1290),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 53),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 53),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[93].base, 10,
g_bytes + 1296),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 54),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 54),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[94].base, 25,
g_bytes + 1306),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 55),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 55),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[95].base, 17,
g_bytes + 1331),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 56),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[19].base, 10,
- g_bytes + 268),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 57),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 56),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[19].base, 10,
+ g_bytes + 268),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 57),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[96].base, 4,
g_bytes + 1348),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 58),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 58),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[97].base, 3,
g_bytes + 1352),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 59),
- StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 59),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[98].base, 16,
g_bytes + 1355),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 60),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 60),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
grpc_core::StaticMetadataSlice(&refcounts[99].base, 1,
g_bytes + 1371),
- 61),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
- grpc_core::StaticMetadataSlice(&refcounts[25].base, 1, g_bytes + 369),
- 62),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
- grpc_core::StaticMetadataSlice(&refcounts[26].base, 1, g_bytes + 370),
- 63),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
+ 61),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
+ grpc_core::StaticMetadataSlice(&refcounts[25].base, 1, g_bytes + 369),
+ 62),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[7].base, 11, g_bytes + 50),
+ grpc_core::StaticMetadataSlice(&refcounts[26].base, 1, g_bytes + 370),
+ 63),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
grpc_core::StaticMetadataSlice(&refcounts[100].base, 8,
g_bytes + 1372),
- 64),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
+ 64),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
grpc_core::StaticMetadataSlice(&refcounts[41].base, 4, g_bytes + 826),
- 65),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
+ 65),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[9].base, 13, g_bytes + 77),
grpc_core::StaticMetadataSlice(&refcounts[40].base, 7, g_bytes + 819),
- 66),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[5].base, 2, g_bytes + 36),
+ 66),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[5].base, 2, g_bytes + 36),
grpc_core::StaticMetadataSlice(&refcounts[101].base, 8,
g_bytes + 1380),
- 67),
- StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[14].base, 12,
- g_bytes + 158),
+ 67),
+ StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[14].base, 12,
+ g_bytes + 158),
grpc_core::StaticMetadataSlice(&refcounts[102].base, 16,
g_bytes + 1388),
- 68),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
+ 68),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[4].base, 7, g_bytes + 29),
grpc_core::StaticMetadataSlice(&refcounts[103].base, 4,
g_bytes + 1404),
- 69),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
+ 69),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[1].base, 7, g_bytes + 5),
grpc_core::StaticMetadataSlice(&refcounts[104].base, 3,
g_bytes + 1408),
- 70),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
- g_bytes + 186),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 71),
- StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[15].base, 16,
- g_bytes + 170),
+ 70),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
+ g_bytes + 186),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 71),
+ StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[15].base, 16,
+ g_bytes + 170),
grpc_core::StaticMetadataSlice(&refcounts[100].base, 8,
g_bytes + 1372),
- 72),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[15].base, 16,
- g_bytes + 170),
+ 72),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[15].base, 16,
+ g_bytes + 170),
grpc_core::StaticMetadataSlice(&refcounts[41].base, 4, g_bytes + 826),
- 73),
- StaticMetadata(
+ 73),
+ StaticMetadata(
grpc_core::StaticMetadataSlice(&refcounts[105].base, 11,
g_bytes + 1411),
- grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
- 74),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ grpc_core::StaticMetadataSlice(&refcounts[29].base, 0, g_bytes + 373),
+ 74),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[100].base, 8,
g_bytes + 1372),
- 75),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ 75),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[40].base, 7, g_bytes + 819),
- 76),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ 76),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[106].base, 16,
g_bytes + 1422),
- 77),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ 77),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[41].base, 4, g_bytes + 826),
- 78),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ 78),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[107].base, 13,
g_bytes + 1438),
- 79),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ 79),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[108].base, 12,
g_bytes + 1451),
- 80),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
+ 80),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[10].base, 20, g_bytes + 90),
grpc_core::StaticMetadataSlice(&refcounts[109].base, 21,
g_bytes + 1463),
- 81),
- StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
- g_bytes + 186),
+ 81),
+ StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
+ g_bytes + 186),
grpc_core::StaticMetadataSlice(&refcounts[100].base, 8,
g_bytes + 1372),
- 82),
- StaticMetadata(
- grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
- g_bytes + 186),
+ 82),
+ StaticMetadata(
+ grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
+ g_bytes + 186),
grpc_core::StaticMetadataSlice(&refcounts[41].base, 4, g_bytes + 826),
- 83),
- StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
- g_bytes + 186),
+ 83),
+ StaticMetadata(grpc_core::StaticMetadataSlice(&refcounts[16].base, 15,
+ g_bytes + 186),
grpc_core::StaticMetadataSlice(&refcounts[107].base, 13,
g_bytes + 1438),
- 84),
- };
-
- /* Warning: the core static metadata currently operates under the soft
- constraint that the first GRPC_CHTTP2_LAST_STATIC_ENTRY (61) entries must
- contain metadata specified by the http2 hpack standard. The CHTTP2 transport
- reads the core metadata with this assumption in mind. If the order of the core
- static metadata is to be changed, then the CHTTP2 transport must be changed as
- well to stop relying on the core metadata. */
-
- grpc_mdelem static_mdelem_manifested[GRPC_STATIC_MDELEM_COUNT] = {
- // clang-format off
- /* GRPC_MDELEM_AUTHORITY_EMPTY:
- ":authority": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[0].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_METHOD_GET:
- ":method": "GET" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[1].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_METHOD_POST:
- ":method": "POST" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[2].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_PATH_SLASH:
- ":path": "/" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[3].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_PATH_SLASH_INDEX_DOT_HTML:
- ":path": "/index.html" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[4].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_SCHEME_HTTP:
- ":scheme": "http" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[5].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_SCHEME_HTTPS:
- ":scheme": "https" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[6].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_200:
- ":status": "200" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[7].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_204:
- ":status": "204" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[8].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_206:
- ":status": "206" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[9].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_304:
- ":status": "304" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[10].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_400:
- ":status": "400" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[11].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_404:
- ":status": "404" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[12].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STATUS_500:
- ":status": "500" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[13].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_CHARSET_EMPTY:
- "accept-charset": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[14].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_ENCODING_GZIP_COMMA_DEFLATE:
- "accept-encoding": "gzip, deflate" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[15].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_LANGUAGE_EMPTY:
- "accept-language": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[16].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_RANGES_EMPTY:
- "accept-ranges": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[17].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_EMPTY:
- "accept": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[18].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCESS_CONTROL_ALLOW_ORIGIN_EMPTY:
- "access-control-allow-origin": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[19].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_AGE_EMPTY:
- "age": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[20].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ALLOW_EMPTY:
- "allow": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[21].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_AUTHORIZATION_EMPTY:
- "authorization": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[22].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CACHE_CONTROL_EMPTY:
- "cache-control": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[23].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_DISPOSITION_EMPTY:
- "content-disposition": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[24].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_ENCODING_EMPTY:
- "content-encoding": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[25].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_LANGUAGE_EMPTY:
- "content-language": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[26].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_LENGTH_EMPTY:
- "content-length": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[27].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_LOCATION_EMPTY:
- "content-location": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[28].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_RANGE_EMPTY:
- "content-range": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[29].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_TYPE_EMPTY:
- "content-type": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[30].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_COOKIE_EMPTY:
- "cookie": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[31].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_DATE_EMPTY:
- "date": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[32].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ETAG_EMPTY:
- "etag": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[33].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_EXPECT_EMPTY:
- "expect": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[34].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_EXPIRES_EMPTY:
- "expires": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[35].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_FROM_EMPTY:
- "from": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[36].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_HOST_EMPTY:
- "host": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[37].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_IF_MATCH_EMPTY:
- "if-match": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[38].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_IF_MODIFIED_SINCE_EMPTY:
- "if-modified-since": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[39].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_IF_NONE_MATCH_EMPTY:
- "if-none-match": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[40].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_IF_RANGE_EMPTY:
- "if-range": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[41].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_IF_UNMODIFIED_SINCE_EMPTY:
- "if-unmodified-since": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[42].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_LAST_MODIFIED_EMPTY:
- "last-modified": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[43].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_LINK_EMPTY:
- "link": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[44].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_LOCATION_EMPTY:
- "location": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[45].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_MAX_FORWARDS_EMPTY:
- "max-forwards": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[46].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_PROXY_AUTHENTICATE_EMPTY:
- "proxy-authenticate": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[47].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_PROXY_AUTHORIZATION_EMPTY:
- "proxy-authorization": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[48].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_RANGE_EMPTY:
- "range": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[49].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_REFERER_EMPTY:
- "referer": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[50].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_REFRESH_EMPTY:
- "refresh": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[51].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_RETRY_AFTER_EMPTY:
- "retry-after": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[52].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_SERVER_EMPTY:
- "server": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[53].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_SET_COOKIE_EMPTY:
- "set-cookie": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[54].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_STRICT_TRANSPORT_SECURITY_EMPTY:
- "strict-transport-security": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[55].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_TRANSFER_ENCODING_EMPTY:
- "transfer-encoding": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[56].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_USER_AGENT_EMPTY:
- "user-agent": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[57].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_VARY_EMPTY:
- "vary": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[58].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_VIA_EMPTY:
- "via": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[59].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_WWW_AUTHENTICATE_EMPTY:
- "www-authenticate": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[60].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_STATUS_0:
- "grpc-status": "0" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[61].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_STATUS_1:
- "grpc-status": "1" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[62].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_STATUS_2:
- "grpc-status": "2" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[63].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ENCODING_IDENTITY:
- "grpc-encoding": "identity" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[64].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ENCODING_GZIP:
- "grpc-encoding": "gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[65].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ENCODING_DEFLATE:
- "grpc-encoding": "deflate" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[66].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_TE_TRAILERS:
- "te": "trailers" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[67].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC:
- "content-type": "application/grpc" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[68].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_SCHEME_GRPC:
- ":scheme": "grpc" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[69].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_METHOD_PUT:
- ":method": "PUT" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[70].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_ENCODING_EMPTY:
- "accept-encoding": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[71].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_ENCODING_IDENTITY:
- "content-encoding": "identity" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[72].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_CONTENT_ENCODING_GZIP:
- "content-encoding": "gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[73].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_LB_COST_BIN_EMPTY:
- "lb-cost-bin": "" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[74].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY:
- "grpc-accept-encoding": "identity" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[75].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE:
- "grpc-accept-encoding": "deflate" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[76].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE:
- "grpc-accept-encoding": "identity,deflate" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[77].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_GZIP:
- "grpc-accept-encoding": "gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[78].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP:
- "grpc-accept-encoding": "identity,gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[79].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE_COMMA_GZIP:
- "grpc-accept-encoding": "deflate,gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[80].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP:
- "grpc-accept-encoding": "identity,deflate,gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[81].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY:
- "accept-encoding": "identity" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[82].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_ENCODING_GZIP:
- "accept-encoding": "gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[83].data(),
- GRPC_MDELEM_STORAGE_STATIC),
- /* GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP:
- "accept-encoding": "identity,gzip" */
- GRPC_MAKE_MDELEM(
- &static_mdelem_table[84].data(),
- GRPC_MDELEM_STORAGE_STATIC)
- // clang-format on
- };
+ 84),
+ };
+
+ /* Warning: the core static metadata currently operates under the soft
+ constraint that the first GRPC_CHTTP2_LAST_STATIC_ENTRY (61) entries must
+ contain metadata specified by the http2 hpack standard. The CHTTP2 transport
+ reads the core metadata with this assumption in mind. If the order of the core
+ static metadata is to be changed, then the CHTTP2 transport must be changed as
+ well to stop relying on the core metadata. */
+
+ grpc_mdelem static_mdelem_manifested[GRPC_STATIC_MDELEM_COUNT] = {
+ // clang-format off
+ /* GRPC_MDELEM_AUTHORITY_EMPTY:
+ ":authority": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[0].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_METHOD_GET:
+ ":method": "GET" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[1].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_METHOD_POST:
+ ":method": "POST" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[2].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_PATH_SLASH:
+ ":path": "/" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[3].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_PATH_SLASH_INDEX_DOT_HTML:
+ ":path": "/index.html" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[4].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_SCHEME_HTTP:
+ ":scheme": "http" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[5].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_SCHEME_HTTPS:
+ ":scheme": "https" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[6].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_200:
+ ":status": "200" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[7].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_204:
+ ":status": "204" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[8].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_206:
+ ":status": "206" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[9].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_304:
+ ":status": "304" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[10].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_400:
+ ":status": "400" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[11].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_404:
+ ":status": "404" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[12].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STATUS_500:
+ ":status": "500" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[13].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_CHARSET_EMPTY:
+ "accept-charset": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[14].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_ENCODING_GZIP_COMMA_DEFLATE:
+ "accept-encoding": "gzip, deflate" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[15].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_LANGUAGE_EMPTY:
+ "accept-language": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[16].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_RANGES_EMPTY:
+ "accept-ranges": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[17].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_EMPTY:
+ "accept": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[18].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCESS_CONTROL_ALLOW_ORIGIN_EMPTY:
+ "access-control-allow-origin": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[19].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_AGE_EMPTY:
+ "age": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[20].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ALLOW_EMPTY:
+ "allow": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[21].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_AUTHORIZATION_EMPTY:
+ "authorization": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[22].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CACHE_CONTROL_EMPTY:
+ "cache-control": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[23].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_DISPOSITION_EMPTY:
+ "content-disposition": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[24].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_ENCODING_EMPTY:
+ "content-encoding": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[25].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_LANGUAGE_EMPTY:
+ "content-language": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[26].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_LENGTH_EMPTY:
+ "content-length": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[27].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_LOCATION_EMPTY:
+ "content-location": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[28].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_RANGE_EMPTY:
+ "content-range": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[29].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_TYPE_EMPTY:
+ "content-type": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[30].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_COOKIE_EMPTY:
+ "cookie": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[31].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_DATE_EMPTY:
+ "date": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[32].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ETAG_EMPTY:
+ "etag": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[33].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_EXPECT_EMPTY:
+ "expect": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[34].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_EXPIRES_EMPTY:
+ "expires": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[35].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_FROM_EMPTY:
+ "from": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[36].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_HOST_EMPTY:
+ "host": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[37].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_IF_MATCH_EMPTY:
+ "if-match": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[38].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_IF_MODIFIED_SINCE_EMPTY:
+ "if-modified-since": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[39].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_IF_NONE_MATCH_EMPTY:
+ "if-none-match": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[40].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_IF_RANGE_EMPTY:
+ "if-range": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[41].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_IF_UNMODIFIED_SINCE_EMPTY:
+ "if-unmodified-since": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[42].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_LAST_MODIFIED_EMPTY:
+ "last-modified": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[43].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_LINK_EMPTY:
+ "link": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[44].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_LOCATION_EMPTY:
+ "location": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[45].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_MAX_FORWARDS_EMPTY:
+ "max-forwards": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[46].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_PROXY_AUTHENTICATE_EMPTY:
+ "proxy-authenticate": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[47].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_PROXY_AUTHORIZATION_EMPTY:
+ "proxy-authorization": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[48].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_RANGE_EMPTY:
+ "range": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[49].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_REFERER_EMPTY:
+ "referer": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[50].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_REFRESH_EMPTY:
+ "refresh": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[51].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_RETRY_AFTER_EMPTY:
+ "retry-after": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[52].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_SERVER_EMPTY:
+ "server": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[53].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_SET_COOKIE_EMPTY:
+ "set-cookie": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[54].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_STRICT_TRANSPORT_SECURITY_EMPTY:
+ "strict-transport-security": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[55].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_TRANSFER_ENCODING_EMPTY:
+ "transfer-encoding": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[56].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_USER_AGENT_EMPTY:
+ "user-agent": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[57].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_VARY_EMPTY:
+ "vary": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[58].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_VIA_EMPTY:
+ "via": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[59].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_WWW_AUTHENTICATE_EMPTY:
+ "www-authenticate": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[60].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_STATUS_0:
+ "grpc-status": "0" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[61].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_STATUS_1:
+ "grpc-status": "1" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[62].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_STATUS_2:
+ "grpc-status": "2" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[63].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ENCODING_IDENTITY:
+ "grpc-encoding": "identity" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[64].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ENCODING_GZIP:
+ "grpc-encoding": "gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[65].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ENCODING_DEFLATE:
+ "grpc-encoding": "deflate" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[66].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_TE_TRAILERS:
+ "te": "trailers" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[67].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC:
+ "content-type": "application/grpc" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[68].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_SCHEME_GRPC:
+ ":scheme": "grpc" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[69].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_METHOD_PUT:
+ ":method": "PUT" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[70].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_ENCODING_EMPTY:
+ "accept-encoding": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[71].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_ENCODING_IDENTITY:
+ "content-encoding": "identity" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[72].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_CONTENT_ENCODING_GZIP:
+ "content-encoding": "gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[73].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_LB_COST_BIN_EMPTY:
+ "lb-cost-bin": "" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[74].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY:
+ "grpc-accept-encoding": "identity" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[75].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE:
+ "grpc-accept-encoding": "deflate" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[76].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE:
+ "grpc-accept-encoding": "identity,deflate" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[77].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_GZIP:
+ "grpc-accept-encoding": "gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[78].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP:
+ "grpc-accept-encoding": "identity,gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[79].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE_COMMA_GZIP:
+ "grpc-accept-encoding": "deflate,gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[80].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP:
+ "grpc-accept-encoding": "identity,deflate,gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[81].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY:
+ "accept-encoding": "identity" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[82].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_ENCODING_GZIP:
+ "accept-encoding": "gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[83].data(),
+ GRPC_MDELEM_STORAGE_STATIC),
+ /* GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP:
+ "accept-encoding": "identity,gzip" */
+ GRPC_MAKE_MDELEM(
+ &static_mdelem_table[84].data(),
+ GRPC_MDELEM_STORAGE_STATIC)
+ // clang-format on
+ };
};
-} // namespace grpc_core
-
-namespace grpc_core {
-static StaticMetadataCtx* g_static_metadata_slice_ctx = nullptr;
-const StaticMetadataSlice* g_static_metadata_slice_table = nullptr;
-StaticSliceRefcount* g_static_metadata_slice_refcounts = nullptr;
-StaticMetadata* g_static_mdelem_table = nullptr;
-grpc_mdelem* g_static_mdelem_manifested = nullptr;
-#ifndef NDEBUG
-uint64_t StaticMetadataInitCanary() {
- return g_static_metadata_slice_ctx->init_canary;
-}
-#endif
-} // namespace grpc_core
-
-void grpc_init_static_metadata_ctx(void) {
- grpc_core::g_static_metadata_slice_ctx = new grpc_core::StaticMetadataCtx();
- grpc_core::g_static_metadata_slice_table =
- grpc_core::g_static_metadata_slice_ctx->slices;
- grpc_core::g_static_metadata_slice_refcounts =
- grpc_core::g_static_metadata_slice_ctx->refcounts;
- grpc_core::g_static_mdelem_table =
- grpc_core::g_static_metadata_slice_ctx->static_mdelem_table;
- grpc_core::g_static_mdelem_manifested =
- grpc_core::g_static_metadata_slice_ctx->static_mdelem_manifested;
-}
-
-void grpc_destroy_static_metadata_ctx(void) {
- delete grpc_core::g_static_metadata_slice_ctx;
- grpc_core::g_static_metadata_slice_ctx = nullptr;
- grpc_core::g_static_metadata_slice_table = nullptr;
- grpc_core::g_static_metadata_slice_refcounts = nullptr;
- grpc_core::g_static_mdelem_table = nullptr;
- grpc_core::g_static_mdelem_manifested = nullptr;
-}
+} // namespace grpc_core
+namespace grpc_core {
+static StaticMetadataCtx* g_static_metadata_slice_ctx = nullptr;
+const StaticMetadataSlice* g_static_metadata_slice_table = nullptr;
+StaticSliceRefcount* g_static_metadata_slice_refcounts = nullptr;
+StaticMetadata* g_static_mdelem_table = nullptr;
+grpc_mdelem* g_static_mdelem_manifested = nullptr;
+#ifndef NDEBUG
+uint64_t StaticMetadataInitCanary() {
+ return g_static_metadata_slice_ctx->init_canary;
+}
+#endif
+} // namespace grpc_core
+
+void grpc_init_static_metadata_ctx(void) {
+ grpc_core::g_static_metadata_slice_ctx = new grpc_core::StaticMetadataCtx();
+ grpc_core::g_static_metadata_slice_table =
+ grpc_core::g_static_metadata_slice_ctx->slices;
+ grpc_core::g_static_metadata_slice_refcounts =
+ grpc_core::g_static_metadata_slice_ctx->refcounts;
+ grpc_core::g_static_mdelem_table =
+ grpc_core::g_static_metadata_slice_ctx->static_mdelem_table;
+ grpc_core::g_static_mdelem_manifested =
+ grpc_core::g_static_metadata_slice_ctx->static_mdelem_manifested;
+}
+
+void grpc_destroy_static_metadata_ctx(void) {
+ delete grpc_core::g_static_metadata_slice_ctx;
+ grpc_core::g_static_metadata_slice_ctx = nullptr;
+ grpc_core::g_static_metadata_slice_table = nullptr;
+ grpc_core::g_static_metadata_slice_refcounts = nullptr;
+ grpc_core::g_static_mdelem_table = nullptr;
+ grpc_core::g_static_mdelem_manifested = nullptr;
+}
+
uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 4, 6, 6, 8, 8, 2, 4, 4};
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 4, 6, 6, 8, 8, 2, 4, 4};
static const int8_t elems_r[] = {
15, 10, -8, 0, 2, -43, -83, -44, 0, 4, -8, 0, 0, 0, 10, 0, -7, 0,
@@ -1231,19 +1231,19 @@ static const uint8_t elem_idxs[] = {
53, 54, 55, 75, 69, 56, 58, 70, 59, 77, 79, 80, 81, 64, 60, 74,
82, 255, 255, 255, 255, 72, 255, 84, 255, 255, 0, 255, 255, 255, 255, 68};
-grpc_mdelem grpc_static_mdelem_for_static_strings(intptr_t a, intptr_t b) {
+grpc_mdelem grpc_static_mdelem_for_static_strings(intptr_t a, intptr_t b) {
if (a == -1 || b == -1) return GRPC_MDNULL;
uint32_t k = static_cast<uint32_t>(a * 110 + b);
uint32_t h = elems_phash(k);
return h < GPR_ARRAY_SIZE(elem_keys) && elem_keys[h] == k &&
elem_idxs[h] != 255
- ? GRPC_MAKE_MDELEM(
- &grpc_static_mdelem_table()[elem_idxs[h]].data(),
- GRPC_MDELEM_STORAGE_STATIC)
+ ? GRPC_MAKE_MDELEM(
+ &grpc_static_mdelem_table()[elem_idxs[h]].data(),
+ GRPC_MDELEM_STORAGE_STATIC)
: GRPC_MDNULL;
}
-const uint8_t grpc_static_accept_encoding_metadata[8] = {0, 75, 76, 77,
- 78, 79, 80, 81};
+const uint8_t grpc_static_accept_encoding_metadata[8] = {0, 75, 76, 77,
+ 78, 79, 80, 81};
-const uint8_t grpc_static_accept_stream_encoding_metadata[4] = {0, 82, 83, 84};
+const uint8_t grpc_static_accept_stream_encoding_metadata[4] = {0, 82, 83, 84};
diff --git a/contrib/libs/grpc/src/core/lib/transport/static_metadata.h b/contrib/libs/grpc/src/core/lib/transport/static_metadata.h
index 5d844af558..1b442741c4 100644
--- a/contrib/libs/grpc/src/core/lib/transport/static_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/transport/static_metadata.h
@@ -29,109 +29,109 @@
#include <grpc/support/port_platform.h>
-#include <cstdint>
-
+#include <cstdint>
+
#include "src/core/lib/transport/metadata.h"
-static_assert(
- std::is_trivially_destructible<grpc_core::StaticMetadataSlice>::value,
- "grpc_core::StaticMetadataSlice must be trivially destructible.");
+static_assert(
+ std::is_trivially_destructible<grpc_core::StaticMetadataSlice>::value,
+ "grpc_core::StaticMetadataSlice must be trivially destructible.");
#define GRPC_STATIC_MDSTR_COUNT 110
-
-void grpc_init_static_metadata_ctx(void);
-void grpc_destroy_static_metadata_ctx(void);
-namespace grpc_core {
-#ifndef NDEBUG
-constexpr uint64_t kGrpcStaticMetadataInitCanary = 0xCAFEF00DC0FFEE11L;
-uint64_t StaticMetadataInitCanary();
-#endif
-extern const StaticMetadataSlice* g_static_metadata_slice_table;
+
+void grpc_init_static_metadata_ctx(void);
+void grpc_destroy_static_metadata_ctx(void);
+namespace grpc_core {
+#ifndef NDEBUG
+constexpr uint64_t kGrpcStaticMetadataInitCanary = 0xCAFEF00DC0FFEE11L;
+uint64_t StaticMetadataInitCanary();
+#endif
+extern const StaticMetadataSlice* g_static_metadata_slice_table;
} // namespace grpc_core
-inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
- GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
- grpc_core::kGrpcStaticMetadataInitCanary);
- GPR_DEBUG_ASSERT(grpc_core::g_static_metadata_slice_table != nullptr);
- return grpc_core::g_static_metadata_slice_table;
-}
-
+inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
+ GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
+ grpc_core::kGrpcStaticMetadataInitCanary);
+ GPR_DEBUG_ASSERT(grpc_core::g_static_metadata_slice_table != nullptr);
+ return grpc_core::g_static_metadata_slice_table;
+}
+
/* ":path" */
-#define GRPC_MDSTR_PATH (grpc_static_slice_table()[0])
+#define GRPC_MDSTR_PATH (grpc_static_slice_table()[0])
/* ":method" */
-#define GRPC_MDSTR_METHOD (grpc_static_slice_table()[1])
+#define GRPC_MDSTR_METHOD (grpc_static_slice_table()[1])
/* ":status" */
-#define GRPC_MDSTR_STATUS (grpc_static_slice_table()[2])
+#define GRPC_MDSTR_STATUS (grpc_static_slice_table()[2])
/* ":authority" */
-#define GRPC_MDSTR_AUTHORITY (grpc_static_slice_table()[3])
+#define GRPC_MDSTR_AUTHORITY (grpc_static_slice_table()[3])
/* ":scheme" */
-#define GRPC_MDSTR_SCHEME (grpc_static_slice_table()[4])
+#define GRPC_MDSTR_SCHEME (grpc_static_slice_table()[4])
/* "te" */
-#define GRPC_MDSTR_TE (grpc_static_slice_table()[5])
+#define GRPC_MDSTR_TE (grpc_static_slice_table()[5])
/* "grpc-message" */
-#define GRPC_MDSTR_GRPC_MESSAGE (grpc_static_slice_table()[6])
+#define GRPC_MDSTR_GRPC_MESSAGE (grpc_static_slice_table()[6])
/* "grpc-status" */
-#define GRPC_MDSTR_GRPC_STATUS (grpc_static_slice_table()[7])
+#define GRPC_MDSTR_GRPC_STATUS (grpc_static_slice_table()[7])
/* "grpc-payload-bin" */
-#define GRPC_MDSTR_GRPC_PAYLOAD_BIN (grpc_static_slice_table()[8])
+#define GRPC_MDSTR_GRPC_PAYLOAD_BIN (grpc_static_slice_table()[8])
/* "grpc-encoding" */
-#define GRPC_MDSTR_GRPC_ENCODING (grpc_static_slice_table()[9])
+#define GRPC_MDSTR_GRPC_ENCODING (grpc_static_slice_table()[9])
/* "grpc-accept-encoding" */
-#define GRPC_MDSTR_GRPC_ACCEPT_ENCODING (grpc_static_slice_table()[10])
+#define GRPC_MDSTR_GRPC_ACCEPT_ENCODING (grpc_static_slice_table()[10])
/* "grpc-server-stats-bin" */
-#define GRPC_MDSTR_GRPC_SERVER_STATS_BIN (grpc_static_slice_table()[11])
+#define GRPC_MDSTR_GRPC_SERVER_STATS_BIN (grpc_static_slice_table()[11])
/* "grpc-tags-bin" */
-#define GRPC_MDSTR_GRPC_TAGS_BIN (grpc_static_slice_table()[12])
+#define GRPC_MDSTR_GRPC_TAGS_BIN (grpc_static_slice_table()[12])
/* "grpc-trace-bin" */
-#define GRPC_MDSTR_GRPC_TRACE_BIN (grpc_static_slice_table()[13])
+#define GRPC_MDSTR_GRPC_TRACE_BIN (grpc_static_slice_table()[13])
/* "content-type" */
-#define GRPC_MDSTR_CONTENT_TYPE (grpc_static_slice_table()[14])
+#define GRPC_MDSTR_CONTENT_TYPE (grpc_static_slice_table()[14])
/* "content-encoding" */
-#define GRPC_MDSTR_CONTENT_ENCODING (grpc_static_slice_table()[15])
+#define GRPC_MDSTR_CONTENT_ENCODING (grpc_static_slice_table()[15])
/* "accept-encoding" */
-#define GRPC_MDSTR_ACCEPT_ENCODING (grpc_static_slice_table()[16])
+#define GRPC_MDSTR_ACCEPT_ENCODING (grpc_static_slice_table()[16])
/* "grpc-internal-encoding-request" */
-#define GRPC_MDSTR_GRPC_INTERNAL_ENCODING_REQUEST \
- (grpc_static_slice_table()[17])
+#define GRPC_MDSTR_GRPC_INTERNAL_ENCODING_REQUEST \
+ (grpc_static_slice_table()[17])
/* "grpc-internal-stream-encoding-request" */
#define GRPC_MDSTR_GRPC_INTERNAL_STREAM_ENCODING_REQUEST \
- (grpc_static_slice_table()[18])
+ (grpc_static_slice_table()[18])
/* "user-agent" */
-#define GRPC_MDSTR_USER_AGENT (grpc_static_slice_table()[19])
+#define GRPC_MDSTR_USER_AGENT (grpc_static_slice_table()[19])
/* "host" */
-#define GRPC_MDSTR_HOST (grpc_static_slice_table()[20])
+#define GRPC_MDSTR_HOST (grpc_static_slice_table()[20])
/* "grpc-previous-rpc-attempts" */
-#define GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS (grpc_static_slice_table()[21])
+#define GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS (grpc_static_slice_table()[21])
/* "grpc-retry-pushback-ms" */
-#define GRPC_MDSTR_GRPC_RETRY_PUSHBACK_MS (grpc_static_slice_table()[22])
-/* "x-endpoint-load-metrics-bin" */
-#define GRPC_MDSTR_X_ENDPOINT_LOAD_METRICS_BIN (grpc_static_slice_table()[23])
+#define GRPC_MDSTR_GRPC_RETRY_PUSHBACK_MS (grpc_static_slice_table()[22])
+/* "x-endpoint-load-metrics-bin" */
+#define GRPC_MDSTR_X_ENDPOINT_LOAD_METRICS_BIN (grpc_static_slice_table()[23])
/* "grpc-timeout" */
-#define GRPC_MDSTR_GRPC_TIMEOUT (grpc_static_slice_table()[24])
+#define GRPC_MDSTR_GRPC_TIMEOUT (grpc_static_slice_table()[24])
/* "1" */
-#define GRPC_MDSTR_1 (grpc_static_slice_table()[25])
+#define GRPC_MDSTR_1 (grpc_static_slice_table()[25])
/* "2" */
-#define GRPC_MDSTR_2 (grpc_static_slice_table()[26])
+#define GRPC_MDSTR_2 (grpc_static_slice_table()[26])
/* "3" */
-#define GRPC_MDSTR_3 (grpc_static_slice_table()[27])
+#define GRPC_MDSTR_3 (grpc_static_slice_table()[27])
/* "4" */
-#define GRPC_MDSTR_4 (grpc_static_slice_table()[28])
+#define GRPC_MDSTR_4 (grpc_static_slice_table()[28])
/* "" */
-#define GRPC_MDSTR_EMPTY (grpc_static_slice_table()[29])
+#define GRPC_MDSTR_EMPTY (grpc_static_slice_table()[29])
/* "grpc.wait_for_ready" */
-#define GRPC_MDSTR_GRPC_DOT_WAIT_FOR_READY (grpc_static_slice_table()[30])
+#define GRPC_MDSTR_GRPC_DOT_WAIT_FOR_READY (grpc_static_slice_table()[30])
/* "grpc.timeout" */
-#define GRPC_MDSTR_GRPC_DOT_TIMEOUT (grpc_static_slice_table()[31])
+#define GRPC_MDSTR_GRPC_DOT_TIMEOUT (grpc_static_slice_table()[31])
/* "grpc.max_request_message_bytes" */
#define GRPC_MDSTR_GRPC_DOT_MAX_REQUEST_MESSAGE_BYTES \
- (grpc_static_slice_table()[32])
+ (grpc_static_slice_table()[32])
/* "grpc.max_response_message_bytes" */
#define GRPC_MDSTR_GRPC_DOT_MAX_RESPONSE_MESSAGE_BYTES \
- (grpc_static_slice_table()[33])
+ (grpc_static_slice_table()[33])
/* "/grpc.lb.v1.LoadBalancer/BalanceLoad" */
#define GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD \
- (grpc_static_slice_table()[34])
-/* "/envoy.service.load_stats.v2.LoadReportingService/StreamLoadStats" */
-#define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_LOAD_STATS_DOT_V2_DOT_LOADREPORTINGSERVICE_SLASH_STREAMLOADSTATS \
- (grpc_static_slice_table()[35])
+ (grpc_static_slice_table()[34])
+/* "/envoy.service.load_stats.v2.LoadReportingService/StreamLoadStats" */
+#define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_LOAD_STATS_DOT_V2_DOT_LOADREPORTINGSERVICE_SLASH_STREAMLOADSTATS \
+ (grpc_static_slice_table()[35])
/* "/envoy.service.load_stats.v3.LoadReportingService/StreamLoadStats" */
#define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_LOAD_STATS_DOT_V3_DOT_LOADREPORTINGSERVICE_SLASH_STREAMLOADSTATS \
(grpc_static_slice_table()[36])
@@ -288,238 +288,238 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
#define GRPC_MDSTR_IDENTITY_COMMA_DEFLATE_COMMA_GZIP \
(grpc_static_slice_table()[109])
-namespace grpc_core {
-struct StaticSliceRefcount;
-extern StaticSliceRefcount* g_static_metadata_slice_refcounts;
-} // namespace grpc_core
-inline grpc_core::StaticSliceRefcount* grpc_static_metadata_refcounts() {
- GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
- grpc_core::kGrpcStaticMetadataInitCanary);
- GPR_DEBUG_ASSERT(grpc_core::g_static_metadata_slice_refcounts != nullptr);
- return grpc_core::g_static_metadata_slice_refcounts;
-}
-
+namespace grpc_core {
+struct StaticSliceRefcount;
+extern StaticSliceRefcount* g_static_metadata_slice_refcounts;
+} // namespace grpc_core
+inline grpc_core::StaticSliceRefcount* grpc_static_metadata_refcounts() {
+ GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
+ grpc_core::kGrpcStaticMetadataInitCanary);
+ GPR_DEBUG_ASSERT(grpc_core::g_static_metadata_slice_refcounts != nullptr);
+ return grpc_core::g_static_metadata_slice_refcounts;
+}
+
#define GRPC_IS_STATIC_METADATA_STRING(slice) \
((slice).refcount != NULL && \
- (slice).refcount->GetType() == grpc_slice_refcount::Type::STATIC)
+ (slice).refcount->GetType() == grpc_slice_refcount::Type::STATIC)
-#define GRPC_STATIC_METADATA_INDEX(static_slice) \
- (reinterpret_cast<grpc_core::StaticSliceRefcount*>((static_slice).refcount) \
- ->index)
-
-#define GRPC_STATIC_MDELEM_COUNT 85
-
-namespace grpc_core {
-extern StaticMetadata* g_static_mdelem_table;
-extern grpc_mdelem* g_static_mdelem_manifested;
-} // namespace grpc_core
-inline grpc_core::StaticMetadata* grpc_static_mdelem_table() {
- GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
- grpc_core::kGrpcStaticMetadataInitCanary);
- GPR_DEBUG_ASSERT(grpc_core::g_static_mdelem_table != nullptr);
- return grpc_core::g_static_mdelem_table;
-}
-inline grpc_mdelem* grpc_static_mdelem_manifested() {
- GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
- grpc_core::kGrpcStaticMetadataInitCanary);
- GPR_DEBUG_ASSERT(grpc_core::g_static_mdelem_manifested != nullptr);
- return grpc_core::g_static_mdelem_manifested;
-}
+#define GRPC_STATIC_METADATA_INDEX(static_slice) \
+ (reinterpret_cast<grpc_core::StaticSliceRefcount*>((static_slice).refcount) \
+ ->index)
+#define GRPC_STATIC_MDELEM_COUNT 85
+
+namespace grpc_core {
+extern StaticMetadata* g_static_mdelem_table;
+extern grpc_mdelem* g_static_mdelem_manifested;
+} // namespace grpc_core
+inline grpc_core::StaticMetadata* grpc_static_mdelem_table() {
+ GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
+ grpc_core::kGrpcStaticMetadataInitCanary);
+ GPR_DEBUG_ASSERT(grpc_core::g_static_mdelem_table != nullptr);
+ return grpc_core::g_static_mdelem_table;
+}
+inline grpc_mdelem* grpc_static_mdelem_manifested() {
+ GPR_DEBUG_ASSERT(grpc_core::StaticMetadataInitCanary() ==
+ grpc_core::kGrpcStaticMetadataInitCanary);
+ GPR_DEBUG_ASSERT(grpc_core::g_static_mdelem_manifested != nullptr);
+ return grpc_core::g_static_mdelem_manifested;
+}
+
extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
/* ":authority": "" */
-#define GRPC_MDELEM_AUTHORITY_EMPTY (grpc_static_mdelem_manifested()[0])
+#define GRPC_MDELEM_AUTHORITY_EMPTY (grpc_static_mdelem_manifested()[0])
/* ":method": "GET" */
-#define GRPC_MDELEM_METHOD_GET (grpc_static_mdelem_manifested()[1])
+#define GRPC_MDELEM_METHOD_GET (grpc_static_mdelem_manifested()[1])
/* ":method": "POST" */
-#define GRPC_MDELEM_METHOD_POST (grpc_static_mdelem_manifested()[2])
+#define GRPC_MDELEM_METHOD_POST (grpc_static_mdelem_manifested()[2])
/* ":path": "/" */
-#define GRPC_MDELEM_PATH_SLASH (grpc_static_mdelem_manifested()[3])
+#define GRPC_MDELEM_PATH_SLASH (grpc_static_mdelem_manifested()[3])
/* ":path": "/index.html" */
#define GRPC_MDELEM_PATH_SLASH_INDEX_DOT_HTML \
- (grpc_static_mdelem_manifested()[4])
+ (grpc_static_mdelem_manifested()[4])
/* ":scheme": "http" */
-#define GRPC_MDELEM_SCHEME_HTTP (grpc_static_mdelem_manifested()[5])
+#define GRPC_MDELEM_SCHEME_HTTP (grpc_static_mdelem_manifested()[5])
/* ":scheme": "https" */
-#define GRPC_MDELEM_SCHEME_HTTPS (grpc_static_mdelem_manifested()[6])
+#define GRPC_MDELEM_SCHEME_HTTPS (grpc_static_mdelem_manifested()[6])
/* ":status": "200" */
-#define GRPC_MDELEM_STATUS_200 (grpc_static_mdelem_manifested()[7])
+#define GRPC_MDELEM_STATUS_200 (grpc_static_mdelem_manifested()[7])
/* ":status": "204" */
-#define GRPC_MDELEM_STATUS_204 (grpc_static_mdelem_manifested()[8])
+#define GRPC_MDELEM_STATUS_204 (grpc_static_mdelem_manifested()[8])
/* ":status": "206" */
-#define GRPC_MDELEM_STATUS_206 (grpc_static_mdelem_manifested()[9])
+#define GRPC_MDELEM_STATUS_206 (grpc_static_mdelem_manifested()[9])
/* ":status": "304" */
-#define GRPC_MDELEM_STATUS_304 (grpc_static_mdelem_manifested()[10])
+#define GRPC_MDELEM_STATUS_304 (grpc_static_mdelem_manifested()[10])
/* ":status": "400" */
-#define GRPC_MDELEM_STATUS_400 (grpc_static_mdelem_manifested()[11])
+#define GRPC_MDELEM_STATUS_400 (grpc_static_mdelem_manifested()[11])
/* ":status": "404" */
-#define GRPC_MDELEM_STATUS_404 (grpc_static_mdelem_manifested()[12])
+#define GRPC_MDELEM_STATUS_404 (grpc_static_mdelem_manifested()[12])
/* ":status": "500" */
-#define GRPC_MDELEM_STATUS_500 (grpc_static_mdelem_manifested()[13])
+#define GRPC_MDELEM_STATUS_500 (grpc_static_mdelem_manifested()[13])
/* "accept-charset": "" */
-#define GRPC_MDELEM_ACCEPT_CHARSET_EMPTY (grpc_static_mdelem_manifested()[14])
+#define GRPC_MDELEM_ACCEPT_CHARSET_EMPTY (grpc_static_mdelem_manifested()[14])
/* "accept-encoding": "gzip, deflate" */
#define GRPC_MDELEM_ACCEPT_ENCODING_GZIP_COMMA_DEFLATE \
- (grpc_static_mdelem_manifested()[15])
+ (grpc_static_mdelem_manifested()[15])
/* "accept-language": "" */
-#define GRPC_MDELEM_ACCEPT_LANGUAGE_EMPTY (grpc_static_mdelem_manifested()[16])
+#define GRPC_MDELEM_ACCEPT_LANGUAGE_EMPTY (grpc_static_mdelem_manifested()[16])
/* "accept-ranges": "" */
-#define GRPC_MDELEM_ACCEPT_RANGES_EMPTY (grpc_static_mdelem_manifested()[17])
+#define GRPC_MDELEM_ACCEPT_RANGES_EMPTY (grpc_static_mdelem_manifested()[17])
/* "accept": "" */
-#define GRPC_MDELEM_ACCEPT_EMPTY (grpc_static_mdelem_manifested()[18])
+#define GRPC_MDELEM_ACCEPT_EMPTY (grpc_static_mdelem_manifested()[18])
/* "access-control-allow-origin": "" */
#define GRPC_MDELEM_ACCESS_CONTROL_ALLOW_ORIGIN_EMPTY \
- (grpc_static_mdelem_manifested()[19])
+ (grpc_static_mdelem_manifested()[19])
/* "age": "" */
-#define GRPC_MDELEM_AGE_EMPTY (grpc_static_mdelem_manifested()[20])
+#define GRPC_MDELEM_AGE_EMPTY (grpc_static_mdelem_manifested()[20])
/* "allow": "" */
-#define GRPC_MDELEM_ALLOW_EMPTY (grpc_static_mdelem_manifested()[21])
+#define GRPC_MDELEM_ALLOW_EMPTY (grpc_static_mdelem_manifested()[21])
/* "authorization": "" */
-#define GRPC_MDELEM_AUTHORIZATION_EMPTY (grpc_static_mdelem_manifested()[22])
+#define GRPC_MDELEM_AUTHORIZATION_EMPTY (grpc_static_mdelem_manifested()[22])
/* "cache-control": "" */
-#define GRPC_MDELEM_CACHE_CONTROL_EMPTY (grpc_static_mdelem_manifested()[23])
+#define GRPC_MDELEM_CACHE_CONTROL_EMPTY (grpc_static_mdelem_manifested()[23])
/* "content-disposition": "" */
#define GRPC_MDELEM_CONTENT_DISPOSITION_EMPTY \
- (grpc_static_mdelem_manifested()[24])
+ (grpc_static_mdelem_manifested()[24])
/* "content-encoding": "" */
-#define GRPC_MDELEM_CONTENT_ENCODING_EMPTY (grpc_static_mdelem_manifested()[25])
+#define GRPC_MDELEM_CONTENT_ENCODING_EMPTY (grpc_static_mdelem_manifested()[25])
/* "content-language": "" */
-#define GRPC_MDELEM_CONTENT_LANGUAGE_EMPTY (grpc_static_mdelem_manifested()[26])
+#define GRPC_MDELEM_CONTENT_LANGUAGE_EMPTY (grpc_static_mdelem_manifested()[26])
/* "content-length": "" */
-#define GRPC_MDELEM_CONTENT_LENGTH_EMPTY (grpc_static_mdelem_manifested()[27])
+#define GRPC_MDELEM_CONTENT_LENGTH_EMPTY (grpc_static_mdelem_manifested()[27])
/* "content-location": "" */
-#define GRPC_MDELEM_CONTENT_LOCATION_EMPTY (grpc_static_mdelem_manifested()[28])
+#define GRPC_MDELEM_CONTENT_LOCATION_EMPTY (grpc_static_mdelem_manifested()[28])
/* "content-range": "" */
-#define GRPC_MDELEM_CONTENT_RANGE_EMPTY (grpc_static_mdelem_manifested()[29])
+#define GRPC_MDELEM_CONTENT_RANGE_EMPTY (grpc_static_mdelem_manifested()[29])
/* "content-type": "" */
-#define GRPC_MDELEM_CONTENT_TYPE_EMPTY (grpc_static_mdelem_manifested()[30])
+#define GRPC_MDELEM_CONTENT_TYPE_EMPTY (grpc_static_mdelem_manifested()[30])
/* "cookie": "" */
-#define GRPC_MDELEM_COOKIE_EMPTY (grpc_static_mdelem_manifested()[31])
+#define GRPC_MDELEM_COOKIE_EMPTY (grpc_static_mdelem_manifested()[31])
/* "date": "" */
-#define GRPC_MDELEM_DATE_EMPTY (grpc_static_mdelem_manifested()[32])
+#define GRPC_MDELEM_DATE_EMPTY (grpc_static_mdelem_manifested()[32])
/* "etag": "" */
-#define GRPC_MDELEM_ETAG_EMPTY (grpc_static_mdelem_manifested()[33])
+#define GRPC_MDELEM_ETAG_EMPTY (grpc_static_mdelem_manifested()[33])
/* "expect": "" */
-#define GRPC_MDELEM_EXPECT_EMPTY (grpc_static_mdelem_manifested()[34])
+#define GRPC_MDELEM_EXPECT_EMPTY (grpc_static_mdelem_manifested()[34])
/* "expires": "" */
-#define GRPC_MDELEM_EXPIRES_EMPTY (grpc_static_mdelem_manifested()[35])
+#define GRPC_MDELEM_EXPIRES_EMPTY (grpc_static_mdelem_manifested()[35])
/* "from": "" */
-#define GRPC_MDELEM_FROM_EMPTY (grpc_static_mdelem_manifested()[36])
+#define GRPC_MDELEM_FROM_EMPTY (grpc_static_mdelem_manifested()[36])
/* "host": "" */
-#define GRPC_MDELEM_HOST_EMPTY (grpc_static_mdelem_manifested()[37])
+#define GRPC_MDELEM_HOST_EMPTY (grpc_static_mdelem_manifested()[37])
/* "if-match": "" */
-#define GRPC_MDELEM_IF_MATCH_EMPTY (grpc_static_mdelem_manifested()[38])
+#define GRPC_MDELEM_IF_MATCH_EMPTY (grpc_static_mdelem_manifested()[38])
/* "if-modified-since": "" */
#define GRPC_MDELEM_IF_MODIFIED_SINCE_EMPTY \
- (grpc_static_mdelem_manifested()[39])
+ (grpc_static_mdelem_manifested()[39])
/* "if-none-match": "" */
-#define GRPC_MDELEM_IF_NONE_MATCH_EMPTY (grpc_static_mdelem_manifested()[40])
+#define GRPC_MDELEM_IF_NONE_MATCH_EMPTY (grpc_static_mdelem_manifested()[40])
/* "if-range": "" */
-#define GRPC_MDELEM_IF_RANGE_EMPTY (grpc_static_mdelem_manifested()[41])
+#define GRPC_MDELEM_IF_RANGE_EMPTY (grpc_static_mdelem_manifested()[41])
/* "if-unmodified-since": "" */
#define GRPC_MDELEM_IF_UNMODIFIED_SINCE_EMPTY \
- (grpc_static_mdelem_manifested()[42])
+ (grpc_static_mdelem_manifested()[42])
/* "last-modified": "" */
-#define GRPC_MDELEM_LAST_MODIFIED_EMPTY (grpc_static_mdelem_manifested()[43])
+#define GRPC_MDELEM_LAST_MODIFIED_EMPTY (grpc_static_mdelem_manifested()[43])
/* "link": "" */
-#define GRPC_MDELEM_LINK_EMPTY (grpc_static_mdelem_manifested()[44])
+#define GRPC_MDELEM_LINK_EMPTY (grpc_static_mdelem_manifested()[44])
/* "location": "" */
-#define GRPC_MDELEM_LOCATION_EMPTY (grpc_static_mdelem_manifested()[45])
+#define GRPC_MDELEM_LOCATION_EMPTY (grpc_static_mdelem_manifested()[45])
/* "max-forwards": "" */
-#define GRPC_MDELEM_MAX_FORWARDS_EMPTY (grpc_static_mdelem_manifested()[46])
+#define GRPC_MDELEM_MAX_FORWARDS_EMPTY (grpc_static_mdelem_manifested()[46])
/* "proxy-authenticate": "" */
#define GRPC_MDELEM_PROXY_AUTHENTICATE_EMPTY \
- (grpc_static_mdelem_manifested()[47])
+ (grpc_static_mdelem_manifested()[47])
/* "proxy-authorization": "" */
#define GRPC_MDELEM_PROXY_AUTHORIZATION_EMPTY \
- (grpc_static_mdelem_manifested()[48])
+ (grpc_static_mdelem_manifested()[48])
/* "range": "" */
-#define GRPC_MDELEM_RANGE_EMPTY (grpc_static_mdelem_manifested()[49])
+#define GRPC_MDELEM_RANGE_EMPTY (grpc_static_mdelem_manifested()[49])
/* "referer": "" */
-#define GRPC_MDELEM_REFERER_EMPTY (grpc_static_mdelem_manifested()[50])
+#define GRPC_MDELEM_REFERER_EMPTY (grpc_static_mdelem_manifested()[50])
/* "refresh": "" */
-#define GRPC_MDELEM_REFRESH_EMPTY (grpc_static_mdelem_manifested()[51])
+#define GRPC_MDELEM_REFRESH_EMPTY (grpc_static_mdelem_manifested()[51])
/* "retry-after": "" */
-#define GRPC_MDELEM_RETRY_AFTER_EMPTY (grpc_static_mdelem_manifested()[52])
+#define GRPC_MDELEM_RETRY_AFTER_EMPTY (grpc_static_mdelem_manifested()[52])
/* "server": "" */
-#define GRPC_MDELEM_SERVER_EMPTY (grpc_static_mdelem_manifested()[53])
+#define GRPC_MDELEM_SERVER_EMPTY (grpc_static_mdelem_manifested()[53])
/* "set-cookie": "" */
-#define GRPC_MDELEM_SET_COOKIE_EMPTY (grpc_static_mdelem_manifested()[54])
+#define GRPC_MDELEM_SET_COOKIE_EMPTY (grpc_static_mdelem_manifested()[54])
/* "strict-transport-security": "" */
#define GRPC_MDELEM_STRICT_TRANSPORT_SECURITY_EMPTY \
- (grpc_static_mdelem_manifested()[55])
+ (grpc_static_mdelem_manifested()[55])
/* "transfer-encoding": "" */
#define GRPC_MDELEM_TRANSFER_ENCODING_EMPTY \
- (grpc_static_mdelem_manifested()[56])
+ (grpc_static_mdelem_manifested()[56])
/* "user-agent": "" */
-#define GRPC_MDELEM_USER_AGENT_EMPTY (grpc_static_mdelem_manifested()[57])
+#define GRPC_MDELEM_USER_AGENT_EMPTY (grpc_static_mdelem_manifested()[57])
/* "vary": "" */
-#define GRPC_MDELEM_VARY_EMPTY (grpc_static_mdelem_manifested()[58])
+#define GRPC_MDELEM_VARY_EMPTY (grpc_static_mdelem_manifested()[58])
/* "via": "" */
-#define GRPC_MDELEM_VIA_EMPTY (grpc_static_mdelem_manifested()[59])
+#define GRPC_MDELEM_VIA_EMPTY (grpc_static_mdelem_manifested()[59])
/* "www-authenticate": "" */
-#define GRPC_MDELEM_WWW_AUTHENTICATE_EMPTY (grpc_static_mdelem_manifested()[60])
+#define GRPC_MDELEM_WWW_AUTHENTICATE_EMPTY (grpc_static_mdelem_manifested()[60])
/* "grpc-status": "0" */
-#define GRPC_MDELEM_GRPC_STATUS_0 (grpc_static_mdelem_manifested()[61])
+#define GRPC_MDELEM_GRPC_STATUS_0 (grpc_static_mdelem_manifested()[61])
/* "grpc-status": "1" */
-#define GRPC_MDELEM_GRPC_STATUS_1 (grpc_static_mdelem_manifested()[62])
+#define GRPC_MDELEM_GRPC_STATUS_1 (grpc_static_mdelem_manifested()[62])
/* "grpc-status": "2" */
-#define GRPC_MDELEM_GRPC_STATUS_2 (grpc_static_mdelem_manifested()[63])
+#define GRPC_MDELEM_GRPC_STATUS_2 (grpc_static_mdelem_manifested()[63])
/* "grpc-encoding": "identity" */
-#define GRPC_MDELEM_GRPC_ENCODING_IDENTITY (grpc_static_mdelem_manifested()[64])
+#define GRPC_MDELEM_GRPC_ENCODING_IDENTITY (grpc_static_mdelem_manifested()[64])
/* "grpc-encoding": "gzip" */
-#define GRPC_MDELEM_GRPC_ENCODING_GZIP (grpc_static_mdelem_manifested()[65])
+#define GRPC_MDELEM_GRPC_ENCODING_GZIP (grpc_static_mdelem_manifested()[65])
/* "grpc-encoding": "deflate" */
-#define GRPC_MDELEM_GRPC_ENCODING_DEFLATE (grpc_static_mdelem_manifested()[66])
+#define GRPC_MDELEM_GRPC_ENCODING_DEFLATE (grpc_static_mdelem_manifested()[66])
/* "te": "trailers" */
-#define GRPC_MDELEM_TE_TRAILERS (grpc_static_mdelem_manifested()[67])
+#define GRPC_MDELEM_TE_TRAILERS (grpc_static_mdelem_manifested()[67])
/* "content-type": "application/grpc" */
#define GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC \
- (grpc_static_mdelem_manifested()[68])
+ (grpc_static_mdelem_manifested()[68])
/* ":scheme": "grpc" */
-#define GRPC_MDELEM_SCHEME_GRPC (grpc_static_mdelem_manifested()[69])
+#define GRPC_MDELEM_SCHEME_GRPC (grpc_static_mdelem_manifested()[69])
/* ":method": "PUT" */
-#define GRPC_MDELEM_METHOD_PUT (grpc_static_mdelem_manifested()[70])
+#define GRPC_MDELEM_METHOD_PUT (grpc_static_mdelem_manifested()[70])
/* "accept-encoding": "" */
-#define GRPC_MDELEM_ACCEPT_ENCODING_EMPTY (grpc_static_mdelem_manifested()[71])
+#define GRPC_MDELEM_ACCEPT_ENCODING_EMPTY (grpc_static_mdelem_manifested()[71])
/* "content-encoding": "identity" */
#define GRPC_MDELEM_CONTENT_ENCODING_IDENTITY \
- (grpc_static_mdelem_manifested()[72])
+ (grpc_static_mdelem_manifested()[72])
/* "content-encoding": "gzip" */
-#define GRPC_MDELEM_CONTENT_ENCODING_GZIP (grpc_static_mdelem_manifested()[73])
+#define GRPC_MDELEM_CONTENT_ENCODING_GZIP (grpc_static_mdelem_manifested()[73])
/* "lb-cost-bin": "" */
-#define GRPC_MDELEM_LB_COST_BIN_EMPTY (grpc_static_mdelem_manifested()[74])
+#define GRPC_MDELEM_LB_COST_BIN_EMPTY (grpc_static_mdelem_manifested()[74])
/* "grpc-accept-encoding": "identity" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY \
- (grpc_static_mdelem_manifested()[75])
+ (grpc_static_mdelem_manifested()[75])
/* "grpc-accept-encoding": "deflate" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE \
- (grpc_static_mdelem_manifested()[76])
+ (grpc_static_mdelem_manifested()[76])
/* "grpc-accept-encoding": "identity,deflate" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE \
- (grpc_static_mdelem_manifested()[77])
+ (grpc_static_mdelem_manifested()[77])
/* "grpc-accept-encoding": "gzip" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_GZIP \
- (grpc_static_mdelem_manifested()[78])
+ (grpc_static_mdelem_manifested()[78])
/* "grpc-accept-encoding": "identity,gzip" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP \
- (grpc_static_mdelem_manifested()[79])
+ (grpc_static_mdelem_manifested()[79])
/* "grpc-accept-encoding": "deflate,gzip" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE_COMMA_GZIP \
- (grpc_static_mdelem_manifested()[80])
+ (grpc_static_mdelem_manifested()[80])
/* "grpc-accept-encoding": "identity,deflate,gzip" */
#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP \
- (grpc_static_mdelem_manifested()[81])
+ (grpc_static_mdelem_manifested()[81])
/* "accept-encoding": "identity" */
#define GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY \
- (grpc_static_mdelem_manifested()[82])
+ (grpc_static_mdelem_manifested()[82])
/* "accept-encoding": "gzip" */
-#define GRPC_MDELEM_ACCEPT_ENCODING_GZIP (grpc_static_mdelem_manifested()[83])
+#define GRPC_MDELEM_ACCEPT_ENCODING_GZIP (grpc_static_mdelem_manifested()[83])
/* "accept-encoding": "identity,gzip" */
#define GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP \
- (grpc_static_mdelem_manifested()[84])
+ (grpc_static_mdelem_manifested()[84])
-grpc_mdelem grpc_static_mdelem_for_static_strings(intptr_t a, intptr_t b);
+grpc_mdelem grpc_static_mdelem_for_static_strings(intptr_t a, intptr_t b);
typedef enum {
GRPC_BATCH_PATH,
GRPC_BATCH_METHOD,
@@ -544,7 +544,7 @@ typedef enum {
GRPC_BATCH_HOST,
GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS,
GRPC_BATCH_GRPC_RETRY_PUSHBACK_MS,
- GRPC_BATCH_X_ENDPOINT_LOAD_METRICS_BIN,
+ GRPC_BATCH_X_ENDPOINT_LOAD_METRICS_BIN,
GRPC_BATCH_CALLOUTS_COUNT
} grpc_metadata_batch_callouts_index;
@@ -574,31 +574,31 @@ typedef union {
struct grpc_linked_mdelem* host;
struct grpc_linked_mdelem* grpc_previous_rpc_attempts;
struct grpc_linked_mdelem* grpc_retry_pushback_ms;
- struct grpc_linked_mdelem* x_endpoint_load_metrics_bin;
+ struct grpc_linked_mdelem* x_endpoint_load_metrics_bin;
} named;
} grpc_metadata_batch_callouts;
-#define GRPC_BATCH_INDEX_OF(slice) \
- (GRPC_IS_STATIC_METADATA_STRING((slice)) && \
- reinterpret_cast<grpc_core::StaticSliceRefcount*>((slice).refcount) \
- ->index <= static_cast<uint32_t>(GRPC_BATCH_CALLOUTS_COUNT) \
- ? static_cast<grpc_metadata_batch_callouts_index>( \
- reinterpret_cast<grpc_core::StaticSliceRefcount*>( \
- (slice).refcount) \
- ->index) \
+#define GRPC_BATCH_INDEX_OF(slice) \
+ (GRPC_IS_STATIC_METADATA_STRING((slice)) && \
+ reinterpret_cast<grpc_core::StaticSliceRefcount*>((slice).refcount) \
+ ->index <= static_cast<uint32_t>(GRPC_BATCH_CALLOUTS_COUNT) \
+ ? static_cast<grpc_metadata_batch_callouts_index>( \
+ reinterpret_cast<grpc_core::StaticSliceRefcount*>( \
+ (slice).refcount) \
+ ->index) \
: GRPC_BATCH_CALLOUTS_COUNT)
extern const uint8_t grpc_static_accept_encoding_metadata[8];
-#define GRPC_MDELEM_ACCEPT_ENCODING_FOR_ALGORITHMS(algs) \
- (GRPC_MAKE_MDELEM(&grpc_static_mdelem_table() \
- [grpc_static_accept_encoding_metadata[(algs)]] \
- .data(), \
- GRPC_MDELEM_STORAGE_STATIC))
+#define GRPC_MDELEM_ACCEPT_ENCODING_FOR_ALGORITHMS(algs) \
+ (GRPC_MAKE_MDELEM(&grpc_static_mdelem_table() \
+ [grpc_static_accept_encoding_metadata[(algs)]] \
+ .data(), \
+ GRPC_MDELEM_STORAGE_STATIC))
extern const uint8_t grpc_static_accept_stream_encoding_metadata[4];
#define GRPC_MDELEM_ACCEPT_STREAM_ENCODING_FOR_ALGORITHMS(algs) \
- (GRPC_MAKE_MDELEM(&grpc_static_mdelem_table() \
- [grpc_static_accept_stream_encoding_metadata[(algs)]] \
- .data(), \
+ (GRPC_MAKE_MDELEM(&grpc_static_mdelem_table() \
+ [grpc_static_accept_stream_encoding_metadata[(algs)]] \
+ .data(), \
GRPC_MDELEM_STORAGE_STATIC))
#endif /* GRPC_CORE_LIB_TRANSPORT_STATIC_METADATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/status_conversion.cc b/contrib/libs/grpc/src/core/lib/transport/status_conversion.cc
index 46c6cd8c3b..be665864c9 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_conversion.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/status_conversion.cc
@@ -89,4 +89,4 @@ grpc_status_code grpc_http2_status_to_grpc_status(int status) {
}
}
-int grpc_status_to_http2_status(grpc_status_code /*status*/) { return 200; }
+int grpc_status_to_http2_status(grpc_status_code /*status*/) { return 200; }
diff --git a/contrib/libs/grpc/src/core/lib/transport/status_metadata.cc b/contrib/libs/grpc/src/core/lib/transport/status_metadata.cc
index c83d6b0d2d..f2e96dbaa5 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/status_metadata.cc
@@ -28,16 +28,16 @@
*/
#define STATUS_OFFSET 1
-static void destroy_status(void* /*ignored*/) {}
+static void destroy_status(void* /*ignored*/) {}
grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md) {
- if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_0)) {
+ if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_0)) {
return GRPC_STATUS_OK;
}
- if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_1)) {
+ if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_1)) {
return GRPC_STATUS_CANCELLED;
}
- if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_2)) {
+ if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_2)) {
return GRPC_STATUS_UNKNOWN;
}
void* user_data = grpc_mdelem_get_user_data(md, destroy_status);
@@ -52,10 +52,10 @@ grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md) {
md, destroy_status, (void*)static_cast<intptr_t>(status + STATUS_OFFSET));
return static_cast<grpc_status_code>(status);
}
-
-grpc_mdelem grpc_get_reffed_status_elem_slowpath(int status_code) {
- char tmp[GPR_LTOA_MIN_BUFSIZE];
- gpr_ltoa(status_code, tmp);
- return grpc_mdelem_from_slices(GRPC_MDSTR_GRPC_STATUS,
- grpc_core::UnmanagedMemorySlice(tmp));
-}
+
+grpc_mdelem grpc_get_reffed_status_elem_slowpath(int status_code) {
+ char tmp[GPR_LTOA_MIN_BUFSIZE];
+ gpr_ltoa(status_code, tmp);
+ return grpc_mdelem_from_slices(GRPC_MDSTR_GRPC_STATUS,
+ grpc_core::UnmanagedMemorySlice(tmp));
+}
diff --git a/contrib/libs/grpc/src/core/lib/transport/status_metadata.h b/contrib/libs/grpc/src/core/lib/transport/status_metadata.h
index 24022c0cf5..2f4be18ef0 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/transport/status_metadata.h
@@ -24,25 +24,25 @@
#include <grpc/status.h>
#include "src/core/lib/transport/metadata.h"
-#include "src/core/lib/transport/static_metadata.h"
+#include "src/core/lib/transport/static_metadata.h"
grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md);
-/** Get a grpc_mdelem of grpc-status: X where X is the numeric value of
- status_code.
-
- The returned elem is owned by the caller. */
-grpc_mdelem grpc_get_reffed_status_elem_slowpath(int status_code);
-inline grpc_mdelem grpc_get_reffed_status_elem(int status_code) {
- switch (status_code) {
- case 0:
- return GRPC_MDELEM_GRPC_STATUS_0;
- case 1:
- return GRPC_MDELEM_GRPC_STATUS_1;
- case 2:
- return GRPC_MDELEM_GRPC_STATUS_2;
- }
- return grpc_get_reffed_status_elem_slowpath(status_code);
-}
-
+/** Get a grpc_mdelem of grpc-status: X where X is the numeric value of
+ status_code.
+
+ The returned elem is owned by the caller. */
+grpc_mdelem grpc_get_reffed_status_elem_slowpath(int status_code);
+inline grpc_mdelem grpc_get_reffed_status_elem(int status_code) {
+ switch (status_code) {
+ case 0:
+ return GRPC_MDELEM_GRPC_STATUS_0;
+ case 1:
+ return GRPC_MDELEM_GRPC_STATUS_1;
+ case 2:
+ return GRPC_MDELEM_GRPC_STATUS_2;
+ }
+ return grpc_get_reffed_status_elem_slowpath(status_code);
+}
+
#endif /* GRPC_CORE_LIB_TRANSPORT_STATUS_METADATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc b/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc
index 26d4b4a426..1c18f45c89 100644
--- a/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc
@@ -44,9 +44,9 @@ static int64_t round_up_to_three_sig_figs(int64_t x) {
/* encode our minimum viable timeout value */
static void enc_tiny(char* buffer) { memcpy(buffer, "1n", 3); }
-/* encode our maximum timeout value, about 1157 days */
-static void enc_huge(char* buffer) { memcpy(buffer, "99999999S", 10); }
-
+/* encode our maximum timeout value, about 1157 days */
+static void enc_huge(char* buffer) { memcpy(buffer, "99999999S", 10); }
+
static void enc_ext(char* buffer, int64_t value, char ext) {
int n = int64_ttoa(value, buffer);
buffer[n] = ext;
@@ -54,7 +54,7 @@ static void enc_ext(char* buffer, int64_t value, char ext) {
}
static void enc_seconds(char* buffer, int64_t sec) {
- sec = round_up_to_three_sig_figs(sec);
+ sec = round_up_to_three_sig_figs(sec);
if (sec % 3600 == 0) {
enc_ext(buffer, sec / 3600, 'H');
} else if (sec % 60 == 0) {
@@ -78,13 +78,13 @@ static void enc_millis(char* buffer, int64_t x) {
}
void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer) {
- const grpc_millis kMaxTimeout = 99999999000;
+ const grpc_millis kMaxTimeout = 99999999000;
if (timeout <= 0) {
enc_tiny(buffer);
} else if (timeout < 1000 * GPR_MS_PER_SEC) {
enc_millis(buffer, timeout);
- } else if (timeout >= kMaxTimeout) {
- enc_huge(buffer);
+ } else if (timeout >= kMaxTimeout) {
+ enc_huge(buffer);
} else {
enc_seconds(buffer,
timeout / GPR_MS_PER_SEC + (timeout % GPR_MS_PER_SEC != 0));
@@ -96,7 +96,7 @@ static int is_all_whitespace(const char* p, const char* end) {
return p == end;
}
-int grpc_http2_decode_timeout(const grpc_slice& text, grpc_millis* timeout) {
+int grpc_http2_decode_timeout(const grpc_slice& text, grpc_millis* timeout) {
grpc_millis x = 0;
const uint8_t* p = GRPC_SLICE_START_PTR(text);
const uint8_t* end = GRPC_SLICE_END_PTR(text);
diff --git a/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h b/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h
index c87ff39d49..755669079e 100644
--- a/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h
+++ b/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h
@@ -27,12 +27,12 @@
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-#define GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE 10
+#define GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE 10
/* Encode/decode timeouts to the GRPC over HTTP/2 format;
- encoding may round up arbitrarily. If the timeout is larger than about 1157
- days, it will be capped and "99999999S" will be sent on the wire. */
+ encoding may round up arbitrarily. If the timeout is larger than about 1157
+ days, it will be capped and "99999999S" will be sent on the wire. */
void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer);
-int grpc_http2_decode_timeout(const grpc_slice& text, grpc_millis* timeout);
+int grpc_http2_decode_timeout(const grpc_slice& text, grpc_millis* timeout);
#endif /* GRPC_CORE_LIB_TRANSPORT_TIMEOUT_ENCODING_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/transport.cc b/contrib/libs/grpc/src/core/lib/transport/transport.cc
index 99a32980aa..8558930cde 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/transport.cc
@@ -29,7 +29,7 @@
#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/slice/slice_internal.h"
@@ -39,39 +39,39 @@
grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount(false,
"stream_refcount");
-void grpc_stream_destroy(grpc_stream_refcount* refcount) {
- if (!grpc_iomgr_is_any_background_poller_thread() &&
- (grpc_core::ExecCtx::Get()->flags() &
- GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP)) {
- /* Ick.
- The thread we're running on MAY be owned (indirectly) by a call-stack.
- If that's the case, destroying the call-stack MAY try to destroy the
- thread, which is a tangled mess that we just don't want to ever have to
- cope with.
- Throw this over to the executor (on a core-owned thread) and process it
- there. */
- grpc_core::Executor::Run(&refcount->destroy, GRPC_ERROR_NONE);
- } else {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, &refcount->destroy,
- GRPC_ERROR_NONE);
+void grpc_stream_destroy(grpc_stream_refcount* refcount) {
+ if (!grpc_iomgr_is_any_background_poller_thread() &&
+ (grpc_core::ExecCtx::Get()->flags() &
+ GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP)) {
+ /* Ick.
+ The thread we're running on MAY be owned (indirectly) by a call-stack.
+ If that's the case, destroying the call-stack MAY try to destroy the
+ thread, which is a tangled mess that we just don't want to ever have to
+ cope with.
+ Throw this over to the executor (on a core-owned thread) and process it
+ there. */
+ grpc_core::Executor::Run(&refcount->destroy, GRPC_ERROR_NONE);
+ } else {
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, &refcount->destroy,
+ GRPC_ERROR_NONE);
}
}
-void slice_stream_destroy(void* arg) {
- grpc_stream_destroy(static_cast<grpc_stream_refcount*>(arg));
+void slice_stream_destroy(void* arg) {
+ grpc_stream_destroy(static_cast<grpc_stream_refcount*>(arg));
}
#define STREAM_REF_FROM_SLICE_REF(p) \
((grpc_stream_refcount*)(((uint8_t*)p) - \
offsetof(grpc_stream_refcount, slice_refcount)))
-grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount,
- void* buffer, size_t length) {
+grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount,
+ void* buffer, size_t length) {
#ifndef NDEBUG
- grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(&refcount->slice_refcount),
- "slice");
+ grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(&refcount->slice_refcount),
+ "slice");
#else
- grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(&refcount->slice_refcount));
+ grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(&refcount->slice_refcount));
#endif
grpc_slice res;
res.refcount = &refcount->slice_refcount;
@@ -81,20 +81,20 @@ grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount,
}
#ifndef NDEBUG
-void grpc_stream_ref_init(grpc_stream_refcount* refcount, int /*initial_refs*/,
+void grpc_stream_ref_init(grpc_stream_refcount* refcount, int /*initial_refs*/,
grpc_iomgr_cb_func cb, void* cb_arg,
const char* object_type) {
refcount->object_type = object_type;
#else
-void grpc_stream_ref_init(grpc_stream_refcount* refcount, int /*initial_refs*/,
+void grpc_stream_ref_init(grpc_stream_refcount* refcount, int /*initial_refs*/,
grpc_iomgr_cb_func cb, void* cb_arg) {
#endif
GRPC_CLOSURE_INIT(&refcount->destroy, cb, cb_arg, grpc_schedule_on_exec_ctx);
-
- new (&refcount->refs) grpc_core::RefCount(1, &grpc_trace_stream_refcount);
- new (&refcount->slice_refcount) grpc_slice_refcount(
- grpc_slice_refcount::Type::REGULAR, &refcount->refs, slice_stream_destroy,
- refcount, &refcount->slice_refcount);
+
+ new (&refcount->refs) grpc_core::RefCount(1, &grpc_trace_stream_refcount);
+ new (&refcount->slice_refcount) grpc_slice_refcount(
+ grpc_slice_refcount::Type::REGULAR, &refcount->refs, slice_stream_destroy,
+ refcount, &refcount->slice_refcount);
}
static void move64(uint64_t* from, uint64_t* to) {
@@ -125,8 +125,8 @@ void grpc_transport_destroy(grpc_transport* transport) {
int grpc_transport_init_stream(grpc_transport* transport, grpc_stream* stream,
grpc_stream_refcount* refcount,
- const void* server_data,
- grpc_core::Arena* arena) {
+ const void* server_data,
+ grpc_core::Arena* arena) {
return transport->vtable->init_stream(transport, stream, refcount,
server_data, arena);
}
@@ -176,7 +176,7 @@ grpc_endpoint* grpc_transport_get_endpoint(grpc_transport* transport) {
// it's grpc_transport_stream_op_batch_finish_with_failure
void grpc_transport_stream_op_batch_finish_with_failure(
grpc_transport_stream_op_batch* batch, grpc_error* error,
- grpc_core::CallCombiner* call_combiner) {
+ grpc_core::CallCombiner* call_combiner) {
if (batch->send_message) {
batch->payload->send_message.send_message.reset();
}
@@ -208,24 +208,24 @@ void grpc_transport_stream_op_batch_finish_with_failure(
GRPC_ERROR_UNREF(error);
}
-struct made_transport_op {
+struct made_transport_op {
grpc_closure outer_on_complete;
- grpc_closure* inner_on_complete = nullptr;
+ grpc_closure* inner_on_complete = nullptr;
grpc_transport_op op;
- made_transport_op() {
- memset(&outer_on_complete, 0, sizeof(outer_on_complete));
- }
-};
+ made_transport_op() {
+ memset(&outer_on_complete, 0, sizeof(outer_on_complete));
+ }
+};
static void destroy_made_transport_op(void* arg, grpc_error* error) {
made_transport_op* op = static_cast<made_transport_op*>(arg);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->inner_on_complete,
- GRPC_ERROR_REF(error));
- delete op;
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->inner_on_complete,
+ GRPC_ERROR_REF(error));
+ delete op;
}
grpc_transport_op* grpc_make_transport_op(grpc_closure* on_complete) {
- made_transport_op* op = new made_transport_op();
+ made_transport_op* op = new made_transport_op();
GRPC_CLOSURE_INIT(&op->outer_on_complete, destroy_made_transport_op, op,
grpc_schedule_on_exec_ctx);
op->inner_on_complete = on_complete;
@@ -243,7 +243,7 @@ static void destroy_made_transport_stream_op(void* arg, grpc_error* error) {
made_transport_stream_op* op = static_cast<made_transport_stream_op*>(arg);
grpc_closure* c = op->inner_on_complete;
gpr_free(op);
- grpc_core::Closure::Run(DEBUG_LOCATION, c, GRPC_ERROR_REF(error));
+ grpc_core::Closure::Run(DEBUG_LOCATION, c, GRPC_ERROR_REF(error));
}
grpc_transport_stream_op_batch* grpc_make_transport_stream_op(
diff --git a/contrib/libs/grpc/src/core/lib/transport/transport.h b/contrib/libs/grpc/src/core/lib/transport/transport.h
index 2404455f9f..95ad72e6bb 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport.h
+++ b/contrib/libs/grpc/src/core/lib/transport/transport.h
@@ -24,16 +24,16 @@
#include <stddef.h>
#include "src/core/lib/channel/context.h"
-#include "src/core/lib/gprpp/arena.h"
-#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/gprpp/arena.h"
+#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_set.h"
-#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/transport/byte_stream.h"
-#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/metadata_batch.h"
/* Minimum and maximum protocol accepted versions. */
@@ -54,7 +54,7 @@ typedef struct grpc_stream grpc_stream;
extern grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount;
typedef struct grpc_stream_refcount {
- grpc_core::RefCount refs;
+ grpc_core::RefCount refs;
grpc_closure destroy;
#ifndef NDEBUG
const char* object_type;
@@ -72,48 +72,48 @@ void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs,
void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs,
grpc_iomgr_cb_func cb, void* cb_arg);
#define GRPC_STREAM_REF_INIT(rc, ir, cb, cb_arg, objtype) \
- do { \
- grpc_stream_ref_init(rc, ir, cb, cb_arg); \
- (void)(objtype); \
- } while (0)
-#endif
-
-#ifndef NDEBUG
-inline void grpc_stream_ref(grpc_stream_refcount* refcount,
- const char* reason) {
- if (grpc_trace_stream_refcount.enabled()) {
- gpr_log(GPR_DEBUG, "%s %p:%p REF %s", refcount->object_type, refcount,
- refcount->destroy.cb_arg, reason);
- }
- refcount->refs.RefNonZero(DEBUG_LOCATION, reason);
-}
-#else
-inline void grpc_stream_ref(grpc_stream_refcount* refcount) {
- refcount->refs.RefNonZero();
-}
-#endif
-
-void grpc_stream_destroy(grpc_stream_refcount* refcount);
-
-#ifndef NDEBUG
-inline void grpc_stream_unref(grpc_stream_refcount* refcount,
- const char* reason) {
- if (grpc_trace_stream_refcount.enabled()) {
- gpr_log(GPR_DEBUG, "%s %p:%p UNREF %s", refcount->object_type, refcount,
- refcount->destroy.cb_arg, reason);
- }
- if (GPR_UNLIKELY(refcount->refs.Unref(DEBUG_LOCATION, reason))) {
- grpc_stream_destroy(refcount);
- }
-}
-#else
-inline void grpc_stream_unref(grpc_stream_refcount* refcount) {
- if (GPR_UNLIKELY(refcount->refs.Unref())) {
- grpc_stream_destroy(refcount);
- }
-}
+ do { \
+ grpc_stream_ref_init(rc, ir, cb, cb_arg); \
+ (void)(objtype); \
+ } while (0)
#endif
+#ifndef NDEBUG
+inline void grpc_stream_ref(grpc_stream_refcount* refcount,
+ const char* reason) {
+ if (grpc_trace_stream_refcount.enabled()) {
+ gpr_log(GPR_DEBUG, "%s %p:%p REF %s", refcount->object_type, refcount,
+ refcount->destroy.cb_arg, reason);
+ }
+ refcount->refs.RefNonZero(DEBUG_LOCATION, reason);
+}
+#else
+inline void grpc_stream_ref(grpc_stream_refcount* refcount) {
+ refcount->refs.RefNonZero();
+}
+#endif
+
+void grpc_stream_destroy(grpc_stream_refcount* refcount);
+
+#ifndef NDEBUG
+inline void grpc_stream_unref(grpc_stream_refcount* refcount,
+ const char* reason) {
+ if (grpc_trace_stream_refcount.enabled()) {
+ gpr_log(GPR_DEBUG, "%s %p:%p UNREF %s", refcount->object_type, refcount,
+ refcount->destroy.cb_arg, reason);
+ }
+ if (GPR_UNLIKELY(refcount->refs.Unref(DEBUG_LOCATION, reason))) {
+ grpc_stream_destroy(refcount);
+ }
+}
+#else
+inline void grpc_stream_unref(grpc_stream_refcount* refcount) {
+ if (GPR_UNLIKELY(refcount->refs.Unref())) {
+ grpc_stream_destroy(refcount);
+ }
+}
+#endif
+
/* Wrap a buffer that is owned by some stream object into a slice that shares
the same refcount */
grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount,
@@ -149,11 +149,11 @@ void grpc_transport_move_stats(grpc_transport_stream_stats* from,
// currently handling the batch). Once a filter or transport passes control
// of the batch to the next handler, it cannot depend on the contents of
// this struct anymore, because the next handler may reuse it.
-struct grpc_handler_private_op_data {
- void* extra_arg = nullptr;
+struct grpc_handler_private_op_data {
+ void* extra_arg = nullptr;
grpc_closure closure;
- grpc_handler_private_op_data() { memset(&closure, 0, sizeof(closure)); }
-};
+ grpc_handler_private_op_data() { memset(&closure, 0, sizeof(closure)); }
+};
typedef struct grpc_transport_stream_op_batch_payload
grpc_transport_stream_op_batch_payload;
@@ -256,18 +256,18 @@ struct grpc_transport_stream_op_batch_payload {
// The batch's on_complete will not be called until after the byte
// stream is orphaned.
grpc_core::OrphanablePtr<grpc_core::ByteStream> send_message;
- // Set by the transport if the stream has been closed for writes. If this
- // is set and send message op is present, we set the operation to be a
- // failure without sending a cancel OP down the stack. This is so that the
- // status of the call does not get overwritten by the Cancel OP, which would
- // be especially problematic if we had received a valid status from the
- // server.
- // For send_initial_metadata, it is fine for the status to be overwritten
- // because at that point, the client will not have received a status.
- // For send_trailing_metadata, we might overwrite the status if we have
- // non-zero metadata to send. This is fine because the API does not allow
- // the client to send trailing metadata.
- bool stream_write_closed = false;
+ // Set by the transport if the stream has been closed for writes. If this
+ // is set and send message op is present, we set the operation to be a
+ // failure without sending a cancel OP down the stack. This is so that the
+ // status of the call does not get overwritten by the Cancel OP, which would
+ // be especially problematic if we had received a valid status from the
+ // server.
+ // For send_initial_metadata, it is fine for the status to be overwritten
+ // because at that point, the client will not have received a status.
+ // For send_trailing_metadata, we might overwrite the status if we have
+ // non-zero metadata to send. This is fine because the API does not allow
+ // the client to send trailing metadata.
+ bool stream_write_closed = false;
} send_message;
struct {
@@ -302,7 +302,7 @@ struct grpc_transport_stream_op_batch_payload {
struct {
grpc_metadata_batch* recv_trailing_metadata = nullptr;
grpc_transport_stream_stats* collect_stats = nullptr;
- /** Should be enqueued when trailing metadata is ready to be processed. */
+ /** Should be enqueued when trailing metadata is ready to be processed. */
grpc_closure* recv_trailing_metadata_ready = nullptr;
} recv_trailing_metadata;
@@ -329,43 +329,43 @@ struct grpc_transport_stream_op_batch_payload {
/** Transport op: a set of operations to perform on a transport as a whole */
typedef struct grpc_transport_op {
/** Called when processing of this op is done. */
- grpc_closure* on_consumed = nullptr;
+ grpc_closure* on_consumed = nullptr;
/** connectivity monitoring - set connectivity_state to NULL to unsubscribe */
- grpc_core::OrphanablePtr<grpc_core::ConnectivityStateWatcherInterface>
- start_connectivity_watch;
- grpc_connectivity_state start_connectivity_watch_state = GRPC_CHANNEL_IDLE;
- grpc_core::ConnectivityStateWatcherInterface* stop_connectivity_watch =
- nullptr;
+ grpc_core::OrphanablePtr<grpc_core::ConnectivityStateWatcherInterface>
+ start_connectivity_watch;
+ grpc_connectivity_state start_connectivity_watch_state = GRPC_CHANNEL_IDLE;
+ grpc_core::ConnectivityStateWatcherInterface* stop_connectivity_watch =
+ nullptr;
/** should the transport be disconnected
* Error contract: the transport that gets this op must cause
* disconnect_with_error to be unref'ed after processing it */
- grpc_error* disconnect_with_error = nullptr;
+ grpc_error* disconnect_with_error = nullptr;
/** what should the goaway contain?
* Error contract: the transport that gets this op must cause
* goaway_error to be unref'ed after processing it */
- grpc_error* goaway_error = nullptr;
+ grpc_error* goaway_error = nullptr;
/** set the callback for accepting new streams;
this is a permanent callback, unlike the other one-shot closures.
If true, the callback is set to set_accept_stream_fn, with its
user_data argument set to set_accept_stream_user_data */
- bool set_accept_stream = false;
+ bool set_accept_stream = false;
void (*set_accept_stream_fn)(void* user_data, grpc_transport* transport,
- const void* server_data) = nullptr;
- void* set_accept_stream_user_data = nullptr;
+ const void* server_data) = nullptr;
+ void* set_accept_stream_user_data = nullptr;
/** add this transport to a pollset */
- grpc_pollset* bind_pollset = nullptr;
+ grpc_pollset* bind_pollset = nullptr;
/** add this transport to a pollset_set */
- grpc_pollset_set* bind_pollset_set = nullptr;
+ grpc_pollset_set* bind_pollset_set = nullptr;
/** send a ping, if either on_initiate or on_ack is not NULL */
struct {
/** Ping may be delayed by the transport, on_initiate callback will be
called when the ping is actually being sent. */
- grpc_closure* on_initiate = nullptr;
+ grpc_closure* on_initiate = nullptr;
/** Called when the ping ack is received */
- grpc_closure* on_ack = nullptr;
+ grpc_closure* on_ack = nullptr;
} send_ping;
// If true, will reset the channel's connection backoff.
- bool reset_connect_backoff = false;
+ bool reset_connect_backoff = false;
/***************************************************************************
* remaining fields are initialized and used at the discretion of the
@@ -390,8 +390,8 @@ size_t grpc_transport_stream_size(grpc_transport* transport);
supplied from the accept_stream callback function */
int grpc_transport_init_stream(grpc_transport* transport, grpc_stream* stream,
grpc_stream_refcount* refcount,
- const void* server_data,
- grpc_core::Arena* arena);
+ const void* server_data,
+ grpc_core::Arena* arena);
void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream,
grpc_polling_entity* pollent);
@@ -412,7 +412,7 @@ void grpc_transport_destroy_stream(grpc_transport* transport,
void grpc_transport_stream_op_batch_finish_with_failure(
grpc_transport_stream_op_batch* op, grpc_error* error,
- grpc_core::CallCombiner* call_combiner);
+ grpc_core::CallCombiner* call_combiner);
TString grpc_transport_stream_op_batch_string(
grpc_transport_stream_op_batch* op);
diff --git a/contrib/libs/grpc/src/core/lib/transport/transport_impl.h b/contrib/libs/grpc/src/core/lib/transport/transport_impl.h
index 526cc1b1ba..e51549a46e 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport_impl.h
+++ b/contrib/libs/grpc/src/core/lib/transport/transport_impl.h
@@ -34,7 +34,7 @@ typedef struct grpc_transport_vtable {
/* implementation of grpc_transport_init_stream */
int (*init_stream)(grpc_transport* self, grpc_stream* stream,
grpc_stream_refcount* refcount, const void* server_data,
- grpc_core::Arena* arena);
+ grpc_core::Arena* arena);
/* implementation of grpc_transport_set_pollset */
void (*set_pollset)(grpc_transport* self, grpc_stream* stream,
diff --git a/contrib/libs/grpc/src/core/lib/transport/transport_op_string.cc b/contrib/libs/grpc/src/core/lib/transport/transport_op_string.cc
index b26ee0a4fd..c259903a39 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport_op_string.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/transport_op_string.cc
@@ -118,18 +118,18 @@ TString grpc_transport_stream_op_batch_string(
TString grpc_transport_op_string(grpc_transport_op* op) {
std::vector<TString> out;
- if (op->start_connectivity_watch != nullptr) {
+ if (op->start_connectivity_watch != nullptr) {
out.push_back(y_absl::StrFormat(
" START_CONNECTIVITY_WATCH:watcher=%p:from=%s",
- op->start_connectivity_watch.get(),
+ op->start_connectivity_watch.get(),
grpc_core::ConnectivityStateName(op->start_connectivity_watch_state)));
}
- if (op->stop_connectivity_watch != nullptr) {
+ if (op->stop_connectivity_watch != nullptr) {
out.push_back(y_absl::StrFormat(" STOP_CONNECTIVITY_WATCH:watcher=%p",
op->stop_connectivity_watch));
- }
-
+ }
+
if (op->disconnect_with_error != GRPC_ERROR_NONE) {
out.push_back(y_absl::StrCat(" DISCONNECT:",
grpc_error_string(op->disconnect_with_error)));
diff --git a/contrib/libs/grpc/src/core/lib/ya.make b/contrib/libs/grpc/src/core/lib/ya.make
index 93f59abe37..8476f12ae6 100644
--- a/contrib/libs/grpc/src/core/lib/ya.make
+++ b/contrib/libs/grpc/src/core/lib/ya.make
@@ -1,7 +1,7 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
OWNER(g:cpp-contrib)
LICENSE(Apache-2.0)
@@ -18,62 +18,62 @@ PEERDIR(
contrib/restricted/abseil-cpp-tstring/y_absl/time
)
-ADDINCL(
- GLOBAL contrib/libs/grpc/include
+ADDINCL(
+ GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+)
+
+NO_COMPILER_WARNINGS()
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- gpr/alloc.cc
- gpr/atm.cc
- gpr/cpu_iphone.cc
- gpr/cpu_linux.cc
- gpr/cpu_posix.cc
- gpr/cpu_windows.cc
- gpr/env_linux.cc
- gpr/env_posix.cc
- gpr/env_windows.cc
- gpr/log.cc
- gpr/log_android.cc
- gpr/log_linux.cc
- gpr/log_posix.cc
- gpr/log_windows.cc
- gpr/murmur_hash.cc
- gpr/string.cc
- gpr/string_posix.cc
- gpr/string_util_windows.cc
- gpr/string_windows.cc
- gpr/sync.cc
+ENDIF()
+
+SRCS(
+ gpr/alloc.cc
+ gpr/atm.cc
+ gpr/cpu_iphone.cc
+ gpr/cpu_linux.cc
+ gpr/cpu_posix.cc
+ gpr/cpu_windows.cc
+ gpr/env_linux.cc
+ gpr/env_posix.cc
+ gpr/env_windows.cc
+ gpr/log.cc
+ gpr/log_android.cc
+ gpr/log_linux.cc
+ gpr/log_posix.cc
+ gpr/log_windows.cc
+ gpr/murmur_hash.cc
+ gpr/string.cc
+ gpr/string_posix.cc
+ gpr/string_util_windows.cc
+ gpr/string_windows.cc
+ gpr/sync.cc
gpr/sync_abseil.cc
- gpr/sync_posix.cc
- gpr/sync_windows.cc
- gpr/time.cc
- gpr/time_posix.cc
- gpr/time_precise.cc
- gpr/time_windows.cc
- gpr/tls_pthread.cc
- gpr/tmpfile_msys.cc
- gpr/tmpfile_posix.cc
- gpr/tmpfile_windows.cc
- gpr/wrap_memcpy.cc
- gprpp/arena.cc
- gprpp/fork.cc
- gprpp/global_config_env.cc
- gprpp/host_port.cc
- gprpp/mpscq.cc
- gprpp/thd_posix.cc
- gprpp/thd_windows.cc
- profiling/basic_timers.cc
- profiling/stap_timers.cc
-)
-
-END()
+ gpr/sync_posix.cc
+ gpr/sync_windows.cc
+ gpr/time.cc
+ gpr/time_posix.cc
+ gpr/time_precise.cc
+ gpr/time_windows.cc
+ gpr/tls_pthread.cc
+ gpr/tmpfile_msys.cc
+ gpr/tmpfile_posix.cc
+ gpr/tmpfile_windows.cc
+ gpr/wrap_memcpy.cc
+ gprpp/arena.cc
+ gprpp/fork.cc
+ gprpp/global_config_env.cc
+ gprpp/host_port.cc
+ gprpp/mpscq.cc
+ gprpp/thd_posix.cc
+ gprpp/thd_windows.cc
+ profiling/basic_timers.cc
+ profiling/stap_timers.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/src/core/plugin_registry/grpc_plugin_registry.cc b/contrib/libs/grpc/src/core/plugin_registry/grpc_plugin_registry.cc
index e048760c7f..34bcb18451 100644
--- a/contrib/libs/grpc/src/core/plugin_registry/grpc_plugin_registry.cc
+++ b/contrib/libs/grpc/src/core/plugin_registry/grpc_plugin_registry.cc
@@ -48,8 +48,8 @@ void grpc_resolver_dns_native_init(void);
void grpc_resolver_dns_native_shutdown(void);
void grpc_resolver_sockaddr_init(void);
void grpc_resolver_sockaddr_shutdown(void);
-void grpc_client_idle_filter_init(void);
-void grpc_client_idle_filter_shutdown(void);
+void grpc_client_idle_filter_init(void);
+void grpc_client_idle_filter_shutdown(void);
void grpc_max_age_filter_init(void);
void grpc_max_age_filter_shutdown(void);
void grpc_message_size_filter_init(void);
@@ -103,14 +103,14 @@ void grpc_register_built_in_plugins(void) {
grpc_lb_policy_pick_first_shutdown);
grpc_register_plugin(grpc_lb_policy_round_robin_init,
grpc_lb_policy_round_robin_shutdown);
- grpc_register_plugin(grpc_resolver_dns_ares_init,
- grpc_resolver_dns_ares_shutdown);
+ grpc_register_plugin(grpc_resolver_dns_ares_init,
+ grpc_resolver_dns_ares_shutdown);
grpc_register_plugin(grpc_resolver_dns_native_init,
grpc_resolver_dns_native_shutdown);
grpc_register_plugin(grpc_resolver_sockaddr_init,
grpc_resolver_sockaddr_shutdown);
- grpc_register_plugin(grpc_client_idle_filter_init,
- grpc_client_idle_filter_shutdown);
+ grpc_register_plugin(grpc_client_idle_filter_init,
+ grpc_client_idle_filter_shutdown);
grpc_register_plugin(grpc_max_age_filter_init,
grpc_max_age_filter_shutdown);
grpc_register_plugin(grpc_message_size_filter_init,
diff --git a/contrib/libs/grpc/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc b/contrib/libs/grpc/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc
index fd9bf9c14d..fdc0d0d3be 100644
--- a/contrib/libs/grpc/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc
+++ b/contrib/libs/grpc/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc
@@ -48,8 +48,8 @@ void grpc_lb_policy_pick_first_init(void);
void grpc_lb_policy_pick_first_shutdown(void);
void grpc_lb_policy_round_robin_init(void);
void grpc_lb_policy_round_robin_shutdown(void);
-void grpc_client_idle_filter_init(void);
-void grpc_client_idle_filter_shutdown(void);
+void grpc_client_idle_filter_init(void);
+void grpc_client_idle_filter_shutdown(void);
void grpc_max_age_filter_init(void);
void grpc_max_age_filter_shutdown(void);
void grpc_message_size_filter_init(void);
@@ -72,8 +72,8 @@ void grpc_register_built_in_plugins(void) {
grpc_client_channel_shutdown);
grpc_register_plugin(grpc_inproc_plugin_init,
grpc_inproc_plugin_shutdown);
- grpc_register_plugin(grpc_resolver_dns_ares_init,
- grpc_resolver_dns_ares_shutdown);
+ grpc_register_plugin(grpc_resolver_dns_ares_init,
+ grpc_resolver_dns_ares_shutdown);
grpc_register_plugin(grpc_resolver_dns_native_init,
grpc_resolver_dns_native_shutdown);
grpc_register_plugin(grpc_resolver_sockaddr_init,
@@ -90,8 +90,8 @@ void grpc_register_built_in_plugins(void) {
grpc_lb_policy_pick_first_shutdown);
grpc_register_plugin(grpc_lb_policy_round_robin_init,
grpc_lb_policy_round_robin_shutdown);
- grpc_register_plugin(grpc_client_idle_filter_init,
- grpc_client_idle_filter_shutdown);
+ grpc_register_plugin(grpc_client_idle_filter_init,
+ grpc_client_idle_filter_shutdown);
grpc_register_plugin(grpc_max_age_filter_init,
grpc_max_age_filter_shutdown);
grpc_register_plugin(grpc_message_size_filter_init,
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc
index a5b7003231..8eb0806181 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc
@@ -33,7 +33,7 @@ static void maybe_copy_error_msg(const char* src, char** dst) {
/* Perform input santity check. */
static grpc_status_code unseal_check(alts_crypter* c, const unsigned char* data,
- size_t /*data_allocated_size*/,
+ size_t /*data_allocated_size*/,
size_t data_size, size_t* output_size,
char** error_details) {
/* Do common input sanity check. */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc
index e2f04f7310..47358022f8 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc
@@ -18,8 +18,8 @@
#include <grpc/support/port_platform.h>
-#include <list>
-
+#include <list>
+
#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
#include "upb/upb.hpp"
@@ -28,7 +28,7 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel.h"
@@ -44,18 +44,18 @@ struct alts_handshaker_client {
const alts_handshaker_client_vtable* vtable;
};
-struct recv_message_result {
- tsi_result status;
- const unsigned char* bytes_to_send;
- size_t bytes_to_send_size;
- tsi_handshaker_result* result;
-};
-
+struct recv_message_result {
+ tsi_result status;
+ const unsigned char* bytes_to_send;
+ size_t bytes_to_send_size;
+ tsi_handshaker_result* result;
+};
+
typedef struct alts_grpc_handshaker_client {
alts_handshaker_client base;
- /* One ref is held by the entity that created this handshaker_client, and
- * another ref is held by the pending RECEIVE_STATUS_ON_CLIENT op. */
- gpr_refcount refs;
+ /* One ref is held by the entity that created this handshaker_client, and
+ * another ref is held by the pending RECEIVE_STATUS_ON_CLIENT op. */
+ gpr_refcount refs;
alts_tsi_handshaker* handshaker;
grpc_call* call;
/* A pointer to a function handling the interaction with handshaker service.
@@ -65,7 +65,7 @@ typedef struct alts_grpc_handshaker_client {
* case. */
alts_grpc_caller grpc_caller;
/* A gRPC closure to be scheduled when the response from handshaker service
- * is received. It will be initialized with the injected grpc RPC callback. */
+ * is received. It will be initialized with the injected grpc RPC callback. */
grpc_closure on_handshaker_service_resp_recv;
/* Buffers containing information to be sent (or received) to (or from) the
* handshaker service. */
@@ -92,18 +92,18 @@ typedef struct alts_grpc_handshaker_client {
/* a buffer containing data to be sent to the grpc client or server's peer. */
unsigned char* buffer;
size_t buffer_size;
- /** callback for receiving handshake call status */
- grpc_closure on_status_received;
- /** gRPC status code of handshake call */
- grpc_status_code handshake_status_code;
- /** gRPC status details of handshake call */
- grpc_slice handshake_status_details;
- /* mu synchronizes all fields below including their internal fields. */
- gpr_mu mu;
- /* indicates if the handshaker call's RECV_STATUS_ON_CLIENT op is done. */
- bool receive_status_finished;
- /* if non-null, contains arguments to complete a TSI next callback. */
- recv_message_result* pending_recv_message_result;
+ /** callback for receiving handshake call status */
+ grpc_closure on_status_received;
+ /** gRPC status code of handshake call */
+ grpc_status_code handshake_status_code;
+ /** gRPC status details of handshake call */
+ grpc_slice handshake_status_details;
+ /* mu synchronizes all fields below including their internal fields. */
+ gpr_mu mu;
+ /* indicates if the handshaker call's RECV_STATUS_ON_CLIENT op is done. */
+ bool receive_status_finished;
+ /* if non-null, contains arguments to complete a TSI next callback. */
+ recv_message_result* pending_recv_message_result;
/* Maximum frame size used by frame protector. */
size_t max_frame_size;
} alts_grpc_handshaker_client;
@@ -115,83 +115,83 @@ static void handshaker_client_send_buffer_destroy(
client->send_buffer = nullptr;
}
-static bool is_handshake_finished_properly(grpc_gcp_HandshakerResp* resp) {
+static bool is_handshake_finished_properly(grpc_gcp_HandshakerResp* resp) {
GPR_ASSERT(resp != nullptr);
- if (grpc_gcp_HandshakerResp_result(resp)) {
+ if (grpc_gcp_HandshakerResp_result(resp)) {
return true;
}
return false;
}
-static void alts_grpc_handshaker_client_unref(
- alts_grpc_handshaker_client* client) {
- if (gpr_unref(&client->refs)) {
- if (client->base.vtable != nullptr &&
- client->base.vtable->destruct != nullptr) {
- client->base.vtable->destruct(&client->base);
- }
- grpc_byte_buffer_destroy(client->send_buffer);
- grpc_byte_buffer_destroy(client->recv_buffer);
- client->send_buffer = nullptr;
- client->recv_buffer = nullptr;
- grpc_metadata_array_destroy(&client->recv_initial_metadata);
- grpc_slice_unref_internal(client->recv_bytes);
- grpc_slice_unref_internal(client->target_name);
- grpc_alts_credentials_options_destroy(client->options);
- gpr_free(client->buffer);
- grpc_slice_unref_internal(client->handshake_status_details);
- gpr_mu_destroy(&client->mu);
- gpr_free(client);
- }
-}
-
-static void maybe_complete_tsi_next(
- alts_grpc_handshaker_client* client, bool receive_status_finished,
- recv_message_result* pending_recv_message_result) {
- recv_message_result* r;
- {
- grpc_core::MutexLock lock(&client->mu);
- client->receive_status_finished |= receive_status_finished;
- if (pending_recv_message_result != nullptr) {
- GPR_ASSERT(client->pending_recv_message_result == nullptr);
- client->pending_recv_message_result = pending_recv_message_result;
- }
- if (client->pending_recv_message_result == nullptr) {
- return;
- }
- const bool have_final_result =
- client->pending_recv_message_result->result != nullptr ||
- client->pending_recv_message_result->status != TSI_OK;
- if (have_final_result && !client->receive_status_finished) {
- // If we've received the final message from the handshake
- // server, or we're about to invoke the TSI next callback
- // with a status other than TSI_OK (which terminates the
- // handshake), then first wait for the RECV_STATUS op to complete.
- return;
- }
- r = client->pending_recv_message_result;
- client->pending_recv_message_result = nullptr;
- }
- client->cb(r->status, client->user_data, r->bytes_to_send,
- r->bytes_to_send_size, r->result);
- gpr_free(r);
-}
-
-static void handle_response_done(alts_grpc_handshaker_client* client,
- tsi_result status,
- const unsigned char* bytes_to_send,
- size_t bytes_to_send_size,
- tsi_handshaker_result* result) {
- recv_message_result* p =
- static_cast<recv_message_result*>(gpr_zalloc(sizeof(*p)));
- p->status = status;
- p->bytes_to_send = bytes_to_send;
- p->bytes_to_send_size = bytes_to_send_size;
- p->result = result;
- maybe_complete_tsi_next(client, false /* receive_status_finished */,
- p /* pending_recv_message_result */);
-}
-
+static void alts_grpc_handshaker_client_unref(
+ alts_grpc_handshaker_client* client) {
+ if (gpr_unref(&client->refs)) {
+ if (client->base.vtable != nullptr &&
+ client->base.vtable->destruct != nullptr) {
+ client->base.vtable->destruct(&client->base);
+ }
+ grpc_byte_buffer_destroy(client->send_buffer);
+ grpc_byte_buffer_destroy(client->recv_buffer);
+ client->send_buffer = nullptr;
+ client->recv_buffer = nullptr;
+ grpc_metadata_array_destroy(&client->recv_initial_metadata);
+ grpc_slice_unref_internal(client->recv_bytes);
+ grpc_slice_unref_internal(client->target_name);
+ grpc_alts_credentials_options_destroy(client->options);
+ gpr_free(client->buffer);
+ grpc_slice_unref_internal(client->handshake_status_details);
+ gpr_mu_destroy(&client->mu);
+ gpr_free(client);
+ }
+}
+
+static void maybe_complete_tsi_next(
+ alts_grpc_handshaker_client* client, bool receive_status_finished,
+ recv_message_result* pending_recv_message_result) {
+ recv_message_result* r;
+ {
+ grpc_core::MutexLock lock(&client->mu);
+ client->receive_status_finished |= receive_status_finished;
+ if (pending_recv_message_result != nullptr) {
+ GPR_ASSERT(client->pending_recv_message_result == nullptr);
+ client->pending_recv_message_result = pending_recv_message_result;
+ }
+ if (client->pending_recv_message_result == nullptr) {
+ return;
+ }
+ const bool have_final_result =
+ client->pending_recv_message_result->result != nullptr ||
+ client->pending_recv_message_result->status != TSI_OK;
+ if (have_final_result && !client->receive_status_finished) {
+ // If we've received the final message from the handshake
+ // server, or we're about to invoke the TSI next callback
+ // with a status other than TSI_OK (which terminates the
+ // handshake), then first wait for the RECV_STATUS op to complete.
+ return;
+ }
+ r = client->pending_recv_message_result;
+ client->pending_recv_message_result = nullptr;
+ }
+ client->cb(r->status, client->user_data, r->bytes_to_send,
+ r->bytes_to_send_size, r->result);
+ gpr_free(r);
+}
+
+static void handle_response_done(alts_grpc_handshaker_client* client,
+ tsi_result status,
+ const unsigned char* bytes_to_send,
+ size_t bytes_to_send_size,
+ tsi_handshaker_result* result) {
+ recv_message_result* p =
+ static_cast<recv_message_result*>(gpr_zalloc(sizeof(*p)));
+ p->status = status;
+ p->bytes_to_send = bytes_to_send;
+ p->bytes_to_send_size = bytes_to_send_size;
+ p->result = result;
+ maybe_complete_tsi_next(client, false /* receive_status_finished */,
+ p /* pending_recv_message_result */);
+}
+
void alts_handshaker_client_handle_response(alts_handshaker_client* c,
bool is_ok) {
GPR_ASSERT(c != nullptr);
@@ -201,64 +201,64 @@ void alts_handshaker_client_handle_response(alts_handshaker_client* c,
grpc_status_code status = client->status;
alts_tsi_handshaker* handshaker = client->handshaker;
/* Invalid input check. */
- if (client->cb == nullptr) {
+ if (client->cb == nullptr) {
gpr_log(GPR_ERROR,
- "client->cb is nullptr in alts_tsi_handshaker_handle_response()");
+ "client->cb is nullptr in alts_tsi_handshaker_handle_response()");
return;
}
if (handshaker == nullptr) {
gpr_log(GPR_ERROR,
"handshaker is nullptr in alts_tsi_handshaker_handle_response()");
- handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr);
+ handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr);
return;
}
/* TSI handshake has been shutdown. */
if (alts_tsi_handshaker_has_shutdown(handshaker)) {
gpr_log(GPR_ERROR, "TSI handshake shutdown");
- handle_response_done(client, TSI_HANDSHAKE_SHUTDOWN, nullptr, 0, nullptr);
+ handle_response_done(client, TSI_HANDSHAKE_SHUTDOWN, nullptr, 0, nullptr);
return;
}
/* Failed grpc call check. */
if (!is_ok || status != GRPC_STATUS_OK) {
gpr_log(GPR_ERROR, "grpc call made to handshaker service failed");
- handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr);
+ handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr);
return;
}
if (recv_buffer == nullptr) {
gpr_log(GPR_ERROR,
"recv_buffer is nullptr in alts_tsi_handshaker_handle_response()");
- handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr);
+ handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr);
return;
}
- upb::Arena arena;
- grpc_gcp_HandshakerResp* resp =
- alts_tsi_utils_deserialize_response(recv_buffer, arena.ptr());
+ upb::Arena arena;
+ grpc_gcp_HandshakerResp* resp =
+ alts_tsi_utils_deserialize_response(recv_buffer, arena.ptr());
grpc_byte_buffer_destroy(client->recv_buffer);
client->recv_buffer = nullptr;
/* Invalid handshaker response check. */
if (resp == nullptr) {
gpr_log(GPR_ERROR, "alts_tsi_utils_deserialize_response() failed");
- handle_response_done(client, TSI_DATA_CORRUPTED, nullptr, 0, nullptr);
- return;
- }
- const grpc_gcp_HandshakerStatus* resp_status =
- grpc_gcp_HandshakerResp_status(resp);
- if (resp_status == nullptr) {
- gpr_log(GPR_ERROR, "No status in HandshakerResp");
- handle_response_done(client, TSI_DATA_CORRUPTED, nullptr, 0, nullptr);
+ handle_response_done(client, TSI_DATA_CORRUPTED, nullptr, 0, nullptr);
return;
}
- upb_strview out_frames = grpc_gcp_HandshakerResp_out_frames(resp);
+ const grpc_gcp_HandshakerStatus* resp_status =
+ grpc_gcp_HandshakerResp_status(resp);
+ if (resp_status == nullptr) {
+ gpr_log(GPR_ERROR, "No status in HandshakerResp");
+ handle_response_done(client, TSI_DATA_CORRUPTED, nullptr, 0, nullptr);
+ return;
+ }
+ upb_strview out_frames = grpc_gcp_HandshakerResp_out_frames(resp);
unsigned char* bytes_to_send = nullptr;
size_t bytes_to_send_size = 0;
- if (out_frames.size > 0) {
- bytes_to_send_size = out_frames.size;
+ if (out_frames.size > 0) {
+ bytes_to_send_size = out_frames.size;
while (bytes_to_send_size > client->buffer_size) {
client->buffer_size *= 2;
client->buffer = static_cast<unsigned char*>(
gpr_realloc(client->buffer, client->buffer_size));
}
- memcpy(client->buffer, out_frames.data, bytes_to_send_size);
+ memcpy(client->buffer, out_frames.data, bytes_to_send_size);
bytes_to_send = client->buffer;
}
tsi_handshaker_result* result = nullptr;
@@ -270,53 +270,53 @@ void alts_handshaker_client_handle_response(alts_handshaker_client* c,
handle_response_done(client, status, nullptr, 0, nullptr);
return;
}
- alts_tsi_handshaker_result_set_unused_bytes(
- result, &client->recv_bytes,
- grpc_gcp_HandshakerResp_bytes_consumed(resp));
+ alts_tsi_handshaker_result_set_unused_bytes(
+ result, &client->recv_bytes,
+ grpc_gcp_HandshakerResp_bytes_consumed(resp));
}
- grpc_status_code code = static_cast<grpc_status_code>(
- grpc_gcp_HandshakerStatus_code(resp_status));
+ grpc_status_code code = static_cast<grpc_status_code>(
+ grpc_gcp_HandshakerStatus_code(resp_status));
if (code != GRPC_STATUS_OK) {
- upb_strview details = grpc_gcp_HandshakerStatus_details(resp_status);
- if (details.size > 0) {
- char* error_details = (char*)gpr_zalloc(details.size + 1);
- memcpy(error_details, details.data, details.size);
+ upb_strview details = grpc_gcp_HandshakerStatus_details(resp_status);
+ if (details.size > 0) {
+ char* error_details = (char*)gpr_zalloc(details.size + 1);
+ memcpy(error_details, details.data, details.size);
gpr_log(GPR_ERROR, "Error from handshaker service:%s", error_details);
gpr_free(error_details);
}
}
- // TODO(apolcyn): consider short ciruiting handle_response_done and
- // invoking the TSI callback directly if we aren't done yet, if
- // handle_response_done's allocation per message received causes
- // a performance issue.
- handle_response_done(client, alts_tsi_utils_convert_to_tsi_result(code),
- bytes_to_send, bytes_to_send_size, result);
+ // TODO(apolcyn): consider short ciruiting handle_response_done and
+ // invoking the TSI callback directly if we aren't done yet, if
+ // handle_response_done's allocation per message received causes
+ // a performance issue.
+ handle_response_done(client, alts_tsi_utils_convert_to_tsi_result(code),
+ bytes_to_send, bytes_to_send_size, result);
}
-static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client,
- bool is_start) {
- GPR_ASSERT(client != nullptr);
+static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client,
+ bool is_start) {
+ GPR_ASSERT(client != nullptr);
grpc_op ops[kHandshakerClientOpNum];
memset(ops, 0, sizeof(ops));
grpc_op* op = ops;
if (is_start) {
- op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
- op->data.recv_status_on_client.trailing_metadata = nullptr;
- op->data.recv_status_on_client.status = &client->handshake_status_code;
- op->data.recv_status_on_client.status_details =
- &client->handshake_status_details;
- op->flags = 0;
- op->reserved = nullptr;
- op++;
- GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
- gpr_ref(&client->refs);
- grpc_call_error call_error =
- client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops),
- &client->on_status_received);
- // TODO(apolcyn): return the error here instead, as done for other ops?
- GPR_ASSERT(call_error == GRPC_CALL_OK);
- memset(ops, 0, sizeof(ops));
- op = ops;
+ op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
+ op->data.recv_status_on_client.trailing_metadata = nullptr;
+ op->data.recv_status_on_client.status = &client->handshake_status_code;
+ op->data.recv_status_on_client.status_details =
+ &client->handshake_status_details;
+ op->flags = 0;
+ op->reserved = nullptr;
+ op++;
+ GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
+ gpr_ref(&client->refs);
+ grpc_call_error call_error =
+ client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops),
+ &client->on_status_received);
+ // TODO(apolcyn): return the error here instead, as done for other ops?
+ GPR_ASSERT(call_error == GRPC_CALL_OK);
+ memset(ops, 0, sizeof(ops));
+ op = ops;
op->op = GRPC_OP_SEND_INITIAL_METADATA;
op->data.send_initial_metadata.count = 0;
op++;
@@ -345,180 +345,180 @@ static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client,
return TSI_OK;
}
-// TODO(apolcyn): remove this global queue when we can safely rely
-// on a MAX_CONCURRENT_STREAMS setting in the ALTS handshake server to
-// limit the number of concurrent handshakes.
-namespace {
-
-class HandshakeQueue {
- public:
- explicit HandshakeQueue(size_t max_outstanding_handshakes)
- : max_outstanding_handshakes_(max_outstanding_handshakes) {}
-
- void RequestHandshake(alts_grpc_handshaker_client* client) {
- {
- grpc_core::MutexLock lock(&mu_);
- if (outstanding_handshakes_ == max_outstanding_handshakes_) {
- // Max number already running, add to queue.
- queued_handshakes_.push_back(client);
- return;
- }
- // Start the handshake immediately.
- ++outstanding_handshakes_;
- }
- continue_make_grpc_call(client, true /* is_start */);
- }
-
- void HandshakeDone() {
- alts_grpc_handshaker_client* client = nullptr;
- {
- grpc_core::MutexLock lock(&mu_);
- if (queued_handshakes_.empty()) {
- // Nothing more in queue. Decrement count and return immediately.
- --outstanding_handshakes_;
- return;
- }
- // Remove next entry from queue and start the handshake.
- client = queued_handshakes_.front();
- queued_handshakes_.pop_front();
- }
- continue_make_grpc_call(client, true /* is_start */);
- }
-
- private:
- grpc_core::Mutex mu_;
- std::list<alts_grpc_handshaker_client*> queued_handshakes_;
- size_t outstanding_handshakes_ = 0;
- const size_t max_outstanding_handshakes_;
-};
-
-gpr_once g_queued_handshakes_init = GPR_ONCE_INIT;
-/* Using separate queues for client and server handshakes is a
- * hack that's mainly intended to satisfy the alts_concurrent_connectivity_test,
- * which runs many concurrent handshakes where both endpoints
- * are in the same process; this situation is problematic with a
- * single queue because we have a high chance of using up all outstanding
- * slots in the queue, such that there aren't any
- * mutual client/server handshakes outstanding at the same time and
- * able to make progress. */
-HandshakeQueue* g_client_handshake_queue;
-HandshakeQueue* g_server_handshake_queue;
-
-void DoHandshakeQueuesInit(void) {
- const size_t per_queue_max_outstanding_handshakes = 40;
- g_client_handshake_queue =
- new HandshakeQueue(per_queue_max_outstanding_handshakes);
- g_server_handshake_queue =
- new HandshakeQueue(per_queue_max_outstanding_handshakes);
-}
-
-void RequestHandshake(alts_grpc_handshaker_client* client, bool is_client) {
- gpr_once_init(&g_queued_handshakes_init, DoHandshakeQueuesInit);
- HandshakeQueue* queue =
- is_client ? g_client_handshake_queue : g_server_handshake_queue;
- queue->RequestHandshake(client);
-}
-
-void HandshakeDone(bool is_client) {
- HandshakeQueue* queue =
- is_client ? g_client_handshake_queue : g_server_handshake_queue;
- queue->HandshakeDone();
-}
-
-}; // namespace
-
-/**
- * Populate grpc operation data with the fields of ALTS handshaker client and
- * make a grpc call.
- */
-static tsi_result make_grpc_call(alts_handshaker_client* c, bool is_start) {
- GPR_ASSERT(c != nullptr);
- alts_grpc_handshaker_client* client =
- reinterpret_cast<alts_grpc_handshaker_client*>(c);
- if (is_start) {
- RequestHandshake(client, client->is_client);
- return TSI_OK;
- } else {
- return continue_make_grpc_call(client, is_start);
- }
-}
-
-static void on_status_received(void* arg, grpc_error* error) {
- alts_grpc_handshaker_client* client =
- static_cast<alts_grpc_handshaker_client*>(arg);
- if (client->handshake_status_code != GRPC_STATUS_OK) {
- // TODO(apolcyn): consider overriding the handshake result's
- // status from the final ALTS message with the status here.
- char* status_details =
- grpc_slice_to_c_string(client->handshake_status_details);
- gpr_log(GPR_INFO,
- "alts_grpc_handshaker_client:%p on_status_received "
- "status:%d details:|%s| error:|%s|",
- client, client->handshake_status_code, status_details,
- grpc_error_string(error));
- gpr_free(status_details);
- }
- maybe_complete_tsi_next(client, true /* receive_status_finished */,
- nullptr /* pending_recv_message_result */);
- HandshakeDone(client->is_client);
- alts_grpc_handshaker_client_unref(client);
-}
-
-/* Serializes a grpc_gcp_HandshakerReq message into a buffer and returns newly
- * grpc_byte_buffer holding it. */
-static grpc_byte_buffer* get_serialized_handshaker_req(
- grpc_gcp_HandshakerReq* req, upb_arena* arena) {
- size_t buf_length;
- char* buf = grpc_gcp_HandshakerReq_serialize(req, arena, &buf_length);
- if (buf == nullptr) {
- return nullptr;
- }
- grpc_slice slice = grpc_slice_from_copied_buffer(buf, buf_length);
- grpc_byte_buffer* byte_buffer = grpc_raw_byte_buffer_create(&slice, 1);
- grpc_slice_unref_internal(slice);
- return byte_buffer;
-}
-
+// TODO(apolcyn): remove this global queue when we can safely rely
+// on a MAX_CONCURRENT_STREAMS setting in the ALTS handshake server to
+// limit the number of concurrent handshakes.
+namespace {
+
+class HandshakeQueue {
+ public:
+ explicit HandshakeQueue(size_t max_outstanding_handshakes)
+ : max_outstanding_handshakes_(max_outstanding_handshakes) {}
+
+ void RequestHandshake(alts_grpc_handshaker_client* client) {
+ {
+ grpc_core::MutexLock lock(&mu_);
+ if (outstanding_handshakes_ == max_outstanding_handshakes_) {
+ // Max number already running, add to queue.
+ queued_handshakes_.push_back(client);
+ return;
+ }
+ // Start the handshake immediately.
+ ++outstanding_handshakes_;
+ }
+ continue_make_grpc_call(client, true /* is_start */);
+ }
+
+ void HandshakeDone() {
+ alts_grpc_handshaker_client* client = nullptr;
+ {
+ grpc_core::MutexLock lock(&mu_);
+ if (queued_handshakes_.empty()) {
+ // Nothing more in queue. Decrement count and return immediately.
+ --outstanding_handshakes_;
+ return;
+ }
+ // Remove next entry from queue and start the handshake.
+ client = queued_handshakes_.front();
+ queued_handshakes_.pop_front();
+ }
+ continue_make_grpc_call(client, true /* is_start */);
+ }
+
+ private:
+ grpc_core::Mutex mu_;
+ std::list<alts_grpc_handshaker_client*> queued_handshakes_;
+ size_t outstanding_handshakes_ = 0;
+ const size_t max_outstanding_handshakes_;
+};
+
+gpr_once g_queued_handshakes_init = GPR_ONCE_INIT;
+/* Using separate queues for client and server handshakes is a
+ * hack that's mainly intended to satisfy the alts_concurrent_connectivity_test,
+ * which runs many concurrent handshakes where both endpoints
+ * are in the same process; this situation is problematic with a
+ * single queue because we have a high chance of using up all outstanding
+ * slots in the queue, such that there aren't any
+ * mutual client/server handshakes outstanding at the same time and
+ * able to make progress. */
+HandshakeQueue* g_client_handshake_queue;
+HandshakeQueue* g_server_handshake_queue;
+
+void DoHandshakeQueuesInit(void) {
+ const size_t per_queue_max_outstanding_handshakes = 40;
+ g_client_handshake_queue =
+ new HandshakeQueue(per_queue_max_outstanding_handshakes);
+ g_server_handshake_queue =
+ new HandshakeQueue(per_queue_max_outstanding_handshakes);
+}
+
+void RequestHandshake(alts_grpc_handshaker_client* client, bool is_client) {
+ gpr_once_init(&g_queued_handshakes_init, DoHandshakeQueuesInit);
+ HandshakeQueue* queue =
+ is_client ? g_client_handshake_queue : g_server_handshake_queue;
+ queue->RequestHandshake(client);
+}
+
+void HandshakeDone(bool is_client) {
+ HandshakeQueue* queue =
+ is_client ? g_client_handshake_queue : g_server_handshake_queue;
+ queue->HandshakeDone();
+}
+
+}; // namespace
+
+/**
+ * Populate grpc operation data with the fields of ALTS handshaker client and
+ * make a grpc call.
+ */
+static tsi_result make_grpc_call(alts_handshaker_client* c, bool is_start) {
+ GPR_ASSERT(c != nullptr);
+ alts_grpc_handshaker_client* client =
+ reinterpret_cast<alts_grpc_handshaker_client*>(c);
+ if (is_start) {
+ RequestHandshake(client, client->is_client);
+ return TSI_OK;
+ } else {
+ return continue_make_grpc_call(client, is_start);
+ }
+}
+
+static void on_status_received(void* arg, grpc_error* error) {
+ alts_grpc_handshaker_client* client =
+ static_cast<alts_grpc_handshaker_client*>(arg);
+ if (client->handshake_status_code != GRPC_STATUS_OK) {
+ // TODO(apolcyn): consider overriding the handshake result's
+ // status from the final ALTS message with the status here.
+ char* status_details =
+ grpc_slice_to_c_string(client->handshake_status_details);
+ gpr_log(GPR_INFO,
+ "alts_grpc_handshaker_client:%p on_status_received "
+ "status:%d details:|%s| error:|%s|",
+ client, client->handshake_status_code, status_details,
+ grpc_error_string(error));
+ gpr_free(status_details);
+ }
+ maybe_complete_tsi_next(client, true /* receive_status_finished */,
+ nullptr /* pending_recv_message_result */);
+ HandshakeDone(client->is_client);
+ alts_grpc_handshaker_client_unref(client);
+}
+
+/* Serializes a grpc_gcp_HandshakerReq message into a buffer and returns newly
+ * grpc_byte_buffer holding it. */
+static grpc_byte_buffer* get_serialized_handshaker_req(
+ grpc_gcp_HandshakerReq* req, upb_arena* arena) {
+ size_t buf_length;
+ char* buf = grpc_gcp_HandshakerReq_serialize(req, arena, &buf_length);
+ if (buf == nullptr) {
+ return nullptr;
+ }
+ grpc_slice slice = grpc_slice_from_copied_buffer(buf, buf_length);
+ grpc_byte_buffer* byte_buffer = grpc_raw_byte_buffer_create(&slice, 1);
+ grpc_slice_unref_internal(slice);
+ return byte_buffer;
+}
+
/* Create and populate a client_start handshaker request, then serialize it. */
static grpc_byte_buffer* get_serialized_start_client(
alts_handshaker_client* c) {
GPR_ASSERT(c != nullptr);
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
- upb::Arena arena;
- grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
- grpc_gcp_StartClientHandshakeReq* start_client =
- grpc_gcp_HandshakerReq_mutable_client_start(req, arena.ptr());
- grpc_gcp_StartClientHandshakeReq_set_handshake_security_protocol(
- start_client, grpc_gcp_ALTS);
- grpc_gcp_StartClientHandshakeReq_add_application_protocols(
- start_client, upb_strview_makez(ALTS_APPLICATION_PROTOCOL), arena.ptr());
- grpc_gcp_StartClientHandshakeReq_add_record_protocols(
- start_client, upb_strview_makez(ALTS_RECORD_PROTOCOL), arena.ptr());
- grpc_gcp_RpcProtocolVersions* client_version =
- grpc_gcp_StartClientHandshakeReq_mutable_rpc_versions(start_client,
- arena.ptr());
- grpc_gcp_RpcProtocolVersions_assign_from_struct(
- client_version, arena.ptr(), &client->options->rpc_versions);
- grpc_gcp_StartClientHandshakeReq_set_target_name(
- start_client,
- upb_strview_make(reinterpret_cast<const char*>(
- GRPC_SLICE_START_PTR(client->target_name)),
- GRPC_SLICE_LENGTH(client->target_name)));
+ upb::Arena arena;
+ grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
+ grpc_gcp_StartClientHandshakeReq* start_client =
+ grpc_gcp_HandshakerReq_mutable_client_start(req, arena.ptr());
+ grpc_gcp_StartClientHandshakeReq_set_handshake_security_protocol(
+ start_client, grpc_gcp_ALTS);
+ grpc_gcp_StartClientHandshakeReq_add_application_protocols(
+ start_client, upb_strview_makez(ALTS_APPLICATION_PROTOCOL), arena.ptr());
+ grpc_gcp_StartClientHandshakeReq_add_record_protocols(
+ start_client, upb_strview_makez(ALTS_RECORD_PROTOCOL), arena.ptr());
+ grpc_gcp_RpcProtocolVersions* client_version =
+ grpc_gcp_StartClientHandshakeReq_mutable_rpc_versions(start_client,
+ arena.ptr());
+ grpc_gcp_RpcProtocolVersions_assign_from_struct(
+ client_version, arena.ptr(), &client->options->rpc_versions);
+ grpc_gcp_StartClientHandshakeReq_set_target_name(
+ start_client,
+ upb_strview_make(reinterpret_cast<const char*>(
+ GRPC_SLICE_START_PTR(client->target_name)),
+ GRPC_SLICE_LENGTH(client->target_name)));
target_service_account* ptr =
(reinterpret_cast<grpc_alts_credentials_client_options*>(client->options))
->target_account_list_head;
while (ptr != nullptr) {
- grpc_gcp_Identity* target_identity =
- grpc_gcp_StartClientHandshakeReq_add_target_identities(start_client,
- arena.ptr());
- grpc_gcp_Identity_set_service_account(target_identity,
- upb_strview_makez(ptr->data));
+ grpc_gcp_Identity* target_identity =
+ grpc_gcp_StartClientHandshakeReq_add_target_identities(start_client,
+ arena.ptr());
+ grpc_gcp_Identity_set_service_account(target_identity,
+ upb_strview_makez(ptr->data));
ptr = ptr->next;
}
grpc_gcp_StartClientHandshakeReq_set_max_frame_size(
start_client, static_cast<uint32_t>(client->max_frame_size));
- return get_serialized_handshaker_req(req, arena.ptr());
+ return get_serialized_handshaker_req(req, arena.ptr());
}
static tsi_result handshaker_client_start_client(alts_handshaker_client* c) {
@@ -549,32 +549,32 @@ static grpc_byte_buffer* get_serialized_start_server(
GPR_ASSERT(bytes_received != nullptr);
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
-
- upb::Arena arena;
- grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
-
- grpc_gcp_StartServerHandshakeReq* start_server =
- grpc_gcp_HandshakerReq_mutable_server_start(req, arena.ptr());
- grpc_gcp_StartServerHandshakeReq_add_application_protocols(
- start_server, upb_strview_makez(ALTS_APPLICATION_PROTOCOL), arena.ptr());
- grpc_gcp_ServerHandshakeParameters* value =
- grpc_gcp_ServerHandshakeParameters_new(arena.ptr());
- grpc_gcp_ServerHandshakeParameters_add_record_protocols(
- value, upb_strview_makez(ALTS_RECORD_PROTOCOL), arena.ptr());
+
+ upb::Arena arena;
+ grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
+
+ grpc_gcp_StartServerHandshakeReq* start_server =
+ grpc_gcp_HandshakerReq_mutable_server_start(req, arena.ptr());
+ grpc_gcp_StartServerHandshakeReq_add_application_protocols(
+ start_server, upb_strview_makez(ALTS_APPLICATION_PROTOCOL), arena.ptr());
+ grpc_gcp_ServerHandshakeParameters* value =
+ grpc_gcp_ServerHandshakeParameters_new(arena.ptr());
+ grpc_gcp_ServerHandshakeParameters_add_record_protocols(
+ value, upb_strview_makez(ALTS_RECORD_PROTOCOL), arena.ptr());
grpc_gcp_StartServerHandshakeReq_handshake_parameters_set(
start_server, grpc_gcp_ALTS, value, arena.ptr());
- grpc_gcp_StartServerHandshakeReq_set_in_bytes(
- start_server, upb_strview_make(reinterpret_cast<const char*>(
- GRPC_SLICE_START_PTR(*bytes_received)),
- GRPC_SLICE_LENGTH(*bytes_received)));
- grpc_gcp_RpcProtocolVersions* server_version =
- grpc_gcp_StartServerHandshakeReq_mutable_rpc_versions(start_server,
- arena.ptr());
- grpc_gcp_RpcProtocolVersions_assign_from_struct(
- server_version, arena.ptr(), &client->options->rpc_versions);
+ grpc_gcp_StartServerHandshakeReq_set_in_bytes(
+ start_server, upb_strview_make(reinterpret_cast<const char*>(
+ GRPC_SLICE_START_PTR(*bytes_received)),
+ GRPC_SLICE_LENGTH(*bytes_received)));
+ grpc_gcp_RpcProtocolVersions* server_version =
+ grpc_gcp_StartServerHandshakeReq_mutable_rpc_versions(start_server,
+ arena.ptr());
+ grpc_gcp_RpcProtocolVersions_assign_from_struct(
+ server_version, arena.ptr(), &client->options->rpc_versions);
grpc_gcp_StartServerHandshakeReq_set_max_frame_size(
start_server, static_cast<uint32_t>(client->max_frame_size));
- return get_serialized_handshaker_req(req, arena.ptr());
+ return get_serialized_handshaker_req(req, arena.ptr());
}
static tsi_result handshaker_client_start_server(alts_handshaker_client* c,
@@ -602,15 +602,15 @@ static tsi_result handshaker_client_start_server(alts_handshaker_client* c,
/* Create and populate a next handshaker request, then serialize it. */
static grpc_byte_buffer* get_serialized_next(grpc_slice* bytes_received) {
GPR_ASSERT(bytes_received != nullptr);
- upb::Arena arena;
- grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
- grpc_gcp_NextHandshakeMessageReq* next =
- grpc_gcp_HandshakerReq_mutable_next(req, arena.ptr());
- grpc_gcp_NextHandshakeMessageReq_set_in_bytes(
- next, upb_strview_make(reinterpret_cast<const char*> GRPC_SLICE_START_PTR(
- *bytes_received),
- GRPC_SLICE_LENGTH(*bytes_received)));
- return get_serialized_handshaker_req(req, arena.ptr());
+ upb::Arena arena;
+ grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr());
+ grpc_gcp_NextHandshakeMessageReq* next =
+ grpc_gcp_HandshakerReq_mutable_next(req, arena.ptr());
+ grpc_gcp_NextHandshakeMessageReq_set_in_bytes(
+ next, upb_strview_make(reinterpret_cast<const char*> GRPC_SLICE_START_PTR(
+ *bytes_received),
+ GRPC_SLICE_LENGTH(*bytes_received)));
+ return get_serialized_handshaker_req(req, arena.ptr());
}
static tsi_result handshaker_client_next(alts_handshaker_client* c,
@@ -622,7 +622,7 @@ static tsi_result handshaker_client_next(alts_handshaker_client* c,
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
grpc_slice_unref_internal(client->recv_bytes);
- client->recv_bytes = grpc_slice_ref_internal(*bytes_received);
+ client->recv_bytes = grpc_slice_ref_internal(*bytes_received);
grpc_byte_buffer* buffer = get_serialized_next(bytes_received);
if (buffer == nullptr) {
gpr_log(GPR_ERROR, "get_serialized_next() failed");
@@ -647,10 +647,10 @@ static void handshaker_client_shutdown(alts_handshaker_client* c) {
}
static void handshaker_call_unref(void* arg, grpc_error* /* error */) {
- grpc_call* call = static_cast<grpc_call*>(arg);
- grpc_call_unref(call);
-}
-
+ grpc_call* call = static_cast<grpc_call*>(arg);
+ grpc_call_unref(call);
+}
+
static void handshaker_client_destruct(alts_handshaker_client* c) {
if (c == nullptr) {
return;
@@ -658,12 +658,12 @@ static void handshaker_client_destruct(alts_handshaker_client* c) {
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
if (client->call != nullptr) {
- // Throw this grpc_call_unref over to the ExecCtx so that
- // we invoke it at the bottom of the call stack and
- // prevent lock inversion problems due to nested ExecCtx flushing.
- // TODO(apolcyn): we could remove this indirection and call
- // grpc_call_unref inline if there was an internal variant of
- // grpc_call_unref that didn't need to flush an ExecCtx.
+ // Throw this grpc_call_unref over to the ExecCtx so that
+ // we invoke it at the bottom of the call stack and
+ // prevent lock inversion problems due to nested ExecCtx flushing.
+ // TODO(apolcyn): we could remove this indirection and call
+ // grpc_call_unref inline if there was an internal variant of
+ // grpc_call_unref that didn't need to flush an ExecCtx.
if (grpc_core::ExecCtx::Get() == nullptr) {
// Unref handshaker call if there is no exec_ctx, e.g., in the case of
// Envoy ALTS transport socket.
@@ -687,7 +687,7 @@ static const alts_handshaker_client_vtable vtable = {
alts_handshaker_client* alts_grpc_handshaker_client_create(
alts_tsi_handshaker* handshaker, grpc_channel* channel,
const char* handshaker_service_url, grpc_pollset_set* interested_parties,
- grpc_alts_credentials_options* options, const grpc_slice& target_name,
+ grpc_alts_credentials_options* options, const grpc_slice& target_name,
grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb,
void* user_data, alts_handshaker_client_vtable* vtable_for_testing,
bool is_client, size_t max_frame_size) {
@@ -697,8 +697,8 @@ alts_handshaker_client* alts_grpc_handshaker_client_create(
}
alts_grpc_handshaker_client* client =
static_cast<alts_grpc_handshaker_client*>(gpr_zalloc(sizeof(*client)));
- gpr_mu_init(&client->mu);
- gpr_ref_init(&client->refs, 1);
+ gpr_mu_init(&client->mu);
+ gpr_ref_init(&client->refs, 1);
client->grpc_caller = grpc_call_start_batch_and_execute;
client->handshaker = handshaker;
client->cb = cb;
@@ -724,10 +724,10 @@ alts_handshaker_client* alts_grpc_handshaker_client_create(
GRPC_MILLIS_INF_FUTURE, nullptr);
client->base.vtable =
vtable_for_testing == nullptr ? &vtable : vtable_for_testing;
- GRPC_CLOSURE_INIT(&client->on_handshaker_service_resp_recv, grpc_cb, client,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&client->on_status_received, on_status_received, client,
- grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&client->on_handshaker_service_resp_recv, grpc_cb, client,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&client->on_status_received, on_status_received, client,
+ grpc_schedule_on_exec_ctx);
grpc_slice_unref_internal(slice);
return &client->base;
}
@@ -772,7 +772,7 @@ void alts_handshaker_client_set_recv_bytes_for_testing(
GPR_ASSERT(c != nullptr);
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
- client->recv_bytes = grpc_slice_ref_internal(*recv_bytes);
+ client->recv_bytes = grpc_slice_ref_internal(*recv_bytes);
}
void alts_handshaker_client_set_fields_for_testing(
@@ -837,27 +837,27 @@ grpc_closure* alts_handshaker_client_get_closure_for_testing(
return &client->on_handshaker_service_resp_recv;
}
-void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c) {
- alts_grpc_handshaker_client* client =
- reinterpret_cast<alts_grpc_handshaker_client*>(c);
- gpr_ref(&client->refs);
-}
-
-void alts_handshaker_client_on_status_received_for_testing(
- alts_handshaker_client* c, grpc_status_code status, grpc_error* error) {
- // We first make sure that the handshake queue has been initialized
- // here because there are tests that use this API that mock out
- // other parts of the alts_handshaker_client in such a way that the
- // code path that would normally ensure that the handshake queue
- // has been initialized isn't taken.
- gpr_once_init(&g_queued_handshakes_init, DoHandshakeQueuesInit);
- alts_grpc_handshaker_client* client =
- reinterpret_cast<alts_grpc_handshaker_client*>(c);
- client->handshake_status_code = status;
- client->handshake_status_details = grpc_empty_slice();
- grpc_core::Closure::Run(DEBUG_LOCATION, &client->on_status_received, error);
-}
-
+void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c) {
+ alts_grpc_handshaker_client* client =
+ reinterpret_cast<alts_grpc_handshaker_client*>(c);
+ gpr_ref(&client->refs);
+}
+
+void alts_handshaker_client_on_status_received_for_testing(
+ alts_handshaker_client* c, grpc_status_code status, grpc_error* error) {
+ // We first make sure that the handshake queue has been initialized
+ // here because there are tests that use this API that mock out
+ // other parts of the alts_handshaker_client in such a way that the
+ // code path that would normally ensure that the handshake queue
+ // has been initialized isn't taken.
+ gpr_once_init(&g_queued_handshakes_init, DoHandshakeQueuesInit);
+ alts_grpc_handshaker_client* client =
+ reinterpret_cast<alts_grpc_handshaker_client*>(c);
+ client->handshake_status_code = status;
+ client->handshake_status_details = grpc_empty_slice();
+ grpc_core::Closure::Run(DEBUG_LOCATION, &client->on_status_received, error);
+}
+
} // namespace internal
} // namespace grpc_core
@@ -904,6 +904,6 @@ void alts_handshaker_client_destroy(alts_handshaker_client* c) {
if (c != nullptr) {
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
- alts_grpc_handshaker_client_unref(client);
+ alts_grpc_handshaker_client_unref(client);
}
}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h
index d8669da01c..b9311d9dc6 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h
@@ -142,7 +142,7 @@ void alts_handshaker_client_destroy(alts_handshaker_client* client);
alts_handshaker_client* alts_grpc_handshaker_client_create(
alts_tsi_handshaker* handshaker, grpc_channel* channel,
const char* handshaker_service_url, grpc_pollset_set* interested_parties,
- grpc_alts_credentials_options* options, const grpc_slice& target_name,
+ grpc_alts_credentials_options* options, const grpc_slice& target_name,
grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb,
void* user_data, alts_handshaker_client_vtable* vtable_for_testing,
bool is_client, size_t max_frame_size);
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc
index 255eda5df3..e08bfb2080 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc
@@ -30,7 +30,7 @@ alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void) {
return &g_alts_resource_dedicated;
}
-static void thread_worker(void* /*arg*/) {
+static void thread_worker(void* /*arg*/) {
while (true) {
grpc_event event =
grpc_completion_queue_next(g_alts_resource_dedicated.cq,
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h
index d8638e7df6..f1d28aab67 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h
@@ -48,7 +48,7 @@ alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void);
/**
* This method destroys the alts_shared_resource_dedicated object
- * shared by all TSI handshakes. The application is responsible for
+ * shared by all TSI handshakes. The application is responsible for
* invoking the API before calling grpc_shutdown().
*/
void grpc_alts_shared_resource_dedicated_shutdown();
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc
index 01ef56157a..044e09c506 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc
@@ -32,11 +32,11 @@
#include <grpc/support/sync.h>
#include <grpc/support/thd_id.h>
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/surface/channel.h"
#include "src/core/tsi/alts/frame_protector/alts_frame_protector.h"
#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
#include "src/core/tsi/alts/handshaker/alts_shared_resource.h"
@@ -55,16 +55,16 @@ struct alts_tsi_handshaker {
grpc_alts_credentials_options* options;
alts_handshaker_client_vtable* client_vtable_for_testing;
grpc_channel* channel;
- bool use_dedicated_cq;
- // mu synchronizes all fields below. Note these are the
- // only fields that can be concurrently accessed (due to
- // potential concurrency of tsi_handshaker_shutdown and
- // tsi_handshaker_next).
- gpr_mu mu;
- alts_handshaker_client* client;
- // shutdown effectively follows base.handshake_shutdown,
- // but is synchronized by the mutex of this object.
- bool shutdown;
+ bool use_dedicated_cq;
+ // mu synchronizes all fields below. Note these are the
+ // only fields that can be concurrently accessed (due to
+ // potential concurrency of tsi_handshaker_shutdown and
+ // tsi_handshaker_next).
+ gpr_mu mu;
+ alts_handshaker_client* client;
+ // shutdown effectively follows base.handshake_shutdown,
+ // but is synchronized by the mutex of this object.
+ bool shutdown;
// Maximum frame size used by frame protector.
size_t max_frame_size;
};
@@ -78,7 +78,7 @@ typedef struct alts_tsi_handshaker_result {
size_t unused_bytes_size;
grpc_slice rpc_versions;
bool is_client;
- grpc_slice serialized_context;
+ grpc_slice serialized_context;
// Peer's maximum frame size.
size_t max_frame_size;
} alts_tsi_handshaker_result;
@@ -122,21 +122,21 @@ static tsi_result handshaker_result_extract_peer(
ok = tsi_construct_string_peer_property(
TSI_ALTS_RPC_VERSIONS,
reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->rpc_versions)),
- GRPC_SLICE_LENGTH(result->rpc_versions), &peer->properties[index]);
- if (ok != TSI_OK) {
- tsi_peer_destruct(peer);
- gpr_log(GPR_ERROR, "Failed to set tsi peer property");
- }
- index++;
- GPR_ASSERT(&peer->properties[index] != nullptr);
- ok = tsi_construct_string_peer_property(
- TSI_ALTS_CONTEXT,
- reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->serialized_context)),
- GRPC_SLICE_LENGTH(result->serialized_context), &peer->properties[index]);
+ GRPC_SLICE_LENGTH(result->rpc_versions), &peer->properties[index]);
if (ok != TSI_OK) {
tsi_peer_destruct(peer);
gpr_log(GPR_ERROR, "Failed to set tsi peer property");
}
+ index++;
+ GPR_ASSERT(&peer->properties[index] != nullptr);
+ ok = tsi_construct_string_peer_property(
+ TSI_ALTS_CONTEXT,
+ reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->serialized_context)),
+ GRPC_SLICE_LENGTH(result->serialized_context), &peer->properties[index]);
+ if (ok != TSI_OK) {
+ tsi_peer_destruct(peer);
+ gpr_log(GPR_ERROR, "Failed to set tsi peer property");
+ }
index++;
GPR_ASSERT(&peer->properties[index] != nullptr);
ok = tsi_construct_string_peer_property_from_cstring(
@@ -241,7 +241,7 @@ static void handshaker_result_destroy(tsi_handshaker_result* self) {
gpr_free(result->key_data);
gpr_free(result->unused_bytes);
grpc_slice_unref_internal(result->rpc_versions);
- grpc_slice_unref_internal(result->serialized_context);
+ grpc_slice_unref_internal(result->serialized_context);
gpr_free(result);
}
@@ -251,89 +251,89 @@ static const tsi_handshaker_result_vtable result_vtable = {
handshaker_result_create_frame_protector,
handshaker_result_get_unused_bytes, handshaker_result_destroy};
-tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
+tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
bool is_client,
tsi_handshaker_result** self) {
if (self == nullptr || resp == nullptr) {
gpr_log(GPR_ERROR, "Invalid arguments to create_handshaker_result()");
return TSI_INVALID_ARGUMENT;
}
- const grpc_gcp_HandshakerResult* hresult =
- grpc_gcp_HandshakerResp_result(resp);
- const grpc_gcp_Identity* identity =
- grpc_gcp_HandshakerResult_peer_identity(hresult);
+ const grpc_gcp_HandshakerResult* hresult =
+ grpc_gcp_HandshakerResp_result(resp);
+ const grpc_gcp_Identity* identity =
+ grpc_gcp_HandshakerResult_peer_identity(hresult);
if (identity == nullptr) {
- gpr_log(GPR_ERROR, "Invalid identity");
- return TSI_FAILED_PRECONDITION;
- }
- upb_strview peer_service_account =
- grpc_gcp_Identity_service_account(identity);
- if (peer_service_account.size == 0) {
- gpr_log(GPR_ERROR, "Invalid peer service account");
+ gpr_log(GPR_ERROR, "Invalid identity");
return TSI_FAILED_PRECONDITION;
}
- upb_strview key_data = grpc_gcp_HandshakerResult_key_data(hresult);
- if (key_data.size < kAltsAes128GcmRekeyKeyLength) {
+ upb_strview peer_service_account =
+ grpc_gcp_Identity_service_account(identity);
+ if (peer_service_account.size == 0) {
+ gpr_log(GPR_ERROR, "Invalid peer service account");
+ return TSI_FAILED_PRECONDITION;
+ }
+ upb_strview key_data = grpc_gcp_HandshakerResult_key_data(hresult);
+ if (key_data.size < kAltsAes128GcmRekeyKeyLength) {
gpr_log(GPR_ERROR, "Bad key length");
return TSI_FAILED_PRECONDITION;
}
- const grpc_gcp_RpcProtocolVersions* peer_rpc_version =
- grpc_gcp_HandshakerResult_peer_rpc_versions(hresult);
- if (peer_rpc_version == nullptr) {
- gpr_log(GPR_ERROR, "Peer does not set RPC protocol versions.");
- return TSI_FAILED_PRECONDITION;
- }
- upb_strview application_protocol =
- grpc_gcp_HandshakerResult_application_protocol(hresult);
- if (application_protocol.size == 0) {
- gpr_log(GPR_ERROR, "Invalid application protocol");
- return TSI_FAILED_PRECONDITION;
- }
- upb_strview record_protocol =
- grpc_gcp_HandshakerResult_record_protocol(hresult);
- if (record_protocol.size == 0) {
- gpr_log(GPR_ERROR, "Invalid record protocol");
- return TSI_FAILED_PRECONDITION;
- }
- const grpc_gcp_Identity* local_identity =
- grpc_gcp_HandshakerResult_local_identity(hresult);
- if (local_identity == nullptr) {
- gpr_log(GPR_ERROR, "Invalid local identity");
- return TSI_FAILED_PRECONDITION;
- }
- upb_strview local_service_account =
- grpc_gcp_Identity_service_account(local_identity);
- // We don't check if local service account is empty here
- // because local identity could be empty in certain situations.
+ const grpc_gcp_RpcProtocolVersions* peer_rpc_version =
+ grpc_gcp_HandshakerResult_peer_rpc_versions(hresult);
+ if (peer_rpc_version == nullptr) {
+ gpr_log(GPR_ERROR, "Peer does not set RPC protocol versions.");
+ return TSI_FAILED_PRECONDITION;
+ }
+ upb_strview application_protocol =
+ grpc_gcp_HandshakerResult_application_protocol(hresult);
+ if (application_protocol.size == 0) {
+ gpr_log(GPR_ERROR, "Invalid application protocol");
+ return TSI_FAILED_PRECONDITION;
+ }
+ upb_strview record_protocol =
+ grpc_gcp_HandshakerResult_record_protocol(hresult);
+ if (record_protocol.size == 0) {
+ gpr_log(GPR_ERROR, "Invalid record protocol");
+ return TSI_FAILED_PRECONDITION;
+ }
+ const grpc_gcp_Identity* local_identity =
+ grpc_gcp_HandshakerResult_local_identity(hresult);
+ if (local_identity == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid local identity");
+ return TSI_FAILED_PRECONDITION;
+ }
+ upb_strview local_service_account =
+ grpc_gcp_Identity_service_account(local_identity);
+ // We don't check if local service account is empty here
+ // because local identity could be empty in certain situations.
alts_tsi_handshaker_result* result =
static_cast<alts_tsi_handshaker_result*>(gpr_zalloc(sizeof(*result)));
result->key_data =
static_cast<char*>(gpr_zalloc(kAltsAes128GcmRekeyKeyLength));
- memcpy(result->key_data, key_data.data, kAltsAes128GcmRekeyKeyLength);
- result->peer_identity =
- static_cast<char*>(gpr_zalloc(peer_service_account.size + 1));
- memcpy(result->peer_identity, peer_service_account.data,
- peer_service_account.size);
+ memcpy(result->key_data, key_data.data, kAltsAes128GcmRekeyKeyLength);
+ result->peer_identity =
+ static_cast<char*>(gpr_zalloc(peer_service_account.size + 1));
+ memcpy(result->peer_identity, peer_service_account.data,
+ peer_service_account.size);
result->max_frame_size = grpc_gcp_HandshakerResult_max_frame_size(hresult);
- upb::Arena rpc_versions_arena;
- bool serialized = grpc_gcp_rpc_protocol_versions_encode(
- peer_rpc_version, rpc_versions_arena.ptr(), &result->rpc_versions);
- if (!serialized) {
- gpr_log(GPR_ERROR, "Failed to serialize peer's RPC protocol versions.");
+ upb::Arena rpc_versions_arena;
+ bool serialized = grpc_gcp_rpc_protocol_versions_encode(
+ peer_rpc_version, rpc_versions_arena.ptr(), &result->rpc_versions);
+ if (!serialized) {
+ gpr_log(GPR_ERROR, "Failed to serialize peer's RPC protocol versions.");
return TSI_FAILED_PRECONDITION;
}
- upb::Arena context_arena;
- grpc_gcp_AltsContext* context = grpc_gcp_AltsContext_new(context_arena.ptr());
- grpc_gcp_AltsContext_set_application_protocol(context, application_protocol);
- grpc_gcp_AltsContext_set_record_protocol(context, record_protocol);
- // ALTS currently only supports the security level of 2,
- // which is "grpc_gcp_INTEGRITY_AND_PRIVACY".
- grpc_gcp_AltsContext_set_security_level(context, 2);
- grpc_gcp_AltsContext_set_peer_service_account(context, peer_service_account);
- grpc_gcp_AltsContext_set_local_service_account(context,
- local_service_account);
- grpc_gcp_AltsContext_set_peer_rpc_versions(
- context, const_cast<grpc_gcp_RpcProtocolVersions*>(peer_rpc_version));
+ upb::Arena context_arena;
+ grpc_gcp_AltsContext* context = grpc_gcp_AltsContext_new(context_arena.ptr());
+ grpc_gcp_AltsContext_set_application_protocol(context, application_protocol);
+ grpc_gcp_AltsContext_set_record_protocol(context, record_protocol);
+ // ALTS currently only supports the security level of 2,
+ // which is "grpc_gcp_INTEGRITY_AND_PRIVACY".
+ grpc_gcp_AltsContext_set_security_level(context, 2);
+ grpc_gcp_AltsContext_set_peer_service_account(context, peer_service_account);
+ grpc_gcp_AltsContext_set_local_service_account(context,
+ local_service_account);
+ grpc_gcp_AltsContext_set_peer_rpc_versions(
+ context, const_cast<grpc_gcp_RpcProtocolVersions*>(peer_rpc_version));
grpc_gcp_Identity* peer_identity = const_cast<grpc_gcp_Identity*>(identity);
if (peer_identity == nullptr) {
gpr_log(GPR_ERROR, "Null peer identity in ALTS context.");
@@ -356,15 +356,15 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
grpc_gcp_Identity_attributes_nextmutable(peer_identity, &iter);
}
}
- size_t serialized_ctx_length;
- char* serialized_ctx = grpc_gcp_AltsContext_serialize(
- context, context_arena.ptr(), &serialized_ctx_length);
- if (serialized_ctx == nullptr) {
- gpr_log(GPR_ERROR, "Failed to serialize peer's ALTS context.");
+ size_t serialized_ctx_length;
+ char* serialized_ctx = grpc_gcp_AltsContext_serialize(
+ context, context_arena.ptr(), &serialized_ctx_length);
+ if (serialized_ctx == nullptr) {
+ gpr_log(GPR_ERROR, "Failed to serialize peer's ALTS context.");
return TSI_FAILED_PRECONDITION;
}
- result->serialized_context =
- grpc_slice_from_copied_buffer(serialized_ctx, serialized_ctx_length);
+ result->serialized_context =
+ grpc_slice_from_copied_buffer(serialized_ctx, serialized_ctx_length);
result->is_client = is_client;
result->base.vtable = &result_vtable;
*self = &result->base;
@@ -378,32 +378,32 @@ static void on_handshaker_service_resp_recv(void* arg, grpc_error* error) {
gpr_log(GPR_ERROR, "ALTS handshaker client is nullptr");
return;
}
- bool success = true;
- if (error != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR,
- "ALTS handshaker on_handshaker_service_resp_recv error: %s",
- grpc_error_string(error));
- success = false;
- }
- alts_handshaker_client_handle_response(client, success);
+ bool success = true;
+ if (error != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR,
+ "ALTS handshaker on_handshaker_service_resp_recv error: %s",
+ grpc_error_string(error));
+ success = false;
+ }
+ alts_handshaker_client_handle_response(client, success);
}
/* gRPC provided callback used when dedicatd CQ and thread are used.
* It serves to safely bring the control back to application. */
static void on_handshaker_service_resp_recv_dedicated(void* arg,
- grpc_error* /*error*/) {
+ grpc_error* /*error*/) {
alts_shared_resource_dedicated* resource =
grpc_alts_get_shared_resource_dedicated();
grpc_cq_end_op(resource->cq, arg, GRPC_ERROR_NONE,
- [](void* /*done_arg*/, grpc_cq_completion* /*storage*/) {},
- nullptr, &resource->storage);
+ [](void* /*done_arg*/, grpc_cq_completion* /*storage*/) {},
+ nullptr, &resource->storage);
}
-/* Returns TSI_OK if and only if no error is encountered. */
-static tsi_result alts_tsi_handshaker_continue_handshaker_next(
- alts_tsi_handshaker* handshaker, const unsigned char* received_bytes,
- size_t received_bytes_size, tsi_handshaker_on_next_done_cb cb,
- void* user_data) {
+/* Returns TSI_OK if and only if no error is encountered. */
+static tsi_result alts_tsi_handshaker_continue_handshaker_next(
+ alts_tsi_handshaker* handshaker, const unsigned char* received_bytes,
+ size_t received_bytes_size, tsi_handshaker_on_next_done_cb cb,
+ void* user_data) {
if (!handshaker->has_created_handshaker_client) {
if (handshaker->channel == nullptr) {
grpc_alts_shared_resource_dedicated_start(
@@ -419,25 +419,25 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next(
handshaker->channel == nullptr
? grpc_alts_get_shared_resource_dedicated()->channel
: handshaker->channel;
- alts_handshaker_client* client = alts_grpc_handshaker_client_create(
+ alts_handshaker_client* client = alts_grpc_handshaker_client_create(
handshaker, channel, handshaker->handshaker_service_url,
handshaker->interested_parties, handshaker->options,
handshaker->target_name, grpc_cb, cb, user_data,
handshaker->client_vtable_for_testing, handshaker->is_client,
handshaker->max_frame_size);
- if (client == nullptr) {
+ if (client == nullptr) {
gpr_log(GPR_ERROR, "Failed to create ALTS handshaker client");
return TSI_FAILED_PRECONDITION;
}
- {
- grpc_core::MutexLock lock(&handshaker->mu);
- GPR_ASSERT(handshaker->client == nullptr);
- handshaker->client = client;
- if (handshaker->shutdown) {
- gpr_log(GPR_ERROR, "TSI handshake shutdown");
- return TSI_HANDSHAKE_SHUTDOWN;
- }
- }
+ {
+ grpc_core::MutexLock lock(&handshaker->mu);
+ GPR_ASSERT(handshaker->client == nullptr);
+ handshaker->client = client;
+ if (handshaker->shutdown) {
+ gpr_log(GPR_ERROR, "TSI handshake shutdown");
+ return TSI_HANDSHAKE_SHUTDOWN;
+ }
+ }
handshaker->has_created_handshaker_client = true;
}
if (handshaker->channel == nullptr &&
@@ -450,101 +450,101 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next(
: grpc_slice_from_copied_buffer(
reinterpret_cast<const char*>(received_bytes),
received_bytes_size);
- tsi_result ok = TSI_OK;
+ tsi_result ok = TSI_OK;
if (!handshaker->has_sent_start_message) {
- handshaker->has_sent_start_message = true;
+ handshaker->has_sent_start_message = true;
ok = handshaker->is_client
? alts_handshaker_client_start_client(handshaker->client)
: alts_handshaker_client_start_server(handshaker->client, &slice);
- // It's unsafe for the current thread to access any state in handshaker
- // at this point, since alts_handshaker_client_start_client/server
- // have potentially just started an op batch on the handshake call.
- // The completion callback for that batch is unsynchronized and so
- // can invoke the TSI next API callback from any thread, at which point
- // there is nothing taking ownership of this handshaker to prevent it
- // from being destroyed.
+ // It's unsafe for the current thread to access any state in handshaker
+ // at this point, since alts_handshaker_client_start_client/server
+ // have potentially just started an op batch on the handshake call.
+ // The completion callback for that batch is unsynchronized and so
+ // can invoke the TSI next API callback from any thread, at which point
+ // there is nothing taking ownership of this handshaker to prevent it
+ // from being destroyed.
} else {
ok = alts_handshaker_client_next(handshaker->client, &slice);
}
grpc_slice_unref_internal(slice);
- return ok;
-}
-
-struct alts_tsi_handshaker_continue_handshaker_next_args {
- alts_tsi_handshaker* handshaker;
- std::unique_ptr<unsigned char> received_bytes;
- size_t received_bytes_size;
- tsi_handshaker_on_next_done_cb cb;
- void* user_data;
- grpc_closure closure;
-};
-
-static void alts_tsi_handshaker_create_channel(void* arg,
+ return ok;
+}
+
+struct alts_tsi_handshaker_continue_handshaker_next_args {
+ alts_tsi_handshaker* handshaker;
+ std::unique_ptr<unsigned char> received_bytes;
+ size_t received_bytes_size;
+ tsi_handshaker_on_next_done_cb cb;
+ void* user_data;
+ grpc_closure closure;
+};
+
+static void alts_tsi_handshaker_create_channel(void* arg,
grpc_error* /* unused_error */) {
- alts_tsi_handshaker_continue_handshaker_next_args* next_args =
- static_cast<alts_tsi_handshaker_continue_handshaker_next_args*>(arg);
- alts_tsi_handshaker* handshaker = next_args->handshaker;
- GPR_ASSERT(handshaker->channel == nullptr);
- handshaker->channel = grpc_insecure_channel_create(
- next_args->handshaker->handshaker_service_url, nullptr, nullptr);
- tsi_result continue_next_result =
- alts_tsi_handshaker_continue_handshaker_next(
- handshaker, next_args->received_bytes.get(),
- next_args->received_bytes_size, next_args->cb, next_args->user_data);
- if (continue_next_result != TSI_OK) {
- next_args->cb(continue_next_result, next_args->user_data, nullptr, 0,
- nullptr);
- }
- delete next_args;
-}
-
-static tsi_result handshaker_next(
- tsi_handshaker* self, const unsigned char* received_bytes,
- size_t received_bytes_size, const unsigned char** /*bytes_to_send*/,
- size_t* /*bytes_to_send_size*/, tsi_handshaker_result** /*result*/,
- tsi_handshaker_on_next_done_cb cb, void* user_data) {
- if (self == nullptr || cb == nullptr) {
- gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()");
- return TSI_INVALID_ARGUMENT;
- }
- alts_tsi_handshaker* handshaker =
- reinterpret_cast<alts_tsi_handshaker*>(self);
- {
- grpc_core::MutexLock lock(&handshaker->mu);
- if (handshaker->shutdown) {
- gpr_log(GPR_ERROR, "TSI handshake shutdown");
- return TSI_HANDSHAKE_SHUTDOWN;
- }
- }
- if (handshaker->channel == nullptr && !handshaker->use_dedicated_cq) {
- alts_tsi_handshaker_continue_handshaker_next_args* args =
- new alts_tsi_handshaker_continue_handshaker_next_args();
- args->handshaker = handshaker;
- args->received_bytes = nullptr;
- args->received_bytes_size = received_bytes_size;
- if (received_bytes_size > 0) {
- args->received_bytes = std::unique_ptr<unsigned char>(
- static_cast<unsigned char*>(gpr_zalloc(received_bytes_size)));
- memcpy(args->received_bytes.get(), received_bytes, received_bytes_size);
- }
- args->cb = cb;
- args->user_data = user_data;
- GRPC_CLOSURE_INIT(&args->closure, alts_tsi_handshaker_create_channel, args,
- grpc_schedule_on_exec_ctx);
- // We continue this handshaker_next call at the bottom of the ExecCtx just
- // so that we can invoke grpc_channel_create at the bottom of the call
- // stack. Doing so avoids potential lock cycles between g_init_mu and other
- // mutexes within core that might be held on the current call stack
- // (note that g_init_mu gets acquired during channel creation).
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, &args->closure, GRPC_ERROR_NONE);
- } else {
- tsi_result ok = alts_tsi_handshaker_continue_handshaker_next(
- handshaker, received_bytes, received_bytes_size, cb, user_data);
- if (ok != TSI_OK) {
- gpr_log(GPR_ERROR, "Failed to schedule ALTS handshaker requests");
- return ok;
- }
- }
+ alts_tsi_handshaker_continue_handshaker_next_args* next_args =
+ static_cast<alts_tsi_handshaker_continue_handshaker_next_args*>(arg);
+ alts_tsi_handshaker* handshaker = next_args->handshaker;
+ GPR_ASSERT(handshaker->channel == nullptr);
+ handshaker->channel = grpc_insecure_channel_create(
+ next_args->handshaker->handshaker_service_url, nullptr, nullptr);
+ tsi_result continue_next_result =
+ alts_tsi_handshaker_continue_handshaker_next(
+ handshaker, next_args->received_bytes.get(),
+ next_args->received_bytes_size, next_args->cb, next_args->user_data);
+ if (continue_next_result != TSI_OK) {
+ next_args->cb(continue_next_result, next_args->user_data, nullptr, 0,
+ nullptr);
+ }
+ delete next_args;
+}
+
+static tsi_result handshaker_next(
+ tsi_handshaker* self, const unsigned char* received_bytes,
+ size_t received_bytes_size, const unsigned char** /*bytes_to_send*/,
+ size_t* /*bytes_to_send_size*/, tsi_handshaker_result** /*result*/,
+ tsi_handshaker_on_next_done_cb cb, void* user_data) {
+ if (self == nullptr || cb == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_tsi_handshaker* handshaker =
+ reinterpret_cast<alts_tsi_handshaker*>(self);
+ {
+ grpc_core::MutexLock lock(&handshaker->mu);
+ if (handshaker->shutdown) {
+ gpr_log(GPR_ERROR, "TSI handshake shutdown");
+ return TSI_HANDSHAKE_SHUTDOWN;
+ }
+ }
+ if (handshaker->channel == nullptr && !handshaker->use_dedicated_cq) {
+ alts_tsi_handshaker_continue_handshaker_next_args* args =
+ new alts_tsi_handshaker_continue_handshaker_next_args();
+ args->handshaker = handshaker;
+ args->received_bytes = nullptr;
+ args->received_bytes_size = received_bytes_size;
+ if (received_bytes_size > 0) {
+ args->received_bytes = std::unique_ptr<unsigned char>(
+ static_cast<unsigned char*>(gpr_zalloc(received_bytes_size)));
+ memcpy(args->received_bytes.get(), received_bytes, received_bytes_size);
+ }
+ args->cb = cb;
+ args->user_data = user_data;
+ GRPC_CLOSURE_INIT(&args->closure, alts_tsi_handshaker_create_channel, args,
+ grpc_schedule_on_exec_ctx);
+ // We continue this handshaker_next call at the bottom of the ExecCtx just
+ // so that we can invoke grpc_channel_create at the bottom of the call
+ // stack. Doing so avoids potential lock cycles between g_init_mu and other
+ // mutexes within core that might be held on the current call stack
+ // (note that g_init_mu gets acquired during channel creation).
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, &args->closure, GRPC_ERROR_NONE);
+ } else {
+ tsi_result ok = alts_tsi_handshaker_continue_handshaker_next(
+ handshaker, received_bytes, received_bytes_size, cb, user_data);
+ if (ok != TSI_OK) {
+ gpr_log(GPR_ERROR, "Failed to schedule ALTS handshaker requests");
+ return ok;
+ }
+ }
return TSI_ASYNC;
}
@@ -566,16 +566,16 @@ static tsi_result handshaker_next_dedicated(
static void handshaker_shutdown(tsi_handshaker* self) {
GPR_ASSERT(self != nullptr);
- alts_tsi_handshaker* handshaker =
- reinterpret_cast<alts_tsi_handshaker*>(self);
- grpc_core::MutexLock lock(&handshaker->mu);
- if (handshaker->shutdown) {
+ alts_tsi_handshaker* handshaker =
+ reinterpret_cast<alts_tsi_handshaker*>(self);
+ grpc_core::MutexLock lock(&handshaker->mu);
+ if (handshaker->shutdown) {
return;
}
- if (handshaker->client != nullptr) {
- alts_handshaker_client_shutdown(handshaker->client);
- }
- handshaker->shutdown = true;
+ if (handshaker->client != nullptr) {
+ alts_handshaker_client_shutdown(handshaker->client);
+ }
+ handshaker->shutdown = true;
}
static void handshaker_destroy(tsi_handshaker* self) {
@@ -588,10 +588,10 @@ static void handshaker_destroy(tsi_handshaker* self) {
grpc_slice_unref_internal(handshaker->target_name);
grpc_alts_credentials_options_destroy(handshaker->options);
if (handshaker->channel != nullptr) {
- grpc_channel_destroy_internal(handshaker->channel);
+ grpc_channel_destroy_internal(handshaker->channel);
}
gpr_free(handshaker->handshaker_service_url);
- gpr_mu_destroy(&handshaker->mu);
+ gpr_mu_destroy(&handshaker->mu);
gpr_free(handshaker);
}
@@ -613,8 +613,8 @@ static const tsi_handshaker_vtable handshaker_vtable_dedicated = {
bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker) {
GPR_ASSERT(handshaker != nullptr);
- grpc_core::MutexLock lock(&handshaker->mu);
- return handshaker->shutdown;
+ grpc_core::MutexLock lock(&handshaker->mu);
+ return handshaker->shutdown;
}
tsi_result alts_tsi_handshaker_create(
@@ -629,8 +629,8 @@ tsi_result alts_tsi_handshaker_create(
}
alts_tsi_handshaker* handshaker =
static_cast<alts_tsi_handshaker*>(gpr_zalloc(sizeof(*handshaker)));
- gpr_mu_init(&handshaker->mu);
- handshaker->use_dedicated_cq = interested_parties == nullptr;
+ gpr_mu_init(&handshaker->mu);
+ handshaker->use_dedicated_cq = interested_parties == nullptr;
handshaker->client = nullptr;
handshaker->is_client = is_client;
handshaker->has_sent_start_message = false;
@@ -644,9 +644,9 @@ tsi_result alts_tsi_handshaker_create(
handshaker->max_frame_size = user_specified_max_frame_size != 0
? user_specified_max_frame_size
: kTsiAltsMaxFrameSize;
- handshaker->base.vtable = handshaker->use_dedicated_cq
- ? &handshaker_vtable_dedicated
- : &handshaker_vtable;
+ handshaker->base.vtable = handshaker->use_dedicated_cq
+ ? &handshaker_vtable_dedicated
+ : &handshaker_vtable;
*self = &handshaker->base;
return TSI_OK;
}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h
index e1ae985a84..de67e95f4f 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h
@@ -28,13 +28,13 @@
#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
#include "src/core/tsi/transport_security.h"
#include "src/core/tsi/transport_security_interface.h"
-#include "src/proto/grpc/gcp/altscontext.upb.h"
-#include "src/proto/grpc/gcp/handshaker.upb.h"
+#include "src/proto/grpc/gcp/altscontext.upb.h"
+#include "src/proto/grpc/gcp/handshaker.upb.h"
-#define TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY "service_account"
+#define TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY "service_account"
#define TSI_ALTS_CERTIFICATE_TYPE "ALTS"
#define TSI_ALTS_RPC_VERSIONS "rpc_versions"
-#define TSI_ALTS_CONTEXT "alts_context"
+#define TSI_ALTS_CONTEXT "alts_context"
const size_t kTsiAltsNumOfPeerProperties = 5;
@@ -80,7 +80,7 @@ tsi_result alts_tsi_handshaker_create(
* client or not.
* - result: address of ALTS TSI handshaker result instance.
*/
-tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
+tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
bool is_client,
tsi_handshaker_result** result);
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h
index cb99fdcce0..1ce3e1de10 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h
@@ -77,11 +77,11 @@ void alts_handshaker_client_set_cb_for_testing(
grpc_closure* alts_handshaker_client_get_closure_for_testing(
alts_handshaker_client* client);
-void alts_handshaker_client_on_status_received_for_testing(
- alts_handshaker_client* client, grpc_status_code status, grpc_error* error);
-
-void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c);
-
+void alts_handshaker_client_on_status_received_for_testing(
+ alts_handshaker_client* client, grpc_status_code status, grpc_error* error);
+
+void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c);
+
} // namespace internal
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc
index f80498db99..6422eb9ee5 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc
@@ -41,22 +41,22 @@ tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code) {
}
}
-grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response(
- grpc_byte_buffer* resp_buffer, upb_arena* arena) {
+grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response(
+ grpc_byte_buffer* resp_buffer, upb_arena* arena) {
GPR_ASSERT(resp_buffer != nullptr);
- GPR_ASSERT(arena != nullptr);
+ GPR_ASSERT(arena != nullptr);
grpc_byte_buffer_reader bbr;
grpc_byte_buffer_reader_init(&bbr, resp_buffer);
grpc_slice slice = grpc_byte_buffer_reader_readall(&bbr);
- size_t buf_size = GPR_SLICE_LENGTH(slice);
- void* buf = upb_arena_malloc(arena, buf_size);
- memcpy(buf, reinterpret_cast<const char*>(GPR_SLICE_START_PTR(slice)),
- buf_size);
- grpc_gcp_HandshakerResp* resp = grpc_gcp_HandshakerResp_parse(
- reinterpret_cast<char*>(buf), buf_size, arena);
+ size_t buf_size = GPR_SLICE_LENGTH(slice);
+ void* buf = upb_arena_malloc(arena, buf_size);
+ memcpy(buf, reinterpret_cast<const char*>(GPR_SLICE_START_PTR(slice)),
+ buf_size);
+ grpc_gcp_HandshakerResp* resp = grpc_gcp_HandshakerResp_parse(
+ reinterpret_cast<char*>(buf), buf_size, arena);
grpc_slice_unref_internal(slice);
grpc_byte_buffer_reader_destroy(&bbr);
- if (resp == nullptr) {
+ if (resp == nullptr) {
gpr_log(GPR_ERROR, "grpc_gcp_handshaker_resp_decode() failed");
return nullptr;
}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h
index a20e5e9cd9..17c347d36f 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h
@@ -25,7 +25,7 @@
#include <grpc/grpc.h>
#include "src/core/tsi/transport_security_interface.h"
-#include "src/proto/grpc/gcp/handshaker.upb.h"
+#include "src/proto/grpc/gcp/handshaker.upb.h"
/**
* This method converts grpc_status_code code to the corresponding tsi_result
@@ -42,12 +42,12 @@ tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code);
* service.
*
* - bytes_received: data returned from ALTS handshaker service.
- * - arena: upb arena.
+ * - arena: upb arena.
*
* It returns a deserialized handshaker response on success and nullptr on
* failure.
*/
-grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response(
- grpc_byte_buffer* resp_buffer, upb_arena* arena);
+grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response(
+ grpc_byte_buffer* resp_buffer, upb_arena* arena);
#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc
index a0462b2d76..e4d1b2ec1a 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc
@@ -50,107 +50,107 @@ bool grpc_gcp_rpc_protocol_versions_set_min(
return true;
}
-bool grpc_gcp_rpc_protocol_versions_encode(
- const grpc_gcp_rpc_protocol_versions* versions, grpc_slice* slice) {
- if (versions == nullptr || slice == nullptr) {
+bool grpc_gcp_rpc_protocol_versions_encode(
+ const grpc_gcp_rpc_protocol_versions* versions, grpc_slice* slice) {
+ if (versions == nullptr || slice == nullptr) {
gpr_log(GPR_ERROR,
"Invalid nullptr arguments to "
- "grpc_gcp_rpc_protocol_versions_encode().");
- return false;
+ "grpc_gcp_rpc_protocol_versions_encode().");
+ return false;
}
- upb::Arena arena;
- grpc_gcp_RpcProtocolVersions* versions_msg =
- grpc_gcp_RpcProtocolVersions_new(arena.ptr());
- grpc_gcp_RpcProtocolVersions_assign_from_struct(versions_msg, arena.ptr(),
- versions);
- return grpc_gcp_rpc_protocol_versions_encode(versions_msg, arena.ptr(),
- slice);
+ upb::Arena arena;
+ grpc_gcp_RpcProtocolVersions* versions_msg =
+ grpc_gcp_RpcProtocolVersions_new(arena.ptr());
+ grpc_gcp_RpcProtocolVersions_assign_from_struct(versions_msg, arena.ptr(),
+ versions);
+ return grpc_gcp_rpc_protocol_versions_encode(versions_msg, arena.ptr(),
+ slice);
}
-bool grpc_gcp_rpc_protocol_versions_encode(
- const grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
- grpc_slice* slice) {
- if (versions == nullptr || arena == nullptr || slice == nullptr) {
+bool grpc_gcp_rpc_protocol_versions_encode(
+ const grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
+ grpc_slice* slice) {
+ if (versions == nullptr || arena == nullptr || slice == nullptr) {
gpr_log(GPR_ERROR,
"Invalid nullptr arguments to "
- "grpc_gcp_rpc_protocol_versions_encode().");
+ "grpc_gcp_rpc_protocol_versions_encode().");
return false;
}
- size_t buf_length;
- char* buf =
- grpc_gcp_RpcProtocolVersions_serialize(versions, arena, &buf_length);
- if (buf == nullptr) {
+ size_t buf_length;
+ char* buf =
+ grpc_gcp_RpcProtocolVersions_serialize(versions, arena, &buf_length);
+ if (buf == nullptr) {
return false;
}
- *slice = grpc_slice_from_copied_buffer(buf, buf_length);
+ *slice = grpc_slice_from_copied_buffer(buf, buf_length);
return true;
}
bool grpc_gcp_rpc_protocol_versions_decode(
- const grpc_slice& slice, grpc_gcp_rpc_protocol_versions* versions) {
+ const grpc_slice& slice, grpc_gcp_rpc_protocol_versions* versions) {
if (versions == nullptr) {
gpr_log(GPR_ERROR,
"version is nullptr in "
"grpc_gcp_rpc_protocol_versions_decode().");
return false;
}
- upb::Arena arena;
- grpc_gcp_RpcProtocolVersions* versions_msg =
- grpc_gcp_RpcProtocolVersions_parse(
- reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(slice)),
- GRPC_SLICE_LENGTH(slice), arena.ptr());
- if (versions_msg == nullptr) {
- gpr_log(GPR_ERROR, "cannot deserialize RpcProtocolVersions message");
+ upb::Arena arena;
+ grpc_gcp_RpcProtocolVersions* versions_msg =
+ grpc_gcp_RpcProtocolVersions_parse(
+ reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(slice)),
+ GRPC_SLICE_LENGTH(slice), arena.ptr());
+ if (versions_msg == nullptr) {
+ gpr_log(GPR_ERROR, "cannot deserialize RpcProtocolVersions message");
return false;
}
- grpc_gcp_rpc_protocol_versions_assign_from_upb(versions, versions_msg);
+ grpc_gcp_rpc_protocol_versions_assign_from_upb(versions, versions_msg);
return true;
}
-void grpc_gcp_rpc_protocol_versions_assign_from_upb(
- grpc_gcp_rpc_protocol_versions* versions,
- const grpc_gcp_RpcProtocolVersions* value) {
- const grpc_gcp_RpcProtocolVersions_Version* max_version_msg =
- grpc_gcp_RpcProtocolVersions_max_rpc_version(value);
- if (max_version_msg != nullptr) {
- versions->max_rpc_version.major =
- grpc_gcp_RpcProtocolVersions_Version_major(max_version_msg);
- versions->max_rpc_version.minor =
- grpc_gcp_RpcProtocolVersions_Version_minor(max_version_msg);
- } else {
- versions->max_rpc_version.major = 0;
- versions->max_rpc_version.minor = 0;
- }
- const grpc_gcp_RpcProtocolVersions_Version* min_version_msg =
- grpc_gcp_RpcProtocolVersions_min_rpc_version(value);
- if (min_version_msg != nullptr) {
- versions->min_rpc_version.major =
- grpc_gcp_RpcProtocolVersions_Version_major(min_version_msg);
- versions->min_rpc_version.minor =
- grpc_gcp_RpcProtocolVersions_Version_minor(min_version_msg);
- } else {
- versions->min_rpc_version.major = 0;
- versions->min_rpc_version.minor = 0;
- }
-}
-
-void grpc_gcp_RpcProtocolVersions_assign_from_struct(
- grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
- const grpc_gcp_rpc_protocol_versions* value) {
- grpc_gcp_RpcProtocolVersions_Version* max_version_msg =
- grpc_gcp_RpcProtocolVersions_mutable_max_rpc_version(versions, arena);
- grpc_gcp_RpcProtocolVersions_Version_set_major(max_version_msg,
- value->max_rpc_version.major);
- grpc_gcp_RpcProtocolVersions_Version_set_minor(max_version_msg,
- value->max_rpc_version.minor);
- grpc_gcp_RpcProtocolVersions_Version* min_version_msg =
- grpc_gcp_RpcProtocolVersions_mutable_min_rpc_version(versions, arena);
- grpc_gcp_RpcProtocolVersions_Version_set_major(min_version_msg,
- value->min_rpc_version.major);
- grpc_gcp_RpcProtocolVersions_Version_set_minor(min_version_msg,
- value->min_rpc_version.minor);
-}
-
+void grpc_gcp_rpc_protocol_versions_assign_from_upb(
+ grpc_gcp_rpc_protocol_versions* versions,
+ const grpc_gcp_RpcProtocolVersions* value) {
+ const grpc_gcp_RpcProtocolVersions_Version* max_version_msg =
+ grpc_gcp_RpcProtocolVersions_max_rpc_version(value);
+ if (max_version_msg != nullptr) {
+ versions->max_rpc_version.major =
+ grpc_gcp_RpcProtocolVersions_Version_major(max_version_msg);
+ versions->max_rpc_version.minor =
+ grpc_gcp_RpcProtocolVersions_Version_minor(max_version_msg);
+ } else {
+ versions->max_rpc_version.major = 0;
+ versions->max_rpc_version.minor = 0;
+ }
+ const grpc_gcp_RpcProtocolVersions_Version* min_version_msg =
+ grpc_gcp_RpcProtocolVersions_min_rpc_version(value);
+ if (min_version_msg != nullptr) {
+ versions->min_rpc_version.major =
+ grpc_gcp_RpcProtocolVersions_Version_major(min_version_msg);
+ versions->min_rpc_version.minor =
+ grpc_gcp_RpcProtocolVersions_Version_minor(min_version_msg);
+ } else {
+ versions->min_rpc_version.major = 0;
+ versions->min_rpc_version.minor = 0;
+ }
+}
+
+void grpc_gcp_RpcProtocolVersions_assign_from_struct(
+ grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
+ const grpc_gcp_rpc_protocol_versions* value) {
+ grpc_gcp_RpcProtocolVersions_Version* max_version_msg =
+ grpc_gcp_RpcProtocolVersions_mutable_max_rpc_version(versions, arena);
+ grpc_gcp_RpcProtocolVersions_Version_set_major(max_version_msg,
+ value->max_rpc_version.major);
+ grpc_gcp_RpcProtocolVersions_Version_set_minor(max_version_msg,
+ value->max_rpc_version.minor);
+ grpc_gcp_RpcProtocolVersions_Version* min_version_msg =
+ grpc_gcp_RpcProtocolVersions_mutable_min_rpc_version(versions, arena);
+ grpc_gcp_RpcProtocolVersions_Version_set_major(min_version_msg,
+ value->min_rpc_version.major);
+ grpc_gcp_RpcProtocolVersions_Version_set_minor(min_version_msg,
+ value->min_rpc_version.minor);
+}
+
bool grpc_gcp_rpc_protocol_versions_copy(
const grpc_gcp_rpc_protocol_versions* src,
grpc_gcp_rpc_protocol_versions* dst) {
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h
index 75739e4fe7..b4b39125ad 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h
@@ -26,19 +26,19 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-#include "src/proto/grpc/gcp/transport_security_common.upb.h"
+#include "src/proto/grpc/gcp/transport_security_common.upb.h"
-// C struct coresponding to protobuf message RpcProtocolVersions.Version
-typedef struct _grpc_gcp_RpcProtocolVersions_Version {
- uint32_t major;
- uint32_t minor;
-} grpc_gcp_rpc_protocol_versions_version;
+// C struct coresponding to protobuf message RpcProtocolVersions.Version
+typedef struct _grpc_gcp_RpcProtocolVersions_Version {
+ uint32_t major;
+ uint32_t minor;
+} grpc_gcp_rpc_protocol_versions_version;
-// C struct coresponding to protobuf message RpcProtocolVersions
-typedef struct _grpc_gcp_RpcProtocolVersions {
- grpc_gcp_rpc_protocol_versions_version max_rpc_version;
- grpc_gcp_rpc_protocol_versions_version min_rpc_version;
-} grpc_gcp_rpc_protocol_versions;
+// C struct coresponding to protobuf message RpcProtocolVersions
+typedef struct _grpc_gcp_RpcProtocolVersions {
+ grpc_gcp_rpc_protocol_versions_version max_rpc_version;
+ grpc_gcp_rpc_protocol_versions_version min_rpc_version;
+} grpc_gcp_rpc_protocol_versions;
/**
* This method sets the value for max_rpc_versions field of rpc protocol
@@ -69,30 +69,30 @@ bool grpc_gcp_rpc_protocol_versions_set_min(
uint32_t min_minor);
/**
- * This method serializes an rpc protocol version and returns serialized rpc
- * versions in grpc slice.
+ * This method serializes an rpc protocol version and returns serialized rpc
+ * versions in grpc slice.
*
* - versions: an rpc protocol versions instance.
- * - slice: grpc slice where the serialized result will be written.
+ * - slice: grpc slice where the serialized result will be written.
*
* The method returns true on success and false otherwise.
*/
-bool grpc_gcp_rpc_protocol_versions_encode(
- const grpc_gcp_rpc_protocol_versions* versions, grpc_slice* slice);
+bool grpc_gcp_rpc_protocol_versions_encode(
+ const grpc_gcp_rpc_protocol_versions* versions, grpc_slice* slice);
/**
* This method serializes an rpc protocol version and returns serialized rpc
* versions in grpc slice.
*
* - versions: an rpc protocol versions instance.
- * - arena: upb arena.
+ * - arena: upb arena.
* - slice: grpc slice where the serialized result will be written.
*
* The method returns true on success and false otherwise.
*/
bool grpc_gcp_rpc_protocol_versions_encode(
- const grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
- grpc_slice* slice);
+ const grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
+ grpc_slice* slice);
/**
* This method de-serializes input in grpc slice form and stores the result
@@ -105,24 +105,24 @@ bool grpc_gcp_rpc_protocol_versions_encode(
* The method returns true on success and false otherwise.
*/
bool grpc_gcp_rpc_protocol_versions_decode(
- const grpc_slice& slice, grpc_gcp_rpc_protocol_versions* versions);
-
-/**
- * Assigns value of upb RpcProtocolVersions to grpc_gcp_rpc_protocol_versions.
- */
-void grpc_gcp_rpc_protocol_versions_assign_from_upb(
- grpc_gcp_rpc_protocol_versions* versions,
- const grpc_gcp_RpcProtocolVersions* value);
-
-/**
- * Assigns value of struct grpc_gcp_rpc_protocol_versions to
- * RpcProtocolVersions.
- */
-void grpc_gcp_RpcProtocolVersions_assign_from_struct(
- grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
- const grpc_gcp_rpc_protocol_versions* value);
+ const grpc_slice& slice, grpc_gcp_rpc_protocol_versions* versions);
/**
+ * Assigns value of upb RpcProtocolVersions to grpc_gcp_rpc_protocol_versions.
+ */
+void grpc_gcp_rpc_protocol_versions_assign_from_upb(
+ grpc_gcp_rpc_protocol_versions* versions,
+ const grpc_gcp_RpcProtocolVersions* value);
+
+/**
+ * Assigns value of struct grpc_gcp_rpc_protocol_versions to
+ * RpcProtocolVersions.
+ */
+void grpc_gcp_RpcProtocolVersions_assign_from_struct(
+ grpc_gcp_RpcProtocolVersions* versions, upb_arena* arena,
+ const grpc_gcp_rpc_protocol_versions* value);
+
+/**
* This method performs a deep copy operation on rpc protocol versions
* instance.
*
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc
index 352561d469..f902fcd6fe 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc
@@ -1,226 +1,226 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include <string.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
-
-/* Main struct for alts_grpc_integrity_only_record_protocol. */
-typedef struct alts_grpc_integrity_only_record_protocol {
- alts_grpc_record_protocol base;
- bool enable_extra_copy;
- grpc_slice_buffer data_sb;
- unsigned char* tag_buf;
-} alts_grpc_integrity_only_record_protocol;
-
-/* --- alts_grpc_record_protocol methods implementation. --- */
-
-static tsi_result alts_grpc_integrity_only_extra_copy_protect(
- alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- /* Allocates memory for protected frame and copies data. */
- size_t data_length = unprotected_slices->length;
- size_t protected_frame_size =
- unprotected_slices->length + rp->header_length + rp->tag_length;
- grpc_slice protected_slice = GRPC_SLICE_MALLOC(protected_frame_size);
- uint8_t* data = GRPC_SLICE_START_PTR(protected_slice) + rp->header_length;
- for (size_t i = 0; i < unprotected_slices->count; i++) {
- memcpy(data, GRPC_SLICE_START_PTR(unprotected_slices->slices[i]),
- GRPC_SLICE_LENGTH(unprotected_slices->slices[i]));
- data += GRPC_SLICE_LENGTH(unprotected_slices->slices[i]);
- }
- /* Calls alts_iovec_record_protocol protect. */
- char* error_details = nullptr;
- iovec_t header_iovec = {GRPC_SLICE_START_PTR(protected_slice),
- rp->header_length};
- iovec_t tag_iovec = {
- GRPC_SLICE_START_PTR(protected_slice) + rp->header_length + data_length,
- rp->tag_length};
- rp->iovec_buf[0].iov_base =
- GRPC_SLICE_START_PTR(protected_slice) + rp->header_length;
- rp->iovec_buf[0].iov_len = data_length;
- grpc_status_code status = alts_iovec_record_protocol_integrity_only_protect(
- rp->iovec_rp, rp->iovec_buf, 1, header_iovec, tag_iovec, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- grpc_slice_buffer_add(protected_slices, protected_slice);
- grpc_slice_buffer_reset_and_unref_internal(unprotected_slices);
- return TSI_OK;
-}
-
-static tsi_result alts_grpc_integrity_only_protect(
- alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- /* Input sanity check. */
- if (rp == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol protect.");
- return TSI_INVALID_ARGUMENT;
- }
- alts_grpc_integrity_only_record_protocol* integrity_only_record_protocol =
- reinterpret_cast<alts_grpc_integrity_only_record_protocol*>(rp);
- if (integrity_only_record_protocol->enable_extra_copy) {
- return alts_grpc_integrity_only_extra_copy_protect(rp, unprotected_slices,
- protected_slices);
- }
- /* Allocates memory for header and tag slices. */
- grpc_slice header_slice = GRPC_SLICE_MALLOC(rp->header_length);
- grpc_slice tag_slice = GRPC_SLICE_MALLOC(rp->tag_length);
- /* Calls alts_iovec_record_protocol protect. */
- char* error_details = nullptr;
- iovec_t header_iovec = {GRPC_SLICE_START_PTR(header_slice),
- GRPC_SLICE_LENGTH(header_slice)};
- iovec_t tag_iovec = {GRPC_SLICE_START_PTR(tag_slice),
- GRPC_SLICE_LENGTH(tag_slice)};
- alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp,
- unprotected_slices);
- grpc_status_code status = alts_iovec_record_protocol_integrity_only_protect(
- rp->iovec_rp, rp->iovec_buf, unprotected_slices->count, header_iovec,
- tag_iovec, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- /* Appends result to protected_slices. */
- grpc_slice_buffer_add(protected_slices, header_slice);
- grpc_slice_buffer_move_into(unprotected_slices, protected_slices);
- grpc_slice_buffer_add(protected_slices, tag_slice);
- return TSI_OK;
-}
-
-static tsi_result alts_grpc_integrity_only_unprotect(
- alts_grpc_record_protocol* rp, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices) {
- /* Input sanity check. */
- if (rp == nullptr || protected_slices == nullptr ||
- unprotected_slices == nullptr) {
- gpr_log(
- GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol unprotect.");
- return TSI_INVALID_ARGUMENT;
- }
- if (protected_slices->length < rp->header_length + rp->tag_length) {
- gpr_log(GPR_ERROR, "Protected slices do not have sufficient data.");
- return TSI_INVALID_ARGUMENT;
- }
- /* In this method, rp points to alts_grpc_record_protocol struct
- * and integrity_only_record_protocol points to
- * alts_grpc_integrity_only_record_protocol struct. */
- alts_grpc_integrity_only_record_protocol* integrity_only_record_protocol =
- reinterpret_cast<alts_grpc_integrity_only_record_protocol*>(rp);
- /* Strips frame header from protected slices. */
- grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
- grpc_slice_buffer_move_first(protected_slices, rp->header_length,
- &rp->header_sb);
- GPR_ASSERT(rp->header_sb.length == rp->header_length);
- iovec_t header_iovec = alts_grpc_record_protocol_get_header_iovec(rp);
- /* Moves protected slices data to data_sb and leaves the remaining tag. */
- grpc_slice_buffer_reset_and_unref_internal(
- &integrity_only_record_protocol->data_sb);
- grpc_slice_buffer_move_first(protected_slices,
- protected_slices->length - rp->tag_length,
- &integrity_only_record_protocol->data_sb);
- GPR_ASSERT(protected_slices->length == rp->tag_length);
- iovec_t tag_iovec = {nullptr, rp->tag_length};
- if (protected_slices->count == 1) {
- tag_iovec.iov_base = GRPC_SLICE_START_PTR(protected_slices->slices[0]);
- } else {
- /* Frame tag is in multiple slices, copies the tag bytes from slice
- * buffer to a single flat buffer. */
- alts_grpc_record_protocol_copy_slice_buffer(
- protected_slices, integrity_only_record_protocol->tag_buf);
- tag_iovec.iov_base = integrity_only_record_protocol->tag_buf;
- }
- /* Calls alts_iovec_record_protocol unprotect. */
- char* error_details = nullptr;
- alts_grpc_record_protocol_convert_slice_buffer_to_iovec(
- rp, &integrity_only_record_protocol->data_sb);
- grpc_status_code status = alts_iovec_record_protocol_integrity_only_unprotect(
- rp->iovec_rp, rp->iovec_buf,
- integrity_only_record_protocol->data_sb.count, header_iovec, tag_iovec,
- &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to unprotect, %s", error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
- grpc_slice_buffer_reset_and_unref_internal(protected_slices);
- grpc_slice_buffer_move_into(&integrity_only_record_protocol->data_sb,
- unprotected_slices);
- return TSI_OK;
-}
-
-static void alts_grpc_integrity_only_destruct(alts_grpc_record_protocol* rp) {
- if (rp == nullptr) {
- return;
- }
- alts_grpc_integrity_only_record_protocol* integrity_only_rp =
- reinterpret_cast<alts_grpc_integrity_only_record_protocol*>(rp);
- grpc_slice_buffer_destroy_internal(&integrity_only_rp->data_sb);
- gpr_free(integrity_only_rp->tag_buf);
-}
-
-static const alts_grpc_record_protocol_vtable
- alts_grpc_integrity_only_record_protocol_vtable = {
- alts_grpc_integrity_only_protect, alts_grpc_integrity_only_unprotect,
- alts_grpc_integrity_only_destruct};
-
-tsi_result alts_grpc_integrity_only_record_protocol_create(
- gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
- bool is_protect, bool enable_extra_copy, alts_grpc_record_protocol** rp) {
- if (crypter == nullptr || rp == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol create.");
- return TSI_INVALID_ARGUMENT;
- }
- alts_grpc_integrity_only_record_protocol* impl =
- static_cast<alts_grpc_integrity_only_record_protocol*>(
- gpr_zalloc(sizeof(alts_grpc_integrity_only_record_protocol)));
- /* Calls alts_grpc_record_protocol init. */
- tsi_result result = alts_grpc_record_protocol_init(
- &impl->base, crypter, overflow_size, is_client,
- /*is_integrity_only=*/true, is_protect);
- if (result != TSI_OK) {
- gpr_free(impl);
- return result;
- }
- impl->enable_extra_copy = enable_extra_copy;
- /* Initializes slice buffer for data_sb. */
- grpc_slice_buffer_init(&impl->data_sb);
- /* Allocates tag buffer. */
- impl->tag_buf =
- static_cast<unsigned char*>(gpr_malloc(impl->base.tag_length));
- impl->base.vtable = &alts_grpc_integrity_only_record_protocol_vtable;
- *rp = &impl->base;
- return TSI_OK;
-}
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include <string.h>
+
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
+
+/* Main struct for alts_grpc_integrity_only_record_protocol. */
+typedef struct alts_grpc_integrity_only_record_protocol {
+ alts_grpc_record_protocol base;
+ bool enable_extra_copy;
+ grpc_slice_buffer data_sb;
+ unsigned char* tag_buf;
+} alts_grpc_integrity_only_record_protocol;
+
+/* --- alts_grpc_record_protocol methods implementation. --- */
+
+static tsi_result alts_grpc_integrity_only_extra_copy_protect(
+ alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ /* Allocates memory for protected frame and copies data. */
+ size_t data_length = unprotected_slices->length;
+ size_t protected_frame_size =
+ unprotected_slices->length + rp->header_length + rp->tag_length;
+ grpc_slice protected_slice = GRPC_SLICE_MALLOC(protected_frame_size);
+ uint8_t* data = GRPC_SLICE_START_PTR(protected_slice) + rp->header_length;
+ for (size_t i = 0; i < unprotected_slices->count; i++) {
+ memcpy(data, GRPC_SLICE_START_PTR(unprotected_slices->slices[i]),
+ GRPC_SLICE_LENGTH(unprotected_slices->slices[i]));
+ data += GRPC_SLICE_LENGTH(unprotected_slices->slices[i]);
+ }
+ /* Calls alts_iovec_record_protocol protect. */
+ char* error_details = nullptr;
+ iovec_t header_iovec = {GRPC_SLICE_START_PTR(protected_slice),
+ rp->header_length};
+ iovec_t tag_iovec = {
+ GRPC_SLICE_START_PTR(protected_slice) + rp->header_length + data_length,
+ rp->tag_length};
+ rp->iovec_buf[0].iov_base =
+ GRPC_SLICE_START_PTR(protected_slice) + rp->header_length;
+ rp->iovec_buf[0].iov_len = data_length;
+ grpc_status_code status = alts_iovec_record_protocol_integrity_only_protect(
+ rp->iovec_rp, rp->iovec_buf, 1, header_iovec, tag_iovec, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ grpc_slice_buffer_add(protected_slices, protected_slice);
+ grpc_slice_buffer_reset_and_unref_internal(unprotected_slices);
+ return TSI_OK;
+}
+
+static tsi_result alts_grpc_integrity_only_protect(
+ alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ /* Input sanity check. */
+ if (rp == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol protect.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_grpc_integrity_only_record_protocol* integrity_only_record_protocol =
+ reinterpret_cast<alts_grpc_integrity_only_record_protocol*>(rp);
+ if (integrity_only_record_protocol->enable_extra_copy) {
+ return alts_grpc_integrity_only_extra_copy_protect(rp, unprotected_slices,
+ protected_slices);
+ }
+ /* Allocates memory for header and tag slices. */
+ grpc_slice header_slice = GRPC_SLICE_MALLOC(rp->header_length);
+ grpc_slice tag_slice = GRPC_SLICE_MALLOC(rp->tag_length);
+ /* Calls alts_iovec_record_protocol protect. */
+ char* error_details = nullptr;
+ iovec_t header_iovec = {GRPC_SLICE_START_PTR(header_slice),
+ GRPC_SLICE_LENGTH(header_slice)};
+ iovec_t tag_iovec = {GRPC_SLICE_START_PTR(tag_slice),
+ GRPC_SLICE_LENGTH(tag_slice)};
+ alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp,
+ unprotected_slices);
+ grpc_status_code status = alts_iovec_record_protocol_integrity_only_protect(
+ rp->iovec_rp, rp->iovec_buf, unprotected_slices->count, header_iovec,
+ tag_iovec, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ /* Appends result to protected_slices. */
+ grpc_slice_buffer_add(protected_slices, header_slice);
+ grpc_slice_buffer_move_into(unprotected_slices, protected_slices);
+ grpc_slice_buffer_add(protected_slices, tag_slice);
+ return TSI_OK;
+}
+
+static tsi_result alts_grpc_integrity_only_unprotect(
+ alts_grpc_record_protocol* rp, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices) {
+ /* Input sanity check. */
+ if (rp == nullptr || protected_slices == nullptr ||
+ unprotected_slices == nullptr) {
+ gpr_log(
+ GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol unprotect.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (protected_slices->length < rp->header_length + rp->tag_length) {
+ gpr_log(GPR_ERROR, "Protected slices do not have sufficient data.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ /* In this method, rp points to alts_grpc_record_protocol struct
+ * and integrity_only_record_protocol points to
+ * alts_grpc_integrity_only_record_protocol struct. */
+ alts_grpc_integrity_only_record_protocol* integrity_only_record_protocol =
+ reinterpret_cast<alts_grpc_integrity_only_record_protocol*>(rp);
+ /* Strips frame header from protected slices. */
+ grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
+ grpc_slice_buffer_move_first(protected_slices, rp->header_length,
+ &rp->header_sb);
+ GPR_ASSERT(rp->header_sb.length == rp->header_length);
+ iovec_t header_iovec = alts_grpc_record_protocol_get_header_iovec(rp);
+ /* Moves protected slices data to data_sb and leaves the remaining tag. */
+ grpc_slice_buffer_reset_and_unref_internal(
+ &integrity_only_record_protocol->data_sb);
+ grpc_slice_buffer_move_first(protected_slices,
+ protected_slices->length - rp->tag_length,
+ &integrity_only_record_protocol->data_sb);
+ GPR_ASSERT(protected_slices->length == rp->tag_length);
+ iovec_t tag_iovec = {nullptr, rp->tag_length};
+ if (protected_slices->count == 1) {
+ tag_iovec.iov_base = GRPC_SLICE_START_PTR(protected_slices->slices[0]);
+ } else {
+ /* Frame tag is in multiple slices, copies the tag bytes from slice
+ * buffer to a single flat buffer. */
+ alts_grpc_record_protocol_copy_slice_buffer(
+ protected_slices, integrity_only_record_protocol->tag_buf);
+ tag_iovec.iov_base = integrity_only_record_protocol->tag_buf;
+ }
+ /* Calls alts_iovec_record_protocol unprotect. */
+ char* error_details = nullptr;
+ alts_grpc_record_protocol_convert_slice_buffer_to_iovec(
+ rp, &integrity_only_record_protocol->data_sb);
+ grpc_status_code status = alts_iovec_record_protocol_integrity_only_unprotect(
+ rp->iovec_rp, rp->iovec_buf,
+ integrity_only_record_protocol->data_sb.count, header_iovec, tag_iovec,
+ &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to unprotect, %s", error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
+ grpc_slice_buffer_reset_and_unref_internal(protected_slices);
+ grpc_slice_buffer_move_into(&integrity_only_record_protocol->data_sb,
+ unprotected_slices);
+ return TSI_OK;
+}
+
+static void alts_grpc_integrity_only_destruct(alts_grpc_record_protocol* rp) {
+ if (rp == nullptr) {
+ return;
+ }
+ alts_grpc_integrity_only_record_protocol* integrity_only_rp =
+ reinterpret_cast<alts_grpc_integrity_only_record_protocol*>(rp);
+ grpc_slice_buffer_destroy_internal(&integrity_only_rp->data_sb);
+ gpr_free(integrity_only_rp->tag_buf);
+}
+
+static const alts_grpc_record_protocol_vtable
+ alts_grpc_integrity_only_record_protocol_vtable = {
+ alts_grpc_integrity_only_protect, alts_grpc_integrity_only_unprotect,
+ alts_grpc_integrity_only_destruct};
+
+tsi_result alts_grpc_integrity_only_record_protocol_create(
+ gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
+ bool is_protect, bool enable_extra_copy, alts_grpc_record_protocol** rp) {
+ if (crypter == nullptr || rp == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol create.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_grpc_integrity_only_record_protocol* impl =
+ static_cast<alts_grpc_integrity_only_record_protocol*>(
+ gpr_zalloc(sizeof(alts_grpc_integrity_only_record_protocol)));
+ /* Calls alts_grpc_record_protocol init. */
+ tsi_result result = alts_grpc_record_protocol_init(
+ &impl->base, crypter, overflow_size, is_client,
+ /*is_integrity_only=*/true, is_protect);
+ if (result != TSI_OK) {
+ gpr_free(impl);
+ return result;
+ }
+ impl->enable_extra_copy = enable_extra_copy;
+ /* Initializes slice buffer for data_sb. */
+ grpc_slice_buffer_init(&impl->data_sb);
+ /* Allocates tag buffer. */
+ impl->tag_buf =
+ static_cast<unsigned char*>(gpr_malloc(impl->base.tag_length));
+ impl->base.vtable = &alts_grpc_integrity_only_record_protocol_vtable;
+ *rp = &impl->base;
+ return TSI_OK;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc
index e7890903d5..269f031eb0 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc
@@ -1,144 +1,144 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
-
-/* Privacy-integrity alts_grpc_record_protocol object uses the same struct
- * defined in alts_grpc_record_protocol_common.h. */
-
-/* --- alts_grpc_record_protocol methods implementation. --- */
-
-static tsi_result alts_grpc_privacy_integrity_protect(
- alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- /* Input sanity check. */
- if (rp == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol protect.");
- return TSI_INVALID_ARGUMENT;
- }
- /* Allocates memory for output frame. In privacy-integrity protect, the
- * protected frame is stored in a newly allocated buffer. */
- size_t protected_frame_size =
- unprotected_slices->length + rp->header_length +
- alts_iovec_record_protocol_get_tag_length(rp->iovec_rp);
- grpc_slice protected_slice = GRPC_SLICE_MALLOC(protected_frame_size);
- iovec_t protected_iovec = {GRPC_SLICE_START_PTR(protected_slice),
- GRPC_SLICE_LENGTH(protected_slice)};
- /* Calls alts_iovec_record_protocol protect. */
- char* error_details = nullptr;
- alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp,
- unprotected_slices);
- grpc_status_code status =
- alts_iovec_record_protocol_privacy_integrity_protect(
- rp->iovec_rp, rp->iovec_buf, unprotected_slices->count,
- protected_iovec, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
- gpr_free(error_details);
- grpc_slice_unref_internal(protected_slice);
- return TSI_INTERNAL_ERROR;
- }
- grpc_slice_buffer_add(protected_slices, protected_slice);
- grpc_slice_buffer_reset_and_unref_internal(unprotected_slices);
- return TSI_OK;
-}
-
-static tsi_result alts_grpc_privacy_integrity_unprotect(
- alts_grpc_record_protocol* rp, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices) {
- /* Input sanity check. */
- if (rp == nullptr || protected_slices == nullptr ||
- unprotected_slices == nullptr) {
- gpr_log(
- GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol unprotect.");
- return TSI_INVALID_ARGUMENT;
- }
- /* Allocates memory for output frame. In privacy-integrity unprotect, the
- * unprotected data are stored in a newly allocated buffer. */
- if (protected_slices->length < rp->header_length + rp->tag_length) {
- gpr_log(GPR_ERROR, "Protected slices do not have sufficient data.");
- return TSI_INVALID_ARGUMENT;
- }
- size_t unprotected_frame_size =
- protected_slices->length - rp->header_length - rp->tag_length;
- grpc_slice unprotected_slice = GRPC_SLICE_MALLOC(unprotected_frame_size);
- iovec_t unprotected_iovec = {GRPC_SLICE_START_PTR(unprotected_slice),
- GRPC_SLICE_LENGTH(unprotected_slice)};
- /* Strips frame header from protected slices. */
- grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
- grpc_slice_buffer_move_first(protected_slices, rp->header_length,
- &rp->header_sb);
- iovec_t header_iovec = alts_grpc_record_protocol_get_header_iovec(rp);
- /* Calls alts_iovec_record_protocol unprotect. */
- char* error_details = nullptr;
- alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp, protected_slices);
- grpc_status_code status =
- alts_iovec_record_protocol_privacy_integrity_unprotect(
- rp->iovec_rp, header_iovec, rp->iovec_buf, protected_slices->count,
- unprotected_iovec, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to unprotect, %s", error_details);
- gpr_free(error_details);
- grpc_slice_unref_internal(unprotected_slice);
- return TSI_INTERNAL_ERROR;
- }
- grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
- grpc_slice_buffer_reset_and_unref_internal(protected_slices);
- grpc_slice_buffer_add(unprotected_slices, unprotected_slice);
- return TSI_OK;
-}
-
-static const alts_grpc_record_protocol_vtable
- alts_grpc_privacy_integrity_record_protocol_vtable = {
- alts_grpc_privacy_integrity_protect,
- alts_grpc_privacy_integrity_unprotect, nullptr};
-
-tsi_result alts_grpc_privacy_integrity_record_protocol_create(
- gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
- bool is_protect, alts_grpc_record_protocol** rp) {
- if (crypter == nullptr || rp == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol create.");
- return TSI_INVALID_ARGUMENT;
- }
- auto* impl = static_cast<alts_grpc_record_protocol*>(
- gpr_zalloc(sizeof(alts_grpc_record_protocol)));
- /* Calls alts_grpc_record_protocol init. */
- tsi_result result =
- alts_grpc_record_protocol_init(impl, crypter, overflow_size, is_client,
- /*is_integrity_only=*/false, is_protect);
- if (result != TSI_OK) {
- gpr_free(impl);
- return result;
- }
- impl->vtable = &alts_grpc_privacy_integrity_record_protocol_vtable;
- *rp = impl;
- return TSI_OK;
-}
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
+
+/* Privacy-integrity alts_grpc_record_protocol object uses the same struct
+ * defined in alts_grpc_record_protocol_common.h. */
+
+/* --- alts_grpc_record_protocol methods implementation. --- */
+
+static tsi_result alts_grpc_privacy_integrity_protect(
+ alts_grpc_record_protocol* rp, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ /* Input sanity check. */
+ if (rp == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol protect.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ /* Allocates memory for output frame. In privacy-integrity protect, the
+ * protected frame is stored in a newly allocated buffer. */
+ size_t protected_frame_size =
+ unprotected_slices->length + rp->header_length +
+ alts_iovec_record_protocol_get_tag_length(rp->iovec_rp);
+ grpc_slice protected_slice = GRPC_SLICE_MALLOC(protected_frame_size);
+ iovec_t protected_iovec = {GRPC_SLICE_START_PTR(protected_slice),
+ GRPC_SLICE_LENGTH(protected_slice)};
+ /* Calls alts_iovec_record_protocol protect. */
+ char* error_details = nullptr;
+ alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp,
+ unprotected_slices);
+ grpc_status_code status =
+ alts_iovec_record_protocol_privacy_integrity_protect(
+ rp->iovec_rp, rp->iovec_buf, unprotected_slices->count,
+ protected_iovec, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to protect, %s", error_details);
+ gpr_free(error_details);
+ grpc_slice_unref_internal(protected_slice);
+ return TSI_INTERNAL_ERROR;
+ }
+ grpc_slice_buffer_add(protected_slices, protected_slice);
+ grpc_slice_buffer_reset_and_unref_internal(unprotected_slices);
+ return TSI_OK;
+}
+
+static tsi_result alts_grpc_privacy_integrity_unprotect(
+ alts_grpc_record_protocol* rp, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices) {
+ /* Input sanity check. */
+ if (rp == nullptr || protected_slices == nullptr ||
+ unprotected_slices == nullptr) {
+ gpr_log(
+ GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol unprotect.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ /* Allocates memory for output frame. In privacy-integrity unprotect, the
+ * unprotected data are stored in a newly allocated buffer. */
+ if (protected_slices->length < rp->header_length + rp->tag_length) {
+ gpr_log(GPR_ERROR, "Protected slices do not have sufficient data.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ size_t unprotected_frame_size =
+ protected_slices->length - rp->header_length - rp->tag_length;
+ grpc_slice unprotected_slice = GRPC_SLICE_MALLOC(unprotected_frame_size);
+ iovec_t unprotected_iovec = {GRPC_SLICE_START_PTR(unprotected_slice),
+ GRPC_SLICE_LENGTH(unprotected_slice)};
+ /* Strips frame header from protected slices. */
+ grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
+ grpc_slice_buffer_move_first(protected_slices, rp->header_length,
+ &rp->header_sb);
+ iovec_t header_iovec = alts_grpc_record_protocol_get_header_iovec(rp);
+ /* Calls alts_iovec_record_protocol unprotect. */
+ char* error_details = nullptr;
+ alts_grpc_record_protocol_convert_slice_buffer_to_iovec(rp, protected_slices);
+ grpc_status_code status =
+ alts_iovec_record_protocol_privacy_integrity_unprotect(
+ rp->iovec_rp, header_iovec, rp->iovec_buf, protected_slices->count,
+ unprotected_iovec, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to unprotect, %s", error_details);
+ gpr_free(error_details);
+ grpc_slice_unref_internal(unprotected_slice);
+ return TSI_INTERNAL_ERROR;
+ }
+ grpc_slice_buffer_reset_and_unref_internal(&rp->header_sb);
+ grpc_slice_buffer_reset_and_unref_internal(protected_slices);
+ grpc_slice_buffer_add(unprotected_slices, unprotected_slice);
+ return TSI_OK;
+}
+
+static const alts_grpc_record_protocol_vtable
+ alts_grpc_privacy_integrity_record_protocol_vtable = {
+ alts_grpc_privacy_integrity_protect,
+ alts_grpc_privacy_integrity_unprotect, nullptr};
+
+tsi_result alts_grpc_privacy_integrity_record_protocol_create(
+ gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
+ bool is_protect, alts_grpc_record_protocol** rp) {
+ if (crypter == nullptr || rp == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol create.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ auto* impl = static_cast<alts_grpc_record_protocol*>(
+ gpr_zalloc(sizeof(alts_grpc_record_protocol)));
+ /* Calls alts_grpc_record_protocol init. */
+ tsi_result result =
+ alts_grpc_record_protocol_init(impl, crypter, overflow_size, is_client,
+ /*is_integrity_only=*/false, is_protect);
+ if (result != TSI_OK) {
+ gpr_free(impl);
+ return result;
+ }
+ impl->vtable = &alts_grpc_privacy_integrity_record_protocol_vtable;
+ *rp = impl;
+ return TSI_OK;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc
index 0cdf97465d..22278b61f0 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc
@@ -37,7 +37,7 @@
constexpr size_t kMinFrameLength = 1024;
constexpr size_t kDefaultFrameLength = 16 * 1024;
-constexpr size_t kMaxFrameLength = 16 * 1024 * 1024;
+constexpr size_t kMaxFrameLength = 16 * 1024 * 1024;
/**
* Main struct for alts_zero_copy_grpc_protector.
@@ -105,7 +105,7 @@ static bool read_frame_size(const grpc_slice_buffer* sb,
* Creates an alts_grpc_record_protocol object, given key, key size, and flags
* to indicate whether the record_protocol object uses the rekeying AEAD,
* whether the object is for client or server, whether the object is for
- * integrity-only or privacy-integrity mode, and whether the object is used
+ * integrity-only or privacy-integrity mode, and whether the object is used
* for protect or unprotect.
*/
static tsi_result create_alts_grpc_record_protocol(
@@ -233,21 +233,21 @@ static void alts_zero_copy_grpc_protector_destroy(
gpr_free(protector);
}
-static tsi_result alts_zero_copy_grpc_protector_max_frame_size(
+static tsi_result alts_zero_copy_grpc_protector_max_frame_size(
tsi_zero_copy_grpc_protector* self, size_t* max_frame_size) {
if (self == nullptr || max_frame_size == nullptr) return TSI_INVALID_ARGUMENT;
- alts_zero_copy_grpc_protector* protector =
- reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
+ alts_zero_copy_grpc_protector* protector =
+ reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
*max_frame_size = protector->max_protected_frame_size;
- return TSI_OK;
-}
-
+ return TSI_OK;
+}
+
static const tsi_zero_copy_grpc_protector_vtable
alts_zero_copy_grpc_protector_vtable = {
alts_zero_copy_grpc_protector_protect,
alts_zero_copy_grpc_protector_unprotect,
- alts_zero_copy_grpc_protector_destroy,
- alts_zero_copy_grpc_protector_max_frame_size};
+ alts_zero_copy_grpc_protector_destroy,
+ alts_zero_copy_grpc_protector_max_frame_size};
tsi_result alts_zero_copy_grpc_protector_create(
const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
diff --git a/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc b/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc
index 1b6b8ca07b..785ddebc92 100644
--- a/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc
+++ b/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc
@@ -479,7 +479,7 @@ static const tsi_zero_copy_grpc_protector_vtable
fake_zero_copy_grpc_protector_protect,
fake_zero_copy_grpc_protector_unprotect,
fake_zero_copy_grpc_protector_destroy,
- nullptr /* fake_zero_copy_grpc_protector_max_frame_size */
+ nullptr /* fake_zero_copy_grpc_protector_max_frame_size */
};
/* --- tsi_handshaker_result methods implementation. ---*/
@@ -506,8 +506,8 @@ static tsi_result fake_handshaker_result_extract_peer(
}
static tsi_result fake_handshaker_result_create_zero_copy_grpc_protector(
- const tsi_handshaker_result* /*self*/,
- size_t* max_output_protected_frame_size,
+ const tsi_handshaker_result* /*self*/,
+ size_t* max_output_protected_frame_size,
tsi_zero_copy_grpc_protector** protector) {
*protector =
tsi_create_fake_zero_copy_grpc_protector(max_output_protected_frame_size);
@@ -515,8 +515,8 @@ static tsi_result fake_handshaker_result_create_zero_copy_grpc_protector(
}
static tsi_result fake_handshaker_result_create_frame_protector(
- const tsi_handshaker_result* /*self*/,
- size_t* max_output_protected_frame_size, tsi_frame_protector** protector) {
+ const tsi_handshaker_result* /*self*/,
+ size_t* max_output_protected_frame_size, tsi_frame_protector** protector) {
*protector = tsi_create_fake_frame_protector(max_output_protected_frame_size);
return TSI_OK;
}
@@ -586,7 +586,7 @@ static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
if (next_message_to_send > TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
next_message_to_send = TSI_FAKE_HANDSHAKE_MESSAGE_MAX;
}
- if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
+ if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
gpr_log(GPR_INFO, "%s prepared %s.",
impl->is_client ? "Client" : "Server",
tsi_fake_handshake_message_to_string(impl->next_message_to_send));
@@ -598,7 +598,7 @@ static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
if (!impl->is_client &&
impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
/* We're done. */
- if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
+ if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
gpr_log(GPR_INFO, "Server is done.");
}
impl->result = TSI_OK;
@@ -637,7 +637,7 @@ static tsi_result fake_handshaker_process_bytes_from_peer(
tsi_fake_handshake_message_to_string(received_msg),
tsi_fake_handshake_message_to_string(expected_msg));
}
- if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
+ if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
gpr_log(GPR_INFO, "%s received %s.", impl->is_client ? "Client" : "Server",
tsi_fake_handshake_message_to_string(received_msg));
}
@@ -645,7 +645,7 @@ static tsi_result fake_handshaker_process_bytes_from_peer(
impl->needs_incoming_message = 0;
if (impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
/* We're done. */
- if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
+ if (GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
gpr_log(GPR_INFO, "%s is done.", impl->is_client ? "Client" : "Server");
}
impl->result = TSI_OK;
@@ -670,7 +670,7 @@ static tsi_result fake_handshaker_next(
tsi_handshaker* self, const unsigned char* received_bytes,
size_t received_bytes_size, const unsigned char** bytes_to_send,
size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
- tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
+ tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
/* Sanity check the arguments. */
if ((received_bytes_size > 0 && received_bytes == nullptr) ||
bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
diff --git a/contrib/libs/grpc/src/core/tsi/local_transport_security.cc b/contrib/libs/grpc/src/core/tsi/local_transport_security.cc
index f7e004f4a7..ecc3b439bf 100644
--- a/contrib/libs/grpc/src/core/tsi/local_transport_security.cc
+++ b/contrib/libs/grpc/src/core/tsi/local_transport_security.cc
@@ -84,8 +84,8 @@ static const tsi_zero_copy_grpc_protector_vtable
local_zero_copy_grpc_protector_vtable = {
local_zero_copy_grpc_protector_protect,
local_zero_copy_grpc_protector_unprotect,
- local_zero_copy_grpc_protector_destroy,
- nullptr /* local_zero_copy_grpc_protector_max_frame_size */};
+ local_zero_copy_grpc_protector_destroy,
+ nullptr /* local_zero_copy_grpc_protector_max_frame_size */};
tsi_result local_zero_copy_grpc_protector_create(
tsi_zero_copy_grpc_protector** protector) {
@@ -105,13 +105,13 @@ tsi_result local_zero_copy_grpc_protector_create(
/* --- tsi_handshaker_result methods implementation. --- */
static tsi_result handshaker_result_extract_peer(
- const tsi_handshaker_result* /*self*/, tsi_peer* /*peer*/) {
+ const tsi_handshaker_result* /*self*/, tsi_peer* /*peer*/) {
return TSI_OK;
}
static tsi_result handshaker_result_create_zero_copy_grpc_protector(
- const tsi_handshaker_result* self,
- size_t* /*max_output_protected_frame_size*/,
+ const tsi_handshaker_result* self,
+ size_t* /*max_output_protected_frame_size*/,
tsi_zero_copy_grpc_protector** protector) {
if (self == nullptr || protector == nullptr) {
gpr_log(GPR_ERROR,
@@ -159,10 +159,10 @@ static tsi_result create_handshaker_result(bool is_client,
/* --- tsi_handshaker methods implementation. --- */
static tsi_result handshaker_next(
- tsi_handshaker* self, const unsigned char* /*received_bytes*/,
- size_t /*received_bytes_size*/, const unsigned char** /*bytes_to_send*/,
+ tsi_handshaker* self, const unsigned char* /*received_bytes*/,
+ size_t /*received_bytes_size*/, const unsigned char** /*bytes_to_send*/,
size_t* bytes_to_send_size, tsi_handshaker_result** result,
- tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
+ tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
if (self == nullptr) {
gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()");
return TSI_INVALID_ARGUMENT;
diff --git a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session.h b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session.h
index 108c0cd133..3371ac3224 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session.h
+++ b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session.h
@@ -55,12 +55,12 @@ class SslCachedSession {
SslCachedSession& operator=(const SslCachedSession&) = delete;
/// Create single cached instance of \a session.
- static std::unique_ptr<SslCachedSession> Create(SslSessionPtr session);
+ static std::unique_ptr<SslCachedSession> Create(SslSessionPtr session);
virtual ~SslCachedSession() = default;
/// Returns a copy of previously cached session.
- virtual SslSessionPtr CopySession() const = 0;
+ virtual SslSessionPtr CopySession() const = 0;
protected:
SslCachedSession() = default;
diff --git a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc
index a77b17c5dd..8fea1a0013 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc
+++ b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc
@@ -47,7 +47,7 @@ class BoringSslCachedSession : public SslCachedSession {
} // namespace
-std::unique_ptr<SslCachedSession> SslCachedSession::Create(
+std::unique_ptr<SslCachedSession> SslCachedSession::Create(
SslSessionPtr session) {
return y_absl::make_unique<BoringSslCachedSession>(std::move(session));
}
diff --git a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc
index 6da4fb4ee1..9229e20bd1 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc
+++ b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc
@@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/tsi/ssl/session_cache/ssl_session.h"
#include "src/core/tsi/ssl/session_cache/ssl_session_cache.h"
@@ -28,20 +28,20 @@
namespace tsi {
-static void cache_key_avl_destroy(void* /*key*/, void* /*unused*/) {}
+static void cache_key_avl_destroy(void* /*key*/, void* /*unused*/) {}
-static void* cache_key_avl_copy(void* key, void* /*unused*/) { return key; }
+static void* cache_key_avl_copy(void* key, void* /*unused*/) { return key; }
-static long cache_key_avl_compare(void* key1, void* key2, void* /*unused*/) {
+static long cache_key_avl_compare(void* key1, void* key2, void* /*unused*/) {
return grpc_slice_cmp(*static_cast<grpc_slice*>(key1),
*static_cast<grpc_slice*>(key2));
}
-static void cache_value_avl_destroy(void* /*value*/, void* /*unused*/) {}
+static void cache_value_avl_destroy(void* /*value*/, void* /*unused*/) {}
-static void* cache_value_avl_copy(void* value, void* /*unused*/) {
- return value;
-}
+static void* cache_value_avl_copy(void* value, void* /*unused*/) {
+ return value;
+}
// AVL only stores pointers, ownership belonges to the linked list.
static const grpc_avl_vtable cache_avl_vtable = {
@@ -76,7 +76,7 @@ class SslSessionLRUCache::Node {
friend class SslSessionLRUCache;
grpc_slice key_;
- std::unique_ptr<SslCachedSession> session_;
+ std::unique_ptr<SslCachedSession> session_;
Node* next_ = nullptr;
Node* prev_ = nullptr;
@@ -92,7 +92,7 @@ SslSessionLRUCache::~SslSessionLRUCache() {
Node* node = use_order_list_head_;
while (node) {
Node* next = node->next_;
- delete node;
+ delete node;
node = next;
}
grpc_avl_unref(entry_by_key_, nullptr);
@@ -127,7 +127,7 @@ void SslSessionLRUCache::Put(const char* key, SslSessionPtr session) {
return;
}
grpc_slice key_slice = grpc_slice_from_copied_string(key);
- node = new Node(key_slice, std::move(session));
+ node = new Node(key_slice, std::move(session));
PushFront(node);
entry_by_key_ = grpc_avl_add(entry_by_key_, node->AvlKey(), node, nullptr);
AssertInvariants();
@@ -137,7 +137,7 @@ void SslSessionLRUCache::Put(const char* key, SslSessionPtr session) {
Remove(node);
// Order matters, key is destroyed after deleting node.
entry_by_key_ = grpc_avl_remove(entry_by_key_, node->AvlKey(), nullptr);
- delete node;
+ delete node;
AssertInvariants();
}
}
diff --git a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h
index 5d91af7b18..061e826627 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h
+++ b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h
@@ -51,10 +51,10 @@ class SslSessionLRUCache : public grpc_core::RefCounted<SslSessionLRUCache> {
return grpc_core::MakeRefCounted<SslSessionLRUCache>(capacity);
}
- // Use Create function instead of using this directly.
- explicit SslSessionLRUCache(size_t capacity);
- ~SslSessionLRUCache();
-
+ // Use Create function instead of using this directly.
+ explicit SslSessionLRUCache(size_t capacity);
+ ~SslSessionLRUCache();
+
// Not copyable nor movable.
SslSessionLRUCache(const SslSessionLRUCache&) = delete;
SslSessionLRUCache& operator=(const SslSessionLRUCache&) = delete;
diff --git a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc
index 1df8139681..554076ac7e 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc
+++ b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc
@@ -65,7 +65,7 @@ class OpenSslCachedSession : public SslCachedSession {
} // namespace
-std::unique_ptr<SslCachedSession> SslCachedSession::Create(
+std::unique_ptr<SslCachedSession> SslCachedSession::Create(
SslSessionPtr session) {
return y_absl::make_unique<OpenSslCachedSession>(std::move(session));
}
diff --git a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc
index 374f8e583f..8d69bef023 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc
+++ b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc
@@ -229,7 +229,7 @@ static const char* ssl_error_string(int error) {
/* TODO(jboeuf): Remove when we are past the debugging phase with this code. */
static void ssl_log_where_info(const SSL* ssl, int where, int flag,
const char* msg) {
- if ((where & flag) && GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
+ if ((where & flag) && GRPC_TRACE_FLAG_ENABLED(tsi_tracing_enabled)) {
gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg,
SSL_state_string_long(ssl), SSL_state_string(ssl));
}
@@ -252,7 +252,7 @@ static void ssl_info_callback(const SSL* ssl, int where, int ret) {
static int looks_like_ip_address(y_absl::string_view name) {
size_t dot_count = 0;
size_t num_size = 0;
- for (size_t i = 0; i < name.size(); ++i) {
+ for (size_t i = 0; i < name.size(); ++i) {
if (name[i] == ':') {
/* IPv6 Address in hexadecimal form, : is not allowed in DNS names. */
return 1;
@@ -363,19 +363,19 @@ static tsi_result add_subject_alt_names_properties_to_peer(
for (i = 0; i < subject_alt_name_count; i++) {
GENERAL_NAME* subject_alt_name =
sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i));
- if (subject_alt_name->type == GEN_DNS ||
- subject_alt_name->type == GEN_EMAIL ||
- subject_alt_name->type == GEN_URI) {
+ if (subject_alt_name->type == GEN_DNS ||
+ subject_alt_name->type == GEN_EMAIL ||
+ subject_alt_name->type == GEN_URI) {
unsigned char* name = nullptr;
int name_size;
- if (subject_alt_name->type == GEN_DNS) {
- name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName);
- } else if (subject_alt_name->type == GEN_EMAIL) {
- name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.rfc822Name);
- } else {
- name_size = ASN1_STRING_to_UTF8(
- &name, subject_alt_name->d.uniformResourceIdentifier);
- }
+ if (subject_alt_name->type == GEN_DNS) {
+ name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName);
+ } else if (subject_alt_name->type == GEN_EMAIL) {
+ name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.rfc822Name);
+ } else {
+ name_size = ASN1_STRING_to_UTF8(
+ &name, subject_alt_name->d.uniformResourceIdentifier);
+ }
if (name_size < 0) {
gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
result = TSI_INTERNAL_ERROR;
@@ -584,8 +584,8 @@ static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
break;
}
/* We don't need to free certificate_authority as its ownership has been
- transferred to the context. That is not the case for certificate
- though.
+ transferred to the context. That is not the case for certificate
+ though.
*/
}
} while (0);
@@ -835,8 +835,8 @@ static tsi_result populate_ssl_context(
}
/* Extracts the CN and the SANs from an X509 cert as a peer object. */
-tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
- const char* pem_cert, tsi_peer* peer) {
+tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
+ const char* pem_cert, tsi_peer* peer) {
tsi_result result = TSI_OK;
X509* cert = nullptr;
BIO* pem;
@@ -897,7 +897,7 @@ static tsi_result build_alpn_protocol_name_list(
// the server's certificate, but we need to pull it anyway, in case a higher
// layer wants to look at it. In this case the verification may fail, but
// we don't really care.
-static int NullVerifyCallback(int /*preverify_ok*/, X509_STORE_CTX* /*ctx*/) {
+static int NullVerifyCallback(int /*preverify_ok*/, X509_STORE_CTX* /*ctx*/) {
return 1;
}
@@ -1498,7 +1498,7 @@ static tsi_result ssl_handshaker_next(
tsi_handshaker* self, const unsigned char* received_bytes,
size_t received_bytes_size, const unsigned char** bytes_to_send,
size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result,
- tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
+ tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) {
/* Input sanity check. */
if ((received_bytes_size > 0 && received_bytes == nullptr) ||
bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
@@ -1708,9 +1708,9 @@ static void tsi_ssl_client_handshaker_factory_destroy(
gpr_free(self);
}
-static int client_handshaker_factory_npn_callback(
- SSL* /*ssl*/, unsigned char** out, unsigned char* outlen,
- const unsigned char* in, unsigned int inlen, void* arg) {
+static int client_handshaker_factory_npn_callback(
+ SSL* /*ssl*/, unsigned char** out, unsigned char* outlen,
+ const unsigned char* in, unsigned int inlen, void* arg) {
tsi_ssl_client_handshaker_factory* factory =
static_cast<tsi_ssl_client_handshaker_factory*>(arg);
return select_protocol_list((const unsigned char**)out, outlen,
@@ -1757,47 +1757,47 @@ static void tsi_ssl_server_handshaker_factory_destroy(
static int does_entry_match_name(y_absl::string_view entry,
y_absl::string_view name) {
- if (entry.empty()) return 0;
+ if (entry.empty()) return 0;
/* Take care of '.' terminations. */
- if (name.back() == '.') {
- name.remove_suffix(1);
+ if (name.back() == '.') {
+ name.remove_suffix(1);
}
- if (entry.back() == '.') {
- entry.remove_suffix(1);
- if (entry.empty()) return 0;
+ if (entry.back() == '.') {
+ entry.remove_suffix(1);
+ if (entry.empty()) return 0;
}
if (y_absl::EqualsIgnoreCase(name, entry)) {
return 1; /* Perfect match. */
}
- if (entry.front() != '*') return 0;
+ if (entry.front() != '*') return 0;
/* Wildchar subdomain matching. */
- if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
+ if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
gpr_log(GPR_ERROR, "Invalid wildchar entry.");
return 0;
}
- size_t name_subdomain_pos = name.find('.');
+ size_t name_subdomain_pos = name.find('.');
if (name_subdomain_pos == y_absl::string_view::npos) return 0;
- if (name_subdomain_pos >= name.size() - 2) return 0;
+ if (name_subdomain_pos >= name.size() - 2) return 0;
y_absl::string_view name_subdomain =
- name.substr(name_subdomain_pos + 1); /* Starts after the dot. */
- entry.remove_prefix(2); /* Remove *. */
- size_t dot = name_subdomain.find('.');
+ name.substr(name_subdomain_pos + 1); /* Starts after the dot. */
+ entry.remove_prefix(2); /* Remove *. */
+ size_t dot = name_subdomain.find('.');
if (dot == y_absl::string_view::npos || dot == name_subdomain.size() - 1) {
- gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s",
+ gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s",
TString(name_subdomain).c_str());
return 0;
}
- if (name_subdomain.back() == '.') {
- name_subdomain.remove_suffix(1);
+ if (name_subdomain.back() == '.') {
+ name_subdomain.remove_suffix(1);
}
return !entry.empty() && y_absl::EqualsIgnoreCase(name_subdomain, entry);
}
-static int ssl_server_handshaker_factory_servername_callback(SSL* ssl,
- int* /*ap*/,
+static int ssl_server_handshaker_factory_servername_callback(SSL* ssl,
+ int* /*ap*/,
void* arg) {
tsi_ssl_server_handshaker_factory* impl =
static_cast<tsi_ssl_server_handshaker_factory*>(arg);
@@ -1820,7 +1820,7 @@ static int ssl_server_handshaker_factory_servername_callback(SSL* ssl,
#if TSI_OPENSSL_ALPN_SUPPORT
static int server_handshaker_factory_alpn_callback(
- SSL* /*ssl*/, const unsigned char** out, unsigned char* outlen,
+ SSL* /*ssl*/, const unsigned char** out, unsigned char* outlen,
const unsigned char* in, unsigned int inlen, void* arg) {
tsi_ssl_server_handshaker_factory* factory =
static_cast<tsi_ssl_server_handshaker_factory*>(arg);
@@ -1831,7 +1831,7 @@ static int server_handshaker_factory_alpn_callback(
#endif /* TSI_OPENSSL_ALPN_SUPPORT */
static int server_handshaker_factory_npn_advertised_callback(
- SSL* /*ssl*/, const unsigned char** out, unsigned int* outlen, void* arg) {
+ SSL* /*ssl*/, const unsigned char** out, unsigned int* outlen, void* arg) {
tsi_ssl_server_handshaker_factory* factory =
static_cast<tsi_ssl_server_handshaker_factory*>(arg);
*out = factory->alpn_protocol_list;
@@ -1860,7 +1860,7 @@ static int server_handshaker_factory_new_session_callback(
return 0;
}
factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
- // Return 1 to indicate transferred ownership over the given session.
+ // Return 1 to indicate transferred ownership over the given session.
return 1;
}
@@ -2143,7 +2143,7 @@ tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
}
/* TODO(jboeuf): Add revocation verification. */
- result = tsi_ssl_extract_x509_subject_names_from_pem_cert(
+ result = tsi_ssl_extract_x509_subject_names_from_pem_cert(
options->pem_key_cert_pairs[i].cert_chain,
&impl->ssl_context_x509_subject_names[i]);
if (result != TSI_OK) break;
@@ -2188,9 +2188,9 @@ int tsi_ssl_peer_matches_name(const tsi_peer* peer, y_absl::string_view name) {
san_count++;
y_absl::string_view entry(property->value.data, property->value.length);
- if (!like_ip && does_entry_match_name(entry, name)) {
+ if (!like_ip && does_entry_match_name(entry, name)) {
return 1;
- } else if (like_ip && name == entry) {
+ } else if (like_ip && name == entry) {
/* IP Addresses are exact matches only. */
return 1;
}
@@ -2204,7 +2204,7 @@ int tsi_ssl_peer_matches_name(const tsi_peer* peer, y_absl::string_view name) {
if (san_count == 0 && cn_property != nullptr && !like_ip) {
if (does_entry_match_name(y_absl::string_view(cn_property->value.data,
cn_property->value.length),
- name)) {
+ name)) {
return 1;
}
}
diff --git a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.h b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.h
index 2f2dc08c05..82c2e88df4 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.h
+++ b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.h
@@ -120,7 +120,7 @@ tsi_result tsi_create_ssl_client_handshaker_factory(
const char** alpn_protocols, uint16_t num_alpn_protocols,
tsi_ssl_client_handshaker_factory** factory);
-struct tsi_ssl_client_handshaker_options {
+struct tsi_ssl_client_handshaker_options {
/* pem_key_cert_pair is a pointer to the object containing client's private
key and certificate chain. This parameter can be NULL if the client does
not have such a key/cert pair. */
@@ -157,19 +157,19 @@ struct tsi_ssl_client_handshaker_options {
tsi_tls_version min_tls_version;
tsi_tls_version max_tls_version;
- tsi_ssl_client_handshaker_options()
- : pem_key_cert_pair(nullptr),
- pem_root_certs(nullptr),
- root_store(nullptr),
- cipher_suites(nullptr),
- alpn_protocols(nullptr),
- num_alpn_protocols(0),
+ tsi_ssl_client_handshaker_options()
+ : pem_key_cert_pair(nullptr),
+ pem_root_certs(nullptr),
+ root_store(nullptr),
+ cipher_suites(nullptr),
+ alpn_protocols(nullptr),
+ num_alpn_protocols(0),
session_cache(nullptr),
skip_server_certificate_verification(false),
min_tls_version(tsi_tls_version::TSI_TLS1_2),
max_tls_version(tsi_tls_version::TSI_TLS1_3) {}
-};
-
+};
+
/* Creates a client handshaker factory.
- options is the options used to create a factory.
- factory is the address of the factory pointer to be created.
@@ -249,7 +249,7 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex(
const char* cipher_suites, const char** alpn_protocols,
uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory);
-struct tsi_ssl_server_handshaker_options {
+struct tsi_ssl_server_handshaker_options {
/* pem_key_cert_pairs is an array private key / certificate chains of the
server. */
const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs;
@@ -278,8 +278,8 @@ struct tsi_ssl_server_handshaker_options {
specified. If this parameter is 0, the other alpn parameters must be
NULL. */
uint16_t num_alpn_protocols;
- /* session_ticket_key is optional key for encrypting session keys. If
- parameter is not specified it must be NULL. */
+ /* session_ticket_key is optional key for encrypting session keys. If
+ parameter is not specified it must be NULL. */
const char* session_ticket_key;
/* session_ticket_key_size is a size of session ticket encryption key. */
size_t session_ticket_key_size;
@@ -287,20 +287,20 @@ struct tsi_ssl_server_handshaker_options {
tsi_tls_version min_tls_version;
tsi_tls_version max_tls_version;
- tsi_ssl_server_handshaker_options()
- : pem_key_cert_pairs(nullptr),
- num_key_cert_pairs(0),
- pem_client_root_certs(nullptr),
- client_certificate_request(TSI_DONT_REQUEST_CLIENT_CERTIFICATE),
- cipher_suites(nullptr),
- alpn_protocols(nullptr),
- num_alpn_protocols(0),
- session_ticket_key(nullptr),
+ tsi_ssl_server_handshaker_options()
+ : pem_key_cert_pairs(nullptr),
+ num_key_cert_pairs(0),
+ pem_client_root_certs(nullptr),
+ client_certificate_request(TSI_DONT_REQUEST_CLIENT_CERTIFICATE),
+ cipher_suites(nullptr),
+ alpn_protocols(nullptr),
+ num_alpn_protocols(0),
+ session_ticket_key(nullptr),
session_ticket_key_size(0),
min_tls_version(tsi_tls_version::TSI_TLS1_2),
max_tls_version(tsi_tls_version::TSI_TLS1_3) {}
-};
-
+};
+
/* Creates a server handshaker factory.
- options is the options used to create a factory.
- factory is the address of the factory pointer to be created.
@@ -354,10 +354,10 @@ const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
tsi_ssl_handshaker_factory* factory,
tsi_ssl_handshaker_factory_vtable* new_vtable);
-/* Exposed for testing only. */
-tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
- const char* pem_cert, tsi_peer* peer);
-
+/* Exposed for testing only. */
+tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
+ const char* pem_cert, tsi_peer* peer);
+
/* Exposed for testing only. */
tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain,
tsi_peer_property* property);
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/BUILD b/contrib/libs/grpc/src/core/tsi/test_creds/BUILD
index 94bb5d4bde..e801f3a45e 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/BUILD
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/BUILD
@@ -15,17 +15,17 @@
licenses(["notice"]) # Apache v2
exports_files([
- "ca.pem",
- "server1.key",
- "server1.pem",
- "server0.key",
- "server0.pem",
- "client.key",
- "client.pem",
- "badserver.key",
- "badserver.pem",
- "badclient.key",
- "badclient.pem",
- "multi-domain.key",
- "multi-domain.pem",
+ "ca.pem",
+ "server1.key",
+ "server1.pem",
+ "server0.key",
+ "server0.pem",
+ "client.key",
+ "client.pem",
+ "badserver.key",
+ "badserver.pem",
+ "badclient.key",
+ "badclient.pem",
+ "multi-domain.key",
+ "multi-domain.pem",
])
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/multi-domain.pem b/contrib/libs/grpc/src/core/tsi/test_creds/multi-domain.pem
index d4ff936fde..3df93ba192 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/multi-domain.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/multi-domain.pem
@@ -1,9 +1,9 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIID/jCCAuagAwIBAgIUV2eOzlQQj1U+++TDdNyRHjRNamQwDQYJKoZIhvcNAQEL
-BQAwSjELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJTRjEPMA0G
+BQAwSjELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJTRjEPMA0G
A1UECwwGR29vZ2xlMRAwDgYDVQQDDAd4cGlnb3JzMB4XDTIwMDYwNzIyNTk1MFoX
DTMwMDYwNTIyNTk1MFowSjELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYD
-VQQHDAJTRjEPMA0GA1UECwwGR29vZ2xlMRAwDgYDVQQDDAd4cGlnb3JzMIIBIjAN
+VQQHDAJTRjEPMA0GA1UECwwGR29vZ2xlMRAwDgYDVQQDDAd4cGlnb3JzMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArhlQWA9z/w9nk54QYWdIsz/p7qMz
QhDv4kLv5MsumQsyBBb8pLdGj8yVS3LAhwmlnDSVRT0qlQ1UZvUuWR1Mi5Z0ped5
ilJbWSOLQw1THBHa+yqX13gXPOpZv/dw6hQ4AGA5L3m3pEa//AdTiYVSURqMF4wF
@@ -21,4 +21,4 @@ AQBlLNl/uXN01VARQFd5CNFMhwez879uB5N3s/pGBjzE8Z+NA9YjsBFkBSQlebFM
nyFZ+jo2OS1lbv7kE7IW6slCXbCFaxPIKvjPbpGFngsLt44sZ9VvSJCeKhDglMfn
HKkhd4/UMnRn+8tZZ6eH/C5tpeKAChMUF+bkuwk3dBwnHq484KbBAKd2cwzZhTB7
8unku1S1GumvoEYAgbG1P4gC
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc b/contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc
index cec872690d..58d46a05e1 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc
+++ b/contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc
@@ -64,10 +64,10 @@ void tsi_zero_copy_grpc_protector_destroy(tsi_zero_copy_grpc_protector* self) {
if (self == nullptr) return;
self->vtable->destroy(self);
}
-
-tsi_result tsi_zero_copy_grpc_protector_max_frame_size(
+
+tsi_result tsi_zero_copy_grpc_protector_max_frame_size(
tsi_zero_copy_grpc_protector* self, size_t* max_frame_size) {
if (self == nullptr || max_frame_size == nullptr) return TSI_INVALID_ARGUMENT;
- if (self->vtable->max_frame_size == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->max_frame_size(self, max_frame_size);
-}
+ if (self->vtable->max_frame_size == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->max_frame_size(self, max_frame_size);
+}
diff --git a/contrib/libs/grpc/src/core/tsi/transport_security_grpc.h b/contrib/libs/grpc/src/core/tsi/transport_security_grpc.h
index 4779b686c6..f278c51b76 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security_grpc.h
+++ b/contrib/libs/grpc/src/core/tsi/transport_security_grpc.h
@@ -56,10 +56,10 @@ tsi_result tsi_zero_copy_grpc_protector_unprotect(
/* Destroys the tsi_zero_copy_grpc_protector object. */
void tsi_zero_copy_grpc_protector_destroy(tsi_zero_copy_grpc_protector* self);
-/* Returns value of max protected frame size. Useful for testing. */
-tsi_result tsi_zero_copy_grpc_protector_max_frame_size(
+/* Returns value of max protected frame size. Useful for testing. */
+tsi_result tsi_zero_copy_grpc_protector_max_frame_size(
tsi_zero_copy_grpc_protector* self, size_t* max_frame_size);
-
+
/* Base for tsi_zero_copy_grpc_protector implementations. */
struct tsi_zero_copy_grpc_protector_vtable {
tsi_result (*protect)(tsi_zero_copy_grpc_protector* self,
@@ -69,7 +69,7 @@ struct tsi_zero_copy_grpc_protector_vtable {
grpc_slice_buffer* protected_slices,
grpc_slice_buffer* unprotected_slices);
void (*destroy)(tsi_zero_copy_grpc_protector* self);
- tsi_result (*max_frame_size)(tsi_zero_copy_grpc_protector* self,
+ tsi_result (*max_frame_size)(tsi_zero_copy_grpc_protector* self,
size_t* max_frame_size);
};
struct tsi_zero_copy_grpc_protector {
diff --git a/contrib/libs/grpc/src/cpp/README.md b/contrib/libs/grpc/src/cpp/README.md
index 967a0a43b7..e7099c03aa 100755
--- a/contrib/libs/grpc/src/cpp/README.md
+++ b/contrib/libs/grpc/src/cpp/README.md
@@ -137,26 +137,26 @@ if you later want to remove the grpc and/or protobuf installation or upgrade to
## Packaging systems
-We do not officially support any packaging system for C++, but there are some community-maintained packages that are kept up-to-date
-and are known to work well. More contributions and support for popular packaging systems are welcome!
-
-### Install using vcpkg package
-gRPC is available using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
-
-```
-# install vcpkg package manager on your system using the official instructions
-git clone https://github.com/Microsoft/vcpkg.git
-cd vcpkg
-./bootstrap-vcpkg.sh
-./vcpkg integrate install
-
-# install gRPC using vcpkg package manager
-vcpkg install grpc
-```
-
-The gRPC port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
-
-
+We do not officially support any packaging system for C++, but there are some community-maintained packages that are kept up-to-date
+and are known to work well. More contributions and support for popular packaging systems are welcome!
+
+### Install using vcpkg package
+gRPC is available using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
+
+```
+# install vcpkg package manager on your system using the official instructions
+git clone https://github.com/Microsoft/vcpkg.git
+cd vcpkg
+./bootstrap-vcpkg.sh
+./vcpkg integrate install
+
+# install gRPC using vcpkg package manager
+vcpkg install grpc
+```
+
+The gRPC port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
+
+
## Examples & Additional Documentation
You can find out how to build and run our simplest gRPC C++ example in our
diff --git a/contrib/libs/grpc/src/cpp/client/channel_cc.cc b/contrib/libs/grpc/src/cpp/client/channel_cc.cc
index ac95c29efc..0d3fcc1444 100644
--- a/contrib/libs/grpc/src/cpp/client/channel_cc.cc
+++ b/contrib/libs/grpc/src/cpp/client/channel_cc.cc
@@ -43,11 +43,11 @@
namespace grpc {
-static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer;
+static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer;
Channel::Channel(const TString& host, grpc_channel* channel,
- std::vector<std::unique_ptr<
- ::grpc::experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators)
+ std::vector<std::unique_ptr<
+ ::grpc::experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators)
: host_(host), c_channel_(channel) {
interceptor_creators_ = std::move(interceptor_creators);
g_gli_initializer.summon();
@@ -101,9 +101,9 @@ void ChannelResetConnectionBackoff(Channel* channel) {
} // namespace experimental
-::grpc::internal::Call Channel::CreateCallInternal(
- const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context,
- ::grpc::CompletionQueue* cq, size_t interceptor_pos) {
+::grpc::internal::Call Channel::CreateCallInternal(
+ const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context,
+ ::grpc::CompletionQueue* cq, size_t interceptor_pos) {
const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = nullptr;
if (kRegistered) {
@@ -122,7 +122,7 @@ void ChannelResetConnectionBackoff(Channel* channel) {
SliceFromArray(method.name(), strlen(method.name()));
grpc_slice host_slice;
if (host_str != nullptr) {
- host_slice = ::grpc::SliceFromCopiedString(*host_str);
+ host_slice = ::grpc::SliceFromCopiedString(*host_str);
}
c_call = grpc_channel_create_call(
c_channel_, context->propagate_from_call_,
@@ -138,23 +138,23 @@ void ChannelResetConnectionBackoff(Channel* channel) {
// ClientRpcInfo should be set before call because set_call also checks
// whether the call has been cancelled, and if the call was cancelled, we
- // should notify the interceptors too.
+ // should notify the interceptors too.
auto* info =
context->set_client_rpc_info(method.name(), method.method_type(), this,
interceptor_creators_, interceptor_pos);
context->set_call(c_call, shared_from_this());
- return ::grpc::internal::Call(c_call, this, cq, info);
+ return ::grpc::internal::Call(c_call, this, cq, info);
}
-::grpc::internal::Call Channel::CreateCall(
- const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context,
- CompletionQueue* cq) {
+::grpc::internal::Call Channel::CreateCall(
+ const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context,
+ CompletionQueue* cq) {
return CreateCallInternal(method, context, cq, 0);
}
-void Channel::PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops,
- ::grpc::internal::Call* call) {
+void Channel::PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops,
+ ::grpc::internal::Call* call) {
ops->FillOps(
call); // Make a copy of call. It's fine since Call just has pointers
}
@@ -170,11 +170,11 @@ grpc_connectivity_state Channel::GetState(bool try_to_connect) {
namespace {
-class TagSaver final : public ::grpc::internal::CompletionQueueTag {
+class TagSaver final : public ::grpc::internal::CompletionQueueTag {
public:
explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver() override {}
- bool FinalizeResult(void** tag, bool* /*status*/) override {
+ bool FinalizeResult(void** tag, bool* /*status*/) override {
*tag = tag_;
delete this;
return true;
@@ -188,7 +188,7 @@ class TagSaver final : public ::grpc::internal::CompletionQueueTag {
void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
- ::grpc::CompletionQueue* cq, void* tag) {
+ ::grpc::CompletionQueue* cq, void* tag) {
TagSaver* tag_saver = new TagSaver(tag);
grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
cq->cq(), tag_saver);
@@ -196,7 +196,7 @@ void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) {
- ::grpc::CompletionQueue cq;
+ ::grpc::CompletionQueue cq;
bool ok = false;
void* tag = nullptr;
NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
@@ -208,17 +208,17 @@ bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
namespace {
class ShutdownCallback : public grpc_experimental_completion_queue_functor {
public:
- ShutdownCallback() {
- functor_run = &ShutdownCallback::Run;
- // Set inlineable to true since this callback is trivial and thus does not
- // need to be run from the executor (triggering a thread hop). This should
- // only be used by internal callbacks like this and not by user application
- // code.
- inlineable = true;
- }
+ ShutdownCallback() {
+ functor_run = &ShutdownCallback::Run;
+ // Set inlineable to true since this callback is trivial and thus does not
+ // need to be run from the executor (triggering a thread hop). This should
+ // only be used by internal callbacks like this and not by user application
+ // code.
+ inlineable = true;
+ }
// TakeCQ takes ownership of the cq into the shutdown callback
// so that the shutdown callback will be responsible for destroying it
- void TakeCQ(::grpc::CompletionQueue* cq) { cq_ = cq; }
+ void TakeCQ(::grpc::CompletionQueue* cq) { cq_ = cq; }
// The Run function will get invoked by the completion queue library
// when the shutdown is actually complete
@@ -229,17 +229,17 @@ class ShutdownCallback : public grpc_experimental_completion_queue_functor {
}
private:
- ::grpc::CompletionQueue* cq_ = nullptr;
+ ::grpc::CompletionQueue* cq_ = nullptr;
};
} // namespace
-::grpc::CompletionQueue* Channel::CallbackCQ() {
+::grpc::CompletionQueue* Channel::CallbackCQ() {
// TODO(vjpai): Consider using a single global CQ for the default CQ
// if there is no explicit per-channel CQ registered
- grpc::internal::MutexLock l(&mu_);
+ grpc::internal::MutexLock l(&mu_);
if (callback_cq_ == nullptr) {
auto* shutdown_callback = new ShutdownCallback;
- callback_cq_ = new ::grpc::CompletionQueue(grpc_completion_queue_attributes{
+ callback_cq_ = new ::grpc::CompletionQueue(grpc_completion_queue_attributes{
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
shutdown_callback});
diff --git a/contrib/libs/grpc/src/cpp/client/client_context.cc b/contrib/libs/grpc/src/cpp/client/client_context.cc
index b75343d089..e3cb5cef57 100644
--- a/contrib/libs/grpc/src/cpp/client/client_context.cc
+++ b/contrib/libs/grpc/src/cpp/client/client_context.cc
@@ -25,7 +25,7 @@
#include <grpc/support/string_util.h>
#include <grpcpp/impl/codegen/interceptor_common.h>
-#include <grpcpp/impl/codegen/sync.h>
+#include <grpcpp/impl/codegen/sync.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/security/credentials.h>
#include <grpcpp/server_context.h>
@@ -33,14 +33,14 @@
namespace grpc {
-class Channel;
-
+class Channel;
+
class DefaultGlobalClientCallbacks final
: public ClientContext::GlobalCallbacks {
public:
~DefaultGlobalClientCallbacks() override {}
- void DefaultConstructor(ClientContext* /*context*/) override {}
- void Destructor(ClientContext* /*context*/) override {}
+ void DefaultConstructor(ClientContext* /*context*/) override {}
+ void Destructor(ClientContext* /*context*/) override {}
};
static internal::GrpcLibraryInitializer g_gli_initializer;
@@ -72,23 +72,23 @@ ClientContext::~ClientContext() {
g_client_callbacks->Destructor(this);
}
-void ClientContext::set_credentials(
+void ClientContext::set_credentials(
const std::shared_ptr<CallCredentials>& creds) {
- creds_ = creds;
- // If call_ is set, we have already created the call, and set the call
- // credentials. This should only be done before we have started the batch
- // for sending initial metadata.
- if (creds_ != nullptr && call_ != nullptr) {
- if (!creds_->ApplyToCall(call_)) {
- SendCancelToInterceptors();
- grpc_call_cancel_with_status(call_, GRPC_STATUS_CANCELLED,
- "Failed to set credentials to rpc.",
- nullptr);
- }
- }
-}
-
-std::unique_ptr<ClientContext> ClientContext::FromInternalServerContext(
+ creds_ = creds;
+ // If call_ is set, we have already created the call, and set the call
+ // credentials. This should only be done before we have started the batch
+ // for sending initial metadata.
+ if (creds_ != nullptr && call_ != nullptr) {
+ if (!creds_->ApplyToCall(call_)) {
+ SendCancelToInterceptors();
+ grpc_call_cancel_with_status(call_, GRPC_STATUS_CANCELLED,
+ "Failed to set credentials to rpc.",
+ nullptr);
+ }
+ }
+}
+
+std::unique_ptr<ClientContext> ClientContext::FromInternalServerContext(
const grpc::ServerContextBase& context, PropagationOptions options) {
std::unique_ptr<ClientContext> ctx(new ClientContext);
ctx->propagate_from_call_ = context.call_.call;
@@ -96,17 +96,17 @@ std::unique_ptr<ClientContext> ClientContext::FromInternalServerContext(
return ctx;
}
-std::unique_ptr<ClientContext> ClientContext::FromServerContext(
+std::unique_ptr<ClientContext> ClientContext::FromServerContext(
const grpc::ServerContext& server_context, PropagationOptions options) {
- return FromInternalServerContext(server_context, options);
-}
-
-std::unique_ptr<ClientContext> ClientContext::FromCallbackServerContext(
+ return FromInternalServerContext(server_context, options);
+}
+
+std::unique_ptr<ClientContext> ClientContext::FromCallbackServerContext(
const grpc::CallbackServerContext& server_context,
- PropagationOptions options) {
- return FromInternalServerContext(server_context, options);
-}
-
+ PropagationOptions options) {
+ return FromInternalServerContext(server_context, options);
+}
+
void ClientContext::AddMetadata(const TString& meta_key,
const TString& meta_value) {
send_initial_metadata_.insert(std::make_pair(meta_key, meta_value));
diff --git a/contrib/libs/grpc/src/cpp/client/client_interceptor.cc b/contrib/libs/grpc/src/cpp/client/client_interceptor.cc
index a91950cae2..9b2f03b49a 100644
--- a/contrib/libs/grpc/src/cpp/client/client_interceptor.cc
+++ b/contrib/libs/grpc/src/cpp/client/client_interceptor.cc
@@ -28,17 +28,17 @@ experimental::ClientInterceptorFactoryInterface*
namespace experimental {
void RegisterGlobalClientInterceptorFactory(
ClientInterceptorFactoryInterface* factory) {
- if (internal::g_global_client_interceptor_factory != nullptr) {
- GPR_ASSERT(false &&
- "It is illegal to call RegisterGlobalClientInterceptorFactory "
- "multiple times.");
- }
+ if (internal::g_global_client_interceptor_factory != nullptr) {
+ GPR_ASSERT(false &&
+ "It is illegal to call RegisterGlobalClientInterceptorFactory "
+ "multiple times.");
+ }
internal::g_global_client_interceptor_factory = factory;
}
-
-// For testing purposes only.
-void TestOnlyResetGlobalClientInterceptorFactory() {
- internal::g_global_client_interceptor_factory = nullptr;
-}
+
+// For testing purposes only.
+void TestOnlyResetGlobalClientInterceptorFactory() {
+ internal::g_global_client_interceptor_factory = nullptr;
+}
} // namespace experimental
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/client/create_channel.cc b/contrib/libs/grpc/src/cpp/client/create_channel.cc
index 97327490ed..0a3863e83f 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel.cc
+++ b/contrib/libs/grpc/src/cpp/client/create_channel.cc
@@ -21,7 +21,7 @@
#include <grpcpp/channel.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/credentials.h>
#include <grpcpp/support/channel_arguments.h>
#include "src/cpp/client/create_channel_internal.h"
@@ -29,25 +29,25 @@
namespace grpc {
std::shared_ptr<grpc::Channel> CreateChannel(
const grpc::string& target,
- const std::shared_ptr<grpc::ChannelCredentials>& creds) {
+ const std::shared_ptr<grpc::ChannelCredentials>& creds) {
return CreateCustomChannel(target, creds, grpc::ChannelArguments());
}
std::shared_ptr<grpc::Channel> CreateCustomChannel(
const grpc::string& target,
- const std::shared_ptr<grpc::ChannelCredentials>& creds,
- const grpc::ChannelArguments& args) {
- grpc::GrpcLibraryCodegen
- init_lib; // We need to call init in case of bad creds.
- return creds ? creds->CreateChannelImpl(target, args)
- : grpc::CreateChannelInternal(
+ const std::shared_ptr<grpc::ChannelCredentials>& creds,
+ const grpc::ChannelArguments& args) {
+ grpc::GrpcLibraryCodegen
+ init_lib; // We need to call init in case of bad creds.
+ return creds ? creds->CreateChannelImpl(target, args)
+ : grpc::CreateChannelInternal(
"",
grpc_lame_client_channel_create(
nullptr, GRPC_STATUS_INVALID_ARGUMENT,
"Invalid credentials."),
std::vector<std::unique_ptr<
- grpc::experimental::
- ClientInterceptorFactoryInterface>>());
+ grpc::experimental::
+ ClientInterceptorFactoryInterface>>());
}
namespace experimental {
@@ -62,23 +62,23 @@ namespace experimental {
/// hold an object or is invalid, a lame channel (one on which all operations
/// fail) is returned.
/// \param args Options for channel creation.
-std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors(
+std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors(
const TString& target,
- const std::shared_ptr<grpc::ChannelCredentials>& creds,
- const grpc::ChannelArguments& args,
+ const std::shared_ptr<grpc::ChannelCredentials>& creds,
+ const grpc::ChannelArguments& args,
std::vector<
- std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) {
- grpc::GrpcLibraryCodegen
- init_lib; // We need to call init in case of bad creds.
+ grpc::GrpcLibraryCodegen
+ init_lib; // We need to call init in case of bad creds.
return creds ? creds->CreateChannelWithInterceptors(
target, args, std::move(interceptor_creators))
- : grpc::CreateChannelInternal(
+ : grpc::CreateChannelInternal(
"",
grpc_lame_client_channel_create(
nullptr, GRPC_STATUS_INVALID_ARGUMENT,
"Invalid credentials."),
- std::move(interceptor_creators));
+ std::move(interceptor_creators));
}
} // namespace experimental
diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc
index da2a878a22..a1ce29c8c0 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc
+++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc
@@ -26,11 +26,11 @@ namespace grpc {
std::shared_ptr<Channel> CreateChannelInternal(
const TString& host, grpc_channel* c_channel,
- std::vector<std::unique_ptr<
- ::grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::vector<std::unique_ptr<
+ ::grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) {
return std::shared_ptr<Channel>(
new Channel(host, c_channel, std::move(interceptor_creators)));
}
-
+
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h
index 09d4e56b02..8932d12a4f 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h
+++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h
@@ -21,7 +21,7 @@
#include <memory>
-#include <grpcpp/channel.h>
+#include <grpcpp/channel.h>
#include <grpcpp/impl/codegen/client_interceptor.h>
#include <grpcpp/support/config.h>
@@ -31,8 +31,8 @@ namespace grpc {
std::shared_ptr<Channel> CreateChannelInternal(
const TString& host, grpc_channel* c_channel,
- std::vector<std::unique_ptr<
- ::grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::vector<std::unique_ptr<
+ ::grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc
index db09eda8a6..57b0cc7da6 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc
+++ b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc
@@ -20,19 +20,19 @@
#include <grpc/grpc_posix.h>
#include <grpcpp/channel.h>
#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/support/channel_arguments.h>
+#include <grpcpp/support/channel_arguments.h>
#include "src/cpp/client/create_channel_internal.h"
namespace grpc {
-class ChannelArguments;
-
+class ChannelArguments;
+
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
std::shared_ptr<Channel> CreateInsecureChannelFromFd(const TString& target,
int fd) {
- grpc::internal::GrpcLibrary init_lib;
+ grpc::internal::GrpcLibrary init_lib;
init_lib.init();
return CreateChannelInternal(
"", grpc_insecure_channel_create_from_fd(target.c_str(), fd, nullptr),
@@ -58,9 +58,9 @@ namespace experimental {
std::shared_ptr<Channel> CreateCustomInsecureChannelWithInterceptorsFromFd(
const TString& target, int fd, const ChannelArguments& args,
std::vector<
- std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) {
- grpc::internal::GrpcLibrary init_lib;
+ grpc::internal::GrpcLibrary init_lib;
init_lib.init();
grpc_channel_args channel_args;
args.SetChannelArgs(&channel_args);
diff --git a/contrib/libs/grpc/src/cpp/client/credentials_cc.cc b/contrib/libs/grpc/src/cpp/client/credentials_cc.cc
index 9dfb2f491c..99cf583f72 100644
--- a/contrib/libs/grpc/src/cpp/client/credentials_cc.cc
+++ b/contrib/libs/grpc/src/cpp/client/credentials_cc.cc
@@ -21,7 +21,7 @@
namespace grpc {
-static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
+static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
ChannelCredentials::ChannelCredentials() { g_gli_initializer.summon(); }
ChannelCredentials::~ChannelCredentials() {}
diff --git a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc
index e5bafff70a..8820efb1ee 100644
--- a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc
@@ -29,22 +29,22 @@ namespace grpc {
namespace {
class InsecureChannelCredentialsImpl final : public ChannelCredentials {
public:
- std::shared_ptr<Channel> CreateChannelImpl(
+ std::shared_ptr<Channel> CreateChannelImpl(
const TString& target, const ChannelArguments& args) override {
return CreateChannelWithInterceptors(
target, args,
std::vector<std::unique_ptr<
- grpc::experimental::ClientInterceptorFactoryInterface>>());
+ grpc::experimental::ClientInterceptorFactoryInterface>>());
}
- std::shared_ptr<Channel> CreateChannelWithInterceptors(
+ std::shared_ptr<Channel> CreateChannelWithInterceptors(
const TString& target, const ChannelArguments& args,
- std::vector<std::unique_ptr<
- grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::vector<std::unique_ptr<
+ grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) override {
grpc_channel_args channel_args;
args.SetChannelArgs(&channel_args);
- return ::grpc::CreateChannelInternal(
+ return ::grpc::CreateChannelInternal(
"",
grpc_insecure_channel_create(target.c_str(), &channel_args, nullptr),
std::move(interceptor_creators));
diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc
index 0f6db3caa5..c31d8fef8e 100644
--- a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc
@@ -17,53 +17,53 @@
*/
#include "src/cpp/client/secure_credentials.h"
-
-#include <grpc/impl/codegen/slice.h>
-#include <grpc/slice.h>
+
+#include <grpc/impl/codegen/slice.h>
+#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpcpp/channel.h>
-#include <grpcpp/impl/codegen/status.h>
+#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/support/channel_arguments.h>
-
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/load_file.h"
-#include "src/core/lib/json/json.h"
-#include "src/core/lib/security/transport/auth_filters.h"
-#include "src/core/lib/security/util/json_util.h"
+
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/load_file.h"
+#include "src/core/lib/json/json.h"
+#include "src/core/lib/security/transport/auth_filters.h"
+#include "src/core/lib/security/util/json_util.h"
#include "src/cpp/client/create_channel_internal.h"
#include "src/cpp/common/secure_auth_context.h"
namespace grpc {
-static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
+static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
SecureChannelCredentials::SecureChannelCredentials(
grpc_channel_credentials* c_creds)
: c_creds_(c_creds) {
g_gli_initializer.summon();
}
-std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl(
+std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl(
const TString& target, const ChannelArguments& args) {
return CreateChannelWithInterceptors(
target, args,
- std::vector<std::unique_ptr<
- grpc::experimental::ClientInterceptorFactoryInterface>>());
+ std::vector<std::unique_ptr<
+ grpc::experimental::ClientInterceptorFactoryInterface>>());
}
-std::shared_ptr<Channel>
+std::shared_ptr<Channel>
SecureChannelCredentials::CreateChannelWithInterceptors(
const TString& target, const ChannelArguments& args,
std::vector<
- std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) {
grpc_channel_args channel_args;
args.SetChannelArgs(&channel_args);
- return ::grpc::CreateChannelInternal(
+ return ::grpc::CreateChannelInternal(
args.GetSslTargetNameOverride(),
grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args,
nullptr),
@@ -96,7 +96,7 @@ std::shared_ptr<CallCredentials> WrapCallCredentials(
} // namespace
std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
return WrapChannelCredentials(
grpc_google_default_credentials_create(nullptr));
}
@@ -104,7 +104,7 @@ std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
// Builds SSL Credentials given SSL specific options
std::shared_ptr<ChannelCredentials> SslCredentials(
const SslCredentialsOptions& options) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};
@@ -117,139 +117,139 @@ std::shared_ptr<ChannelCredentials> SslCredentials(
namespace experimental {
-namespace {
-
-void ClearStsCredentialsOptions(StsCredentialsOptions* options) {
- if (options == nullptr) return;
- options->token_exchange_service_uri.clear();
- options->resource.clear();
- options->audience.clear();
- options->scope.clear();
- options->requested_token_type.clear();
- options->subject_token_path.clear();
- options->subject_token_type.clear();
- options->actor_token_path.clear();
- options->actor_token_type.clear();
-}
-
-} // namespace
-
-// Builds STS credentials options from JSON.
+namespace {
+
+void ClearStsCredentialsOptions(StsCredentialsOptions* options) {
+ if (options == nullptr) return;
+ options->token_exchange_service_uri.clear();
+ options->resource.clear();
+ options->audience.clear();
+ options->scope.clear();
+ options->requested_token_type.clear();
+ options->subject_token_path.clear();
+ options->subject_token_type.clear();
+ options->actor_token_path.clear();
+ options->actor_token_type.clear();
+}
+
+} // namespace
+
+// Builds STS credentials options from JSON.
grpc::Status StsCredentialsOptionsFromJson(const TString& json_string,
- StsCredentialsOptions* options) {
- if (options == nullptr) {
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
- "options cannot be nullptr.");
- }
- ClearStsCredentialsOptions(options);
+ StsCredentialsOptions* options) {
+ if (options == nullptr) {
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+ "options cannot be nullptr.");
+ }
+ ClearStsCredentialsOptions(options);
grpc_error* error = GRPC_ERROR_NONE;
grpc_core::Json json = grpc_core::Json::Parse(json_string.c_str(), &error);
if (error != GRPC_ERROR_NONE ||
json.type() != grpc_core::Json::Type::OBJECT) {
GRPC_ERROR_UNREF(error);
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Invalid json.");
- }
-
- // Required fields.
- const char* value = grpc_json_get_string_property(
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Invalid json.");
+ }
+
+ // Required fields.
+ const char* value = grpc_json_get_string_property(
json, "token_exchange_service_uri", nullptr);
- if (value == nullptr) {
- ClearStsCredentialsOptions(options);
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
- "token_exchange_service_uri must be specified.");
- }
- options->token_exchange_service_uri.assign(value);
+ if (value == nullptr) {
+ ClearStsCredentialsOptions(options);
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+ "token_exchange_service_uri must be specified.");
+ }
+ options->token_exchange_service_uri.assign(value);
value = grpc_json_get_string_property(json, "subject_token_path", nullptr);
- if (value == nullptr) {
- ClearStsCredentialsOptions(options);
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
- "subject_token_path must be specified.");
- }
- options->subject_token_path.assign(value);
+ if (value == nullptr) {
+ ClearStsCredentialsOptions(options);
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+ "subject_token_path must be specified.");
+ }
+ options->subject_token_path.assign(value);
value = grpc_json_get_string_property(json, "subject_token_type", nullptr);
- if (value == nullptr) {
- ClearStsCredentialsOptions(options);
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
- "subject_token_type must be specified.");
- }
- options->subject_token_type.assign(value);
-
- // Optional fields.
+ if (value == nullptr) {
+ ClearStsCredentialsOptions(options);
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+ "subject_token_type must be specified.");
+ }
+ options->subject_token_type.assign(value);
+
+ // Optional fields.
value = grpc_json_get_string_property(json, "resource", nullptr);
- if (value != nullptr) options->resource.assign(value);
+ if (value != nullptr) options->resource.assign(value);
value = grpc_json_get_string_property(json, "audience", nullptr);
- if (value != nullptr) options->audience.assign(value);
+ if (value != nullptr) options->audience.assign(value);
value = grpc_json_get_string_property(json, "scope", nullptr);
- if (value != nullptr) options->scope.assign(value);
+ if (value != nullptr) options->scope.assign(value);
value = grpc_json_get_string_property(json, "requested_token_type", nullptr);
- if (value != nullptr) options->requested_token_type.assign(value);
+ if (value != nullptr) options->requested_token_type.assign(value);
value = grpc_json_get_string_property(json, "actor_token_path", nullptr);
- if (value != nullptr) options->actor_token_path.assign(value);
+ if (value != nullptr) options->actor_token_path.assign(value);
value = grpc_json_get_string_property(json, "actor_token_type", nullptr);
- if (value != nullptr) options->actor_token_type.assign(value);
-
- return grpc::Status();
-}
-
-// Builds STS credentials Options from the $STS_CREDENTIALS env var.
-grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options) {
- if (options == nullptr) {
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
- "options cannot be nullptr.");
- }
- ClearStsCredentialsOptions(options);
- grpc_slice json_string = grpc_empty_slice();
- char* sts_creds_path = gpr_getenv("STS_CREDENTIALS");
- grpc_error* error = GRPC_ERROR_NONE;
- grpc::Status status;
- auto cleanup = [&json_string, &sts_creds_path, &error, &status]() {
- grpc_slice_unref_internal(json_string);
- gpr_free(sts_creds_path);
- GRPC_ERROR_UNREF(error);
- return status;
- };
-
- if (sts_creds_path == nullptr) {
- status = grpc::Status(grpc::StatusCode::NOT_FOUND,
- "STS_CREDENTIALS environment variable not set.");
- return cleanup();
- }
- error = grpc_load_file(sts_creds_path, 1, &json_string);
- if (error != GRPC_ERROR_NONE) {
- status =
- grpc::Status(grpc::StatusCode::NOT_FOUND, grpc_error_string(error));
- return cleanup();
- }
- status = StsCredentialsOptionsFromJson(
- reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(json_string)),
- options);
- return cleanup();
-}
-
-// C++ to Core STS Credentials options.
-grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
- const StsCredentialsOptions& options) {
- grpc_sts_credentials_options opts;
- memset(&opts, 0, sizeof(opts));
- opts.token_exchange_service_uri = options.token_exchange_service_uri.c_str();
- opts.resource = options.resource.c_str();
- opts.audience = options.audience.c_str();
- opts.scope = options.scope.c_str();
- opts.requested_token_type = options.requested_token_type.c_str();
- opts.subject_token_path = options.subject_token_path.c_str();
- opts.subject_token_type = options.subject_token_type.c_str();
- opts.actor_token_path = options.actor_token_path.c_str();
- opts.actor_token_type = options.actor_token_type.c_str();
- return opts;
-}
-
-// Builds STS credentials.
-std::shared_ptr<CallCredentials> StsCredentials(
- const StsCredentialsOptions& options) {
- auto opts = StsCredentialsCppToCoreOptions(options);
- return WrapCallCredentials(grpc_sts_credentials_create(&opts, nullptr));
-}
-
+ if (value != nullptr) options->actor_token_type.assign(value);
+
+ return grpc::Status();
+}
+
+// Builds STS credentials Options from the $STS_CREDENTIALS env var.
+grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options) {
+ if (options == nullptr) {
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+ "options cannot be nullptr.");
+ }
+ ClearStsCredentialsOptions(options);
+ grpc_slice json_string = grpc_empty_slice();
+ char* sts_creds_path = gpr_getenv("STS_CREDENTIALS");
+ grpc_error* error = GRPC_ERROR_NONE;
+ grpc::Status status;
+ auto cleanup = [&json_string, &sts_creds_path, &error, &status]() {
+ grpc_slice_unref_internal(json_string);
+ gpr_free(sts_creds_path);
+ GRPC_ERROR_UNREF(error);
+ return status;
+ };
+
+ if (sts_creds_path == nullptr) {
+ status = grpc::Status(grpc::StatusCode::NOT_FOUND,
+ "STS_CREDENTIALS environment variable not set.");
+ return cleanup();
+ }
+ error = grpc_load_file(sts_creds_path, 1, &json_string);
+ if (error != GRPC_ERROR_NONE) {
+ status =
+ grpc::Status(grpc::StatusCode::NOT_FOUND, grpc_error_string(error));
+ return cleanup();
+ }
+ status = StsCredentialsOptionsFromJson(
+ reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(json_string)),
+ options);
+ return cleanup();
+}
+
+// C++ to Core STS Credentials options.
+grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
+ const StsCredentialsOptions& options) {
+ grpc_sts_credentials_options opts;
+ memset(&opts, 0, sizeof(opts));
+ opts.token_exchange_service_uri = options.token_exchange_service_uri.c_str();
+ opts.resource = options.resource.c_str();
+ opts.audience = options.audience.c_str();
+ opts.scope = options.scope.c_str();
+ opts.requested_token_type = options.requested_token_type.c_str();
+ opts.subject_token_path = options.subject_token_path.c_str();
+ opts.subject_token_type = options.subject_token_type.c_str();
+ opts.actor_token_path = options.actor_token_path.c_str();
+ opts.actor_token_type = options.actor_token_type.c_str();
+ return opts;
+}
+
+// Builds STS credentials.
+std::shared_ptr<CallCredentials> StsCredentials(
+ const StsCredentialsOptions& options) {
+ auto opts = StsCredentialsCppToCoreOptions(options);
+ return WrapCallCredentials(grpc_sts_credentials_create(&opts, nullptr));
+}
+
std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
std::unique_ptr<MetadataCredentialsPlugin> plugin,
grpc_security_level min_security_level) {
@@ -268,12 +268,12 @@ std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
// Builds ALTS Credentials given ALTS specific options
std::shared_ptr<ChannelCredentials> AltsCredentials(
const AltsCredentialsOptions& options) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
grpc_alts_credentials_options* c_options =
grpc_alts_credentials_client_options_create();
- for (const auto& service_account : options.target_service_accounts) {
+ for (const auto& service_account : options.target_service_accounts) {
grpc_alts_credentials_client_options_add_target_service_account(
- c_options, service_account.c_str());
+ c_options, service_account.c_str());
}
grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
grpc_alts_credentials_options_destroy(c_options);
@@ -283,22 +283,22 @@ std::shared_ptr<ChannelCredentials> AltsCredentials(
// Builds Local Credentials
std::shared_ptr<ChannelCredentials> LocalCredentials(
grpc_local_connect_type type) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
return WrapChannelCredentials(grpc_local_credentials_create(type));
}
-// Builds TLS Credentials given TLS options.
-std::shared_ptr<ChannelCredentials> TlsCredentials(
- const TlsCredentialsOptions& options) {
- return WrapChannelCredentials(
+// Builds TLS Credentials given TLS options.
+std::shared_ptr<ChannelCredentials> TlsCredentials(
+ const TlsCredentialsOptions& options) {
+ return WrapChannelCredentials(
grpc_tls_credentials_create(options.c_credentials_options()));
-}
-
+}
+
} // namespace experimental
// Builds credentials for use when running in GCE
std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
return WrapCallCredentials(
grpc_google_compute_engine_credentials_create(nullptr));
}
@@ -306,7 +306,7 @@ std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
// Builds JWT credentials.
std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
const TString& json_key, long token_lifetime_seconds) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
if (token_lifetime_seconds <= 0) {
gpr_log(GPR_ERROR,
"Trying to create JWTCredentials with non-positive lifetime");
@@ -321,7 +321,7 @@ std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
// Builds refresh token credentials.
std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
const TString& json_refresh_token) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
return WrapCallCredentials(grpc_google_refresh_token_credentials_create(
json_refresh_token.c_str(), nullptr));
}
@@ -329,7 +329,7 @@ std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
// Builds access token credentials.
std::shared_ptr<CallCredentials> AccessTokenCredentials(
const TString& access_token) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
return WrapCallCredentials(
grpc_access_token_credentials_create(access_token.c_str(), nullptr));
}
@@ -338,7 +338,7 @@ std::shared_ptr<CallCredentials> AccessTokenCredentials(
std::shared_ptr<CallCredentials> GoogleIAMCredentials(
const TString& authorization_token,
const TString& authority_selector) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
return WrapCallCredentials(grpc_google_iam_credentials_create(
authorization_token.c_str(), authority_selector.c_str(), nullptr));
}
@@ -374,27 +374,27 @@ std::shared_ptr<CallCredentials> CompositeCallCredentials(
return nullptr;
}
-std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin> plugin) {
- grpc::GrpcLibraryCodegen init; // To call grpc_init().
- const char* type = plugin->GetType();
- grpc::MetadataCredentialsPluginWrapper* wrapper =
- new grpc::MetadataCredentialsPluginWrapper(std::move(plugin));
- grpc_metadata_credentials_plugin c_plugin = {
- grpc::MetadataCredentialsPluginWrapper::GetMetadata,
+std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin> plugin) {
+ grpc::GrpcLibraryCodegen init; // To call grpc_init().
+ const char* type = plugin->GetType();
+ grpc::MetadataCredentialsPluginWrapper* wrapper =
+ new grpc::MetadataCredentialsPluginWrapper(std::move(plugin));
+ grpc_metadata_credentials_plugin c_plugin = {
+ grpc::MetadataCredentialsPluginWrapper::GetMetadata,
grpc::MetadataCredentialsPluginWrapper::DebugString,
- grpc::MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
+ grpc::MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
return WrapCallCredentials(grpc_metadata_credentials_create_from_plugin(
c_plugin, GRPC_PRIVACY_AND_INTEGRITY, nullptr));
-}
-
-namespace {
-void DeleteWrapper(void* wrapper, grpc_error* /*ignored*/) {
+}
+
+namespace {
+void DeleteWrapper(void* wrapper, grpc_error* /*ignored*/) {
MetadataCredentialsPluginWrapper* w =
static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
delete w;
}
-} // namespace
+} // namespace
char* MetadataCredentialsPluginWrapper::DebugString(void* wrapper) {
GPR_ASSERT(wrapper);
@@ -403,14 +403,14 @@ char* MetadataCredentialsPluginWrapper::DebugString(void* wrapper) {
return gpr_strdup(w->plugin_->DebugString().c_str());
}
-void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
- if (wrapper == nullptr) return;
- grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_core::Executor::Run(GRPC_CLOSURE_CREATE(DeleteWrapper, wrapper, nullptr),
- GRPC_ERROR_NONE);
-}
-
+void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
+ if (wrapper == nullptr) return;
+ grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
+ grpc_core::Executor::Run(GRPC_CLOSURE_CREATE(DeleteWrapper, wrapper, nullptr),
+ GRPC_ERROR_NONE);
+}
+
int MetadataCredentialsPluginWrapper::GetMetadata(
void* wrapper, grpc_auth_metadata_context context,
grpc_credentials_plugin_metadata_cb cb, void* user_data,
@@ -424,18 +424,18 @@ int MetadataCredentialsPluginWrapper::GetMetadata(
*num_creds_md = 0;
*status = GRPC_STATUS_OK;
*error_details = nullptr;
- return 1;
+ return 1;
}
if (w->plugin_->IsBlocking()) {
- // The internals of context may be destroyed if GetMetadata is cancelled.
- // Make a copy for InvokePlugin.
- grpc_auth_metadata_context context_copy = grpc_auth_metadata_context();
- grpc_auth_metadata_context_copy(&context, &context_copy);
+ // The internals of context may be destroyed if GetMetadata is cancelled.
+ // Make a copy for InvokePlugin.
+ grpc_auth_metadata_context context_copy = grpc_auth_metadata_context();
+ grpc_auth_metadata_context_copy(&context, &context_copy);
// Asynchronous return.
- w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable {
+ w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable {
w->MetadataCredentialsPluginWrapper::InvokePlugin(
- context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr);
- grpc_auth_metadata_context_reset(&context_copy);
+ context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr);
+ grpc_auth_metadata_context_reset(&context_copy);
});
return 0;
} else {
@@ -449,9 +449,9 @@ int MetadataCredentialsPluginWrapper::GetMetadata(
namespace {
void UnrefMetadata(const std::vector<grpc_metadata>& md) {
- for (const auto& metadatum : md) {
- grpc_slice_unref(metadatum.key);
- grpc_slice_unref(metadatum.value);
+ for (const auto& metadatum : md) {
+ grpc_slice_unref(metadatum.key);
+ grpc_slice_unref(metadatum.value);
}
}
@@ -471,10 +471,10 @@ void MetadataCredentialsPluginWrapper::InvokePlugin(
Status status = plugin_->GetMetadata(context.service_url, context.method_name,
cpp_channel_auth_context, &metadata);
std::vector<grpc_metadata> md;
- for (auto& metadatum : metadata) {
+ for (auto& metadatum : metadata) {
grpc_metadata md_entry;
- md_entry.key = SliceFromCopiedString(metadatum.first);
- md_entry.value = SliceFromCopiedString(metadatum.second);
+ md_entry.key = SliceFromCopiedString(metadatum.first);
+ md_entry.value = SliceFromCopiedString(metadatum.second);
md_entry.flags = 0;
md.push_back(md_entry);
}
diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.h b/contrib/libs/grpc/src/cpp/client/secure_credentials.h
index 4fc79346bf..16f6b9c805 100644
--- a/contrib/libs/grpc/src/cpp/client/secure_credentials.h
+++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.h
@@ -22,7 +22,7 @@
#include <grpc/grpc_security.h>
#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/tls_credentials_options.h>
+#include <grpcpp/security/tls_credentials_options.h>
#include <grpcpp/support/config.h>
#include "y_absl/strings/str_cat.h"
@@ -31,8 +31,8 @@
namespace grpc {
-class Channel;
-
+class Channel;
+
class SecureChannelCredentials final : public ChannelCredentials {
public:
explicit SecureChannelCredentials(grpc_channel_credentials* c_creds);
@@ -41,16 +41,16 @@ class SecureChannelCredentials final : public ChannelCredentials {
}
grpc_channel_credentials* GetRawCreds() { return c_creds_; }
- std::shared_ptr<Channel> CreateChannelImpl(
+ std::shared_ptr<Channel> CreateChannelImpl(
const TString& target, const ChannelArguments& args) override;
SecureChannelCredentials* AsSecureCredentials() override { return this; }
private:
- std::shared_ptr<Channel> CreateChannelWithInterceptors(
+ std::shared_ptr<Channel> CreateChannelWithInterceptors(
const TString& target, const ChannelArguments& args,
- std::vector<std::unique_ptr<
- ::grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::vector<std::unique_ptr<
+ ::grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) override;
grpc_channel_credentials* const c_creds_;
};
@@ -74,16 +74,16 @@ class SecureCallCredentials final : public CallCredentials {
grpc_call_credentials* const c_creds_;
};
-namespace experimental {
-
-// Transforms C++ STS Credentials options to core options. The pointers of the
-// resulting core options point to the memory held by the C++ options so C++
-// options need to be kept alive until after the core credentials creation.
-grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
- const StsCredentialsOptions& options);
-
-} // namespace experimental
-
+namespace experimental {
+
+// Transforms C++ STS Credentials options to core options. The pointers of the
+// resulting core options point to the memory held by the C++ options so C++
+// options need to be kept alive until after the core credentials creation.
+grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
+ const StsCredentialsOptions& options);
+
+} // namespace experimental
+
class MetadataCredentialsPluginWrapper final : private GrpcLibraryCodegen {
public:
static void Destroy(void* wrapper);
diff --git a/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc b/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc
index e1e47cbb17..a79c211ba0 100644
--- a/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc
+++ b/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc
@@ -20,7 +20,7 @@
#include <grpcpp/impl/codegen/grpc_library.h>
/// Null-initializes the global gRPC variables for the codegen library. These
-/// stay null in the absence of grpc++ library. In this case, no gRPC
+/// stay null in the absence of grpc++ library. In this case, no gRPC
/// features such as the ability to perform calls will be available. Trying to
/// perform them would result in a segmentation fault when trying to deference
/// the following nulled globals. These should be associated with actual
diff --git a/contrib/libs/grpc/src/cpp/common/alarm.cc b/contrib/libs/grpc/src/cpp/common/alarm.cc
index a2612874b2..bfbf26ed4d 100644
--- a/contrib/libs/grpc/src/cpp/common/alarm.cc
+++ b/contrib/libs/grpc/src/cpp/common/alarm.cc
@@ -42,7 +42,7 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag {
grpc_timer_init_unset(&timer_);
}
~AlarmImpl() {}
- bool FinalizeResult(void** tag, bool* /*status*/) override {
+ bool FinalizeResult(void** tag, bool* /*status*/) override {
*tag = tag_;
Unref();
return true;
@@ -54,23 +54,23 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag {
cq_ = cq->cq();
tag_ = tag;
GPR_ASSERT(grpc_cq_begin_op(cq_, this));
- GRPC_CLOSURE_INIT(
- &on_alarm_,
- [](void* arg, grpc_error* error) {
- // queue the op on the completion queue
- AlarmImpl* alarm = static_cast<AlarmImpl*>(arg);
- alarm->Ref();
- // Preserve the cq and reset the cq_ so that the alarm
- // can be reset when the alarm tag is delivered.
- grpc_completion_queue* cq = alarm->cq_;
- alarm->cq_ = nullptr;
- grpc_cq_end_op(
- cq, alarm, error,
- [](void* /*arg*/, grpc_cq_completion* /*completion*/) {}, arg,
- &alarm->completion_);
- GRPC_CQ_INTERNAL_UNREF(cq, "alarm");
- },
- this, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(
+ &on_alarm_,
+ [](void* arg, grpc_error* error) {
+ // queue the op on the completion queue
+ AlarmImpl* alarm = static_cast<AlarmImpl*>(arg);
+ alarm->Ref();
+ // Preserve the cq and reset the cq_ so that the alarm
+ // can be reset when the alarm tag is delivered.
+ grpc_completion_queue* cq = alarm->cq_;
+ alarm->cq_ = nullptr;
+ grpc_cq_end_op(
+ cq, alarm, error,
+ [](void* /*arg*/, grpc_cq_completion* /*completion*/) {}, arg,
+ &alarm->completion_);
+ GRPC_CQ_INTERNAL_UNREF(cq, "alarm");
+ },
+ this, grpc_schedule_on_exec_ctx);
grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline),
&on_alarm_);
}
diff --git a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc
index 5a5dd91b5e..63232a5129 100644
--- a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc
+++ b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc
@@ -31,7 +31,7 @@ namespace grpc {
ChannelArguments::ChannelArguments() {
// This will be ignored if used on the server side.
- SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, "grpc-c++/" + grpc::Version());
+ SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, "grpc-c++/" + grpc::Version());
}
ChannelArguments::ChannelArguments(const ChannelArguments& other)
@@ -39,26 +39,26 @@ ChannelArguments::ChannelArguments(const ChannelArguments& other)
args_.reserve(other.args_.size());
auto list_it_dst = strings_.begin();
auto list_it_src = other.strings_.begin();
- for (const auto& a : other.args_) {
+ for (const auto& a : other.args_) {
grpc_arg ap;
- ap.type = a.type;
- GPR_ASSERT(list_it_src->c_str() == a.key);
+ ap.type = a.type;
+ GPR_ASSERT(list_it_src->c_str() == a.key);
ap.key = const_cast<char*>(list_it_dst->c_str());
++list_it_src;
++list_it_dst;
- switch (a.type) {
+ switch (a.type) {
case GRPC_ARG_INTEGER:
- ap.value.integer = a.value.integer;
+ ap.value.integer = a.value.integer;
break;
case GRPC_ARG_STRING:
- GPR_ASSERT(list_it_src->c_str() == a.value.string);
+ GPR_ASSERT(list_it_src->c_str() == a.value.string);
ap.value.string = const_cast<char*>(list_it_dst->c_str());
++list_it_src;
++list_it_dst;
break;
case GRPC_ARG_POINTER:
- ap.value.pointer = a.value.pointer;
- ap.value.pointer.p = a.value.pointer.vtable->copy(ap.value.pointer.p);
+ ap.value.pointer = a.value.pointer;
+ ap.value.pointer.p = a.value.pointer.vtable->copy(ap.value.pointer.p);
break;
}
args_.push_back(ap);
@@ -67,9 +67,9 @@ ChannelArguments::ChannelArguments(const ChannelArguments& other)
ChannelArguments::~ChannelArguments() {
grpc_core::ExecCtx exec_ctx;
- for (auto& arg : args_) {
- if (arg.type == GRPC_ARG_POINTER) {
- arg.value.pointer.vtable->destroy(arg.value.pointer.p);
+ for (auto& arg : args_) {
+ if (arg.type == GRPC_ARG_POINTER) {
+ arg.value.pointer.vtable->destroy(arg.value.pointer.p);
}
}
}
@@ -95,12 +95,12 @@ void ChannelArguments::SetSocketMutator(grpc_socket_mutator* mutator) {
grpc_arg mutator_arg = grpc_socket_mutator_to_arg(mutator);
bool replaced = false;
grpc_core::ExecCtx exec_ctx;
- for (auto& arg : args_) {
- if (arg.type == mutator_arg.type &&
+ for (auto& arg : args_) {
+ if (arg.type == mutator_arg.type &&
TString(arg.key) == TString(mutator_arg.key)) {
GPR_ASSERT(!replaced);
- arg.value.pointer.vtable->destroy(arg.value.pointer.p);
- arg.value.pointer = mutator_arg.value.pointer;
+ arg.value.pointer.vtable->destroy(arg.value.pointer.p);
+ arg.value.pointer = mutator_arg.value.pointer;
replaced = true;
}
}
@@ -123,13 +123,13 @@ void ChannelArguments::SetUserAgentPrefix(
}
bool replaced = false;
auto strings_it = strings_.begin();
- for (auto& arg : args_) {
+ for (auto& arg : args_) {
++strings_it;
if (arg.type == GRPC_ARG_STRING) {
if (TString(arg.key) == GRPC_ARG_PRIMARY_USER_AGENT_STRING) {
GPR_ASSERT(arg.value.string == strings_it->c_str());
*(strings_it) = user_agent_prefix + " " + arg.value.string;
- arg.value.string = const_cast<char*>(strings_it->c_str());
+ arg.value.string = const_cast<char*>(strings_it->c_str());
replaced = true;
break;
}
diff --git a/contrib/libs/grpc/src/cpp/common/channel_filter.h b/contrib/libs/grpc/src/cpp/common/channel_filter.h
index 5ce720b307..f5d5dfbb6a 100644
--- a/contrib/libs/grpc/src/cpp/common/channel_filter.h
+++ b/contrib/libs/grpc/src/cpp/common/channel_filter.h
@@ -236,13 +236,13 @@ class ChannelData {
// TODO(roth): Come up with a more C++-like API for the channel element.
/// Initializes the channel data.
- virtual grpc_error* Init(grpc_channel_element* /*elem*/,
- grpc_channel_element_args* /*args*/) {
+ virtual grpc_error* Init(grpc_channel_element* /*elem*/,
+ grpc_channel_element_args* /*args*/) {
return GRPC_ERROR_NONE;
}
// Called before destruction.
- virtual void Destroy(grpc_channel_element* /*elem*/) {}
+ virtual void Destroy(grpc_channel_element* /*elem*/) {}
virtual void StartTransportOp(grpc_channel_element* elem, TransportOp* op);
@@ -259,15 +259,15 @@ class CallData {
// TODO(roth): Come up with a more C++-like API for the call element.
/// Initializes the call data.
- virtual grpc_error* Init(grpc_call_element* /*elem*/,
- const grpc_call_element_args* /*args*/) {
+ virtual grpc_error* Init(grpc_call_element* /*elem*/,
+ const grpc_call_element_args* /*args*/) {
return GRPC_ERROR_NONE;
}
// Called before destruction.
- virtual void Destroy(grpc_call_element* /*elem*/,
- const grpc_call_final_info* /*final_info*/,
- grpc_closure* /*then_call_closure*/) {}
+ virtual void Destroy(grpc_call_element* /*elem*/,
+ const grpc_call_final_info* /*final_info*/,
+ grpc_closure* /*then_call_closure*/) {}
/// Starts a new stream operation.
virtual void StartTransportStreamOpBatch(grpc_call_element* elem,
diff --git a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc
index 96a7105eaf..6cab616d53 100644
--- a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc
+++ b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc
@@ -58,8 +58,8 @@ CompletionQueue::NextStatus CompletionQueue::AsyncNextInternal(
case GRPC_QUEUE_SHUTDOWN:
return SHUTDOWN;
case GRPC_OP_COMPLETE:
- auto core_cq_tag =
- static_cast<::grpc::internal::CompletionQueueTag*>(ev.tag);
+ auto core_cq_tag =
+ static_cast<::grpc::internal::CompletionQueueTag*>(ev.tag);
*ok = ev.success != 0;
*tag = core_cq_tag;
if (core_cq_tag->FinalizeResult(tag, ok)) {
@@ -86,8 +86,8 @@ bool CompletionQueue::CompletionQueueTLSCache::Flush(void** tag, bool* ok) {
flushed_ = true;
if (grpc_completion_queue_thread_local_cache_flush(cq_->cq_, &res_tag,
&res)) {
- auto core_cq_tag =
- static_cast<::grpc::internal::CompletionQueueTag*>(res_tag);
+ auto core_cq_tag =
+ static_cast<::grpc::internal::CompletionQueueTag*>(res_tag);
*ok = res == 1;
if (core_cq_tag->FinalizeResult(tag, ok)) {
return true;
diff --git a/contrib/libs/grpc/src/cpp/common/core_codegen.cc b/contrib/libs/grpc/src/cpp/common/core_codegen.cc
index 75383ed511..0966358d6f 100644
--- a/contrib/libs/grpc/src/cpp/common/core_codegen.cc
+++ b/contrib/libs/grpc/src/cpp/common/core_codegen.cc
@@ -81,7 +81,7 @@ void CoreCodegen::gpr_free(void* p) { return ::gpr_free(p); }
void CoreCodegen::grpc_init() { ::grpc_init(); }
void CoreCodegen::grpc_shutdown() { ::grpc_shutdown(); }
-void CoreCodegen::gpr_mu_init(gpr_mu* mu) { ::gpr_mu_init(mu); }
+void CoreCodegen::gpr_mu_init(gpr_mu* mu) { ::gpr_mu_init(mu); }
void CoreCodegen::gpr_mu_destroy(gpr_mu* mu) { ::gpr_mu_destroy(mu); }
void CoreCodegen::gpr_mu_lock(gpr_mu* mu) { ::gpr_mu_lock(mu); }
void CoreCodegen::gpr_mu_unlock(gpr_mu* mu) { ::gpr_mu_unlock(mu); }
@@ -123,9 +123,9 @@ void CoreCodegen::grpc_call_unref(grpc_call* call) { ::grpc_call_unref(call); }
void* CoreCodegen::grpc_call_arena_alloc(grpc_call* call, size_t length) {
return ::grpc_call_arena_alloc(call, length);
}
-const char* CoreCodegen::grpc_call_error_to_string(grpc_call_error error) {
- return ::grpc_call_error_to_string(error);
-}
+const char* CoreCodegen::grpc_call_error_to_string(grpc_call_error error) {
+ return ::grpc_call_error_to_string(error);
+}
int CoreCodegen::grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader,
grpc_byte_buffer* buffer) {
@@ -142,11 +142,11 @@ int CoreCodegen::grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader,
return ::grpc_byte_buffer_reader_next(reader, slice);
}
-int CoreCodegen::grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
- grpc_slice** slice) {
- return ::grpc_byte_buffer_reader_peek(reader, slice);
-}
-
+int CoreCodegen::grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
+ grpc_slice** slice) {
+ return ::grpc_byte_buffer_reader_peek(reader, slice);
+}
+
grpc_byte_buffer* CoreCodegen::grpc_raw_byte_buffer_create(grpc_slice* slice,
size_t nslices) {
return ::grpc_raw_byte_buffer_create(slice, nslices);
diff --git a/contrib/libs/grpc/src/cpp/common/tls_credentials_options.cc b/contrib/libs/grpc/src/cpp/common/tls_credentials_options.cc
index 7e435ac1de..cf5eec58a4 100644
--- a/contrib/libs/grpc/src/cpp/common/tls_credentials_options.cc
+++ b/contrib/libs/grpc/src/cpp/common/tls_credentials_options.cc
@@ -1,98 +1,98 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
#include <grpc/support/alloc.h>
-#include <grpcpp/security/tls_credentials_options.h>
+#include <grpcpp/security/tls_credentials_options.h>
#include "y_absl/container/inlined_vector.h"
-#include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h"
-#include "src/cpp/common/tls_credentials_options_util.h"
-
+#include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h"
+#include "src/cpp/common/tls_credentials_options_util.h"
+
namespace grpc {
-namespace experimental {
-
-/** TLS key materials config API implementation **/
+namespace experimental {
+
+/** TLS key materials config API implementation **/
void TlsKeyMaterialsConfig::set_pem_root_certs(
const TString& pem_root_certs) {
pem_root_certs_ = pem_root_certs;
-}
-
-void TlsKeyMaterialsConfig::add_pem_key_cert_pair(
- const PemKeyCertPair& pem_key_cert_pair) {
- pem_key_cert_pair_list_.push_back(pem_key_cert_pair);
-}
-
-void TlsKeyMaterialsConfig::set_key_materials(
+}
+
+void TlsKeyMaterialsConfig::add_pem_key_cert_pair(
+ const PemKeyCertPair& pem_key_cert_pair) {
+ pem_key_cert_pair_list_.push_back(pem_key_cert_pair);
+}
+
+void TlsKeyMaterialsConfig::set_key_materials(
const TString& pem_root_certs,
const std::vector<PemKeyCertPair>& pem_key_cert_pair_list) {
pem_key_cert_pair_list_ = pem_key_cert_pair_list;
pem_root_certs_ = pem_root_certs;
-}
-
-/** TLS credential reload arg API implementation **/
-TlsCredentialReloadArg::TlsCredentialReloadArg(
- grpc_tls_credential_reload_arg* arg)
- : c_arg_(arg) {
- if (c_arg_ != nullptr && c_arg_->context != nullptr) {
- gpr_log(GPR_ERROR, "c_arg context has already been set");
- }
- c_arg_->context = static_cast<void*>(this);
- c_arg_->destroy_context = &TlsCredentialReloadArgDestroyContext;
-}
-
-TlsCredentialReloadArg::~TlsCredentialReloadArg() {}
-
-void* TlsCredentialReloadArg::cb_user_data() const {
- return c_arg_->cb_user_data;
-}
-bool TlsCredentialReloadArg::is_pem_key_cert_pair_list_empty() const {
- return c_arg_->key_materials_config->pem_key_cert_pair_list().empty();
-}
-
-grpc_ssl_certificate_config_reload_status TlsCredentialReloadArg::status()
- const {
- return c_arg_->status;
-}
-
+}
+
+/** TLS credential reload arg API implementation **/
+TlsCredentialReloadArg::TlsCredentialReloadArg(
+ grpc_tls_credential_reload_arg* arg)
+ : c_arg_(arg) {
+ if (c_arg_ != nullptr && c_arg_->context != nullptr) {
+ gpr_log(GPR_ERROR, "c_arg context has already been set");
+ }
+ c_arg_->context = static_cast<void*>(this);
+ c_arg_->destroy_context = &TlsCredentialReloadArgDestroyContext;
+}
+
+TlsCredentialReloadArg::~TlsCredentialReloadArg() {}
+
+void* TlsCredentialReloadArg::cb_user_data() const {
+ return c_arg_->cb_user_data;
+}
+bool TlsCredentialReloadArg::is_pem_key_cert_pair_list_empty() const {
+ return c_arg_->key_materials_config->pem_key_cert_pair_list().empty();
+}
+
+grpc_ssl_certificate_config_reload_status TlsCredentialReloadArg::status()
+ const {
+ return c_arg_->status;
+}
+
TString TlsCredentialReloadArg::error_details() const {
return c_arg_->error_details->error_details();
-}
-
-void TlsCredentialReloadArg::set_cb_user_data(void* cb_user_data) {
- c_arg_->cb_user_data = cb_user_data;
-}
-
-void TlsCredentialReloadArg::set_pem_root_certs(
+}
+
+void TlsCredentialReloadArg::set_cb_user_data(void* cb_user_data) {
+ c_arg_->cb_user_data = cb_user_data;
+}
+
+void TlsCredentialReloadArg::set_pem_root_certs(
const TString& pem_root_certs) {
- ::grpc_core::UniquePtr<char> c_pem_root_certs(
- gpr_strdup(pem_root_certs.c_str()));
- c_arg_->key_materials_config->set_pem_root_certs(std::move(c_pem_root_certs));
-}
-
+ ::grpc_core::UniquePtr<char> c_pem_root_certs(
+ gpr_strdup(pem_root_certs.c_str()));
+ c_arg_->key_materials_config->set_pem_root_certs(std::move(c_pem_root_certs));
+}
+
namespace {
::grpc_core::PemKeyCertPair ConvertToCorePemKeyCertPair(
const TlsKeyMaterialsConfig::PemKeyCertPair& pem_key_cert_pair) {
- grpc_ssl_pem_key_cert_pair* ssl_pair =
- (grpc_ssl_pem_key_cert_pair*)gpr_malloc(
- sizeof(grpc_ssl_pem_key_cert_pair));
- ssl_pair->private_key = gpr_strdup(pem_key_cert_pair.private_key.c_str());
- ssl_pair->cert_chain = gpr_strdup(pem_key_cert_pair.cert_chain.c_str());
+ grpc_ssl_pem_key_cert_pair* ssl_pair =
+ (grpc_ssl_pem_key_cert_pair*)gpr_malloc(
+ sizeof(grpc_ssl_pem_key_cert_pair));
+ ssl_pair->private_key = gpr_strdup(pem_key_cert_pair.private_key.c_str());
+ ssl_pair->cert_chain = gpr_strdup(pem_key_cert_pair.cert_chain.c_str());
return ::grpc_core::PemKeyCertPair(ssl_pair);
}
@@ -100,10 +100,10 @@ namespace {
void TlsCredentialReloadArg::add_pem_key_cert_pair(
const TlsKeyMaterialsConfig::PemKeyCertPair& pem_key_cert_pair) {
- c_arg_->key_materials_config->add_pem_key_cert_pair(
+ c_arg_->key_materials_config->add_pem_key_cert_pair(
ConvertToCorePemKeyCertPair(pem_key_cert_pair));
-}
-
+}
+
void TlsCredentialReloadArg::set_key_materials(
const TString& pem_root_certs,
std::vector<TlsKeyMaterialsConfig::PemKeyCertPair> pem_key_cert_pair_list) {
@@ -124,163 +124,163 @@ void TlsCredentialReloadArg::set_key_materials(
c_pem_key_cert_pair_list);
}
-void TlsCredentialReloadArg::set_key_materials_config(
- const std::shared_ptr<TlsKeyMaterialsConfig>& key_materials_config) {
- if (key_materials_config == nullptr) {
- c_arg_->key_materials_config = nullptr;
- return;
- }
+void TlsCredentialReloadArg::set_key_materials_config(
+ const std::shared_ptr<TlsKeyMaterialsConfig>& key_materials_config) {
+ if (key_materials_config == nullptr) {
+ c_arg_->key_materials_config = nullptr;
+ return;
+ }
::y_absl::InlinedVector<::grpc_core::PemKeyCertPair, 1>
- c_pem_key_cert_pair_list;
- for (const auto& key_cert_pair :
- key_materials_config->pem_key_cert_pair_list()) {
- grpc_ssl_pem_key_cert_pair* ssl_pair =
- (grpc_ssl_pem_key_cert_pair*)gpr_malloc(
- sizeof(grpc_ssl_pem_key_cert_pair));
- ssl_pair->private_key = gpr_strdup(key_cert_pair.private_key.c_str());
- ssl_pair->cert_chain = gpr_strdup(key_cert_pair.cert_chain.c_str());
- ::grpc_core::PemKeyCertPair c_pem_key_cert_pair =
- ::grpc_core::PemKeyCertPair(ssl_pair);
- c_pem_key_cert_pair_list.emplace_back(std::move(c_pem_key_cert_pair));
- }
- ::grpc_core::UniquePtr<char> c_pem_root_certs(
- gpr_strdup(key_materials_config->pem_root_certs().c_str()));
- if (c_arg_->key_materials_config == nullptr) {
- c_arg_->key_materials_config = grpc_tls_key_materials_config_create();
- }
- c_arg_->key_materials_config->set_key_materials(
+ c_pem_key_cert_pair_list;
+ for (const auto& key_cert_pair :
+ key_materials_config->pem_key_cert_pair_list()) {
+ grpc_ssl_pem_key_cert_pair* ssl_pair =
+ (grpc_ssl_pem_key_cert_pair*)gpr_malloc(
+ sizeof(grpc_ssl_pem_key_cert_pair));
+ ssl_pair->private_key = gpr_strdup(key_cert_pair.private_key.c_str());
+ ssl_pair->cert_chain = gpr_strdup(key_cert_pair.cert_chain.c_str());
+ ::grpc_core::PemKeyCertPair c_pem_key_cert_pair =
+ ::grpc_core::PemKeyCertPair(ssl_pair);
+ c_pem_key_cert_pair_list.emplace_back(std::move(c_pem_key_cert_pair));
+ }
+ ::grpc_core::UniquePtr<char> c_pem_root_certs(
+ gpr_strdup(key_materials_config->pem_root_certs().c_str()));
+ if (c_arg_->key_materials_config == nullptr) {
+ c_arg_->key_materials_config = grpc_tls_key_materials_config_create();
+ }
+ c_arg_->key_materials_config->set_key_materials(
key_materials_config->pem_root_certs().c_str(), c_pem_key_cert_pair_list);
- c_arg_->key_materials_config->set_version(key_materials_config->version());
-}
-
-void TlsCredentialReloadArg::set_status(
- grpc_ssl_certificate_config_reload_status status) {
- c_arg_->status = status;
-}
-
-void TlsCredentialReloadArg::set_error_details(
+ c_arg_->key_materials_config->set_version(key_materials_config->version());
+}
+
+void TlsCredentialReloadArg::set_status(
+ grpc_ssl_certificate_config_reload_status status) {
+ c_arg_->status = status;
+}
+
+void TlsCredentialReloadArg::set_error_details(
const TString& error_details) {
c_arg_->error_details->set_error_details(error_details.c_str());
-}
-
-void TlsCredentialReloadArg::OnCredentialReloadDoneCallback() {
- if (c_arg_->cb == nullptr) {
- gpr_log(GPR_ERROR, "credential reload arg callback API is nullptr");
- return;
- }
- c_arg_->cb(c_arg_);
-}
-
-/** gRPC TLS credential reload config API implementation **/
-TlsCredentialReloadConfig::TlsCredentialReloadConfig(
- std::shared_ptr<TlsCredentialReloadInterface> credential_reload_interface)
- : credential_reload_interface_(std::move(credential_reload_interface)) {
- c_config_ = grpc_tls_credential_reload_config_create(
- nullptr, &TlsCredentialReloadConfigCSchedule,
- &TlsCredentialReloadConfigCCancel, nullptr);
- c_config_->set_context(static_cast<void*>(this));
-}
-
-TlsCredentialReloadConfig::~TlsCredentialReloadConfig() {}
-
-/** gRPC TLS server authorization check arg API implementation **/
-TlsServerAuthorizationCheckArg::TlsServerAuthorizationCheckArg(
- grpc_tls_server_authorization_check_arg* arg)
- : c_arg_(arg) {
- if (c_arg_ != nullptr && c_arg_->context != nullptr) {
- gpr_log(GPR_ERROR, "c_arg context has already been set");
- }
- c_arg_->context = static_cast<void*>(this);
- c_arg_->destroy_context = &TlsServerAuthorizationCheckArgDestroyContext;
-}
-
-TlsServerAuthorizationCheckArg::~TlsServerAuthorizationCheckArg() {}
-
-void* TlsServerAuthorizationCheckArg::cb_user_data() const {
- return c_arg_->cb_user_data;
-}
-
-int TlsServerAuthorizationCheckArg::success() const { return c_arg_->success; }
-
+}
+
+void TlsCredentialReloadArg::OnCredentialReloadDoneCallback() {
+ if (c_arg_->cb == nullptr) {
+ gpr_log(GPR_ERROR, "credential reload arg callback API is nullptr");
+ return;
+ }
+ c_arg_->cb(c_arg_);
+}
+
+/** gRPC TLS credential reload config API implementation **/
+TlsCredentialReloadConfig::TlsCredentialReloadConfig(
+ std::shared_ptr<TlsCredentialReloadInterface> credential_reload_interface)
+ : credential_reload_interface_(std::move(credential_reload_interface)) {
+ c_config_ = grpc_tls_credential_reload_config_create(
+ nullptr, &TlsCredentialReloadConfigCSchedule,
+ &TlsCredentialReloadConfigCCancel, nullptr);
+ c_config_->set_context(static_cast<void*>(this));
+}
+
+TlsCredentialReloadConfig::~TlsCredentialReloadConfig() {}
+
+/** gRPC TLS server authorization check arg API implementation **/
+TlsServerAuthorizationCheckArg::TlsServerAuthorizationCheckArg(
+ grpc_tls_server_authorization_check_arg* arg)
+ : c_arg_(arg) {
+ if (c_arg_ != nullptr && c_arg_->context != nullptr) {
+ gpr_log(GPR_ERROR, "c_arg context has already been set");
+ }
+ c_arg_->context = static_cast<void*>(this);
+ c_arg_->destroy_context = &TlsServerAuthorizationCheckArgDestroyContext;
+}
+
+TlsServerAuthorizationCheckArg::~TlsServerAuthorizationCheckArg() {}
+
+void* TlsServerAuthorizationCheckArg::cb_user_data() const {
+ return c_arg_->cb_user_data;
+}
+
+int TlsServerAuthorizationCheckArg::success() const { return c_arg_->success; }
+
TString TlsServerAuthorizationCheckArg::target_name() const {
TString cpp_target_name(c_arg_->target_name);
- return cpp_target_name;
-}
-
+ return cpp_target_name;
+}
+
TString TlsServerAuthorizationCheckArg::peer_cert() const {
TString cpp_peer_cert(c_arg_->peer_cert);
- return cpp_peer_cert;
-}
-
+ return cpp_peer_cert;
+}
+
TString TlsServerAuthorizationCheckArg::peer_cert_full_chain() const {
TString cpp_peer_cert_full_chain(c_arg_->peer_cert_full_chain);
return cpp_peer_cert_full_chain;
}
-grpc_status_code TlsServerAuthorizationCheckArg::status() const {
- return c_arg_->status;
-}
-
+grpc_status_code TlsServerAuthorizationCheckArg::status() const {
+ return c_arg_->status;
+}
+
TString TlsServerAuthorizationCheckArg::error_details() const {
return c_arg_->error_details->error_details();
-}
-
-void TlsServerAuthorizationCheckArg::set_cb_user_data(void* cb_user_data) {
- c_arg_->cb_user_data = cb_user_data;
-}
-
-void TlsServerAuthorizationCheckArg::set_success(int success) {
- c_arg_->success = success;
-}
-
-void TlsServerAuthorizationCheckArg::set_target_name(
+}
+
+void TlsServerAuthorizationCheckArg::set_cb_user_data(void* cb_user_data) {
+ c_arg_->cb_user_data = cb_user_data;
+}
+
+void TlsServerAuthorizationCheckArg::set_success(int success) {
+ c_arg_->success = success;
+}
+
+void TlsServerAuthorizationCheckArg::set_target_name(
const TString& target_name) {
- c_arg_->target_name = gpr_strdup(target_name.c_str());
-}
-
-void TlsServerAuthorizationCheckArg::set_peer_cert(
+ c_arg_->target_name = gpr_strdup(target_name.c_str());
+}
+
+void TlsServerAuthorizationCheckArg::set_peer_cert(
const TString& peer_cert) {
- c_arg_->peer_cert = gpr_strdup(peer_cert.c_str());
-}
-
+ c_arg_->peer_cert = gpr_strdup(peer_cert.c_str());
+}
+
void TlsServerAuthorizationCheckArg::set_peer_cert_full_chain(
const TString& peer_cert_full_chain) {
c_arg_->peer_cert_full_chain = gpr_strdup(peer_cert_full_chain.c_str());
}
-void TlsServerAuthorizationCheckArg::set_status(grpc_status_code status) {
- c_arg_->status = status;
-}
-
-void TlsServerAuthorizationCheckArg::set_error_details(
+void TlsServerAuthorizationCheckArg::set_status(grpc_status_code status) {
+ c_arg_->status = status;
+}
+
+void TlsServerAuthorizationCheckArg::set_error_details(
const TString& error_details) {
c_arg_->error_details->set_error_details(error_details.c_str());
-}
-
-void TlsServerAuthorizationCheckArg::OnServerAuthorizationCheckDoneCallback() {
- if (c_arg_->cb == nullptr) {
- gpr_log(GPR_ERROR, "server authorizaton check arg callback API is nullptr");
- return;
- }
- c_arg_->cb(c_arg_);
-}
-
-/** gRPC TLS server authorization check config API implementation. **/
-TlsServerAuthorizationCheckConfig::TlsServerAuthorizationCheckConfig(
- std::shared_ptr<TlsServerAuthorizationCheckInterface>
- server_authorization_check_interface)
- : server_authorization_check_interface_(
- std::move(server_authorization_check_interface)) {
- c_config_ = grpc_tls_server_authorization_check_config_create(
- nullptr, &TlsServerAuthorizationCheckConfigCSchedule,
- &TlsServerAuthorizationCheckConfigCCancel, nullptr);
- c_config_->set_context(static_cast<void*>(this));
-}
-
-TlsServerAuthorizationCheckConfig::~TlsServerAuthorizationCheckConfig() {}
-
-/** gRPC TLS credential options API implementation **/
-TlsCredentialsOptions::TlsCredentialsOptions(
+}
+
+void TlsServerAuthorizationCheckArg::OnServerAuthorizationCheckDoneCallback() {
+ if (c_arg_->cb == nullptr) {
+ gpr_log(GPR_ERROR, "server authorizaton check arg callback API is nullptr");
+ return;
+ }
+ c_arg_->cb(c_arg_);
+}
+
+/** gRPC TLS server authorization check config API implementation. **/
+TlsServerAuthorizationCheckConfig::TlsServerAuthorizationCheckConfig(
+ std::shared_ptr<TlsServerAuthorizationCheckInterface>
+ server_authorization_check_interface)
+ : server_authorization_check_interface_(
+ std::move(server_authorization_check_interface)) {
+ c_config_ = grpc_tls_server_authorization_check_config_create(
+ nullptr, &TlsServerAuthorizationCheckConfigCSchedule,
+ &TlsServerAuthorizationCheckConfigCCancel, nullptr);
+ c_config_->set_context(static_cast<void*>(this));
+}
+
+TlsServerAuthorizationCheckConfig::~TlsServerAuthorizationCheckConfig() {}
+
+/** gRPC TLS credential options API implementation **/
+TlsCredentialsOptions::TlsCredentialsOptions(
grpc_tls_server_verification_option server_verification_option,
std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config,
std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config,
@@ -292,7 +292,7 @@ TlsCredentialsOptions::TlsCredentialsOptions(
std::move(server_authorization_check_config)) {}
TlsCredentialsOptions::TlsCredentialsOptions(
- grpc_ssl_client_certificate_request_type cert_request_type,
+ grpc_ssl_client_certificate_request_type cert_request_type,
std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config,
std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config)
: TlsCredentialsOptions(cert_request_type, GRPC_TLS_SERVER_VERIFICATION,
@@ -302,42 +302,42 @@ TlsCredentialsOptions::TlsCredentialsOptions(
TlsCredentialsOptions::TlsCredentialsOptions(
grpc_ssl_client_certificate_request_type cert_request_type,
grpc_tls_server_verification_option server_verification_option,
- std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config,
- std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config,
- std::shared_ptr<TlsServerAuthorizationCheckConfig>
- server_authorization_check_config)
- : cert_request_type_(cert_request_type),
+ std::shared_ptr<TlsKeyMaterialsConfig> key_materials_config,
+ std::shared_ptr<TlsCredentialReloadConfig> credential_reload_config,
+ std::shared_ptr<TlsServerAuthorizationCheckConfig>
+ server_authorization_check_config)
+ : cert_request_type_(cert_request_type),
server_verification_option_(server_verification_option),
- key_materials_config_(std::move(key_materials_config)),
- credential_reload_config_(std::move(credential_reload_config)),
- server_authorization_check_config_(
- std::move(server_authorization_check_config)) {
- c_credentials_options_ = grpc_tls_credentials_options_create();
- grpc_tls_credentials_options_set_cert_request_type(c_credentials_options_,
- cert_request_type_);
- if (key_materials_config_ != nullptr) {
- grpc_tls_credentials_options_set_key_materials_config(
- c_credentials_options_,
- ConvertToCKeyMaterialsConfig(key_materials_config_));
- }
- if (credential_reload_config_ != nullptr) {
- grpc_tls_credentials_options_set_credential_reload_config(
- c_credentials_options_, credential_reload_config_->c_config());
- }
- if (server_authorization_check_config_ != nullptr) {
- grpc_tls_credentials_options_set_server_authorization_check_config(
- c_credentials_options_, server_authorization_check_config_->c_config());
- }
+ key_materials_config_(std::move(key_materials_config)),
+ credential_reload_config_(std::move(credential_reload_config)),
+ server_authorization_check_config_(
+ std::move(server_authorization_check_config)) {
+ c_credentials_options_ = grpc_tls_credentials_options_create();
+ grpc_tls_credentials_options_set_cert_request_type(c_credentials_options_,
+ cert_request_type_);
+ if (key_materials_config_ != nullptr) {
+ grpc_tls_credentials_options_set_key_materials_config(
+ c_credentials_options_,
+ ConvertToCKeyMaterialsConfig(key_materials_config_));
+ }
+ if (credential_reload_config_ != nullptr) {
+ grpc_tls_credentials_options_set_credential_reload_config(
+ c_credentials_options_, credential_reload_config_->c_config());
+ }
+ if (server_authorization_check_config_ != nullptr) {
+ grpc_tls_credentials_options_set_server_authorization_check_config(
+ c_credentials_options_, server_authorization_check_config_->c_config());
+ }
grpc_tls_credentials_options_set_server_verification_option(
c_credentials_options_, server_verification_option);
-}
-
+}
+
/** Whenever a TlsCredentialsOptions instance is created, the caller takes
* ownership of the c_credentials_options_ pointer (see e.g. the implementation
* of the TlsCredentials API in secure_credentials.cc). For this reason, the
* TlsCredentialsOptions destructor is not responsible for freeing
* c_credentials_options_. **/
-TlsCredentialsOptions::~TlsCredentialsOptions() {}
-
-} // namespace experimental
+TlsCredentialsOptions::~TlsCredentialsOptions() {}
+
+} // namespace experimental
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.cc b/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.cc
index ed84003212..99d6eaf26c 100644
--- a/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.cc
+++ b/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.cc
@@ -1,149 +1,149 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
#include "y_absl/container/inlined_vector.h"
#include <grpcpp/security/tls_credentials_options.h>
-#include "src/cpp/common/tls_credentials_options_util.h"
-
+#include "src/cpp/common/tls_credentials_options_util.h"
+
namespace grpc {
-namespace experimental {
-
-/** Converts the Cpp key materials to C key materials; this allocates memory for
- * the C key materials. Note that the user must free
- * the underlying pointer to private key and cert chain duplicates; they are not
- * freed when the grpc_core::UniquePtr<char> member variables of PemKeyCertPair
- * are unused. Similarly, the user must free the underlying pointer to
- * c_pem_root_certs. **/
-grpc_tls_key_materials_config* ConvertToCKeyMaterialsConfig(
- const std::shared_ptr<TlsKeyMaterialsConfig>& config) {
- if (config == nullptr) {
- return nullptr;
- }
- grpc_tls_key_materials_config* c_config =
- grpc_tls_key_materials_config_create();
+namespace experimental {
+
+/** Converts the Cpp key materials to C key materials; this allocates memory for
+ * the C key materials. Note that the user must free
+ * the underlying pointer to private key and cert chain duplicates; they are not
+ * freed when the grpc_core::UniquePtr<char> member variables of PemKeyCertPair
+ * are unused. Similarly, the user must free the underlying pointer to
+ * c_pem_root_certs. **/
+grpc_tls_key_materials_config* ConvertToCKeyMaterialsConfig(
+ const std::shared_ptr<TlsKeyMaterialsConfig>& config) {
+ if (config == nullptr) {
+ return nullptr;
+ }
+ grpc_tls_key_materials_config* c_config =
+ grpc_tls_key_materials_config_create();
::y_absl::InlinedVector<::grpc_core::PemKeyCertPair, 1>
- c_pem_key_cert_pair_list;
- for (const auto& key_cert_pair : config->pem_key_cert_pair_list()) {
- grpc_ssl_pem_key_cert_pair* ssl_pair =
- (grpc_ssl_pem_key_cert_pair*)gpr_malloc(
- sizeof(grpc_ssl_pem_key_cert_pair));
- ssl_pair->private_key = gpr_strdup(key_cert_pair.private_key.c_str());
- ssl_pair->cert_chain = gpr_strdup(key_cert_pair.cert_chain.c_str());
- ::grpc_core::PemKeyCertPair c_pem_key_cert_pair =
- ::grpc_core::PemKeyCertPair(ssl_pair);
- c_pem_key_cert_pair_list.push_back(::std::move(c_pem_key_cert_pair));
- }
+ c_pem_key_cert_pair_list;
+ for (const auto& key_cert_pair : config->pem_key_cert_pair_list()) {
+ grpc_ssl_pem_key_cert_pair* ssl_pair =
+ (grpc_ssl_pem_key_cert_pair*)gpr_malloc(
+ sizeof(grpc_ssl_pem_key_cert_pair));
+ ssl_pair->private_key = gpr_strdup(key_cert_pair.private_key.c_str());
+ ssl_pair->cert_chain = gpr_strdup(key_cert_pair.cert_chain.c_str());
+ ::grpc_core::PemKeyCertPair c_pem_key_cert_pair =
+ ::grpc_core::PemKeyCertPair(ssl_pair);
+ c_pem_key_cert_pair_list.push_back(::std::move(c_pem_key_cert_pair));
+ }
c_config->set_key_materials(config->pem_root_certs().c_str(),
c_pem_key_cert_pair_list);
- c_config->set_version(config->version());
- return c_config;
-}
-
-/** The C schedule and cancel functions for the credential reload config.
- * They populate a C credential reload arg with the result of a C++ credential
- * reload schedule/cancel API. **/
-int TlsCredentialReloadConfigCSchedule(void* /*config_user_data*/,
- grpc_tls_credential_reload_arg* arg) {
- if (arg == nullptr || arg->config == nullptr ||
- arg->config->context() == nullptr) {
- gpr_log(GPR_ERROR, "credential reload arg was not properly initialized");
- return 1;
- }
- TlsCredentialReloadConfig* cpp_config =
- static_cast<TlsCredentialReloadConfig*>(arg->config->context());
- TlsCredentialReloadArg* cpp_arg = new TlsCredentialReloadArg(arg);
- int schedule_result = cpp_config->Schedule(cpp_arg);
- return schedule_result;
-}
-
-void TlsCredentialReloadConfigCCancel(void* /*config_user_data*/,
- grpc_tls_credential_reload_arg* arg) {
- if (arg == nullptr || arg->config == nullptr ||
- arg->config->context() == nullptr) {
- gpr_log(GPR_ERROR, "credential reload arg was not properly initialized");
- return;
- }
- if (arg->context == nullptr) {
- gpr_log(GPR_ERROR, "credential reload arg schedule has already completed");
- return;
- }
- TlsCredentialReloadConfig* cpp_config =
- static_cast<TlsCredentialReloadConfig*>(arg->config->context());
- TlsCredentialReloadArg* cpp_arg =
- static_cast<TlsCredentialReloadArg*>(arg->context);
- cpp_config->Cancel(cpp_arg);
-}
-
-void TlsCredentialReloadArgDestroyContext(void* context) {
- if (context != nullptr) {
- TlsCredentialReloadArg* cpp_arg =
- static_cast<TlsCredentialReloadArg*>(context);
- delete cpp_arg;
- }
-}
-
-/** The C schedule and cancel functions for the server authorization check
- * config. They populate a C server authorization check arg with the result
- * of a C++ server authorization check schedule/cancel API. **/
-int TlsServerAuthorizationCheckConfigCSchedule(
- void* /*config_user_data*/, grpc_tls_server_authorization_check_arg* arg) {
- if (arg == nullptr || arg->config == nullptr ||
- arg->config->context() == nullptr) {
- gpr_log(GPR_ERROR,
- "server authorization check arg was not properly initialized");
- return 1;
- }
- TlsServerAuthorizationCheckConfig* cpp_config =
- static_cast<TlsServerAuthorizationCheckConfig*>(arg->config->context());
- TlsServerAuthorizationCheckArg* cpp_arg =
- new TlsServerAuthorizationCheckArg(arg);
- int schedule_result = cpp_config->Schedule(cpp_arg);
- return schedule_result;
-}
-
-void TlsServerAuthorizationCheckConfigCCancel(
- void* /*config_user_data*/, grpc_tls_server_authorization_check_arg* arg) {
- if (arg == nullptr || arg->config == nullptr ||
- arg->config->context() == nullptr) {
- gpr_log(GPR_ERROR,
- "server authorization check arg was not properly initialized");
- return;
- }
- if (arg->context == nullptr) {
- gpr_log(GPR_ERROR,
- "server authorization check arg schedule has already completed");
- return;
- }
- TlsServerAuthorizationCheckConfig* cpp_config =
- static_cast<TlsServerAuthorizationCheckConfig*>(arg->config->context());
- TlsServerAuthorizationCheckArg* cpp_arg =
- static_cast<TlsServerAuthorizationCheckArg*>(arg->context);
- cpp_config->Cancel(cpp_arg);
-}
-
-void TlsServerAuthorizationCheckArgDestroyContext(void* context) {
- if (context != nullptr) {
- TlsServerAuthorizationCheckArg* cpp_arg =
- static_cast<TlsServerAuthorizationCheckArg*>(context);
- delete cpp_arg;
- }
-}
-
-} // namespace experimental
+ c_config->set_version(config->version());
+ return c_config;
+}
+
+/** The C schedule and cancel functions for the credential reload config.
+ * They populate a C credential reload arg with the result of a C++ credential
+ * reload schedule/cancel API. **/
+int TlsCredentialReloadConfigCSchedule(void* /*config_user_data*/,
+ grpc_tls_credential_reload_arg* arg) {
+ if (arg == nullptr || arg->config == nullptr ||
+ arg->config->context() == nullptr) {
+ gpr_log(GPR_ERROR, "credential reload arg was not properly initialized");
+ return 1;
+ }
+ TlsCredentialReloadConfig* cpp_config =
+ static_cast<TlsCredentialReloadConfig*>(arg->config->context());
+ TlsCredentialReloadArg* cpp_arg = new TlsCredentialReloadArg(arg);
+ int schedule_result = cpp_config->Schedule(cpp_arg);
+ return schedule_result;
+}
+
+void TlsCredentialReloadConfigCCancel(void* /*config_user_data*/,
+ grpc_tls_credential_reload_arg* arg) {
+ if (arg == nullptr || arg->config == nullptr ||
+ arg->config->context() == nullptr) {
+ gpr_log(GPR_ERROR, "credential reload arg was not properly initialized");
+ return;
+ }
+ if (arg->context == nullptr) {
+ gpr_log(GPR_ERROR, "credential reload arg schedule has already completed");
+ return;
+ }
+ TlsCredentialReloadConfig* cpp_config =
+ static_cast<TlsCredentialReloadConfig*>(arg->config->context());
+ TlsCredentialReloadArg* cpp_arg =
+ static_cast<TlsCredentialReloadArg*>(arg->context);
+ cpp_config->Cancel(cpp_arg);
+}
+
+void TlsCredentialReloadArgDestroyContext(void* context) {
+ if (context != nullptr) {
+ TlsCredentialReloadArg* cpp_arg =
+ static_cast<TlsCredentialReloadArg*>(context);
+ delete cpp_arg;
+ }
+}
+
+/** The C schedule and cancel functions for the server authorization check
+ * config. They populate a C server authorization check arg with the result
+ * of a C++ server authorization check schedule/cancel API. **/
+int TlsServerAuthorizationCheckConfigCSchedule(
+ void* /*config_user_data*/, grpc_tls_server_authorization_check_arg* arg) {
+ if (arg == nullptr || arg->config == nullptr ||
+ arg->config->context() == nullptr) {
+ gpr_log(GPR_ERROR,
+ "server authorization check arg was not properly initialized");
+ return 1;
+ }
+ TlsServerAuthorizationCheckConfig* cpp_config =
+ static_cast<TlsServerAuthorizationCheckConfig*>(arg->config->context());
+ TlsServerAuthorizationCheckArg* cpp_arg =
+ new TlsServerAuthorizationCheckArg(arg);
+ int schedule_result = cpp_config->Schedule(cpp_arg);
+ return schedule_result;
+}
+
+void TlsServerAuthorizationCheckConfigCCancel(
+ void* /*config_user_data*/, grpc_tls_server_authorization_check_arg* arg) {
+ if (arg == nullptr || arg->config == nullptr ||
+ arg->config->context() == nullptr) {
+ gpr_log(GPR_ERROR,
+ "server authorization check arg was not properly initialized");
+ return;
+ }
+ if (arg->context == nullptr) {
+ gpr_log(GPR_ERROR,
+ "server authorization check arg schedule has already completed");
+ return;
+ }
+ TlsServerAuthorizationCheckConfig* cpp_config =
+ static_cast<TlsServerAuthorizationCheckConfig*>(arg->config->context());
+ TlsServerAuthorizationCheckArg* cpp_arg =
+ static_cast<TlsServerAuthorizationCheckArg*>(arg->context);
+ cpp_config->Cancel(cpp_arg);
+}
+
+void TlsServerAuthorizationCheckArgDestroyContext(void* context) {
+ if (context != nullptr) {
+ TlsServerAuthorizationCheckArg* cpp_arg =
+ static_cast<TlsServerAuthorizationCheckArg*>(context);
+ delete cpp_arg;
+ }
+}
+
+} // namespace experimental
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.h b/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.h
index 4ee04d15d7..889fa3b55c 100644
--- a/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.h
+++ b/contrib/libs/grpc/src/cpp/common/tls_credentials_options_util.h
@@ -1,58 +1,58 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_INTERNAL_CPP_COMMON_TLS_CREDENTIALS_OPTIONS_UTIL_H
-#define GRPC_INTERNAL_CPP_COMMON_TLS_CREDENTIALS_OPTIONS_UTIL_H
-
-#include <grpc/grpc_security.h>
-#include <grpcpp/security/tls_credentials_options.h>
-
-#include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h"
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_INTERNAL_CPP_COMMON_TLS_CREDENTIALS_OPTIONS_UTIL_H
+#define GRPC_INTERNAL_CPP_COMMON_TLS_CREDENTIALS_OPTIONS_UTIL_H
+
+#include <grpc/grpc_security.h>
+#include <grpcpp/security/tls_credentials_options.h>
+
+#include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h"
+
namespace grpc {
-namespace experimental {
-
-/** The following function is exposed for testing purposes. **/
-grpc_tls_key_materials_config* ConvertToCKeyMaterialsConfig(
- const std::shared_ptr<TlsKeyMaterialsConfig>& config);
-
-/** The following 4 functions convert the user-provided schedule or cancel
- * functions into C style schedule or cancel functions. These are internal
- * functions, not meant to be accessed by the user. **/
-int TlsCredentialReloadConfigCSchedule(void* config_user_data,
- grpc_tls_credential_reload_arg* arg);
-
-void TlsCredentialReloadConfigCCancel(void* config_user_data,
- grpc_tls_credential_reload_arg* arg);
-
-int TlsServerAuthorizationCheckConfigCSchedule(
- void* config_user_data, grpc_tls_server_authorization_check_arg* arg);
-
-void TlsServerAuthorizationCheckConfigCCancel(
- void* config_user_data, grpc_tls_server_authorization_check_arg* arg);
-
-/** The following 2 functions cleanup data created in the above C schedule
- * functions. **/
-void TlsCredentialReloadArgDestroyContext(void* context);
-
-void TlsServerAuthorizationCheckArgDestroyContext(void* context);
-
-} // namespace experimental
+namespace experimental {
+
+/** The following function is exposed for testing purposes. **/
+grpc_tls_key_materials_config* ConvertToCKeyMaterialsConfig(
+ const std::shared_ptr<TlsKeyMaterialsConfig>& config);
+
+/** The following 4 functions convert the user-provided schedule or cancel
+ * functions into C style schedule or cancel functions. These are internal
+ * functions, not meant to be accessed by the user. **/
+int TlsCredentialReloadConfigCSchedule(void* config_user_data,
+ grpc_tls_credential_reload_arg* arg);
+
+void TlsCredentialReloadConfigCCancel(void* config_user_data,
+ grpc_tls_credential_reload_arg* arg);
+
+int TlsServerAuthorizationCheckConfigCSchedule(
+ void* config_user_data, grpc_tls_server_authorization_check_arg* arg);
+
+void TlsServerAuthorizationCheckConfigCCancel(
+ void* config_user_data, grpc_tls_server_authorization_check_arg* arg);
+
+/** The following 2 functions cleanup data created in the above C schedule
+ * functions. **/
+void TlsCredentialReloadArgDestroyContext(void* context);
+
+void TlsServerAuthorizationCheckArgDestroyContext(void* context);
+
+} // namespace experimental
} // namespace grpc
-
-#endif // GRPC_INTERNAL_CPP_COMMON_TLS_CREDENTIALS_OPTIONS_UTIL_H
+
+#endif // GRPC_INTERNAL_CPP_COMMON_TLS_CREDENTIALS_OPTIONS_UTIL_H
diff --git a/contrib/libs/grpc/src/cpp/common/validate_service_config.cc b/contrib/libs/grpc/src/cpp/common/validate_service_config.cc
index f63cfbc68c..f263c95f03 100644
--- a/contrib/libs/grpc/src/cpp/common/validate_service_config.cc
+++ b/contrib/libs/grpc/src/cpp/common/validate_service_config.cc
@@ -1,40 +1,40 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpcpp/support/validate_service_config.h>
-
-#include "src/core/ext/filters/client_channel/service_config.h"
-
-namespace grpc {
-namespace experimental {
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpcpp/support/validate_service_config.h>
+
+#include "src/core/ext/filters/client_channel/service_config.h"
+
+namespace grpc {
+namespace experimental {
TString ValidateServiceConfigJSON(const TString& service_config_json) {
- grpc_init();
- grpc_error* error = GRPC_ERROR_NONE;
+ grpc_init();
+ grpc_error* error = GRPC_ERROR_NONE;
grpc_core::ServiceConfig::Create(/*args=*/nullptr,
service_config_json.c_str(), &error);
TString return_value;
- if (error != GRPC_ERROR_NONE) {
- return_value = grpc_error_string(error);
- GRPC_ERROR_UNREF(error);
- }
- grpc_shutdown();
- return return_value;
-}
-} // namespace experimental
-} // namespace grpc
+ if (error != GRPC_ERROR_NONE) {
+ return_value = grpc_error_string(error);
+ GRPC_ERROR_UNREF(error);
+ }
+ grpc_shutdown();
+ return return_value;
+}
+} // namespace experimental
+} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc
index 1b388210c0..070db6fd9d 100644
--- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc
+++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc
@@ -94,17 +94,17 @@ Status ProtoServerReflection::ServerReflectionInfo(
void ProtoServerReflection::FillErrorResponse(const Status& status,
ErrorResponse* error_response) {
error_response->set_error_code(status.error_code());
- error_response->set_error_message(TProtoStringType(status.error_message()));
+ error_response->set_error_message(TProtoStringType(status.error_message()));
}
-Status ProtoServerReflection::ListService(ServerContext* /*context*/,
+Status ProtoServerReflection::ListService(ServerContext* /*context*/,
ListServiceResponse* response) {
if (services_ == nullptr) {
return Status(StatusCode::NOT_FOUND, "Services not found.");
}
- for (const auto& value : *services_) {
+ for (const auto& value : *services_) {
ServiceResponse* service_response = response->add_service();
- service_response->set_name(TProtoStringType(value));
+ service_response->set_name(TProtoStringType(value));
}
return Status::OK;
}
@@ -117,7 +117,7 @@ Status ProtoServerReflection::GetFileByName(
}
const protobuf::FileDescriptor* file_desc =
- descriptor_pool_->FindFileByName(TProtoStringType(filename));
+ descriptor_pool_->FindFileByName(TProtoStringType(filename));
if (file_desc == nullptr) {
return Status(StatusCode::NOT_FOUND, "File not found.");
}
@@ -134,7 +134,7 @@ Status ProtoServerReflection::GetFileContainingSymbol(
}
const protobuf::FileDescriptor* file_desc =
- descriptor_pool_->FindFileContainingSymbol(TProtoStringType(symbol));
+ descriptor_pool_->FindFileContainingSymbol(TProtoStringType(symbol));
if (file_desc == nullptr) {
return Status(StatusCode::NOT_FOUND, "Symbol not found.");
}
@@ -144,7 +144,7 @@ Status ProtoServerReflection::GetFileContainingSymbol(
}
Status ProtoServerReflection::GetFileContainingExtension(
- ServerContext* /*context*/, const ExtensionRequest* request,
+ ServerContext* /*context*/, const ExtensionRequest* request,
ServerReflectionResponse* response) {
if (descriptor_pool_ == nullptr) {
return Status::CANCELLED;
@@ -175,17 +175,17 @@ Status ProtoServerReflection::GetAllExtensionNumbers(
}
const protobuf::Descriptor* desc =
- descriptor_pool_->FindMessageTypeByName(TProtoStringType(type));
+ descriptor_pool_->FindMessageTypeByName(TProtoStringType(type));
if (desc == nullptr) {
return Status(StatusCode::NOT_FOUND, "Type not found.");
}
std::vector<const protobuf::FieldDescriptor*> extensions;
descriptor_pool_->FindAllExtensions(desc, &extensions);
- for (const auto& value : extensions) {
- response->add_extension_number(value->number());
+ for (const auto& value : extensions) {
+ response->add_extension_number(value->number());
}
- response->set_base_type_name(TProtoStringType(type));
+ response->set_base_type_name(TProtoStringType(type));
return Status::OK;
}
@@ -199,7 +199,7 @@ void ProtoServerReflection::FillFileDescriptorResponse(
seen_files->insert(file_desc->name());
protobuf::FileDescriptorProto file_desc_proto;
- TProtoStringType data;
+ TProtoStringType data;
file_desc->CopyTo(&file_desc_proto);
file_desc_proto.SerializeToString(&data);
response->mutable_file_descriptor_response()->add_file_descriptor_proto(data);
diff --git a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc
index 007193d7f7..b580ce1502 100644
--- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc
+++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc
@@ -42,7 +42,7 @@ void ProtoServerReflectionPlugin::Finish(grpc::ServerInitializer* si) {
}
void ProtoServerReflectionPlugin::ChangeArguments(const TString& /*name*/,
- void* /*value*/) {}
+ void* /*value*/) {}
bool ProtoServerReflectionPlugin::has_sync_methods() const {
if (reflection_service_) {
diff --git a/contrib/libs/grpc/src/cpp/server/channel_argument_option.cc b/contrib/libs/grpc/src/cpp/server/channel_argument_option.cc
index 9aad932429..00bbe73d88 100644
--- a/contrib/libs/grpc/src/cpp/server/channel_argument_option.cc
+++ b/contrib/libs/grpc/src/cpp/server/channel_argument_option.cc
@@ -31,8 +31,8 @@ std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
args->SetString(name_, value_);
}
virtual void UpdatePlugins(
- std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/)
- override {}
+ std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/)
+ override {}
private:
const TString name_;
@@ -52,8 +52,8 @@ std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
args->SetInt(name_, value_);
}
virtual void UpdatePlugins(
- std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/)
- override {}
+ std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/)
+ override {}
private:
const TString name_;
diff --git a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc
index 6dcf84bf40..e061c62ef4 100644
--- a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc
+++ b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc
@@ -27,25 +27,25 @@ namespace grpc {
namespace {
-grpc::protobuf::util::Status ParseJson(const char* json_str,
- grpc::protobuf::Message* message) {
- grpc::protobuf::json::JsonParseOptions options;
+grpc::protobuf::util::Status ParseJson(const char* json_str,
+ grpc::protobuf::Message* message) {
+ grpc::protobuf::json::JsonParseOptions options;
options.case_insensitive_enum_parsing = true;
- return grpc::protobuf::json::JsonStringToMessage(json_str, message, options);
-}
+ return grpc::protobuf::json::JsonStringToMessage(json_str, message, options);
+}
} // namespace
Status ChannelzService::GetTopChannels(
- ServerContext* /*unused*/,
- const channelz::v1::GetTopChannelsRequest* request,
+ ServerContext* /*unused*/,
+ const channelz::v1::GetTopChannelsRequest* request,
channelz::v1::GetTopChannelsResponse* response) {
char* json_str = grpc_channelz_get_top_channels(request->start_channel_id());
if (json_str == nullptr) {
return Status(StatusCode::INTERNAL,
"grpc_channelz_get_top_channels returned null");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
@@ -54,14 +54,14 @@ Status ChannelzService::GetTopChannels(
}
Status ChannelzService::GetServers(
- ServerContext* /*unused*/, const channelz::v1::GetServersRequest* request,
+ ServerContext* /*unused*/, const channelz::v1::GetServersRequest* request,
channelz::v1::GetServersResponse* response) {
char* json_str = grpc_channelz_get_servers(request->start_server_id());
if (json_str == nullptr) {
return Status(StatusCode::INTERNAL,
"grpc_channelz_get_servers returned null");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
@@ -69,7 +69,7 @@ Status ChannelzService::GetServers(
return Status::OK;
}
-Status ChannelzService::GetServer(ServerContext* /*unused*/,
+Status ChannelzService::GetServer(ServerContext* /*unused*/,
const channelz::v1::GetServerRequest* request,
channelz::v1::GetServerResponse* response) {
char* json_str = grpc_channelz_get_server(request->server_id());
@@ -77,7 +77,7 @@ Status ChannelzService::GetServer(ServerContext* /*unused*/,
return Status(StatusCode::INTERNAL,
"grpc_channelz_get_server returned null");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
@@ -86,8 +86,8 @@ Status ChannelzService::GetServer(ServerContext* /*unused*/,
}
Status ChannelzService::GetServerSockets(
- ServerContext* /*unused*/,
- const channelz::v1::GetServerSocketsRequest* request,
+ ServerContext* /*unused*/,
+ const channelz::v1::GetServerSocketsRequest* request,
channelz::v1::GetServerSocketsResponse* response) {
char* json_str = grpc_channelz_get_server_sockets(
request->server_id(), request->start_socket_id(), request->max_results());
@@ -95,7 +95,7 @@ Status ChannelzService::GetServerSockets(
return Status(StatusCode::INTERNAL,
"grpc_channelz_get_server_sockets returned null");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
@@ -104,13 +104,13 @@ Status ChannelzService::GetServerSockets(
}
Status ChannelzService::GetChannel(
- ServerContext* /*unused*/, const channelz::v1::GetChannelRequest* request,
+ ServerContext* /*unused*/, const channelz::v1::GetChannelRequest* request,
channelz::v1::GetChannelResponse* response) {
char* json_str = grpc_channelz_get_channel(request->channel_id());
if (json_str == nullptr) {
return Status(StatusCode::NOT_FOUND, "No object found for that ChannelId");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
@@ -119,15 +119,15 @@ Status ChannelzService::GetChannel(
}
Status ChannelzService::GetSubchannel(
- ServerContext* /*unused*/,
- const channelz::v1::GetSubchannelRequest* request,
+ ServerContext* /*unused*/,
+ const channelz::v1::GetSubchannelRequest* request,
channelz::v1::GetSubchannelResponse* response) {
char* json_str = grpc_channelz_get_subchannel(request->subchannel_id());
if (json_str == nullptr) {
return Status(StatusCode::NOT_FOUND,
"No object found for that SubchannelId");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
@@ -135,14 +135,14 @@ Status ChannelzService::GetSubchannel(
return Status::OK;
}
-Status ChannelzService::GetSocket(ServerContext* /*unused*/,
+Status ChannelzService::GetSocket(ServerContext* /*unused*/,
const channelz::v1::GetSocketRequest* request,
channelz::v1::GetSocketResponse* response) {
char* json_str = grpc_channelz_get_socket(request->socket_id());
if (json_str == nullptr) {
return Status(StatusCode::NOT_FOUND, "No object found for that SocketId");
}
- grpc::protobuf::util::Status s = ParseJson(json_str, response);
+ grpc::protobuf::util::Status s = ParseJson(json_str, response);
gpr_free(json_str);
if (!s.ok()) {
return Status(StatusCode::INTERNAL, s.ToString());
diff --git a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc
index ae26a447ab..fd1ce81424 100644
--- a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc
+++ b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc
@@ -39,7 +39,7 @@ class ChannelzServicePlugin : public ::grpc::ServerBuilderPlugin {
si->RegisterService(channelz_service_);
}
- void Finish(grpc::ServerInitializer* /*si*/) override {}
+ void Finish(grpc::ServerInitializer* /*si*/) override {}
void ChangeArguments(const TString& /*name*/, void* /*value*/) override {}
@@ -67,13 +67,13 @@ CreateChannelzServicePlugin() {
new ChannelzServicePlugin());
}
-} // namespace experimental
-} // namespace channelz
-} // namespace grpc
-namespace grpc_impl {
-namespace channelz {
-namespace experimental {
-
+} // namespace experimental
+} // namespace channelz
+} // namespace grpc
+namespace grpc_impl {
+namespace channelz {
+namespace experimental {
+
void InitChannelzService() {
static struct Initializer {
Initializer() {
@@ -85,4 +85,4 @@ void InitChannelzService() {
} // namespace experimental
} // namespace channelz
-} // namespace grpc_impl
+} // namespace grpc_impl
diff --git a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc
index 77c5d6a263..004154730b 100644
--- a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc
+++ b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc
@@ -19,7 +19,7 @@
#include "src/cpp/server/dynamic_thread_pool.h"
#include <grpc/support/log.h>
-#include <grpcpp/impl/codegen/sync.h>
+#include <grpcpp/impl/codegen/sync.h>
#include "src/core/lib/gprpp/thd.h"
@@ -39,27 +39,27 @@ DynamicThreadPool::DynamicThread::~DynamicThread() { thd_.Join(); }
void DynamicThreadPool::DynamicThread::ThreadFunc() {
pool_->ThreadFunc();
// Now that we have killed ourselves, we should reduce the thread count
- grpc_core::MutexLock lock(&pool_->mu_);
+ grpc_core::MutexLock lock(&pool_->mu_);
pool_->nthreads_--;
// Move ourselves to dead list
pool_->dead_threads_.push_back(this);
if ((pool_->shutdown_) && (pool_->nthreads_ == 0)) {
- pool_->shutdown_cv_.Signal();
+ pool_->shutdown_cv_.Signal();
}
}
void DynamicThreadPool::ThreadFunc() {
for (;;) {
// Wait until work is available or we are shutting down.
- grpc_core::ReleasableMutexLock lock(&mu_);
+ grpc_core::ReleasableMutexLock lock(&mu_);
if (!shutdown_ && callbacks_.empty()) {
// If there are too many threads waiting, then quit this thread
if (threads_waiting_ >= reserve_threads_) {
break;
}
threads_waiting_++;
- cv_.Wait(&mu_);
+ cv_.Wait(&mu_);
threads_waiting_--;
}
// Drain callbacks before considering shutdown to ensure all work
@@ -67,7 +67,7 @@ void DynamicThreadPool::ThreadFunc() {
if (!callbacks_.empty()) {
auto cb = callbacks_.front();
callbacks_.pop();
- lock.Unlock();
+ lock.Unlock();
cb();
} else if (shutdown_) {
break;
@@ -81,7 +81,7 @@ DynamicThreadPool::DynamicThreadPool(int reserve_threads)
nthreads_(0),
threads_waiting_(0) {
for (int i = 0; i < reserve_threads_; i++) {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
nthreads_++;
new DynamicThread(this);
}
@@ -94,17 +94,17 @@ void DynamicThreadPool::ReapThreads(std::list<DynamicThread*>* tlist) {
}
DynamicThreadPool::~DynamicThreadPool() {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
shutdown_ = true;
- cv_.Broadcast();
+ cv_.Broadcast();
while (nthreads_ != 0) {
- shutdown_cv_.Wait(&mu_);
+ shutdown_cv_.Wait(&mu_);
}
ReapThreads(&dead_threads_);
}
void DynamicThreadPool::Add(const std::function<void()>& callback) {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
// Add works to the callbacks list
callbacks_.push(callback);
// Increase pool size or notify as needed
@@ -113,7 +113,7 @@ void DynamicThreadPool::Add(const std::function<void()>& callback) {
nthreads_++;
new DynamicThread(this);
} else {
- cv_.Signal();
+ cv_.Signal();
}
// Also use this chance to harvest dead threads
if (!dead_threads_.empty()) {
diff --git a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h
index 6f9f943bc3..ea60265165 100644
--- a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h
+++ b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h
@@ -25,7 +25,7 @@
#include <grpcpp/support/config.h>
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/cpp/server/thread_pool_interface.h"
@@ -49,9 +49,9 @@ class DynamicThreadPool final : public ThreadPoolInterface {
grpc_core::Thread thd_;
void ThreadFunc();
};
- grpc_core::Mutex mu_;
- grpc_core::CondVar cv_;
- grpc_core::CondVar shutdown_cv_;
+ grpc_core::Mutex mu_;
+ grpc_core::CondVar cv_;
+ grpc_core::CondVar shutdown_cv_;
bool shutdown_;
std::queue<std::function<void()>> callbacks_;
int reserve_threads_;
diff --git a/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.cc b/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.cc
index 09d2a9d3b5..68bc20638e 100644
--- a/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.cc
+++ b/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.cc
@@ -1,96 +1,96 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "src/cpp/server/external_connection_acceptor_impl.h"
-
-#include <memory>
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include "src/cpp/server/external_connection_acceptor_impl.h"
+
+#include <memory>
+
#include <grpcpp/server_builder.h>
-#include <grpcpp/support/channel_arguments.h>
-
-namespace grpc {
-namespace internal {
-namespace {
-// The actual type to return to user. It co-owns the internal impl object with
-// the server.
-class AcceptorWrapper : public experimental::ExternalConnectionAcceptor {
- public:
- explicit AcceptorWrapper(std::shared_ptr<ExternalConnectionAcceptorImpl> impl)
- : impl_(std::move(impl)) {}
- void HandleNewConnection(NewConnectionParameters* p) override {
- impl_->HandleNewConnection(p);
- }
-
- private:
- std::shared_ptr<ExternalConnectionAcceptorImpl> impl_;
-};
-} // namespace
-
-ExternalConnectionAcceptorImpl::ExternalConnectionAcceptorImpl(
+#include <grpcpp/support/channel_arguments.h>
+
+namespace grpc {
+namespace internal {
+namespace {
+// The actual type to return to user. It co-owns the internal impl object with
+// the server.
+class AcceptorWrapper : public experimental::ExternalConnectionAcceptor {
+ public:
+ explicit AcceptorWrapper(std::shared_ptr<ExternalConnectionAcceptorImpl> impl)
+ : impl_(std::move(impl)) {}
+ void HandleNewConnection(NewConnectionParameters* p) override {
+ impl_->HandleNewConnection(p);
+ }
+
+ private:
+ std::shared_ptr<ExternalConnectionAcceptorImpl> impl_;
+};
+} // namespace
+
+ExternalConnectionAcceptorImpl::ExternalConnectionAcceptorImpl(
const TString& name,
- ServerBuilder::experimental_type::ExternalConnectionType type,
- std::shared_ptr<ServerCredentials> creds)
- : name_(name), creds_(std::move(creds)) {
- GPR_ASSERT(type ==
- ServerBuilder::experimental_type::ExternalConnectionType::FROM_FD);
-}
-
-std::unique_ptr<experimental::ExternalConnectionAcceptor>
-ExternalConnectionAcceptorImpl::GetAcceptor() {
- grpc_core::MutexLock lock(&mu_);
- GPR_ASSERT(!has_acceptor_);
- has_acceptor_ = true;
- return std::unique_ptr<experimental::ExternalConnectionAcceptor>(
- new AcceptorWrapper(shared_from_this()));
-}
-
-void ExternalConnectionAcceptorImpl::HandleNewConnection(
- experimental::ExternalConnectionAcceptor::NewConnectionParameters* p) {
- grpc_core::MutexLock lock(&mu_);
- if (shutdown_ || !started_) {
- // TODO(yangg) clean up.
- gpr_log(
- GPR_ERROR,
- "NOT handling external connection with fd %d, started %d, shutdown %d",
- p->fd, started_, shutdown_);
- return;
- }
- if (handler_) {
- handler_->Handle(p->listener_fd, p->fd, p->read_buffer.c_buffer());
- }
-}
-
-void ExternalConnectionAcceptorImpl::Shutdown() {
- grpc_core::MutexLock lock(&mu_);
- shutdown_ = true;
-}
-
-void ExternalConnectionAcceptorImpl::Start() {
- grpc_core::MutexLock lock(&mu_);
- GPR_ASSERT(!started_);
- GPR_ASSERT(has_acceptor_);
- GPR_ASSERT(!shutdown_);
- started_ = true;
-}
-
-void ExternalConnectionAcceptorImpl::SetToChannelArgs(ChannelArguments* args) {
- args->SetPointer(name_.c_str(), &handler_);
-}
-
-} // namespace internal
-} // namespace grpc
+ ServerBuilder::experimental_type::ExternalConnectionType type,
+ std::shared_ptr<ServerCredentials> creds)
+ : name_(name), creds_(std::move(creds)) {
+ GPR_ASSERT(type ==
+ ServerBuilder::experimental_type::ExternalConnectionType::FROM_FD);
+}
+
+std::unique_ptr<experimental::ExternalConnectionAcceptor>
+ExternalConnectionAcceptorImpl::GetAcceptor() {
+ grpc_core::MutexLock lock(&mu_);
+ GPR_ASSERT(!has_acceptor_);
+ has_acceptor_ = true;
+ return std::unique_ptr<experimental::ExternalConnectionAcceptor>(
+ new AcceptorWrapper(shared_from_this()));
+}
+
+void ExternalConnectionAcceptorImpl::HandleNewConnection(
+ experimental::ExternalConnectionAcceptor::NewConnectionParameters* p) {
+ grpc_core::MutexLock lock(&mu_);
+ if (shutdown_ || !started_) {
+ // TODO(yangg) clean up.
+ gpr_log(
+ GPR_ERROR,
+ "NOT handling external connection with fd %d, started %d, shutdown %d",
+ p->fd, started_, shutdown_);
+ return;
+ }
+ if (handler_) {
+ handler_->Handle(p->listener_fd, p->fd, p->read_buffer.c_buffer());
+ }
+}
+
+void ExternalConnectionAcceptorImpl::Shutdown() {
+ grpc_core::MutexLock lock(&mu_);
+ shutdown_ = true;
+}
+
+void ExternalConnectionAcceptorImpl::Start() {
+ grpc_core::MutexLock lock(&mu_);
+ GPR_ASSERT(!started_);
+ GPR_ASSERT(has_acceptor_);
+ GPR_ASSERT(!shutdown_);
+ started_ = true;
+}
+
+void ExternalConnectionAcceptorImpl::SetToChannelArgs(ChannelArguments* args) {
+ args->SetPointer(name_.c_str(), &handler_);
+}
+
+} // namespace internal
+} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.h b/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.h
index 430c72862e..2340c6e248 100644
--- a/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.h
+++ b/contrib/libs/grpc/src/cpp/server/external_connection_acceptor_impl.h
@@ -1,71 +1,71 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef SRC_CPP_SERVER_EXTERNAL_CONNECTION_ACCEPTOR_IMPL_H_
-#define SRC_CPP_SERVER_EXTERNAL_CONNECTION_ACCEPTOR_IMPL_H_
-
-#include <memory>
-
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/support/channel_arguments.h>
-
-#include "src/core/lib/gprpp/sync.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-
-namespace grpc {
-namespace internal {
-
-class ExternalConnectionAcceptorImpl
- : public std::enable_shared_from_this<ExternalConnectionAcceptorImpl> {
- public:
- ExternalConnectionAcceptorImpl(
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef SRC_CPP_SERVER_EXTERNAL_CONNECTION_ACCEPTOR_IMPL_H_
+#define SRC_CPP_SERVER_EXTERNAL_CONNECTION_ACCEPTOR_IMPL_H_
+
+#include <memory>
+
+#include <grpc/impl/codegen/grpc_types.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/support/channel_arguments.h>
+
+#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+
+namespace grpc {
+namespace internal {
+
+class ExternalConnectionAcceptorImpl
+ : public std::enable_shared_from_this<ExternalConnectionAcceptorImpl> {
+ public:
+ ExternalConnectionAcceptorImpl(
const TString& name,
- ServerBuilder::experimental_type::ExternalConnectionType type,
- std::shared_ptr<ServerCredentials> creds);
- // Should only be called once.
- std::unique_ptr<experimental::ExternalConnectionAcceptor> GetAcceptor();
-
- void HandleNewConnection(
- experimental::ExternalConnectionAcceptor::NewConnectionParameters* p);
-
- void Shutdown();
-
- void Start();
-
- const char* name() { return name_.c_str(); }
-
- ServerCredentials* GetCredentials() { return creds_.get(); }
-
- void SetToChannelArgs(::grpc::ChannelArguments* args);
-
- private:
+ ServerBuilder::experimental_type::ExternalConnectionType type,
+ std::shared_ptr<ServerCredentials> creds);
+ // Should only be called once.
+ std::unique_ptr<experimental::ExternalConnectionAcceptor> GetAcceptor();
+
+ void HandleNewConnection(
+ experimental::ExternalConnectionAcceptor::NewConnectionParameters* p);
+
+ void Shutdown();
+
+ void Start();
+
+ const char* name() { return name_.c_str(); }
+
+ ServerCredentials* GetCredentials() { return creds_.get(); }
+
+ void SetToChannelArgs(::grpc::ChannelArguments* args);
+
+ private:
const TString name_;
- std::shared_ptr<ServerCredentials> creds_;
- grpc_core::TcpServerFdHandler* handler_ = nullptr; // not owned
- grpc_core::Mutex mu_;
- bool has_acceptor_ = false;
- bool started_ = false;
- bool shutdown_ = false;
-};
-
-} // namespace internal
-} // namespace grpc
-
-#endif // SRC_CPP_SERVER_EXTERNAL_CONNECTION_ACCEPTOR_IMPL_H_
+ std::shared_ptr<ServerCredentials> creds_;
+ grpc_core::TcpServerFdHandler* handler_ = nullptr; // not owned
+ grpc_core::Mutex mu_;
+ bool has_acceptor_ = false;
+ bool started_ = false;
+ bool shutdown_ = false;
+};
+
+} // namespace internal
+} // namespace grpc
+
+#endif // SRC_CPP_SERVER_EXTERNAL_CONNECTION_ACCEPTOR_IMPL_H_
diff --git a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc
index 3cc508d0cb..133a13e028 100644
--- a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc
+++ b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc
@@ -26,11 +26,11 @@
#include <grpcpp/impl/codegen/method_handler.h>
#include "src/cpp/server/health/default_health_check_service.h"
-#include "src/proto/grpc/health/v1/health.upb.h"
+#include "src/proto/grpc/health/v1/health.upb.h"
#include "upb/upb.hpp"
-#define MAX_SERVICE_NAME_LENGTH 200
-
+#define MAX_SERVICE_NAME_LENGTH 200
+
namespace grpc {
//
@@ -43,7 +43,7 @@ DefaultHealthCheckService::DefaultHealthCheckService() {
void DefaultHealthCheckService::SetServingStatus(
const TString& service_name, bool serving) {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
if (shutdown_) {
// Set to NOT_SERVING in case service_name is not in the map.
serving = false;
@@ -53,7 +53,7 @@ void DefaultHealthCheckService::SetServingStatus(
void DefaultHealthCheckService::SetServingStatus(bool serving) {
const ServingStatus status = serving ? SERVING : NOT_SERVING;
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
if (shutdown_) {
return;
}
@@ -64,7 +64,7 @@ void DefaultHealthCheckService::SetServingStatus(bool serving) {
}
void DefaultHealthCheckService::Shutdown() {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
if (shutdown_) {
return;
}
@@ -78,7 +78,7 @@ void DefaultHealthCheckService::Shutdown() {
DefaultHealthCheckService::ServingStatus
DefaultHealthCheckService::GetServingStatus(
const TString& service_name) const {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
auto it = services_map_.find(service_name);
if (it == services_map_.end()) {
return NOT_FOUND;
@@ -90,7 +90,7 @@ DefaultHealthCheckService::GetServingStatus(
void DefaultHealthCheckService::RegisterCallHandler(
const TString& service_name,
std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler) {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
ServiceData& service_data = services_map_[service_name];
service_data.AddCallHandler(handler /* copies ref */);
HealthCheckServiceImpl::CallHandler* h = handler.get();
@@ -100,7 +100,7 @@ void DefaultHealthCheckService::RegisterCallHandler(
void DefaultHealthCheckService::UnregisterCallHandler(
const TString& service_name,
const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler) {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
auto it = services_map_.find(service_name);
if (it == services_map_.end()) return;
ServiceData& service_data = it->second;
@@ -168,7 +168,7 @@ DefaultHealthCheckService::HealthCheckServiceImpl::~HealthCheckServiceImpl() {
// We will reach here after the server starts shutting down.
shutdown_ = true;
{
- grpc_core::MutexLock lock(&cq_shutdown_mu_);
+ grpc_core::MutexLock lock(&cq_shutdown_mu_);
cq_->Shutdown();
}
thread_->Join();
@@ -216,43 +216,43 @@ bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest(
copy_to += slices[i].size();
}
}
- upb::Arena arena;
- grpc_health_v1_HealthCheckRequest* request_struct =
- grpc_health_v1_HealthCheckRequest_parse(
- reinterpret_cast<char*>(request_bytes), request_size, arena.ptr());
+ upb::Arena arena;
+ grpc_health_v1_HealthCheckRequest* request_struct =
+ grpc_health_v1_HealthCheckRequest_parse(
+ reinterpret_cast<char*>(request_bytes), request_size, arena.ptr());
if (slices.size() > 1) {
gpr_free(request_bytes);
}
- if (request_struct == nullptr) {
- return false;
- }
- upb_strview service =
- grpc_health_v1_HealthCheckRequest_service(request_struct);
- if (service.size > MAX_SERVICE_NAME_LENGTH) {
- return false;
- }
- service_name->assign(service.data, service.size);
+ if (request_struct == nullptr) {
+ return false;
+ }
+ upb_strview service =
+ grpc_health_v1_HealthCheckRequest_service(request_struct);
+ if (service.size > MAX_SERVICE_NAME_LENGTH) {
+ return false;
+ }
+ service_name->assign(service.data, service.size);
return true;
}
bool DefaultHealthCheckService::HealthCheckServiceImpl::EncodeResponse(
ServingStatus status, ByteBuffer* response) {
- upb::Arena arena;
- grpc_health_v1_HealthCheckResponse* response_struct =
- grpc_health_v1_HealthCheckResponse_new(arena.ptr());
- grpc_health_v1_HealthCheckResponse_set_status(
- response_struct,
+ upb::Arena arena;
+ grpc_health_v1_HealthCheckResponse* response_struct =
+ grpc_health_v1_HealthCheckResponse_new(arena.ptr());
+ grpc_health_v1_HealthCheckResponse_set_status(
+ response_struct,
status == NOT_FOUND
- ? grpc_health_v1_HealthCheckResponse_SERVICE_UNKNOWN
- : status == SERVING ? grpc_health_v1_HealthCheckResponse_SERVING
- : grpc_health_v1_HealthCheckResponse_NOT_SERVING);
- size_t buf_length;
- char* buf = grpc_health_v1_HealthCheckResponse_serialize(
- response_struct, arena.ptr(), &buf_length);
- if (buf == nullptr) {
- return false;
- }
- grpc_slice response_slice = grpc_slice_from_copied_buffer(buf, buf_length);
+ ? grpc_health_v1_HealthCheckResponse_SERVICE_UNKNOWN
+ : status == SERVING ? grpc_health_v1_HealthCheckResponse_SERVING
+ : grpc_health_v1_HealthCheckResponse_NOT_SERVING);
+ size_t buf_length;
+ char* buf = grpc_health_v1_HealthCheckResponse_serialize(
+ response_struct, arena.ptr(), &buf_length);
+ if (buf == nullptr) {
+ return false;
+ }
+ grpc_slice response_slice = grpc_slice_from_copied_buffer(buf, buf_length);
Slice encoded_response(response_slice, Slice::STEAL_REF);
ByteBuffer response_buffer(&encoded_response, 1);
response->Swap(&response_buffer);
@@ -271,7 +271,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler::
std::make_shared<CheckCallHandler>(cq, database, service);
CheckCallHandler* handler = static_cast<CheckCallHandler*>(self.get());
{
- grpc_core::MutexLock lock(&service->cq_shutdown_mu_);
+ grpc_core::MutexLock lock(&service->cq_shutdown_mu_);
if (service->shutdown_) return;
// Request a Check() call.
handler->next_ =
@@ -316,7 +316,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler::
}
// Send response.
{
- grpc_core::MutexLock lock(&service_->cq_shutdown_mu_);
+ grpc_core::MutexLock lock(&service_->cq_shutdown_mu_);
if (!service_->shutdown_) {
next_ =
CallableTag(std::bind(&CheckCallHandler::OnFinishDone, this,
@@ -352,7 +352,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
std::make_shared<WatchCallHandler>(cq, database, service);
WatchCallHandler* handler = static_cast<WatchCallHandler*>(self.get());
{
- grpc_core::MutexLock lock(&service->cq_shutdown_mu_);
+ grpc_core::MutexLock lock(&service->cq_shutdown_mu_);
if (service->shutdown_) return;
// Request AsyncNotifyWhenDone().
handler->on_done_notified_ =
@@ -407,7 +407,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
SendHealth(std::shared_ptr<CallHandler> self, ServingStatus status) {
- grpc_core::MutexLock lock(&send_mu_);
+ grpc_core::MutexLock lock(&send_mu_);
// If there's already a send in flight, cache the new status, and
// we'll start a new send for it when the one in flight completes.
if (send_in_flight_) {
@@ -425,7 +425,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
ByteBuffer response;
bool success = service_->EncodeResponse(status, &response);
// Grab shutdown lock and send response.
- grpc_core::MutexLock cq_lock(&service_->cq_shutdown_mu_);
+ grpc_core::MutexLock cq_lock(&service_->cq_shutdown_mu_);
if (service_->shutdown_) {
SendFinishLocked(std::move(self), Status::CANCELLED);
return;
@@ -447,7 +447,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
SendFinish(std::move(self), Status::CANCELLED);
return;
}
- grpc_core::MutexLock lock(&send_mu_);
+ grpc_core::MutexLock lock(&send_mu_);
send_in_flight_ = false;
// If we got a new status since we started the last send, start a
// new send for it.
@@ -461,7 +461,7 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
SendFinish(std::shared_ptr<CallHandler> self, const Status& status) {
if (finish_called_) return;
- grpc_core::MutexLock cq_lock(&service_->cq_shutdown_mu_);
+ grpc_core::MutexLock cq_lock(&service_->cq_shutdown_mu_);
if (service_->shutdown_) return;
SendFinishLocked(std::move(self), status);
}
diff --git a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h
index 9da1dfc15f..ad6a583294 100644
--- a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h
+++ b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h
@@ -27,11 +27,11 @@
#include <grpcpp/health_check_service_interface.h>
#include <grpcpp/impl/codegen/async_generic_service.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
-#include <grpcpp/impl/codegen/completion_queue.h>
+#include <grpcpp/impl/codegen/completion_queue.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/support/byte_buffer.h>
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/gprpp/thd.h"
namespace grpc {
@@ -119,8 +119,8 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
HealthCheckServiceImpl* service);
// Not used for Check.
- void SendHealth(std::shared_ptr<CallHandler> /*self*/,
- ServingStatus /*status*/) override {}
+ void SendHealth(std::shared_ptr<CallHandler> /*self*/,
+ ServingStatus /*status*/) override {}
private:
// Called when we receive a call.
@@ -198,7 +198,7 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
GenericServerAsyncWriter stream_;
ServerContext ctx_;
- grpc_core::Mutex send_mu_;
+ grpc_core::Mutex send_mu_;
bool send_in_flight_ = false; // Guarded by mu_.
ServingStatus pending_status_ = NOT_FOUND; // Guarded by mu_.
@@ -227,7 +227,7 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
// To synchronize the operations related to shutdown state of cq_, so that
// we don't enqueue new tags into cq_ after it is already shut down.
- grpc_core::Mutex cq_shutdown_mu_;
+ grpc_core::Mutex cq_shutdown_mu_;
std::atomic_bool shutdown_{false};
std::unique_ptr<::grpc_core::Thread> thread_;
};
@@ -273,7 +273,7 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
const TString& service_name,
const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler);
- mutable grpc_core::Mutex mu_;
+ mutable grpc_core::Mutex mu_;
bool shutdown_ = false; // Guarded by mu_.
std::map<TString, ServiceData> services_map_; // Guarded by mu_.
std::unique_ptr<HealthCheckServiceImpl> impl_;
diff --git a/contrib/libs/grpc/src/cpp/server/health/health_check_service_server_builder_option.cc b/contrib/libs/grpc/src/cpp/server/health/health_check_service_server_builder_option.cc
index 3fa384ace9..1d47d67a32 100644
--- a/contrib/libs/grpc/src/cpp/server/health/health_check_service_server_builder_option.cc
+++ b/contrib/libs/grpc/src/cpp/server/health/health_check_service_server_builder_option.cc
@@ -30,6 +30,6 @@ void HealthCheckServiceServerBuilderOption::UpdateArguments(
}
void HealthCheckServiceServerBuilderOption::UpdatePlugins(
- std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/) {}
+ std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/) {}
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc b/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc
index 3f33f4e045..1564bf6f4f 100644
--- a/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc
@@ -29,7 +29,7 @@ class InsecureServerCredentialsImpl final : public ServerCredentials {
return grpc_server_add_insecure_http2_port(server, addr.c_str());
}
void SetAuthMetadataProcessor(
- const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) override {
+ const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) override {
(void)processor;
GPR_ASSERT(0); // Should not be called on InsecureServerCredentials.
}
diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc
index 561d4f5048..d5f7f6973b 100644
--- a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc
+++ b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc
@@ -32,10 +32,10 @@ std::pair<uint64_t, uint64_t> GetCpuStatsImpl() {
FILE* fp;
fp = fopen("/proc/stat", "r");
uint64_t user, nice, system, idle;
- if (fscanf(fp, "cpu %lu %lu %lu %lu", &user, &nice, &system, &idle) != 4) {
- // Something bad happened with the information, so assume it's all invalid
- user = nice = system = idle = 0;
- }
+ if (fscanf(fp, "cpu %lu %lu %lu %lu", &user, &nice, &system, &idle) != 4) {
+ // Something bad happened with the information, so assume it's all invalid
+ user = nice = system = idle = 0;
+ }
fclose(fp);
busy = user + nice + system;
total = busy + idle;
diff --git a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc
index 732602bcb7..580e00b99b 100644
--- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc
@@ -70,18 +70,18 @@ void AuthMetadataProcessorAyncWrapper::InvokeProcessor(
&response_metadata);
std::vector<grpc_metadata> consumed_md;
- for (const auto& consumed : consumed_metadata) {
+ for (const auto& consumed : consumed_metadata) {
grpc_metadata md_entry;
- md_entry.key = SliceReferencingString(consumed.first);
- md_entry.value = SliceReferencingString(consumed.second);
+ md_entry.key = SliceReferencingString(consumed.first);
+ md_entry.value = SliceReferencingString(consumed.second);
md_entry.flags = 0;
consumed_md.push_back(md_entry);
}
std::vector<grpc_metadata> response_md;
- for (const auto& response : response_metadata) {
+ for (const auto& response : response_metadata) {
grpc_metadata md_entry;
- md_entry.key = SliceReferencingString(response.first);
- md_entry.value = SliceReferencingString(response.second);
+ md_entry.key = SliceReferencingString(response.first);
+ md_entry.value = SliceReferencingString(response.second);
md_entry.flags = 0;
response_md.push_back(md_entry);
}
@@ -98,19 +98,19 @@ int SecureServerCredentials::AddPortToServer(const TString& addr,
}
void SecureServerCredentials::SetAuthMetadataProcessor(
- const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) {
- auto* wrapper = new grpc::AuthMetadataProcessorAyncWrapper(processor);
+ const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) {
+ auto* wrapper = new grpc::AuthMetadataProcessorAyncWrapper(processor);
grpc_server_credentials_set_auth_metadata_processor(
- creds_, {grpc::AuthMetadataProcessorAyncWrapper::Process,
- grpc::AuthMetadataProcessorAyncWrapper::Destroy, wrapper});
+ creds_, {grpc::AuthMetadataProcessorAyncWrapper::Process,
+ grpc::AuthMetadataProcessorAyncWrapper::Destroy, wrapper});
}
std::shared_ptr<ServerCredentials> SslServerCredentials(
- const grpc::SslServerCredentialsOptions& options) {
+ const grpc::SslServerCredentialsOptions& options) {
std::vector<grpc_ssl_pem_key_cert_pair> pem_key_cert_pairs;
- for (const auto& key_cert_pair : options.pem_key_cert_pairs) {
- grpc_ssl_pem_key_cert_pair p = {key_cert_pair.private_key.c_str(),
- key_cert_pair.cert_chain.c_str()};
+ for (const auto& key_cert_pair : options.pem_key_cert_pairs) {
+ grpc_ssl_pem_key_cert_pair p = {key_cert_pair.private_key.c_str(),
+ key_cert_pair.cert_chain.c_str()};
pem_key_cert_pairs.push_back(p);
}
grpc_server_credentials* c_creds = grpc_ssl_server_credentials_create_ex(
@@ -128,7 +128,7 @@ std::shared_ptr<ServerCredentials> SslServerCredentials(
namespace experimental {
std::shared_ptr<ServerCredentials> AltsServerCredentials(
- const AltsServerCredentialsOptions& /* options */) {
+ const AltsServerCredentialsOptions& /* options */) {
grpc_alts_credentials_options* c_options =
grpc_alts_credentials_server_options_create();
grpc_server_credentials* c_creds =
@@ -144,12 +144,12 @@ std::shared_ptr<ServerCredentials> LocalServerCredentials(
new SecureServerCredentials(grpc_local_server_credentials_create(type)));
}
-std::shared_ptr<ServerCredentials> TlsServerCredentials(
+std::shared_ptr<ServerCredentials> TlsServerCredentials(
const grpc::experimental::TlsCredentialsOptions& options) {
grpc::GrpcLibraryCodegen init;
return std::shared_ptr<ServerCredentials>(new SecureServerCredentials(
grpc_tls_server_credentials_create(options.c_credentials_options())));
-}
-
+}
+
} // namespace experimental
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h
index 9e3fb3f9eb..945bb445cc 100644
--- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h
+++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h
@@ -22,16 +22,16 @@
#include <memory>
#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/security/tls_credentials_options.h>
+#include <grpcpp/security/tls_credentials_options.h>
#include <grpc/grpc_security.h>
#include "src/cpp/server/thread_pool_interface.h"
namespace grpc {
-
-class SecureServerCredentials;
-
+
+class SecureServerCredentials;
+
class AuthMetadataProcessorAyncWrapper final {
public:
static void Destroy(void* wrapper);
@@ -42,11 +42,11 @@ class AuthMetadataProcessorAyncWrapper final {
AuthMetadataProcessorAyncWrapper(
const std::shared_ptr<AuthMetadataProcessor>& processor)
- : processor_(processor) {
- if (processor && processor->IsBlocking()) {
- thread_pool_.reset(CreateDefaultThreadPool());
- }
- }
+ : processor_(processor) {
+ if (processor && processor->IsBlocking()) {
+ thread_pool_.reset(CreateDefaultThreadPool());
+ }
+ }
private:
void InvokeProcessor(grpc_auth_context* context, const grpc_metadata* md,
@@ -67,11 +67,11 @@ class SecureServerCredentials final : public ServerCredentials {
int AddPortToServer(const TString& addr, grpc_server* server) override;
void SetAuthMetadataProcessor(
- const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) override;
+ const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) override;
private:
grpc_server_credentials* creds_;
- std::unique_ptr<grpc::AuthMetadataProcessorAyncWrapper> processor_;
+ std::unique_ptr<grpc::AuthMetadataProcessorAyncWrapper> processor_;
};
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/server_builder.cc b/contrib/libs/grpc/src/cpp/server/server_builder.cc
index 0cc00b365f..92324cb5e6 100644
--- a/contrib/libs/grpc/src/cpp/server/server_builder.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_builder.cc
@@ -27,9 +27,9 @@
#include <utility>
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/cpp/server/external_connection_acceptor_impl.h"
+#include "src/cpp/server/external_connection_acceptor_impl.h"
#include "src/cpp/server/thread_pool_interface.h"
namespace grpc {
@@ -47,10 +47,10 @@ ServerBuilder::ServerBuilder()
: max_receive_message_size_(INT_MIN),
max_send_message_size_(INT_MIN),
sync_server_settings_(SyncServerSettings()),
- resource_quota_(nullptr) {
+ resource_quota_(nullptr) {
gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
- for (const auto& value : *g_plugin_factory_list) {
- plugins_.emplace_back(value());
+ for (const auto& value : *g_plugin_factory_list) {
+ plugins_.emplace_back(value());
}
// all compression algorithms enabled by default.
@@ -91,9 +91,9 @@ ServerBuilder& ServerBuilder::RegisterService(const TString& addr,
ServerBuilder& ServerBuilder::RegisterAsyncGenericService(
AsyncGenericService* service) {
- if (generic_service_ || callback_generic_service_) {
+ if (generic_service_ || callback_generic_service_) {
gpr_log(GPR_ERROR,
- "Adding multiple generic services is unsupported for now. "
+ "Adding multiple generic services is unsupported for now. "
"Dropping the service %p",
(void*)service);
} else {
@@ -116,33 +116,33 @@ ServerBuilder& ServerBuilder::RegisterCallbackGenericService(
return *this;
}
#else
-ServerBuilder& ServerBuilder::experimental_type::RegisterCallbackGenericService(
+ServerBuilder& ServerBuilder::experimental_type::RegisterCallbackGenericService(
experimental::CallbackGenericService* service) {
- if (builder_->generic_service_ || builder_->callback_generic_service_) {
- gpr_log(GPR_ERROR,
- "Adding multiple generic services is unsupported for now. "
- "Dropping the service %p",
- (void*)service);
- } else {
- builder_->callback_generic_service_ = service;
- }
- return *builder_;
-}
+ if (builder_->generic_service_ || builder_->callback_generic_service_) {
+ gpr_log(GPR_ERROR,
+ "Adding multiple generic services is unsupported for now. "
+ "Dropping the service %p",
+ (void*)service);
+ } else {
+ builder_->callback_generic_service_ = service;
+ }
+ return *builder_;
+}
#endif
-
-std::unique_ptr<grpc::experimental::ExternalConnectionAcceptor>
-ServerBuilder::experimental_type::AddExternalConnectionAcceptor(
- experimental_type::ExternalConnectionType type,
- std::shared_ptr<ServerCredentials> creds) {
+
+std::unique_ptr<grpc::experimental::ExternalConnectionAcceptor>
+ServerBuilder::experimental_type::AddExternalConnectionAcceptor(
+ experimental_type::ExternalConnectionType type,
+ std::shared_ptr<ServerCredentials> creds) {
TString name_prefix("external:");
- char count_str[GPR_LTOA_MIN_BUFSIZE];
- gpr_ltoa(static_cast<long>(builder_->acceptors_.size()), count_str);
- builder_->acceptors_.emplace_back(
- std::make_shared<grpc::internal::ExternalConnectionAcceptorImpl>(
- name_prefix.append(count_str), type, creds));
- return builder_->acceptors_.back()->GetAcceptor();
-}
-
+ char count_str[GPR_LTOA_MIN_BUFSIZE];
+ gpr_ltoa(static_cast<long>(builder_->acceptors_.size()), count_str);
+ builder_->acceptors_.emplace_back(
+ std::make_shared<grpc::internal::ExternalConnectionAcceptorImpl>(
+ name_prefix.append(count_str), type, creds));
+ return builder_->acceptors_.back()->GetAcceptor();
+}
+
ServerBuilder& ServerBuilder::SetOption(
std::unique_ptr<ServerBuilderOption> option) {
options_.push_back(std::move(option));
@@ -217,8 +217,8 @@ ServerBuilder& ServerBuilder::AddListeningPort(
return *this;
}
-std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
- grpc::ChannelArguments args;
+std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
+ grpc::ChannelArguments args;
if (max_receive_message_size_ >= -1) {
args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_);
}
@@ -252,16 +252,16 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
// == Determine if the server has any syncrhonous methods ==
bool has_sync_methods = false;
- for (const auto& value : services_) {
- if (value->service->has_synchronous_methods()) {
+ for (const auto& value : services_) {
+ if (value->service->has_synchronous_methods()) {
has_sync_methods = true;
break;
}
}
if (!has_sync_methods) {
- for (const auto& value : plugins_) {
- if (value->has_sync_methods()) {
+ for (const auto& value : plugins_) {
+ if (value->has_sync_methods()) {
has_sync_methods = true;
break;
}
@@ -280,26 +280,26 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
std::make_shared<
std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>());
- bool has_frequently_polled_cqs = false;
- for (const auto& cq : cqs_) {
- if (cq->IsFrequentlyPolled()) {
- has_frequently_polled_cqs = true;
- break;
- }
- }
-
- // == Determine if the server has any callback methods ==
- bool has_callback_methods = false;
- for (const auto& service : services_) {
- if (service->service->has_callback_methods()) {
- has_callback_methods = true;
- has_frequently_polled_cqs = true;
- break;
+ bool has_frequently_polled_cqs = false;
+ for (const auto& cq : cqs_) {
+ if (cq->IsFrequentlyPolled()) {
+ has_frequently_polled_cqs = true;
+ break;
}
}
- const bool is_hybrid_server = has_sync_methods && has_frequently_polled_cqs;
+ // == Determine if the server has any callback methods ==
+ bool has_callback_methods = false;
+ for (const auto& service : services_) {
+ if (service->service->has_callback_methods()) {
+ has_callback_methods = true;
+ has_frequently_polled_cqs = true;
+ break;
+ }
+ }
+ const bool is_hybrid_server = has_sync_methods && has_frequently_polled_cqs;
+
if (has_sync_methods) {
grpc_cq_polling_type polling_type =
is_hybrid_server ? GRPC_CQ_NON_POLLING : GRPC_CQ_DEFAULT_POLLING;
@@ -328,7 +328,7 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
gpr_log(GPR_INFO, "Callback server.");
}
- std::unique_ptr<grpc::Server> server(new grpc::Server(
+ std::unique_ptr<grpc::Server> server(new grpc::Server(
&args, sync_server_cqs, sync_server_settings_.min_pollers,
sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec,
std::move(acceptors_), resource_quota_,
@@ -343,10 +343,10 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
for (const auto& cq : *sync_server_cqs) {
grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr);
- has_frequently_polled_cqs = true;
+ has_frequently_polled_cqs = true;
}
- if (has_callback_methods || callback_generic_service_ != nullptr) {
+ if (has_callback_methods || callback_generic_service_ != nullptr) {
auto* cq = server->CallbackCQ();
grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr);
}
@@ -363,29 +363,29 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
cq->RegisterServer(server.get());
}
- if (!has_frequently_polled_cqs) {
+ if (!has_frequently_polled_cqs) {
gpr_log(GPR_ERROR,
"At least one of the completion queues must be frequently polled");
return nullptr;
}
- for (const auto& value : services_) {
- if (!server->RegisterService(value->host.get(), value->service)) {
+ for (const auto& value : services_) {
+ if (!server->RegisterService(value->host.get(), value->service)) {
return nullptr;
}
}
- for (const auto& value : plugins_) {
- value->InitServer(initializer);
+ for (const auto& value : plugins_) {
+ value->InitServer(initializer);
}
if (generic_service_) {
server->RegisterAsyncGenericService(generic_service_);
- } else if (callback_generic_service_) {
- server->RegisterCallbackGenericService(callback_generic_service_);
+ } else if (callback_generic_service_) {
+ server->RegisterCallbackGenericService(callback_generic_service_);
} else {
- for (const auto& value : services_) {
- if (value->service->has_generic_methods()) {
+ for (const auto& value : services_) {
+ if (value->service->has_generic_methods()) {
gpr_log(GPR_ERROR,
"Some methods were marked generic but there is no "
"generic service registered.");
@@ -394,22 +394,22 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
}
}
- for (auto& port : ports_) {
- int r = server->AddListeningPort(port.addr, port.creds.get());
+ for (auto& port : ports_) {
+ int r = server->AddListeningPort(port.addr, port.creds.get());
if (!r) {
server->Shutdown();
return nullptr;
}
- if (port.selected_port != nullptr) {
- *port.selected_port = r;
+ if (port.selected_port != nullptr) {
+ *port.selected_port = r;
}
}
auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0];
server->Start(cqs_data, cqs_.size());
- for (const auto& value : plugins_) {
- value->Finish(initializer);
+ for (const auto& value : plugins_) {
+ value->Finish(initializer);
}
return server;
diff --git a/contrib/libs/grpc/src/cpp/server/server_callback.cc b/contrib/libs/grpc/src/cpp/server/server_callback.cc
index 40aef8e735..04a776fac1 100644
--- a/contrib/libs/grpc/src/cpp/server/server_callback.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_callback.cc
@@ -1,29 +1,29 @@
-/*
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
+/*
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
#include <grpcpp/impl/codegen/server_callback.h>
-
-#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/executor.h"
-
+
+#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/executor.h"
+
namespace grpc {
-namespace internal {
-
+namespace internal {
+
void ServerCallbackCall::ScheduleOnDone(bool inline_ondone) {
if (inline_ondone) {
CallOnDone();
@@ -50,18 +50,18 @@ void ServerCallbackCall::ScheduleOnDone(bool inline_ondone) {
}
}
-void ServerCallbackCall::CallOnCancel(ServerReactor* reactor) {
- if (reactor->InternalInlineable()) {
- reactor->OnCancel();
- } else {
+void ServerCallbackCall::CallOnCancel(ServerReactor* reactor) {
+ if (reactor->InternalInlineable()) {
+ reactor->OnCancel();
+ } else {
// Ref to make sure that the closure executes before the whole call gets
// destructed, and Unref within the closure.
- Ref();
- grpc_core::ExecCtx exec_ctx;
+ Ref();
+ grpc_core::ExecCtx exec_ctx;
struct ClosureWithArg {
grpc_closure closure;
- ServerCallbackCall* call;
- ServerReactor* reactor;
+ ServerCallbackCall* call;
+ ServerReactor* reactor;
ClosureWithArg(ServerCallbackCall* call_arg, ServerReactor* reactor_arg)
: call(call_arg), reactor(reactor_arg) {
GRPC_CLOSURE_INIT(&closure,
@@ -74,11 +74,11 @@ void ServerCallbackCall::CallOnCancel(ServerReactor* reactor) {
},
this, grpc_schedule_on_exec_ctx);
}
- };
+ };
ClosureWithArg* arg = new ClosureWithArg(this, reactor);
grpc_core::Executor::Run(&arg->closure, GRPC_ERROR_NONE);
- }
-}
-
-} // namespace internal
+ }
+}
+
+} // namespace internal
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/server_cc.cc b/contrib/libs/grpc/src/cpp/server/server_cc.cc
index c2a911c7f7..5cf50d9266 100644
--- a/contrib/libs/grpc/src/cpp/server/server_cc.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_cc.cc
@@ -19,7 +19,7 @@
#include <cstdlib>
#include <sstream>
-#include <type_traits>
+#include <type_traits>
#include <utility>
#include <grpc/grpc.h>
@@ -29,10 +29,10 @@
#include <grpcpp/completion_queue.h>
#include <grpcpp/generic/async_generic_service.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
-#include <grpcpp/impl/codegen/byte_buffer.h>
+#include <grpcpp/impl/codegen/byte_buffer.h>
#include <grpcpp/impl/codegen/call.h>
#include <grpcpp/impl/codegen/completion_queue_tag.h>
-#include <grpcpp/impl/codegen/method_handler.h>
+#include <grpcpp/impl/codegen/method_handler.h>
#include <grpcpp/impl/codegen/server_interceptor.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/impl/rpc_service_method.h>
@@ -49,7 +49,7 @@
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/server.h"
#include "src/cpp/client/create_channel_internal.h"
-#include "src/cpp/server/external_connection_acceptor_impl.h"
+#include "src/cpp/server/external_connection_acceptor_impl.h"
#include "src/cpp/server/health/default_health_check_service.h"
#include "src/cpp/thread_manager/thread_manager.h"
@@ -68,8 +68,8 @@ namespace {
class DefaultGlobalCallbacks final : public Server::GlobalCallbacks {
public:
~DefaultGlobalCallbacks() override {}
- void PreSynchronousRequest(ServerContext* /*context*/) override {}
- void PostSynchronousRequest(ServerContext* /*context*/) override {}
+ void PreSynchronousRequest(ServerContext* /*context*/) override {}
+ void PostSynchronousRequest(ServerContext* /*context*/) override {}
};
std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
@@ -83,12 +83,12 @@ void InitGlobalCallbacks() {
class ShutdownTag : public internal::CompletionQueueTag {
public:
- bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return false; }
+ bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return false; }
};
class DummyTag : public internal::CompletionQueueTag {
public:
- bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return true; }
+ bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return true; }
};
class UnimplementedAsyncRequestContext {
@@ -110,187 +110,187 @@ using ::grpc::experimental::GenericCallbackServerContext;
} // namespace
-ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
- ServerInterface* server, ServerContext* context,
- internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
- ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
- : server_(server),
- context_(context),
- stream_(stream),
- call_cq_(call_cq),
- notification_cq_(notification_cq),
- tag_(tag),
- delete_on_finalize_(delete_on_finalize),
- call_(nullptr),
- done_intercepting_(false) {
- /* Set up interception state partially for the receive ops. call_wrapper_ is
- * not filled at this point, but it will be filled before the interceptors are
- * run. */
- interceptor_methods_.SetCall(&call_wrapper_);
- interceptor_methods_.SetReverse();
- call_cq_->RegisterAvalanching(); // This op will trigger more ops
-}
-
-ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
- call_cq_->CompleteAvalanching();
-}
-
-bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
- bool* status) {
- if (done_intercepting_) {
- *tag = tag_;
- if (delete_on_finalize_) {
- delete this;
- }
- return true;
- }
- context_->set_call(call_);
- context_->cq_ = call_cq_;
- if (call_wrapper_.call() == nullptr) {
- // Fill it since it is empty.
- call_wrapper_ = internal::Call(
- call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
- }
-
- // just the pointers inside call are copied here
- stream_->BindCall(&call_wrapper_);
-
- if (*status && call_ && call_wrapper_.server_rpc_info()) {
- done_intercepting_ = true;
- // Set interception point for RECV INITIAL METADATA
- interceptor_methods_.AddInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
- interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
- if (interceptor_methods_.RunInterceptors(
- [this]() { ContinueFinalizeResultAfterInterception(); })) {
- // There are no interceptors to run. Continue
- } else {
- // There were interceptors to be run, so
- // ContinueFinalizeResultAfterInterception will be run when interceptors
- // are done.
- return false;
- }
- }
- if (*status && call_) {
- context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
- }
- *tag = tag_;
- if (delete_on_finalize_) {
- delete this;
- }
- return true;
-}
-
-void ServerInterface::BaseAsyncRequest::
- ContinueFinalizeResultAfterInterception() {
- context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
- // Queue a tag which will be returned immediately
- grpc_core::ExecCtx exec_ctx;
- grpc_cq_begin_op(notification_cq_->cq(), this);
- grpc_cq_end_op(
- notification_cq_->cq(), this, GRPC_ERROR_NONE,
- [](void* /*arg*/, grpc_cq_completion* completion) { delete completion; },
- nullptr, new grpc_cq_completion());
-}
-
-ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
- ServerInterface* server, ServerContext* context,
- internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
- ServerCompletionQueue* notification_cq, void* tag, const char* name,
- internal::RpcMethod::RpcType type)
- : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
- true),
- name_(name),
- type_(type) {}
-
-void ServerInterface::RegisteredAsyncRequest::IssueRequest(
- void* registered_method, grpc_byte_buffer** payload,
- ServerCompletionQueue* notification_cq) {
- // The following call_start_batch is internally-generated so no need for an
- // explanatory log on failure.
- GPR_ASSERT(grpc_server_request_registered_call(
- server_->server(), registered_method, &call_,
- &context_->deadline_, context_->client_metadata_.arr(),
- payload, call_cq_->cq(), notification_cq->cq(),
- this) == GRPC_CALL_OK);
-}
-
-ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
- ServerInterface* server, GenericServerContext* context,
- internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
- ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
- : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
- delete_on_finalize) {
- grpc_call_details_init(&call_details_);
- GPR_ASSERT(notification_cq);
- GPR_ASSERT(call_cq);
- // The following call_start_batch is internally-generated so no need for an
- // explanatory log on failure.
- GPR_ASSERT(grpc_server_request_call(server->server(), &call_, &call_details_,
- context->client_metadata_.arr(),
- call_cq->cq(), notification_cq->cq(),
- this) == GRPC_CALL_OK);
-}
-
-bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
- bool* status) {
- // If we are done intercepting, there is nothing more for us to do
- if (done_intercepting_) {
- return BaseAsyncRequest::FinalizeResult(tag, status);
- }
- // TODO(yangg) remove the copy here.
- if (*status) {
- static_cast<GenericServerContext*>(context_)->method_ =
- StringFromCopiedSlice(call_details_.method);
- static_cast<GenericServerContext*>(context_)->host_ =
- StringFromCopiedSlice(call_details_.host);
- context_->deadline_ = call_details_.deadline;
- }
- grpc_slice_unref(call_details_.method);
- grpc_slice_unref(call_details_.host);
- call_wrapper_ = internal::Call(
- call_, server_, call_cq_, server_->max_receive_message_size(),
- context_->set_server_rpc_info(
- static_cast<GenericServerContext*>(context_)->method_.c_str(),
- internal::RpcMethod::BIDI_STREAMING,
- *server_->interceptor_creators()));
- return BaseAsyncRequest::FinalizeResult(tag, status);
-}
-
-namespace {
-class ShutdownCallback : public grpc_experimental_completion_queue_functor {
- public:
- ShutdownCallback() {
- functor_run = &ShutdownCallback::Run;
- // Set inlineable to true since this callback is trivial and thus does not
- // need to be run from the executor (triggering a thread hop). This should
- // only be used by internal callbacks like this and not by user application
- // code.
- inlineable = true;
- }
- // TakeCQ takes ownership of the cq into the shutdown callback
- // so that the shutdown callback will be responsible for destroying it
- void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
-
- // The Run function will get invoked by the completion queue library
- // when the shutdown is actually complete
- static void Run(grpc_experimental_completion_queue_functor* cb, int) {
- auto* callback = static_cast<ShutdownCallback*>(cb);
- delete callback->cq_;
- delete callback;
- }
-
- private:
- CompletionQueue* cq_ = nullptr;
-};
-} // namespace
-
+ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
+ ServerInterface* server, ServerContext* context,
+ internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
+ ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
+ : server_(server),
+ context_(context),
+ stream_(stream),
+ call_cq_(call_cq),
+ notification_cq_(notification_cq),
+ tag_(tag),
+ delete_on_finalize_(delete_on_finalize),
+ call_(nullptr),
+ done_intercepting_(false) {
+ /* Set up interception state partially for the receive ops. call_wrapper_ is
+ * not filled at this point, but it will be filled before the interceptors are
+ * run. */
+ interceptor_methods_.SetCall(&call_wrapper_);
+ interceptor_methods_.SetReverse();
+ call_cq_->RegisterAvalanching(); // This op will trigger more ops
+}
+
+ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
+ call_cq_->CompleteAvalanching();
+}
+
+bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
+ bool* status) {
+ if (done_intercepting_) {
+ *tag = tag_;
+ if (delete_on_finalize_) {
+ delete this;
+ }
+ return true;
+ }
+ context_->set_call(call_);
+ context_->cq_ = call_cq_;
+ if (call_wrapper_.call() == nullptr) {
+ // Fill it since it is empty.
+ call_wrapper_ = internal::Call(
+ call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
+ }
+
+ // just the pointers inside call are copied here
+ stream_->BindCall(&call_wrapper_);
+
+ if (*status && call_ && call_wrapper_.server_rpc_info()) {
+ done_intercepting_ = true;
+ // Set interception point for RECV INITIAL METADATA
+ interceptor_methods_.AddInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
+ interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
+ if (interceptor_methods_.RunInterceptors(
+ [this]() { ContinueFinalizeResultAfterInterception(); })) {
+ // There are no interceptors to run. Continue
+ } else {
+ // There were interceptors to be run, so
+ // ContinueFinalizeResultAfterInterception will be run when interceptors
+ // are done.
+ return false;
+ }
+ }
+ if (*status && call_) {
+ context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
+ }
+ *tag = tag_;
+ if (delete_on_finalize_) {
+ delete this;
+ }
+ return true;
+}
+
+void ServerInterface::BaseAsyncRequest::
+ ContinueFinalizeResultAfterInterception() {
+ context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
+ // Queue a tag which will be returned immediately
+ grpc_core::ExecCtx exec_ctx;
+ grpc_cq_begin_op(notification_cq_->cq(), this);
+ grpc_cq_end_op(
+ notification_cq_->cq(), this, GRPC_ERROR_NONE,
+ [](void* /*arg*/, grpc_cq_completion* completion) { delete completion; },
+ nullptr, new grpc_cq_completion());
+}
+
+ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
+ ServerInterface* server, ServerContext* context,
+ internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
+ ServerCompletionQueue* notification_cq, void* tag, const char* name,
+ internal::RpcMethod::RpcType type)
+ : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
+ true),
+ name_(name),
+ type_(type) {}
+
+void ServerInterface::RegisteredAsyncRequest::IssueRequest(
+ void* registered_method, grpc_byte_buffer** payload,
+ ServerCompletionQueue* notification_cq) {
+ // The following call_start_batch is internally-generated so no need for an
+ // explanatory log on failure.
+ GPR_ASSERT(grpc_server_request_registered_call(
+ server_->server(), registered_method, &call_,
+ &context_->deadline_, context_->client_metadata_.arr(),
+ payload, call_cq_->cq(), notification_cq->cq(),
+ this) == GRPC_CALL_OK);
+}
+
+ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
+ ServerInterface* server, GenericServerContext* context,
+ internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
+ ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
+ : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
+ delete_on_finalize) {
+ grpc_call_details_init(&call_details_);
+ GPR_ASSERT(notification_cq);
+ GPR_ASSERT(call_cq);
+ // The following call_start_batch is internally-generated so no need for an
+ // explanatory log on failure.
+ GPR_ASSERT(grpc_server_request_call(server->server(), &call_, &call_details_,
+ context->client_metadata_.arr(),
+ call_cq->cq(), notification_cq->cq(),
+ this) == GRPC_CALL_OK);
+}
+
+bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
+ bool* status) {
+ // If we are done intercepting, there is nothing more for us to do
+ if (done_intercepting_) {
+ return BaseAsyncRequest::FinalizeResult(tag, status);
+ }
+ // TODO(yangg) remove the copy here.
+ if (*status) {
+ static_cast<GenericServerContext*>(context_)->method_ =
+ StringFromCopiedSlice(call_details_.method);
+ static_cast<GenericServerContext*>(context_)->host_ =
+ StringFromCopiedSlice(call_details_.host);
+ context_->deadline_ = call_details_.deadline;
+ }
+ grpc_slice_unref(call_details_.method);
+ grpc_slice_unref(call_details_.host);
+ call_wrapper_ = internal::Call(
+ call_, server_, call_cq_, server_->max_receive_message_size(),
+ context_->set_server_rpc_info(
+ static_cast<GenericServerContext*>(context_)->method_.c_str(),
+ internal::RpcMethod::BIDI_STREAMING,
+ *server_->interceptor_creators()));
+ return BaseAsyncRequest::FinalizeResult(tag, status);
+}
+
+namespace {
+class ShutdownCallback : public grpc_experimental_completion_queue_functor {
+ public:
+ ShutdownCallback() {
+ functor_run = &ShutdownCallback::Run;
+ // Set inlineable to true since this callback is trivial and thus does not
+ // need to be run from the executor (triggering a thread hop). This should
+ // only be used by internal callbacks like this and not by user application
+ // code.
+ inlineable = true;
+ }
+ // TakeCQ takes ownership of the cq into the shutdown callback
+ // so that the shutdown callback will be responsible for destroying it
+ void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
+
+ // The Run function will get invoked by the completion queue library
+ // when the shutdown is actually complete
+ static void Run(grpc_experimental_completion_queue_functor* cb, int) {
+ auto* callback = static_cast<ShutdownCallback*>(cb);
+ delete callback->cq_;
+ delete callback;
+ }
+
+ private:
+ CompletionQueue* cq_ = nullptr;
+};
+} // namespace
+
/// Use private inheritance rather than composition only to establish order
/// of construction, since the public base class should be constructed after the
/// elements belonging to the private base class are constructed. This is not
/// possible using true composition.
class Server::UnimplementedAsyncRequest final
- : private grpc::UnimplementedAsyncRequestContext,
+ : private grpc::UnimplementedAsyncRequestContext,
public GenericAsyncRequest {
public:
UnimplementedAsyncRequest(ServerInterface* server,
@@ -300,25 +300,25 @@ class Server::UnimplementedAsyncRequest final
bool FinalizeResult(void** tag, bool* status) override;
- grpc::ServerContext* context() { return &server_context_; }
- grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
+ grpc::ServerContext* context() { return &server_context_; }
+ grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
};
/// UnimplementedAsyncResponse should not post user-visible completions to the
/// C++ completion queue, but is generated as a CQ event by the core
class Server::UnimplementedAsyncResponse final
- : public grpc::internal::CallOpSet<
- grpc::internal::CallOpSendInitialMetadata,
- grpc::internal::CallOpServerSendStatus> {
+ : public grpc::internal::CallOpSet<
+ grpc::internal::CallOpSendInitialMetadata,
+ grpc::internal::CallOpServerSendStatus> {
public:
UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
~UnimplementedAsyncResponse() { delete request_; }
bool FinalizeResult(void** tag, bool* status) override {
- if (grpc::internal::CallOpSet<
- grpc::internal::CallOpSendInitialMetadata,
- grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag,
- status)) {
+ if (grpc::internal::CallOpSet<
+ grpc::internal::CallOpSendInitialMetadata,
+ grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag,
+ status)) {
delete this;
} else {
// The tag was swallowed due to interception. We will see it again.
@@ -330,16 +330,16 @@ class Server::UnimplementedAsyncResponse final
UnimplementedAsyncRequest* const request_;
};
-class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
+class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
public:
- SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag)
+ SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag)
: method_(method),
method_tag_(method_tag),
in_flight_(false),
- has_request_payload_(method->method_type() ==
- grpc::internal::RpcMethod::NORMAL_RPC ||
- method->method_type() ==
- grpc::internal::RpcMethod::SERVER_STREAMING),
+ has_request_payload_(method->method_type() ==
+ grpc::internal::RpcMethod::NORMAL_RPC ||
+ method->method_type() ==
+ grpc::internal::RpcMethod::SERVER_STREAMING),
call_details_(nullptr),
cq_(nullptr) {
grpc_metadata_array_init(&request_metadata_);
@@ -395,7 +395,7 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
}
}
- bool FinalizeResult(void** /*tag*/, bool* status) override {
+ bool FinalizeResult(void** /*tag*/, bool* status) override {
if (!*status) {
grpc_completion_queue_destroy(cq_);
cq_ = nullptr;
@@ -450,8 +450,8 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
interceptor_methods_.SetReverse();
// Set interception point for RECV INITIAL METADATA
interceptor_methods_.AddInterceptionHookPoint(
- grpc::experimental::InterceptionHookPoints::
- POST_RECV_INITIAL_METADATA);
+ grpc::experimental::InterceptionHookPoints::
+ POST_RECV_INITIAL_METADATA);
interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_);
if (has_request_payload_) {
@@ -459,11 +459,11 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
auto* handler = resources_ ? method_->handler()
: server_->resource_exhausted_handler_.get();
request_ = handler->Deserialize(call_.call(), request_payload_,
- &request_status_, nullptr);
+ &request_status_, nullptr);
request_payload_ = nullptr;
interceptor_methods_.AddInterceptionHookPoint(
- grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
+ grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
interceptor_methods_.SetRecvMessage(request_, nullptr);
}
@@ -482,40 +482,40 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
global_callbacks_->PreSynchronousRequest(&ctx_);
auto* handler = resources_ ? method_->handler()
: server_->resource_exhausted_handler_.get();
- handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
- &call_, &ctx_, request_, request_status_, nullptr, nullptr));
+ handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
+ &call_, &ctx_, request_, request_status_, nullptr, nullptr));
request_ = nullptr;
global_callbacks_->PostSynchronousRequest(&ctx_);
cq_.Shutdown();
- grpc::internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
+ grpc::internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME));
/* Ensure the cq_ is shutdown */
- grpc::DummyTag ignored_tag;
+ grpc::DummyTag ignored_tag;
GPR_ASSERT(cq_.Pluck(&ignored_tag) == false);
}
delete this;
}
private:
- grpc::CompletionQueue cq_;
- grpc::ServerContext ctx_;
+ grpc::CompletionQueue cq_;
+ grpc::ServerContext ctx_;
const bool has_request_payload_;
grpc_byte_buffer* request_payload_;
void* request_;
- grpc::Status request_status_;
- grpc::internal::RpcServiceMethod* const method_;
- grpc::internal::Call call_;
+ grpc::Status request_status_;
+ grpc::internal::RpcServiceMethod* const method_;
+ grpc::internal::Call call_;
Server* server_;
std::shared_ptr<GlobalCallbacks> global_callbacks_;
bool resources_;
- grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
+ grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
};
private:
- grpc::internal::RpcServiceMethod* const method_;
+ grpc::internal::RpcServiceMethod* const method_;
void* const method_tag_;
bool in_flight_;
const bool has_request_payload_;
@@ -527,14 +527,14 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
grpc_completion_queue* cq_;
};
-template <class ServerContextType>
+template <class ServerContextType>
class Server::CallbackRequest final
: public grpc::internal::CompletionQueueTag {
- public:
+ public:
static_assert(
std::is_base_of<grpc::CallbackServerContext, ServerContextType>::value,
"ServerContextType must be derived from CallbackServerContext");
-
+
// For codegen services, the value of method represents the defined
// characteristics of the method being requested. For generic services, method
// is nullptr since these services don't have pre-defined methods.
@@ -578,26 +578,26 @@ class Server::CallbackRequest final
server_->UnrefWithPossibleNotify();
}
- // Needs specialization to account for different processing of metadata
- // in generic API
- bool FinalizeResult(void** tag, bool* status) override;
+ // Needs specialization to account for different processing of metadata
+ // in generic API
+ bool FinalizeResult(void** tag, bool* status) override;
private:
- // method_name needs to be specialized between named method and generic
- const char* method_name() const;
-
+ // method_name needs to be specialized between named method and generic
+ const char* method_name() const;
+
class CallbackCallTag : public grpc_experimental_completion_queue_functor {
public:
- CallbackCallTag(Server::CallbackRequest<ServerContextType>* req)
- : req_(req) {
+ CallbackCallTag(Server::CallbackRequest<ServerContextType>* req)
+ : req_(req) {
functor_run = &CallbackCallTag::StaticRun;
- // Set inlineable to true since this callback is internally-controlled
- // without taking any locks, and thus does not need to be run from the
- // executor (which triggers a thread hop). This should only be used by
- // internal callbacks like this and not by user application code. The work
- // here is actually non-trivial, but there is no chance of having user
- // locks conflict with each other so it's ok to run inlined.
- inlineable = true;
+ // Set inlineable to true since this callback is internally-controlled
+ // without taking any locks, and thus does not need to be run from the
+ // executor (which triggers a thread hop). This should only be used by
+ // internal callbacks like this and not by user application code. The work
+ // here is actually non-trivial, but there is no chance of having user
+ // locks conflict with each other so it's ok to run inlined.
+ inlineable = true;
}
// force_run can not be performed on a tag if operations using this tag
@@ -606,8 +606,8 @@ class Server::CallbackRequest final
void force_run(bool ok) { Run(ok); }
private:
- Server::CallbackRequest<ServerContextType>* req_;
- grpc::internal::Call* call_;
+ Server::CallbackRequest<ServerContextType>* req_;
+ grpc::internal::Call* call_;
static void StaticRun(grpc_experimental_completion_queue_functor* cb,
int ok) {
@@ -634,35 +634,35 @@ class Server::CallbackRequest final
req_->request_metadata_.count = 0;
// Create a C++ Call to control the underlying core call
- call_ =
- new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call)))
- grpc::internal::Call(
- req_->call_, req_->server_, req_->cq_,
- req_->server_->max_receive_message_size(),
- req_->ctx_.set_server_rpc_info(
- req_->method_name(),
- (req_->method_ != nullptr)
- ? req_->method_->method_type()
- : grpc::internal::RpcMethod::BIDI_STREAMING,
- req_->server_->interceptor_creators_));
+ call_ =
+ new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call)))
+ grpc::internal::Call(
+ req_->call_, req_->server_, req_->cq_,
+ req_->server_->max_receive_message_size(),
+ req_->ctx_.set_server_rpc_info(
+ req_->method_name(),
+ (req_->method_ != nullptr)
+ ? req_->method_->method_type()
+ : grpc::internal::RpcMethod::BIDI_STREAMING,
+ req_->server_->interceptor_creators_));
req_->interceptor_methods_.SetCall(call_);
req_->interceptor_methods_.SetReverse();
// Set interception point for RECV INITIAL METADATA
req_->interceptor_methods_.AddInterceptionHookPoint(
- grpc::experimental::InterceptionHookPoints::
- POST_RECV_INITIAL_METADATA);
+ grpc::experimental::InterceptionHookPoints::
+ POST_RECV_INITIAL_METADATA);
req_->interceptor_methods_.SetRecvInitialMetadata(
&req_->ctx_.client_metadata_);
if (req_->has_request_payload_) {
// Set interception point for RECV MESSAGE
req_->request_ = req_->method_->handler()->Deserialize(
- req_->call_, req_->request_payload_, &req_->request_status_,
- &req_->handler_data_);
+ req_->call_, req_->request_payload_, &req_->request_status_,
+ &req_->handler_data_);
req_->request_payload_ = nullptr;
req_->interceptor_methods_.AddInterceptionHookPoint(
- grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
+ grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr);
}
@@ -675,11 +675,11 @@ class Server::CallbackRequest final
}
}
void ContinueRunAfterInterception() {
- auto* handler = (req_->method_ != nullptr)
- ? req_->method_->handler()
- : req_->server_->generic_handler_.get();
- handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
- call_, &req_->ctx_, req_->request_, req_->request_status_,
+ auto* handler = (req_->method_ != nullptr)
+ ? req_->method_->handler()
+ : req_->server_->generic_handler_.get();
+ handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
+ call_, &req_->ctx_, req_->request_, req_->request_status_,
req_->handler_data_, [this] { delete req_; }));
}
};
@@ -694,61 +694,61 @@ class Server::CallbackRequest final
}
Server* const server_;
- grpc::internal::RpcServiceMethod* const method_;
+ grpc::internal::RpcServiceMethod* const method_;
const bool has_request_payload_;
grpc_byte_buffer* request_payload_ = nullptr;
void* request_ = nullptr;
void* handler_data_ = nullptr;
- grpc::Status request_status_;
+ grpc::Status request_status_;
grpc_call_details* const call_details_ = nullptr;
grpc_call* call_;
gpr_timespec deadline_;
grpc_metadata_array request_metadata_;
grpc::CompletionQueue* const cq_;
CallbackCallTag tag_;
- ServerContextType ctx_;
- grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
+ ServerContextType ctx_;
+ grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
};
-template <>
+template <>
bool Server::CallbackRequest<grpc::CallbackServerContext>::FinalizeResult(
void** /*tag*/, bool* /*status*/) {
- return false;
-}
-
-template <>
+ return false;
+}
+
+template <>
bool Server::CallbackRequest<
grpc::GenericCallbackServerContext>::FinalizeResult(void** /*tag*/,
bool* status) {
- if (*status) {
+ if (*status) {
deadline_ = call_details_->deadline;
- // TODO(yangg) remove the copy here
- ctx_.method_ = grpc::StringFromCopiedSlice(call_details_->method);
- ctx_.host_ = grpc::StringFromCopiedSlice(call_details_->host);
- }
- grpc_slice_unref(call_details_->method);
- grpc_slice_unref(call_details_->host);
- return false;
-}
-
-template <>
+ // TODO(yangg) remove the copy here
+ ctx_.method_ = grpc::StringFromCopiedSlice(call_details_->method);
+ ctx_.host_ = grpc::StringFromCopiedSlice(call_details_->host);
+ }
+ grpc_slice_unref(call_details_->method);
+ grpc_slice_unref(call_details_->host);
+ return false;
+}
+
+template <>
const char* Server::CallbackRequest<grpc::CallbackServerContext>::method_name()
const {
- return method_->name();
-}
-
-template <>
-const char* Server::CallbackRequest<
+ return method_->name();
+}
+
+template <>
+const char* Server::CallbackRequest<
grpc::GenericCallbackServerContext>::method_name() const {
- return ctx_.method().c_str();
-}
-
+ return ctx_.method().c_str();
+}
+
// Implementation of ThreadManager. Each instance of SyncRequestThreadManager
// manages a pool of threads that poll for incoming Sync RPCs and call the
// appropriate RPC handlers
-class Server::SyncRequestThreadManager : public grpc::ThreadManager {
+class Server::SyncRequestThreadManager : public grpc::ThreadManager {
public:
- SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq,
+ SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq,
std::shared_ptr<GlobalCallbacks> global_callbacks,
grpc_resource_quota* rq, int min_pollers,
int max_pollers, int cq_timeout_msec)
@@ -767,11 +767,11 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
switch (server_cq_->AsyncNext(tag, ok, deadline)) {
- case grpc::CompletionQueue::TIMEOUT:
+ case grpc::CompletionQueue::TIMEOUT:
return TIMEOUT;
- case grpc::CompletionQueue::SHUTDOWN:
+ case grpc::CompletionQueue::SHUTDOWN:
return SHUTDOWN;
- case grpc::CompletionQueue::GOT_EVENT:
+ case grpc::CompletionQueue::GOT_EVENT:
return WORK_FOUND;
}
@@ -806,15 +806,15 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
// object
}
- void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) {
+ void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) {
sync_requests_.emplace_back(new SyncRequest(method, tag));
}
void AddUnknownSyncMethod() {
if (!sync_requests_.empty()) {
- unknown_method_.reset(new grpc::internal::RpcServiceMethod(
- "unknown", grpc::internal::RpcMethod::BIDI_STREAMING,
- new grpc::internal::UnknownMethodHandler));
+ unknown_method_.reset(new grpc::internal::RpcServiceMethod(
+ "unknown", grpc::internal::RpcMethod::BIDI_STREAMING,
+ new grpc::internal::UnknownMethodHandler));
sync_requests_.emplace_back(
new SyncRequest(unknown_method_.get(), nullptr));
}
@@ -847,9 +847,9 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
void Start() {
if (!sync_requests_.empty()) {
- for (const auto& value : sync_requests_) {
- value->SetupRequest();
- value->Request(server_->c_server(), server_cq_->cq());
+ for (const auto& value : sync_requests_) {
+ value->SetupRequest();
+ value->Request(server_->c_server(), server_cq_->cq());
}
Initialize(); // ThreadManager's Initialize()
@@ -858,27 +858,27 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
private:
Server* server_;
- grpc::CompletionQueue* server_cq_;
+ grpc::CompletionQueue* server_cq_;
int cq_timeout_msec_;
std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
- std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_;
+ std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_;
std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
};
-static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
+static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
Server::Server(
grpc::ChannelArguments* args,
- std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
+ std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
sync_server_cqs,
int min_pollers, int max_pollers, int sync_cq_timeout_msec,
- std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
- acceptors,
+ std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
+ acceptors,
grpc_resource_quota* server_rq,
std::vector<
- std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
+ std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
interceptor_creators)
- : acceptors_(std::move(acceptors)),
- interceptor_creators_(std::move(interceptor_creators)),
+ : acceptors_(std::move(acceptors)),
+ interceptor_creators_(std::move(interceptor_creators)),
max_receive_message_size_(INT_MIN),
sync_server_cqs_(std::move(sync_server_cqs)),
started_(false),
@@ -888,8 +888,8 @@ Server::Server(
server_initializer_(new ServerInitializer(this)),
health_check_service_disabled_(false) {
g_gli_initializer.summon();
- gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
- global_callbacks_ = grpc::g_callbacks;
+ gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
+ global_callbacks_ = grpc::g_callbacks;
global_callbacks_->UpdateArguments(args);
if (sync_server_cqs_ != nullptr) {
@@ -912,22 +912,22 @@ Server::Server(
}
}
- for (auto& acceptor : acceptors_) {
- acceptor->SetToChannelArgs(args);
- }
-
+ for (auto& acceptor : acceptors_) {
+ acceptor->SetToChannelArgs(args);
+ }
+
grpc_channel_args channel_args;
args->SetChannelArgs(&channel_args);
for (size_t i = 0; i < channel_args.num_args; i++) {
- if (0 == strcmp(channel_args.args[i].key,
- grpc::kHealthCheckServiceInterfaceArg)) {
+ if (0 == strcmp(channel_args.args[i].key,
+ grpc::kHealthCheckServiceInterfaceArg)) {
if (channel_args.args[i].value.pointer.p == nullptr) {
health_check_service_disabled_ = true;
} else {
- health_check_service_.reset(
- static_cast<grpc::HealthCheckServiceInterface*>(
- channel_args.args[i].value.pointer.p));
+ health_check_service_.reset(
+ static_cast<grpc::HealthCheckServiceInterface*>(
+ channel_args.args[i].value.pointer.p));
}
}
if (0 ==
@@ -940,19 +940,19 @@ Server::Server(
Server::~Server() {
{
- grpc::internal::ReleasableMutexLock lock(&mu_);
+ grpc::internal::ReleasableMutexLock lock(&mu_);
if (started_ && !shutdown_) {
- lock.Unlock();
+ lock.Unlock();
Shutdown();
} else if (!started_) {
// Shutdown the completion queues
- for (const auto& value : sync_req_mgrs_) {
- value->Shutdown();
- }
- if (callback_cq_ != nullptr) {
- callback_cq_->Shutdown();
- callback_cq_ = nullptr;
+ for (const auto& value : sync_req_mgrs_) {
+ value->Shutdown();
}
+ if (callback_cq_ != nullptr) {
+ callback_cq_->Shutdown();
+ callback_cq_ = nullptr;
+ }
}
}
// Destroy health check service before we destroy the C server so that
@@ -963,43 +963,43 @@ Server::~Server() {
}
void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
- GPR_ASSERT(!grpc::g_callbacks);
+ GPR_ASSERT(!grpc::g_callbacks);
GPR_ASSERT(callbacks);
- grpc::g_callbacks.reset(callbacks);
+ grpc::g_callbacks.reset(callbacks);
}
grpc_server* Server::c_server() { return server_; }
-std::shared_ptr<grpc::Channel> Server::InProcessChannel(
- const grpc::ChannelArguments& args) {
+std::shared_ptr<grpc::Channel> Server::InProcessChannel(
+ const grpc::ChannelArguments& args) {
grpc_channel_args channel_args = args.c_channel_args();
- return grpc::CreateChannelInternal(
+ return grpc::CreateChannelInternal(
"inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr),
- std::vector<std::unique_ptr<
- grpc::experimental::ClientInterceptorFactoryInterface>>());
+ std::vector<std::unique_ptr<
+ grpc::experimental::ClientInterceptorFactoryInterface>>());
}
-std::shared_ptr<grpc::Channel>
+std::shared_ptr<grpc::Channel>
Server::experimental_type::InProcessChannelWithInterceptors(
- const grpc::ChannelArguments& args,
+ const grpc::ChannelArguments& args,
std::vector<
- std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
+ std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) {
grpc_channel_args channel_args = args.c_channel_args();
- return grpc::CreateChannelInternal(
+ return grpc::CreateChannelInternal(
"inproc",
grpc_inproc_channel_create(server_->server_, &channel_args, nullptr),
std::move(interceptor_creators));
}
static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
- grpc::internal::RpcServiceMethod* method) {
+ grpc::internal::RpcServiceMethod* method) {
switch (method->method_type()) {
- case grpc::internal::RpcMethod::NORMAL_RPC:
- case grpc::internal::RpcMethod::SERVER_STREAMING:
+ case grpc::internal::RpcMethod::NORMAL_RPC:
+ case grpc::internal::RpcMethod::SERVER_STREAMING:
return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
- case grpc::internal::RpcMethod::CLIENT_STREAMING:
- case grpc::internal::RpcMethod::BIDI_STREAMING:
+ case grpc::internal::RpcMethod::CLIENT_STREAMING:
+ case grpc::internal::RpcMethod::BIDI_STREAMING:
return GRPC_SRM_PAYLOAD_NONE;
}
GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
@@ -1015,14 +1015,14 @@ bool Server::RegisterService(const TString* host, grpc::Service* service) {
const char* method_name = nullptr;
- for (const auto& method : service->methods_) {
- if (method.get() == nullptr) { // Handled by generic service if any.
+ for (const auto& method : service->methods_) {
+ if (method.get() == nullptr) { // Handled by generic service if any.
continue;
}
void* method_registration_tag = grpc_server_register_method(
server_, method->name(), host ? host->c_str() : nullptr,
- PayloadHandlingForMethod(method.get()), 0);
+ PayloadHandlingForMethod(method.get()), 0);
if (method_registration_tag == nullptr) {
gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
method->name());
@@ -1032,9 +1032,9 @@ bool Server::RegisterService(const TString* host, grpc::Service* service) {
if (method->handler() == nullptr) { // Async method without handler
method->set_server_tag(method_registration_tag);
} else if (method->api_type() ==
- grpc::internal::RpcServiceMethod::ApiType::SYNC) {
- for (const auto& value : sync_req_mgrs_) {
- value->AddSyncMethod(method.get(), method_registration_tag);
+ grpc::internal::RpcServiceMethod::ApiType::SYNC) {
+ for (const auto& value : sync_req_mgrs_) {
+ value->AddSyncMethod(method.get(), method_registration_tag);
}
} else {
has_callback_methods_ = true;
@@ -1064,32 +1064,32 @@ bool Server::RegisterService(const TString* host, grpc::Service* service) {
return true;
}
-void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) {
+void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) {
GPR_ASSERT(service->server_ == nullptr &&
"Can only register an async generic service against one server.");
service->server_ = this;
- has_async_generic_service_ = true;
+ has_async_generic_service_ = true;
}
-void Server::RegisterCallbackGenericService(
+void Server::RegisterCallbackGenericService(
grpc::CallbackGenericService* service) {
- GPR_ASSERT(
- service->server_ == nullptr &&
- "Can only register a callback generic service against one server.");
- service->server_ = this;
- has_callback_generic_service_ = true;
- generic_handler_.reset(service->Handler());
-
+ GPR_ASSERT(
+ service->server_ == nullptr &&
+ "Can only register a callback generic service against one server.");
+ service->server_ = this;
+ has_callback_generic_service_ = true;
+ generic_handler_.reset(service->Handler());
+
grpc::CompletionQueue* cq = CallbackCQ();
server_->core_server->SetBatchMethodAllocator(cq->cq(), [this, cq] {
grpc_core::Server::BatchCallAllocation result;
new CallbackRequest<grpc::GenericCallbackServerContext>(this, cq, &result);
return result;
});
-}
-
+}
+
int Server::AddListeningPort(const TString& addr,
- grpc::ServerCredentials* creds) {
+ grpc::ServerCredentials* creds) {
GPR_ASSERT(!started_);
int port = creds->AddPortToServer(addr, server_);
global_callbacks_->AddPort(this, addr, creds, port);
@@ -1121,46 +1121,46 @@ void Server::UnrefAndWaitLocked() {
shutdown_done_cv_.WaitUntil(&mu_, [this] { return shutdown_done_; });
}
-void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
+void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
GPR_ASSERT(!started_);
global_callbacks_->PreServerStart(this);
started_ = true;
// Only create default health check service when user did not provide an
// explicit one.
- grpc::ServerCompletionQueue* health_check_cq = nullptr;
- grpc::DefaultHealthCheckService::HealthCheckServiceImpl*
+ grpc::ServerCompletionQueue* health_check_cq = nullptr;
+ grpc::DefaultHealthCheckService::HealthCheckServiceImpl*
default_health_check_service_impl = nullptr;
if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
- grpc::DefaultHealthCheckServiceEnabled()) {
- auto* default_hc_service = new grpc::DefaultHealthCheckService;
+ grpc::DefaultHealthCheckServiceEnabled()) {
+ auto* default_hc_service = new grpc::DefaultHealthCheckService;
health_check_service_.reset(default_hc_service);
// We create a non-polling CQ to avoid impacting application
// performance. This ensures that we don't introduce thread hops
// for application requests that wind up on this CQ, which is polled
// in its own thread.
- health_check_cq = new grpc::ServerCompletionQueue(
- GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
+ health_check_cq = new grpc::ServerCompletionQueue(
+ GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
grpc_server_register_completion_queue(server_, health_check_cq->cq(),
nullptr);
default_health_check_service_impl =
default_hc_service->GetHealthCheckService(
- std::unique_ptr<grpc::ServerCompletionQueue>(health_check_cq));
+ std::unique_ptr<grpc::ServerCompletionQueue>(health_check_cq));
RegisterService(nullptr, default_health_check_service_impl);
}
- for (auto& acceptor : acceptors_) {
- acceptor->GetCredentials()->AddPortToServer(acceptor->name(), server_);
- }
-
- // If this server uses callback methods, then create a callback generic
- // service to handle any unimplemented methods using the default reactor
- // creator
+ for (auto& acceptor : acceptors_) {
+ acceptor->GetCredentials()->AddPortToServer(acceptor->name(), server_);
+ }
+
+ // If this server uses callback methods, then create a callback generic
+ // service to handle any unimplemented methods using the default reactor
+ // creator
if (has_callback_methods_ && !has_callback_generic_service_) {
unimplemented_service_.reset(new grpc::CallbackGenericService);
- RegisterCallbackGenericService(unimplemented_service_.get());
- }
-
+ RegisterCallbackGenericService(unimplemented_service_.get());
+ }
+
#ifndef NDEBUG
for (size_t i = 0; i < num_cqs; i++) {
cq_list_.push_back(cqs[i]);
@@ -1169,9 +1169,9 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
grpc_server_start(server_);
- if (!has_async_generic_service_ && !has_callback_generic_service_) {
- for (const auto& value : sync_req_mgrs_) {
- value->AddUnknownSyncMethod();
+ if (!has_async_generic_service_ && !has_callback_generic_service_) {
+ for (const auto& value : sync_req_mgrs_) {
+ value->AddUnknownSyncMethod();
}
for (size_t i = 0; i < num_cqs; i++) {
@@ -1188,50 +1188,50 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
// server CQs), make sure that we have a ResourceExhausted handler
// to deal with the case of thread exhaustion
if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) {
- resource_exhausted_handler_.reset(
- new grpc::internal::ResourceExhaustedHandler);
+ resource_exhausted_handler_.reset(
+ new grpc::internal::ResourceExhaustedHandler);
}
- for (const auto& value : sync_req_mgrs_) {
- value->Start();
+ for (const auto& value : sync_req_mgrs_) {
+ value->Start();
}
if (default_health_check_service_impl != nullptr) {
default_health_check_service_impl->StartServingThread();
}
-
- for (auto& acceptor : acceptors_) {
- acceptor->Start();
- }
+
+ for (auto& acceptor : acceptors_) {
+ acceptor->Start();
+ }
}
void Server::ShutdownInternal(gpr_timespec deadline) {
- grpc::internal::MutexLock lock(&mu_);
+ grpc::internal::MutexLock lock(&mu_);
if (shutdown_) {
return;
}
shutdown_ = true;
- for (auto& acceptor : acceptors_) {
- acceptor->Shutdown();
- }
-
+ for (auto& acceptor : acceptors_) {
+ acceptor->Shutdown();
+ }
+
/// The completion queue to use for server shutdown completion notification
- grpc::CompletionQueue shutdown_cq;
- grpc::ShutdownTag shutdown_tag; // Dummy shutdown tag
+ grpc::CompletionQueue shutdown_cq;
+ grpc::ShutdownTag shutdown_tag; // Dummy shutdown tag
grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
shutdown_cq.Shutdown();
void* tag;
bool ok;
- grpc::CompletionQueue::NextStatus status =
+ grpc::CompletionQueue::NextStatus status =
shutdown_cq.AsyncNext(&tag, &ok, deadline);
// If this timed out, it means we are done with the grace period for a clean
// shutdown. We should force a shutdown now by cancelling all inflight calls
- if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) {
+ if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) {
grpc_server_cancel_all_calls(server_);
}
// Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
@@ -1239,25 +1239,25 @@ void Server::ShutdownInternal(gpr_timespec deadline) {
// Shutdown all ThreadManagers. This will try to gracefully stop all the
// threads in the ThreadManagers (once they process any inflight requests)
- for (const auto& value : sync_req_mgrs_) {
- value->Shutdown(); // ThreadManager's Shutdown()
+ for (const auto& value : sync_req_mgrs_) {
+ value->Shutdown(); // ThreadManager's Shutdown()
}
// Wait for threads in all ThreadManagers to terminate
- for (const auto& value : sync_req_mgrs_) {
- value->Wait();
+ for (const auto& value : sync_req_mgrs_) {
+ value->Wait();
}
// Drop the shutdown ref and wait for all other refs to drop as well.
UnrefAndWaitLocked();
- // Shutdown the callback CQ. The CQ is owned by its own shutdown tag, so it
- // will delete itself at true shutdown.
- if (callback_cq_ != nullptr) {
- callback_cq_->Shutdown();
- callback_cq_ = nullptr;
- }
-
+ // Shutdown the callback CQ. The CQ is owned by its own shutdown tag, so it
+ // will delete itself at true shutdown.
+ if (callback_cq_ != nullptr) {
+ callback_cq_->Shutdown();
+ callback_cq_ = nullptr;
+ }
+
// Drain the shutdown queue (if the previous call to AsyncNext() timed out
// and we didn't remove the tag from the queue yet)
while (shutdown_cq.Next(&tag, &ok)) {
@@ -1265,7 +1265,7 @@ void Server::ShutdownInternal(gpr_timespec deadline) {
}
shutdown_notified_ = true;
- shutdown_cv_.Broadcast();
+ shutdown_cv_.Broadcast();
#ifndef NDEBUG
// Unregister this server with the CQs passed into it by the user so that
@@ -1278,14 +1278,14 @@ void Server::ShutdownInternal(gpr_timespec deadline) {
}
void Server::Wait() {
- grpc::internal::MutexLock lock(&mu_);
+ grpc::internal::MutexLock lock(&mu_);
while (started_ && !shutdown_notified_) {
- shutdown_cv_.Wait(&mu_);
+ shutdown_cv_.Wait(&mu_);
}
}
-void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
- grpc::internal::Call* call) {
+void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
+ grpc::internal::Call* call) {
ops->FillOps(call);
}
@@ -1310,19 +1310,19 @@ bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
UnimplementedAsyncRequest* request)
: request_(request) {
- grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, "");
- grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this);
+ grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, "");
+ grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this);
request_->stream()->call_.PerformOps(this);
}
-grpc::ServerInitializer* Server::initializer() {
- return server_initializer_.get();
-}
+grpc::ServerInitializer* Server::initializer() {
+ return server_initializer_.get();
+}
-grpc::CompletionQueue* Server::CallbackCQ() {
+grpc::CompletionQueue* Server::CallbackCQ() {
// TODO(vjpai): Consider using a single global CQ for the default CQ
// if there is no explicit per-server CQ registered
- grpc::internal::MutexLock l(&mu_);
+ grpc::internal::MutexLock l(&mu_);
if (callback_cq_ != nullptr) {
return callback_cq_;
}
@@ -1335,6 +1335,6 @@ grpc::CompletionQueue* Server::CallbackCQ() {
shutdown_callback->TakeCQ(callback_cq_);
return callback_cq_;
-}
+}
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/server_context.cc b/contrib/libs/grpc/src/cpp/server/server_context.cc
index 458ac20d87..4a4181d39f 100644
--- a/contrib/libs/grpc/src/cpp/server/server_context.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_context.cc
@@ -28,18 +28,18 @@
#include <grpc/support/log.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/codegen/completion_queue.h>
-#include <grpcpp/support/server_callback.h>
+#include <grpcpp/support/server_callback.h>
#include <grpcpp/support/time.h>
-#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/surface/call.h"
namespace grpc {
// CompletionOp
-class ServerContextBase::CompletionOp final
+class ServerContextBase::CompletionOp final
: public internal::CallOpSetInterface {
public:
// initial refs: one in the server context, one in the cq
@@ -47,7 +47,7 @@ class ServerContextBase::CompletionOp final
CompletionOp(internal::Call* call,
::grpc::internal::ServerCallbackCall* callback_controller)
: call_(*call),
- callback_controller_(callback_controller),
+ callback_controller_(callback_controller),
has_tag_(false),
tag_(nullptr),
core_cq_tag_(this),
@@ -73,10 +73,10 @@ class ServerContextBase::CompletionOp final
// This should always be arena allocated in the call, so override delete.
// But this class is not trivially destructible, so must actually call delete
// before allowing the arena to be freed
- static void operator delete(void* /*ptr*/, std::size_t size) {
- // Use size to avoid unused-parameter warning since assert seems to be
- // compiled out and treated as unused in some gcc optimized versions.
- (void)size;
+ static void operator delete(void* /*ptr*/, std::size_t size) {
+ // Use size to avoid unused-parameter warning since assert seems to be
+ // compiled out and treated as unused in some gcc optimized versions.
+ (void)size;
assert(size == sizeof(CompletionOp));
}
@@ -110,7 +110,7 @@ class ServerContextBase::CompletionOp final
// RPC. This should set hijacking state for each of the ops.
void SetHijackingState() override {
/* Servers don't allow hijacking */
- GPR_ASSERT(false);
+ GPR_ASSERT(false);
}
/* Should be called after interceptors are done running */
@@ -122,17 +122,17 @@ class ServerContextBase::CompletionOp final
done_intercepting_ = true;
if (!has_tag_) {
/* We don't have a tag to return. */
- Unref();
+ Unref();
return;
}
/* Start a dummy op so that we can return the tag */
- GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag_,
- nullptr) == GRPC_CALL_OK);
+ GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag_,
+ nullptr) == GRPC_CALL_OK);
}
private:
bool CheckCancelledNoPluck() {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
return finalized_ ? (cancelled_ != 0) : false;
}
@@ -141,16 +141,16 @@ class ServerContextBase::CompletionOp final
bool has_tag_;
void* tag_;
void* core_cq_tag_;
- grpc_core::RefCount refs_;
- grpc_core::Mutex mu_;
+ grpc_core::RefCount refs_;
+ grpc_core::Mutex mu_;
bool finalized_;
int cancelled_; // This is an int (not bool) because it is passed to core
bool done_intercepting_;
internal::InterceptorBatchMethodsImpl interceptor_methods_;
};
-void ServerContextBase::CompletionOp::Unref() {
- if (refs_.Unref()) {
+void ServerContextBase::CompletionOp::Unref() {
+ if (refs_.Unref()) {
grpc_call* call = call_.call();
delete this;
grpc_call_unref(call);
@@ -166,14 +166,14 @@ void ServerContextBase::CompletionOp::FillOps(internal::Call* call) {
interceptor_methods_.SetCall(&call_);
interceptor_methods_.SetReverse();
interceptor_methods_.SetCallOpSetInterface(this);
- // The following call_start_batch is internally-generated so no need for an
- // explanatory log on failure.
- GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_,
- nullptr) == GRPC_CALL_OK);
+ // The following call_start_batch is internally-generated so no need for an
+ // explanatory log on failure.
+ GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_,
+ nullptr) == GRPC_CALL_OK);
/* No interceptors to run here */
}
-bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) {
+bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) {
// Decide whether to call the cancel callback within the lock
bool call_cancel;
@@ -201,8 +201,8 @@ bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) {
// Release the lock since we may call a callback and interceptors.
}
- if (call_cancel && callback_controller_ != nullptr) {
- callback_controller_->MaybeCallOnCancel();
+ if (call_cancel && callback_controller_ != nullptr) {
+ callback_controller_->MaybeCallOnCancel();
}
/* Add interception point and run through interceptors */
interceptor_methods_.AddInterceptionHookPoint(
@@ -213,26 +213,26 @@ bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) {
if (has_tag) {
*tag = tag_;
}
- Unref();
+ Unref();
return has_tag;
}
// There are interceptors to be run. Return false for now.
return false;
}
-// ServerContextBase body
+// ServerContextBase body
ServerContextBase::ServerContextBase()
: deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)) {}
-ServerContextBase::ServerContextBase(gpr_timespec deadline,
+ServerContextBase::ServerContextBase(gpr_timespec deadline,
grpc_metadata_array* arr)
: deadline_(deadline) {
std::swap(*client_metadata_.arr(), *arr);
}
-void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline,
- grpc_metadata_array* arr) {
+void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline,
+ grpc_metadata_array* arr) {
deadline_ = deadline;
std::swap(*client_metadata_.arr(), *arr);
}
@@ -244,9 +244,9 @@ ServerContextBase::~ServerContextBase() {
if (rpc_info_) {
rpc_info_->Unref();
}
- if (default_reactor_used_.load(std::memory_order_relaxed)) {
+ if (default_reactor_used_.load(std::memory_order_relaxed)) {
reinterpret_cast<Reactor*>(&default_reactor_)->~Reactor();
- }
+ }
}
ServerContextBase::CallWrapper::~CallWrapper() {
@@ -257,7 +257,7 @@ ServerContextBase::CallWrapper::~CallWrapper() {
}
}
-void ServerContextBase::BeginCompletionOp(
+void ServerContextBase::BeginCompletionOp(
internal::Call* call, std::function<void(bool)> callback,
::grpc::internal::ServerCallbackCall* callback_controller) {
GPR_ASSERT(!completion_op_);
@@ -267,10 +267,10 @@ void ServerContextBase::BeginCompletionOp(
grpc_call_ref(call->call());
completion_op_ =
new (grpc_call_arena_alloc(call->call(), sizeof(CompletionOp)))
- CompletionOp(call, callback_controller);
- if (callback_controller != nullptr) {
- completion_tag_.Set(call->call(), std::move(callback), completion_op_,
- true);
+ CompletionOp(call, callback_controller);
+ if (callback_controller != nullptr) {
+ completion_tag_.Set(call->call(), std::move(callback), completion_op_,
+ true);
completion_op_->set_core_cq_tag(&completion_tag_);
completion_op_->set_tag(completion_op_);
} else if (has_notify_when_done_tag_) {
@@ -293,7 +293,7 @@ void ServerContextBase::AddTrailingMetadata(const TString& key,
trailing_metadata_.insert(std::make_pair(key, value));
}
-void ServerContextBase::TryCancel() const {
+void ServerContextBase::TryCancel() const {
internal::CancelInterceptorBatchMethods cancel_methods;
if (rpc_info_) {
for (size_t i = 0; i < rpc_info_->interceptors_.size(); i++) {
@@ -308,7 +308,7 @@ void ServerContextBase::TryCancel() const {
}
}
-bool ServerContextBase::IsCancelled() const {
+bool ServerContextBase::IsCancelled() const {
if (completion_tag_) {
// When using callback API, this result is always valid.
return completion_op_->CheckCancelledAsync();
@@ -322,7 +322,7 @@ bool ServerContextBase::IsCancelled() const {
}
}
-void ServerContextBase::set_compression_algorithm(
+void ServerContextBase::set_compression_algorithm(
grpc_compression_algorithm algorithm) {
compression_algorithm_ = algorithm;
const char* algorithm_name = nullptr;
@@ -345,12 +345,12 @@ TString ServerContextBase::peer() const {
return peer;
}
-const struct census_context* ServerContextBase::census_context() const {
+const struct census_context* ServerContextBase::census_context() const {
return call_.call == nullptr ? nullptr
: grpc_census_call_get_context(call_.call);
}
-void ServerContextBase::SetLoadReportingCosts(
+void ServerContextBase::SetLoadReportingCosts(
const std::vector<TString>& cost_data) {
if (call_.call == nullptr) return;
for (const auto& cost_datum : cost_data) {
diff --git a/contrib/libs/grpc/src/cpp/server/server_posix.cc b/contrib/libs/grpc/src/cpp/server/server_posix.cc
index c3d40d4fa2..85709b0c70 100644
--- a/contrib/libs/grpc/src/cpp/server/server_posix.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_posix.cc
@@ -24,7 +24,7 @@ namespace grpc {
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
-void AddInsecureChannelFromFd(grpc::Server* server, int fd) {
+void AddInsecureChannelFromFd(grpc::Server* server, int fd) {
grpc_server_add_insecure_channel_from_fd(server->c_server(), nullptr, fd);
}
diff --git a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc
index c8560aa81d..cac4b57eb2 100644
--- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc
+++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc
@@ -33,10 +33,10 @@ ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr)
thd_ = grpc_core::Thread(
"grpcpp_sync_server",
[](void* th) { static_cast<ThreadManager::WorkerThread*>(th)->Run(); },
- this, &created_);
- if (!created_) {
- gpr_log(GPR_ERROR, "Could not create grpc_sync_server worker-thread");
- }
+ this, &created_);
+ if (!created_) {
+ gpr_log(GPR_ERROR, "Could not create grpc_sync_server worker-thread");
+ }
}
void ThreadManager::WorkerThread::Run() {
@@ -63,7 +63,7 @@ ThreadManager::ThreadManager(const char* name,
ThreadManager::~ThreadManager() {
{
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
GPR_ASSERT(num_threads_ == 0);
}
@@ -73,38 +73,38 @@ ThreadManager::~ThreadManager() {
}
void ThreadManager::Wait() {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
while (num_threads_ != 0) {
- shutdown_cv_.Wait(&mu_);
+ shutdown_cv_.Wait(&mu_);
}
}
void ThreadManager::Shutdown() {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
shutdown_ = true;
}
bool ThreadManager::IsShutdown() {
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
return shutdown_;
}
int ThreadManager::GetMaxActiveThreadsSoFar() {
- grpc_core::MutexLock list_lock(&list_mu_);
+ grpc_core::MutexLock list_lock(&list_mu_);
return max_active_threads_sofar_;
}
void ThreadManager::MarkAsCompleted(WorkerThread* thd) {
{
- grpc_core::MutexLock list_lock(&list_mu_);
+ grpc_core::MutexLock list_lock(&list_mu_);
completed_threads_.push_back(thd);
}
{
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
num_threads_--;
if (num_threads_ == 0) {
- shutdown_cv_.Signal();
+ shutdown_cv_.Signal();
}
}
@@ -117,7 +117,7 @@ void ThreadManager::CleanupCompletedThreads() {
{
// swap out the completed threads list: allows other threads to clean up
// more quickly
- grpc_core::MutexLock lock(&list_mu_);
+ grpc_core::MutexLock lock(&list_mu_);
completed_threads.swap(completed_threads_);
}
for (auto thd : completed_threads) delete thd;
@@ -133,16 +133,16 @@ void ThreadManager::Initialize() {
}
{
- grpc_core::MutexLock lock(&mu_);
+ grpc_core::MutexLock lock(&mu_);
num_pollers_ = min_pollers_;
num_threads_ = min_pollers_;
max_active_threads_sofar_ = min_pollers_;
}
for (int i = 0; i < min_pollers_; i++) {
- WorkerThread* worker = new WorkerThread(this);
- GPR_ASSERT(worker->created()); // Must be able to create the minimum
- worker->Start();
+ WorkerThread* worker = new WorkerThread(this);
+ GPR_ASSERT(worker->created()); // Must be able to create the minimum
+ worker->Start();
}
}
@@ -152,7 +152,7 @@ void ThreadManager::MainWorkLoop() {
bool ok;
WorkStatus work_status = PollForWork(&tag, &ok);
- grpc_core::ReleasableMutexLock lock(&mu_);
+ grpc_core::ReleasableMutexLock lock(&mu_);
// Reduce the number of pollers by 1 and check what happened with the poll
num_pollers_--;
bool done = false;
@@ -179,40 +179,40 @@ void ThreadManager::MainWorkLoop() {
max_active_threads_sofar_ = num_threads_;
}
// Drop lock before spawning thread to avoid contention
- lock.Unlock();
- WorkerThread* worker = new WorkerThread(this);
- if (worker->created()) {
- worker->Start();
- } else {
+ lock.Unlock();
+ WorkerThread* worker = new WorkerThread(this);
+ if (worker->created()) {
+ worker->Start();
+ } else {
// Get lock again to undo changes to poller/thread counters.
grpc_core::MutexLock failure_lock(&mu_);
- num_pollers_--;
- num_threads_--;
- resource_exhausted = true;
- delete worker;
- }
+ num_pollers_--;
+ num_threads_--;
+ resource_exhausted = true;
+ delete worker;
+ }
} else if (num_pollers_ > 0) {
// There is still at least some thread polling, so we can go on
// even though we are below the number of pollers that we would
// like to have (min_pollers_)
- lock.Unlock();
+ lock.Unlock();
} else {
// There are no pollers to spare and we couldn't allocate
// a new thread, so resources are exhausted!
- lock.Unlock();
+ lock.Unlock();
resource_exhausted = true;
}
} else {
// There are a sufficient number of pollers available so we can do
// the work and continue polling with our existing poller threads
- lock.Unlock();
+ lock.Unlock();
}
// Lock is always released at this point - do the application work
// or return resource exhausted if there is new work but we couldn't
// get a thread in which to do it.
DoWork(tag, ok, !resource_exhausted);
// Take the lock again to check post conditions
- lock.Lock();
+ lock.Lock();
// If we're shutdown, we should finish at this point.
if (shutdown_) done = true;
break;
diff --git a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h
index 43f1fd5585..bfdaf3bfda 100644
--- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h
+++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h
@@ -24,7 +24,7 @@
#include <grpcpp/support/config.h>
-#include "src/core/lib/gprpp/sync.h"
+#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/resource_quota.h"
@@ -54,7 +54,7 @@ class ThreadManager {
// DoWork()
//
// If the return value is SHUTDOWN:,
- // - ThreadManager WILL NOT call DoWork() and terminates the thread
+ // - ThreadManager WILL NOT call DoWork() and terminates the thread
//
// If the return value is TIMEOUT:,
// - ThreadManager WILL NOT call DoWork()
@@ -122,9 +122,9 @@ class ThreadManager {
WorkerThread(ThreadManager* thd_mgr);
~WorkerThread();
- bool created() const { return created_; }
- void Start() { thd_.Start(); }
-
+ bool created() const { return created_; }
+ void Start() { thd_.Start(); }
+
private:
// Calls thd_mgr_->MainWorkLoop() and once that completes, calls
// thd_mgr_>MarkAsCompleted(this) to mark the thread as completed
@@ -132,10 +132,10 @@ class ThreadManager {
ThreadManager* const thd_mgr_;
grpc_core::Thread thd_;
- bool created_;
+ bool created_;
};
- // The main function in ThreadManager
+ // The main function in ThreadManager
void MainWorkLoop();
void MarkAsCompleted(WorkerThread* thd);
@@ -143,16 +143,16 @@ class ThreadManager {
// Protects shutdown_, num_pollers_, num_threads_ and
// max_active_threads_sofar_
- grpc_core::Mutex mu_;
+ grpc_core::Mutex mu_;
bool shutdown_;
- grpc_core::CondVar shutdown_cv_;
+ grpc_core::CondVar shutdown_cv_;
// The resource user object to use when requesting quota to create threads
//
// Note: The user of this ThreadManager object must create grpc_resource_quota
// object (that contains the actual max thread quota) and a grpc_resource_user
- // object through which quota is requested whenever new threads need to be
+ // object through which quota is requested whenever new threads need to be
// created
grpc_resource_user* resource_user_;
@@ -172,7 +172,7 @@ class ThreadManager {
// ever set so far
int max_active_threads_sofar_;
- grpc_core::Mutex list_mu_;
+ grpc_core::Mutex list_mu_;
std::list<WorkerThread*> completed_threads_;
};
diff --git a/contrib/libs/grpc/src/cpp/util/error_details.cc b/contrib/libs/grpc/src/cpp/util/error_details.cc
index dfd3351be1..009dd97483 100644
--- a/contrib/libs/grpc/src/cpp/util/error_details.cc
+++ b/contrib/libs/grpc/src/cpp/util/error_details.cc
@@ -22,29 +22,29 @@
namespace grpc {
-grpc::Status ExtractErrorDetails(const grpc::Status& from,
- ::google::rpc::Status* to) {
+grpc::Status ExtractErrorDetails(const grpc::Status& from,
+ ::google::rpc::Status* to) {
if (to == nullptr) {
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "");
+ return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "");
}
- if (!to->ParseFromString(TProtoStringType(from.error_details()))) {
- return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "");
+ if (!to->ParseFromString(TProtoStringType(from.error_details()))) {
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "");
}
- return grpc::Status::OK;
+ return grpc::Status::OK;
}
-grpc::Status SetErrorDetails(const ::google::rpc::Status& from,
- grpc::Status* to) {
+grpc::Status SetErrorDetails(const ::google::rpc::Status& from,
+ grpc::Status* to) {
if (to == nullptr) {
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "");
+ return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "");
}
- grpc::StatusCode code = grpc::StatusCode::UNKNOWN;
- if (from.code() >= grpc::StatusCode::OK &&
- from.code() <= grpc::StatusCode::UNAUTHENTICATED) {
- code = static_cast<grpc::StatusCode>(from.code());
+ grpc::StatusCode code = grpc::StatusCode::UNKNOWN;
+ if (from.code() >= grpc::StatusCode::OK &&
+ from.code() <= grpc::StatusCode::UNAUTHENTICATED) {
+ code = static_cast<grpc::StatusCode>(from.code());
}
- *to = grpc::Status(code, from.message(), from.SerializeAsString());
- return grpc::Status::OK;
+ *to = grpc::Status(code, from.message(), from.SerializeAsString());
+ return grpc::Status::OK;
}
} // namespace grpc
diff --git a/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto b/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto
index d0781094ea..a61c47ba49 100644
--- a/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto
+++ b/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto
@@ -35,7 +35,7 @@ option java_outer_classname = "ChannelzProto";
// Channel is a logical grouping of channels, subchannels, and sockets.
message Channel {
- // The identifier for this channel. This should be set.
+ // The identifier for this channel. This should be set.
ChannelRef ref = 1;
// Data specific to this channel.
ChannelData data = 2;
@@ -165,7 +165,7 @@ message ChannelRef {
reserved 3, 4, 5, 6, 7, 8;
}
-// SubchannelRef is a reference to a Subchannel.
+// SubchannelRef is a reference to a Subchannel.
message SubchannelRef {
// The globally unique id for this subchannel. Must be a positive number.
int64 subchannel_id = 7;
diff --git a/contrib/libs/grpc/src/proto/grpc/channelz/ya.make b/contrib/libs/grpc/src/proto/grpc/channelz/ya.make
index 9f1e3cedc9..42d41b87ea 100644
--- a/contrib/libs/grpc/src/proto/grpc/channelz/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/channelz/ya.make
@@ -1,27 +1,27 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- dvshkurko
- g:contrib
- g:cpp-contrib
-)
-
+OWNER(
+ akastornov
+ dvshkurko
+ g:contrib
+ g:cpp-contrib
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-GRPC()
-
-SRCS(
- channelz.proto
-)
-
+
+GRPC()
+
+SRCS(
+ channelz.proto
+)
+
EXCLUDE_TAGS(GO_PROTO)
-END()
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/core/ya.make b/contrib/libs/grpc/src/proto/grpc/core/ya.make
index 856c34ee53..c308922451 100644
--- a/contrib/libs/grpc/src/proto/grpc/core/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/core/ya.make
@@ -1,26 +1,26 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
+OWNER(
+ akastornov
+ g:contrib
g:cpp-contrib
-)
-
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-GRPC()
-
-SRCS(
- stats.proto
-)
-
+
+GRPC()
+
+SRCS(
+ stats.proto
+)
+
EXCLUDE_TAGS(GO_PROTO)
-END()
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/gcp/altscontext.proto b/contrib/libs/grpc/src/proto/grpc/gcp/altscontext.proto
index cce6dd2afc..60d16dc790 100644
--- a/contrib/libs/grpc/src/proto/grpc/gcp/altscontext.proto
+++ b/contrib/libs/grpc/src/proto/grpc/gcp/altscontext.proto
@@ -1,50 +1,50 @@
-// Copyright 2018 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// The canonical version of this proto can be found at
-// https://github.com/grpc/grpc-proto/blob/master/grpc/gcp/altscontext.proto
-
-syntax = "proto3";
-
-package grpc.gcp;
-
-import "src/proto/grpc/gcp/transport_security_common.proto";
-
-option go_package = "google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp";
-option java_multiple_files = true;
-option java_outer_classname = "AltsContextProto";
-option java_package = "io.grpc.alts.internal";
-
-message AltsContext {
- // The application protocol negotiated for this connection.
- string application_protocol = 1;
-
- // The record protocol negotiated for this connection.
- string record_protocol = 2;
-
- // The security level of the created secure channel.
- SecurityLevel security_level = 3;
-
- // The peer service account.
- string peer_service_account = 4;
-
- // The local service account.
- string local_service_account = 5;
-
- // The RPC protocol versions supported by the peer.
- RpcProtocolVersions peer_rpc_versions = 6;
-
- // Additional attributes of the peer.
- map<string, string> peer_attributes = 7;
-}
+// Copyright 2018 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The canonical version of this proto can be found at
+// https://github.com/grpc/grpc-proto/blob/master/grpc/gcp/altscontext.proto
+
+syntax = "proto3";
+
+package grpc.gcp;
+
+import "src/proto/grpc/gcp/transport_security_common.proto";
+
+option go_package = "google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp";
+option java_multiple_files = true;
+option java_outer_classname = "AltsContextProto";
+option java_package = "io.grpc.alts.internal";
+
+message AltsContext {
+ // The application protocol negotiated for this connection.
+ string application_protocol = 1;
+
+ // The record protocol negotiated for this connection.
+ string record_protocol = 2;
+
+ // The security level of the created secure channel.
+ SecurityLevel security_level = 3;
+
+ // The peer service account.
+ string peer_service_account = 4;
+
+ // The local service account.
+ string local_service_account = 5;
+
+ // The RPC protocol versions supported by the peer.
+ RpcProtocolVersions peer_rpc_versions = 6;
+
+ // Additional attributes of the peer.
+ map<string, string> peer_attributes = 7;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/gcp/handshaker.proto b/contrib/libs/grpc/src/proto/grpc/gcp/handshaker.proto
index fe0e1e199a..39bdc09ac7 100644
--- a/contrib/libs/grpc/src/proto/grpc/gcp/handshaker.proto
+++ b/contrib/libs/grpc/src/proto/grpc/gcp/handshaker.proto
@@ -1,243 +1,243 @@
-// Copyright 2018 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// The canonical version of this proto can be found at
-// https://github.com/grpc/grpc-proto/blob/master/grpc/gcp/handshaker.proto
-
-syntax = "proto3";
-
-package grpc.gcp;
-
-import "src/proto/grpc/gcp/transport_security_common.proto";
-
-option go_package = "google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp";
-option java_multiple_files = true;
-option java_outer_classname = "HandshakerProto";
-option java_package = "io.grpc.alts.internal";
-
-
-enum HandshakeProtocol {
- // Default value.
- HANDSHAKE_PROTOCOL_UNSPECIFIED = 0;
-
- // TLS handshake protocol.
- TLS = 1;
-
- // Application Layer Transport Security handshake protocol.
- ALTS = 2;
-}
-
-enum NetworkProtocol {
- NETWORK_PROTOCOL_UNSPECIFIED = 0;
- TCP = 1;
- UDP = 2;
-}
-
-message Endpoint {
- // IP address. It should contain an IPv4 or IPv6 string literal, e.g.
- // "192.168.0.1" or "2001:db8::1".
- string ip_address = 1;
-
- // Port number.
- int32 port = 2;
-
- // Network protocol (e.g., TCP, UDP) associated with this endpoint.
- NetworkProtocol protocol = 3;
-}
-
-message Identity {
- oneof identity_oneof {
- // Service account of a connection endpoint.
- string service_account = 1;
-
- // Hostname of a connection endpoint.
- string hostname = 2;
- }
-
- // Additional attributes of the identity.
- map<string, string> attributes = 3;
-}
-
-message StartClientHandshakeReq {
- // Handshake security protocol requested by the client.
- HandshakeProtocol handshake_security_protocol = 1;
-
- // The application protocols supported by the client, e.g., "h2" (for http2),
- // "grpc".
- repeated string application_protocols = 2;
-
- // The record protocols supported by the client, e.g.,
- // "ALTSRP_GCM_AES128".
- repeated string record_protocols = 3;
-
- // (Optional) Describes which server identities are acceptable by the client.
- // If target identities are provided and none of them matches the peer
- // identity of the server, handshake will fail.
- repeated Identity target_identities = 4;
-
- // (Optional) Application may specify a local identity. Otherwise, the
- // handshaker chooses a default local identity.
- Identity local_identity = 5;
-
- // (Optional) Local endpoint information of the connection to the server,
- // such as local IP address, port number, and network protocol.
- Endpoint local_endpoint = 6;
-
- // (Optional) Endpoint information of the remote server, such as IP address,
- // port number, and network protocol.
- Endpoint remote_endpoint = 7;
-
- // (Optional) If target name is provided, a secure naming check is performed
- // to verify that the peer authenticated identity is indeed authorized to run
- // the target name.
- string target_name = 8;
-
- // (Optional) RPC protocol versions supported by the client.
- RpcProtocolVersions rpc_versions = 9;
+// Copyright 2018 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The canonical version of this proto can be found at
+// https://github.com/grpc/grpc-proto/blob/master/grpc/gcp/handshaker.proto
+
+syntax = "proto3";
+
+package grpc.gcp;
+
+import "src/proto/grpc/gcp/transport_security_common.proto";
+
+option go_package = "google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp";
+option java_multiple_files = true;
+option java_outer_classname = "HandshakerProto";
+option java_package = "io.grpc.alts.internal";
+
+
+enum HandshakeProtocol {
+ // Default value.
+ HANDSHAKE_PROTOCOL_UNSPECIFIED = 0;
+
+ // TLS handshake protocol.
+ TLS = 1;
+
+ // Application Layer Transport Security handshake protocol.
+ ALTS = 2;
+}
+
+enum NetworkProtocol {
+ NETWORK_PROTOCOL_UNSPECIFIED = 0;
+ TCP = 1;
+ UDP = 2;
+}
+
+message Endpoint {
+ // IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+ // "192.168.0.1" or "2001:db8::1".
+ string ip_address = 1;
+
+ // Port number.
+ int32 port = 2;
+
+ // Network protocol (e.g., TCP, UDP) associated with this endpoint.
+ NetworkProtocol protocol = 3;
+}
+
+message Identity {
+ oneof identity_oneof {
+ // Service account of a connection endpoint.
+ string service_account = 1;
+
+ // Hostname of a connection endpoint.
+ string hostname = 2;
+ }
+
+ // Additional attributes of the identity.
+ map<string, string> attributes = 3;
+}
+
+message StartClientHandshakeReq {
+ // Handshake security protocol requested by the client.
+ HandshakeProtocol handshake_security_protocol = 1;
+
+ // The application protocols supported by the client, e.g., "h2" (for http2),
+ // "grpc".
+ repeated string application_protocols = 2;
+
+ // The record protocols supported by the client, e.g.,
+ // "ALTSRP_GCM_AES128".
+ repeated string record_protocols = 3;
+
+ // (Optional) Describes which server identities are acceptable by the client.
+ // If target identities are provided and none of them matches the peer
+ // identity of the server, handshake will fail.
+ repeated Identity target_identities = 4;
+
+ // (Optional) Application may specify a local identity. Otherwise, the
+ // handshaker chooses a default local identity.
+ Identity local_identity = 5;
+
+ // (Optional) Local endpoint information of the connection to the server,
+ // such as local IP address, port number, and network protocol.
+ Endpoint local_endpoint = 6;
+
+ // (Optional) Endpoint information of the remote server, such as IP address,
+ // port number, and network protocol.
+ Endpoint remote_endpoint = 7;
+
+ // (Optional) If target name is provided, a secure naming check is performed
+ // to verify that the peer authenticated identity is indeed authorized to run
+ // the target name.
+ string target_name = 8;
+
+ // (Optional) RPC protocol versions supported by the client.
+ RpcProtocolVersions rpc_versions = 9;
// (Optional) Maximum frame size supported by the client.
uint32 max_frame_size = 10;
-}
-
-message ServerHandshakeParameters {
- // The record protocols supported by the server, e.g.,
- // "ALTSRP_GCM_AES128".
- repeated string record_protocols = 1;
-
- // (Optional) A list of local identities supported by the server, if
- // specified. Otherwise, the handshaker chooses a default local identity.
- repeated Identity local_identities = 2;
-}
-
-message StartServerHandshakeReq {
- // The application protocols supported by the server, e.g., "h2" (for http2),
- // "grpc".
- repeated string application_protocols = 1;
-
- // Handshake parameters (record protocols and local identities supported by
- // the server) mapped by the handshake protocol. Each handshake security
- // protocol (e.g., TLS or ALTS) has its own set of record protocols and local
- // identities. Since protobuf does not support enum as key to the map, the key
- // to handshake_parameters is the integer value of HandshakeProtocol enum.
- map<int32, ServerHandshakeParameters> handshake_parameters = 2;
-
- // Bytes in out_frames returned from the peer's HandshakerResp. It is possible
- // that the peer's out_frames are split into multiple HandshakReq messages.
- bytes in_bytes = 3;
-
- // (Optional) Local endpoint information of the connection to the client,
- // such as local IP address, port number, and network protocol.
- Endpoint local_endpoint = 4;
-
- // (Optional) Endpoint information of the remote client, such as IP address,
- // port number, and network protocol.
- Endpoint remote_endpoint = 5;
-
- // (Optional) RPC protocol versions supported by the server.
- RpcProtocolVersions rpc_versions = 6;
+}
+
+message ServerHandshakeParameters {
+ // The record protocols supported by the server, e.g.,
+ // "ALTSRP_GCM_AES128".
+ repeated string record_protocols = 1;
+
+ // (Optional) A list of local identities supported by the server, if
+ // specified. Otherwise, the handshaker chooses a default local identity.
+ repeated Identity local_identities = 2;
+}
+
+message StartServerHandshakeReq {
+ // The application protocols supported by the server, e.g., "h2" (for http2),
+ // "grpc".
+ repeated string application_protocols = 1;
+
+ // Handshake parameters (record protocols and local identities supported by
+ // the server) mapped by the handshake protocol. Each handshake security
+ // protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+ // identities. Since protobuf does not support enum as key to the map, the key
+ // to handshake_parameters is the integer value of HandshakeProtocol enum.
+ map<int32, ServerHandshakeParameters> handshake_parameters = 2;
+
+ // Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+ // that the peer's out_frames are split into multiple HandshakReq messages.
+ bytes in_bytes = 3;
+
+ // (Optional) Local endpoint information of the connection to the client,
+ // such as local IP address, port number, and network protocol.
+ Endpoint local_endpoint = 4;
+
+ // (Optional) Endpoint information of the remote client, such as IP address,
+ // port number, and network protocol.
+ Endpoint remote_endpoint = 5;
+
+ // (Optional) RPC protocol versions supported by the server.
+ RpcProtocolVersions rpc_versions = 6;
// (Optional) Maximum frame size supported by the server.
uint32 max_frame_size = 7;
-}
-
-message NextHandshakeMessageReq {
- // Bytes in out_frames returned from the peer's HandshakerResp. It is possible
- // that the peer's out_frames are split into multiple NextHandshakerMessageReq
- // messages.
- bytes in_bytes = 1;
-}
-
-message HandshakerReq {
- oneof req_oneof {
- // The start client handshake request message.
- StartClientHandshakeReq client_start = 1;
-
- // The start server handshake request message.
- StartServerHandshakeReq server_start = 2;
-
- // The next handshake request message.
- NextHandshakeMessageReq next = 3;
- }
-}
-
-message HandshakerResult {
- // The application protocol negotiated for this connection.
- string application_protocol = 1;
-
- // The record protocol negotiated for this connection.
- string record_protocol = 2;
-
- // Cryptographic key data. The key data may be more than the key length
- // required for the record protocol, thus the client of the handshaker
- // service needs to truncate the key data into the right key length.
- bytes key_data = 3;
-
- // The authenticated identity of the peer.
- Identity peer_identity = 4;
-
- // The local identity used in the handshake.
- Identity local_identity = 5;
-
- // Indicate whether the handshaker service client should keep the channel
- // between the handshaker service open, e.g., in order to handle
- // post-handshake messages in the future.
- bool keep_channel_open = 6;
-
- // The RPC protocol versions supported by the peer.
- RpcProtocolVersions peer_rpc_versions = 7;
+}
+
+message NextHandshakeMessageReq {
+ // Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+ // that the peer's out_frames are split into multiple NextHandshakerMessageReq
+ // messages.
+ bytes in_bytes = 1;
+}
+
+message HandshakerReq {
+ oneof req_oneof {
+ // The start client handshake request message.
+ StartClientHandshakeReq client_start = 1;
+
+ // The start server handshake request message.
+ StartServerHandshakeReq server_start = 2;
+
+ // The next handshake request message.
+ NextHandshakeMessageReq next = 3;
+ }
+}
+
+message HandshakerResult {
+ // The application protocol negotiated for this connection.
+ string application_protocol = 1;
+
+ // The record protocol negotiated for this connection.
+ string record_protocol = 2;
+
+ // Cryptographic key data. The key data may be more than the key length
+ // required for the record protocol, thus the client of the handshaker
+ // service needs to truncate the key data into the right key length.
+ bytes key_data = 3;
+
+ // The authenticated identity of the peer.
+ Identity peer_identity = 4;
+
+ // The local identity used in the handshake.
+ Identity local_identity = 5;
+
+ // Indicate whether the handshaker service client should keep the channel
+ // between the handshaker service open, e.g., in order to handle
+ // post-handshake messages in the future.
+ bool keep_channel_open = 6;
+
+ // The RPC protocol versions supported by the peer.
+ RpcProtocolVersions peer_rpc_versions = 7;
// The maximum frame size of the peer.
uint32 max_frame_size = 8;
-}
-
-message HandshakerStatus {
- // The status code. This could be the gRPC status code.
- uint32 code = 1;
-
- // The status details.
- string details = 2;
-}
-
-message HandshakerResp {
- // Frames to be given to the peer for the NextHandshakeMessageReq. May be
- // empty if no out_frames have to be sent to the peer or if in_bytes in the
- // HandshakerReq are incomplete. All the non-empty out frames must be sent to
- // the peer even if the handshaker status is not OK as these frames may
- // contain the alert frames.
- bytes out_frames = 1;
-
- // Number of bytes in the in_bytes consumed by the handshaker. It is possible
- // that part of in_bytes in HandshakerReq was unrelated to the handshake
- // process.
- uint32 bytes_consumed = 2;
-
- // This is set iff the handshake was successful. out_frames may still be set
- // to frames that needs to be forwarded to the peer.
- HandshakerResult result = 3;
-
- // Status of the handshaker.
- HandshakerStatus status = 4;
-}
-
-service HandshakerService {
- // Handshaker service accepts a stream of handshaker request, returning a
- // stream of handshaker response. Client is expected to send exactly one
- // message with either client_start or server_start followed by one or more
- // messages with next. Each time client sends a request, the handshaker
- // service expects to respond. Client does not have to wait for service's
- // response before sending next request.
- rpc DoHandshake(stream HandshakerReq)
- returns (stream HandshakerResp) {
- }
-}
+}
+
+message HandshakerStatus {
+ // The status code. This could be the gRPC status code.
+ uint32 code = 1;
+
+ // The status details.
+ string details = 2;
+}
+
+message HandshakerResp {
+ // Frames to be given to the peer for the NextHandshakeMessageReq. May be
+ // empty if no out_frames have to be sent to the peer or if in_bytes in the
+ // HandshakerReq are incomplete. All the non-empty out frames must be sent to
+ // the peer even if the handshaker status is not OK as these frames may
+ // contain the alert frames.
+ bytes out_frames = 1;
+
+ // Number of bytes in the in_bytes consumed by the handshaker. It is possible
+ // that part of in_bytes in HandshakerReq was unrelated to the handshake
+ // process.
+ uint32 bytes_consumed = 2;
+
+ // This is set iff the handshake was successful. out_frames may still be set
+ // to frames that needs to be forwarded to the peer.
+ HandshakerResult result = 3;
+
+ // Status of the handshaker.
+ HandshakerStatus status = 4;
+}
+
+service HandshakerService {
+ // Handshaker service accepts a stream of handshaker request, returning a
+ // stream of handshaker response. Client is expected to send exactly one
+ // message with either client_start or server_start followed by one or more
+ // messages with next. Each time client sends a request, the handshaker
+ // service expects to respond. Client does not have to wait for service's
+ // response before sending next request.
+ rpc DoHandshake(stream HandshakerReq)
+ returns (stream HandshakerResp) {
+ }
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/gcp/transport_security_common.proto b/contrib/libs/grpc/src/proto/grpc/gcp/transport_security_common.proto
index 8f01be79e3..8a123b1c26 100644
--- a/contrib/libs/grpc/src/proto/grpc/gcp/transport_security_common.proto
+++ b/contrib/libs/grpc/src/proto/grpc/gcp/transport_security_common.proto
@@ -1,46 +1,46 @@
-// Copyright 2018 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// The canonical version of this proto can be found at
-// https://github.com/grpc/grpc-proto/blob/master/grpc/gcp/transport_security_common.proto
-
-syntax = "proto3";
-
-package grpc.gcp;
-
-option go_package = "google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp";
-option java_multiple_files = true;
-option java_outer_classname = "TransportSecurityCommonProto";
-option java_package = "io.grpc.alts.internal";
-
-// The security level of the created channel. The list is sorted in increasing
-// level of security. This order must always be maintained.
-enum SecurityLevel {
- SECURITY_NONE = 0;
- INTEGRITY_ONLY = 1;
- INTEGRITY_AND_PRIVACY = 2;
-}
-
-// Max and min supported RPC protocol versions.
-message RpcProtocolVersions {
- // RPC version contains a major version and a minor version.
- message Version {
- uint32 major = 1;
- uint32 minor = 2;
- }
- // Maximum supported RPC version.
- Version max_rpc_version = 1;
- // Minimum supported RPC version.
- Version min_rpc_version = 2;
-}
+// Copyright 2018 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The canonical version of this proto can be found at
+// https://github.com/grpc/grpc-proto/blob/master/grpc/gcp/transport_security_common.proto
+
+syntax = "proto3";
+
+package grpc.gcp;
+
+option go_package = "google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp";
+option java_multiple_files = true;
+option java_outer_classname = "TransportSecurityCommonProto";
+option java_package = "io.grpc.alts.internal";
+
+// The security level of the created channel. The list is sorted in increasing
+// level of security. This order must always be maintained.
+enum SecurityLevel {
+ SECURITY_NONE = 0;
+ INTEGRITY_ONLY = 1;
+ INTEGRITY_AND_PRIVACY = 2;
+}
+
+// Max and min supported RPC protocol versions.
+message RpcProtocolVersions {
+ // RPC version contains a major version and a minor version.
+ message Version {
+ uint32 major = 1;
+ uint32 minor = 2;
+ }
+ // Maximum supported RPC version.
+ Version max_rpc_version = 1;
+ // Minimum supported RPC version.
+ Version min_rpc_version = 2;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make b/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make
index 7bb8b0dff9..a33e7629ae 100644
--- a/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make
@@ -1,26 +1,26 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
+OWNER(
+ akastornov
+ g:contrib
g:cpp-contrib
-)
-
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-GRPC()
-
-SRCS(
- health.proto
-)
-
+
+GRPC()
+
+SRCS(
+ health.proto
+)
+
EXCLUDE_TAGS(GO_PROTO)
-END()
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/http_over_grpc/http_over_grpc.proto b/contrib/libs/grpc/src/proto/grpc/http_over_grpc/http_over_grpc.proto
index ccfa951cd4..87165db66f 100644
--- a/contrib/libs/grpc/src/proto/grpc/http_over_grpc/http_over_grpc.proto
+++ b/contrib/libs/grpc/src/proto/grpc/http_over_grpc/http_over_grpc.proto
@@ -1,51 +1,51 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.http_over_grpc;
-
-// Represents HTTP 1.1 header.
-message Header {
- string key = 1;
- repeated string values = 2;
-}
-
-// An HTTP 1.1 request encapsulated in a gRPC.
-message HTTPOverGRPCRequest {
- // The HTTP request method.
- string method = 1;
- // The HTTP request URL.
- string url = 2;
- // The HTTP request headers.
- repeated Header headers = 3;
- // HTTP request body.
- bytes body = 4;
-}
-
-// An HTTP 1.1 reply encapsulated in an RPC.
-message HTTPOverGRPCReply {
- // The HTTP status code (e.g. 200, 400, 404).
- int32 status = 1;
- // The HTTP response headers.
- repeated Header headers = 2;
- // The HTTP response body.
- bytes body = 3;
-}
-
-// Currently does not support HTTP chunked transfer encoding.
-service HTTPOverGRPC {
- // Perform the given HTTP request.
- rpc HTTPRequest(HTTPOverGRPCRequest) returns (HTTPOverGRPCReply) {}
-}
+// Copyright 2019 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+syntax = "proto3";
+
+package grpc.http_over_grpc;
+
+// Represents HTTP 1.1 header.
+message Header {
+ string key = 1;
+ repeated string values = 2;
+}
+
+// An HTTP 1.1 request encapsulated in a gRPC.
+message HTTPOverGRPCRequest {
+ // The HTTP request method.
+ string method = 1;
+ // The HTTP request URL.
+ string url = 2;
+ // The HTTP request headers.
+ repeated Header headers = 3;
+ // HTTP request body.
+ bytes body = 4;
+}
+
+// An HTTP 1.1 reply encapsulated in an RPC.
+message HTTPOverGRPCReply {
+ // The HTTP status code (e.g. 200, 400, 404).
+ int32 status = 1;
+ // The HTTP response headers.
+ repeated Header headers = 2;
+ // The HTTP response body.
+ bytes body = 3;
+}
+
+// Currently does not support HTTP chunked transfer encoding.
+service HTTPOverGRPC {
+ // Perform the given HTTP request.
+ rpc HTTPRequest(HTTPOverGRPCRequest) returns (HTTPOverGRPCReply) {}
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/ya.make b/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/ya.make
index f8e301c937..5c59d3fad0 100644
--- a/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/ya.make
@@ -1,28 +1,28 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
- g:cpp-contrib
-)
-
+OWNER(
+ akastornov
+ g:contrib
+ g:cpp-contrib
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
+
PY_NAMESPACE(src.proto.grpc.reflection.v1alpha)
-GRPC()
-
-SRCS(
- reflection.proto
-)
-
+GRPC()
+
+SRCS(
+ reflection.proto
+)
+
EXCLUDE_TAGS(GO_PROTO)
-END()
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/status/ya.make b/contrib/libs/grpc/src/proto/grpc/status/ya.make
index eec367765f..491b0fe2eb 100644
--- a/contrib/libs/grpc/src/proto/grpc/status/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/status/ya.make
@@ -1,26 +1,26 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
- g:cpp-contrib
-)
-
+OWNER(
+ akastornov
+ g:contrib
+ g:cpp-contrib
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-GRPC()
-
-SRCS(
- status.proto
-)
-
+
+GRPC()
+
+SRCS(
+ status.proto
+)
+
EXCLUDE_TAGS(GO_PROTO)
-END()
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/control.proto b/contrib/libs/grpc/src/proto/grpc/testing/control.proto
index 742b21926e..9c23dff71e 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/control.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/control.proto
@@ -226,22 +226,22 @@ message Scenarios {
// once the scenario has finished.
message ScenarioResultSummary
{
- // Total number of operations per second over all clients. What is counted as 1 'operation' depends on the benchmark scenarios:
- // For unary benchmarks, an operation is processing of a single unary RPC.
- // For streaming benchmarks, an operation is processing of a single ping pong of request and response.
+ // Total number of operations per second over all clients. What is counted as 1 'operation' depends on the benchmark scenarios:
+ // For unary benchmarks, an operation is processing of a single unary RPC.
+ // For streaming benchmarks, an operation is processing of a single ping pong of request and response.
double qps = 1;
- // QPS per server core.
+ // QPS per server core.
double qps_per_server_core = 2;
- // The total server cpu load based on system time across all server processes, expressed as percentage of a single cpu core.
- // For example, 85 implies 85% of a cpu core, 125 implies 125% of a cpu core. Since we are accumulating the cpu load across all the server
- // processes, the value could > 100 when there are multiple servers or a single server using multiple threads and cores.
- // Same explanation for the total client cpu load below.
+ // The total server cpu load based on system time across all server processes, expressed as percentage of a single cpu core.
+ // For example, 85 implies 85% of a cpu core, 125 implies 125% of a cpu core. Since we are accumulating the cpu load across all the server
+ // processes, the value could > 100 when there are multiple servers or a single server using multiple threads and cores.
+ // Same explanation for the total client cpu load below.
double server_system_time = 3;
- // The total server cpu load based on user time across all server processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
+ // The total server cpu load based on user time across all server processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
double server_user_time = 4;
- // The total client cpu load based on system time across all client processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
+ // The total client cpu load based on system time across all client processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
double client_system_time = 5;
- // The total client cpu load based on user time across all client processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
+ // The total client cpu load based on user time across all client processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
double client_user_time = 6;
// X% latency percentiles (in nanoseconds)
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make b/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make
index b94aa415f8..10f4d8a6ea 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make
@@ -1,34 +1,34 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
+OWNER(
+ akastornov
+ g:contrib
g:cpp-contrib
-)
-
-EXCLUDE_TAGS(
+)
+
+EXCLUDE_TAGS(
GO_PROTO
- PY_PROTO
- PY3_PROTO
-)
-
+ PY_PROTO
+ PY3_PROTO
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/testing
-)
-
-GRPC()
-
-SRCS(
- echo_duplicate.proto
-)
-
-END()
+
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/testing
+)
+
+GRPC()
+
+SRCS(
+ echo_duplicate.proto
+)
+
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
index 6f1e5f3404..91cc79e292 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
@@ -17,8 +17,8 @@ syntax = "proto3";
package grpc.testing;
-option cc_enable_arenas = true;
-
+option cc_enable_arenas = true;
+
// Message to be echoed back serialized in trailer.
message DebugInfo {
repeated string stack_entries = 1;
@@ -49,7 +49,7 @@ message RequestParams {
ErrorStatus expected_error = 14;
int32 server_sleep_us = 15; // sleep when invoking server for deadline tests
int32 backend_channel_idx = 16; // which backend to send request to
- bool echo_metadata_initially = 17;
+ bool echo_metadata_initially = 17;
bool server_notify_client_when_started = 18;
}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
index 70e3427760..4523e298c5 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
@@ -48,21 +48,21 @@ message EchoStatus {
string message = 2;
}
-// The type of route that a client took to reach a server w.r.t. gRPCLB.
-// The server must fill in "fallback" if it detects that the RPC reached
-// the server via the "gRPCLB fallback" path, and "backend" if it detects
-// that the RPC reached the server via "gRPCLB backend" path (i.e. if it got
-// the address of this server from the gRPCLB server BalanceLoad RPC). Exactly
-// how this detection is done is context and server dependent.
-enum GrpclbRouteType {
- // Server didn't detect the route that a client took to reach it.
- GRPCLB_ROUTE_TYPE_UNKNOWN = 0;
- // Indicates that a client reached a server via gRPCLB fallback.
- GRPCLB_ROUTE_TYPE_FALLBACK = 1;
- // Indicates that a client reached a server as a gRPCLB-given backend.
- GRPCLB_ROUTE_TYPE_BACKEND = 2;
-}
-
+// The type of route that a client took to reach a server w.r.t. gRPCLB.
+// The server must fill in "fallback" if it detects that the RPC reached
+// the server via the "gRPCLB fallback" path, and "backend" if it detects
+// that the RPC reached the server via "gRPCLB backend" path (i.e. if it got
+// the address of this server from the gRPCLB server BalanceLoad RPC). Exactly
+// how this detection is done is context and server dependent.
+enum GrpclbRouteType {
+ // Server didn't detect the route that a client took to reach it.
+ GRPCLB_ROUTE_TYPE_UNKNOWN = 0;
+ // Indicates that a client reached a server via gRPCLB fallback.
+ GRPCLB_ROUTE_TYPE_FALLBACK = 1;
+ // Indicates that a client reached a server as a gRPCLB-given backend.
+ GRPCLB_ROUTE_TYPE_BACKEND = 2;
+}
+
// Unary request.
message SimpleRequest {
// Desired payload type in the response from the server.
@@ -92,12 +92,12 @@ message SimpleRequest {
// Whether the server should expect this request to be compressed.
BoolValue expect_compressed = 8;
-
- // Whether SimpleResponse should include server_id.
- bool fill_server_id = 9;
-
- // Whether SimpleResponse should include grpclb_route_type.
- bool fill_grpclb_route_type = 10;
+
+ // Whether SimpleResponse should include server_id.
+ bool fill_server_id = 9;
+
+ // Whether SimpleResponse should include grpclb_route_type.
+ bool fill_grpclb_route_type = 10;
}
// Unary response, as configured by the request.
@@ -109,12 +109,12 @@ message SimpleResponse {
string username = 2;
// OAuth scope.
string oauth_scope = 3;
-
- // Server ID. This must be unique among different server instances,
- // but the same across all RPC's made to a particular server instance.
- string server_id = 4;
- // gRPCLB Path.
- GrpclbRouteType grpclb_route_type = 5;
+
+ // Server ID. This must be unique among different server instances,
+ // but the same across all RPC's made to a particular server instance.
+ string server_id = 4;
+ // gRPCLB Path.
+ GrpclbRouteType grpclb_route_type = 5;
// Server hostname.
string hostname = 6;
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto b/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
index 6950400643..cffd985d4e 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
@@ -22,7 +22,7 @@ syntax = "proto3";
package grpc.testing;
-// Response message containing the gauge name and value
+// Response message containing the gauge name and value
message GaugeResponse {
string name = 1;
oneof value {
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto
index 0d308fbbea..a6aafbe53e 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto
@@ -1,51 +1,51 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the eds protocol and its dependency.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.service.discovery.v2;
-
-import "src/proto/grpc/testing/xds/eds_for_test.proto";
-
-// [#not-implemented-hide:] Discovery services for endpoints, clusters, routes,
-// and listeners are retained in the package `envoy.api.v2` for backwards
-// compatibility with existing management servers. New development in discovery
-// services should proceed in the package `envoy.service.discovery.v2`.
-
-// See https://github.com/lyft/envoy-api#apis for a description of the role of
-// ADS and how it is intended to be used by a management server. ADS requests
-// have the same structure as their singleton xDS counterparts, but can
-// multiplex many resource types on a single stream. The type_url in the
-// DiscoveryRequest/DiscoveryResponse provides sufficient information to recover
-// the multiplexed singleton APIs at the Envoy instance and management server.
-service AggregatedDiscoveryService {
- // This is a gRPC-only API.
- rpc StreamAggregatedResources(stream envoy.api.v2.DiscoveryRequest)
- returns (stream envoy.api.v2.DiscoveryResponse) {
- }
-
- // Commented out so that we don't have to copy the request/response protos.
-// rpc DeltaAggregatedResources(stream api.v2.DeltaDiscoveryRequest)
-// returns (stream api.v2.DeltaDiscoveryResponse) {
-// }
-}
+// Copyright 2019 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// This file contains the eds protocol and its dependency.
+//
+// TODO(juanlishen): This file is a hack to avoid a problem we're
+// currently having where we can't depend on a proto file in an external
+// repo due to bazel limitations. Once that's fixed, this should be
+// removed. Until this, it should be used in the gRPC tests only, or else it
+// will cause a conflict due to the same proto messages being defined in
+// multiple files in the same binary.
+
+syntax = "proto3";
+
+package envoy.service.discovery.v2;
+
+import "src/proto/grpc/testing/xds/eds_for_test.proto";
+
+// [#not-implemented-hide:] Discovery services for endpoints, clusters, routes,
+// and listeners are retained in the package `envoy.api.v2` for backwards
+// compatibility with existing management servers. New development in discovery
+// services should proceed in the package `envoy.service.discovery.v2`.
+
+// See https://github.com/lyft/envoy-api#apis for a description of the role of
+// ADS and how it is intended to be used by a management server. ADS requests
+// have the same structure as their singleton xDS counterparts, but can
+// multiplex many resource types on a single stream. The type_url in the
+// DiscoveryRequest/DiscoveryResponse provides sufficient information to recover
+// the multiplexed singleton APIs at the Envoy instance and management server.
+service AggregatedDiscoveryService {
+ // This is a gRPC-only API.
+ rpc StreamAggregatedResources(stream envoy.api.v2.DiscoveryRequest)
+ returns (stream envoy.api.v2.DiscoveryResponse) {
+ }
+
+ // Commented out so that we don't have to copy the request/response protos.
+// rpc DeltaAggregatedResources(stream api.v2.DeltaDiscoveryRequest)
+// returns (stream api.v2.DeltaDiscoveryResponse) {
+// }
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto
index 3b8ce66f0e..b095996e4b 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto
@@ -1,108 +1,108 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the xds protocol and its dependency. It can't be used by
-// the gRPC library; otherwise there can be duplicate definition problems if
-// users depend on both gRPC and Envoy. It can only be used by gRPC tests.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.api.v2;
-
-import "google/protobuf/any.proto";
+// Copyright 2019 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// This file contains the xds protocol and its dependency. It can't be used by
+// the gRPC library; otherwise there can be duplicate definition problems if
+// users depend on both gRPC and Envoy. It can only be used by gRPC tests.
+//
+// TODO(juanlishen): This file is a hack to avoid a problem we're
+// currently having where we can't depend on a proto file in an external
+// repo due to bazel limitations. Once that's fixed, this should be
+// removed. Until this, it should be used in the gRPC tests only, or else it
+// will cause a conflict due to the same proto messages being defined in
+// multiple files in the same binary.
+
+syntax = "proto3";
+
+package envoy.api.v2;
+
+import "google/protobuf/any.proto";
import "google/protobuf/struct.proto";
import "google/protobuf/wrappers.proto";
-
-message Status {
- // The status code, which should be an enum value of [google.rpc.Code][].
- int32 code = 1;
-
- // A developer-facing error message, which should be in English. Any
- // user-facing error message should be localized and sent in the
- // [google.rpc.Status.details][] field, or localized by the client.
- string message = 2;
-
- // A list of messages that carry the error details. There is a common set of
- // message types for APIs to use.
- repeated google.protobuf.Any details = 3;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Identifies location of where either Envoy runs or where upstream hosts run.
-message Locality {
- // Region this :ref:`zone <envoy_api_field_core.Locality.zone>` belongs to.
- string region = 1;
-
- // Defines the local service zone where Envoy is running. Though optional, it
- // should be set if discovery service routing is used and the discovery
- // service exposes :ref:`zone data <envoy_api_field_endpoint.LocalityLbEndpoints.locality>`,
- // either in this message or via :option:`--service-zone`. The meaning of zone
- // is context dependent, e.g. `Availability Zone (AZ)
- // <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html>`_
- // on AWS, `Zone <https://cloud.google.com/compute/docs/regions-zones/>`_ on
- // GCP, etc.
- string zone = 2;
-
- // When used for locality of upstream hosts, this field further splits zone
- // into smaller chunks of sub-zones so they can be load balanced
- // independently.
- string sub_zone = 3;
-}
-
-// Identifies a specific Envoy instance. The node identifier is presented to the
-// management server, which may use this identifier to distinguish per Envoy
-// configuration for serving.
-message Node {
- // An opaque node identifier for the Envoy node. This also provides the local
- // service node name. It should be set if any of the following features are
- // used: :ref:`statsd <arch_overview_statistics>`, :ref:`CDS
- // <config_cluster_manager_cds>`, and :ref:`HTTP tracing
- // <arch_overview_tracing>`, either in this message or via
- // :option:`--service-node`.
- string id = 1;
-
- // Defines the local service cluster name where Envoy is running. Though
- // optional, it should be set if any of the following features are used:
- // :ref:`statsd <arch_overview_statistics>`, :ref:`health check cluster
- // verification <envoy_api_field_core.HealthCheck.HttpHealthCheck.service_name>`,
- // :ref:`runtime override directory <envoy_api_msg_config.bootstrap.v2.Runtime>`,
- // :ref:`user agent addition
- // <envoy_api_field_config.filter.network.http_connection_manager.v2.HttpConnectionManager.add_user_agent>`,
- // :ref:`HTTP global rate limiting <config_http_filters_rate_limit>`,
- // :ref:`CDS <config_cluster_manager_cds>`, and :ref:`HTTP tracing
- // <arch_overview_tracing>`, either in this message or via
- // :option:`--service-cluster`.
- string cluster = 2;
-
- // Opaque metadata extending the node identifier. Envoy will pass this
- // directly to the management server.
+
+message Status {
+ // The status code, which should be an enum value of [google.rpc.Code][].
+ int32 code = 1;
+
+ // A developer-facing error message, which should be in English. Any
+ // user-facing error message should be localized and sent in the
+ // [google.rpc.Status.details][] field, or localized by the client.
+ string message = 2;
+
+ // A list of messages that carry the error details. There is a common set of
+ // message types for APIs to use.
+ repeated google.protobuf.Any details = 3;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+// Identifies location of where either Envoy runs or where upstream hosts run.
+message Locality {
+ // Region this :ref:`zone <envoy_api_field_core.Locality.zone>` belongs to.
+ string region = 1;
+
+ // Defines the local service zone where Envoy is running. Though optional, it
+ // should be set if discovery service routing is used and the discovery
+ // service exposes :ref:`zone data <envoy_api_field_endpoint.LocalityLbEndpoints.locality>`,
+ // either in this message or via :option:`--service-zone`. The meaning of zone
+ // is context dependent, e.g. `Availability Zone (AZ)
+ // <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html>`_
+ // on AWS, `Zone <https://cloud.google.com/compute/docs/regions-zones/>`_ on
+ // GCP, etc.
+ string zone = 2;
+
+ // When used for locality of upstream hosts, this field further splits zone
+ // into smaller chunks of sub-zones so they can be load balanced
+ // independently.
+ string sub_zone = 3;
+}
+
+// Identifies a specific Envoy instance. The node identifier is presented to the
+// management server, which may use this identifier to distinguish per Envoy
+// configuration for serving.
+message Node {
+ // An opaque node identifier for the Envoy node. This also provides the local
+ // service node name. It should be set if any of the following features are
+ // used: :ref:`statsd <arch_overview_statistics>`, :ref:`CDS
+ // <config_cluster_manager_cds>`, and :ref:`HTTP tracing
+ // <arch_overview_tracing>`, either in this message or via
+ // :option:`--service-node`.
+ string id = 1;
+
+ // Defines the local service cluster name where Envoy is running. Though
+ // optional, it should be set if any of the following features are used:
+ // :ref:`statsd <arch_overview_statistics>`, :ref:`health check cluster
+ // verification <envoy_api_field_core.HealthCheck.HttpHealthCheck.service_name>`,
+ // :ref:`runtime override directory <envoy_api_msg_config.bootstrap.v2.Runtime>`,
+ // :ref:`user agent addition
+ // <envoy_api_field_config.filter.network.http_connection_manager.v2.HttpConnectionManager.add_user_agent>`,
+ // :ref:`HTTP global rate limiting <config_http_filters_rate_limit>`,
+ // :ref:`CDS <config_cluster_manager_cds>`, and :ref:`HTTP tracing
+ // <arch_overview_tracing>`, either in this message or via
+ // :option:`--service-cluster`.
+ string cluster = 2;
+
+ // Opaque metadata extending the node identifier. Envoy will pass this
+ // directly to the management server.
google.protobuf.Struct metadata = 3;
-
- // Locality specifying where the Envoy instance is running.
- Locality locality = 4;
-
- // This is motivated by informing a management server during canary which
- // version of Envoy is being tested in a heterogeneous fleet. This will be set
- // by Envoy in management server RPCs.
+
+ // Locality specifying where the Envoy instance is running.
+ Locality locality = 4;
+
+ // This is motivated by informing a management server during canary which
+ // version of Envoy is being tested in a heterogeneous fleet. This will be set
+ // by Envoy in management server RPCs.
string build_version = 5 [deprecated = true];
// Free-form string that identifies the entity requesting config.
@@ -121,397 +121,397 @@ message Node {
// See :ref:`the list of features <client_features>` that xDS client may
// support.
repeated string client_features = 10;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// A DiscoveryRequest requests a set of versioned resources of the same type for
-// a given Envoy node on some API.
-message DiscoveryRequest {
- // The version_info provided in the request messages will be the version_info
- // received with the most recent successfully processed response or empty on
- // the first request. It is expected that no new request is sent after a
- // response is received until the Envoy instance is ready to ACK/NACK the new
- // configuration. ACK/NACK takes place by returning the new API config version
- // as applied or the previous API config version respectively. Each type_url
- // (see below) has an independent version associated with it.
- string version_info = 1;
-
- // The node making the request.
- Node node = 2;
-
- // List of resources to subscribe to, e.g. list of cluster names or a route
- // configuration name. If this is empty, all resources for the API are
- // returned. LDS/CDS expect empty resource_names, since this is global
- // discovery for the Envoy instance. The LDS and CDS responses will then imply
- // a number of resources that need to be fetched via EDS/RDS, which will be
- // explicitly enumerated in resource_names.
- repeated string resource_names = 3;
-
- // Type of the resource that is being requested, e.g.
- // "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment". This is implicit
- // in requests made via singleton xDS APIs such as CDS, LDS, etc. but is
- // required for ADS.
- string type_url = 4;
-
- // nonce corresponding to DiscoveryResponse being ACK/NACKed. See above
- // discussion on version_info and the DiscoveryResponse nonce comment. This
- // may be empty if no nonce is available, e.g. at startup or for non-stream
- // xDS implementations.
- string response_nonce = 5;
-
- // This is populated when the previous :ref:`DiscoveryResponse <envoy_api_msg_DiscoveryResponse>`
- // failed to update configuration. The *message* field in *error_details* provides the Envoy
- // internal exception related to the failure. It is only intended for consumption during manual
- // debugging, the string provided is not guaranteed to be stable across Envoy versions.
- Status error_detail = 6;
-}
-
-message DiscoveryResponse {
- // The version of the response data.
- string version_info = 1;
-
- // The response resources. These resources are typed and depend on the API being called.
- repeated google.protobuf.Any resources = 2;
-
- // [#not-implemented-hide:]
- // Canary is used to support two Envoy command line flags:
- //
- // * --terminate-on-canary-transition-failure. When set, Envoy is able to
- // terminate if it detects that configuration is stuck at canary. Consider
- // this example sequence of updates:
- // - Management server applies a canary config successfully.
- // - Management server rolls back to a production config.
- // - Envoy rejects the new production config.
- // Since there is no sensible way to continue receiving configuration
- // updates, Envoy will then terminate and apply production config from a
- // clean slate.
- // * --dry-run-canary. When set, a canary response will never be applied, only
- // validated via a dry run.
- bool canary = 3;
-
- // Type URL for resources. This must be consistent with the type_url in the
- // Any messages for resources if resources is non-empty. This effectively
- // identifies the xDS API when muxing over ADS.
- string type_url = 4;
-
- // For gRPC based subscriptions, the nonce provides a way to explicitly ack a
- // specific DiscoveryResponse in a following DiscoveryRequest. Additional
- // messages may have been sent by Envoy to the management server for the
- // previous version on the stream prior to this DiscoveryResponse, that were
- // unprocessed at response send time. The nonce allows the management server
- // to ignore any further DiscoveryRequests for the previous version until a
- // DiscoveryRequest bearing the nonce. The nonce is optional and is not
- // required for non-stream based xDS implementations.
- string nonce = 5;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-message Pipe {
- // Unix Domain Socket path. On Linux, paths starting with '@' will use the
- // abstract namespace. The starting '@' is replaced by a null byte by Envoy.
- // Paths starting with '@' will result in an error in environments other than
- // Linux.
- string path = 1;
-}
-
-message SocketAddress {
- enum Protocol {
- TCP = 0;
- // [#not-implemented-hide:]
- UDP = 1;
- }
- Protocol protocol = 1;
- // The address for this socket. :ref:`Listeners <config_listeners>` will bind
- // to the address. An empty address is not allowed. Specify ``0.0.0.0`` or ``::``
- // to bind to any address. [#comment:TODO(zuercher) reinstate when implemented:
- // It is possible to distinguish a Listener address via the prefix/suffix matching
- // in :ref:`FilterChainMatch <envoy_api_msg_listener.FilterChainMatch>`.] When used
- // within an upstream :ref:`BindConfig <envoy_api_msg_core.BindConfig>`, the address
- // controls the source address of outbound connections. For :ref:`clusters
- // <envoy_api_msg_Cluster>`, the cluster type determines whether the
- // address must be an IP (*STATIC* or *EDS* clusters) or a hostname resolved by DNS
- // (*STRICT_DNS* or *LOGICAL_DNS* clusters). Address resolution can be customized
- // via :ref:`resolver_name <envoy_api_field_core.SocketAddress.resolver_name>`.
- string address = 2;
- oneof port_specifier {
- uint32 port_value = 3;
- // This is only valid if :ref:`resolver_name
- // <envoy_api_field_core.SocketAddress.resolver_name>` is specified below and the
- // named resolver is capable of named port resolution.
- string named_port = 4;
- }
- // The name of the resolver. This must have been registered with Envoy. If this is
- // empty, a context dependent default applies. If address is a hostname this
- // should be set for resolution other than DNS. If the address is a concrete
- // IP address, no resolution will occur.
- string resolver_name = 5;
-
- // When binding to an IPv6 address above, this enables `IPv4 compatibity
- // <https://tools.ietf.org/html/rfc3493#page-11>`_. Binding to ``::`` will
- // allow both IPv4 and IPv6 connections, with peer IPv4 addresses mapped into
- // IPv6 space as ``::FFFF:<IPv4-address>``.
- bool ipv4_compat = 6;
-}
-
-// Addresses specify either a logical or physical address and port, which are
-// used to tell Envoy where to bind/listen, connect to upstream and find
-// management servers.
-message Address {
- oneof address {
-
- SocketAddress socket_address = 1;
- Pipe pipe = 2;
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-message Metadata {
- // Key is the reverse DNS filter name, e.g. com.acme.widget. The envoy.*
- // namespace is reserved for Envoy's built-in filters.
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+// A DiscoveryRequest requests a set of versioned resources of the same type for
+// a given Envoy node on some API.
+message DiscoveryRequest {
+ // The version_info provided in the request messages will be the version_info
+ // received with the most recent successfully processed response or empty on
+ // the first request. It is expected that no new request is sent after a
+ // response is received until the Envoy instance is ready to ACK/NACK the new
+ // configuration. ACK/NACK takes place by returning the new API config version
+ // as applied or the previous API config version respectively. Each type_url
+ // (see below) has an independent version associated with it.
+ string version_info = 1;
+
+ // The node making the request.
+ Node node = 2;
+
+ // List of resources to subscribe to, e.g. list of cluster names or a route
+ // configuration name. If this is empty, all resources for the API are
+ // returned. LDS/CDS expect empty resource_names, since this is global
+ // discovery for the Envoy instance. The LDS and CDS responses will then imply
+ // a number of resources that need to be fetched via EDS/RDS, which will be
+ // explicitly enumerated in resource_names.
+ repeated string resource_names = 3;
+
+ // Type of the resource that is being requested, e.g.
+ // "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment". This is implicit
+ // in requests made via singleton xDS APIs such as CDS, LDS, etc. but is
+ // required for ADS.
+ string type_url = 4;
+
+ // nonce corresponding to DiscoveryResponse being ACK/NACKed. See above
+ // discussion on version_info and the DiscoveryResponse nonce comment. This
+ // may be empty if no nonce is available, e.g. at startup or for non-stream
+ // xDS implementations.
+ string response_nonce = 5;
+
+ // This is populated when the previous :ref:`DiscoveryResponse <envoy_api_msg_DiscoveryResponse>`
+ // failed to update configuration. The *message* field in *error_details* provides the Envoy
+ // internal exception related to the failure. It is only intended for consumption during manual
+ // debugging, the string provided is not guaranteed to be stable across Envoy versions.
+ Status error_detail = 6;
+}
+
+message DiscoveryResponse {
+ // The version of the response data.
+ string version_info = 1;
+
+ // The response resources. These resources are typed and depend on the API being called.
+ repeated google.protobuf.Any resources = 2;
+
+ // [#not-implemented-hide:]
+ // Canary is used to support two Envoy command line flags:
+ //
+ // * --terminate-on-canary-transition-failure. When set, Envoy is able to
+ // terminate if it detects that configuration is stuck at canary. Consider
+ // this example sequence of updates:
+ // - Management server applies a canary config successfully.
+ // - Management server rolls back to a production config.
+ // - Envoy rejects the new production config.
+ // Since there is no sensible way to continue receiving configuration
+ // updates, Envoy will then terminate and apply production config from a
+ // clean slate.
+ // * --dry-run-canary. When set, a canary response will never be applied, only
+ // validated via a dry run.
+ bool canary = 3;
+
+ // Type URL for resources. This must be consistent with the type_url in the
+ // Any messages for resources if resources is non-empty. This effectively
+ // identifies the xDS API when muxing over ADS.
+ string type_url = 4;
+
+ // For gRPC based subscriptions, the nonce provides a way to explicitly ack a
+ // specific DiscoveryResponse in a following DiscoveryRequest. Additional
+ // messages may have been sent by Envoy to the management server for the
+ // previous version on the stream prior to this DiscoveryResponse, that were
+ // unprocessed at response send time. The nonce allows the management server
+ // to ignore any further DiscoveryRequests for the previous version until a
+ // DiscoveryRequest bearing the nonce. The nonce is optional and is not
+ // required for non-stream based xDS implementations.
+ string nonce = 5;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+message Pipe {
+ // Unix Domain Socket path. On Linux, paths starting with '@' will use the
+ // abstract namespace. The starting '@' is replaced by a null byte by Envoy.
+ // Paths starting with '@' will result in an error in environments other than
+ // Linux.
+ string path = 1;
+}
+
+message SocketAddress {
+ enum Protocol {
+ TCP = 0;
+ // [#not-implemented-hide:]
+ UDP = 1;
+ }
+ Protocol protocol = 1;
+ // The address for this socket. :ref:`Listeners <config_listeners>` will bind
+ // to the address. An empty address is not allowed. Specify ``0.0.0.0`` or ``::``
+ // to bind to any address. [#comment:TODO(zuercher) reinstate when implemented:
+ // It is possible to distinguish a Listener address via the prefix/suffix matching
+ // in :ref:`FilterChainMatch <envoy_api_msg_listener.FilterChainMatch>`.] When used
+ // within an upstream :ref:`BindConfig <envoy_api_msg_core.BindConfig>`, the address
+ // controls the source address of outbound connections. For :ref:`clusters
+ // <envoy_api_msg_Cluster>`, the cluster type determines whether the
+ // address must be an IP (*STATIC* or *EDS* clusters) or a hostname resolved by DNS
+ // (*STRICT_DNS* or *LOGICAL_DNS* clusters). Address resolution can be customized
+ // via :ref:`resolver_name <envoy_api_field_core.SocketAddress.resolver_name>`.
+ string address = 2;
+ oneof port_specifier {
+ uint32 port_value = 3;
+ // This is only valid if :ref:`resolver_name
+ // <envoy_api_field_core.SocketAddress.resolver_name>` is specified below and the
+ // named resolver is capable of named port resolution.
+ string named_port = 4;
+ }
+ // The name of the resolver. This must have been registered with Envoy. If this is
+ // empty, a context dependent default applies. If address is a hostname this
+ // should be set for resolution other than DNS. If the address is a concrete
+ // IP address, no resolution will occur.
+ string resolver_name = 5;
+
+ // When binding to an IPv6 address above, this enables `IPv4 compatibity
+ // <https://tools.ietf.org/html/rfc3493#page-11>`_. Binding to ``::`` will
+ // allow both IPv4 and IPv6 connections, with peer IPv4 addresses mapped into
+ // IPv6 space as ``::FFFF:<IPv4-address>``.
+ bool ipv4_compat = 6;
+}
+
+// Addresses specify either a logical or physical address and port, which are
+// used to tell Envoy where to bind/listen, connect to upstream and find
+// management servers.
+message Address {
+ oneof address {
+
+ SocketAddress socket_address = 1;
+ Pipe pipe = 2;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+message Metadata {
+ // Key is the reverse DNS filter name, e.g. com.acme.widget. The envoy.*
+ // namespace is reserved for Envoy's built-in filters.
map<string, google.protobuf.Struct> filter_metadata = 1;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Endpoint health status.
-enum HealthStatus {
- // The health status is not known. This is interpreted by Envoy as *HEALTHY*.
- UNKNOWN = 0;
-
- // Healthy.
- HEALTHY = 1;
-
- // Unhealthy.
- UNHEALTHY = 2;
-
- // Connection draining in progress. E.g.,
- // `<https://aws.amazon.com/blogs/aws/elb-connection-draining-remove-instances-from-service-with-care/>`_
- // or
- // `<https://cloud.google.com/compute/docs/load-balancing/enabling-connection-draining>`_.
- // This is interpreted by Envoy as *UNHEALTHY*.
- DRAINING = 3;
-
- // Health check timed out. This is part of HDS and is interpreted by Envoy as
- // *UNHEALTHY*.
- TIMEOUT = 4;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Upstream host identifier.
-message Endpoint {
- // The upstream host address.
- //
- // .. attention::
- //
- // The form of host address depends on the given cluster type. For STATIC or EDS,
- // it is expected to be a direct IP address (or something resolvable by the
- // specified :ref:`resolver <envoy_api_field_core.SocketAddress.resolver_name>`
- // in the Address). For LOGICAL or STRICT DNS, it is expected to be hostname,
- // and will be resolved via DNS.
- Address address = 1;
-
- // The optional health check configuration.
- message HealthCheckConfig {
- // Optional alternative health check port value.
- //
- // By default the health check address port of an upstream host is the same
- // as the host's serving address port. This provides an alternative health
- // check port. Setting this with a non-zero value allows an upstream host
- // to have different health check address port.
- uint32 port_value = 1;
- }
-
- // The optional health check configuration is used as configuration for the
- // health checker to contact the health checked host.
- //
- // .. attention::
- //
- // This takes into effect only for upstream clusters with
- // :ref:`active health checking <arch_overview_health_checking>` enabled.
- HealthCheckConfig health_check_config = 2;
-}
-
-// An Endpoint that Envoy can route traffic to.
-message LbEndpoint {
- // Upstream host identifier
- Endpoint endpoint = 1;
-
- // Optional health status when known and supplied by EDS server.
- HealthStatus health_status = 2;
-
- // The endpoint metadata specifies values that may be used by the load
- // balancer to select endpoints in a cluster for a given request. The filter
- // name should be specified as *envoy.lb*. An example boolean key-value pair
- // is *canary*, providing the optional canary status of the upstream host.
- // This may be matched against in a route's
- // :ref:`RouteAction <envoy_api_msg_route.RouteAction>` metadata_match field
- // to subset the endpoints considered in cluster load balancing.
- Metadata metadata = 3;
-
- // The optional load balancing weight of the upstream host, in the range 1 -
- // 128. Envoy uses the load balancing weight in some of the built in load
- // balancers. The load balancing weight for an endpoint is divided by the sum
- // of the weights of all endpoints in the endpoint's locality to produce a
- // percentage of traffic for the endpoint. This percentage is then further
- // weighted by the endpoint's locality's load balancing weight from
- // LocalityLbEndpoints. If unspecified, each host is presumed to have equal
- // weight in a locality.
- //
- // .. attention::
- //
- // The limit of 128 is somewhat arbitrary, but is applied due to performance
- // concerns with the current implementation and can be removed when
- // `this issue <https://github.com/envoyproxy/envoy/issues/1285>`_ is fixed.
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+// Endpoint health status.
+enum HealthStatus {
+ // The health status is not known. This is interpreted by Envoy as *HEALTHY*.
+ UNKNOWN = 0;
+
+ // Healthy.
+ HEALTHY = 1;
+
+ // Unhealthy.
+ UNHEALTHY = 2;
+
+ // Connection draining in progress. E.g.,
+ // `<https://aws.amazon.com/blogs/aws/elb-connection-draining-remove-instances-from-service-with-care/>`_
+ // or
+ // `<https://cloud.google.com/compute/docs/load-balancing/enabling-connection-draining>`_.
+ // This is interpreted by Envoy as *UNHEALTHY*.
+ DRAINING = 3;
+
+ // Health check timed out. This is part of HDS and is interpreted by Envoy as
+ // *UNHEALTHY*.
+ TIMEOUT = 4;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+// Upstream host identifier.
+message Endpoint {
+ // The upstream host address.
+ //
+ // .. attention::
+ //
+ // The form of host address depends on the given cluster type. For STATIC or EDS,
+ // it is expected to be a direct IP address (or something resolvable by the
+ // specified :ref:`resolver <envoy_api_field_core.SocketAddress.resolver_name>`
+ // in the Address). For LOGICAL or STRICT DNS, it is expected to be hostname,
+ // and will be resolved via DNS.
+ Address address = 1;
+
+ // The optional health check configuration.
+ message HealthCheckConfig {
+ // Optional alternative health check port value.
+ //
+ // By default the health check address port of an upstream host is the same
+ // as the host's serving address port. This provides an alternative health
+ // check port. Setting this with a non-zero value allows an upstream host
+ // to have different health check address port.
+ uint32 port_value = 1;
+ }
+
+ // The optional health check configuration is used as configuration for the
+ // health checker to contact the health checked host.
+ //
+ // .. attention::
+ //
+ // This takes into effect only for upstream clusters with
+ // :ref:`active health checking <arch_overview_health_checking>` enabled.
+ HealthCheckConfig health_check_config = 2;
+}
+
+// An Endpoint that Envoy can route traffic to.
+message LbEndpoint {
+ // Upstream host identifier
+ Endpoint endpoint = 1;
+
+ // Optional health status when known and supplied by EDS server.
+ HealthStatus health_status = 2;
+
+ // The endpoint metadata specifies values that may be used by the load
+ // balancer to select endpoints in a cluster for a given request. The filter
+ // name should be specified as *envoy.lb*. An example boolean key-value pair
+ // is *canary*, providing the optional canary status of the upstream host.
+ // This may be matched against in a route's
+ // :ref:`RouteAction <envoy_api_msg_route.RouteAction>` metadata_match field
+ // to subset the endpoints considered in cluster load balancing.
+ Metadata metadata = 3;
+
+ // The optional load balancing weight of the upstream host, in the range 1 -
+ // 128. Envoy uses the load balancing weight in some of the built in load
+ // balancers. The load balancing weight for an endpoint is divided by the sum
+ // of the weights of all endpoints in the endpoint's locality to produce a
+ // percentage of traffic for the endpoint. This percentage is then further
+ // weighted by the endpoint's locality's load balancing weight from
+ // LocalityLbEndpoints. If unspecified, each host is presumed to have equal
+ // weight in a locality.
+ //
+ // .. attention::
+ //
+ // The limit of 128 is somewhat arbitrary, but is applied due to performance
+ // concerns with the current implementation and can be removed when
+ // `this issue <https://github.com/envoyproxy/envoy/issues/1285>`_ is fixed.
google.protobuf.UInt32Value load_balancing_weight = 4;
-}
-
-// A group of endpoints belonging to a Locality.
-// One can have multiple LocalityLbEndpoints for a locality, but this is
-// generally only done if the different groups need to have different load
-// balancing weights or different priorities.
-message LocalityLbEndpoints {
- // Identifies location of where the upstream hosts run.
- Locality locality = 1;
-
- // The group of endpoints belonging to the locality specified.
- repeated LbEndpoint lb_endpoints = 2;
-
- // Optional: Per priority/region/zone/sub_zone weight - range 1-128. The load
- // balancing weight for a locality is divided by the sum of the weights of all
- // localities at the same priority level to produce the effective percentage
- // of traffic for the locality.
- //
- // Locality weights are only considered when :ref:`locality weighted load
- // balancing <arch_overview_load_balancing_locality_weighted_lb>` is
- // configured. These weights are ignored otherwise. If no weights are
- // specificed when locality weighted load balancing is enabled, the cluster is
- // assumed to have a weight of 1.
- //
- // .. attention::
- //
- // The limit of 128 is somewhat arbitrary, but is applied due to performance
- // concerns with the current implementation and can be removed when
- // `this issue <https://github.com/envoyproxy/envoy/issues/1285>`_ is fixed.
+}
+
+// A group of endpoints belonging to a Locality.
+// One can have multiple LocalityLbEndpoints for a locality, but this is
+// generally only done if the different groups need to have different load
+// balancing weights or different priorities.
+message LocalityLbEndpoints {
+ // Identifies location of where the upstream hosts run.
+ Locality locality = 1;
+
+ // The group of endpoints belonging to the locality specified.
+ repeated LbEndpoint lb_endpoints = 2;
+
+ // Optional: Per priority/region/zone/sub_zone weight - range 1-128. The load
+ // balancing weight for a locality is divided by the sum of the weights of all
+ // localities at the same priority level to produce the effective percentage
+ // of traffic for the locality.
+ //
+ // Locality weights are only considered when :ref:`locality weighted load
+ // balancing <arch_overview_load_balancing_locality_weighted_lb>` is
+ // configured. These weights are ignored otherwise. If no weights are
+ // specificed when locality weighted load balancing is enabled, the cluster is
+ // assumed to have a weight of 1.
+ //
+ // .. attention::
+ //
+ // The limit of 128 is somewhat arbitrary, but is applied due to performance
+ // concerns with the current implementation and can be removed when
+ // `this issue <https://github.com/envoyproxy/envoy/issues/1285>`_ is fixed.
google.protobuf.UInt32Value load_balancing_weight = 3;
-
- // Optional: the priority for this LocalityLbEndpoints. If unspecified this will
- // default to the highest priority (0).
- //
- // Under usual circumstances, Envoy will only select endpoints for the highest
- // priority (0). In the event all endpoints for a particular priority are
- // unavailable/unhealthy, Envoy will fail over to selecting endpoints for the
- // next highest priority group.
- //
- // Priorities should range from 0 (highest) to N (lowest) without skipping.
- uint32 priority = 5;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-message FractionalPercent {
- // Specifies the numerator. Defaults to 0.
- uint32 numerator = 1;
-
- // Fraction percentages support several fixed denominator values.
- enum DenominatorType {
- // 100.
- //
- // **Example**: 1/100 = 1%.
- HUNDRED = 0;
-
- // 10,000.
- //
- // **Example**: 1/10000 = 0.01%.
- TEN_THOUSAND = 1;
-
- // 1,000,000.
- //
- // **Example**: 1/1000000 = 0.0001%.
- MILLION = 2;
- }
-
- // Specifies the denominator. If the denominator specified is less than the numerator, the final
- // fractional percentage is capped at 1 (100%).
- DenominatorType denominator = 2;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// [#protodoc-title: EDS]
-// Endpoint discovery :ref:`architecture overview <arch_overview_service_discovery_types_eds>`
-service EndpointDiscoveryService {
- // The resource_names field in DiscoveryRequest specifies a list of clusters
- // to subscribe to updates for.
- rpc StreamEndpoints(stream DiscoveryRequest) returns (stream DiscoveryResponse) {
- }
-}
-
-// Each route from RDS will map to a single cluster or traffic split across
-// clusters using weights expressed in the RDS WeightedCluster.
-//
-// With EDS, each cluster is treated independently from a LB perspective, with
-// LB taking place between the Localities within a cluster and at a finer
-// granularity between the hosts within a locality. For a given cluster, the
-// effective weight of a host is its load_balancing_weight multiplied by the
-// load_balancing_weight of its Locality.
-message ClusterLoadAssignment {
- // Name of the cluster. This will be the :ref:`service_name
- // <envoy_api_field_Cluster.EdsClusterConfig.service_name>` value if specified
- // in the cluster :ref:`EdsClusterConfig
- // <envoy_api_msg_Cluster.EdsClusterConfig>`.
- string cluster_name = 1;
-
- // List of endpoints to load balance to.
- repeated LocalityLbEndpoints endpoints = 2;
-
- // Load balancing policy settings.
- message Policy {
- reserved 1;
-
- message DropOverload {
- // Identifier for the policy specifying the drop.
- string category = 1;
-
- // Percentage of traffic that should be dropped for the category.
- FractionalPercent drop_percentage = 2;
- }
- // Action to trim the overall incoming traffic to protect the upstream
- // hosts. This action allows protection in case the hosts are unable to
- // recover from an outage, or unable to autoscale or unable to handle
- // incoming traffic volume for any reason.
- //
- // At the client each category is applied one after the other to generate
- // the 'actual' drop percentage on all outgoing traffic. For example:
- //
- // .. code-block:: json
- //
- // { "drop_overloads": [
- // { "category": "throttle", "drop_percentage": 60 }
- // { "category": "lb", "drop_percentage": 50 }
- // ]}
- //
- // The actual drop percentages applied to the traffic at the clients will be
- // "throttle"_drop = 60%
- // "lb"_drop = 20% // 50% of the remaining 'actual' load, which is 40%.
- // actual_outgoing_load = 20% // remaining after applying all categories.
- repeated DropOverload drop_overloads = 2;
-
- // Priority levels and localities are considered overprovisioned with this
- // factor (in percentage). This means that we don't consider a priority
- // level or locality unhealthy until the percentage of healthy hosts
- // multiplied by the overprovisioning factor drops below 100.
- // With the default value 140(1.4), Envoy doesn't consider a priority level
- // or a locality unhealthy until their percentage of healthy hosts drops
- // below 72%.
- // Read more at :ref:`priority levels <arch_overview_load_balancing_priority_levels>` and
- // :ref:`localities <arch_overview_load_balancing_locality_weighted_lb>`.
+
+ // Optional: the priority for this LocalityLbEndpoints. If unspecified this will
+ // default to the highest priority (0).
+ //
+ // Under usual circumstances, Envoy will only select endpoints for the highest
+ // priority (0). In the event all endpoints for a particular priority are
+ // unavailable/unhealthy, Envoy will fail over to selecting endpoints for the
+ // next highest priority group.
+ //
+ // Priorities should range from 0 (highest) to N (lowest) without skipping.
+ uint32 priority = 5;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+message FractionalPercent {
+ // Specifies the numerator. Defaults to 0.
+ uint32 numerator = 1;
+
+ // Fraction percentages support several fixed denominator values.
+ enum DenominatorType {
+ // 100.
+ //
+ // **Example**: 1/100 = 1%.
+ HUNDRED = 0;
+
+ // 10,000.
+ //
+ // **Example**: 1/10000 = 0.01%.
+ TEN_THOUSAND = 1;
+
+ // 1,000,000.
+ //
+ // **Example**: 1/1000000 = 0.0001%.
+ MILLION = 2;
+ }
+
+ // Specifies the denominator. If the denominator specified is less than the numerator, the final
+ // fractional percentage is capped at 1 (100%).
+ DenominatorType denominator = 2;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+// [#protodoc-title: EDS]
+// Endpoint discovery :ref:`architecture overview <arch_overview_service_discovery_types_eds>`
+service EndpointDiscoveryService {
+ // The resource_names field in DiscoveryRequest specifies a list of clusters
+ // to subscribe to updates for.
+ rpc StreamEndpoints(stream DiscoveryRequest) returns (stream DiscoveryResponse) {
+ }
+}
+
+// Each route from RDS will map to a single cluster or traffic split across
+// clusters using weights expressed in the RDS WeightedCluster.
+//
+// With EDS, each cluster is treated independently from a LB perspective, with
+// LB taking place between the Localities within a cluster and at a finer
+// granularity between the hosts within a locality. For a given cluster, the
+// effective weight of a host is its load_balancing_weight multiplied by the
+// load_balancing_weight of its Locality.
+message ClusterLoadAssignment {
+ // Name of the cluster. This will be the :ref:`service_name
+ // <envoy_api_field_Cluster.EdsClusterConfig.service_name>` value if specified
+ // in the cluster :ref:`EdsClusterConfig
+ // <envoy_api_msg_Cluster.EdsClusterConfig>`.
+ string cluster_name = 1;
+
+ // List of endpoints to load balance to.
+ repeated LocalityLbEndpoints endpoints = 2;
+
+ // Load balancing policy settings.
+ message Policy {
+ reserved 1;
+
+ message DropOverload {
+ // Identifier for the policy specifying the drop.
+ string category = 1;
+
+ // Percentage of traffic that should be dropped for the category.
+ FractionalPercent drop_percentage = 2;
+ }
+ // Action to trim the overall incoming traffic to protect the upstream
+ // hosts. This action allows protection in case the hosts are unable to
+ // recover from an outage, or unable to autoscale or unable to handle
+ // incoming traffic volume for any reason.
+ //
+ // At the client each category is applied one after the other to generate
+ // the 'actual' drop percentage on all outgoing traffic. For example:
+ //
+ // .. code-block:: json
+ //
+ // { "drop_overloads": [
+ // { "category": "throttle", "drop_percentage": 60 }
+ // { "category": "lb", "drop_percentage": 50 }
+ // ]}
+ //
+ // The actual drop percentages applied to the traffic at the clients will be
+ // "throttle"_drop = 60%
+ // "lb"_drop = 20% // 50% of the remaining 'actual' load, which is 40%.
+ // actual_outgoing_load = 20% // remaining after applying all categories.
+ repeated DropOverload drop_overloads = 2;
+
+ // Priority levels and localities are considered overprovisioned with this
+ // factor (in percentage). This means that we don't consider a priority
+ // level or locality unhealthy until the percentage of healthy hosts
+ // multiplied by the overprovisioning factor drops below 100.
+ // With the default value 140(1.4), Envoy doesn't consider a priority level
+ // or a locality unhealthy until their percentage of healthy hosts drops
+ // below 72%.
+ // Read more at :ref:`priority levels <arch_overview_load_balancing_priority_levels>` and
+ // :ref:`localities <arch_overview_load_balancing_locality_weighted_lb>`.
google.protobuf.UInt32Value overprovisioning_factor = 3;
- }
-
- // Load balancing policy settings.
- Policy policy = 4;
-}
+ }
+
+ // Load balancing policy settings.
+ Policy policy = 4;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto
index d46d5e2ccc..30913e3927 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto
@@ -1,189 +1,189 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the eds protocol and its dependency.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.service.load_stats.v2;
-
-import "google/protobuf/duration.proto";
-import "src/proto/grpc/testing/xds/eds_for_test.proto";
-
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-message EndpointLoadMetricStats {
- // Name of the metric; may be empty.
- string metric_name = 1;
-
- // Number of calls that finished and included this metric.
- uint64 num_requests_finished_with_metric = 2;
-
- // Sum of metric values across all calls that finished with this metric for
- // load_reporting_interval.
- double total_metric_value = 3;
-}
-
-message UpstreamLocalityStats {
- // Name of zone, region and optionally endpoint group these metrics were
- // collected from. Zone and region names could be empty if unknown.
- envoy.api.v2.Locality locality = 1;
-
- // The total number of requests successfully completed by the endpoints in the
- // locality.
- uint64 total_successful_requests = 2;
-
- // The total number of unfinished requests
- uint64 total_requests_in_progress = 3;
-
- // The total number of requests that failed due to errors at the endpoint,
- // aggregated over all endpoints in the locality.
- uint64 total_error_requests = 4;
-
- // The total number of requests that were issued by this Envoy since
- // the last report. This information is aggregated over all the
- // upstream endpoints in the locality.
- uint64 total_issued_requests = 8;
-
- // Stats for multi-dimensional load balancing.
- repeated EndpointLoadMetricStats load_metric_stats = 5;
-
-// // Endpoint granularity stats information for this locality. This information
-// // is populated if the Server requests it by setting
-// // :ref:`LoadStatsResponse.report_endpoint_granularity<envoy_api_field_load_stats.LoadStatsResponse.report_endpoint_granularity>`.
-// repeated UpstreamEndpointStats upstream_endpoint_stats = 7;
-
- // [#not-implemented-hide:] The priority of the endpoint group these metrics
- // were collected from.
- uint32 priority = 6;
-}
-
-// Per cluster load stats. Envoy reports these stats a management server in a
-// :ref:`LoadStatsRequest<envoy_api_msg_load_stats.LoadStatsRequest>`
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-// Next ID: 7
-message ClusterStats {
- // The name of the cluster.
- string cluster_name = 1;
-
- // The eds_cluster_config service_name of the cluster.
- // It's possible that two clusters send the same service_name to EDS,
- // in that case, the management server is supposed to do aggregation on the load reports.
- string cluster_service_name = 6;
-
- // Need at least one.
- repeated UpstreamLocalityStats upstream_locality_stats = 2;
-
- // Cluster-level stats such as total_successful_requests may be computed by
- // summing upstream_locality_stats. In addition, below there are additional
- // cluster-wide stats.
- //
- // The total number of dropped requests. This covers requests
- // deliberately dropped by the drop_overload policy and circuit breaking.
- uint64 total_dropped_requests = 3;
-
- message DroppedRequests {
- // Identifier for the policy specifying the drop.
- string category = 1;
- // Total number of deliberately dropped requests for the category.
- uint64 dropped_count = 2;
- }
- // Information about deliberately dropped requests for each category specified
- // in the DropOverload policy.
- repeated DroppedRequests dropped_requests = 5;
-
- // Period over which the actual load report occurred. This will be guaranteed to include every
- // request reported. Due to system load and delays between the *LoadStatsRequest* sent from Envoy
- // and the *LoadStatsResponse* message sent from the management server, this may be longer than
- // the requested load reporting interval in the *LoadStatsResponse*.
- google.protobuf.Duration load_report_interval = 4;
-}
-
-// [#protodoc-title: Load reporting service]
-
-service LoadReportingService {
- // Advanced API to allow for multi-dimensional load balancing by remote
- // server. For receiving LB assignments, the steps are:
- // 1, The management server is configured with per cluster/zone/load metric
- // capacity configuration. The capacity configuration definition is
- // outside of the scope of this document.
- // 2. Envoy issues a standard {Stream,Fetch}Endpoints request for the clusters
- // to balance.
- //
- // Independently, Envoy will initiate a StreamLoadStats bidi stream with a
- // management server:
- // 1. Once a connection establishes, the management server publishes a
- // LoadStatsResponse for all clusters it is interested in learning load
- // stats about.
- // 2. For each cluster, Envoy load balances incoming traffic to upstream hosts
- // based on per-zone weights and/or per-instance weights (if specified)
- // based on intra-zone LbPolicy. This information comes from the above
- // {Stream,Fetch}Endpoints.
- // 3. When upstream hosts reply, they optionally add header <define header
- // name> with ASCII representation of EndpointLoadMetricStats.
- // 4. Envoy aggregates load reports over the period of time given to it in
- // LoadStatsResponse.load_reporting_interval. This includes aggregation
- // stats Envoy maintains by itself (total_requests, rpc_errors etc.) as
- // well as load metrics from upstream hosts.
- // 5. When the timer of load_reporting_interval expires, Envoy sends new
- // LoadStatsRequest filled with load reports for each cluster.
- // 6. The management server uses the load reports from all reported Envoys
- // from around the world, computes global assignment and prepares traffic
- // assignment destined for each zone Envoys are located in. Goto 2.
- rpc StreamLoadStats(stream LoadStatsRequest) returns (stream LoadStatsResponse) {
- }
-}
-
-// A load report Envoy sends to the management server.
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-message LoadStatsRequest {
- // Node identifier for Envoy instance.
- envoy.api.v2.Node node = 1;
-
- // A list of load stats to report.
- repeated ClusterStats cluster_stats = 2;
-}
-
-// The management server sends envoy a LoadStatsResponse with all clusters it
-// is interested in learning load stats about.
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-message LoadStatsResponse {
- // Clusters to report stats for.
+// Copyright 2019 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// This file contains the eds protocol and its dependency.
+//
+// TODO(juanlishen): This file is a hack to avoid a problem we're
+// currently having where we can't depend on a proto file in an external
+// repo due to bazel limitations. Once that's fixed, this should be
+// removed. Until this, it should be used in the gRPC tests only, or else it
+// will cause a conflict due to the same proto messages being defined in
+// multiple files in the same binary.
+
+syntax = "proto3";
+
+package envoy.service.load_stats.v2;
+
+import "google/protobuf/duration.proto";
+import "src/proto/grpc/testing/xds/eds_for_test.proto";
+
+// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
+message EndpointLoadMetricStats {
+ // Name of the metric; may be empty.
+ string metric_name = 1;
+
+ // Number of calls that finished and included this metric.
+ uint64 num_requests_finished_with_metric = 2;
+
+ // Sum of metric values across all calls that finished with this metric for
+ // load_reporting_interval.
+ double total_metric_value = 3;
+}
+
+message UpstreamLocalityStats {
+ // Name of zone, region and optionally endpoint group these metrics were
+ // collected from. Zone and region names could be empty if unknown.
+ envoy.api.v2.Locality locality = 1;
+
+ // The total number of requests successfully completed by the endpoints in the
+ // locality.
+ uint64 total_successful_requests = 2;
+
+ // The total number of unfinished requests
+ uint64 total_requests_in_progress = 3;
+
+ // The total number of requests that failed due to errors at the endpoint,
+ // aggregated over all endpoints in the locality.
+ uint64 total_error_requests = 4;
+
+ // The total number of requests that were issued by this Envoy since
+ // the last report. This information is aggregated over all the
+ // upstream endpoints in the locality.
+ uint64 total_issued_requests = 8;
+
+ // Stats for multi-dimensional load balancing.
+ repeated EndpointLoadMetricStats load_metric_stats = 5;
+
+// // Endpoint granularity stats information for this locality. This information
+// // is populated if the Server requests it by setting
+// // :ref:`LoadStatsResponse.report_endpoint_granularity<envoy_api_field_load_stats.LoadStatsResponse.report_endpoint_granularity>`.
+// repeated UpstreamEndpointStats upstream_endpoint_stats = 7;
+
+ // [#not-implemented-hide:] The priority of the endpoint group these metrics
+ // were collected from.
+ uint32 priority = 6;
+}
+
+// Per cluster load stats. Envoy reports these stats a management server in a
+// :ref:`LoadStatsRequest<envoy_api_msg_load_stats.LoadStatsRequest>`
+// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
+// Next ID: 7
+message ClusterStats {
+ // The name of the cluster.
+ string cluster_name = 1;
+
+ // The eds_cluster_config service_name of the cluster.
+ // It's possible that two clusters send the same service_name to EDS,
+ // in that case, the management server is supposed to do aggregation on the load reports.
+ string cluster_service_name = 6;
+
+ // Need at least one.
+ repeated UpstreamLocalityStats upstream_locality_stats = 2;
+
+ // Cluster-level stats such as total_successful_requests may be computed by
+ // summing upstream_locality_stats. In addition, below there are additional
+ // cluster-wide stats.
+ //
+ // The total number of dropped requests. This covers requests
+ // deliberately dropped by the drop_overload policy and circuit breaking.
+ uint64 total_dropped_requests = 3;
+
+ message DroppedRequests {
+ // Identifier for the policy specifying the drop.
+ string category = 1;
+ // Total number of deliberately dropped requests for the category.
+ uint64 dropped_count = 2;
+ }
+ // Information about deliberately dropped requests for each category specified
+ // in the DropOverload policy.
+ repeated DroppedRequests dropped_requests = 5;
+
+ // Period over which the actual load report occurred. This will be guaranteed to include every
+ // request reported. Due to system load and delays between the *LoadStatsRequest* sent from Envoy
+ // and the *LoadStatsResponse* message sent from the management server, this may be longer than
+ // the requested load reporting interval in the *LoadStatsResponse*.
+ google.protobuf.Duration load_report_interval = 4;
+}
+
+// [#protodoc-title: Load reporting service]
+
+service LoadReportingService {
+ // Advanced API to allow for multi-dimensional load balancing by remote
+ // server. For receiving LB assignments, the steps are:
+ // 1, The management server is configured with per cluster/zone/load metric
+ // capacity configuration. The capacity configuration definition is
+ // outside of the scope of this document.
+ // 2. Envoy issues a standard {Stream,Fetch}Endpoints request for the clusters
+ // to balance.
+ //
+ // Independently, Envoy will initiate a StreamLoadStats bidi stream with a
+ // management server:
+ // 1. Once a connection establishes, the management server publishes a
+ // LoadStatsResponse for all clusters it is interested in learning load
+ // stats about.
+ // 2. For each cluster, Envoy load balances incoming traffic to upstream hosts
+ // based on per-zone weights and/or per-instance weights (if specified)
+ // based on intra-zone LbPolicy. This information comes from the above
+ // {Stream,Fetch}Endpoints.
+ // 3. When upstream hosts reply, they optionally add header <define header
+ // name> with ASCII representation of EndpointLoadMetricStats.
+ // 4. Envoy aggregates load reports over the period of time given to it in
+ // LoadStatsResponse.load_reporting_interval. This includes aggregation
+ // stats Envoy maintains by itself (total_requests, rpc_errors etc.) as
+ // well as load metrics from upstream hosts.
+ // 5. When the timer of load_reporting_interval expires, Envoy sends new
+ // LoadStatsRequest filled with load reports for each cluster.
+ // 6. The management server uses the load reports from all reported Envoys
+ // from around the world, computes global assignment and prepares traffic
+ // assignment destined for each zone Envoys are located in. Goto 2.
+ rpc StreamLoadStats(stream LoadStatsRequest) returns (stream LoadStatsResponse) {
+ }
+}
+
+// A load report Envoy sends to the management server.
+// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
+message LoadStatsRequest {
+ // Node identifier for Envoy instance.
+ envoy.api.v2.Node node = 1;
+
+ // A list of load stats to report.
+ repeated ClusterStats cluster_stats = 2;
+}
+
+// The management server sends envoy a LoadStatsResponse with all clusters it
+// is interested in learning load stats about.
+// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
+message LoadStatsResponse {
+ // Clusters to report stats for.
// Not populated if *send_all_clusters* is true.
- repeated string clusters = 1;
-
+ repeated string clusters = 1;
+
// If true, the client should send all clusters it knows about.
// Only clients that advertise the "envoy.lrs.supports_send_all_clusters" capability in their
// :ref:`client_features<envoy_api_field_core.Node.client_features>` field will honor this field.
bool send_all_clusters = 4;
- // The minimum interval of time to collect stats over. This is only a minimum for two reasons:
- // 1. There may be some delay from when the timer fires until stats sampling occurs.
- // 2. For clusters that were already feature in the previous *LoadStatsResponse*, any traffic
- // that is observed in between the corresponding previous *LoadStatsRequest* and this
- // *LoadStatsResponse* will also be accumulated and billed to the cluster. This avoids a period
- // of inobservability that might otherwise exists between the messages. New clusters are not
- // subject to this consideration.
- google.protobuf.Duration load_reporting_interval = 2;
-
- // Set to *true* if the management server supports endpoint granularity
- // report.
- bool report_endpoint_granularity = 3;
-}
+ // The minimum interval of time to collect stats over. This is only a minimum for two reasons:
+ // 1. There may be some delay from when the timer fires until stats sampling occurs.
+ // 2. For clusters that were already feature in the previous *LoadStatsResponse*, any traffic
+ // that is observed in between the corresponding previous *LoadStatsRequest* and this
+ // *LoadStatsResponse* will also be accumulated and billed to the cluster. This avoids a period
+ // of inobservability that might otherwise exists between the messages. New clusters are not
+ // subject to this consideration.
+ google.protobuf.Duration load_reporting_interval = 2;
+
+ // Set to *true* if the management server supports endpoint granularity
+ // report.
+ bool report_endpoint_granularity = 3;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/orca_load_report_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/orca_load_report_for_test.proto
index 1feaedd6a4..8d062779ee 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/orca_load_report_for_test.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/xds/orca_load_report_for_test.proto
@@ -1,58 +1,58 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains a copy of the ORCA load reporting protos, with the
-// validation options stripped out to avoid the extra dependency on
-// protoc-gen-validate.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package udpa.data.orca.v1;
-
-option java_outer_classname = "OrcaLoadReportProto";
-option java_multiple_files = true;
-option java_package = "io.envoyproxy.udpa.data.orca.v1";
-option go_package = "v1";
-
-// See section `ORCA load report format` of the design document in
-// :ref:`https://github.com/envoyproxy/envoy/issues/6614`.
-
-message OrcaLoadReport {
- // CPU utilization expressed as a fraction of available CPU resources. This
- // should be derived from the latest sample or measurement.
- double cpu_utilization = 1;
-
- // Memory utilization expressed as a fraction of available memory
- // resources. This should be derived from the latest sample or measurement.
- double mem_utilization = 2;
-
- // Total RPS being served by an endpoint. This should cover all services that an endpoint is
- // responsible for.
- uint64 rps = 3;
-
- // Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of
- // storage) associated with the request.
- map<string, double> request_cost = 4;
-
- // Resource utilization values. Each value is expressed as a fraction of total resources
- // available, derived from the latest sample or measurement.
- map<string, double> utilization = 5;
-}
+// Copyright 2019 The gRPC Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// This file contains a copy of the ORCA load reporting protos, with the
+// validation options stripped out to avoid the extra dependency on
+// protoc-gen-validate.
+//
+// TODO(juanlishen): This file is a hack to avoid a problem we're
+// currently having where we can't depend on a proto file in an external
+// repo due to bazel limitations. Once that's fixed, this should be
+// removed. Until this, it should be used in the gRPC tests only, or else it
+// will cause a conflict due to the same proto messages being defined in
+// multiple files in the same binary.
+
+syntax = "proto3";
+
+package udpa.data.orca.v1;
+
+option java_outer_classname = "OrcaLoadReportProto";
+option java_multiple_files = true;
+option java_package = "io.envoyproxy.udpa.data.orca.v1";
+option go_package = "v1";
+
+// See section `ORCA load report format` of the design document in
+// :ref:`https://github.com/envoyproxy/envoy/issues/6614`.
+
+message OrcaLoadReport {
+ // CPU utilization expressed as a fraction of available CPU resources. This
+ // should be derived from the latest sample or measurement.
+ double cpu_utilization = 1;
+
+ // Memory utilization expressed as a fraction of available memory
+ // resources. This should be derived from the latest sample or measurement.
+ double mem_utilization = 2;
+
+ // Total RPS being served by an endpoint. This should cover all services that an endpoint is
+ // responsible for.
+ uint64 rps = 3;
+
+ // Application specific requests costs. Each value is an absolute cost (e.g. 3487 bytes of
+ // storage) associated with the request.
+ map<string, double> request_cost = 4;
+
+ // Resource utilization values. Each value is expressed as a fraction of total resources
+ // available, derived from the latest sample or measurement.
+ map<string, double> utilization = 5;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make b/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make
index 994ec6fa82..62bd4e2a7c 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make
@@ -1,39 +1,39 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
- g:cpp-contrib
-)
-
-EXCLUDE_TAGS(
+OWNER(
+ akastornov
+ g:contrib
+ g:cpp-contrib
+)
+
+EXCLUDE_TAGS(
GO_PROTO
- PY_PROTO
- PY3_PROTO
-)
-
+ PY_PROTO
+ PY3_PROTO
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/testing
-)
-
-GRPC()
-
-SRCS(
- ads_for_test.proto
+
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/testing
+)
+
+GRPC()
+
+SRCS(
+ ads_for_test.proto
cds_for_test.proto
- eds_for_test.proto
+ eds_for_test.proto
lds_rds_for_test.proto
- lrs_for_test.proto
- orca_load_report_for_test.proto
-)
-
-END()
+ lrs_for_test.proto
+ orca_load_report_for_test.proto
+)
+
+END()
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/ya.make b/contrib/libs/grpc/src/proto/grpc/testing/ya.make
index 2704585a37..ee7c496b0d 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/testing/ya.make
@@ -1,49 +1,49 @@
-PROTO_LIBRARY()
-
+PROTO_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- g:contrib
+OWNER(
+ akastornov
+ g:contrib
g:cpp-contrib
-)
-
-EXCLUDE_TAGS(
+)
+
+EXCLUDE_TAGS(
GO_PROTO
- PY_PROTO
- PY3_PROTO
-)
-
+ PY_PROTO
+ PY3_PROTO
+)
+
PROTO_NAMESPACE(
GLOBAL
contrib/libs/grpc
)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/core
-)
-
-GRPC()
-
-SRCS(
- benchmark_service.proto
- compiler_test.proto
- control.proto
- echo.proto
- echo_messages.proto
- empty.proto
- empty_service.proto
- messages.proto
- metrics.proto
- payloads.proto
- proxy-service.proto
- report_qps_scenario_service.proto
- simple_messages.proto
- stats.proto
- test.proto
- worker_service.proto
-)
-
-END()
+
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/core
+)
+
+GRPC()
+
+SRCS(
+ benchmark_service.proto
+ compiler_test.proto
+ control.proto
+ echo.proto
+ echo_messages.proto
+ empty.proto
+ empty_service.proto
+ messages.proto
+ metrics.proto
+ payloads.proto
+ proxy-service.proto
+ report_qps_scenario_service.proto
+ simple_messages.proto
+ stats.proto
+ test.proto
+ worker_service.proto
+)
+
+END()
diff --git a/contrib/libs/grpc/src/python/grpcio/README.rst b/contrib/libs/grpc/src/python/grpcio/README.rst
index fe34ad5adf..9bfec34f6d 100644
--- a/contrib/libs/grpc/src/python/grpcio/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio/README.rst
@@ -1,24 +1,24 @@
gRPC Python
===========
-|compat_check_pypi|
-
+|compat_check_pypi|
+
Package for gRPC Python.
-.. |compat_check_pypi| image:: https://python-compatibility-tools.appspot.com/one_badge_image?package=grpcio
- :target: https://python-compatibility-tools.appspot.com/one_badge_target?package=grpcio
-
-Supported Python Versions
--------------------------
-Python >= 3.5
-
+.. |compat_check_pypi| image:: https://python-compatibility-tools.appspot.com/one_badge_image?package=grpcio
+ :target: https://python-compatibility-tools.appspot.com/one_badge_target?package=grpcio
+
+Supported Python Versions
+-------------------------
+Python >= 3.5
+
Installation
------------
gRPC Python is available for Linux, macOS, and Windows.
-Installing From PyPI
-~~~~~~~~~~~~~~~~~~~~
+Installing From PyPI
+~~~~~~~~~~~~~~~~~~~~
If you are installing locally...
@@ -46,8 +46,8 @@ n.b. On Windows and on Mac OS X one *must* have a recent release of :code:`pip`
to retrieve the proper wheel from PyPI. Be sure to upgrade to the latest
version!
-Installing From Source
-~~~~~~~~~~~~~~~~~~~~~~
+Installing From Source
+~~~~~~~~~~~~~~~~~~~~~~
Building from source requires that you have the Python headers (usually a
package named :code:`python-dev`).
diff --git a/contrib/libs/grpc/src/python/grpcio/commands.py b/contrib/libs/grpc/src/python/grpcio/commands.py
index 8240beb295..dcb2ce5a53 100644
--- a/contrib/libs/grpc/src/python/grpcio/commands.py
+++ b/contrib/libs/grpc/src/python/grpcio/commands.py
@@ -212,43 +212,43 @@ class BuildExt(build_ext.build_ext):
LINK_OPTIONS = {}
def build_extensions(self):
-
- def compiler_ok_with_extra_std():
- """Test if default compiler is okay with specifying c++ version
- when invoked in C mode. GCC is okay with this, while clang is not.
- """
+
+ def compiler_ok_with_extra_std():
+ """Test if default compiler is okay with specifying c++ version
+ when invoked in C mode. GCC is okay with this, while clang is not.
+ """
if platform.system() != 'Windows':
return False
- # TODO(lidiz) Remove the generated a.out for success tests.
+ # TODO(lidiz) Remove the generated a.out for success tests.
cc_test = subprocess.Popen(['cc', '-x', 'c', '-std=c++11', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
- _, cc_err = cc_test.communicate(input=b'int main(){return 0;}')
- return not 'invalid argument' in str(cc_err)
-
+ _, cc_err = cc_test.communicate(input=b'int main(){return 0;}')
+ return not 'invalid argument' in str(cc_err)
+
# This special conditioning is here due to difference of compiler
# behavior in gcc and clang. The clang doesn't take --stdc++11
# flags but gcc does. Since the setuptools of Python only support
# all C or all C++ compilation, the mix of C and C++ will crash.
- # *By default*, macOS and FreBSD use clang and Linux use gcc
- #
- # If we are not using a permissive compiler that's OK with being
- # passed wrong std flags, swap out compile function by adding a filter
- # for it.
- if not compiler_ok_with_extra_std():
- old_compile = self.compiler._compile
-
- def new_compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
- if src[-2:] == '.c':
- extra_postargs = [
- arg for arg in extra_postargs if not '-std=c++' in arg
- ]
- return old_compile(obj, src, ext, cc_args, extra_postargs,
- pp_opts)
-
- self.compiler._compile = new_compile
-
+ # *By default*, macOS and FreBSD use clang and Linux use gcc
+ #
+ # If we are not using a permissive compiler that's OK with being
+ # passed wrong std flags, swap out compile function by adding a filter
+ # for it.
+ if not compiler_ok_with_extra_std():
+ old_compile = self.compiler._compile
+
+ def new_compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
+ if src[-2:] == '.c':
+ extra_postargs = [
+ arg for arg in extra_postargs if not '-std=c++' in arg
+ ]
+ return old_compile(obj, src, ext, cc_args, extra_postargs,
+ pp_opts)
+
+ self.compiler._compile = new_compile
+
compiler = self.compiler.compiler_type
if compiler in BuildExt.C_OPTIONS:
for extension in self.extensions:
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py
index abe87458c4..62205cd0ad 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py
@@ -14,14 +14,14 @@
"""gRPC's Python API."""
import abc
-import contextlib
+import contextlib
import enum
import logging
import sys
import six
from grpc._cython import cygrpc as _cygrpc
-from grpc import _compression
+from grpc import _compression
logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -192,9 +192,9 @@ class Future(six.with_metaclass(abc.ABCMeta)):
If the computation has already completed, the callback will be called
immediately.
- Exceptions raised in the callback will be logged at ERROR level, but
- will not terminate any threads of execution.
-
+ Exceptions raised in the callback will be logged at ERROR level, but
+ will not terminate any threads of execution.
+
Args:
fn: A callable taking this Future object as its single parameter.
"""
@@ -286,7 +286,7 @@ class Status(six.with_metaclass(abc.ABCMeta)):
Attributes:
code: A StatusCode object to be sent to the client.
- details: A UTF-8-encodable string to be sent to the client upon
+ details: A UTF-8-encodable string to be sent to the client upon
termination of the RPC.
trailing_metadata: The trailing :term:`metadata` in the RPC.
"""
@@ -342,7 +342,7 @@ class RpcContext(six.with_metaclass(abc.ABCMeta)):
callback: A no-parameter callable to be called on RPC termination.
Returns:
- True if the callback was added and will be called later; False if
+ True if the callback was added and will be called later; False if
the callback was not added and will not be called (because the RPC
already terminated or some other reason).
"""
@@ -416,8 +416,8 @@ class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
credentials: An optional CallCredentials for the RPC.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
"""
@@ -586,9 +586,9 @@ class ChannelCredentials(object):
class CallCredentials(object):
"""An encapsulation of the data required to assert an identity over a call.
- A CallCredentials has to be used with secure Channel, otherwise the
- metadata will not be transmitted to the server.
-
+ A CallCredentials has to be used with secure Channel, otherwise the
+ metadata will not be transmitted to the server.
+
A CallCredentials may be composed with ChannelCredentials to always assert
identity for every call over that Channel.
@@ -677,8 +677,8 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Synchronously invokes the underlying RPC.
Args:
@@ -687,12 +687,12 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
for the RPC.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
The response value for the RPC.
@@ -710,8 +710,8 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Synchronously invokes the underlying RPC.
Args:
@@ -720,12 +720,12 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
The response value for the RPC and a Call value for the RPC.
@@ -743,8 +743,8 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Asynchronously invokes the underlying RPC.
Args:
@@ -753,12 +753,12 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
An object that is both a Call for the RPC and a Future.
@@ -779,8 +779,8 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Invokes the underlying RPC.
Args:
@@ -789,12 +789,12 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC. If None, the timeout is considered infinite.
metadata: An optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
An object that is both a Call for the RPC and an iterator of
@@ -814,8 +814,8 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Synchronously invokes the underlying RPC.
Args:
@@ -825,12 +825,12 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC. If None, the timeout is considered infinite.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
The response value for the RPC.
@@ -848,8 +848,8 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Synchronously invokes the underlying RPC on the client.
Args:
@@ -859,12 +859,12 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC. If None, the timeout is considered infinite.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
The response value for the RPC and a Call object for the RPC.
@@ -882,8 +882,8 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Asynchronously invokes the underlying RPC on the client.
Args:
@@ -892,12 +892,12 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC. If None, the timeout is considered infinite.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
An object that is both a Call for the RPC and a Future.
@@ -918,8 +918,8 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
"""Invokes the underlying RPC on the client.
Args:
@@ -928,12 +928,12 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
the RPC. If not specified, the timeout is considered infinite.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
- credentials: An optional CallCredentials for the RPC. Only valid for
- secure Channel.
+ credentials: An optional CallCredentials for the RPC. Only valid for
+ secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
An object that is both a Call for the RPC and an iterator of
@@ -1145,17 +1145,17 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
"""
raise NotImplementedError()
- def set_compression(self, compression):
- """Set the compression algorithm to be used for the entire call.
-
- This is an EXPERIMENTAL method.
-
- Args:
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip.
- """
- raise NotImplementedError()
-
+ def set_compression(self, compression):
+ """Set the compression algorithm to be used for the entire call.
+
+ This is an EXPERIMENTAL method.
+
+ Args:
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip.
+ """
+ raise NotImplementedError()
+
@abc.abstractmethod
def send_initial_metadata(self, initial_metadata):
"""Sends the initial metadata value to the client.
@@ -1196,7 +1196,7 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
Args:
code: A StatusCode object to be sent to the client.
It must not be StatusCode.OK.
- details: A UTF-8-encodable string to be sent to the client upon
+ details: A UTF-8-encodable string to be sent to the client upon
termination of the RPC.
Raises:
@@ -1244,22 +1244,22 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
no details to transmit.
Args:
- details: A UTF-8-encodable string to be sent to the client upon
+ details: A UTF-8-encodable string to be sent to the client upon
termination of the RPC.
"""
raise NotImplementedError()
- def disable_next_message_compression(self):
- """Disables compression for the next response message.
-
- This is an EXPERIMENTAL method.
-
- This method will override any compression configuration set during
- server creation or set on the call.
- """
- raise NotImplementedError()
-
-
+ def disable_next_message_compression(self):
+ """Disables compression for the next response message.
+
+ This is an EXPERIMENTAL method.
+
+ This method will override any compression configuration set during
+ server creation or set on the call.
+ """
+ raise NotImplementedError()
+
+
##################### Service-Side Handler Interfaces ########################
@@ -1301,7 +1301,7 @@ class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
"""Describes an RPC that has just arrived for service.
-
+
Attributes:
method: The method name of the RPC.
invocation_metadata: The :term:`metadata` sent by the client.
@@ -1398,8 +1398,8 @@ class Server(six.with_metaclass(abc.ABCMeta)):
This method may only be called before starting the server.
Args:
- address: The address for which to open a port. If the port is 0,
- or not specified in the address, then gRPC runtime will choose a port.
+ address: The address for which to open a port. If the port is 0,
+ or not specified in the address, then gRPC runtime will choose a port.
Returns:
An integer port on which server will accept RPC requests.
@@ -1461,30 +1461,30 @@ class Server(six.with_metaclass(abc.ABCMeta)):
"""
raise NotImplementedError()
- def wait_for_termination(self, timeout=None):
- """Block current thread until the server stops.
-
- This is an EXPERIMENTAL API.
-
- The wait will not consume computational resources during blocking, and
- it will block until one of the two following conditions are met:
-
- 1) The server is stopped or terminated;
- 2) A timeout occurs if timeout is not `None`.
-
- The timeout argument works in the same way as `threading.Event.wait()`.
+ def wait_for_termination(self, timeout=None):
+ """Block current thread until the server stops.
+
+ This is an EXPERIMENTAL API.
+
+ The wait will not consume computational resources during blocking, and
+ it will block until one of the two following conditions are met:
+
+ 1) The server is stopped or terminated;
+ 2) A timeout occurs if timeout is not `None`.
+
+ The timeout argument works in the same way as `threading.Event.wait()`.
https://docs.python.org/3/library/threading.html#threading.Event.wait
-
- Args:
- timeout: A floating point number specifying a timeout for the
- operation in seconds.
-
- Returns:
- A bool indicates if the operation times out.
- """
- raise NotImplementedError()
-
-
+
+ Args:
+ timeout: A floating point number specifying a timeout for the
+ operation in seconds.
+
+ Returns:
+ A bool indicates if the operation times out.
+ """
+ raise NotImplementedError()
+
+
################################# Functions ################################
@@ -1761,78 +1761,78 @@ def dynamic_ssl_server_credentials(initial_certificate_configuration,
certificate_configuration_fetcher, require_client_authentication))
-@enum.unique
-class LocalConnectionType(enum.Enum):
- """Types of local connection for local credential creation.
-
- Attributes:
- UDS: Unix domain socket connections
- LOCAL_TCP: Local TCP connections.
- """
- UDS = _cygrpc.LocalConnectionType.uds
- LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
-
-
-def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
- """Creates a local ChannelCredentials used for local connections.
-
- This is an EXPERIMENTAL API.
-
- Local credentials are used by local TCP endpoints (e.g. localhost:10000)
- also UDS connections.
-
- The connections created by local channel credentials are not
- encrypted, but will be checked if they are local or not.
- The UDS connections are considered secure by providing peer authentication
- and data confidentiality while TCP connections are considered insecure.
-
- It is allowed to transmit call credentials over connections created by
- local channel credentials.
-
- Local channel credentials are useful for 1) eliminating insecure_channel usage;
- 2) enable unit testing for call credentials without setting up secrets.
-
- Args:
- local_connect_type: Local connection type (either
- grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
-
- Returns:
- A ChannelCredentials for use with a local Channel
- """
- return ChannelCredentials(
- _cygrpc.channel_credentials_local(local_connect_type.value))
-
-
-def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
- """Creates a local ServerCredentials used for local connections.
-
- This is an EXPERIMENTAL API.
-
- Local credentials are used by local TCP endpoints (e.g. localhost:10000)
- also UDS connections.
-
- The connections created by local server credentials are not
- encrypted, but will be checked if they are local or not.
- The UDS connections are considered secure by providing peer authentication
- and data confidentiality while TCP connections are considered insecure.
-
- It is allowed to transmit call credentials over connections created by local
- server credentials.
-
- Local server credentials are useful for 1) eliminating insecure_channel usage;
- 2) enable unit testing for call credentials without setting up secrets.
-
- Args:
- local_connect_type: Local connection type (either
- grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
-
- Returns:
- A ServerCredentials for use with a local Server
- """
- return ServerCredentials(
- _cygrpc.server_credentials_local(local_connect_type.value))
-
-
+@enum.unique
+class LocalConnectionType(enum.Enum):
+ """Types of local connection for local credential creation.
+
+ Attributes:
+ UDS: Unix domain socket connections
+ LOCAL_TCP: Local TCP connections.
+ """
+ UDS = _cygrpc.LocalConnectionType.uds
+ LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
+
+
+def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
+ """Creates a local ChannelCredentials used for local connections.
+
+ This is an EXPERIMENTAL API.
+
+ Local credentials are used by local TCP endpoints (e.g. localhost:10000)
+ also UDS connections.
+
+ The connections created by local channel credentials are not
+ encrypted, but will be checked if they are local or not.
+ The UDS connections are considered secure by providing peer authentication
+ and data confidentiality while TCP connections are considered insecure.
+
+ It is allowed to transmit call credentials over connections created by
+ local channel credentials.
+
+ Local channel credentials are useful for 1) eliminating insecure_channel usage;
+ 2) enable unit testing for call credentials without setting up secrets.
+
+ Args:
+ local_connect_type: Local connection type (either
+ grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
+
+ Returns:
+ A ChannelCredentials for use with a local Channel
+ """
+ return ChannelCredentials(
+ _cygrpc.channel_credentials_local(local_connect_type.value))
+
+
+def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
+ """Creates a local ServerCredentials used for local connections.
+
+ This is an EXPERIMENTAL API.
+
+ Local credentials are used by local TCP endpoints (e.g. localhost:10000)
+ also UDS connections.
+
+ The connections created by local server credentials are not
+ encrypted, but will be checked if they are local or not.
+ The UDS connections are considered secure by providing peer authentication
+ and data confidentiality while TCP connections are considered insecure.
+
+ It is allowed to transmit call credentials over connections created by local
+ server credentials.
+
+ Local server credentials are useful for 1) eliminating insecure_channel usage;
+ 2) enable unit testing for call credentials without setting up secrets.
+
+ Args:
+ local_connect_type: Local connection type (either
+ grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
+
+ Returns:
+ A ServerCredentials for use with a local Server
+ """
+ return ServerCredentials(
+ _cygrpc.server_credentials_local(local_connect_type.value))
+
+
def alts_channel_credentials(service_accounts=None):
"""Creates a ChannelCredentials for use with an ALTS-enabled Channel.
@@ -1902,7 +1902,7 @@ def channel_ready_future(channel):
return _utilities.channel_ready_future(channel)
-def insecure_channel(target, options=None, compression=None):
+def insecure_channel(target, options=None, compression=None):
"""Creates an insecure Channel to a server.
The returned Channel is thread-safe.
@@ -1911,8 +1911,8 @@ def insecure_channel(target, options=None, compression=None):
target: The server address
options: An optional list of key-value pairs (:term:`channel_arguments`
in gRPC Core runtime) to configure the channel.
- compression: An optional value indicating the compression method to be
- used over the lifetime of the channel. This is an EXPERIMENTAL option.
+ compression: An optional value indicating the compression method to be
+ used over the lifetime of the channel. This is an EXPERIMENTAL option.
Returns:
A Channel.
@@ -1922,7 +1922,7 @@ def insecure_channel(target, options=None, compression=None):
compression)
-def secure_channel(target, credentials, options=None, compression=None):
+def secure_channel(target, credentials, options=None, compression=None):
"""Creates a secure Channel to a server.
The returned Channel is thread-safe.
@@ -1932,8 +1932,8 @@ def secure_channel(target, credentials, options=None, compression=None):
credentials: A ChannelCredentials instance.
options: An optional list of key-value pairs (:term:`channel_arguments`
in gRPC Core runtime) to configure the channel.
- compression: An optional value indicating the compression method to be
- used over the lifetime of the channel. This is an EXPERIMENTAL option.
+ compression: An optional value indicating the compression method to be
+ used over the lifetime of the channel. This is an EXPERIMENTAL option.
Returns:
A Channel.
@@ -1945,7 +1945,7 @@ def secure_channel(target, credentials, options=None, compression=None):
"secure_channel cannot be called with insecure credentials." +
" Call insecure_channel instead.")
return _channel.Channel(target, () if options is None else options,
- credentials._credentials, compression)
+ credentials._credentials, compression)
def intercept_channel(channel, *interceptors):
@@ -1980,8 +1980,8 @@ def server(thread_pool,
handlers=None,
interceptors=None,
options=None,
- maximum_concurrent_rpcs=None,
- compression=None):
+ maximum_concurrent_rpcs=None,
+ compression=None):
"""Creates a Server with which RPCs can be serviced.
Args:
@@ -1999,9 +1999,9 @@ def server(thread_pool,
maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
will service before returning RESOURCE_EXHAUSTED status, or None to
indicate no limit.
- compression: An element of grpc.compression, e.g.
- grpc.compression.Gzip. This compression algorithm will be used for the
- lifetime of the server unless overridden. This is an EXPERIMENTAL option.
+ compression: An element of grpc.compression, e.g.
+ grpc.compression.Gzip. This compression algorithm will be used for the
+ lifetime of the server unless overridden. This is an EXPERIMENTAL option.
Returns:
A Server object.
@@ -2011,33 +2011,33 @@ def server(thread_pool,
() if handlers is None else handlers,
() if interceptors is None else interceptors,
() if options is None else options,
- maximum_concurrent_rpcs, compression)
-
-
-@contextlib.contextmanager
-def _create_servicer_context(rpc_event, state, request_deserializer):
- from grpc import _server # pylint: disable=cyclic-import
- context = _server._Context(rpc_event, state, request_deserializer)
- yield context
- context._finalize_state() # pylint: disable=protected-access
-
-
-@enum.unique
-class Compression(enum.IntEnum):
- """Indicates the compression method to be used for an RPC.
-
- This enumeration is part of an EXPERIMENTAL API.
-
- Attributes:
- NoCompression: Do not use compression algorithm.
- Deflate: Use "Deflate" compression algorithm.
- Gzip: Use "Gzip" compression algorithm.
- """
- NoCompression = _compression.NoCompression
- Deflate = _compression.Deflate
- Gzip = _compression.Gzip
-
-
+ maximum_concurrent_rpcs, compression)
+
+
+@contextlib.contextmanager
+def _create_servicer_context(rpc_event, state, request_deserializer):
+ from grpc import _server # pylint: disable=cyclic-import
+ context = _server._Context(rpc_event, state, request_deserializer)
+ yield context
+ context._finalize_state() # pylint: disable=protected-access
+
+
+@enum.unique
+class Compression(enum.IntEnum):
+ """Indicates the compression method to be used for an RPC.
+
+ This enumeration is part of an EXPERIMENTAL API.
+
+ Attributes:
+ NoCompression: Do not use compression algorithm.
+ Deflate: Use "Deflate" compression algorithm.
+ Gzip: Use "Gzip" compression algorithm.
+ """
+ NoCompression = _compression.NoCompression
+ Deflate = _compression.Deflate
+ Gzip = _compression.Gzip
+
+
from grpc._runtime_protos import protos, services, protos_and_services # pylint: disable=wrong-import-position
################################### __all__ #################################
@@ -2057,11 +2057,11 @@ __all__ = (
'AuthMetadataContext',
'AuthMetadataPluginCallback',
'AuthMetadataPlugin',
- 'Compression',
+ 'Compression',
'ClientCallDetails',
'ServerCertificateConfiguration',
'ServerCredentials',
- 'LocalConnectionType',
+ 'LocalConnectionType',
'UnaryUnaryMultiCallable',
'UnaryStreamMultiCallable',
'StreamUnaryMultiCallable',
@@ -2088,8 +2088,8 @@ __all__ = (
'access_token_call_credentials',
'composite_call_credentials',
'composite_channel_credentials',
- 'local_channel_credentials',
- 'local_server_credentials',
+ 'local_channel_credentials',
+ 'local_server_credentials',
'alts_channel_credentials',
'alts_server_credentials',
'ssl_server_credentials',
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py b/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py
index 11921d7883..f8ffb7eb2a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py
@@ -13,17 +13,17 @@
# limitations under the License.
"""Invocation-side implementation of gRPC Python."""
-import copy
-import functools
+import copy
+import functools
import logging
-import os
+import os
import sys
import threading
import time
import grpc
-import grpc.experimental
-from grpc import _compression
+import grpc.experimental
+from grpc import _compression
from grpc import _common
from grpc import _grpcio_metadata
from grpc._cython import cygrpc
@@ -34,11 +34,11 @@ _USER_AGENT = 'grpc-python/{}'.format(_grpcio_metadata.__version__)
_EMPTY_FLAGS = 0
-# NOTE(rbellevi): No guarantees are given about the maintenance of this
-# environment variable.
-_DEFAULT_SINGLE_THREADED_UNARY_STREAM = os.getenv(
- "GRPC_SINGLE_THREADED_UNARY_STREAM") is not None
-
+# NOTE(rbellevi): No guarantees are given about the maintenance of this
+# environment variable.
+_DEFAULT_SINGLE_THREADED_UNARY_STREAM = os.getenv(
+ "GRPC_SINGLE_THREADED_UNARY_STREAM") is not None
+
_UNARY_UNARY_INITIAL_DUE = (
cygrpc.OperationType.send_initial_metadata,
cygrpc.OperationType.send_message,
@@ -69,12 +69,12 @@ _STREAM_STREAM_INITIAL_DUE = (
_CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = (
'Exception calling channel subscription callback!')
-_OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n'
+_OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n'
'\tstatus = {}\n'
'\tdetails = "{}"\n'
'>')
-_NON_OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n'
+_NON_OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n'
'\tstatus = {}\n'
'\tdetails = "{}"\n'
'\tdebug_error_string = "{}"\n'
@@ -167,11 +167,11 @@ def _event_handler(state, response_deserializer):
state.condition.notify_all()
done = not state.due
for callback in callbacks:
- try:
- callback()
- except Exception as e: # pylint: disable=broad-except
- # NOTE(rbellevi): We suppress but log errors here so as not to
- # kill the channel spin thread.
+ try:
+ callback()
+ except Exception as e: # pylint: disable=broad-except
+ # NOTE(rbellevi): We suppress but log errors here so as not to
+ # kill the channel spin thread.
logging.error('Exception in callback %s: %s',
repr(callback.func), repr(e))
return done and state.fork_epoch >= cygrpc.get_fork_epoch()
@@ -182,11 +182,11 @@ def _event_handler(state, response_deserializer):
#pylint: disable=too-many-statements
def _consume_request_iterator(request_iterator, state, call, request_serializer,
event_handler):
- """Consume a request iterator supplied by the user."""
+ """Consume a request iterator supplied by the user."""
def consume_request_iterator(): # pylint: disable=too-many-branches
- # Iterate over the request iterator until it is exhausted or an error
- # condition is encountered.
+ # Iterate over the request iterator until it is exhausted or an error
+ # condition is encountered.
while True:
return_from_user_request_generator_invoked = False
try:
@@ -227,19 +227,19 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer,
state.due.add(cygrpc.OperationType.send_message)
else:
return
-
- def _done():
- return (state.code is not None or
- cygrpc.OperationType.send_message not in
- state.due)
-
+
+ def _done():
+ return (state.code is not None or
+ cygrpc.OperationType.send_message not in
+ state.due)
+
_common.wait(state.condition.wait,
_done,
spin_cb=functools.partial(
cygrpc.block_if_fork_in_progress,
state))
- if state.code is not None:
- return
+ if state.code is not None:
+ return
else:
return
with state.condition:
@@ -256,112 +256,112 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer,
consumption_thread.start()
-def _rpc_state_string(class_name, rpc_state):
- """Calculates error string for RPC."""
- with rpc_state.condition:
- if rpc_state.code is None:
- return '<{} object>'.format(class_name)
- elif rpc_state.code is grpc.StatusCode.OK:
- return _OK_RENDEZVOUS_REPR_FORMAT.format(class_name, rpc_state.code,
- rpc_state.details)
- else:
- return _NON_OK_RENDEZVOUS_REPR_FORMAT.format(
- class_name, rpc_state.code, rpc_state.details,
- rpc_state.debug_error_string)
-
-
-class _InactiveRpcError(grpc.RpcError, grpc.Call, grpc.Future):
- """An RPC error not tied to the execution of a particular RPC.
-
- The RPC represented by the state object must not be in-progress or
- cancelled.
-
- Attributes:
- _state: An instance of _RPCState.
- """
-
- def __init__(self, state):
- with state.condition:
- self._state = _RPCState((), copy.deepcopy(state.initial_metadata),
- copy.deepcopy(state.trailing_metadata),
- state.code, copy.deepcopy(state.details))
- self._state.response = copy.copy(state.response)
- self._state.debug_error_string = copy.copy(state.debug_error_string)
-
- def initial_metadata(self):
- return self._state.initial_metadata
-
- def trailing_metadata(self):
- return self._state.trailing_metadata
-
- def code(self):
- return self._state.code
-
- def details(self):
- return _common.decode(self._state.details)
-
- def debug_error_string(self):
- return _common.decode(self._state.debug_error_string)
-
- def _repr(self):
- return _rpc_state_string(self.__class__.__name__, self._state)
-
- def __repr__(self):
- return self._repr()
-
- def __str__(self):
- return self._repr()
-
- def cancel(self):
- """See grpc.Future.cancel."""
- return False
-
- def cancelled(self):
- """See grpc.Future.cancelled."""
- return False
-
- def running(self):
- """See grpc.Future.running."""
- return False
-
- def done(self):
- """See grpc.Future.done."""
- return True
-
- def result(self, timeout=None): # pylint: disable=unused-argument
- """See grpc.Future.result."""
- raise self
-
- def exception(self, timeout=None): # pylint: disable=unused-argument
- """See grpc.Future.exception."""
- return self
-
- def traceback(self, timeout=None): # pylint: disable=unused-argument
- """See grpc.Future.traceback."""
- try:
- raise self
- except grpc.RpcError:
- return sys.exc_info()[2]
-
- def add_done_callback(self, fn, timeout=None): # pylint: disable=unused-argument
- """See grpc.Future.add_done_callback."""
- fn(self)
-
-
-class _Rendezvous(grpc.RpcError, grpc.RpcContext):
- """An RPC iterator.
-
- Attributes:
- _state: An instance of _RPCState.
- _call: An instance of SegregatedCall or IntegratedCall.
- In either case, the _call object is expected to have operate, cancel,
- and next_event methods.
- _response_deserializer: A callable taking bytes and return a Python
- object.
- _deadline: A float representing the deadline of the RPC in seconds. Or
- possibly None, to represent an RPC with no deadline at all.
- """
-
+def _rpc_state_string(class_name, rpc_state):
+ """Calculates error string for RPC."""
+ with rpc_state.condition:
+ if rpc_state.code is None:
+ return '<{} object>'.format(class_name)
+ elif rpc_state.code is grpc.StatusCode.OK:
+ return _OK_RENDEZVOUS_REPR_FORMAT.format(class_name, rpc_state.code,
+ rpc_state.details)
+ else:
+ return _NON_OK_RENDEZVOUS_REPR_FORMAT.format(
+ class_name, rpc_state.code, rpc_state.details,
+ rpc_state.debug_error_string)
+
+
+class _InactiveRpcError(grpc.RpcError, grpc.Call, grpc.Future):
+ """An RPC error not tied to the execution of a particular RPC.
+
+ The RPC represented by the state object must not be in-progress or
+ cancelled.
+
+ Attributes:
+ _state: An instance of _RPCState.
+ """
+
+ def __init__(self, state):
+ with state.condition:
+ self._state = _RPCState((), copy.deepcopy(state.initial_metadata),
+ copy.deepcopy(state.trailing_metadata),
+ state.code, copy.deepcopy(state.details))
+ self._state.response = copy.copy(state.response)
+ self._state.debug_error_string = copy.copy(state.debug_error_string)
+
+ def initial_metadata(self):
+ return self._state.initial_metadata
+
+ def trailing_metadata(self):
+ return self._state.trailing_metadata
+
+ def code(self):
+ return self._state.code
+
+ def details(self):
+ return _common.decode(self._state.details)
+
+ def debug_error_string(self):
+ return _common.decode(self._state.debug_error_string)
+
+ def _repr(self):
+ return _rpc_state_string(self.__class__.__name__, self._state)
+
+ def __repr__(self):
+ return self._repr()
+
+ def __str__(self):
+ return self._repr()
+
+ def cancel(self):
+ """See grpc.Future.cancel."""
+ return False
+
+ def cancelled(self):
+ """See grpc.Future.cancelled."""
+ return False
+
+ def running(self):
+ """See grpc.Future.running."""
+ return False
+
+ def done(self):
+ """See grpc.Future.done."""
+ return True
+
+ def result(self, timeout=None): # pylint: disable=unused-argument
+ """See grpc.Future.result."""
+ raise self
+
+ def exception(self, timeout=None): # pylint: disable=unused-argument
+ """See grpc.Future.exception."""
+ return self
+
+ def traceback(self, timeout=None): # pylint: disable=unused-argument
+ """See grpc.Future.traceback."""
+ try:
+ raise self
+ except grpc.RpcError:
+ return sys.exc_info()[2]
+
+ def add_done_callback(self, fn, timeout=None): # pylint: disable=unused-argument
+ """See grpc.Future.add_done_callback."""
+ fn(self)
+
+
+class _Rendezvous(grpc.RpcError, grpc.RpcContext):
+ """An RPC iterator.
+
+ Attributes:
+ _state: An instance of _RPCState.
+ _call: An instance of SegregatedCall or IntegratedCall.
+ In either case, the _call object is expected to have operate, cancel,
+ and next_event methods.
+ _response_deserializer: A callable taking bytes and return a Python
+ object.
+ _deadline: A float representing the deadline of the RPC in seconds. Or
+ possibly None, to represent an RPC with no deadline at all.
+ """
+
def __init__(self, state, call, response_deserializer, deadline):
super(_Rendezvous, self).__init__()
self._state = state
@@ -369,21 +369,21 @@ class _Rendezvous(grpc.RpcError, grpc.RpcContext):
self._response_deserializer = response_deserializer
self._deadline = deadline
- def is_active(self):
- """See grpc.RpcContext.is_active"""
- with self._state.condition:
- return self._state.code is None
-
- def time_remaining(self):
- """See grpc.RpcContext.time_remaining"""
- with self._state.condition:
- if self._deadline is None:
- return None
- else:
- return max(self._deadline - time.time(), 0)
-
+ def is_active(self):
+ """See grpc.RpcContext.is_active"""
+ with self._state.condition:
+ return self._state.code is None
+
+ def time_remaining(self):
+ """See grpc.RpcContext.time_remaining"""
+ with self._state.condition:
+ if self._deadline is None:
+ return None
+ else:
+ return max(self._deadline - time.time(), 0)
+
def cancel(self):
- """See grpc.RpcContext.cancel"""
+ """See grpc.RpcContext.cancel"""
with self._state.condition:
if self._state.code is None:
code = grpc.StatusCode.CANCELLED
@@ -393,69 +393,69 @@ class _Rendezvous(grpc.RpcError, grpc.RpcContext):
self._state.cancelled = True
_abort(self._state, code, details)
self._state.condition.notify_all()
- return True
- else:
- return False
-
- def add_callback(self, callback):
- """See grpc.RpcContext.add_callback"""
- with self._state.condition:
- if self._state.callbacks is None:
- return False
- else:
- self._state.callbacks.append(callback)
- return True
-
- def __iter__(self):
- return self
-
- def next(self):
- return self._next()
-
- def __next__(self):
- return self._next()
-
- def _next(self):
- raise NotImplementedError()
-
- def debug_error_string(self):
- raise NotImplementedError()
-
- def _repr(self):
- return _rpc_state_string(self.__class__.__name__, self._state)
-
- def __repr__(self):
- return self._repr()
-
- def __str__(self):
- return self._repr()
-
- def __del__(self):
- with self._state.condition:
- if self._state.code is None:
- self._state.code = grpc.StatusCode.CANCELLED
- self._state.details = 'Cancelled upon garbage collection!'
- self._state.cancelled = True
- self._call.cancel(
- _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[self._state.code],
- self._state.details)
- self._state.condition.notify_all()
-
-
+ return True
+ else:
+ return False
+
+ def add_callback(self, callback):
+ """See grpc.RpcContext.add_callback"""
+ with self._state.condition:
+ if self._state.callbacks is None:
+ return False
+ else:
+ self._state.callbacks.append(callback)
+ return True
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ return self._next()
+
+ def __next__(self):
+ return self._next()
+
+ def _next(self):
+ raise NotImplementedError()
+
+ def debug_error_string(self):
+ raise NotImplementedError()
+
+ def _repr(self):
+ return _rpc_state_string(self.__class__.__name__, self._state)
+
+ def __repr__(self):
+ return self._repr()
+
+ def __str__(self):
+ return self._repr()
+
+ def __del__(self):
+ with self._state.condition:
+ if self._state.code is None:
+ self._state.code = grpc.StatusCode.CANCELLED
+ self._state.details = 'Cancelled upon garbage collection!'
+ self._state.cancelled = True
+ self._call.cancel(
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[self._state.code],
+ self._state.details)
+ self._state.condition.notify_all()
+
+
class _SingleThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint: disable=too-many-ancestors
- """An RPC iterator operating entirely on a single thread.
-
- The __next__ method of _SingleThreadedRendezvous does not depend on the
- existence of any other thread, including the "channel spin thread".
- However, this means that its interface is entirely synchronous. So this
+ """An RPC iterator operating entirely on a single thread.
+
+ The __next__ method of _SingleThreadedRendezvous does not depend on the
+ existence of any other thread, including the "channel spin thread".
+ However, this means that its interface is entirely synchronous. So this
class cannot completely fulfill the grpc.Future interface. The result,
exception, and traceback methods will never block and will instead raise
an exception if calling the method would result in blocking.
This means that these methods are safe to call from add_done_callback
handlers.
- """
-
+ """
+
def _is_complete(self):
return self._state.code is not None
@@ -548,145 +548,145 @@ class _SingleThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
fn(self)
- def initial_metadata(self):
- """See grpc.Call.initial_metadata"""
- with self._state.condition:
- # NOTE(gnossen): Based on our initial call batch, we are guaranteed
- # to receive initial metadata before any messages.
- while self._state.initial_metadata is None:
- self._consume_next_event()
- return self._state.initial_metadata
-
- def trailing_metadata(self):
- """See grpc.Call.trailing_metadata"""
- with self._state.condition:
- if self._state.trailing_metadata is None:
- raise grpc.experimental.UsageError(
- "Cannot get trailing metadata until RPC is completed.")
- return self._state.trailing_metadata
-
- def code(self):
- """See grpc.Call.code"""
- with self._state.condition:
- if self._state.code is None:
- raise grpc.experimental.UsageError(
- "Cannot get code until RPC is completed.")
- return self._state.code
-
- def details(self):
- """See grpc.Call.details"""
- with self._state.condition:
- if self._state.details is None:
- raise grpc.experimental.UsageError(
- "Cannot get details until RPC is completed.")
- return _common.decode(self._state.details)
-
- def _consume_next_event(self):
- event = self._call.next_event()
- with self._state.condition:
- callbacks = _handle_event(event, self._state,
- self._response_deserializer)
- for callback in callbacks:
- # NOTE(gnossen): We intentionally allow exceptions to bubble up
- # to the user when running on a single thread.
- callback()
- return event
-
- def _next_response(self):
- while True:
- self._consume_next_event()
- with self._state.condition:
- if self._state.response is not None:
- response = self._state.response
- self._state.response = None
- return response
- elif cygrpc.OperationType.receive_message not in self._state.due:
- if self._state.code is grpc.StatusCode.OK:
- raise StopIteration()
- elif self._state.code is not None:
- raise self
-
- def _next(self):
- with self._state.condition:
- if self._state.code is None:
- operating = self._call.operate(
- (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), None)
- if operating:
- self._state.due.add(cygrpc.OperationType.receive_message)
- elif self._state.code is grpc.StatusCode.OK:
- raise StopIteration()
- else:
- raise self
- return self._next_response()
-
- def debug_error_string(self):
- with self._state.condition:
- if self._state.debug_error_string is None:
- raise grpc.experimental.UsageError(
- "Cannot get debug error string until RPC is completed.")
- return _common.decode(self._state.debug_error_string)
-
-
-class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint: disable=too-many-ancestors
- """An RPC iterator that depends on a channel spin thread.
-
- This iterator relies upon a per-channel thread running in the background,
- dequeueing events from the completion queue, and notifying threads waiting
- on the threading.Condition object in the _RPCState object.
-
- This extra thread allows _MultiThreadedRendezvous to fulfill the grpc.Future interface
- and to mediate a bidirection streaming RPC.
- """
-
- def initial_metadata(self):
- """See grpc.Call.initial_metadata"""
- with self._state.condition:
-
- def _done():
- return self._state.initial_metadata is not None
-
- _common.wait(self._state.condition.wait, _done)
- return self._state.initial_metadata
-
- def trailing_metadata(self):
- """See grpc.Call.trailing_metadata"""
- with self._state.condition:
-
- def _done():
- return self._state.trailing_metadata is not None
-
- _common.wait(self._state.condition.wait, _done)
- return self._state.trailing_metadata
-
- def code(self):
- """See grpc.Call.code"""
- with self._state.condition:
-
- def _done():
- return self._state.code is not None
-
- _common.wait(self._state.condition.wait, _done)
- return self._state.code
-
- def details(self):
- """See grpc.Call.details"""
- with self._state.condition:
-
- def _done():
- return self._state.details is not None
-
- _common.wait(self._state.condition.wait, _done)
- return _common.decode(self._state.details)
-
- def debug_error_string(self):
- with self._state.condition:
-
- def _done():
- return self._state.debug_error_string is not None
-
- _common.wait(self._state.condition.wait, _done)
- return _common.decode(self._state.debug_error_string)
-
+ def initial_metadata(self):
+ """See grpc.Call.initial_metadata"""
+ with self._state.condition:
+ # NOTE(gnossen): Based on our initial call batch, we are guaranteed
+ # to receive initial metadata before any messages.
+ while self._state.initial_metadata is None:
+ self._consume_next_event()
+ return self._state.initial_metadata
+
+ def trailing_metadata(self):
+ """See grpc.Call.trailing_metadata"""
+ with self._state.condition:
+ if self._state.trailing_metadata is None:
+ raise grpc.experimental.UsageError(
+ "Cannot get trailing metadata until RPC is completed.")
+ return self._state.trailing_metadata
+
+ def code(self):
+ """See grpc.Call.code"""
+ with self._state.condition:
+ if self._state.code is None:
+ raise grpc.experimental.UsageError(
+ "Cannot get code until RPC is completed.")
+ return self._state.code
+
+ def details(self):
+ """See grpc.Call.details"""
+ with self._state.condition:
+ if self._state.details is None:
+ raise grpc.experimental.UsageError(
+ "Cannot get details until RPC is completed.")
+ return _common.decode(self._state.details)
+
+ def _consume_next_event(self):
+ event = self._call.next_event()
+ with self._state.condition:
+ callbacks = _handle_event(event, self._state,
+ self._response_deserializer)
+ for callback in callbacks:
+ # NOTE(gnossen): We intentionally allow exceptions to bubble up
+ # to the user when running on a single thread.
+ callback()
+ return event
+
+ def _next_response(self):
+ while True:
+ self._consume_next_event()
+ with self._state.condition:
+ if self._state.response is not None:
+ response = self._state.response
+ self._state.response = None
+ return response
+ elif cygrpc.OperationType.receive_message not in self._state.due:
+ if self._state.code is grpc.StatusCode.OK:
+ raise StopIteration()
+ elif self._state.code is not None:
+ raise self
+
+ def _next(self):
+ with self._state.condition:
+ if self._state.code is None:
+ operating = self._call.operate(
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), None)
+ if operating:
+ self._state.due.add(cygrpc.OperationType.receive_message)
+ elif self._state.code is grpc.StatusCode.OK:
+ raise StopIteration()
+ else:
+ raise self
+ return self._next_response()
+
+ def debug_error_string(self):
+ with self._state.condition:
+ if self._state.debug_error_string is None:
+ raise grpc.experimental.UsageError(
+ "Cannot get debug error string until RPC is completed.")
+ return _common.decode(self._state.debug_error_string)
+
+
+class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint: disable=too-many-ancestors
+ """An RPC iterator that depends on a channel spin thread.
+
+ This iterator relies upon a per-channel thread running in the background,
+ dequeueing events from the completion queue, and notifying threads waiting
+ on the threading.Condition object in the _RPCState object.
+
+ This extra thread allows _MultiThreadedRendezvous to fulfill the grpc.Future interface
+ and to mediate a bidirection streaming RPC.
+ """
+
+ def initial_metadata(self):
+ """See grpc.Call.initial_metadata"""
+ with self._state.condition:
+
+ def _done():
+ return self._state.initial_metadata is not None
+
+ _common.wait(self._state.condition.wait, _done)
+ return self._state.initial_metadata
+
+ def trailing_metadata(self):
+ """See grpc.Call.trailing_metadata"""
+ with self._state.condition:
+
+ def _done():
+ return self._state.trailing_metadata is not None
+
+ _common.wait(self._state.condition.wait, _done)
+ return self._state.trailing_metadata
+
+ def code(self):
+ """See grpc.Call.code"""
+ with self._state.condition:
+
+ def _done():
+ return self._state.code is not None
+
+ _common.wait(self._state.condition.wait, _done)
+ return self._state.code
+
+ def details(self):
+ """See grpc.Call.details"""
+ with self._state.condition:
+
+ def _done():
+ return self._state.details is not None
+
+ _common.wait(self._state.condition.wait, _done)
+ return _common.decode(self._state.details)
+
+ def debug_error_string(self):
+ with self._state.condition:
+
+ def _done():
+ return self._state.debug_error_string is not None
+
+ _common.wait(self._state.condition.wait, _done)
+ return _common.decode(self._state.debug_error_string)
+
def cancelled(self):
with self._state.condition:
return self._state.cancelled
@@ -699,22 +699,22 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
with self._state.condition:
return self._state.code is not None
- def _is_complete(self):
- return self._state.code is not None
-
+ def _is_complete(self):
+ return self._state.code is not None
+
def result(self, timeout=None):
- """Returns the result of the computation or raises its exception.
-
- See grpc.Future.result for the full API contract.
- """
+ """Returns the result of the computation or raises its exception.
+
+ See grpc.Future.result for the full API contract.
+ """
with self._state.condition:
timed_out = _common.wait(self._state.condition.wait,
self._is_complete,
timeout=timeout)
- if timed_out:
- raise grpc.FutureTimeoutError()
- else:
- if self._state.code is grpc.StatusCode.OK:
+ if timed_out:
+ raise grpc.FutureTimeoutError()
+ else:
+ if self._state.code is grpc.StatusCode.OK:
return self._state.response
elif self._state.cancelled:
raise grpc.FutureCancelledError()
@@ -722,18 +722,18 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
raise self
def exception(self, timeout=None):
- """Return the exception raised by the computation.
-
- See grpc.Future.exception for the full API contract.
- """
+ """Return the exception raised by the computation.
+
+ See grpc.Future.exception for the full API contract.
+ """
with self._state.condition:
timed_out = _common.wait(self._state.condition.wait,
self._is_complete,
timeout=timeout)
- if timed_out:
- raise grpc.FutureTimeoutError()
- else:
- if self._state.code is grpc.StatusCode.OK:
+ if timed_out:
+ raise grpc.FutureTimeoutError()
+ else:
+ if self._state.code is grpc.StatusCode.OK:
return None
elif self._state.cancelled:
raise grpc.FutureCancelledError()
@@ -741,18 +741,18 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
return self
def traceback(self, timeout=None):
- """Access the traceback of the exception raised by the computation.
-
- See grpc.future.traceback for the full API contract.
- """
+ """Access the traceback of the exception raised by the computation.
+
+ See grpc.future.traceback for the full API contract.
+ """
with self._state.condition:
timed_out = _common.wait(self._state.condition.wait,
self._is_complete,
timeout=timeout)
- if timed_out:
- raise grpc.FutureTimeoutError()
- else:
- if self._state.code is grpc.StatusCode.OK:
+ if timed_out:
+ raise grpc.FutureTimeoutError()
+ else:
+ if self._state.code is grpc.StatusCode.OK:
return None
elif self._state.cancelled:
raise grpc.FutureCancelledError()
@@ -765,7 +765,7 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
def add_done_callback(self, fn):
with self._state.condition:
if self._state.code is None:
- self._state.callbacks.append(functools.partial(fn, self))
+ self._state.callbacks.append(functools.partial(fn, self))
return
fn(self)
@@ -785,22 +785,22 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
else:
raise self
- def _response_ready():
- return (
- self._state.response is not None or
- (cygrpc.OperationType.receive_message not in self._state.due
- and self._state.code is not None))
-
- _common.wait(self._state.condition.wait, _response_ready)
- if self._state.response is not None:
- response = self._state.response
- self._state.response = None
- return response
- elif cygrpc.OperationType.receive_message not in self._state.due:
- if self._state.code is grpc.StatusCode.OK:
- raise StopIteration()
- elif self._state.code is not None:
- raise self
+ def _response_ready():
+ return (
+ self._state.response is not None or
+ (cygrpc.OperationType.receive_message not in self._state.due
+ and self._state.code is not None))
+
+ _common.wait(self._state.condition.wait, _response_ready)
+ if self._state.response is not None:
+ response = self._state.response
+ self._state.response = None
+ return response
+ elif cygrpc.OperationType.receive_message not in self._state.due:
+ if self._state.code is grpc.StatusCode.OK:
+ raise StopIteration()
+ elif self._state.code is not None:
+ raise self
def _start_unary_request(request, timeout, request_serializer):
@@ -809,8 +809,8 @@ def _start_unary_request(request, timeout, request_serializer):
if serialized_request is None:
state = _RPCState((), (), (), grpc.StatusCode.INTERNAL,
'Exception serializing request!')
- error = _InactiveRpcError(state)
- return deadline, None, error
+ error = _InactiveRpcError(state)
+ return deadline, None, error
else:
return deadline, serialized_request, None
@@ -818,12 +818,12 @@ def _start_unary_request(request, timeout, request_serializer):
def _end_unary_response_blocking(state, call, with_call, deadline):
if state.code is grpc.StatusCode.OK:
if with_call:
- rendezvous = _MultiThreadedRendezvous(state, call, None, deadline)
+ rendezvous = _MultiThreadedRendezvous(state, call, None, deadline)
return state.response, rendezvous
else:
return state.response
else:
- raise _InactiveRpcError(state)
+ raise _InactiveRpcError(state)
def _stream_unary_invocation_operationses(metadata, initial_metadata_flags):
@@ -847,18 +847,18 @@ def _stream_unary_invocation_operationses_and_tags(metadata,
metadata, initial_metadata_flags))
-def _determine_deadline(user_deadline):
- parent_deadline = cygrpc.get_deadline_from_context()
- if parent_deadline is None and user_deadline is None:
- return None
- elif parent_deadline is not None and user_deadline is None:
- return parent_deadline
- elif user_deadline is not None and parent_deadline is None:
- return user_deadline
- else:
- return min(parent_deadline, user_deadline)
-
-
+def _determine_deadline(user_deadline):
+ parent_deadline = cygrpc.get_deadline_from_context()
+ if parent_deadline is None and user_deadline is None:
+ return None
+ elif parent_deadline is not None and user_deadline is None:
+ return parent_deadline
+ elif user_deadline is not None and parent_deadline is None:
+ return user_deadline
+ else:
+ return min(parent_deadline, user_deadline)
+
+
class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
# pylint: disable=too-many-arguments
@@ -871,19 +871,19 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
self._response_deserializer = response_deserializer
self._context = cygrpc.build_census_context()
- def _prepare(self, request, timeout, metadata, wait_for_ready, compression):
+ def _prepare(self, request, timeout, metadata, wait_for_ready, compression):
deadline, serialized_request, rendezvous = _start_unary_request(
request, timeout, self._request_serializer)
initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
wait_for_ready)
- augmented_metadata = _compression.augment_metadata(
- metadata, compression)
+ augmented_metadata = _compression.augment_metadata(
+ metadata, compression)
if serialized_request is None:
return None, None, None, rendezvous
else:
state = _RPCState(_UNARY_UNARY_INITIAL_DUE, None, None, None, None)
operations = (
- cygrpc.SendInitialMetadataOperation(augmented_metadata,
+ cygrpc.SendInitialMetadataOperation(augmented_metadata,
initial_metadata_flags),
cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
@@ -893,17 +893,17 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
)
return state, operations, deadline, None
- def _blocking(self, request, timeout, metadata, credentials, wait_for_ready,
- compression):
+ def _blocking(self, request, timeout, metadata, credentials, wait_for_ready,
+ compression):
state, operations, deadline, rendezvous = self._prepare(
- request, timeout, metadata, wait_for_ready, compression)
+ request, timeout, metadata, wait_for_ready, compression)
if state is None:
raise rendezvous # pylint: disable-msg=raising-bad-type
else:
call = self._channel.segregated_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
- self._method, None, _determine_deadline(deadline), metadata,
- None if credentials is None else credentials._credentials, ((
+ self._method, None, _determine_deadline(deadline), metadata,
+ None if credentials is None else credentials._credentials, ((
operations,
None,
),), self._context)
@@ -916,10 +916,10 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
state, call, = self._blocking(request, timeout, metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready, compression)
return _end_unary_response_blocking(state, call, False, None)
def with_call(self,
@@ -927,10 +927,10 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
state, call, = self._blocking(request, timeout, metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready, compression)
return _end_unary_response_blocking(state, call, True, None)
def future(self,
@@ -938,10 +938,10 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
state, operations, deadline, rendezvous = self._prepare(
- request, timeout, metadata, wait_for_ready, compression)
+ request, timeout, metadata, wait_for_ready, compression)
if state is None:
raise rendezvous # pylint: disable-msg=raising-bad-type
else:
@@ -956,56 +956,56 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
deadline)
-class _SingleThreadedUnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
-
- # pylint: disable=too-many-arguments
- def __init__(self, channel, method, request_serializer,
- response_deserializer):
- self._channel = channel
- self._method = method
- self._request_serializer = request_serializer
- self._response_deserializer = response_deserializer
- self._context = cygrpc.build_census_context()
-
- def __call__( # pylint: disable=too-many-locals
- self,
- request,
- timeout=None,
- metadata=None,
- credentials=None,
- wait_for_ready=None,
- compression=None):
- deadline = _deadline(timeout)
- serialized_request = _common.serialize(request,
- self._request_serializer)
- if serialized_request is None:
- state = _RPCState((), (), (), grpc.StatusCode.INTERNAL,
- 'Exception serializing request!')
- raise _InactiveRpcError(state)
-
- state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
- call_credentials = None if credentials is None else credentials._credentials
- initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
- wait_for_ready)
- augmented_metadata = _compression.augment_metadata(
- metadata, compression)
- operations = (
- (cygrpc.SendInitialMetadataOperation(augmented_metadata,
- initial_metadata_flags),
- cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS)),
- (cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),),
- (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
- )
- operations_and_tags = tuple((ops, None) for ops in operations)
- call = self._channel.segregated_call(
- cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method,
- None, _determine_deadline(deadline), metadata, call_credentials,
- operations_and_tags, self._context)
- return _SingleThreadedRendezvous(state, call,
- self._response_deserializer, deadline)
-
-
+class _SingleThreadedUnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
+
+ # pylint: disable=too-many-arguments
+ def __init__(self, channel, method, request_serializer,
+ response_deserializer):
+ self._channel = channel
+ self._method = method
+ self._request_serializer = request_serializer
+ self._response_deserializer = response_deserializer
+ self._context = cygrpc.build_census_context()
+
+ def __call__( # pylint: disable=too-many-locals
+ self,
+ request,
+ timeout=None,
+ metadata=None,
+ credentials=None,
+ wait_for_ready=None,
+ compression=None):
+ deadline = _deadline(timeout)
+ serialized_request = _common.serialize(request,
+ self._request_serializer)
+ if serialized_request is None:
+ state = _RPCState((), (), (), grpc.StatusCode.INTERNAL,
+ 'Exception serializing request!')
+ raise _InactiveRpcError(state)
+
+ state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
+ call_credentials = None if credentials is None else credentials._credentials
+ initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+ wait_for_ready)
+ augmented_metadata = _compression.augment_metadata(
+ metadata, compression)
+ operations = (
+ (cygrpc.SendInitialMetadataOperation(augmented_metadata,
+ initial_metadata_flags),
+ cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS)),
+ (cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),),
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+ )
+ operations_and_tags = tuple((ops, None) for ops in operations)
+ call = self._channel.segregated_call(
+ cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method,
+ None, _determine_deadline(deadline), metadata, call_credentials,
+ operations_and_tags, self._context)
+ return _SingleThreadedRendezvous(state, call,
+ self._response_deserializer, deadline)
+
+
class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
# pylint: disable=too-many-arguments
@@ -1018,14 +1018,14 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
self._response_deserializer = response_deserializer
self._context = cygrpc.build_census_context()
- def __call__( # pylint: disable=too-many-locals
- self,
- request,
- timeout=None,
- metadata=None,
- credentials=None,
- wait_for_ready=None,
- compression=None):
+ def __call__( # pylint: disable=too-many-locals
+ self,
+ request,
+ timeout=None,
+ metadata=None,
+ credentials=None,
+ wait_for_ready=None,
+ compression=None):
deadline, serialized_request, rendezvous = _start_unary_request(
request, timeout, self._request_serializer)
initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
@@ -1033,12 +1033,12 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
if serialized_request is None:
raise rendezvous # pylint: disable-msg=raising-bad-type
else:
- augmented_metadata = _compression.augment_metadata(
- metadata, compression)
+ augmented_metadata = _compression.augment_metadata(
+ metadata, compression)
state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
operationses = (
(
- cygrpc.SendInitialMetadataOperation(augmented_metadata,
+ cygrpc.SendInitialMetadataOperation(augmented_metadata,
initial_metadata_flags),
cygrpc.SendMessageOperation(serialized_request,
_EMPTY_FLAGS),
@@ -1049,7 +1049,7 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
)
call = self._managed_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
- self._method, None, _determine_deadline(deadline), metadata,
+ self._method, None, _determine_deadline(deadline), metadata,
None if credentials is None else credentials._credentials,
operationses, _event_handler(state,
self._response_deserializer),
@@ -1072,19 +1072,19 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
self._context = cygrpc.build_census_context()
def _blocking(self, request_iterator, timeout, metadata, credentials,
- wait_for_ready, compression):
+ wait_for_ready, compression):
deadline = _deadline(timeout)
state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
wait_for_ready)
- augmented_metadata = _compression.augment_metadata(
- metadata, compression)
+ augmented_metadata = _compression.augment_metadata(
+ metadata, compression)
call = self._channel.segregated_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method,
None, _determine_deadline(deadline), augmented_metadata,
None if credentials is None else credentials._credentials,
_stream_unary_invocation_operationses_and_tags(
- augmented_metadata, initial_metadata_flags), self._context)
+ augmented_metadata, initial_metadata_flags), self._context)
_consume_request_iterator(request_iterator, state, call,
self._request_serializer, None)
while True:
@@ -1101,10 +1101,10 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
state, call, = self._blocking(request_iterator, timeout, metadata,
- credentials, wait_for_ready, compression)
+ credentials, wait_for_ready, compression)
return _end_unary_response_blocking(state, call, False, None)
def with_call(self,
@@ -1112,10 +1112,10 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
state, call, = self._blocking(request_iterator, timeout, metadata,
- credentials, wait_for_ready, compression)
+ credentials, wait_for_ready, compression)
return _end_unary_response_blocking(state, call, True, None)
def future(self,
@@ -1123,15 +1123,15 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
deadline = _deadline(timeout)
state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
event_handler = _event_handler(state, self._response_deserializer)
initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
wait_for_ready)
- augmented_metadata = _compression.augment_metadata(
- metadata, compression)
+ augmented_metadata = _compression.augment_metadata(
+ metadata, compression)
call = self._managed_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method,
None, deadline, augmented_metadata,
@@ -1141,8 +1141,8 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
event_handler, self._context)
_consume_request_iterator(request_iterator, state, call,
self._request_serializer, event_handler)
- return _MultiThreadedRendezvous(state, call,
- self._response_deserializer, deadline)
+ return _MultiThreadedRendezvous(state, call,
+ self._response_deserializer, deadline)
class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
@@ -1162,17 +1162,17 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
deadline = _deadline(timeout)
state = _RPCState(_STREAM_STREAM_INITIAL_DUE, None, None, None, None)
initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
wait_for_ready)
- augmented_metadata = _compression.augment_metadata(
- metadata, compression)
+ augmented_metadata = _compression.augment_metadata(
+ metadata, compression)
operationses = (
(
- cygrpc.SendInitialMetadataOperation(augmented_metadata,
+ cygrpc.SendInitialMetadataOperation(augmented_metadata,
initial_metadata_flags),
cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
),
@@ -1186,8 +1186,8 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
operationses, event_handler, self._context)
_consume_request_iterator(request_iterator, state, call,
self._request_serializer, event_handler)
- return _MultiThreadedRendezvous(state, call,
- self._response_deserializer, deadline)
+ return _MultiThreadedRendezvous(state, call,
+ self._response_deserializer, deadline)
class _InitialMetadataFlags(int):
@@ -1416,55 +1416,55 @@ def _unsubscribe(state, callback):
break
-def _augment_options(base_options, compression):
- compression_option = _compression.create_channel_option(compression)
- return tuple(base_options) + compression_option + ((
- cygrpc.ChannelArgKey.primary_user_agent_string,
- _USER_AGENT,
- ),)
-
-
-def _separate_channel_options(options):
- """Separates core channel options from Python channel options."""
- core_options = []
- python_options = []
- for pair in options:
- if pair[0] == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream:
- python_options.append(pair)
- else:
- core_options.append(pair)
- return python_options, core_options
-
-
+def _augment_options(base_options, compression):
+ compression_option = _compression.create_channel_option(compression)
+ return tuple(base_options) + compression_option + ((
+ cygrpc.ChannelArgKey.primary_user_agent_string,
+ _USER_AGENT,
+ ),)
+
+
+def _separate_channel_options(options):
+ """Separates core channel options from Python channel options."""
+ core_options = []
+ python_options = []
+ for pair in options:
+ if pair[0] == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream:
+ python_options.append(pair)
+ else:
+ core_options.append(pair)
+ return python_options, core_options
+
+
class Channel(grpc.Channel):
"""A cygrpc.Channel-backed implementation of grpc.Channel."""
- def __init__(self, target, options, credentials, compression):
+ def __init__(self, target, options, credentials, compression):
"""Constructor.
Args:
target: The target to which to connect.
options: Configuration options for the channel.
credentials: A cygrpc.ChannelCredentials or None.
- compression: An optional value indicating the compression method to be
- used over the lifetime of the channel.
+ compression: An optional value indicating the compression method to be
+ used over the lifetime of the channel.
"""
- python_options, core_options = _separate_channel_options(options)
- self._single_threaded_unary_stream = _DEFAULT_SINGLE_THREADED_UNARY_STREAM
- self._process_python_options(python_options)
+ python_options, core_options = _separate_channel_options(options)
+ self._single_threaded_unary_stream = _DEFAULT_SINGLE_THREADED_UNARY_STREAM
+ self._process_python_options(python_options)
self._channel = cygrpc.Channel(
- _common.encode(target), _augment_options(core_options, compression),
- credentials)
+ _common.encode(target), _augment_options(core_options, compression),
+ credentials)
self._call_state = _ChannelCallState(self._channel)
self._connectivity_state = _ChannelConnectivityState(self._channel)
cygrpc.fork_register_channel(self)
- def _process_python_options(self, python_options):
- """Sets channel attributes according to python-only channel options."""
- for pair in python_options:
- if pair[0] == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream:
- self._single_threaded_unary_stream = True
-
+ def _process_python_options(self, python_options):
+ """Sets channel attributes according to python-only channel options."""
+ for pair in python_options:
+ if pair[0] == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream:
+ self._single_threaded_unary_stream = True
+
def subscribe(self, callback, try_to_connect=None):
_subscribe(self._connectivity_state, callback, try_to_connect)
@@ -1483,15 +1483,15 @@ class Channel(grpc.Channel):
method,
request_serializer=None,
response_deserializer=None):
- # NOTE(rbellevi): Benchmarks have shown that running a unary-stream RPC
- # on a single Python thread results in an appreciable speed-up. However,
- # due to slight differences in capability, the multi-threaded variant
- # remains the default.
- if self._single_threaded_unary_stream:
- return _SingleThreadedUnaryStreamMultiCallable(
- self._channel, _common.encode(method), request_serializer,
- response_deserializer)
- else:
+ # NOTE(rbellevi): Benchmarks have shown that running a unary-stream RPC
+ # on a single Python thread results in an appreciable speed-up. However,
+ # due to slight differences in capability, the multi-threaded variant
+ # remains the default.
+ if self._single_threaded_unary_stream:
+ return _SingleThreadedUnaryStreamMultiCallable(
+ self._channel, _common.encode(method), request_serializer,
+ response_deserializer)
+ else:
return _UnaryStreamMultiCallable(
self._channel,
_channel_managed_call_management(self._call_state),
@@ -1514,19 +1514,19 @@ class Channel(grpc.Channel):
self._channel, _channel_managed_call_management(self._call_state),
_common.encode(method), request_serializer, response_deserializer)
- def _unsubscribe_all(self):
- state = self._connectivity_state
- if state:
- with state.lock:
- del state.callbacks_and_connectivities[:]
-
+ def _unsubscribe_all(self):
+ state = self._connectivity_state
+ if state:
+ with state.lock:
+ del state.callbacks_and_connectivities[:]
+
def _close(self):
- self._unsubscribe_all()
+ self._unsubscribe_all()
self._channel.close(cygrpc.StatusCode.cancelled, 'Channel closed!')
- cygrpc.fork_unregister_channel(self)
+ cygrpc.fork_unregister_channel(self)
def _close_on_fork(self):
- self._unsubscribe_all()
+ self._unsubscribe_all()
self._channel.close_on_fork(cygrpc.StatusCode.cancelled,
'Channel closed due to fork')
@@ -1550,9 +1550,9 @@ class Channel(grpc.Channel):
# for as long as they are in use and to close them after using them,
# then deletion of this grpc._channel.Channel instance can be made to
# effect closure of the underlying cygrpc.Channel instance.
- try:
- self._unsubscribe_all()
- except: # pylint: disable=bare-except
- # Exceptions in __del__ are ignored by Python anyway, but they can
- # keep spamming logs. Just silence them.
- pass
+ try:
+ self._unsubscribe_all()
+ except: # pylint: disable=bare-except
+ # Exceptions in __del__ are ignored by Python anyway, but they can
+ # keep spamming logs. Just silence them.
+ pass
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_common.py b/contrib/libs/grpc/src/python/grpcio/grpc/_common.py
index 128124c325..c18d2fca18 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_common.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_common.py
@@ -14,7 +14,7 @@
"""Shared implementation."""
import logging
-import time
+import time
import six
import grpc
@@ -59,11 +59,11 @@ STATUS_CODE_TO_CYGRPC_STATUS_CODE = {
CYGRPC_STATUS_CODE_TO_STATUS_CODE)
}
-MAXIMUM_WAIT_TIMEOUT = 0.1
+MAXIMUM_WAIT_TIMEOUT = 0.1
_ERROR_MESSAGE_PORT_BINDING_FAILED = 'Failed to bind to address %s; set ' \
'GRPC_VERBOSITY=debug environment variable to see detailed error message.'
-
+
def encode(s):
if isinstance(s, bytes):
@@ -100,53 +100,53 @@ def deserialize(serialized_message, deserializer):
def fully_qualified_method(group, method):
return '/{}/{}'.format(group, method)
-
-
-def _wait_once(wait_fn, timeout, spin_cb):
- wait_fn(timeout=timeout)
- if spin_cb is not None:
- spin_cb()
-
-
-def wait(wait_fn, wait_complete_fn, timeout=None, spin_cb=None):
- """Blocks waiting for an event without blocking the thread indefinitely.
-
- See https://github.com/grpc/grpc/issues/19464 for full context. CPython's
- `threading.Event.wait` and `threading.Condition.wait` methods, if invoked
- without a timeout kwarg, may block the calling thread indefinitely. If the
- call is made from the main thread, this means that signal handlers may not
- run for an arbitrarily long period of time.
-
- This wrapper calls the supplied wait function with an arbitrary short
- timeout to ensure that no signal handler has to wait longer than
- MAXIMUM_WAIT_TIMEOUT before executing.
-
- Args:
- wait_fn: A callable acceptable a single float-valued kwarg named
- `timeout`. This function is expected to be one of `threading.Event.wait`
- or `threading.Condition.wait`.
- wait_complete_fn: A callable taking no arguments and returning a bool.
- When this function returns true, it indicates that waiting should cease.
- timeout: An optional float-valued number of seconds after which the wait
- should cease.
- spin_cb: An optional Callable taking no arguments and returning nothing.
- This callback will be called on each iteration of the spin. This may be
- used for, e.g. work related to forking.
-
- Returns:
- True if a timeout was supplied and it was reached. False otherwise.
- """
- if timeout is None:
- while not wait_complete_fn():
- _wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb)
- else:
- end = time.time() + timeout
- while not wait_complete_fn():
- remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT)
- if remaining < 0:
- return True
- _wait_once(wait_fn, remaining, spin_cb)
- return False
+
+
+def _wait_once(wait_fn, timeout, spin_cb):
+ wait_fn(timeout=timeout)
+ if spin_cb is not None:
+ spin_cb()
+
+
+def wait(wait_fn, wait_complete_fn, timeout=None, spin_cb=None):
+ """Blocks waiting for an event without blocking the thread indefinitely.
+
+ See https://github.com/grpc/grpc/issues/19464 for full context. CPython's
+ `threading.Event.wait` and `threading.Condition.wait` methods, if invoked
+ without a timeout kwarg, may block the calling thread indefinitely. If the
+ call is made from the main thread, this means that signal handlers may not
+ run for an arbitrarily long period of time.
+
+ This wrapper calls the supplied wait function with an arbitrary short
+ timeout to ensure that no signal handler has to wait longer than
+ MAXIMUM_WAIT_TIMEOUT before executing.
+
+ Args:
+ wait_fn: A callable acceptable a single float-valued kwarg named
+ `timeout`. This function is expected to be one of `threading.Event.wait`
+ or `threading.Condition.wait`.
+ wait_complete_fn: A callable taking no arguments and returning a bool.
+ When this function returns true, it indicates that waiting should cease.
+ timeout: An optional float-valued number of seconds after which the wait
+ should cease.
+ spin_cb: An optional Callable taking no arguments and returning nothing.
+ This callback will be called on each iteration of the spin. This may be
+ used for, e.g. work related to forking.
+
+ Returns:
+ True if a timeout was supplied and it was reached. False otherwise.
+ """
+ if timeout is None:
+ while not wait_complete_fn():
+ _wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb)
+ else:
+ end = time.time() + timeout
+ while not wait_complete_fn():
+ remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT)
+ if remaining < 0:
+ return True
+ _wait_once(wait_fn, remaining, spin_cb)
+ return False
def validate_port_binding_result(address, port):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_compression.py b/contrib/libs/grpc/src/python/grpcio/grpc/_compression.py
index 45339c3afe..18da583271 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_compression.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_compression.py
@@ -1,55 +1,55 @@
-# Copyright 2019 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from grpc._cython import cygrpc
-
-NoCompression = cygrpc.CompressionAlgorithm.none
-Deflate = cygrpc.CompressionAlgorithm.deflate
-Gzip = cygrpc.CompressionAlgorithm.gzip
-
-_METADATA_STRING_MAPPING = {
- NoCompression: 'identity',
- Deflate: 'deflate',
- Gzip: 'gzip',
-}
-
-
-def _compression_algorithm_to_metadata_value(compression):
- return _METADATA_STRING_MAPPING[compression]
-
-
-def compression_algorithm_to_metadata(compression):
- return (cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
- _compression_algorithm_to_metadata_value(compression))
-
-
-def create_channel_option(compression):
- return ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM,
- int(compression)),) if compression else ()
-
-
-def augment_metadata(metadata, compression):
- if not metadata and not compression:
- return None
- base_metadata = tuple(metadata) if metadata else ()
- compression_metadata = (
- compression_algorithm_to_metadata(compression),) if compression else ()
- return base_metadata + compression_metadata
-
-
-__all__ = (
- "NoCompression",
- "Deflate",
- "Gzip",
-)
+# Copyright 2019 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from grpc._cython import cygrpc
+
+NoCompression = cygrpc.CompressionAlgorithm.none
+Deflate = cygrpc.CompressionAlgorithm.deflate
+Gzip = cygrpc.CompressionAlgorithm.gzip
+
+_METADATA_STRING_MAPPING = {
+ NoCompression: 'identity',
+ Deflate: 'deflate',
+ Gzip: 'gzip',
+}
+
+
+def _compression_algorithm_to_metadata_value(compression):
+ return _METADATA_STRING_MAPPING[compression]
+
+
+def compression_algorithm_to_metadata(compression):
+ return (cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
+ _compression_algorithm_to_metadata_value(compression))
+
+
+def create_channel_option(compression):
+ return ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM,
+ int(compression)),) if compression else ()
+
+
+def augment_metadata(metadata, compression):
+ if not metadata and not compression:
+ return None
+ base_metadata = tuple(metadata) if metadata else ()
+ compression_metadata = (
+ compression_algorithm_to_metadata(compression),) if compression else ()
+ return base_metadata + compression_metadata
+
+
+__all__ = (
+ "NoCompression",
+ "Deflate",
+ "Gzip",
+)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi
index de4d71b819..da5317830a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi
@@ -16,7 +16,7 @@
cdef object _custom_op_on_c_call(int op, grpc_call *call):
raise NotImplementedError("No custom hooks are implemented")
-def install_context_from_request_call_event(RequestCallEvent event):
+def install_context_from_request_call_event(RequestCallEvent event):
pass
def uninstall_context():
@@ -30,6 +30,6 @@ cdef class CensusContext:
def set_census_context_on_call(_CallState call_state, CensusContext census_ctx):
pass
-
-def get_deadline_from_context():
- return None
+
+def get_deadline_from_context():
+ return None
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pxd.pxi
index 867245a694..7e7f554672 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pxd.pxi
@@ -1,29 +1,29 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
cdef class _AioCall(GrpcCallWrapper):
- cdef:
+ cdef:
readonly AioChannel _channel
- list _references
+ list _references
object _deadline
list _done_callbacks
# Caches the picked event loop, so we can avoid the 30ns overhead each
# time we need access to the event loop.
object _loop
-
+
# Flag indicates whether cancel being called or not. Cancellation from
# Core or peer works perfectly fine with normal procedure. However, we
# need this flag to clean up resources for cancellation from the
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pyx.pxi
index 10c024e1b3..5b6edf35cf 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/call.pyx.pxi
@@ -1,34 +1,34 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-_EMPTY_FLAGS = 0
-_EMPTY_MASK = 0
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+_EMPTY_FLAGS = 0
+_EMPTY_MASK = 0
_IMMUTABLE_EMPTY_METADATA = tuple()
-
+
_UNKNOWN_CANCELLATION_DETAILS = 'RPC cancelled for unknown reason.'
_OK_CALL_REPRESENTATION = ('<{} of RPC that terminated with:\n'
'\tstatus = {}\n'
'\tdetails = "{}"\n'
'>')
-
+
_NON_OK_CALL_REPRESENTATION = ('<{} of RPC that terminated with:\n'
'\tstatus = {}\n'
'\tdetails = "{}"\n'
'\tdebug_error_string = "{}"\n'
'>')
-
+
cdef int _get_send_initial_metadata_flags(object wait_for_ready) except *:
cdef int flags = 0
@@ -48,9 +48,9 @@ cdef class _AioCall(GrpcCallWrapper):
bytes method, CallCredentials call_credentials, object wait_for_ready):
init_grpc_aio()
self.call = NULL
- self._channel = channel
+ self._channel = channel
self._loop = channel.loop
- self._references = []
+ self._references = []
self._status = None
self._initial_metadata = None
self._waiters_status = []
@@ -60,7 +60,7 @@ cdef class _AioCall(GrpcCallWrapper):
self._deadline = deadline
self._send_initial_metadata_flags = _get_send_initial_metadata_flags(wait_for_ready)
self._create_grpc_call(deadline, method, call_credentials)
-
+
def __dealloc__(self):
if self.call:
grpc_call_unref(self.call)
@@ -71,7 +71,7 @@ cdef class _AioCall(GrpcCallWrapper):
# This needs to be loaded at run time once everything
# has been loaded.
from grpc import _common
-
+
if not self.done():
return '<{} object>'.format(self.__class__.__name__)
@@ -97,40 +97,40 @@ cdef class _AioCall(GrpcCallWrapper):
object deadline,
bytes method,
CallCredentials credentials) except *:
- """Creates the corresponding Core object for this RPC.
-
+ """Creates the corresponding Core object for this RPC.
+
For unary calls, the grpc_call lives shortly and can be destroyed after
- invoke start_batch. However, if either side is streaming, the grpc_call
- life span will be longer than one function. So, it would better save it
- as an instance variable than a stack variable, which reflects its
- nature in Core.
- """
- cdef grpc_slice method_slice
+ invoke start_batch. However, if either side is streaming, the grpc_call
+ life span will be longer than one function. So, it would better save it
+ as an instance variable than a stack variable, which reflects its
+ nature in Core.
+ """
+ cdef grpc_slice method_slice
cdef gpr_timespec c_deadline = _timespec_from_time(deadline)
cdef grpc_call_error set_credentials_error
-
- method_slice = grpc_slice_from_copied_buffer(
- <const char *> method,
- <size_t> len(method)
- )
+
+ method_slice = grpc_slice_from_copied_buffer(
+ <const char *> method,
+ <size_t> len(method)
+ )
self.call = grpc_channel_create_call(
- self._channel.channel,
- NULL,
- _EMPTY_MASK,
+ self._channel.channel,
+ NULL,
+ _EMPTY_MASK,
global_completion_queue(),
- method_slice,
- NULL,
+ method_slice,
+ NULL,
c_deadline,
- NULL
- )
+ NULL
+ )
if credentials is not None:
set_credentials_error = grpc_call_set_credentials(self.call, credentials.c())
if set_credentials_error != GRPC_CALL_OK:
raise InternalError("Credentials couldn't have been set: {0}".format(set_credentials_error))
- grpc_slice_unref(method_slice)
-
+ grpc_slice_unref(method_slice)
+
cdef void _set_status(self, AioRpcStatus status) except *:
cdef list waiters
@@ -177,7 +177,7 @@ cdef class _AioCall(GrpcCallWrapper):
return None
else:
return max(0, self._deadline - time.time())
-
+
def cancel(self, str details):
"""Cancels the RPC in Core with given RPC status.
@@ -185,11 +185,11 @@ cdef class _AioCall(GrpcCallWrapper):
proper state.
"""
self._is_locally_cancelled = True
-
+
cdef object details_bytes
cdef char *c_details
cdef grpc_call_error error
-
+
self._set_status(AioRpcStatus(
StatusCode.cancelled,
details,
@@ -294,7 +294,7 @@ cdef class _AioCall(GrpcCallWrapper):
outbound_initial_metadata: optional outbound metadata.
"""
cdef tuple ops
-
+
cdef SendInitialMetadataOperation initial_metadata_op = SendInitialMetadataOperation(
outbound_initial_metadata,
self._send_initial_metadata_flags)
@@ -303,19 +303,19 @@ cdef class _AioCall(GrpcCallWrapper):
cdef ReceiveInitialMetadataOperation receive_initial_metadata_op = ReceiveInitialMetadataOperation(_EMPTY_FLAGS)
cdef ReceiveMessageOperation receive_message_op = ReceiveMessageOperation(_EMPTY_FLAGS)
cdef ReceiveStatusOnClientOperation receive_status_on_client_op = ReceiveStatusOnClientOperation(_EMPTY_FLAGS)
-
+
ops = (initial_metadata_op, send_message_op, send_close_op,
receive_initial_metadata_op, receive_message_op,
receive_status_on_client_op)
-
+
# Executes all operations in one batch.
# Might raise CancelledError, handling it in Python UnaryUnaryCall.
await execute_batch(self,
ops,
self._loop)
-
+
self._set_initial_metadata(receive_initial_metadata_op.initial_metadata())
-
+
cdef grpc_status_code code
code = receive_status_on_client_op.code()
@@ -325,12 +325,12 @@ cdef class _AioCall(GrpcCallWrapper):
receive_status_on_client_op.trailing_metadata(),
receive_status_on_client_op.error_string(),
))
-
+
if code == StatusCode.ok:
return receive_message_op.message()
else:
return None
-
+
async def _handle_status_once_received(self):
"""Handles the status sent by peer once received."""
cdef ReceiveStatusOnClientOperation op = ReceiveStatusOnClientOperation(_EMPTY_FLAGS)
@@ -347,11 +347,11 @@ cdef class _AioCall(GrpcCallWrapper):
op.trailing_metadata(),
op.error_string(),
))
-
+
async def receive_serialized_message(self):
"""Receives one single raw message in bytes."""
cdef bytes received_message
-
+
# Receives a message. Returns None when failed:
# * EOF, no more messages to read;
# * The client application cancels;
@@ -364,7 +364,7 @@ cdef class _AioCall(GrpcCallWrapper):
return received_message
else:
return EOF
-
+
async def send_serialized_message(self, bytes message):
"""Sends one single raw message in bytes."""
await _send_message(self,
@@ -372,7 +372,7 @@ cdef class _AioCall(GrpcCallWrapper):
None,
False,
self._loop)
-
+
async def send_receive_close(self):
"""Half close the RPC on the client-side."""
cdef SendCloseFromClientOperation op = SendCloseFromClientOperation(_EMPTY_FLAGS)
@@ -401,7 +401,7 @@ cdef class _AioCall(GrpcCallWrapper):
initial_metadata_op,
send_message_op,
send_close_op,
- )
+ )
try:
# Sends out the request message.
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pxd.pxi
index e5620cd166..44276bbad3 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pxd.pxi
@@ -1,57 +1,57 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-cdef class CallbackFailureHandler:
- cdef str _core_function_name
- cdef object _error_details
- cdef object _exception_type
-
- cdef handle(self, object future)
-
-
-cdef struct CallbackContext:
- # C struct to store callback context in the form of pointers.
- #
- # Attributes:
- # functor: A grpc_experimental_completion_queue_functor represents the
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+cdef class CallbackFailureHandler:
+ cdef str _core_function_name
+ cdef object _error_details
+ cdef object _exception_type
+
+ cdef handle(self, object future)
+
+
+cdef struct CallbackContext:
+ # C struct to store callback context in the form of pointers.
+ #
+ # Attributes:
+ # functor: A grpc_experimental_completion_queue_functor represents the
# callback function in the only way Core understands.
- # waiter: An asyncio.Future object that fulfills when the callback is
+ # waiter: An asyncio.Future object that fulfills when the callback is
# invoked by Core.
# failure_handler: A CallbackFailureHandler object that called when Core
- # returns 'success == 0' state.
+ # returns 'success == 0' state.
# wrapper: A self-reference to the CallbackWrapper to help life cycle
# management.
- grpc_experimental_completion_queue_functor functor
- cpython.PyObject *waiter
+ grpc_experimental_completion_queue_functor functor
+ cpython.PyObject *waiter
cpython.PyObject *loop
- cpython.PyObject *failure_handler
+ cpython.PyObject *failure_handler
cpython.PyObject *callback_wrapper
-
-
-cdef class CallbackWrapper:
- cdef CallbackContext context
- cdef object _reference_of_future
- cdef object _reference_of_failure_handler
-
- @staticmethod
- cdef void functor_run(
- grpc_experimental_completion_queue_functor* functor,
- int succeed)
-
- cdef grpc_experimental_completion_queue_functor *c_functor(self)
-
-
-cdef class GrpcCallWrapper:
- cdef grpc_call* call
+
+
+cdef class CallbackWrapper:
+ cdef CallbackContext context
+ cdef object _reference_of_future
+ cdef object _reference_of_failure_handler
+
+ @staticmethod
+ cdef void functor_run(
+ grpc_experimental_completion_queue_functor* functor,
+ int succeed)
+
+ cdef grpc_experimental_completion_queue_functor *c_functor(self)
+
+
+cdef class GrpcCallWrapper:
+ cdef grpc_call* call
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pyx.pxi
index 86fc91e76a..00a05448ab 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/callback_common.pyx.pxi
@@ -1,57 +1,57 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-cdef class CallbackFailureHandler:
-
- def __cinit__(self,
- str core_function_name,
- object error_details,
- object exception_type):
- """Handles failure by raising exception."""
- self._core_function_name = core_function_name
- self._error_details = error_details
- self._exception_type = exception_type
-
- cdef handle(self, object future):
- future.set_exception(self._exception_type(
- 'Failed "%s": %s' % (self._core_function_name, self._error_details)
- ))
-
-
-cdef class CallbackWrapper:
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+cdef class CallbackFailureHandler:
+
+ def __cinit__(self,
+ str core_function_name,
+ object error_details,
+ object exception_type):
+ """Handles failure by raising exception."""
+ self._core_function_name = core_function_name
+ self._error_details = error_details
+ self._exception_type = exception_type
+
+ cdef handle(self, object future):
+ future.set_exception(self._exception_type(
+ 'Failed "%s": %s' % (self._core_function_name, self._error_details)
+ ))
+
+
+cdef class CallbackWrapper:
+
def __cinit__(self, object future, object loop, CallbackFailureHandler failure_handler):
- self.context.functor.functor_run = self.functor_run
- self.context.waiter = <cpython.PyObject*>future
+ self.context.functor.functor_run = self.functor_run
+ self.context.waiter = <cpython.PyObject*>future
self.context.loop = <cpython.PyObject*>loop
- self.context.failure_handler = <cpython.PyObject*>failure_handler
+ self.context.failure_handler = <cpython.PyObject*>failure_handler
self.context.callback_wrapper = <cpython.PyObject*>self
- # NOTE(lidiz) Not using a list here, because this class is critical in
- # data path. We should make it as efficient as possible.
- self._reference_of_future = future
- self._reference_of_failure_handler = failure_handler
+ # NOTE(lidiz) Not using a list here, because this class is critical in
+ # data path. We should make it as efficient as possible.
+ self._reference_of_future = future
+ self._reference_of_failure_handler = failure_handler
# NOTE(lidiz) We need to ensure when Core invokes our callback, the
# callback function itself is not deallocated. Othersise, we will get
# a segfault. We can view this as Core holding a ref.
cpython.Py_INCREF(self)
-
- @staticmethod
- cdef void functor_run(
- grpc_experimental_completion_queue_functor* functor,
- int success):
- cdef CallbackContext *context = <CallbackContext *>functor
+
+ @staticmethod
+ cdef void functor_run(
+ grpc_experimental_completion_queue_functor* functor,
+ int success):
+ cdef CallbackContext *context = <CallbackContext *>functor
cdef object waiter = <object>context.waiter
if not waiter.cancelled():
if success == 0:
@@ -59,47 +59,47 @@ cdef class CallbackWrapper:
else:
waiter.set_result(None)
cpython.Py_DECREF(<object>context.callback_wrapper)
-
- cdef grpc_experimental_completion_queue_functor *c_functor(self):
- return &self.context.functor
-
-
-cdef CallbackFailureHandler CQ_SHUTDOWN_FAILURE_HANDLER = CallbackFailureHandler(
- 'grpc_completion_queue_shutdown',
- 'Unknown',
+
+ cdef grpc_experimental_completion_queue_functor *c_functor(self):
+ return &self.context.functor
+
+
+cdef CallbackFailureHandler CQ_SHUTDOWN_FAILURE_HANDLER = CallbackFailureHandler(
+ 'grpc_completion_queue_shutdown',
+ 'Unknown',
InternalError)
-
-
+
+
class ExecuteBatchError(InternalError):
"""Raised when execute batch returns a failure from Core."""
-
-
+
+
async def execute_batch(GrpcCallWrapper grpc_call_wrapper,
- tuple operations,
- object loop):
- """The callback version of start batch operations."""
- cdef _BatchOperationTag batch_operation_tag = _BatchOperationTag(None, operations, None)
- batch_operation_tag.prepare()
-
- cdef object future = loop.create_future()
- cdef CallbackWrapper wrapper = CallbackWrapper(
- future,
+ tuple operations,
+ object loop):
+ """The callback version of start batch operations."""
+ cdef _BatchOperationTag batch_operation_tag = _BatchOperationTag(None, operations, None)
+ batch_operation_tag.prepare()
+
+ cdef object future = loop.create_future()
+ cdef CallbackWrapper wrapper = CallbackWrapper(
+ future,
loop,
CallbackFailureHandler('execute_batch', operations, ExecuteBatchError))
- cdef grpc_call_error error = grpc_call_start_batch(
- grpc_call_wrapper.call,
- batch_operation_tag.c_ops,
- batch_operation_tag.c_nops,
- wrapper.c_functor(), NULL)
-
- if error != GRPC_CALL_OK:
+ cdef grpc_call_error error = grpc_call_start_batch(
+ grpc_call_wrapper.call,
+ batch_operation_tag.c_ops,
+ batch_operation_tag.c_nops,
+ wrapper.c_functor(), NULL)
+
+ if error != GRPC_CALL_OK:
raise ExecuteBatchError("Failed grpc_call_start_batch: {}".format(error))
+
+ await future
- await future
-
- cdef grpc_event c_event
- # Tag.event must be called, otherwise messages won't be parsed from C
- batch_operation_tag.event(c_event)
+ cdef grpc_event c_event
+ # Tag.event must be called, otherwise messages won't be parsed from C
+ batch_operation_tag.event(c_event)
cdef prepend_send_initial_metadata_op(tuple ops, tuple metadata):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pxd.pxi
index 03b4990e48..d25de9a741 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pxd.pxi
@@ -1,27 +1,27 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
cdef enum AioChannelStatus:
AIO_CHANNEL_STATUS_UNKNOWN
AIO_CHANNEL_STATUS_READY
AIO_CHANNEL_STATUS_CLOSING
AIO_CHANNEL_STATUS_DESTROYED
-cdef class AioChannel:
- cdef:
- grpc_channel * channel
+cdef class AioChannel:
+ cdef:
+ grpc_channel * channel
object loop
- bytes _target
+ bytes _target
AioChannelStatus _status
bint _is_secure
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pyx.pxi
index beadce67b4..45cdc5171c 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/channel.pyx.pxi
@@ -1,18 +1,18 @@
-# Copyright 2019 gRPC authors.
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
#
-# 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.
-#
-
+
class _WatchConnectivityFailed(Exception):
"""Dedicated exception class for watch connectivity failed.
@@ -25,7 +25,7 @@ cdef CallbackFailureHandler _WATCH_CONNECTIVITY_FAILURE_HANDLER = CallbackFailur
_WatchConnectivityFailed)
-cdef class AioChannel:
+cdef class AioChannel:
def __cinit__(self, bytes target, tuple options, ChannelCredentials credentials, object loop):
init_grpc_aio()
if options is None:
@@ -34,7 +34,7 @@ cdef class AioChannel:
self._target = target
self.loop = loop
self._status = AIO_CHANNEL_STATUS_READY
-
+
if credentials is None:
self._is_secure = False
self.channel = grpc_insecure_channel_create(
@@ -52,11 +52,11 @@ cdef class AioChannel:
def __dealloc__(self):
shutdown_grpc_aio()
- def __repr__(self):
- class_name = self.__class__.__name__
- id_ = id(self)
- return f"<{class_name} {id_}>"
-
+ def __repr__(self):
+ class_name = self.__class__.__name__
+ id_ = id(self)
+ return f"<{class_name} {id_}>"
+
def check_connectivity_state(self, bint try_to_connect):
"""A Cython wrapper for Core's check connectivity state API."""
if self._status == AIO_CHANNEL_STATUS_DESTROYED:
@@ -102,10 +102,10 @@ cdef class AioChannel:
def closing(self):
self._status = AIO_CHANNEL_STATUS_CLOSING
- def close(self):
+ def close(self):
self._status = AIO_CHANNEL_STATUS_DESTROYED
- grpc_channel_destroy(self.channel)
-
+ grpc_channel_destroy(self.channel)
+
def closed(self):
return self._status in (AIO_CHANNEL_STATUS_CLOSING, AIO_CHANNEL_STATUS_DESTROYED)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pxd.pxi
index ebf0660174..d2941b6044 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pxd.pxi
@@ -1,18 +1,18 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# distutils: language=c++
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# distutils: language=c++
+
cdef class _AioState:
cdef object lock # threading.RLock
cdef int refcount
@@ -29,15 +29,15 @@ cpdef init_grpc_aio()
cpdef shutdown_grpc_aio()
-cdef extern from "src/core/lib/iomgr/timer_manager.h":
+cdef extern from "src/core/lib/iomgr/timer_manager.h":
void grpc_timer_manager_set_threading(bint enabled)
+
-
-cdef extern from "src/core/lib/iomgr/iomgr_internal.h":
+cdef extern from "src/core/lib/iomgr/iomgr_internal.h":
void grpc_set_default_iomgr_platform()
+
-
-cdef extern from "src/core/lib/iomgr/executor.h" namespace "grpc_core":
- cdef cppclass Executor:
- @staticmethod
+cdef extern from "src/core/lib/iomgr/executor.h" namespace "grpc_core":
+ cdef cppclass Executor:
+ @staticmethod
void SetThreadingAll(bint enable)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pyx.pxi
index 06c92cac58..ea9b7b9a0e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/grpc_aio.pyx.pxi
@@ -1,28 +1,28 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import enum
-
+
cdef str _GRPC_ASYNCIO_ENGINE = os.environ.get('GRPC_ASYNCIO_ENGINE', 'poller').upper()
cdef _AioState _global_aio_state = _AioState()
-
-
+
+
class AsyncIOEngine(enum.Enum):
CUSTOM_IO_MANAGER = 'custom_io_manager'
POLLER = 'poller'
-
-
+
+
cdef _default_asyncio_engine():
return AsyncIOEngine.POLLER
@@ -45,20 +45,20 @@ cdef _initialize_custom_io_manager():
# NOTE(lidiz) Custom IO manager must be activated before the first
# `grpc_init()`. Otherwise, some special configurations in Core won't
# pick up the change, and resulted in SEGFAULT or ABORT.
- install_asyncio_iomgr()
+ install_asyncio_iomgr()
# Initializes gRPC Core, must be called before other Core API
- grpc_init()
-
- # Timers are triggered by the Asyncio loop. We disable
- # the background thread that is being used by the native
- # gRPC iomgr.
+ grpc_init()
+
+ # Timers are triggered by the Asyncio loop. We disable
+ # the background thread that is being used by the native
+ # gRPC iomgr.
grpc_timer_manager_set_threading(False)
-
- # gRPC callbaks are executed within the same thread used by the Asyncio
- # event loop, as it is being done by the other Asyncio callbacks.
+
+ # gRPC callbaks are executed within the same thread used by the Asyncio
+ # event loop, as it is being done by the other Asyncio callbacks.
Executor.SetThreadingAll(False)
-
+
# Creates the only completion queue
_global_aio_state.cq = CallbackCompletionQueue()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/iomgr.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/iomgr.pyx.pxi
index 917ae24e11..c3b1e2fe75 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/iomgr.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/iomgr.pyx.pxi
@@ -1,217 +1,217 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import platform
-from cpython cimport Py_INCREF, Py_DECREF
-from libc cimport string
-
-import socket as native_socket
-try:
- import ipaddress # CPython 3.3 and above
-except ImportError:
- pass
-
-cdef grpc_socket_vtable asyncio_socket_vtable
-cdef grpc_custom_resolver_vtable asyncio_resolver_vtable
-cdef grpc_custom_timer_vtable asyncio_timer_vtable
-cdef grpc_custom_poller_vtable asyncio_pollset_vtable
+from cpython cimport Py_INCREF, Py_DECREF
+from libc cimport string
+
+import socket as native_socket
+try:
+ import ipaddress # CPython 3.3 and above
+except ImportError:
+ pass
+
+cdef grpc_socket_vtable asyncio_socket_vtable
+cdef grpc_custom_resolver_vtable asyncio_resolver_vtable
+cdef grpc_custom_timer_vtable asyncio_timer_vtable
+cdef grpc_custom_poller_vtable asyncio_pollset_vtable
cdef bint so_reuse_port
-
-
-cdef grpc_error* asyncio_socket_init(
- grpc_custom_socket* grpc_socket,
- int domain) with gil:
- socket = _AsyncioSocket.create(grpc_socket, None, None)
- Py_INCREF(socket)
- grpc_socket.impl = <void*>socket
- return <grpc_error*>0
-
-
-cdef void asyncio_socket_destroy(grpc_custom_socket* grpc_socket) with gil:
- Py_DECREF(<_AsyncioSocket>grpc_socket.impl)
-
-
-cdef void asyncio_socket_connect(
- grpc_custom_socket* grpc_socket,
- const grpc_sockaddr* addr,
- size_t addr_len,
- grpc_custom_connect_callback connect_cb) with gil:
- host, port = sockaddr_to_tuple(addr, addr_len)
- socket = <_AsyncioSocket>grpc_socket.impl
- socket.connect(host, port, connect_cb)
-
-
-cdef void asyncio_socket_close(
- grpc_custom_socket* grpc_socket,
- grpc_custom_close_callback close_cb) with gil:
- socket = (<_AsyncioSocket>grpc_socket.impl)
- socket.close()
- close_cb(grpc_socket)
-
-
-cdef void asyncio_socket_shutdown(grpc_custom_socket* grpc_socket) with gil:
- socket = (<_AsyncioSocket>grpc_socket.impl)
- socket.close()
-
-
-cdef void asyncio_socket_write(
- grpc_custom_socket* grpc_socket,
- grpc_slice_buffer* slice_buffer,
- grpc_custom_write_callback write_cb) with gil:
- socket = (<_AsyncioSocket>grpc_socket.impl)
- socket.write(slice_buffer, write_cb)
-
-
-cdef void asyncio_socket_read(
- grpc_custom_socket* grpc_socket,
- char* buffer_,
- size_t length,
- grpc_custom_read_callback read_cb) with gil:
- socket = (<_AsyncioSocket>grpc_socket.impl)
- socket.read(buffer_, length, read_cb)
-
-
-cdef grpc_error* asyncio_socket_getpeername(
- grpc_custom_socket* grpc_socket,
- const grpc_sockaddr* addr,
- int* length) with gil:
- peer = (<_AsyncioSocket>grpc_socket.impl).peername()
-
- cdef grpc_resolved_address c_addr
- hostname = str_to_bytes(peer[0])
- grpc_string_to_sockaddr(&c_addr, hostname, peer[1])
- # TODO(https://github.com/grpc/grpc/issues/20684) Remove the memcpy
- string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len)
- length[0] = c_addr.len
- return grpc_error_none()
-
-
-cdef grpc_error* asyncio_socket_getsockname(
- grpc_custom_socket* grpc_socket,
- const grpc_sockaddr* addr,
- int* length) with gil:
- """Supplies sock_addr in add_socket_to_server."""
- cdef grpc_resolved_address c_addr
- socket = (<_AsyncioSocket>grpc_socket.impl)
- if socket is None:
- peer = ('0.0.0.0', 0)
- else:
- peer = socket.sockname()
- hostname = str_to_bytes(peer[0])
- grpc_string_to_sockaddr(&c_addr, hostname, peer[1])
- # TODO(https://github.com/grpc/grpc/issues/20684) Remove the memcpy
- string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len)
- length[0] = c_addr.len
- return grpc_error_none()
-
-
-cdef grpc_error* asyncio_socket_listen(grpc_custom_socket* grpc_socket) with gil:
- (<_AsyncioSocket>grpc_socket.impl).listen()
- return grpc_error_none()
-
-
+
+
+cdef grpc_error* asyncio_socket_init(
+ grpc_custom_socket* grpc_socket,
+ int domain) with gil:
+ socket = _AsyncioSocket.create(grpc_socket, None, None)
+ Py_INCREF(socket)
+ grpc_socket.impl = <void*>socket
+ return <grpc_error*>0
+
+
+cdef void asyncio_socket_destroy(grpc_custom_socket* grpc_socket) with gil:
+ Py_DECREF(<_AsyncioSocket>grpc_socket.impl)
+
+
+cdef void asyncio_socket_connect(
+ grpc_custom_socket* grpc_socket,
+ const grpc_sockaddr* addr,
+ size_t addr_len,
+ grpc_custom_connect_callback connect_cb) with gil:
+ host, port = sockaddr_to_tuple(addr, addr_len)
+ socket = <_AsyncioSocket>grpc_socket.impl
+ socket.connect(host, port, connect_cb)
+
+
+cdef void asyncio_socket_close(
+ grpc_custom_socket* grpc_socket,
+ grpc_custom_close_callback close_cb) with gil:
+ socket = (<_AsyncioSocket>grpc_socket.impl)
+ socket.close()
+ close_cb(grpc_socket)
+
+
+cdef void asyncio_socket_shutdown(grpc_custom_socket* grpc_socket) with gil:
+ socket = (<_AsyncioSocket>grpc_socket.impl)
+ socket.close()
+
+
+cdef void asyncio_socket_write(
+ grpc_custom_socket* grpc_socket,
+ grpc_slice_buffer* slice_buffer,
+ grpc_custom_write_callback write_cb) with gil:
+ socket = (<_AsyncioSocket>grpc_socket.impl)
+ socket.write(slice_buffer, write_cb)
+
+
+cdef void asyncio_socket_read(
+ grpc_custom_socket* grpc_socket,
+ char* buffer_,
+ size_t length,
+ grpc_custom_read_callback read_cb) with gil:
+ socket = (<_AsyncioSocket>grpc_socket.impl)
+ socket.read(buffer_, length, read_cb)
+
+
+cdef grpc_error* asyncio_socket_getpeername(
+ grpc_custom_socket* grpc_socket,
+ const grpc_sockaddr* addr,
+ int* length) with gil:
+ peer = (<_AsyncioSocket>grpc_socket.impl).peername()
+
+ cdef grpc_resolved_address c_addr
+ hostname = str_to_bytes(peer[0])
+ grpc_string_to_sockaddr(&c_addr, hostname, peer[1])
+ # TODO(https://github.com/grpc/grpc/issues/20684) Remove the memcpy
+ string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len)
+ length[0] = c_addr.len
+ return grpc_error_none()
+
+
+cdef grpc_error* asyncio_socket_getsockname(
+ grpc_custom_socket* grpc_socket,
+ const grpc_sockaddr* addr,
+ int* length) with gil:
+ """Supplies sock_addr in add_socket_to_server."""
+ cdef grpc_resolved_address c_addr
+ socket = (<_AsyncioSocket>grpc_socket.impl)
+ if socket is None:
+ peer = ('0.0.0.0', 0)
+ else:
+ peer = socket.sockname()
+ hostname = str_to_bytes(peer[0])
+ grpc_string_to_sockaddr(&c_addr, hostname, peer[1])
+ # TODO(https://github.com/grpc/grpc/issues/20684) Remove the memcpy
+ string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len)
+ length[0] = c_addr.len
+ return grpc_error_none()
+
+
+cdef grpc_error* asyncio_socket_listen(grpc_custom_socket* grpc_socket) with gil:
+ (<_AsyncioSocket>grpc_socket.impl).listen()
+ return grpc_error_none()
+
+
def _asyncio_apply_socket_options(object s, int flags):
# Turn SO_REUSEADDR on for TCP sockets; if we want to support UDS, we will
# need to update this function.
- s.setsockopt(native_socket.SOL_SOCKET, native_socket.SO_REUSEADDR, 1)
+ s.setsockopt(native_socket.SOL_SOCKET, native_socket.SO_REUSEADDR, 1)
# SO_REUSEPORT only available in POSIX systems.
if platform.system() != 'Windows':
if GRPC_CUSTOM_SOCKET_OPT_SO_REUSEPORT & flags:
s.setsockopt(native_socket.SOL_SOCKET, native_socket.SO_REUSEPORT, 1)
- s.setsockopt(native_socket.IPPROTO_TCP, native_socket.TCP_NODELAY, True)
-
-
-cdef grpc_error* asyncio_socket_bind(
- grpc_custom_socket* grpc_socket,
- const grpc_sockaddr* addr,
- size_t len, int flags) with gil:
- host, port = sockaddr_to_tuple(addr, len)
- try:
- ip = ipaddress.ip_address(host)
- if isinstance(ip, ipaddress.IPv6Address):
- family = native_socket.AF_INET6
- else:
- family = native_socket.AF_INET
-
- socket = native_socket.socket(family=family)
+ s.setsockopt(native_socket.IPPROTO_TCP, native_socket.TCP_NODELAY, True)
+
+
+cdef grpc_error* asyncio_socket_bind(
+ grpc_custom_socket* grpc_socket,
+ const grpc_sockaddr* addr,
+ size_t len, int flags) with gil:
+ host, port = sockaddr_to_tuple(addr, len)
+ try:
+ ip = ipaddress.ip_address(host)
+ if isinstance(ip, ipaddress.IPv6Address):
+ family = native_socket.AF_INET6
+ else:
+ family = native_socket.AF_INET
+
+ socket = native_socket.socket(family=family)
_asyncio_apply_socket_options(socket, flags)
- socket.bind((host, port))
- except IOError as io_error:
+ socket.bind((host, port))
+ except IOError as io_error:
socket.close()
- return socket_error("bind", str(io_error))
- else:
- aio_socket = _AsyncioSocket.create_with_py_socket(grpc_socket, socket)
- cpython.Py_INCREF(aio_socket) # Py_DECREF in asyncio_socket_destroy
- grpc_socket.impl = <void*>aio_socket
- return grpc_error_none()
-
-
-cdef void asyncio_socket_accept(
- grpc_custom_socket* grpc_socket,
- grpc_custom_socket* grpc_socket_client,
- grpc_custom_accept_callback accept_cb) with gil:
- (<_AsyncioSocket>grpc_socket.impl).accept(grpc_socket_client, accept_cb)
-
-
-cdef grpc_error* asyncio_resolve(
+ return socket_error("bind", str(io_error))
+ else:
+ aio_socket = _AsyncioSocket.create_with_py_socket(grpc_socket, socket)
+ cpython.Py_INCREF(aio_socket) # Py_DECREF in asyncio_socket_destroy
+ grpc_socket.impl = <void*>aio_socket
+ return grpc_error_none()
+
+
+cdef void asyncio_socket_accept(
+ grpc_custom_socket* grpc_socket,
+ grpc_custom_socket* grpc_socket_client,
+ grpc_custom_accept_callback accept_cb) with gil:
+ (<_AsyncioSocket>grpc_socket.impl).accept(grpc_socket_client, accept_cb)
+
+
+cdef grpc_error* asyncio_resolve(
const char* host,
const char* port,
- grpc_resolved_addresses** res) with gil:
- result = native_socket.getaddrinfo(host, port)
- res[0] = tuples_to_resolvaddr(result)
-
-
-cdef void asyncio_resolve_async(
- grpc_custom_resolver* grpc_resolver,
+ grpc_resolved_addresses** res) with gil:
+ result = native_socket.getaddrinfo(host, port)
+ res[0] = tuples_to_resolvaddr(result)
+
+
+cdef void asyncio_resolve_async(
+ grpc_custom_resolver* grpc_resolver,
const char* host,
const char* port) with gil:
- resolver = _AsyncioResolver.create(grpc_resolver)
- resolver.resolve(host, port)
-
-
-cdef void asyncio_timer_start(grpc_custom_timer* grpc_timer) with gil:
- timer = _AsyncioTimer.create(grpc_timer, grpc_timer.timeout_ms / 1000.0)
- grpc_timer.timer = <void*>timer
-
-
-cdef void asyncio_timer_stop(grpc_custom_timer* grpc_timer) with gil:
+ resolver = _AsyncioResolver.create(grpc_resolver)
+ resolver.resolve(host, port)
+
+
+cdef void asyncio_timer_start(grpc_custom_timer* grpc_timer) with gil:
+ timer = _AsyncioTimer.create(grpc_timer, grpc_timer.timeout_ms / 1000.0)
+ grpc_timer.timer = <void*>timer
+
+
+cdef void asyncio_timer_stop(grpc_custom_timer* grpc_timer) with gil:
# TODO(https://github.com/grpc/grpc/issues/22278) remove this if condition
if grpc_timer.timer == NULL:
return
else:
timer = <_AsyncioTimer>grpc_timer.timer
timer.stop()
-
-
-cdef void asyncio_init_loop() with gil:
- pass
-
-
-cdef void asyncio_destroy_loop() with gil:
- pass
-
-
-cdef void asyncio_kick_loop() with gil:
- pass
-
-
-cdef void asyncio_run_loop(size_t timeout_ms) with gil:
- pass
-
-
+
+
+cdef void asyncio_init_loop() with gil:
+ pass
+
+
+cdef void asyncio_destroy_loop() with gil:
+ pass
+
+
+cdef void asyncio_kick_loop() with gil:
+ pass
+
+
+cdef void asyncio_run_loop(size_t timeout_ms) with gil:
+ pass
+
+
def _auth_plugin_callback_wrapper(object cb,
str service_url,
str method_name,
@@ -219,38 +219,38 @@ def _auth_plugin_callback_wrapper(object cb,
get_working_loop().call_soon(cb, service_url, method_name, callback)
-def install_asyncio_iomgr():
+def install_asyncio_iomgr():
# Auth plugins invoke user provided logic in another thread by default. We
# need to override that behavior by registering the call to the event loop.
set_async_callback_func(_auth_plugin_callback_wrapper)
- asyncio_resolver_vtable.resolve = asyncio_resolve
- asyncio_resolver_vtable.resolve_async = asyncio_resolve_async
-
- asyncio_socket_vtable.init = asyncio_socket_init
- asyncio_socket_vtable.connect = asyncio_socket_connect
- asyncio_socket_vtable.destroy = asyncio_socket_destroy
- asyncio_socket_vtable.shutdown = asyncio_socket_shutdown
- asyncio_socket_vtable.close = asyncio_socket_close
- asyncio_socket_vtable.write = asyncio_socket_write
- asyncio_socket_vtable.read = asyncio_socket_read
- asyncio_socket_vtable.getpeername = asyncio_socket_getpeername
- asyncio_socket_vtable.getsockname = asyncio_socket_getsockname
- asyncio_socket_vtable.bind = asyncio_socket_bind
- asyncio_socket_vtable.listen = asyncio_socket_listen
- asyncio_socket_vtable.accept = asyncio_socket_accept
-
- asyncio_timer_vtable.start = asyncio_timer_start
- asyncio_timer_vtable.stop = asyncio_timer_stop
-
- asyncio_pollset_vtable.init = asyncio_init_loop
- asyncio_pollset_vtable.poll = asyncio_run_loop
- asyncio_pollset_vtable.kick = asyncio_kick_loop
- asyncio_pollset_vtable.shutdown = asyncio_destroy_loop
-
- grpc_custom_iomgr_init(
- &asyncio_socket_vtable,
- &asyncio_resolver_vtable,
- &asyncio_timer_vtable,
- &asyncio_pollset_vtable
- )
+ asyncio_resolver_vtable.resolve = asyncio_resolve
+ asyncio_resolver_vtable.resolve_async = asyncio_resolve_async
+
+ asyncio_socket_vtable.init = asyncio_socket_init
+ asyncio_socket_vtable.connect = asyncio_socket_connect
+ asyncio_socket_vtable.destroy = asyncio_socket_destroy
+ asyncio_socket_vtable.shutdown = asyncio_socket_shutdown
+ asyncio_socket_vtable.close = asyncio_socket_close
+ asyncio_socket_vtable.write = asyncio_socket_write
+ asyncio_socket_vtable.read = asyncio_socket_read
+ asyncio_socket_vtable.getpeername = asyncio_socket_getpeername
+ asyncio_socket_vtable.getsockname = asyncio_socket_getsockname
+ asyncio_socket_vtable.bind = asyncio_socket_bind
+ asyncio_socket_vtable.listen = asyncio_socket_listen
+ asyncio_socket_vtable.accept = asyncio_socket_accept
+
+ asyncio_timer_vtable.start = asyncio_timer_start
+ asyncio_timer_vtable.stop = asyncio_timer_stop
+
+ asyncio_pollset_vtable.init = asyncio_init_loop
+ asyncio_pollset_vtable.poll = asyncio_run_loop
+ asyncio_pollset_vtable.kick = asyncio_kick_loop
+ asyncio_pollset_vtable.shutdown = asyncio_destroy_loop
+
+ grpc_custom_iomgr_init(
+ &asyncio_socket_vtable,
+ &asyncio_resolver_vtable,
+ &asyncio_timer_vtable,
+ &asyncio_pollset_vtable
+ )
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pxd.pxi
index 51730c1597..61449745d0 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pxd.pxi
@@ -1,24 +1,24 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-cdef class _AsyncioResolver:
- cdef:
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+cdef class _AsyncioResolver:
+ cdef:
object _loop
- grpc_custom_resolver* _grpc_resolver
- object _task_resolve
-
- @staticmethod
- cdef _AsyncioResolver create(grpc_custom_resolver* grpc_resolver)
-
+ grpc_custom_resolver* _grpc_resolver
+ object _task_resolve
+
+ @staticmethod
+ cdef _AsyncioResolver create(grpc_custom_resolver* grpc_resolver)
+
cdef void resolve(self, const char* host, const char* port)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pyx.pxi
index 1a2e244ff9..70f6a86026 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/resolver.pyx.pxi
@@ -1,56 +1,56 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-cdef class _AsyncioResolver:
- def __cinit__(self):
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+cdef class _AsyncioResolver:
+ def __cinit__(self):
self._loop = get_working_loop()
- self._grpc_resolver = NULL
- self._task_resolve = None
-
- @staticmethod
- cdef _AsyncioResolver create(grpc_custom_resolver* grpc_resolver):
- resolver = _AsyncioResolver()
- resolver._grpc_resolver = grpc_resolver
- return resolver
-
- def __repr__(self):
- class_name = self.__class__.__name__
- id_ = id(self)
- return f"<{class_name} {id_}>"
-
+ self._grpc_resolver = NULL
+ self._task_resolve = None
+
+ @staticmethod
+ cdef _AsyncioResolver create(grpc_custom_resolver* grpc_resolver):
+ resolver = _AsyncioResolver()
+ resolver._grpc_resolver = grpc_resolver
+ return resolver
+
+ def __repr__(self):
+ class_name = self.__class__.__name__
+ id_ = id(self)
+ return f"<{class_name} {id_}>"
+
async def _async_resolve(self, bytes host, bytes port):
self._task_resolve = None
- try:
+ try:
resolved = await self._loop.getaddrinfo(host, port)
- except Exception as e:
- grpc_custom_resolve_callback(
- <grpc_custom_resolver*>self._grpc_resolver,
+ except Exception as e:
+ grpc_custom_resolve_callback(
+ <grpc_custom_resolver*>self._grpc_resolver,
NULL,
grpc_socket_error("Resolve address [{}:{}] failed: {}: {}".format(
host, port, type(e), str(e)).encode())
- )
- else:
- grpc_custom_resolve_callback(
- <grpc_custom_resolver*>self._grpc_resolver,
+ )
+ else:
+ grpc_custom_resolve_callback(
+ <grpc_custom_resolver*>self._grpc_resolver,
tuples_to_resolvaddr(resolved),
<grpc_error*>0
- )
-
+ )
+
cdef void resolve(self, const char* host, const char* port):
- assert not self._task_resolve
-
+ assert not self._task_resolve
+
self._task_resolve = self._loop.create_task(
self._async_resolve(host, port)
- )
+ )
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pxd.pxi
index cfab5549b2..c08f7ace31 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pxd.pxi
@@ -1,63 +1,63 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-cdef class _AsyncioSocket:
- cdef:
- # Common attributes
- grpc_custom_socket * _grpc_socket
- grpc_custom_read_callback _grpc_read_cb
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+cdef class _AsyncioSocket:
+ cdef:
+ # Common attributes
+ grpc_custom_socket * _grpc_socket
+ grpc_custom_read_callback _grpc_read_cb
grpc_custom_write_callback _grpc_write_cb
- object _reader
- object _writer
- object _task_read
+ object _reader
+ object _writer
+ object _task_read
object _task_write
- object _task_connect
+ object _task_connect
object _task_listen
- char * _read_buffer
+ char * _read_buffer
# Caches the picked event loop, so we can avoid the 30ns overhead each
# time we need access to the event loop.
object _loop
# TODO(lidiz) Drop after 3.6 deprecation. Python 3.7 introduces methods
# like `is_closing()` to help graceful shutdown.
bint _closed
-
- # Client-side attributes
- grpc_custom_connect_callback _grpc_connect_cb
-
- # Server-side attributes
- grpc_custom_accept_callback _grpc_accept_cb
- grpc_custom_socket * _grpc_client_socket
- object _server
- object _py_socket
- object _peername
-
- @staticmethod
- cdef _AsyncioSocket create(
- grpc_custom_socket * grpc_socket,
- object reader,
- object writer)
- @staticmethod
- cdef _AsyncioSocket create_with_py_socket(grpc_custom_socket * grpc_socket, object py_socket)
-
- cdef void connect(self, object host, object port, grpc_custom_connect_callback grpc_connect_cb)
- cdef void write(self, grpc_slice_buffer * g_slice_buffer, grpc_custom_write_callback grpc_write_cb)
- cdef void read(self, char * buffer_, size_t length, grpc_custom_read_callback grpc_read_cb)
- cdef bint is_connected(self)
- cdef void close(self)
-
- cdef accept(self, grpc_custom_socket* grpc_socket_client, grpc_custom_accept_callback grpc_accept_cb)
- cdef listen(self)
- cdef tuple peername(self)
- cdef tuple sockname(self)
+
+ # Client-side attributes
+ grpc_custom_connect_callback _grpc_connect_cb
+
+ # Server-side attributes
+ grpc_custom_accept_callback _grpc_accept_cb
+ grpc_custom_socket * _grpc_client_socket
+ object _server
+ object _py_socket
+ object _peername
+
+ @staticmethod
+ cdef _AsyncioSocket create(
+ grpc_custom_socket * grpc_socket,
+ object reader,
+ object writer)
+ @staticmethod
+ cdef _AsyncioSocket create_with_py_socket(grpc_custom_socket * grpc_socket, object py_socket)
+
+ cdef void connect(self, object host, object port, grpc_custom_connect_callback grpc_connect_cb)
+ cdef void write(self, grpc_slice_buffer * g_slice_buffer, grpc_custom_write_callback grpc_write_cb)
+ cdef void read(self, char * buffer_, size_t length, grpc_custom_read_callback grpc_read_cb)
+ cdef bint is_connected(self)
+ cdef void close(self)
+
+ cdef accept(self, grpc_custom_socket* grpc_socket_client, grpc_custom_accept_callback grpc_accept_cb)
+ cdef listen(self)
+ cdef tuple peername(self)
+ cdef tuple sockname(self)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pyx.pxi
index eecef17d98..68d3d55d92 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/socket.pyx.pxi
@@ -1,74 +1,74 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import socket as native_socket
-
-from libc cimport string
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import socket as native_socket
+
+from libc cimport string
+
cdef int _ASYNCIO_STREAM_DEFAULT_SOCKET_BACKLOG = 100
# TODO(https://github.com/grpc/grpc/issues/21348) Better flow control needed.
-cdef class _AsyncioSocket:
- def __cinit__(self):
- self._grpc_socket = NULL
- self._grpc_connect_cb = NULL
- self._grpc_read_cb = NULL
+cdef class _AsyncioSocket:
+ def __cinit__(self):
+ self._grpc_socket = NULL
+ self._grpc_connect_cb = NULL
+ self._grpc_read_cb = NULL
self._grpc_write_cb = NULL
- self._reader = None
- self._writer = None
- self._task_connect = None
- self._task_read = None
+ self._reader = None
+ self._writer = None
+ self._task_connect = None
+ self._task_read = None
self._task_write = None
self._task_listen = None
- self._read_buffer = NULL
- self._server = None
- self._py_socket = None
- self._peername = None
+ self._read_buffer = NULL
+ self._server = None
+ self._py_socket = None
+ self._peername = None
self._closed = False
self._loop = get_working_loop()
-
- @staticmethod
- cdef _AsyncioSocket create(grpc_custom_socket * grpc_socket,
- object reader,
- object writer):
- socket = _AsyncioSocket()
- socket._grpc_socket = grpc_socket
- socket._reader = reader
- socket._writer = writer
- if writer is not None:
- socket._peername = writer.get_extra_info('peername')
- return socket
-
- @staticmethod
- cdef _AsyncioSocket create_with_py_socket(grpc_custom_socket * grpc_socket, object py_socket):
- socket = _AsyncioSocket()
- socket._grpc_socket = grpc_socket
- socket._py_socket = py_socket
- return socket
-
- def __repr__(self):
- class_name = self.__class__.__name__
- id_ = id(self)
- connected = self.is_connected()
- return f"<{class_name} {id_} connected={connected}>"
-
+
+ @staticmethod
+ cdef _AsyncioSocket create(grpc_custom_socket * grpc_socket,
+ object reader,
+ object writer):
+ socket = _AsyncioSocket()
+ socket._grpc_socket = grpc_socket
+ socket._reader = reader
+ socket._writer = writer
+ if writer is not None:
+ socket._peername = writer.get_extra_info('peername')
+ return socket
+
+ @staticmethod
+ cdef _AsyncioSocket create_with_py_socket(grpc_custom_socket * grpc_socket, object py_socket):
+ socket = _AsyncioSocket()
+ socket._grpc_socket = grpc_socket
+ socket._py_socket = py_socket
+ return socket
+
+ def __repr__(self):
+ class_name = self.__class__.__name__
+ id_ = id(self)
+ connected = self.is_connected()
+ return f"<{class_name} {id_} connected={connected}>"
+
async def _async_connect(self, object host, object port,):
self._task_connect = None
- try:
+ try:
self._reader, self._writer = await asyncio.open_connection(host, port)
- except Exception as e:
+ except Exception as e:
self._grpc_connect_cb(
<grpc_custom_socket*>self._grpc_socket,
grpc_socket_error("Socket connect failed: {}: {}".format(type(e), str(e)).encode())
@@ -78,12 +78,12 @@ cdef class _AsyncioSocket:
# algorithm.
sock = self._writer.transport.get_extra_info('socket')
sock.setsockopt(native_socket.IPPROTO_TCP, native_socket.TCP_NODELAY, True)
-
+
self._grpc_connect_cb(
<grpc_custom_socket*>self._grpc_socket,
<grpc_error*>0
)
-
+
cdef void connect(self,
object host,
object port,
@@ -95,10 +95,10 @@ cdef class _AsyncioSocket:
self._async_connect(host, port)
)
self._grpc_connect_cb = grpc_connect_cb
-
+
async def _async_read(self, size_t length):
self._task_read = None
- try:
+ try:
inbound_buffer = await self._reader.read(n=length)
except ConnectionError as e:
self._grpc_read_cb(
@@ -107,22 +107,22 @@ cdef class _AsyncioSocket:
grpc_socket_error("Read failed: {}".format(e).encode())
)
else:
- string.memcpy(
- <void*>self._read_buffer,
+ string.memcpy(
+ <void*>self._read_buffer,
<char*>inbound_buffer,
len(inbound_buffer)
- )
- self._grpc_read_cb(
- <grpc_custom_socket*>self._grpc_socket,
+ )
+ self._grpc_read_cb(
+ <grpc_custom_socket*>self._grpc_socket,
len(inbound_buffer),
- <grpc_error*>0
- )
-
- cdef void read(self, char * buffer_, size_t length, grpc_custom_read_callback grpc_read_cb):
- assert not self._task_read
-
- self._grpc_read_cb = grpc_read_cb
- self._read_buffer = buffer_
+ <grpc_error*>0
+ )
+
+ cdef void read(self, char * buffer_, size_t length, grpc_custom_read_callback grpc_read_cb):
+ assert not self._task_read
+
+ self._grpc_read_cb = grpc_read_cb
+ self._read_buffer = buffer_
self._task_read = self._loop.create_task(self._async_read(length))
async def _async_write(self, bytearray outbound_buffer):
@@ -140,7 +140,7 @@ cdef class _AsyncioSocket:
grpc_socket_error("Socket write failed: {}".format(connection_error).encode()),
)
- cdef void write(self, grpc_slice_buffer * g_slice_buffer, grpc_custom_write_callback grpc_write_cb):
+ cdef void write(self, grpc_slice_buffer * g_slice_buffer, grpc_custom_write_callback grpc_write_cb):
"""Performs write to network socket in AsyncIO.
For each socket, Core guarantees there'll be only one ongoing write.
@@ -148,37 +148,37 @@ cdef class _AsyncioSocket:
Core that the work is done.
"""
assert not self._task_write
- cdef char* start
+ cdef char* start
cdef bytearray outbound_buffer = bytearray()
- for i in range(g_slice_buffer.count):
- start = grpc_slice_buffer_start(g_slice_buffer, i)
- length = grpc_slice_buffer_length(g_slice_buffer, i)
+ for i in range(g_slice_buffer.count):
+ start = grpc_slice_buffer_start(g_slice_buffer, i)
+ length = grpc_slice_buffer_length(g_slice_buffer, i)
outbound_buffer.extend(<bytes>start[:length])
-
+
self._grpc_write_cb = grpc_write_cb
self._task_write = self._loop.create_task(self._async_write(outbound_buffer))
-
- cdef bint is_connected(self):
- return self._reader and not self._reader._transport.is_closing()
-
- cdef void close(self):
+
+ cdef bint is_connected(self):
+ return self._reader and not self._reader._transport.is_closing()
+
+ cdef void close(self):
if self._closed:
return
else:
self._closed = True
- if self.is_connected():
- self._writer.close()
+ if self.is_connected():
+ self._writer.close()
if self._task_listen and not self._task_listen.done():
self._task_listen.close()
- if self._server:
- self._server.close()
- # NOTE(lidiz) If the asyncio.Server is created from a Python socket,
- # the server.close() won't release the fd until the close() is called
- # for the Python socket.
- if self._py_socket:
- self._py_socket.close()
-
- def _new_connection_callback(self, object reader, object writer):
+ if self._server:
+ self._server.close()
+ # NOTE(lidiz) If the asyncio.Server is created from a Python socket,
+ # the server.close() won't release the fd until the close() is called
+ # for the Python socket.
+ if self._py_socket:
+ self._py_socket.close()
+
+ def _new_connection_callback(self, object reader, object writer):
# If the socket is closed, stop.
if self._closed:
return
@@ -188,38 +188,38 @@ cdef class _AsyncioSocket:
writer.close()
return
- client_socket = _AsyncioSocket.create(
- self._grpc_client_socket,
- reader,
- writer,
- )
-
- self._grpc_client_socket.impl = <void*>client_socket
- cpython.Py_INCREF(client_socket) # Py_DECREF in asyncio_socket_destroy
- # Accept callback expects to be called with:
+ client_socket = _AsyncioSocket.create(
+ self._grpc_client_socket,
+ reader,
+ writer,
+ )
+
+ self._grpc_client_socket.impl = <void*>client_socket
+ cpython.Py_INCREF(client_socket) # Py_DECREF in asyncio_socket_destroy
+ # Accept callback expects to be called with:
# * grpc_custom_socket: A grpc custom socket for server
# * grpc_custom_socket: A grpc custom socket for client (with new Socket instance)
# * grpc_error: An error object
- self._grpc_accept_cb(self._grpc_socket, self._grpc_client_socket, grpc_error_none())
-
- cdef listen(self):
+ self._grpc_accept_cb(self._grpc_socket, self._grpc_client_socket, grpc_error_none())
+
+ cdef listen(self):
self._py_socket.listen(_ASYNCIO_STREAM_DEFAULT_SOCKET_BACKLOG)
- async def create_asyncio_server():
- self._server = await asyncio.start_server(
- self._new_connection_callback,
- sock=self._py_socket,
- )
-
+ async def create_asyncio_server():
+ self._server = await asyncio.start_server(
+ self._new_connection_callback,
+ sock=self._py_socket,
+ )
+
self._task_listen = self._loop.create_task(create_asyncio_server())
-
- cdef accept(self,
- grpc_custom_socket* grpc_socket_client,
- grpc_custom_accept_callback grpc_accept_cb):
- self._grpc_client_socket = grpc_socket_client
- self._grpc_accept_cb = grpc_accept_cb
-
- cdef tuple peername(self):
- return self._peername
-
- cdef tuple sockname(self):
- return self._py_socket.getsockname()
+
+ cdef accept(self,
+ grpc_custom_socket* grpc_socket_client,
+ grpc_custom_accept_callback grpc_accept_cb):
+ self._grpc_client_socket = grpc_socket_client
+ self._grpc_accept_cb = grpc_accept_cb
+
+ cdef tuple peername(self):
+ return self._peername
+
+ cdef tuple sockname(self):
+ return self._py_socket.getsockname()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pxd.pxi
index 76c3be0c57..1079411402 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pxd.pxi
@@ -1,25 +1,25 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-cdef class _AsyncioTimer:
- cdef:
- grpc_custom_timer * _grpc_timer
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+cdef class _AsyncioTimer:
+ cdef:
+ grpc_custom_timer * _grpc_timer
object _timer_future
bint _active
object _loop
-
- @staticmethod
+
+ @staticmethod
cdef _AsyncioTimer create(grpc_custom_timer * grpc_timer, float timeout)
-
- cdef stop(self)
+
+ cdef stop(self)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pyx.pxi
index c1508373a4..bace27429f 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/iomgr/timer.pyx.pxi
@@ -1,48 +1,48 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-cdef class _AsyncioTimer:
- def __cinit__(self):
- self._grpc_timer = NULL
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+cdef class _AsyncioTimer:
+ def __cinit__(self):
+ self._grpc_timer = NULL
self._timer_future = None
self._active = False
self._loop = get_working_loop()
cpython.Py_INCREF(self)
-
- @staticmethod
+
+ @staticmethod
cdef _AsyncioTimer create(grpc_custom_timer * grpc_timer, float timeout):
- timer = _AsyncioTimer()
- timer._grpc_timer = grpc_timer
+ timer = _AsyncioTimer()
+ timer._grpc_timer = grpc_timer
timer._timer_future = timer._loop.call_later(timeout, timer.on_time_up)
timer._active = True
- return timer
-
+ return timer
+
def on_time_up(self):
self._active = False
- grpc_custom_timer_callback(self._grpc_timer, <grpc_error*>0)
+ grpc_custom_timer_callback(self._grpc_timer, <grpc_error*>0)
cpython.Py_DECREF(self)
-
- def __repr__(self):
- class_name = self.__class__.__name__
- id_ = id(self)
- return f"<{class_name} {id_} deadline={self._deadline} active={self._active}>"
-
- cdef stop(self):
+
+ def __repr__(self):
+ class_name = self.__class__.__name__
+ id_ = id(self)
+ return f"<{class_name} {id_} deadline={self._deadline} active={self._active}>"
+
+ cdef stop(self):
if not self._active:
- return
-
+ return
+
self._timer_future.cancel()
self._active = False
cpython.Py_DECREF(self)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pxd.pxi
index 46a47bd1ba..4623c2340c 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pxd.pxi
@@ -1,25 +1,25 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-cdef class _HandlerCallDetails:
- cdef readonly str method
- cdef readonly tuple invocation_metadata
-
-
-cdef class RPCState(GrpcCallWrapper):
- cdef grpc_call_details details
- cdef grpc_metadata_array request_metadata
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+cdef class _HandlerCallDetails:
+ cdef readonly str method
+ cdef readonly tuple invocation_metadata
+
+
+cdef class RPCState(GrpcCallWrapper):
+ cdef grpc_call_details details
+ cdef grpc_metadata_array request_metadata
cdef AioServer server
# NOTE(lidiz) Under certain corner case, receiving the client close
# operation won't immediately fail ongoing RECV_MESSAGE operations. Here I
@@ -33,14 +33,14 @@ cdef class RPCState(GrpcCallWrapper):
cdef tuple trailing_metadata
cdef object compression_algorithm
cdef bint disable_next_compression
-
- cdef bytes method(self)
+
+ cdef bytes method(self)
cdef tuple invocation_metadata(self)
cdef void raise_for_termination(self) except *
cdef int get_write_flag(self)
cdef Operation create_send_initial_metadata_op_if_not_sent(self)
-
-
+
+
cdef class _ServicerContext:
cdef RPCState _rpc_state
cdef object _loop # asyncio.AbstractEventLoop
@@ -59,24 +59,24 @@ cdef class _MessageReceiver:
cdef object _agen
-cdef enum AioServerStatus:
- AIO_SERVER_STATUS_UNKNOWN
- AIO_SERVER_STATUS_READY
- AIO_SERVER_STATUS_RUNNING
- AIO_SERVER_STATUS_STOPPED
- AIO_SERVER_STATUS_STOPPING
-
-
-cdef class AioServer:
- cdef Server _server
- cdef list _generic_handlers
- cdef AioServerStatus _status
- cdef object _loop # asyncio.EventLoop
- cdef object _serving_task # asyncio.Task
- cdef object _shutdown_lock # asyncio.Lock
- cdef object _shutdown_completed # asyncio.Future
- cdef CallbackWrapper _shutdown_callback_wrapper
- cdef object _crash_exception # Exception
+cdef enum AioServerStatus:
+ AIO_SERVER_STATUS_UNKNOWN
+ AIO_SERVER_STATUS_READY
+ AIO_SERVER_STATUS_RUNNING
+ AIO_SERVER_STATUS_STOPPED
+ AIO_SERVER_STATUS_STOPPING
+
+
+cdef class AioServer:
+ cdef Server _server
+ cdef list _generic_handlers
+ cdef AioServerStatus _status
+ cdef object _loop # asyncio.EventLoop
+ cdef object _serving_task # asyncio.Task
+ cdef object _shutdown_lock # asyncio.Lock
+ cdef object _shutdown_completed # asyncio.Future
+ cdef CallbackWrapper _shutdown_callback_wrapper
+ cdef object _crash_exception # Exception
cdef tuple _interceptors
cdef object _thread_pool # concurrent.futures.ThreadPoolExecutor
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi
index a630ed8811..74a61f2a7a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi
@@ -1,27 +1,27 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import inspect
import traceback
import functools
-cdef int _EMPTY_FLAG = 0
+cdef int _EMPTY_FLAG = 0
cdef str _RPC_FINISHED_DETAILS = 'RPC already finished.'
cdef str _SERVER_STOPPED_DETAILS = 'Server already stopped.'
-
+
cdef _augment_metadata(tuple metadata, object compression):
if compression is None:
return metadata
@@ -32,24 +32,24 @@ cdef _augment_metadata(tuple metadata, object compression):
),) + metadata
-cdef class _HandlerCallDetails:
- def __cinit__(self, str method, tuple invocation_metadata):
- self.method = method
- self.invocation_metadata = invocation_metadata
-
-
+cdef class _HandlerCallDetails:
+ def __cinit__(self, str method, tuple invocation_metadata):
+ self.method = method
+ self.invocation_metadata = invocation_metadata
+
+
class _ServerStoppedError(BaseError):
"""Raised if the server is stopped."""
-cdef class RPCState:
-
+cdef class RPCState:
+
def __cinit__(self, AioServer server):
init_grpc_aio()
self.call = NULL
self.server = server
- grpc_metadata_array_init(&self.request_metadata)
- grpc_call_details_init(&self.details)
+ grpc_metadata_array_init(&self.request_metadata)
+ grpc_call_details_init(&self.details)
self.client_closed = False
self.abort_exception = None
self.metadata_sent = False
@@ -59,10 +59,10 @@ cdef class RPCState:
self.trailing_metadata = _IMMUTABLE_EMPTY_METADATA
self.compression_algorithm = None
self.disable_next_compression = False
-
- cdef bytes method(self):
+
+ cdef bytes method(self):
return _slice_bytes(self.details.method)
-
+
cdef tuple invocation_metadata(self):
return _metadata(&self.request_metadata)
@@ -101,15 +101,15 @@ cdef class RPCState:
)
return op
- def __dealloc__(self):
- """Cleans the Core objects."""
- grpc_call_details_destroy(&self.details)
- grpc_metadata_array_destroy(&self.request_metadata)
- if self.call:
- grpc_call_unref(self.call)
+ def __dealloc__(self):
+ """Cleans the Core objects."""
+ grpc_call_details_destroy(&self.details)
+ grpc_metadata_array_destroy(&self.request_metadata)
+ if self.call:
+ grpc_call_unref(self.call)
shutdown_grpc_aio()
-
-
+
+
cdef class _ServicerContext:
def __cinit__(self,
@@ -346,7 +346,7 @@ async def _find_method_handler(str method, tuple metadata, list generic_handlers
else:
return query_handlers(handler_call_details)
-
+
async def _finish_handler_with_unary_response(RPCState rpc_state,
object unary_handler,
object request,
@@ -484,21 +484,21 @@ async def _finish_handler_with_stream_responses(RPCState rpc_state,
await execute_batch(rpc_state, finish_ops, loop)
-async def _handle_unary_unary_rpc(object method_handler,
- RPCState rpc_state,
- object loop):
- # Receives request message
+async def _handle_unary_unary_rpc(object method_handler,
+ RPCState rpc_state,
+ object loop):
+ # Receives request message
cdef bytes request_raw = await _receive_message(rpc_state, loop)
if request_raw is None:
# The RPC was cancelled immediately after start on client side.
return
-
- # Deserializes the request message
+
+ # Deserializes the request message
cdef object request_message = deserialize(
method_handler.request_deserializer,
request_raw,
)
-
+
# Creates a dedecated ServicerContext
cdef _ServicerContext servicer_context = _ServicerContext(
rpc_state,
@@ -506,7 +506,7 @@ async def _handle_unary_unary_rpc(object method_handler,
None,
loop,
)
-
+
# Finishes the application handler
await _finish_handler_with_unary_response(
rpc_state,
@@ -516,7 +516,7 @@ async def _handle_unary_unary_rpc(object method_handler,
method_handler.response_serializer,
loop
)
-
+
async def _handle_unary_stream_rpc(object method_handler,
RPCState rpc_state,
@@ -530,8 +530,8 @@ async def _handle_unary_stream_rpc(object method_handler,
cdef object request_message = deserialize(
method_handler.request_deserializer,
request_raw,
- )
-
+ )
+
# Creates a dedecated ServicerContext
cdef _ServicerContext servicer_context = _ServicerContext(
rpc_state,
@@ -539,7 +539,7 @@ async def _handle_unary_stream_rpc(object method_handler,
method_handler.response_serializer,
loop,
)
-
+
# Finishes the application handler
await _finish_handler_with_stream_responses(
rpc_state,
@@ -547,16 +547,16 @@ async def _handle_unary_stream_rpc(object method_handler,
request_message,
servicer_context,
loop,
- )
-
-
+ )
+
+
cdef class _MessageReceiver:
"""Bridge between the async generator API and the reader-writer API."""
-
+
def __cinit__(self, _ServicerContext servicer_context):
self._servicer_context = servicer_context
self._agen = None
-
+
async def _async_message_receiver(self):
"""An async generator that receives messages."""
cdef object message
@@ -587,7 +587,7 @@ async def _handle_stream_unary_rpc(object method_handler,
None,
loop,
)
-
+
# Prepares the request generator
cdef object request_iterator
if _is_async_handler(method_handler.stream_unary):
@@ -597,7 +597,7 @@ async def _handle_stream_unary_rpc(object method_handler,
_MessageReceiver(servicer_context),
loop
)
-
+
# Finishes the application handler
await _finish_handler_with_unary_response(
rpc_state,
@@ -611,15 +611,15 @@ async def _handle_stream_unary_rpc(object method_handler,
async def _handle_stream_stream_rpc(object method_handler,
RPCState rpc_state,
- object loop):
+ object loop):
# Creates a dedecated ServicerContext
cdef _ServicerContext servicer_context = _ServicerContext(
rpc_state,
method_handler.request_deserializer,
method_handler.response_serializer,
loop,
- )
-
+ )
+
# Prepares the request generator
cdef object request_iterator
if _is_async_handler(method_handler.stream_stream):
@@ -629,7 +629,7 @@ async def _handle_stream_stream_rpc(object method_handler,
_MessageReceiver(servicer_context),
loop
)
-
+
# Finishes the application handler
await _finish_handler_with_stream_responses(
rpc_state,
@@ -638,7 +638,7 @@ async def _handle_stream_stream_rpc(object method_handler,
servicer_context,
loop,
)
-
+
async def _handle_exceptions(RPCState rpc_state, object rpc_coro, object loop):
try:
@@ -689,11 +689,11 @@ async def _handle_exceptions(RPCState rpc_state, object rpc_coro, object loop):
)
-async def _handle_cancellation_from_core(object rpc_task,
+async def _handle_cancellation_from_core(object rpc_task,
RPCState rpc_state,
object loop):
- cdef ReceiveCloseOnServerOperation op = ReceiveCloseOnServerOperation(_EMPTY_FLAG)
- cdef tuple ops = (op,)
+ cdef ReceiveCloseOnServerOperation op = ReceiveCloseOnServerOperation(_EMPTY_FLAG)
+ cdef tuple ops = (op,)
# Awaits cancellation from peer.
await execute_batch(rpc_state, ops, loop)
@@ -703,9 +703,9 @@ async def _handle_cancellation_from_core(object rpc_task,
# log that an RPC is both aborted and cancelled.
if op.cancelled() and not rpc_task.done() and not rpc_state.status_sent:
# Injects `CancelledError` to halt the RPC coroutine
- rpc_task.cancel()
-
-
+ rpc_task.cancel()
+
+
async def _schedule_rpc_coro(object rpc_coro,
RPCState rpc_state,
object loop):
@@ -775,60 +775,60 @@ cdef CallbackFailureHandler REQUEST_CALL_FAILURE_HANDLER = CallbackFailureHandle
'grpc_server_request_call', None, _RequestCallError)
-cdef CallbackFailureHandler SERVER_SHUTDOWN_FAILURE_HANDLER = CallbackFailureHandler(
- 'grpc_server_shutdown_and_notify',
+cdef CallbackFailureHandler SERVER_SHUTDOWN_FAILURE_HANDLER = CallbackFailureHandler(
+ 'grpc_server_shutdown_and_notify',
None,
InternalError)
-
-
-cdef class AioServer:
-
- def __init__(self, loop, thread_pool, generic_handlers, interceptors,
+
+
+cdef class AioServer:
+
+ def __init__(self, loop, thread_pool, generic_handlers, interceptors,
options, maximum_concurrent_rpcs):
init_grpc_aio()
- # NOTE(lidiz) Core objects won't be deallocated automatically.
- # If AioServer.shutdown is not called, those objects will leak.
- self._server = Server(options)
- grpc_server_register_completion_queue(
- self._server.c_server,
+ # NOTE(lidiz) Core objects won't be deallocated automatically.
+ # If AioServer.shutdown is not called, those objects will leak.
+ self._server = Server(options)
+ grpc_server_register_completion_queue(
+ self._server.c_server,
global_completion_queue(),
- NULL
- )
-
- self._loop = loop
- self._status = AIO_SERVER_STATUS_READY
- self._generic_handlers = []
- self.add_generic_rpc_handlers(generic_handlers)
- self._serving_task = None
-
- self._shutdown_lock = asyncio.Lock(loop=self._loop)
- self._shutdown_completed = self._loop.create_future()
- self._shutdown_callback_wrapper = CallbackWrapper(
- self._shutdown_completed,
+ NULL
+ )
+
+ self._loop = loop
+ self._status = AIO_SERVER_STATUS_READY
+ self._generic_handlers = []
+ self.add_generic_rpc_handlers(generic_handlers)
+ self._serving_task = None
+
+ self._shutdown_lock = asyncio.Lock(loop=self._loop)
+ self._shutdown_completed = self._loop.create_future()
+ self._shutdown_callback_wrapper = CallbackWrapper(
+ self._shutdown_completed,
self._loop,
- SERVER_SHUTDOWN_FAILURE_HANDLER)
- self._crash_exception = None
-
- if interceptors:
+ SERVER_SHUTDOWN_FAILURE_HANDLER)
+ self._crash_exception = None
+
+ if interceptors:
self._interceptors = interceptors
else:
self._interceptors = ()
self._thread_pool = thread_pool
- if maximum_concurrent_rpcs:
- raise NotImplementedError()
-
+ if maximum_concurrent_rpcs:
+ raise NotImplementedError()
+
def add_generic_rpc_handlers(self, object generic_rpc_handlers):
self._generic_handlers.extend(generic_rpc_handlers)
-
- def add_insecure_port(self, address):
- return self._server.add_http2_port(address)
-
- def add_secure_port(self, address, server_credentials):
- return self._server.add_http2_port(address,
+
+ def add_insecure_port(self, address):
+ return self._server.add_http2_port(address)
+
+ def add_secure_port(self, address, server_credentials):
+ return self._server.add_http2_port(address,
server_credentials._credentials)
-
+
async def _request_call(self):
cdef grpc_call_error error
cdef RPCState rpc_state = RPCState(self)
@@ -849,20 +849,20 @@ cdef class AioServer:
await future
return rpc_state
- async def _server_main_loop(self,
- object server_started):
+ async def _server_main_loop(self,
+ object server_started):
self._server.start(backup_queue=False)
- cdef RPCState rpc_state
- server_started.set_result(True)
-
- while True:
- # When shutdown begins, no more new connections.
- if self._status != AIO_SERVER_STATUS_RUNNING:
- break
-
+ cdef RPCState rpc_state
+ server_started.set_result(True)
+
+ while True:
+ # When shutdown begins, no more new connections.
+ if self._status != AIO_SERVER_STATUS_RUNNING:
+ break
+
# Accepts new request from Core
rpc_state = await self._request_call()
-
+
# Creates the dedicated RPC coroutine. If we schedule it right now,
# there is no guarantee if the cancellation listening coroutine is
# ready or not. So, we should control the ordering by scheduling
@@ -874,124 +874,124 @@ cdef class AioServer:
self._loop)
# Fires off a task that listens on the cancellation from client.
- self._loop.create_task(
+ self._loop.create_task(
_schedule_rpc_coro(
rpc_coro,
- rpc_state,
- self._loop
- )
- )
-
- def _serving_task_crash_handler(self, object task):
- """Shutdown the server immediately if unexpectedly exited."""
- if task.exception() is None:
- return
- if self._status != AIO_SERVER_STATUS_STOPPING:
- self._crash_exception = task.exception()
- _LOGGER.exception(self._crash_exception)
- self._loop.create_task(self.shutdown(None))
-
- async def start(self):
- if self._status == AIO_SERVER_STATUS_RUNNING:
- return
- elif self._status != AIO_SERVER_STATUS_READY:
+ rpc_state,
+ self._loop
+ )
+ )
+
+ def _serving_task_crash_handler(self, object task):
+ """Shutdown the server immediately if unexpectedly exited."""
+ if task.exception() is None:
+ return
+ if self._status != AIO_SERVER_STATUS_STOPPING:
+ self._crash_exception = task.exception()
+ _LOGGER.exception(self._crash_exception)
+ self._loop.create_task(self.shutdown(None))
+
+ async def start(self):
+ if self._status == AIO_SERVER_STATUS_RUNNING:
+ return
+ elif self._status != AIO_SERVER_STATUS_READY:
raise UsageError('Server not in ready state')
-
- self._status = AIO_SERVER_STATUS_RUNNING
- cdef object server_started = self._loop.create_future()
- self._serving_task = self._loop.create_task(self._server_main_loop(server_started))
- self._serving_task.add_done_callback(self._serving_task_crash_handler)
- # Needs to explicitly wait for the server to start up.
- # Otherwise, the actual start time of the server is un-controllable.
- await server_started
-
- async def _start_shutting_down(self):
- """Prepares the server to shutting down.
-
- This coroutine function is NOT coroutine-safe.
- """
- # The shutdown callback won't be called until there is no live RPC.
- grpc_server_shutdown_and_notify(
- self._server.c_server,
+
+ self._status = AIO_SERVER_STATUS_RUNNING
+ cdef object server_started = self._loop.create_future()
+ self._serving_task = self._loop.create_task(self._server_main_loop(server_started))
+ self._serving_task.add_done_callback(self._serving_task_crash_handler)
+ # Needs to explicitly wait for the server to start up.
+ # Otherwise, the actual start time of the server is un-controllable.
+ await server_started
+
+ async def _start_shutting_down(self):
+ """Prepares the server to shutting down.
+
+ This coroutine function is NOT coroutine-safe.
+ """
+ # The shutdown callback won't be called until there is no live RPC.
+ grpc_server_shutdown_and_notify(
+ self._server.c_server,
global_completion_queue(),
- self._shutdown_callback_wrapper.c_functor())
-
- # Ensures the serving task (coroutine) exits.
- try:
- await self._serving_task
- except _RequestCallError:
- pass
-
- async def shutdown(self, grace):
+ self._shutdown_callback_wrapper.c_functor())
+
+ # Ensures the serving task (coroutine) exits.
+ try:
+ await self._serving_task
+ except _RequestCallError:
+ pass
+
+ async def shutdown(self, grace):
"""Gracefully shutdown the Core server.
-
- Application should only call shutdown once.
-
- Args:
- grace: An optional float indicating the length of grace period in
- seconds.
- """
- if self._status == AIO_SERVER_STATUS_READY or self._status == AIO_SERVER_STATUS_STOPPED:
- return
-
- async with self._shutdown_lock:
- if self._status == AIO_SERVER_STATUS_RUNNING:
- self._server.is_shutting_down = True
- self._status = AIO_SERVER_STATUS_STOPPING
- await self._start_shutting_down()
-
- if grace is None:
- # Directly cancels all calls
- grpc_server_cancel_all_calls(self._server.c_server)
- await self._shutdown_completed
- else:
- try:
- await asyncio.wait_for(
- asyncio.shield(
- self._shutdown_completed,
- loop=self._loop
- ),
- grace,
- loop=self._loop,
- )
- except asyncio.TimeoutError:
- # Cancels all ongoing calls by the end of grace period.
- grpc_server_cancel_all_calls(self._server.c_server)
- await self._shutdown_completed
-
- async with self._shutdown_lock:
- if self._status == AIO_SERVER_STATUS_STOPPING:
- grpc_server_destroy(self._server.c_server)
- self._server.c_server = NULL
- self._server.is_shutdown = True
- self._status = AIO_SERVER_STATUS_STOPPED
-
+
+ Application should only call shutdown once.
+
+ Args:
+ grace: An optional float indicating the length of grace period in
+ seconds.
+ """
+ if self._status == AIO_SERVER_STATUS_READY or self._status == AIO_SERVER_STATUS_STOPPED:
+ return
+
+ async with self._shutdown_lock:
+ if self._status == AIO_SERVER_STATUS_RUNNING:
+ self._server.is_shutting_down = True
+ self._status = AIO_SERVER_STATUS_STOPPING
+ await self._start_shutting_down()
+
+ if grace is None:
+ # Directly cancels all calls
+ grpc_server_cancel_all_calls(self._server.c_server)
+ await self._shutdown_completed
+ else:
+ try:
+ await asyncio.wait_for(
+ asyncio.shield(
+ self._shutdown_completed,
+ loop=self._loop
+ ),
+ grace,
+ loop=self._loop,
+ )
+ except asyncio.TimeoutError:
+ # Cancels all ongoing calls by the end of grace period.
+ grpc_server_cancel_all_calls(self._server.c_server)
+ await self._shutdown_completed
+
+ async with self._shutdown_lock:
+ if self._status == AIO_SERVER_STATUS_STOPPING:
+ grpc_server_destroy(self._server.c_server)
+ self._server.c_server = NULL
+ self._server.is_shutdown = True
+ self._status = AIO_SERVER_STATUS_STOPPED
+
async def wait_for_termination(self, object timeout):
- if timeout is None:
- await self._shutdown_completed
- else:
- try:
- await asyncio.wait_for(
- asyncio.shield(
- self._shutdown_completed,
- loop=self._loop,
- ),
- timeout,
- loop=self._loop,
- )
- except asyncio.TimeoutError:
- if self._crash_exception is not None:
- raise self._crash_exception
- return False
- if self._crash_exception is not None:
- raise self._crash_exception
- return True
-
- def __dealloc__(self):
+ if timeout is None:
+ await self._shutdown_completed
+ else:
+ try:
+ await asyncio.wait_for(
+ asyncio.shield(
+ self._shutdown_completed,
+ loop=self._loop,
+ ),
+ timeout,
+ loop=self._loop,
+ )
+ except asyncio.TimeoutError:
+ if self._crash_exception is not None:
+ raise self._crash_exception
+ return False
+ if self._crash_exception is not None:
+ raise self._crash_exception
+ return True
+
+ def __dealloc__(self):
"""Deallocation of Core objects are ensured by Python layer."""
# TODO(lidiz) if users create server, and then dealloc it immediately.
# There is a potential memory leak of created Core server.
- if self._status != AIO_SERVER_STATUS_STOPPED:
+ if self._status != AIO_SERVER_STATUS_STOPPED:
_LOGGER.debug(
'__dealloc__ called on running server %s with status %d',
self,
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi
index 251efe15b3..24c22e6771 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi
@@ -23,7 +23,7 @@ cdef class _ChannelArg:
cdef grpc_arg c_argument
- cdef void c(self, argument, references) except *
+ cdef void c(self, argument, references) except *
cdef class _ChannelArgs:
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi
index 9df308cdbc..c0c8d59b33 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi
@@ -31,7 +31,7 @@ cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg):
cdef class _ChannelArg:
- cdef void c(self, argument, references) except *:
+ cdef void c(self, argument, references) except *:
key, value = argument
cdef bytes encoded_key = _encode(key)
if encoded_key is not key:
@@ -54,7 +54,7 @@ cdef class _ChannelArg:
# lifecycle of the pointer is fixed to the lifecycle of the
# python object wrapping it.
self.c_argument.type = GRPC_ARG_POINTER
- self.c_argument.value.pointer.vtable = &default_vtable
+ self.c_argument.value.pointer.vtable = &default_vtable
self.c_argument.value.pointer.address = <void*>(<intptr_t>int(value))
else:
raise TypeError(
@@ -73,7 +73,7 @@ cdef class _ChannelArgs:
self._c_arguments.arguments_length * sizeof(grpc_arg))
for index, argument in enumerate(self._arguments):
channel_arg = _ChannelArg()
- channel_arg.c(argument, self._references)
+ channel_arg.c(argument, self._references)
self._c_arguments.arguments[index] = channel_arg.c_argument
self._channel_args.append(channel_arg)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi
index bdd155bea9..b97dc738f8 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi
@@ -83,10 +83,10 @@ cdef class Call:
return result
def __dealloc__(self):
- with nogil:
- if self.c_call != NULL:
- grpc_call_unref(self.c_call)
- grpc_shutdown_blocking()
+ with nogil:
+ if self.c_call != NULL:
+ grpc_call_unref(self.c_call)
+ grpc_shutdown_blocking()
# The object *should* always be valid from Python. Used for debugging.
@property
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi
index 74c7f6c140..9699aa1bc6 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi
@@ -142,38 +142,38 @@ cdef _cancel(
cdef _next_call_event(
_ChannelState channel_state, grpc_completion_queue *c_completion_queue,
- on_success, on_failure, deadline):
- """Block on the next event out of the completion queue.
-
- On success, `on_success` will be invoked with the tag taken from the CQ.
- In the case of a failure due to an exception raised in a signal handler,
- `on_failure` will be invoked with no arguments. Note that this situation
- can only occur on the main thread.
-
- Args:
- channel_state: The state for the channel on which the RPC is running.
- c_completion_queue: The CQ which will be polled.
- on_success: A callable object to be invoked upon successful receipt of a
- tag from the CQ.
- on_failure: A callable object to be invoked in case a Python exception is
- raised from a signal handler during polling.
- deadline: The point after which the RPC will time out.
- """
- try:
- tag, event = _latent_event(c_completion_queue, deadline)
- # NOTE(rbellevi): This broad except enables us to clean up resources before
- # propagating any exceptions raised by signal handlers to the application.
- except:
- if on_failure is not None:
- on_failure()
- raise
- else:
- with channel_state.condition:
- on_success(tag)
- channel_state.condition.notify_all()
- return event
-
-
+ on_success, on_failure, deadline):
+ """Block on the next event out of the completion queue.
+
+ On success, `on_success` will be invoked with the tag taken from the CQ.
+ In the case of a failure due to an exception raised in a signal handler,
+ `on_failure` will be invoked with no arguments. Note that this situation
+ can only occur on the main thread.
+
+ Args:
+ channel_state: The state for the channel on which the RPC is running.
+ c_completion_queue: The CQ which will be polled.
+ on_success: A callable object to be invoked upon successful receipt of a
+ tag from the CQ.
+ on_failure: A callable object to be invoked in case a Python exception is
+ raised from a signal handler during polling.
+ deadline: The point after which the RPC will time out.
+ """
+ try:
+ tag, event = _latent_event(c_completion_queue, deadline)
+ # NOTE(rbellevi): This broad except enables us to clean up resources before
+ # propagating any exceptions raised by signal handlers to the application.
+ except:
+ if on_failure is not None:
+ on_failure()
+ raise
+ else:
+ with channel_state.condition:
+ on_success(tag)
+ channel_state.condition.notify_all()
+ return event
+
+
# TODO(https://github.com/grpc/grpc/issues/14569): This could be a lot simpler.
cdef void _call(
_ChannelState channel_state, _CallState call_state,
@@ -329,14 +329,14 @@ cdef class SegregatedCall:
def on_success(tag):
_process_segregated_call_tag(
self._channel_state, self._call_state, self._c_completion_queue, tag)
- def on_failure():
- self._call_state.due.clear()
- grpc_call_unref(self._call_state.c_call)
- self._call_state.c_call = NULL
- self._channel_state.segregated_call_states.remove(self._call_state)
- _destroy_c_completion_queue(self._c_completion_queue)
+ def on_failure():
+ self._call_state.due.clear()
+ grpc_call_unref(self._call_state.c_call)
+ self._call_state.c_call = NULL
+ self._channel_state.segregated_call_states.remove(self._call_state)
+ _destroy_c_completion_queue(self._c_completion_queue)
return _next_call_event(
- self._channel_state, self._c_completion_queue, on_success, on_failure, None)
+ self._channel_state, self._c_completion_queue, on_success, on_failure, None)
cdef SegregatedCall _segregated_call(
@@ -425,7 +425,7 @@ cdef _close(Channel channel, grpc_status_code code, object details,
_destroy_c_completion_queue(state.c_connectivity_completion_queue)
grpc_channel_destroy(state.c_channel)
state.c_channel = NULL
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
state.condition.notify_all()
else:
# Another call to close already completed in the past or is currently
@@ -446,12 +446,12 @@ cdef class Channel:
arguments = () if arguments is None else tuple(arguments)
fork_handlers_and_grpc_init()
self._state = _ChannelState()
- self._state.c_call_completion_queue = (
- grpc_completion_queue_create_for_next(NULL))
- self._state.c_connectivity_completion_queue = (
- grpc_completion_queue_create_for_next(NULL))
- self._arguments = arguments
- cdef _ChannelArgs channel_args = _ChannelArgs(arguments)
+ self._state.c_call_completion_queue = (
+ grpc_completion_queue_create_for_next(NULL))
+ self._state.c_connectivity_completion_queue = (
+ grpc_completion_queue_create_for_next(NULL))
+ self._arguments = arguments
+ cdef _ChannelArgs channel_args = _ChannelArgs(arguments)
if channel_credentials is None:
self._state.c_channel = grpc_insecure_channel_create(
<char *>target, channel_args.c_args(), NULL)
@@ -485,11 +485,11 @@ cdef class Channel:
queue_deadline = time.time() + 1.0
else:
queue_deadline = None
- # NOTE(gnossen): It is acceptable for on_failure to be None here because
- # failure conditions can only ever happen on the main thread and this
- # method is only ever invoked on the channel spin thread.
+ # NOTE(gnossen): It is acceptable for on_failure to be None here because
+ # failure conditions can only ever happen on the main thread and this
+ # method is only ever invoked on the channel spin thread.
return _next_call_event(self._state, self._state.c_call_completion_queue,
- on_success, None, queue_deadline)
+ on_success, None, queue_deadline)
def segregated_call(
self, int flags, method, host, object deadline, object metadata,
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi
index a47403ac51..a5b2c6eaed 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi
@@ -26,20 +26,20 @@ cdef grpc_event _next(grpc_completion_queue *c_completion_queue, deadline) excep
else:
c_deadline = _timespec_from_time(deadline)
- while True:
- with nogil:
+ while True:
+ with nogil:
c_timeout = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), c_increment)
if gpr_time_cmp(c_timeout, c_deadline) > 0:
c_timeout = c_deadline
-
+
c_event = grpc_completion_queue_next(c_completion_queue, c_timeout, NULL)
-
+
if (c_event.type != GRPC_QUEUE_TIMEOUT or
gpr_time_cmp(c_timeout, c_deadline) == 0):
break
- # Handle any signals
- cpython.PyErr_CheckSignals()
+ # Handle any signals
+ cpython.PyErr_CheckSignals()
return c_event
@@ -115,4 +115,4 @@ cdef class CompletionQueue:
self.c_completion_queue, c_deadline, NULL)
self._interpret_event(event)
grpc_completion_queue_destroy(self.c_completion_queue)
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi
index ddaedb30bd..91d2f36195 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi
@@ -26,9 +26,9 @@ cdef int _get_metadata(
grpc_credentials_plugin_metadata_cb cb, void *user_data,
grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
size_t *num_creds_md, grpc_status_code *status,
- const char **error_details) except * with gil
+ const char **error_details) except * with gil
-cdef void _destroy(void *state) except * with gil
+cdef void _destroy(void *state) except * with gil
cdef class MetadataPluginCallCredentials(CallCredentials):
@@ -97,11 +97,11 @@ cdef class ServerCredentials:
cdef object cert_config_fetcher
# whether C-core has asked for the initial_cert_config
cdef bint initial_cert_config_fetched
-
-
-cdef class LocalChannelCredentials(ChannelCredentials):
-
- cdef grpc_local_connect_type _local_connect_type
+
+
+cdef class LocalChannelCredentials(ChannelCredentials):
+
+ cdef grpc_local_connect_type _local_connect_type
cdef class ALTSChannelCredentials(ChannelCredentials):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi
index c75579cc04..7408f2960d 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi
@@ -56,9 +56,9 @@ cdef int _get_metadata(void *state,
return 0 # Asynchronous return
-cdef void _destroy(void *state) except * with gil:
+cdef void _destroy(void *state) except * with gil:
cpython.Py_DECREF(<object>state)
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
cdef class MetadataPluginCallCredentials(CallCredentials):
@@ -124,7 +124,7 @@ cdef class SSLSessionCacheLRU:
def __dealloc__(self):
if self._cache != NULL:
grpc_ssl_session_cache_destroy(self._cache)
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
cdef class SSLChannelCredentials(ChannelCredentials):
@@ -190,7 +190,7 @@ cdef class ServerCertificateConfig:
def __dealloc__(self):
grpc_ssl_server_certificate_config_destroy(self.c_cert_config)
gpr_free(self.c_ssl_pem_key_cert_pairs)
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
cdef class ServerCredentials:
@@ -206,7 +206,7 @@ cdef class ServerCredentials:
def __dealloc__(self):
if self.c_credentials != NULL:
grpc_server_credentials_release(self.c_credentials)
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
cdef const char* _get_c_pem_root_certs(pem_root_certs):
if pem_root_certs is None:
@@ -329,28 +329,28 @@ cdef grpc_ssl_certificate_config_reload_status _server_cert_config_fetcher_wrapp
cert_config.c_ssl_pem_key_cert_pairs_count)
return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW
-
-class LocalConnectionType:
- uds = UDS
- local_tcp = LOCAL_TCP
-
-cdef class LocalChannelCredentials(ChannelCredentials):
-
- def __cinit__(self, grpc_local_connect_type local_connect_type):
- self._local_connect_type = local_connect_type
-
- cdef grpc_channel_credentials *c(self) except *:
- cdef grpc_local_connect_type local_connect_type
- local_connect_type = self._local_connect_type
- return grpc_local_credentials_create(local_connect_type)
-
-def channel_credentials_local(grpc_local_connect_type local_connect_type):
- return LocalChannelCredentials(local_connect_type)
-
-def server_credentials_local(grpc_local_connect_type local_connect_type):
- cdef ServerCredentials credentials = ServerCredentials()
- credentials.c_credentials = grpc_local_server_credentials_create(local_connect_type)
- return credentials
+
+class LocalConnectionType:
+ uds = UDS
+ local_tcp = LOCAL_TCP
+
+cdef class LocalChannelCredentials(ChannelCredentials):
+
+ def __cinit__(self, grpc_local_connect_type local_connect_type):
+ self._local_connect_type = local_connect_type
+
+ cdef grpc_channel_credentials *c(self) except *:
+ cdef grpc_local_connect_type local_connect_type
+ local_connect_type = self._local_connect_type
+ return grpc_local_credentials_create(local_connect_type)
+
+def channel_credentials_local(grpc_local_connect_type local_connect_type):
+ return LocalChannelCredentials(local_connect_type)
+
+def server_credentials_local(grpc_local_connect_type local_connect_type):
+ cdef ServerCredentials credentials = ServerCredentials()
+ credentials.c_credentials = grpc_local_server_credentials_create(local_connect_type)
+ return credentials
cdef class ALTSChannelCredentials(ChannelCredentials):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi
index 53657e8b1a..e430ec5309 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi
@@ -32,12 +32,12 @@ _GRPC_ENABLE_FORK_SUPPORT = (
os.environ.get('GRPC_ENABLE_FORK_SUPPORT', '0')
.lower() in _TRUE_VALUES)
-_fork_handler_failed = False
-
+_fork_handler_failed = False
+
cdef void __prefork() nogil:
with gil:
- global _fork_handler_failed
- _fork_handler_failed = False
+ global _fork_handler_failed
+ _fork_handler_failed = False
with _fork_state.fork_in_progress_condition:
_fork_state.fork_in_progress = True
if not _fork_state.active_thread_count.await_zero_threads(
@@ -45,7 +45,7 @@ cdef void __prefork() nogil:
_LOGGER.error(
'Failed to shutdown gRPC Python threads prior to fork. '
'Behavior after fork will be undefined.')
- _fork_handler_failed = True
+ _fork_handler_failed = True
cdef void __postfork_parent() nogil:
@@ -57,28 +57,28 @@ cdef void __postfork_parent() nogil:
cdef void __postfork_child() nogil:
with gil:
- try:
- if _fork_handler_failed:
- return
- # Thread could be holding the fork_in_progress_condition inside of
- # block_if_fork_in_progress() when fork occurs. Reset the lock here.
- _fork_state.fork_in_progress_condition = threading.Condition()
- # A thread in return_from_user_request_generator() may hold this lock
- # when fork occurs.
- _fork_state.active_thread_count = _ActiveThreadCount()
- for state_to_reset in _fork_state.postfork_states_to_reset:
- state_to_reset.reset_postfork_child()
- _fork_state.postfork_states_to_reset = []
- _fork_state.fork_epoch += 1
- for channel in _fork_state.channels:
- channel._close_on_fork()
- with _fork_state.fork_in_progress_condition:
- _fork_state.fork_in_progress = False
- except:
- _LOGGER.error('Exiting child due to raised exception')
- _LOGGER.error(sys.exc_info()[0])
- os._exit(os.EX_USAGE)
-
+ try:
+ if _fork_handler_failed:
+ return
+ # Thread could be holding the fork_in_progress_condition inside of
+ # block_if_fork_in_progress() when fork occurs. Reset the lock here.
+ _fork_state.fork_in_progress_condition = threading.Condition()
+ # A thread in return_from_user_request_generator() may hold this lock
+ # when fork occurs.
+ _fork_state.active_thread_count = _ActiveThreadCount()
+ for state_to_reset in _fork_state.postfork_states_to_reset:
+ state_to_reset.reset_postfork_child()
+ _fork_state.postfork_states_to_reset = []
+ _fork_state.fork_epoch += 1
+ for channel in _fork_state.channels:
+ channel._close_on_fork()
+ with _fork_state.fork_in_progress_condition:
+ _fork_state.fork_in_progress = False
+ except:
+ _LOGGER.error('Exiting child due to raised exception')
+ _LOGGER.error(sys.exc_info()[0])
+ os._exit(os.EX_USAGE)
+
if grpc_is_initialized() > 0:
with gil:
_LOGGER.error('Failed to shutdown gRPC Core after fork()')
@@ -158,7 +158,7 @@ def fork_register_channel(channel):
def fork_unregister_channel(channel):
if _GRPC_ENABLE_FORK_SUPPORT:
- _fork_state.channels.discard(channel)
+ _fork_state.channels.discard(channel)
class _ActiveThreadCount(object):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi
index 54eb7fdffc..1ffd1fcbd6 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi
@@ -14,16 +14,16 @@
cimport libc.time
-ctypedef ssize_t intptr_t
-ctypedef size_t uintptr_t
-ctypedef signed char int8_t
-ctypedef signed short int16_t
-ctypedef signed int int32_t
-ctypedef signed long long int64_t
-ctypedef unsigned char uint8_t
-ctypedef unsigned short uint16_t
-ctypedef unsigned int uint32_t
-ctypedef unsigned long long uint64_t
+ctypedef ssize_t intptr_t
+ctypedef size_t uintptr_t
+ctypedef signed char int8_t
+ctypedef signed short int16_t
+ctypedef signed int int32_t
+ctypedef signed long long int64_t
+ctypedef unsigned char uint8_t
+ctypedef unsigned short uint16_t
+ctypedef unsigned int uint32_t
+ctypedef unsigned long long uint64_t
cdef extern from "grpc/support/alloc.h":
@@ -41,11 +41,11 @@ cdef extern from "grpc/byte_buffer_reader.h":
pass
-cdef extern from "grpc/impl/codegen/grpc_types.h":
- ctypedef struct grpc_experimental_completion_queue_functor:
- void (*functor_run)(grpc_experimental_completion_queue_functor*, int);
-
-
+cdef extern from "grpc/impl/codegen/grpc_types.h":
+ ctypedef struct grpc_experimental_completion_queue_functor:
+ void (*functor_run)(grpc_experimental_completion_queue_functor*, int);
+
+
cdef extern from "grpc/grpc.h":
ctypedef struct grpc_slice:
@@ -68,10 +68,10 @@ cdef extern from "grpc/grpc.h":
void *grpc_slice_start_ptr "GRPC_SLICE_START_PTR" (grpc_slice s) nogil
size_t grpc_slice_length "GRPC_SLICE_LENGTH" (grpc_slice s) nogil
- const int GPR_MS_PER_SEC
- const int GPR_US_PER_SEC
- const int GPR_NS_PER_SEC
-
+ const int GPR_MS_PER_SEC
+ const int GPR_US_PER_SEC
+ const int GPR_NS_PER_SEC
+
ctypedef enum gpr_clock_type:
GPR_CLOCK_MONOTONIC
GPR_CLOCK_REALTIME
@@ -93,8 +93,8 @@ cdef extern from "grpc/grpc.h":
gpr_clock_type target_clock) nogil
gpr_timespec gpr_time_from_millis(int64_t ms, gpr_clock_type type) nogil
- gpr_timespec gpr_time_from_nanos(int64_t ns, gpr_clock_type type) nogil
- double gpr_timespec_to_micros(gpr_timespec t) nogil
+ gpr_timespec gpr_time_from_nanos(int64_t ns, gpr_clock_type type) nogil
+ double gpr_timespec_to_micros(gpr_timespec t) nogil
gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b) nogil
@@ -145,8 +145,8 @@ cdef extern from "grpc/grpc.h":
const char *GRPC_ARG_SECONDARY_USER_AGENT_STRING
const char *GRPC_SSL_TARGET_NAME_OVERRIDE_ARG
const char *GRPC_SSL_SESSION_CACHE_ARG
- const char *_GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM \
- "GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM"
+ const char *_GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM \
+ "GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM"
const char *GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL
const char *GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET
@@ -330,12 +330,12 @@ cdef extern from "grpc/grpc.h":
ctypedef struct grpc_op:
grpc_op_type type "op"
uint32_t flags
- void * reserved
+ void * reserved
grpc_op_data data
void grpc_dont_init_openssl() nogil
void grpc_init() nogil
- void grpc_shutdown_blocking() nogil
+ void grpc_shutdown_blocking() nogil
int grpc_is_initialized() nogil
ctypedef struct grpc_completion_queue_factory:
@@ -357,10 +357,10 @@ cdef extern from "grpc/grpc.h":
void grpc_completion_queue_shutdown(grpc_completion_queue *cq) nogil
void grpc_completion_queue_destroy(grpc_completion_queue *cq) nogil
- grpc_completion_queue *grpc_completion_queue_create_for_callback(
- grpc_experimental_completion_queue_functor* shutdown_callback,
- void *reserved) nogil
-
+ grpc_completion_queue *grpc_completion_queue_create_for_callback(
+ grpc_experimental_completion_queue_functor* shutdown_callback,
+ void *reserved) nogil
+
grpc_call_error grpc_call_start_batch(
grpc_call *call, const grpc_op *ops, size_t nops, void *tag,
void *reserved) nogil
@@ -564,8 +564,8 @@ cdef extern from "grpc/grpc_security.h":
grpc_credentials_plugin_metadata_cb cb, void *user_data,
grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
size_t *num_creds_md, grpc_status_code *status,
- const char **error_details) except *
- void (*destroy)(void *state) except *
+ const char **error_details) except *
+ void (*destroy)(void *state) except *
void *state
const char *type
@@ -602,11 +602,11 @@ cdef extern from "grpc/grpc_security.h":
void grpc_auth_context_release(grpc_auth_context *context)
- grpc_channel_credentials *grpc_local_credentials_create(
- grpc_local_connect_type type)
- grpc_server_credentials *grpc_local_server_credentials_create(
- grpc_local_connect_type type)
-
+ grpc_channel_credentials *grpc_local_credentials_create(
+ grpc_local_connect_type type)
+ grpc_server_credentials *grpc_local_server_credentials_create(
+ grpc_local_connect_type type)
+
ctypedef struct grpc_alts_credentials_options:
# We don't care about the internals (and in fact don't know them)
pass
@@ -615,7 +615,7 @@ cdef extern from "grpc/grpc_security.h":
const grpc_alts_credentials_options *options)
grpc_server_credentials *grpc_alts_server_credentials_create(
const grpc_alts_credentials_options *options)
-
+
grpc_alts_credentials_options* grpc_alts_credentials_client_options_create()
grpc_alts_credentials_options* grpc_alts_credentials_server_options_create()
void grpc_alts_credentials_options_destroy(grpc_alts_credentials_options *options)
@@ -658,14 +658,14 @@ cdef extern from "grpc/compression.h":
int grpc_compression_options_is_algorithm_enabled(
const grpc_compression_options *opts,
grpc_compression_algorithm algorithm) nogil
-
-cdef extern from "grpc/impl/codegen/compression_types.h":
-
- const char *_GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY \
- "GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY"
-
-
-cdef extern from "grpc/grpc_security_constants.h":
- ctypedef enum grpc_local_connect_type:
- UDS
- LOCAL_TCP
+
+cdef extern from "grpc/impl/codegen/compression_types.h":
+
+ const char *_GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY \
+ "GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY"
+
+
+cdef extern from "grpc/grpc_security_constants.h":
+ ctypedef enum grpc_local_connect_type:
+ UDS
+ LOCAL_TCP
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi
index 0f693ec691..6888af71c3 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi
@@ -31,16 +31,16 @@ def _spawn_greenlet(*args):
cdef class SocketWrapper:
def __cinit__(self):
- fork_handlers_and_grpc_init()
+ fork_handlers_and_grpc_init()
self.sockopts = []
self.socket = None
self.c_socket = NULL
self.c_buffer = NULL
self.len = 0
- def __dealloc__(self):
- grpc_shutdown_blocking()
-
+ def __dealloc__(self):
+ grpc_shutdown_blocking()
+
cdef grpc_error* socket_init(grpc_custom_socket* socket, int domain) with gil:
sw = SocketWrapper()
sw.c_socket = socket
@@ -261,14 +261,14 @@ cdef void socket_accept(grpc_custom_socket* socket, grpc_custom_socket* client,
cdef class ResolveWrapper:
def __cinit__(self):
- fork_handlers_and_grpc_init()
+ fork_handlers_and_grpc_init()
self.c_resolver = NULL
self.c_host = NULL
self.c_port = NULL
- def __dealloc__(self):
- grpc_shutdown_blocking()
-
+ def __dealloc__(self):
+ grpc_shutdown_blocking()
+
cdef socket_resolve_async_cython(ResolveWrapper resolve_wrapper):
try:
res = gevent_socket.getaddrinfo(resolve_wrapper.c_host, resolve_wrapper.c_port)
@@ -305,7 +305,7 @@ cdef grpc_error* socket_resolve(const char* host, const char* port,
cdef class TimerWrapper:
def __cinit__(self, deadline):
- fork_handlers_and_grpc_init()
+ fork_handlers_and_grpc_init()
self.timer = gevent_hub.get_hub().loop.timer(deadline)
self.event = None
@@ -322,9 +322,9 @@ cdef class TimerWrapper:
self.event.set()
self.timer.stop()
- def __dealloc__(self):
- grpc_shutdown_blocking()
-
+ def __dealloc__(self):
+ grpc_shutdown_blocking()
+
cdef void timer_start(grpc_custom_timer* t) with gil:
timer = TimerWrapper(t.timeout_ms / 1000.0)
timer.c_timer = t
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi
index 5c1e0679a9..3bdc172585 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi
@@ -13,7 +13,7 @@
# limitations under the License.
-# This function will ascii encode unicode string inputs if necessary.
+# This function will ascii encode unicode string inputs if necessary.
# In Python3, unicode strings are the default str type.
cdef bytes str_to_bytes(object s):
if s is None or isinstance(s, bytes):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pxd.pxi
index 0c5a4e5763..59abfda2cb 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pxd.pxi
@@ -1,129 +1,129 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# distutils: language=c++
-
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# distutils: language=c++
+
from libcpp cimport bool as bool_t
from libcpp.string cimport string as cppstring
-cdef extern from "grpc/impl/codegen/slice.h":
- struct grpc_slice_buffer:
- int count
-
-cdef extern from "src/core/lib/iomgr/error.h":
- struct grpc_error:
- pass
-
-# TODO(https://github.com/grpc/grpc/issues/20135) Change the filename
-# for something more meaningful.
-cdef extern from "src/core/lib/iomgr/python_util.h":
- grpc_error* grpc_socket_error(char* error)
- char* grpc_slice_buffer_start(grpc_slice_buffer* buffer, int i)
- int grpc_slice_buffer_length(grpc_slice_buffer* buffer, int i)
-
-cdef extern from "src/core/lib/iomgr/sockaddr.h":
- ctypedef struct grpc_sockaddr:
- pass
-
-cdef extern from "src/core/lib/iomgr/resolve_address.h":
- ctypedef struct grpc_resolved_addresses:
- size_t naddrs
- grpc_resolved_address* addrs
-
- ctypedef struct grpc_resolved_address:
- char[128] addr
- size_t len
-
-cdef extern from "src/core/lib/iomgr/resolve_address_custom.h":
- struct grpc_custom_resolver:
- pass
-
- struct grpc_custom_resolver_vtable:
+cdef extern from "grpc/impl/codegen/slice.h":
+ struct grpc_slice_buffer:
+ int count
+
+cdef extern from "src/core/lib/iomgr/error.h":
+ struct grpc_error:
+ pass
+
+# TODO(https://github.com/grpc/grpc/issues/20135) Change the filename
+# for something more meaningful.
+cdef extern from "src/core/lib/iomgr/python_util.h":
+ grpc_error* grpc_socket_error(char* error)
+ char* grpc_slice_buffer_start(grpc_slice_buffer* buffer, int i)
+ int grpc_slice_buffer_length(grpc_slice_buffer* buffer, int i)
+
+cdef extern from "src/core/lib/iomgr/sockaddr.h":
+ ctypedef struct grpc_sockaddr:
+ pass
+
+cdef extern from "src/core/lib/iomgr/resolve_address.h":
+ ctypedef struct grpc_resolved_addresses:
+ size_t naddrs
+ grpc_resolved_address* addrs
+
+ ctypedef struct grpc_resolved_address:
+ char[128] addr
+ size_t len
+
+cdef extern from "src/core/lib/iomgr/resolve_address_custom.h":
+ struct grpc_custom_resolver:
+ pass
+
+ struct grpc_custom_resolver_vtable:
grpc_error* (*resolve)(const char* host, const char* port, grpc_resolved_addresses** res);
void (*resolve_async)(grpc_custom_resolver* resolver, const char* host, const char* port);
-
- void grpc_custom_resolve_callback(grpc_custom_resolver* resolver,
- grpc_resolved_addresses* result,
- grpc_error* error);
-
-cdef extern from "src/core/lib/iomgr/tcp_custom.h":
+
+ void grpc_custom_resolve_callback(grpc_custom_resolver* resolver,
+ grpc_resolved_addresses* result,
+ grpc_error* error);
+
+cdef extern from "src/core/lib/iomgr/tcp_custom.h":
cdef int GRPC_CUSTOM_SOCKET_OPT_SO_REUSEPORT
- struct grpc_custom_socket:
- void* impl
- # We don't care about the rest of the fields
- ctypedef void (*grpc_custom_connect_callback)(grpc_custom_socket* socket,
- grpc_error* error)
- ctypedef void (*grpc_custom_write_callback)(grpc_custom_socket* socket,
- grpc_error* error)
- ctypedef void (*grpc_custom_read_callback)(grpc_custom_socket* socket,
- size_t nread, grpc_error* error)
- ctypedef void (*grpc_custom_accept_callback)(grpc_custom_socket* socket,
- grpc_custom_socket* client,
- grpc_error* error)
- ctypedef void (*grpc_custom_close_callback)(grpc_custom_socket* socket)
-
- struct grpc_socket_vtable:
- grpc_error* (*init)(grpc_custom_socket* socket, int domain);
- void (*connect)(grpc_custom_socket* socket, const grpc_sockaddr* addr,
- size_t len, grpc_custom_connect_callback cb);
- void (*destroy)(grpc_custom_socket* socket);
- void (*shutdown)(grpc_custom_socket* socket);
- void (*close)(grpc_custom_socket* socket, grpc_custom_close_callback cb);
- void (*write)(grpc_custom_socket* socket, grpc_slice_buffer* slices,
- grpc_custom_write_callback cb);
- void (*read)(grpc_custom_socket* socket, char* buffer, size_t length,
- grpc_custom_read_callback cb);
- grpc_error* (*getpeername)(grpc_custom_socket* socket,
- const grpc_sockaddr* addr, int* len);
- grpc_error* (*getsockname)(grpc_custom_socket* socket,
- const grpc_sockaddr* addr, int* len);
- grpc_error* (*bind)(grpc_custom_socket* socket, const grpc_sockaddr* addr,
- size_t len, int flags);
- grpc_error* (*listen)(grpc_custom_socket* socket);
- void (*accept)(grpc_custom_socket* socket, grpc_custom_socket* client,
- grpc_custom_accept_callback cb);
-
-cdef extern from "src/core/lib/iomgr/timer_custom.h":
- struct grpc_custom_timer:
- void* timer
- int timeout_ms
- # We don't care about the rest of the fields
-
- struct grpc_custom_timer_vtable:
- void (*start)(grpc_custom_timer* t);
- void (*stop)(grpc_custom_timer* t);
-
- void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error);
-
-cdef extern from "src/core/lib/iomgr/pollset_custom.h":
- struct grpc_custom_poller_vtable:
- void (*init)()
- void (*poll)(size_t timeout_ms)
- void (*kick)()
- void (*shutdown)()
-
-cdef extern from "src/core/lib/iomgr/iomgr_custom.h":
- void grpc_custom_iomgr_init(grpc_socket_vtable* socket,
- grpc_custom_resolver_vtable* resolver,
- grpc_custom_timer_vtable* timer,
- grpc_custom_poller_vtable* poller);
-
-cdef extern from "src/core/lib/iomgr/sockaddr_utils.h":
- int grpc_sockaddr_get_port(const grpc_resolved_address *addr);
+ struct grpc_custom_socket:
+ void* impl
+ # We don't care about the rest of the fields
+ ctypedef void (*grpc_custom_connect_callback)(grpc_custom_socket* socket,
+ grpc_error* error)
+ ctypedef void (*grpc_custom_write_callback)(grpc_custom_socket* socket,
+ grpc_error* error)
+ ctypedef void (*grpc_custom_read_callback)(grpc_custom_socket* socket,
+ size_t nread, grpc_error* error)
+ ctypedef void (*grpc_custom_accept_callback)(grpc_custom_socket* socket,
+ grpc_custom_socket* client,
+ grpc_error* error)
+ ctypedef void (*grpc_custom_close_callback)(grpc_custom_socket* socket)
+
+ struct grpc_socket_vtable:
+ grpc_error* (*init)(grpc_custom_socket* socket, int domain);
+ void (*connect)(grpc_custom_socket* socket, const grpc_sockaddr* addr,
+ size_t len, grpc_custom_connect_callback cb);
+ void (*destroy)(grpc_custom_socket* socket);
+ void (*shutdown)(grpc_custom_socket* socket);
+ void (*close)(grpc_custom_socket* socket, grpc_custom_close_callback cb);
+ void (*write)(grpc_custom_socket* socket, grpc_slice_buffer* slices,
+ grpc_custom_write_callback cb);
+ void (*read)(grpc_custom_socket* socket, char* buffer, size_t length,
+ grpc_custom_read_callback cb);
+ grpc_error* (*getpeername)(grpc_custom_socket* socket,
+ const grpc_sockaddr* addr, int* len);
+ grpc_error* (*getsockname)(grpc_custom_socket* socket,
+ const grpc_sockaddr* addr, int* len);
+ grpc_error* (*bind)(grpc_custom_socket* socket, const grpc_sockaddr* addr,
+ size_t len, int flags);
+ grpc_error* (*listen)(grpc_custom_socket* socket);
+ void (*accept)(grpc_custom_socket* socket, grpc_custom_socket* client,
+ grpc_custom_accept_callback cb);
+
+cdef extern from "src/core/lib/iomgr/timer_custom.h":
+ struct grpc_custom_timer:
+ void* timer
+ int timeout_ms
+ # We don't care about the rest of the fields
+
+ struct grpc_custom_timer_vtable:
+ void (*start)(grpc_custom_timer* t);
+ void (*stop)(grpc_custom_timer* t);
+
+ void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error);
+
+cdef extern from "src/core/lib/iomgr/pollset_custom.h":
+ struct grpc_custom_poller_vtable:
+ void (*init)()
+ void (*poll)(size_t timeout_ms)
+ void (*kick)()
+ void (*shutdown)()
+
+cdef extern from "src/core/lib/iomgr/iomgr_custom.h":
+ void grpc_custom_iomgr_init(grpc_socket_vtable* socket,
+ grpc_custom_resolver_vtable* resolver,
+ grpc_custom_timer_vtable* timer,
+ grpc_custom_poller_vtable* poller);
+
+cdef extern from "src/core/lib/iomgr/sockaddr_utils.h":
+ int grpc_sockaddr_get_port(const grpc_resolved_address *addr);
cppstring grpc_sockaddr_to_string(const grpc_resolved_address *addr,
bool_t normalize);
- void grpc_string_to_sockaddr(grpc_resolved_address *out, char* addr, int port);
- int grpc_sockaddr_set_port(const grpc_resolved_address *resolved_addr,
- int port)
- const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* resolved_addr)
+ void grpc_string_to_sockaddr(grpc_resolved_address *out, char* addr, int port);
+ int grpc_sockaddr_set_port(const grpc_resolved_address *resolved_addr,
+ int port)
+ const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* resolved_addr)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pyx.pxi
index 3d6bb24f9a..65d61cce38 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/iomgr.pyx.pxi
@@ -1,63 +1,63 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# distutils: language=c++
-
-from libc cimport string
-from libc.stdlib cimport malloc
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# distutils: language=c++
+
+from libc cimport string
+from libc.stdlib cimport malloc
from libcpp.string cimport string as cppstring
-
-cdef grpc_error* grpc_error_none():
- return <grpc_error*>0
-
-cdef grpc_error* socket_error(str syscall, str err):
- error_str = "{} failed: {}".format(syscall, err)
- error_bytes = str_to_bytes(error_str)
- return grpc_socket_error(error_bytes)
-
-cdef resolved_addr_to_tuple(grpc_resolved_address* address):
+
+cdef grpc_error* grpc_error_none():
+ return <grpc_error*>0
+
+cdef grpc_error* socket_error(str syscall, str err):
+ error_str = "{} failed: {}".format(syscall, err)
+ error_bytes = str_to_bytes(error_str)
+ return grpc_socket_error(error_bytes)
+
+cdef resolved_addr_to_tuple(grpc_resolved_address* address):
cdef cppstring res_str
- port = grpc_sockaddr_get_port(address)
+ port = grpc_sockaddr_get_port(address)
res_str = grpc_sockaddr_to_string(address, False)
byte_str = _decode(res_str)
- if byte_str.endswith(':' + str(port)):
- byte_str = byte_str[:(0 - len(str(port)) - 1)]
- byte_str = byte_str.lstrip('[')
- byte_str = byte_str.rstrip(']')
- byte_str = '{}'.format(byte_str)
- return byte_str, port
-
-cdef sockaddr_to_tuple(const grpc_sockaddr* address, size_t length):
- cdef grpc_resolved_address c_addr
- string.memcpy(<void*>c_addr.addr, <void*> address, length)
- c_addr.len = length
- return resolved_addr_to_tuple(&c_addr)
-
-cdef sockaddr_is_ipv4(const grpc_sockaddr* address, size_t length):
- cdef grpc_resolved_address c_addr
- string.memcpy(<void*>c_addr.addr, <void*> address, length)
- c_addr.len = length
- return grpc_sockaddr_get_uri_scheme(&c_addr) == b'ipv4'
-
-cdef grpc_resolved_addresses* tuples_to_resolvaddr(tups):
- cdef grpc_resolved_addresses* addresses
- tups_set = set((tup[4][0], tup[4][1]) for tup in tups)
- addresses = <grpc_resolved_addresses*> malloc(sizeof(grpc_resolved_addresses))
- addresses.naddrs = len(tups_set)
- addresses.addrs = <grpc_resolved_address*> malloc(sizeof(grpc_resolved_address) * len(tups_set))
- i = 0
- for tup in set(tups_set):
- hostname = str_to_bytes(tup[0])
- grpc_string_to_sockaddr(&addresses.addrs[i], hostname, tup[1])
- i += 1
- return addresses
+ if byte_str.endswith(':' + str(port)):
+ byte_str = byte_str[:(0 - len(str(port)) - 1)]
+ byte_str = byte_str.lstrip('[')
+ byte_str = byte_str.rstrip(']')
+ byte_str = '{}'.format(byte_str)
+ return byte_str, port
+
+cdef sockaddr_to_tuple(const grpc_sockaddr* address, size_t length):
+ cdef grpc_resolved_address c_addr
+ string.memcpy(<void*>c_addr.addr, <void*> address, length)
+ c_addr.len = length
+ return resolved_addr_to_tuple(&c_addr)
+
+cdef sockaddr_is_ipv4(const grpc_sockaddr* address, size_t length):
+ cdef grpc_resolved_address c_addr
+ string.memcpy(<void*>c_addr.addr, <void*> address, length)
+ c_addr.len = length
+ return grpc_sockaddr_get_uri_scheme(&c_addr) == b'ipv4'
+
+cdef grpc_resolved_addresses* tuples_to_resolvaddr(tups):
+ cdef grpc_resolved_addresses* addresses
+ tups_set = set((tup[4][0], tup[4][1]) for tup in tups)
+ addresses = <grpc_resolved_addresses*> malloc(sizeof(grpc_resolved_addresses))
+ addresses.naddrs = len(tups_set)
+ addresses.addrs = <grpc_resolved_address*> malloc(sizeof(grpc_resolved_address) * len(tups_set))
+ i = 0
+ for tup in set(tups_set):
+ hostname = str_to_bytes(tup[0])
+ grpc_string_to_sockaddr(&addresses.addrs[i], hostname, tup[1])
+ i += 1
+ return addresses
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi
index 308d677695..9e1e6b3ba4 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi
@@ -108,12 +108,12 @@ class OperationType:
receive_status_on_client = GRPC_OP_RECV_STATUS_ON_CLIENT
receive_close_on_server = GRPC_OP_RECV_CLOSE_ON_SERVER
-GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM= (
- _GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM)
-
-GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY = (
- _GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY)
+GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM= (
+ _GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM)
+GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY = (
+ _GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY)
+
class CompressionAlgorithm:
none = GRPC_COMPRESS_NONE
deflate = GRPC_COMPRESS_DEFLATE
@@ -137,7 +137,7 @@ cdef class CallDetails:
def __dealloc__(self):
with nogil:
grpc_call_details_destroy(&self.c_details)
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
@property
def method(self):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi
index b89ed99d97..8c777169cb 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi
@@ -15,7 +15,7 @@
cdef class Server:
cdef grpc_server *c_server
-
+
cdef bint is_started # start has been called
cdef bint is_shutting_down # shutdown has been called
cdef bint is_shutdown # notification of complete shutdown received
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi
index eff95c4f29..306b779601 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi
@@ -22,10 +22,10 @@ cdef class Server:
self.is_started = False
self.is_shutting_down = False
self.is_shutdown = False
- self.c_server = NULL
- cdef _ChannelArgs channel_args = _ChannelArgs(arguments)
- self.c_server = grpc_server_create(channel_args.c_args(), NULL)
- self.references.append(arguments)
+ self.c_server = NULL
+ cdef _ChannelArgs channel_args = _ChannelArgs(arguments)
+ self.c_server = grpc_server_create(channel_args.c_args(), NULL)
+ self.references.append(arguments)
def request_call(
self, CompletionQueue call_queue not None,
@@ -53,25 +53,25 @@ cdef class Server:
self.c_server, queue.c_completion_queue, NULL)
self.registered_completion_queues.append(queue)
- def start(self, backup_queue=True):
- """Start the Cython gRPC Server.
-
- Args:
- backup_queue: a bool indicates whether to spawn a backup completion
- queue. In the case that no CQ is bound to the server, and the shutdown
- of server becomes un-observable.
- """
+ def start(self, backup_queue=True):
+ """Start the Cython gRPC Server.
+
+ Args:
+ backup_queue: a bool indicates whether to spawn a backup completion
+ queue. In the case that no CQ is bound to the server, and the shutdown
+ of server becomes un-observable.
+ """
if self.is_started:
raise ValueError("the server has already started")
- if backup_queue:
- self.backup_shutdown_queue = CompletionQueue(shutdown_cq=True)
- self.register_completion_queue(self.backup_shutdown_queue)
+ if backup_queue:
+ self.backup_shutdown_queue = CompletionQueue(shutdown_cq=True)
+ self.register_completion_queue(self.backup_shutdown_queue)
self.is_started = True
with nogil:
grpc_server_start(self.c_server)
- if backup_queue:
- # Ensure the core has gotten a chance to do the start-up work
- self.backup_shutdown_queue.poll(deadline=time.time())
+ if backup_queue:
+ # Ensure the core has gotten a chance to do the start-up work
+ self.backup_shutdown_queue.poll(deadline=time.time())
def add_http2_port(self, bytes address,
ServerCredentials server_credentials=None):
@@ -135,14 +135,14 @@ cdef class Server:
elif self.is_shutdown:
pass
elif not self.is_shutting_down:
- if self.backup_shutdown_queue is None:
+ if self.backup_shutdown_queue is None:
raise InternalError('Server shutdown failed: no completion queue.')
- else:
- # the user didn't call shutdown - use our backup queue
- self._c_shutdown(self.backup_shutdown_queue, None)
- # and now we wait
- while not self.is_shutdown:
- self.backup_shutdown_queue.poll()
+ else:
+ # the user didn't call shutdown - use our backup queue
+ self._c_shutdown(self.backup_shutdown_queue, None)
+ # and now we wait
+ while not self.is_shutdown:
+ self.backup_shutdown_queue.poll()
else:
# We're in the process of shutting down, but have not shutdown; can't do
# much but repeatedly release the GIL and wait
@@ -154,4 +154,4 @@ cdef class Server:
def __dealloc__(self):
if self.c_server == NULL:
- grpc_shutdown_blocking()
+ grpc_shutdown_blocking()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi
index e80dc88767..e3cc059e65 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi
@@ -56,19 +56,19 @@ cdef class _BatchOperationTag:
self._retained_call = call
cdef void prepare(self) except *:
- cdef Operation operation
+ cdef Operation operation
self.c_nops = 0 if self._operations is None else len(self._operations)
if 0 < self.c_nops:
self.c_ops = <grpc_op *>gpr_malloc(sizeof(grpc_op) * self.c_nops)
for index, operation in enumerate(self._operations):
- operation.c()
- self.c_ops[index] = operation.c_op
+ operation.c()
+ self.c_ops[index] = operation.c_op
cdef BatchOperationEvent event(self, grpc_event c_event):
- cdef Operation operation
+ cdef Operation operation
if 0 < self.c_nops:
- for operation in self._operations:
- operation.un_c()
+ for operation in self._operations:
+ operation.un_c()
gpr_free(self.c_ops)
return BatchOperationEvent(
c_event.type, c_event.success, self._user_tag, self._operations)
@@ -85,4 +85,4 @@ cdef class _ServerShutdownTag(_Tag):
cdef ServerShutdownEvent event(self, grpc_event c_event):
self._shutting_down_server.notify_shutdown_complete()
- return ServerShutdownEvent(c_event.type, c_event.success, self._user_tag)
+ return ServerShutdownEvent(c_event.type, c_event.success, self._user_tag)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi
index c46e8a98b0..f81ac229c3 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi
@@ -13,7 +13,7 @@
# limitations under the License.
-cdef gpr_timespec _timespec_from_time(object time) except *
+cdef gpr_timespec _timespec_from_time(object time) except *
cdef double _time_from_timespec(gpr_timespec timespec) except *
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi
index 6d181bb1d6..c8d1b6307e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi
@@ -13,17 +13,17 @@
# limitations under the License.
-cdef gpr_timespec _timespec_from_time(object time) except *:
+cdef gpr_timespec _timespec_from_time(object time) except *:
if time is None:
return gpr_inf_future(GPR_CLOCK_REALTIME)
else:
- return gpr_time_from_nanos(
- <int64_t>(<double>time * GPR_NS_PER_SEC),
- GPR_CLOCK_REALTIME,
- )
+ return gpr_time_from_nanos(
+ <int64_t>(<double>time * GPR_NS_PER_SEC),
+ GPR_CLOCK_REALTIME,
+ )
cdef double _time_from_timespec(gpr_timespec timespec) except *:
cdef gpr_timespec real_timespec = gpr_convert_clock_type(
timespec, GPR_CLOCK_REALTIME)
- return gpr_timespec_to_micros(real_timespec) / GPR_US_PER_SEC
+ return gpr_timespec_to_micros(real_timespec) / GPR_US_PER_SEC
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pxd.pxi
index c96e5cb669..8d1f75064e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pxd.pxi
@@ -1,23 +1,23 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-cdef void* _copy_pointer(void* pointer)
-
-cdef void _destroy_pointer(void* pointer)
-
-cdef int _compare_pointer(void* first_pointer, void* second_pointer)
-
-
-cdef grpc_arg_pointer_vtable default_vtable
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+cdef void* _copy_pointer(void* pointer)
+
+cdef void _destroy_pointer(void* pointer)
+
+cdef int _compare_pointer(void* first_pointer, void* second_pointer)
+
+
+cdef grpc_arg_pointer_vtable default_vtable
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pyx.pxi
index da4b81bd97..71f927dcff 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/vtable.pyx.pxi
@@ -1,36 +1,36 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# TODO(https://github.com/grpc/grpc/issues/15662): Reform this.
-cdef void* _copy_pointer(void* pointer):
- return pointer
-
-
-# TODO(https://github.com/grpc/grpc/issues/15662): Reform this.
-cdef void _destroy_pointer(void* pointer):
- pass
-
-
-cdef int _compare_pointer(void* first_pointer, void* second_pointer):
- if first_pointer < second_pointer:
- return -1
- elif first_pointer > second_pointer:
- return 1
- else:
- return 0
-
-cdef grpc_arg_pointer_vtable default_vtable
-default_vtable.copy = &_copy_pointer
-default_vtable.destroy = &_destroy_pointer
-default_vtable.cmp = &_compare_pointer
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# TODO(https://github.com/grpc/grpc/issues/15662): Reform this.
+cdef void* _copy_pointer(void* pointer):
+ return pointer
+
+
+# TODO(https://github.com/grpc/grpc/issues/15662): Reform this.
+cdef void _destroy_pointer(void* pointer):
+ pass
+
+
+cdef int _compare_pointer(void* first_pointer, void* second_pointer):
+ if first_pointer < second_pointer:
+ return -1
+ elif first_pointer > second_pointer:
+ return 1
+ else:
+ return 0
+
+cdef grpc_arg_pointer_vtable default_vtable
+default_vtable.copy = &_copy_pointer
+default_vtable.destroy = &_destroy_pointer
+default_vtable.cmp = &_compare_pointer
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd
index 166be37022..a20909b5ae 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd
@@ -25,30 +25,30 @@ include "_cygrpc/completion_queue.pxd.pxi"
include "_cygrpc/event.pxd.pxi"
include "_cygrpc/metadata.pxd.pxi"
include "_cygrpc/operation.pxd.pxi"
-include "_cygrpc/propagation_bits.pxd.pxi"
+include "_cygrpc/propagation_bits.pxd.pxi"
include "_cygrpc/records.pxd.pxi"
include "_cygrpc/security.pxd.pxi"
include "_cygrpc/server.pxd.pxi"
include "_cygrpc/tag.pxd.pxi"
include "_cygrpc/time.pxd.pxi"
-include "_cygrpc/vtable.pxd.pxi"
+include "_cygrpc/vtable.pxd.pxi"
include "_cygrpc/_hooks.pxd.pxi"
-include "_cygrpc/iomgr.pxd.pxi"
-
+include "_cygrpc/iomgr.pxd.pxi"
+
include "_cygrpc/grpc_gevent.pxd.pxi"
IF UNAME_SYSNAME != "Windows":
include "_cygrpc/fork_posix.pxd.pxi"
-
-# Following pxi files are part of the Aio module
-include "_cygrpc/aio/iomgr/socket.pxd.pxi"
-include "_cygrpc/aio/iomgr/timer.pxd.pxi"
-include "_cygrpc/aio/iomgr/resolver.pxd.pxi"
+
+# Following pxi files are part of the Aio module
+include "_cygrpc/aio/iomgr/socket.pxd.pxi"
+include "_cygrpc/aio/iomgr/timer.pxd.pxi"
+include "_cygrpc/aio/iomgr/resolver.pxd.pxi"
include "_cygrpc/aio/completion_queue.pxd.pxi"
include "_cygrpc/aio/rpc_status.pxd.pxi"
-include "_cygrpc/aio/grpc_aio.pxd.pxi"
-include "_cygrpc/aio/callback_common.pxd.pxi"
-include "_cygrpc/aio/call.pxd.pxi"
-include "_cygrpc/aio/channel.pxd.pxi"
-include "_cygrpc/aio/server.pxd.pxi"
+include "_cygrpc/aio/grpc_aio.pxd.pxi"
+include "_cygrpc/aio/callback_common.pxd.pxi"
+include "_cygrpc/aio/call.pxd.pxi"
+include "_cygrpc/aio/channel.pxd.pxi"
+include "_cygrpc/aio/server.pxd.pxi"
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx
index 8d355c6fbb..702a583461 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx
@@ -23,13 +23,13 @@ import time
import grpc
-try:
- import asyncio
-except ImportError:
- # TODO(https://github.com/grpc/grpc/issues/19728) Improve how Aio Cython is
- # distributed without breaking none compatible Python versions. For now, if
- # Asyncio package is not available we just skip it.
- pass
+try:
+ import asyncio
+except ImportError:
+ # TODO(https://github.com/grpc/grpc/issues/19728) Improve how Aio Cython is
+ # distributed without breaking none compatible Python versions. For now, if
+ # Asyncio package is not available we just skip it.
+ pass
# The only copy of Python logger for the Cython extension
_LOGGER = logging.getLogger(__name__)
@@ -40,23 +40,23 @@ include "_cygrpc/grpc_string.pyx.pxi"
include "_cygrpc/arguments.pyx.pxi"
include "_cygrpc/call.pyx.pxi"
include "_cygrpc/channel.pyx.pxi"
-include "_cygrpc/channelz.pyx.pxi"
+include "_cygrpc/channelz.pyx.pxi"
include "_cygrpc/credentials.pyx.pxi"
include "_cygrpc/completion_queue.pyx.pxi"
include "_cygrpc/event.pyx.pxi"
include "_cygrpc/metadata.pyx.pxi"
include "_cygrpc/operation.pyx.pxi"
-include "_cygrpc/propagation_bits.pyx.pxi"
+include "_cygrpc/propagation_bits.pyx.pxi"
include "_cygrpc/records.pyx.pxi"
include "_cygrpc/security.pyx.pxi"
include "_cygrpc/server.pyx.pxi"
include "_cygrpc/tag.pyx.pxi"
include "_cygrpc/time.pyx.pxi"
-include "_cygrpc/vtable.pyx.pxi"
+include "_cygrpc/vtable.pyx.pxi"
include "_cygrpc/_hooks.pyx.pxi"
-include "_cygrpc/iomgr.pyx.pxi"
-
+include "_cygrpc/iomgr.pyx.pxi"
+
include "_cygrpc/grpc_gevent.pyx.pxi"
include "_cygrpc/thread.pyx.pxi"
@@ -66,21 +66,21 @@ IF UNAME_SYSNAME == "Windows":
ELSE:
include "_cygrpc/fork_posix.pyx.pxi"
-# Following pxi files are part of the Aio module
-include "_cygrpc/aio/iomgr/iomgr.pyx.pxi"
-include "_cygrpc/aio/iomgr/socket.pyx.pxi"
-include "_cygrpc/aio/iomgr/timer.pyx.pxi"
-include "_cygrpc/aio/iomgr/resolver.pyx.pxi"
+# Following pxi files are part of the Aio module
+include "_cygrpc/aio/iomgr/iomgr.pyx.pxi"
+include "_cygrpc/aio/iomgr/socket.pyx.pxi"
+include "_cygrpc/aio/iomgr/timer.pyx.pxi"
+include "_cygrpc/aio/iomgr/resolver.pyx.pxi"
include "_cygrpc/aio/common.pyx.pxi"
include "_cygrpc/aio/rpc_status.pyx.pxi"
include "_cygrpc/aio/completion_queue.pyx.pxi"
include "_cygrpc/aio/callback_common.pyx.pxi"
-include "_cygrpc/aio/grpc_aio.pyx.pxi"
-include "_cygrpc/aio/call.pyx.pxi"
-include "_cygrpc/aio/channel.pyx.pxi"
-include "_cygrpc/aio/server.pyx.pxi"
-
-
+include "_cygrpc/aio/grpc_aio.pyx.pxi"
+include "_cygrpc/aio/call.pyx.pxi"
+include "_cygrpc/aio/channel.pyx.pxi"
+include "_cygrpc/aio/server.pyx.pxi"
+
+
#
# initialize gRPC
#
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py b/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py
index ee63cb3145..4219be1548 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py
@@ -44,9 +44,9 @@ def service_pipeline(interceptors):
class _ClientCallDetails(
- collections.namedtuple('_ClientCallDetails',
- ('method', 'timeout', 'metadata', 'credentials',
- 'wait_for_ready', 'compression')),
+ collections.namedtuple('_ClientCallDetails',
+ ('method', 'timeout', 'metadata', 'credentials',
+ 'wait_for_ready', 'compression')),
grpc.ClientCallDetails):
pass
@@ -77,16 +77,16 @@ def _unwrap_client_call_details(call_details, default_details):
except AttributeError:
wait_for_ready = default_details.wait_for_ready
- try:
- compression = call_details.compression
- except AttributeError:
- compression = default_details.compression
-
- return method, timeout, metadata, credentials, wait_for_ready, compression
+ try:
+ compression = call_details.compression
+ except AttributeError:
+ compression = default_details.compression
+ return method, timeout, metadata, credentials, wait_for_ready, compression
-class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable=too-many-ancestors
+class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable=too-many-ancestors
+
def __init__(self, exception, traceback):
super(_FailureOutcome, self).__init__()
self._exception = exception
@@ -131,7 +131,7 @@ class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable
def traceback(self, ignored_timeout=None):
return self._traceback
- def add_callback(self, unused_callback):
+ def add_callback(self, unused_callback):
return False
def add_done_callback(self, fn):
@@ -211,8 +211,8 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
response, ignored_call = self._with_call(request,
timeout=timeout,
metadata=metadata,
@@ -226,25 +226,25 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
- client_call_details = _ClientCallDetails(self._method, timeout,
- metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready=None,
+ compression=None):
+ client_call_details = _ClientCallDetails(self._method, timeout,
+ metadata, credentials,
+ wait_for_ready, compression)
def continuation(new_details, request):
- (new_method, new_timeout, new_metadata, new_credentials,
- new_wait_for_ready,
- new_compression) = (_unwrap_client_call_details(
- new_details, client_call_details))
+ (new_method, new_timeout, new_metadata, new_credentials,
+ new_wait_for_ready,
+ new_compression) = (_unwrap_client_call_details(
+ new_details, client_call_details))
try:
response, call = self._thunk(new_method).with_call(
request,
timeout=new_timeout,
metadata=new_metadata,
credentials=new_credentials,
- wait_for_ready=new_wait_for_ready,
- compression=new_compression)
+ wait_for_ready=new_wait_for_ready,
+ compression=new_compression)
return _UnaryOutcome(response, call)
except grpc.RpcError as rpc_error:
return rpc_error
@@ -261,8 +261,8 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
return self._with_call(request,
timeout=timeout,
metadata=metadata,
@@ -275,24 +275,24 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
- client_call_details = _ClientCallDetails(self._method, timeout,
- metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready=None,
+ compression=None):
+ client_call_details = _ClientCallDetails(self._method, timeout,
+ metadata, credentials,
+ wait_for_ready, compression)
def continuation(new_details, request):
- (new_method, new_timeout, new_metadata, new_credentials,
- new_wait_for_ready,
- new_compression) = (_unwrap_client_call_details(
- new_details, client_call_details))
+ (new_method, new_timeout, new_metadata, new_credentials,
+ new_wait_for_ready,
+ new_compression) = (_unwrap_client_call_details(
+ new_details, client_call_details))
return self._thunk(new_method).future(
request,
timeout=new_timeout,
metadata=new_metadata,
credentials=new_credentials,
- wait_for_ready=new_wait_for_ready,
- compression=new_compression)
+ wait_for_ready=new_wait_for_ready,
+ compression=new_compression)
try:
return self._interceptor.intercept_unary_unary(
@@ -313,17 +313,17 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
- client_call_details = _ClientCallDetails(self._method, timeout,
- metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready=None,
+ compression=None):
+ client_call_details = _ClientCallDetails(self._method, timeout,
+ metadata, credentials,
+ wait_for_ready, compression)
def continuation(new_details, request):
- (new_method, new_timeout, new_metadata, new_credentials,
- new_wait_for_ready,
- new_compression) = (_unwrap_client_call_details(
- new_details, client_call_details))
+ (new_method, new_timeout, new_metadata, new_credentials,
+ new_wait_for_ready,
+ new_compression) = (_unwrap_client_call_details(
+ new_details, client_call_details))
return self._thunk(new_method)(request,
timeout=new_timeout,
metadata=new_metadata,
@@ -350,8 +350,8 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
response, ignored_call = self._with_call(request_iterator,
timeout=timeout,
metadata=metadata,
@@ -365,25 +365,25 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
- client_call_details = _ClientCallDetails(self._method, timeout,
- metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready=None,
+ compression=None):
+ client_call_details = _ClientCallDetails(self._method, timeout,
+ metadata, credentials,
+ wait_for_ready, compression)
def continuation(new_details, request_iterator):
- (new_method, new_timeout, new_metadata, new_credentials,
- new_wait_for_ready,
- new_compression) = (_unwrap_client_call_details(
- new_details, client_call_details))
+ (new_method, new_timeout, new_metadata, new_credentials,
+ new_wait_for_ready,
+ new_compression) = (_unwrap_client_call_details(
+ new_details, client_call_details))
try:
response, call = self._thunk(new_method).with_call(
request_iterator,
timeout=new_timeout,
metadata=new_metadata,
credentials=new_credentials,
- wait_for_ready=new_wait_for_ready,
- compression=new_compression)
+ wait_for_ready=new_wait_for_ready,
+ compression=new_compression)
return _UnaryOutcome(response, call)
except grpc.RpcError as rpc_error:
return rpc_error
@@ -400,8 +400,8 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
+ wait_for_ready=None,
+ compression=None):
return self._with_call(request_iterator,
timeout=timeout,
metadata=metadata,
@@ -414,24 +414,24 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
- client_call_details = _ClientCallDetails(self._method, timeout,
- metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready=None,
+ compression=None):
+ client_call_details = _ClientCallDetails(self._method, timeout,
+ metadata, credentials,
+ wait_for_ready, compression)
def continuation(new_details, request_iterator):
- (new_method, new_timeout, new_metadata, new_credentials,
- new_wait_for_ready,
- new_compression) = (_unwrap_client_call_details(
- new_details, client_call_details))
+ (new_method, new_timeout, new_metadata, new_credentials,
+ new_wait_for_ready,
+ new_compression) = (_unwrap_client_call_details(
+ new_details, client_call_details))
return self._thunk(new_method).future(
request_iterator,
timeout=new_timeout,
metadata=new_metadata,
credentials=new_credentials,
- wait_for_ready=new_wait_for_ready,
- compression=new_compression)
+ wait_for_ready=new_wait_for_ready,
+ compression=new_compression)
try:
return self._interceptor.intercept_stream_unary(
@@ -452,17 +452,17 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
timeout=None,
metadata=None,
credentials=None,
- wait_for_ready=None,
- compression=None):
- client_call_details = _ClientCallDetails(self._method, timeout,
- metadata, credentials,
- wait_for_ready, compression)
+ wait_for_ready=None,
+ compression=None):
+ client_call_details = _ClientCallDetails(self._method, timeout,
+ metadata, credentials,
+ wait_for_ready, compression)
def continuation(new_details, request_iterator):
- (new_method, new_timeout, new_metadata, new_credentials,
- new_wait_for_ready,
- new_compression) = (_unwrap_client_call_details(
- new_details, client_call_details))
+ (new_method, new_timeout, new_metadata, new_credentials,
+ new_wait_for_ready,
+ new_compression) = (_unwrap_client_call_details(
+ new_details, client_call_details))
return self._thunk(new_method)(request_iterator,
timeout=new_timeout,
metadata=new_metadata,
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_server.py b/contrib/libs/grpc/src/python/grpcio/grpc/_server.py
index 48ff743995..d77bbf755d 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_server.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_server.py
@@ -19,12 +19,12 @@ import logging
import threading
import time
-from concurrent import futures
+from concurrent import futures
import six
import grpc
from grpc import _common
-from grpc import _compression
+from grpc import _compression
from grpc import _interceptor
from grpc._cython import cygrpc
@@ -50,7 +50,7 @@ _CANCELLED = 'cancelled'
_EMPTY_FLAGS = 0
_DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0
-_INF_TIMEOUT = 1e9
+_INF_TIMEOUT = 1e9
def _serialized_request(request_event):
@@ -96,7 +96,7 @@ class _RPCState(object):
self.request = None
self.client = _OPEN
self.initial_metadata_allowed = True
- self.compression_algorithm = None
+ self.compression_algorithm = None
self.disable_next_compression = False
self.trailing_metadata = None
self.code = None
@@ -115,7 +115,7 @@ def _raise_rpc_error(state):
def _possibly_finish_call(state, token):
state.due.remove(token)
- if not _is_rpc_state_active(state) and not state.due:
+ if not _is_rpc_state_active(state) and not state.due:
callbacks = state.callbacks
state.callbacks = None
return state, callbacks
@@ -132,33 +132,33 @@ def _send_status_from_server(state, token):
return send_status_from_server
-def _get_initial_metadata(state, metadata):
- with state.condition:
- if state.compression_algorithm:
- compression_metadata = (
- _compression.compression_algorithm_to_metadata(
- state.compression_algorithm),)
- if metadata is None:
- return compression_metadata
- else:
- return compression_metadata + tuple(metadata)
- else:
- return metadata
-
-
-def _get_initial_metadata_operation(state, metadata):
- operation = cygrpc.SendInitialMetadataOperation(
- _get_initial_metadata(state, metadata), _EMPTY_FLAGS)
- return operation
-
-
+def _get_initial_metadata(state, metadata):
+ with state.condition:
+ if state.compression_algorithm:
+ compression_metadata = (
+ _compression.compression_algorithm_to_metadata(
+ state.compression_algorithm),)
+ if metadata is None:
+ return compression_metadata
+ else:
+ return compression_metadata + tuple(metadata)
+ else:
+ return metadata
+
+
+def _get_initial_metadata_operation(state, metadata):
+ operation = cygrpc.SendInitialMetadataOperation(
+ _get_initial_metadata(state, metadata), _EMPTY_FLAGS)
+ return operation
+
+
def _abort(state, call, code, details):
if state.client is not _CANCELLED:
effective_code = _abortion_code(state, code)
effective_details = details if state.details is None else state.details
if state.initial_metadata_allowed:
operations = (
- _get_initial_metadata_operation(state, None),
+ _get_initial_metadata_operation(state, None),
cygrpc.SendStatusFromServerOperation(state.trailing_metadata,
effective_code,
effective_details,
@@ -243,7 +243,7 @@ class _Context(grpc.ServicerContext):
def is_active(self):
with self._state.condition:
- return _is_rpc_state_active(self._state)
+ return _is_rpc_state_active(self._state)
def time_remaining(self):
return max(self._rpc_event.call_details.deadline - time.time(), 0)
@@ -282,18 +282,18 @@ class _Context(grpc.ServicerContext):
cygrpc.auth_context(self._rpc_event.call))
}
- def set_compression(self, compression):
- with self._state.condition:
- self._state.compression_algorithm = compression
-
+ def set_compression(self, compression):
+ with self._state.condition:
+ self._state.compression_algorithm = compression
+
def send_initial_metadata(self, initial_metadata):
with self._state.condition:
if self._state.client is _CANCELLED:
_raise_rpc_error(self._state)
else:
if self._state.initial_metadata_allowed:
- operation = _get_initial_metadata_operation(
- self._state, initial_metadata)
+ operation = _get_initial_metadata_operation(
+ self._state, initial_metadata)
self._rpc_event.call.start_server_batch(
(operation,), _send_initial_metadata(self._state))
self._state.initial_metadata_allowed = False
@@ -330,10 +330,10 @@ class _Context(grpc.ServicerContext):
with self._state.condition:
self._state.details = _common.encode(details)
- def _finalize_state(self):
- pass
-
+ def _finalize_state(self):
+ pass
+
class _RequestIterator(object):
def __init__(self, state, call, request_deserializer):
@@ -344,7 +344,7 @@ class _RequestIterator(object):
def _raise_or_start_receive_message(self):
if self._state.client is _CANCELLED:
_raise_rpc_error(self._state)
- elif not _is_rpc_state_active(self._state):
+ elif not _is_rpc_state_active(self._state):
raise StopIteration()
else:
self._call.start_server_batch(
@@ -389,7 +389,7 @@ def _unary_request(rpc_event, state, request_deserializer):
def unary_request():
with state.condition:
- if not _is_rpc_state_active(state):
+ if not _is_rpc_state_active(state):
return None
else:
rpc_event.call.start_server_batch(
@@ -417,35 +417,35 @@ def _unary_request(rpc_event, state, request_deserializer):
return unary_request
-def _call_behavior(rpc_event,
- state,
- behavior,
- argument,
- request_deserializer,
- send_response_callback=None):
- from grpc import _create_servicer_context
- with _create_servicer_context(rpc_event, state,
- request_deserializer) as context:
- try:
- response_or_iterator = None
- if send_response_callback is not None:
- response_or_iterator = behavior(argument, context,
- send_response_callback)
- else:
- response_or_iterator = behavior(argument, context)
- return response_or_iterator, True
- except Exception as exception: # pylint: disable=broad-except
- with state.condition:
- if state.aborted:
- _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
- b'RPC Aborted')
- elif exception not in state.rpc_errors:
- details = 'Exception calling application: {}'.format(
- exception)
- _LOGGER.exception(details)
- _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
- _common.encode(details))
- return None, False
+def _call_behavior(rpc_event,
+ state,
+ behavior,
+ argument,
+ request_deserializer,
+ send_response_callback=None):
+ from grpc import _create_servicer_context
+ with _create_servicer_context(rpc_event, state,
+ request_deserializer) as context:
+ try:
+ response_or_iterator = None
+ if send_response_callback is not None:
+ response_or_iterator = behavior(argument, context,
+ send_response_callback)
+ else:
+ response_or_iterator = behavior(argument, context)
+ return response_or_iterator, True
+ except Exception as exception: # pylint: disable=broad-except
+ with state.condition:
+ if state.aborted:
+ _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
+ b'RPC Aborted')
+ elif exception not in state.rpc_errors:
+ details = 'Exception calling application: {}'.format(
+ exception)
+ _LOGGER.exception(details)
+ _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
+ _common.encode(details))
+ return None, False
def _take_response_from_response_iterator(rpc_event, state, response_iterator):
@@ -477,45 +477,45 @@ def _serialize_response(rpc_event, state, response, response_serializer):
return serialized_response
-def _get_send_message_op_flags_from_state(state):
- if state.disable_next_compression:
- return cygrpc.WriteFlag.no_compress
- else:
- return _EMPTY_FLAGS
-
-
-def _reset_per_message_state(state):
- with state.condition:
- state.disable_next_compression = False
-
-
+def _get_send_message_op_flags_from_state(state):
+ if state.disable_next_compression:
+ return cygrpc.WriteFlag.no_compress
+ else:
+ return _EMPTY_FLAGS
+
+
+def _reset_per_message_state(state):
+ with state.condition:
+ state.disable_next_compression = False
+
+
def _send_response(rpc_event, state, serialized_response):
with state.condition:
- if not _is_rpc_state_active(state):
+ if not _is_rpc_state_active(state):
return False
else:
if state.initial_metadata_allowed:
operations = (
- _get_initial_metadata_operation(state, None),
- cygrpc.SendMessageOperation(
- serialized_response,
- _get_send_message_op_flags_from_state(state)),
+ _get_initial_metadata_operation(state, None),
+ cygrpc.SendMessageOperation(
+ serialized_response,
+ _get_send_message_op_flags_from_state(state)),
)
state.initial_metadata_allowed = False
token = _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN
else:
operations = (cygrpc.SendMessageOperation(
- serialized_response,
- _get_send_message_op_flags_from_state(state)),)
+ serialized_response,
+ _get_send_message_op_flags_from_state(state)),)
token = _SEND_MESSAGE_TOKEN
rpc_event.call.start_server_batch(operations,
_send_message(state, token))
state.due.add(token)
- _reset_per_message_state(state)
+ _reset_per_message_state(state)
while True:
state.condition.wait()
if token not in state.due:
- return _is_rpc_state_active(state)
+ return _is_rpc_state_active(state)
def _status(rpc_event, state, serialized_response):
@@ -529,23 +529,23 @@ def _status(rpc_event, state, serialized_response):
_EMPTY_FLAGS),
]
if state.initial_metadata_allowed:
- operations.append(_get_initial_metadata_operation(state, None))
+ operations.append(_get_initial_metadata_operation(state, None))
if serialized_response is not None:
operations.append(
- cygrpc.SendMessageOperation(
- serialized_response,
- _get_send_message_op_flags_from_state(state)))
+ cygrpc.SendMessageOperation(
+ serialized_response,
+ _get_send_message_op_flags_from_state(state)))
rpc_event.call.start_server_batch(
operations,
_send_status_from_server(state, _SEND_STATUS_FROM_SERVER_TOKEN))
state.statused = True
- _reset_per_message_state(state)
+ _reset_per_message_state(state)
state.due.add(_SEND_STATUS_FROM_SERVER_TOKEN)
def _unary_response_in_pool(rpc_event, state, behavior, argument_thunk,
request_deserializer, response_serializer):
- cygrpc.install_context_from_request_call_event(rpc_event)
+ cygrpc.install_context_from_request_call_event(rpc_event)
try:
argument = argument_thunk()
if argument is not None:
@@ -562,92 +562,92 @@ def _unary_response_in_pool(rpc_event, state, behavior, argument_thunk,
def _stream_response_in_pool(rpc_event, state, behavior, argument_thunk,
request_deserializer, response_serializer):
- cygrpc.install_context_from_request_call_event(rpc_event)
-
- def send_response(response):
- if response is None:
- _status(rpc_event, state, None)
- else:
+ cygrpc.install_context_from_request_call_event(rpc_event)
+
+ def send_response(response):
+ if response is None:
+ _status(rpc_event, state, None)
+ else:
serialized_response = _serialize_response(rpc_event, state,
response,
response_serializer)
- if serialized_response is not None:
- _send_response(rpc_event, state, serialized_response)
-
+ if serialized_response is not None:
+ _send_response(rpc_event, state, serialized_response)
+
try:
argument = argument_thunk()
if argument is not None:
- if hasattr(behavior, 'experimental_non_blocking'
- ) and behavior.experimental_non_blocking:
+ if hasattr(behavior, 'experimental_non_blocking'
+ ) and behavior.experimental_non_blocking:
_call_behavior(rpc_event,
state,
behavior,
argument,
request_deserializer,
send_response_callback=send_response)
- else:
- response_iterator, proceed = _call_behavior(
- rpc_event, state, behavior, argument, request_deserializer)
- if proceed:
- _send_message_callback_to_blocking_iterator_adapter(
- rpc_event, state, send_response, response_iterator)
+ else:
+ response_iterator, proceed = _call_behavior(
+ rpc_event, state, behavior, argument, request_deserializer)
+ if proceed:
+ _send_message_callback_to_blocking_iterator_adapter(
+ rpc_event, state, send_response, response_iterator)
finally:
cygrpc.uninstall_context()
-def _is_rpc_state_active(state):
- return state.client is not _CANCELLED and not state.statused
-
-
+def _is_rpc_state_active(state):
+ return state.client is not _CANCELLED and not state.statused
+
+
def _send_message_callback_to_blocking_iterator_adapter(rpc_event, state,
send_response_callback,
response_iterator):
- while True:
- response, proceed = _take_response_from_response_iterator(
- rpc_event, state, response_iterator)
- if proceed:
- send_response_callback(response)
- if not _is_rpc_state_active(state):
- break
- else:
- break
-
-
-def _select_thread_pool_for_behavior(behavior, default_thread_pool):
- if hasattr(behavior, 'experimental_thread_pool') and isinstance(
- behavior.experimental_thread_pool, futures.ThreadPoolExecutor):
- return behavior.experimental_thread_pool
- else:
- return default_thread_pool
-
-
-def _handle_unary_unary(rpc_event, state, method_handler, default_thread_pool):
+ while True:
+ response, proceed = _take_response_from_response_iterator(
+ rpc_event, state, response_iterator)
+ if proceed:
+ send_response_callback(response)
+ if not _is_rpc_state_active(state):
+ break
+ else:
+ break
+
+
+def _select_thread_pool_for_behavior(behavior, default_thread_pool):
+ if hasattr(behavior, 'experimental_thread_pool') and isinstance(
+ behavior.experimental_thread_pool, futures.ThreadPoolExecutor):
+ return behavior.experimental_thread_pool
+ else:
+ return default_thread_pool
+
+
+def _handle_unary_unary(rpc_event, state, method_handler, default_thread_pool):
unary_request = _unary_request(rpc_event, state,
method_handler.request_deserializer)
- thread_pool = _select_thread_pool_for_behavior(method_handler.unary_unary,
- default_thread_pool)
+ thread_pool = _select_thread_pool_for_behavior(method_handler.unary_unary,
+ default_thread_pool)
return thread_pool.submit(_unary_response_in_pool, rpc_event, state,
method_handler.unary_unary, unary_request,
method_handler.request_deserializer,
method_handler.response_serializer)
-def _handle_unary_stream(rpc_event, state, method_handler, default_thread_pool):
+def _handle_unary_stream(rpc_event, state, method_handler, default_thread_pool):
unary_request = _unary_request(rpc_event, state,
method_handler.request_deserializer)
- thread_pool = _select_thread_pool_for_behavior(method_handler.unary_stream,
- default_thread_pool)
+ thread_pool = _select_thread_pool_for_behavior(method_handler.unary_stream,
+ default_thread_pool)
return thread_pool.submit(_stream_response_in_pool, rpc_event, state,
method_handler.unary_stream, unary_request,
method_handler.request_deserializer,
method_handler.response_serializer)
-def _handle_stream_unary(rpc_event, state, method_handler, default_thread_pool):
+def _handle_stream_unary(rpc_event, state, method_handler, default_thread_pool):
request_iterator = _RequestIterator(state, rpc_event.call,
method_handler.request_deserializer)
- thread_pool = _select_thread_pool_for_behavior(method_handler.stream_unary,
- default_thread_pool)
+ thread_pool = _select_thread_pool_for_behavior(method_handler.stream_unary,
+ default_thread_pool)
return thread_pool.submit(_unary_response_in_pool, rpc_event, state,
method_handler.stream_unary,
lambda: request_iterator,
@@ -655,12 +655,12 @@ def _handle_stream_unary(rpc_event, state, method_handler, default_thread_pool):
method_handler.response_serializer)
-def _handle_stream_stream(rpc_event, state, method_handler,
- default_thread_pool):
+def _handle_stream_stream(rpc_event, state, method_handler,
+ default_thread_pool):
request_iterator = _RequestIterator(state, rpc_event.call,
method_handler.request_deserializer)
- thread_pool = _select_thread_pool_for_behavior(method_handler.stream_stream,
- default_thread_pool)
+ thread_pool = _select_thread_pool_for_behavior(method_handler.stream_stream,
+ default_thread_pool)
return thread_pool.submit(_stream_response_in_pool, rpc_event, state,
method_handler.stream_stream,
lambda: request_iterator,
@@ -689,9 +689,9 @@ def _find_method_handler(rpc_event, generic_handlers, interceptor_pipeline):
def _reject_rpc(rpc_event, status, details):
- rpc_state = _RPCState()
+ rpc_state = _RPCState()
operations = (
- _get_initial_metadata_operation(rpc_state, None),
+ _get_initial_metadata_operation(rpc_state, None),
cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
cygrpc.SendStatusFromServerOperation(None, status, details,
_EMPTY_FLAGS),
@@ -771,8 +771,8 @@ class _ServerState(object):
self.interceptor_pipeline = interceptor_pipeline
self.thread_pool = thread_pool
self.stage = _ServerStage.STOPPED
- self.termination_event = threading.Event()
- self.shutdown_events = [self.termination_event]
+ self.termination_event = threading.Event()
+ self.shutdown_events = [self.termination_event]
self.maximum_concurrent_rpcs = maximum_concurrent_rpcs
self.active_rpc_count = 0
@@ -936,18 +936,18 @@ def _validate_generic_rpc_handlers(generic_rpc_handlers):
'not have "service" method!'.format(generic_rpc_handler))
-def _augment_options(base_options, compression):
- compression_option = _compression.create_channel_option(compression)
- return tuple(base_options) + compression_option
-
-
+def _augment_options(base_options, compression):
+ compression_option = _compression.create_channel_option(compression)
+ return tuple(base_options) + compression_option
+
+
class _Server(grpc.Server):
# pylint: disable=too-many-arguments
def __init__(self, thread_pool, generic_handlers, interceptors, options,
- maximum_concurrent_rpcs, compression):
+ maximum_concurrent_rpcs, compression):
completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server(_augment_options(options, compression))
+ server = cygrpc.Server(_augment_options(options, compression))
server.register_completion_queue(completion_queue)
self._state = _ServerState(completion_queue, server, generic_handlers,
_interceptor.service_pipeline(interceptors),
@@ -970,14 +970,14 @@ class _Server(grpc.Server):
def start(self):
_start(self._state)
- def wait_for_termination(self, timeout=None):
- # NOTE(https://bugs.python.org/issue35935)
- # Remove this workaround once threading.Event.wait() is working with
- # CTRL+C across platforms.
+ def wait_for_termination(self, timeout=None):
+ # NOTE(https://bugs.python.org/issue35935)
+ # Remove this workaround once threading.Event.wait() is working with
+ # CTRL+C across platforms.
return _common.wait(self._state.termination_event.wait,
self._state.termination_event.is_set,
timeout=timeout)
-
+
def stop(self, grace):
return _stop(self._state, grace)
@@ -989,7 +989,7 @@ class _Server(grpc.Server):
def create_server(thread_pool, generic_rpc_handlers, interceptors, options,
- maximum_concurrent_rpcs, compression):
+ maximum_concurrent_rpcs, compression):
_validate_generic_rpc_handlers(generic_rpc_handlers)
return _Server(thread_pool, generic_rpc_handlers, interceptors, options,
- maximum_concurrent_rpcs, compression)
+ maximum_concurrent_rpcs, compression)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py
index a4e2660fb4..7814f49a1a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py
@@ -15,30 +15,30 @@
These APIs are subject to be removed during any minor version release.
"""
-
+
import copy
import functools
import sys
import warnings
-
+
import grpc
_EXPERIMENTAL_APIS_USED = set()
-class ChannelOptions(object):
- """Indicates a channel option unique to gRPC Python.
-
- This enumeration is part of an EXPERIMENTAL API.
-
- Attributes:
- SingleThreadedUnaryStream: Perform unary-stream RPCs on a single thread.
- """
- SingleThreadedUnaryStream = "SingleThreadedUnaryStream"
-
-
-class UsageError(Exception):
- """Raised by the gRPC library to indicate usage not allowed by the API."""
+class ChannelOptions(object):
+ """Indicates a channel option unique to gRPC Python.
+
+ This enumeration is part of an EXPERIMENTAL API.
+
+ Attributes:
+ SingleThreadedUnaryStream: Perform unary-stream RPCs on a single thread.
+ """
+ SingleThreadedUnaryStream = "SingleThreadedUnaryStream"
+
+
+class UsageError(Exception):
+ """Raised by the gRPC library to indicate usage not allowed by the API."""
_insecure_channel_credentials_sentinel = object()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/aio/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/aio/__init__.py
index 576cb8dcde..bdfcd76b2f 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/aio/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/aio/__init__.py
@@ -1,16 +1,16 @@
# Copyright 2020 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+#
+# 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.
"""Alias of grpc.aio to keep backward compatibility."""
-
+
from grpc.aio import *
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py b/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py
index 67f985e1f4..424a6751d2 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py
@@ -15,112 +15,112 @@
# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc_core_dependencies.py.template`!!!
CORE_SOURCE_FILES = [
- 'src/core/ext/filters/census/grpc_context.cc',
- 'src/core/ext/filters/client_channel/backend_metric.cc',
- 'src/core/ext/filters/client_channel/backup_poller.cc',
- 'src/core/ext/filters/client_channel/channel_connectivity.cc',
- 'src/core/ext/filters/client_channel/client_channel.cc',
- 'src/core/ext/filters/client_channel/client_channel_channelz.cc',
- 'src/core/ext/filters/client_channel/client_channel_factory.cc',
- 'src/core/ext/filters/client_channel/client_channel_plugin.cc',
+ 'src/core/ext/filters/census/grpc_context.cc',
+ 'src/core/ext/filters/client_channel/backend_metric.cc',
+ 'src/core/ext/filters/client_channel/backup_poller.cc',
+ 'src/core/ext/filters/client_channel/channel_connectivity.cc',
+ 'src/core/ext/filters/client_channel/client_channel.cc',
+ 'src/core/ext/filters/client_channel/client_channel_channelz.cc',
+ 'src/core/ext/filters/client_channel/client_channel_factory.cc',
+ 'src/core/ext/filters/client_channel/client_channel_plugin.cc',
'src/core/ext/filters/client_channel/config_selector.cc',
- 'src/core/ext/filters/client_channel/global_subchannel_pool.cc',
- 'src/core/ext/filters/client_channel/health/health_check_client.cc',
- 'src/core/ext/filters/client_channel/http_connect_handshaker.cc',
- 'src/core/ext/filters/client_channel/http_proxy.cc',
- 'src/core/ext/filters/client_channel/lb_policy.cc',
+ 'src/core/ext/filters/client_channel/global_subchannel_pool.cc',
+ 'src/core/ext/filters/client_channel/health/health_check_client.cc',
+ 'src/core/ext/filters/client_channel/http_connect_handshaker.cc',
+ 'src/core/ext/filters/client_channel/http_proxy.cc',
+ 'src/core/ext/filters/client_channel/lb_policy.cc',
'src/core/ext/filters/client_channel/lb_policy/address_filtering.cc',
'src/core/ext/filters/client_channel/lb_policy/child_policy_handler.cc',
- 'src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc',
- 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc',
'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.cc',
- 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc',
- 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc',
- 'src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc',
- 'src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc',
'src/core/ext/filters/client_channel/lb_policy/priority/priority.cc',
- 'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc',
'src/core/ext/filters/client_channel/lb_policy/weighted_target/weighted_target.cc',
- 'src/core/ext/filters/client_channel/lb_policy/xds/cds.cc',
+ 'src/core/ext/filters/client_channel/lb_policy/xds/cds.cc',
'src/core/ext/filters/client_channel/lb_policy/xds/eds.cc',
'src/core/ext/filters/client_channel/lb_policy/xds/eds_drop.cc',
'src/core/ext/filters/client_channel/lb_policy/xds/xds_cluster_manager.cc',
- 'src/core/ext/filters/client_channel/lb_policy_registry.cc',
- 'src/core/ext/filters/client_channel/local_subchannel_pool.cc',
- 'src/core/ext/filters/client_channel/proxy_mapper_registry.cc',
- 'src/core/ext/filters/client_channel/resolver.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc',
- 'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc',
- 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc',
- 'src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc',
- 'src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc',
- 'src/core/ext/filters/client_channel/resolver_registry.cc',
- 'src/core/ext/filters/client_channel/resolver_result_parsing.cc',
- 'src/core/ext/filters/client_channel/resolving_lb_policy.cc',
- 'src/core/ext/filters/client_channel/retry_throttle.cc',
- 'src/core/ext/filters/client_channel/server_address.cc',
- 'src/core/ext/filters/client_channel/service_config.cc',
+ 'src/core/ext/filters/client_channel/lb_policy_registry.cc',
+ 'src/core/ext/filters/client_channel/local_subchannel_pool.cc',
+ 'src/core/ext/filters/client_channel/proxy_mapper_registry.cc',
+ 'src/core/ext/filters/client_channel/resolver.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc',
+ 'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc',
+ 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc',
+ 'src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc',
+ 'src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc',
+ 'src/core/ext/filters/client_channel/resolver_registry.cc',
+ 'src/core/ext/filters/client_channel/resolver_result_parsing.cc',
+ 'src/core/ext/filters/client_channel/resolving_lb_policy.cc',
+ 'src/core/ext/filters/client_channel/retry_throttle.cc',
+ 'src/core/ext/filters/client_channel/server_address.cc',
+ 'src/core/ext/filters/client_channel/service_config.cc',
'src/core/ext/filters/client_channel/service_config_channel_arg_filter.cc',
'src/core/ext/filters/client_channel/service_config_parser.cc',
- 'src/core/ext/filters/client_channel/subchannel.cc',
- 'src/core/ext/filters/client_channel/subchannel_pool_interface.cc',
- 'src/core/ext/filters/client_idle/client_idle_filter.cc',
- 'src/core/ext/filters/deadline/deadline_filter.cc',
- 'src/core/ext/filters/http/client/http_client_filter.cc',
- 'src/core/ext/filters/http/client_authority_filter.cc',
- 'src/core/ext/filters/http/http_filters_plugin.cc',
- 'src/core/ext/filters/http/message_compress/message_compress_filter.cc',
+ 'src/core/ext/filters/client_channel/subchannel.cc',
+ 'src/core/ext/filters/client_channel/subchannel_pool_interface.cc',
+ 'src/core/ext/filters/client_idle/client_idle_filter.cc',
+ 'src/core/ext/filters/deadline/deadline_filter.cc',
+ 'src/core/ext/filters/http/client/http_client_filter.cc',
+ 'src/core/ext/filters/http/client_authority_filter.cc',
+ 'src/core/ext/filters/http/http_filters_plugin.cc',
+ 'src/core/ext/filters/http/message_compress/message_compress_filter.cc',
'src/core/ext/filters/http/message_compress/message_decompress_filter.cc',
- 'src/core/ext/filters/http/server/http_server_filter.cc',
- 'src/core/ext/filters/max_age/max_age_filter.cc',
- 'src/core/ext/filters/message_size/message_size_filter.cc',
- 'src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc',
- 'src/core/ext/filters/workarounds/workaround_utils.cc',
- 'src/core/ext/transport/chttp2/alpn/alpn.cc',
- 'src/core/ext/transport/chttp2/client/authority.cc',
- 'src/core/ext/transport/chttp2/client/chttp2_connector.cc',
- 'src/core/ext/transport/chttp2/client/insecure/channel_create.cc',
- 'src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc',
- 'src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc',
- 'src/core/ext/transport/chttp2/server/chttp2_server.cc',
- 'src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc',
- 'src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc',
- 'src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc',
- 'src/core/ext/transport/chttp2/transport/bin_decoder.cc',
- 'src/core/ext/transport/chttp2/transport/bin_encoder.cc',
- 'src/core/ext/transport/chttp2/transport/chttp2_plugin.cc',
- 'src/core/ext/transport/chttp2/transport/chttp2_transport.cc',
- 'src/core/ext/transport/chttp2/transport/context_list.cc',
- 'src/core/ext/transport/chttp2/transport/flow_control.cc',
- 'src/core/ext/transport/chttp2/transport/frame_data.cc',
- 'src/core/ext/transport/chttp2/transport/frame_goaway.cc',
- 'src/core/ext/transport/chttp2/transport/frame_ping.cc',
- 'src/core/ext/transport/chttp2/transport/frame_rst_stream.cc',
- 'src/core/ext/transport/chttp2/transport/frame_settings.cc',
- 'src/core/ext/transport/chttp2/transport/frame_window_update.cc',
- 'src/core/ext/transport/chttp2/transport/hpack_encoder.cc',
- 'src/core/ext/transport/chttp2/transport/hpack_parser.cc',
- 'src/core/ext/transport/chttp2/transport/hpack_table.cc',
- 'src/core/ext/transport/chttp2/transport/http2_settings.cc',
- 'src/core/ext/transport/chttp2/transport/huffsyms.cc',
- 'src/core/ext/transport/chttp2/transport/incoming_metadata.cc',
- 'src/core/ext/transport/chttp2/transport/parsing.cc',
- 'src/core/ext/transport/chttp2/transport/stream_lists.cc',
- 'src/core/ext/transport/chttp2/transport/stream_map.cc',
- 'src/core/ext/transport/chttp2/transport/varint.cc',
- 'src/core/ext/transport/chttp2/transport/writing.cc',
- 'src/core/ext/transport/inproc/inproc_plugin.cc',
- 'src/core/ext/transport/inproc/inproc_transport.cc',
+ 'src/core/ext/filters/http/server/http_server_filter.cc',
+ 'src/core/ext/filters/max_age/max_age_filter.cc',
+ 'src/core/ext/filters/message_size/message_size_filter.cc',
+ 'src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc',
+ 'src/core/ext/filters/workarounds/workaround_utils.cc',
+ 'src/core/ext/transport/chttp2/alpn/alpn.cc',
+ 'src/core/ext/transport/chttp2/client/authority.cc',
+ 'src/core/ext/transport/chttp2/client/chttp2_connector.cc',
+ 'src/core/ext/transport/chttp2/client/insecure/channel_create.cc',
+ 'src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc',
+ 'src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc',
+ 'src/core/ext/transport/chttp2/server/chttp2_server.cc',
+ 'src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc',
+ 'src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc',
+ 'src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc',
+ 'src/core/ext/transport/chttp2/transport/bin_decoder.cc',
+ 'src/core/ext/transport/chttp2/transport/bin_encoder.cc',
+ 'src/core/ext/transport/chttp2/transport/chttp2_plugin.cc',
+ 'src/core/ext/transport/chttp2/transport/chttp2_transport.cc',
+ 'src/core/ext/transport/chttp2/transport/context_list.cc',
+ 'src/core/ext/transport/chttp2/transport/flow_control.cc',
+ 'src/core/ext/transport/chttp2/transport/frame_data.cc',
+ 'src/core/ext/transport/chttp2/transport/frame_goaway.cc',
+ 'src/core/ext/transport/chttp2/transport/frame_ping.cc',
+ 'src/core/ext/transport/chttp2/transport/frame_rst_stream.cc',
+ 'src/core/ext/transport/chttp2/transport/frame_settings.cc',
+ 'src/core/ext/transport/chttp2/transport/frame_window_update.cc',
+ 'src/core/ext/transport/chttp2/transport/hpack_encoder.cc',
+ 'src/core/ext/transport/chttp2/transport/hpack_parser.cc',
+ 'src/core/ext/transport/chttp2/transport/hpack_table.cc',
+ 'src/core/ext/transport/chttp2/transport/http2_settings.cc',
+ 'src/core/ext/transport/chttp2/transport/huffsyms.cc',
+ 'src/core/ext/transport/chttp2/transport/incoming_metadata.cc',
+ 'src/core/ext/transport/chttp2/transport/parsing.cc',
+ 'src/core/ext/transport/chttp2/transport/stream_lists.cc',
+ 'src/core/ext/transport/chttp2/transport/stream_map.cc',
+ 'src/core/ext/transport/chttp2/transport/varint.cc',
+ 'src/core/ext/transport/chttp2/transport/writing.cc',
+ 'src/core/ext/transport/inproc/inproc_plugin.cc',
+ 'src/core/ext/transport/inproc/inproc_transport.cc',
'src/core/ext/upb-generated/envoy/annotations/deprecation.upb.c',
'src/core/ext/upb-generated/envoy/annotations/resource.upb.c',
'src/core/ext/upb-generated/envoy/config/accesslog/v3/accesslog.upb.c',
@@ -178,23 +178,23 @@ CORE_SOURCE_FILES = [
'src/core/ext/upb-generated/envoy/type/v3/percent.upb.c',
'src/core/ext/upb-generated/envoy/type/v3/range.upb.c',
'src/core/ext/upb-generated/envoy/type/v3/semantic_version.upb.c',
- 'src/core/ext/upb-generated/google/api/annotations.upb.c',
+ 'src/core/ext/upb-generated/google/api/annotations.upb.c',
'src/core/ext/upb-generated/google/api/expr/v1alpha1/checked.upb.c',
'src/core/ext/upb-generated/google/api/expr/v1alpha1/syntax.upb.c',
- 'src/core/ext/upb-generated/google/api/http.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/any.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/descriptor.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/duration.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/empty.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/struct.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/timestamp.upb.c',
- 'src/core/ext/upb-generated/google/protobuf/wrappers.upb.c',
- 'src/core/ext/upb-generated/google/rpc/status.upb.c',
- 'src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c',
- 'src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c',
- 'src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c',
- 'src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c',
- 'src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c',
+ 'src/core/ext/upb-generated/google/api/http.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/any.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/descriptor.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/duration.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/empty.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/struct.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/timestamp.upb.c',
+ 'src/core/ext/upb-generated/google/protobuf/wrappers.upb.c',
+ 'src/core/ext/upb-generated/google/rpc/status.upb.c',
+ 'src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c',
+ 'src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c',
+ 'src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c',
+ 'src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c',
+ 'src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c',
'src/core/ext/upb-generated/udpa/annotations/migrate.upb.c',
'src/core/ext/upb-generated/udpa/annotations/security.upb.c',
'src/core/ext/upb-generated/udpa/annotations/sensitive.upb.c',
@@ -206,36 +206,36 @@ CORE_SOURCE_FILES = [
'src/core/ext/upb-generated/udpa/core/v1/resource.upb.c',
'src/core/ext/upb-generated/udpa/core/v1/resource_locator.upb.c',
'src/core/ext/upb-generated/udpa/core/v1/resource_name.upb.c',
- 'src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c',
- 'src/core/ext/upb-generated/validate/validate.upb.c',
+ 'src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c',
+ 'src/core/ext/upb-generated/validate/validate.upb.c',
'src/core/ext/xds/certificate_provider_registry.cc',
'src/core/ext/xds/google_mesh_ca_certificate_provider_factory.cc',
'src/core/ext/xds/xds_api.cc',
'src/core/ext/xds/xds_bootstrap.cc',
'src/core/ext/xds/xds_client.cc',
'src/core/ext/xds/xds_client_stats.cc',
- 'src/core/lib/avl/avl.cc',
- 'src/core/lib/backoff/backoff.cc',
- 'src/core/lib/channel/channel_args.cc',
- 'src/core/lib/channel/channel_stack.cc',
- 'src/core/lib/channel/channel_stack_builder.cc',
- 'src/core/lib/channel/channel_trace.cc',
- 'src/core/lib/channel/channelz.cc',
- 'src/core/lib/channel/channelz_registry.cc',
- 'src/core/lib/channel/connected_channel.cc',
- 'src/core/lib/channel/handshaker.cc',
- 'src/core/lib/channel/handshaker_registry.cc',
- 'src/core/lib/channel/status_util.cc',
- 'src/core/lib/compression/compression.cc',
- 'src/core/lib/compression/compression_args.cc',
- 'src/core/lib/compression/compression_internal.cc',
- 'src/core/lib/compression/message_compress.cc',
- 'src/core/lib/compression/stream_compression.cc',
- 'src/core/lib/compression/stream_compression_gzip.cc',
- 'src/core/lib/compression/stream_compression_identity.cc',
- 'src/core/lib/debug/stats.cc',
- 'src/core/lib/debug/stats_data.cc',
- 'src/core/lib/debug/trace.cc',
+ 'src/core/lib/avl/avl.cc',
+ 'src/core/lib/backoff/backoff.cc',
+ 'src/core/lib/channel/channel_args.cc',
+ 'src/core/lib/channel/channel_stack.cc',
+ 'src/core/lib/channel/channel_stack_builder.cc',
+ 'src/core/lib/channel/channel_trace.cc',
+ 'src/core/lib/channel/channelz.cc',
+ 'src/core/lib/channel/channelz_registry.cc',
+ 'src/core/lib/channel/connected_channel.cc',
+ 'src/core/lib/channel/handshaker.cc',
+ 'src/core/lib/channel/handshaker_registry.cc',
+ 'src/core/lib/channel/status_util.cc',
+ 'src/core/lib/compression/compression.cc',
+ 'src/core/lib/compression/compression_args.cc',
+ 'src/core/lib/compression/compression_internal.cc',
+ 'src/core/lib/compression/message_compress.cc',
+ 'src/core/lib/compression/stream_compression.cc',
+ 'src/core/lib/compression/stream_compression_gzip.cc',
+ 'src/core/lib/compression/stream_compression_identity.cc',
+ 'src/core/lib/debug/stats.cc',
+ 'src/core/lib/debug/stats_data.cc',
+ 'src/core/lib/debug/trace.cc',
'src/core/lib/gpr/alloc.cc',
'src/core/lib/gpr/atm.cc',
'src/core/lib/gpr/cpu_iphone.cc',
@@ -268,29 +268,29 @@ CORE_SOURCE_FILES = [
'src/core/lib/gpr/tmpfile_posix.cc',
'src/core/lib/gpr/tmpfile_windows.cc',
'src/core/lib/gpr/wrap_memcpy.cc',
- 'src/core/lib/gprpp/arena.cc',
+ 'src/core/lib/gprpp/arena.cc',
'src/core/lib/gprpp/fork.cc',
- 'src/core/lib/gprpp/global_config_env.cc',
- 'src/core/lib/gprpp/host_port.cc',
- 'src/core/lib/gprpp/mpscq.cc',
+ 'src/core/lib/gprpp/global_config_env.cc',
+ 'src/core/lib/gprpp/host_port.cc',
+ 'src/core/lib/gprpp/mpscq.cc',
'src/core/lib/gprpp/thd_posix.cc',
'src/core/lib/gprpp/thd_windows.cc',
'src/core/lib/http/format_request.cc',
'src/core/lib/http/httpcli.cc',
- 'src/core/lib/http/httpcli_security_connector.cc',
+ 'src/core/lib/http/httpcli_security_connector.cc',
'src/core/lib/http/parser.cc',
'src/core/lib/iomgr/buffer_list.cc',
'src/core/lib/iomgr/call_combiner.cc',
- 'src/core/lib/iomgr/cfstream_handle.cc',
+ 'src/core/lib/iomgr/cfstream_handle.cc',
'src/core/lib/iomgr/combiner.cc',
'src/core/lib/iomgr/dualstack_socket_posix.cc',
'src/core/lib/iomgr/endpoint.cc',
- 'src/core/lib/iomgr/endpoint_cfstream.cc',
+ 'src/core/lib/iomgr/endpoint_cfstream.cc',
'src/core/lib/iomgr/endpoint_pair_posix.cc',
'src/core/lib/iomgr/endpoint_pair_uv.cc',
'src/core/lib/iomgr/endpoint_pair_windows.cc',
'src/core/lib/iomgr/error.cc',
- 'src/core/lib/iomgr/error_cfstream.cc',
+ 'src/core/lib/iomgr/error_cfstream.cc',
'src/core/lib/iomgr/ev_apple.cc',
'src/core/lib/iomgr/ev_epoll1_linux.cc',
'src/core/lib/iomgr/ev_epollex_linux.cc',
@@ -299,8 +299,8 @@ CORE_SOURCE_FILES = [
'src/core/lib/iomgr/ev_windows.cc',
'src/core/lib/iomgr/exec_ctx.cc',
'src/core/lib/iomgr/executor.cc',
- 'src/core/lib/iomgr/executor/mpmcqueue.cc',
- 'src/core/lib/iomgr/executor/threadpool.cc',
+ 'src/core/lib/iomgr/executor/mpmcqueue.cc',
+ 'src/core/lib/iomgr/executor/threadpool.cc',
'src/core/lib/iomgr/fork_posix.cc',
'src/core/lib/iomgr/fork_windows.cc',
'src/core/lib/iomgr/gethostname_fallback.cc',
@@ -314,7 +314,7 @@ CORE_SOURCE_FILES = [
'src/core/lib/iomgr/iomgr_custom.cc',
'src/core/lib/iomgr/iomgr_internal.cc',
'src/core/lib/iomgr/iomgr_posix.cc',
- 'src/core/lib/iomgr/iomgr_posix_cfstream.cc',
+ 'src/core/lib/iomgr/iomgr_posix_cfstream.cc',
'src/core/lib/iomgr/iomgr_uv.cc',
'src/core/lib/iomgr/iomgr_windows.cc',
'src/core/lib/iomgr/is_epollexclusive_available.cc',
@@ -345,7 +345,7 @@ CORE_SOURCE_FILES = [
'src/core/lib/iomgr/socket_utils_windows.cc',
'src/core/lib/iomgr/socket_windows.cc',
'src/core/lib/iomgr/tcp_client.cc',
- 'src/core/lib/iomgr/tcp_client_cfstream.cc',
+ 'src/core/lib/iomgr/tcp_client_cfstream.cc',
'src/core/lib/iomgr/tcp_client_custom.cc',
'src/core/lib/iomgr/tcp_client_posix.cc',
'src/core/lib/iomgr/tcp_client_windows.cc',
@@ -378,53 +378,53 @@ CORE_SOURCE_FILES = [
'src/core/lib/json/json_reader.cc',
'src/core/lib/json/json_util.cc',
'src/core/lib/json/json_writer.cc',
- 'src/core/lib/profiling/basic_timers.cc',
- 'src/core/lib/profiling/stap_timers.cc',
+ 'src/core/lib/profiling/basic_timers.cc',
+ 'src/core/lib/profiling/stap_timers.cc',
'src/core/lib/security/authorization/authorization_engine.cc',
'src/core/lib/security/authorization/evaluate_args.cc',
- 'src/core/lib/security/context/security_context.cc',
- 'src/core/lib/security/credentials/alts/alts_credentials.cc',
- 'src/core/lib/security/credentials/alts/check_gcp_environment.cc',
- 'src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc',
- 'src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc',
- 'src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc',
- 'src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc',
- 'src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc',
- 'src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc',
- 'src/core/lib/security/credentials/composite/composite_credentials.cc',
- 'src/core/lib/security/credentials/credentials.cc',
- 'src/core/lib/security/credentials/credentials_metadata.cc',
- 'src/core/lib/security/credentials/fake/fake_credentials.cc',
- 'src/core/lib/security/credentials/google_default/credentials_generic.cc',
- 'src/core/lib/security/credentials/google_default/google_default_credentials.cc',
- 'src/core/lib/security/credentials/iam/iam_credentials.cc',
- 'src/core/lib/security/credentials/jwt/json_token.cc',
- 'src/core/lib/security/credentials/jwt/jwt_credentials.cc',
- 'src/core/lib/security/credentials/jwt/jwt_verifier.cc',
- 'src/core/lib/security/credentials/local/local_credentials.cc',
- 'src/core/lib/security/credentials/oauth2/oauth2_credentials.cc',
- 'src/core/lib/security/credentials/plugin/plugin_credentials.cc',
- 'src/core/lib/security/credentials/ssl/ssl_credentials.cc',
+ 'src/core/lib/security/context/security_context.cc',
+ 'src/core/lib/security/credentials/alts/alts_credentials.cc',
+ 'src/core/lib/security/credentials/alts/check_gcp_environment.cc',
+ 'src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc',
+ 'src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc',
+ 'src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc',
+ 'src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc',
+ 'src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc',
+ 'src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc',
+ 'src/core/lib/security/credentials/composite/composite_credentials.cc',
+ 'src/core/lib/security/credentials/credentials.cc',
+ 'src/core/lib/security/credentials/credentials_metadata.cc',
+ 'src/core/lib/security/credentials/fake/fake_credentials.cc',
+ 'src/core/lib/security/credentials/google_default/credentials_generic.cc',
+ 'src/core/lib/security/credentials/google_default/google_default_credentials.cc',
+ 'src/core/lib/security/credentials/iam/iam_credentials.cc',
+ 'src/core/lib/security/credentials/jwt/json_token.cc',
+ 'src/core/lib/security/credentials/jwt/jwt_credentials.cc',
+ 'src/core/lib/security/credentials/jwt/jwt_verifier.cc',
+ 'src/core/lib/security/credentials/local/local_credentials.cc',
+ 'src/core/lib/security/credentials/oauth2/oauth2_credentials.cc',
+ 'src/core/lib/security/credentials/plugin/plugin_credentials.cc',
+ 'src/core/lib/security/credentials/ssl/ssl_credentials.cc',
'src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc',
- 'src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc',
+ 'src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc',
'src/core/lib/security/credentials/tls/tls_credentials.cc',
'src/core/lib/security/credentials/xds/xds_credentials.cc',
- 'src/core/lib/security/security_connector/alts/alts_security_connector.cc',
- 'src/core/lib/security/security_connector/fake/fake_security_connector.cc',
- 'src/core/lib/security/security_connector/load_system_roots_fallback.cc',
- 'src/core/lib/security/security_connector/load_system_roots_linux.cc',
- 'src/core/lib/security/security_connector/local/local_security_connector.cc',
- 'src/core/lib/security/security_connector/security_connector.cc',
- 'src/core/lib/security/security_connector/ssl/ssl_security_connector.cc',
- 'src/core/lib/security/security_connector/ssl_utils.cc',
- 'src/core/lib/security/security_connector/ssl_utils_config.cc',
+ 'src/core/lib/security/security_connector/alts/alts_security_connector.cc',
+ 'src/core/lib/security/security_connector/fake/fake_security_connector.cc',
+ 'src/core/lib/security/security_connector/load_system_roots_fallback.cc',
+ 'src/core/lib/security/security_connector/load_system_roots_linux.cc',
+ 'src/core/lib/security/security_connector/local/local_security_connector.cc',
+ 'src/core/lib/security/security_connector/security_connector.cc',
+ 'src/core/lib/security/security_connector/ssl/ssl_security_connector.cc',
+ 'src/core/lib/security/security_connector/ssl_utils.cc',
+ 'src/core/lib/security/security_connector/ssl_utils_config.cc',
'src/core/lib/security/security_connector/tls/tls_security_connector.cc',
- 'src/core/lib/security/transport/client_auth_filter.cc',
- 'src/core/lib/security/transport/secure_endpoint.cc',
- 'src/core/lib/security/transport/security_handshaker.cc',
- 'src/core/lib/security/transport/server_auth_filter.cc',
- 'src/core/lib/security/transport/tsi_error.cc',
- 'src/core/lib/security/util/json_util.cc',
+ 'src/core/lib/security/transport/client_auth_filter.cc',
+ 'src/core/lib/security/transport/secure_endpoint.cc',
+ 'src/core/lib/security/transport/security_handshaker.cc',
+ 'src/core/lib/security/transport/server_auth_filter.cc',
+ 'src/core/lib/security/transport/tsi_error.cc',
+ 'src/core/lib/security/util/json_util.cc',
'src/core/lib/slice/b64.cc',
'src/core/lib/slice/percent_encoding.cc',
'src/core/lib/slice/slice.cc',
@@ -444,8 +444,8 @@ CORE_SOURCE_FILES = [
'src/core/lib/surface/completion_queue.cc',
'src/core/lib/surface/completion_queue_factory.cc',
'src/core/lib/surface/event_string.cc',
- 'src/core/lib/surface/init.cc',
- 'src/core/lib/surface/init_secure.cc',
+ 'src/core/lib/surface/init.cc',
+ 'src/core/lib/surface/init_secure.cc',
'src/core/lib/surface/lame_client.cc',
'src/core/lib/surface/metadata_array.cc',
'src/core/lib/surface/server.cc',
@@ -466,7 +466,7 @@ CORE_SOURCE_FILES = [
'src/core/lib/transport/transport.cc',
'src/core/lib/transport/transport_op_string.cc',
'src/core/lib/uri/uri_parser.cc',
- 'src/core/plugin_registry/grpc_plugin_registry.cc',
+ 'src/core/plugin_registry/grpc_plugin_registry.cc',
'src/core/tsi/alts/crypt/aes_gcm.cc',
'src/core/tsi/alts/crypt/gsec.cc',
'src/core/tsi/alts/frame_protector/alts_counter.cc',
@@ -479,8 +479,8 @@ CORE_SOURCE_FILES = [
'src/core/tsi/alts/handshaker/alts_handshaker_client.cc',
'src/core/tsi/alts/handshaker/alts_shared_resource.cc',
'src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc',
- 'src/core/tsi/alts/handshaker/alts_tsi_utils.cc',
- 'src/core/tsi/alts/handshaker/transport_security_common_api.cc',
+ 'src/core/tsi/alts/handshaker/alts_tsi_utils.cc',
+ 'src/core/tsi/alts/handshaker/transport_security_common_api.cc',
'src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc',
'src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc',
'src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc',
@@ -492,7 +492,7 @@ CORE_SOURCE_FILES = [
'src/core/tsi/ssl/session_cache/ssl_session_cache.cc',
'src/core/tsi/ssl/session_cache/ssl_session_openssl.cc',
'src/core/tsi/ssl_transport_security.cc',
- 'src/core/tsi/transport_security.cc',
+ 'src/core/tsi/transport_security.cc',
'src/core/tsi/transport_security_grpc.cc',
'third_party/abseil-cpp/y_absl/base/dynamic_annotations.cc',
'third_party/abseil-cpp/y_absl/base/internal/cycleclock.cc',
@@ -568,9 +568,9 @@ CORE_SOURCE_FILES = [
'third_party/abseil-cpp/y_absl/time/time.cc',
'third_party/abseil-cpp/y_absl/types/bad_optional_access.cc',
'third_party/abseil-cpp/y_absl/types/bad_variant_access.cc',
- 'third_party/address_sorting/address_sorting.c',
- 'third_party/address_sorting/address_sorting_posix.c',
- 'third_party/address_sorting/address_sorting_windows.c',
+ 'third_party/address_sorting/address_sorting.c',
+ 'third_party/address_sorting/address_sorting_posix.c',
+ 'third_party/address_sorting/address_sorting_windows.c',
'third_party/boringssl-with-bazel/err_data.c',
'third_party/boringssl-with-bazel/src/crypto/asn1/a_bitstr.c',
'third_party/boringssl-with-bazel/src/crypto/asn1/a_bool.c',
@@ -879,7 +879,7 @@ CORE_SOURCE_FILES = [
'third_party/cares/cares/ares_strcasecmp.c',
'third_party/cares/cares/ares_strdup.c',
'third_party/cares/cares/ares_strerror.c',
- 'third_party/cares/cares/ares_strsplit.c',
+ 'third_party/cares/cares/ares_strsplit.c',
'third_party/cares/cares/ares_timeout.c',
'third_party/cares/cares/ares_version.c',
'third_party/cares/cares/ares_writev.c',
@@ -910,27 +910,27 @@ CORE_SOURCE_FILES = [
'third_party/re2/util/pcre.cc',
'third_party/re2/util/rune.cc',
'third_party/re2/util/strutil.cc',
- 'third_party/upb/upb/decode.c',
- 'third_party/upb/upb/encode.c',
- 'third_party/upb/upb/msg.c',
- 'third_party/upb/upb/port.c',
- 'third_party/upb/upb/table.c',
- 'third_party/upb/upb/upb.c',
- 'third_party/zlib/adler32.c',
- 'third_party/zlib/compress.c',
- 'third_party/zlib/crc32.c',
- 'third_party/zlib/deflate.c',
- 'third_party/zlib/gzclose.c',
- 'third_party/zlib/gzlib.c',
- 'third_party/zlib/gzread.c',
- 'third_party/zlib/gzwrite.c',
- 'third_party/zlib/infback.c',
- 'third_party/zlib/inffast.c',
- 'third_party/zlib/inflate.c',
- 'third_party/zlib/inftrees.c',
- 'third_party/zlib/trees.c',
- 'third_party/zlib/uncompr.c',
- 'third_party/zlib/zutil.c',
+ 'third_party/upb/upb/decode.c',
+ 'third_party/upb/upb/encode.c',
+ 'third_party/upb/upb/msg.c',
+ 'third_party/upb/upb/port.c',
+ 'third_party/upb/upb/table.c',
+ 'third_party/upb/upb/upb.c',
+ 'third_party/zlib/adler32.c',
+ 'third_party/zlib/compress.c',
+ 'third_party/zlib/crc32.c',
+ 'third_party/zlib/deflate.c',
+ 'third_party/zlib/gzclose.c',
+ 'third_party/zlib/gzlib.c',
+ 'third_party/zlib/gzread.c',
+ 'third_party/zlib/gzwrite.c',
+ 'third_party/zlib/infback.c',
+ 'third_party/zlib/inffast.c',
+ 'third_party/zlib/inflate.c',
+ 'third_party/zlib/inftrees.c',
+ 'third_party/zlib/trees.c',
+ 'third_party/zlib/uncompr.c',
+ 'third_party/zlib/zutil.c',
]
ASM_SOURCE_FILES = {
diff --git a/contrib/libs/grpc/src/python/grpcio/ya.make b/contrib/libs/grpc/src/python/grpcio/ya.make
index 5cdb0230c4..5de0a4d591 100644
--- a/contrib/libs/grpc/src/python/grpcio/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio/ya.make
@@ -5,13 +5,13 @@ LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
OWNER(
- akastornov
- g:contrib
- g:cpp-contrib
+ akastornov
+ g:contrib
+ g:cpp-contrib
)
PEERDIR(
- contrib/libs/grpc/grpc
+ contrib/libs/grpc/grpc
contrib/python/six
)
@@ -31,10 +31,10 @@ ADDINCL(
IF (SANITIZER_TYPE == undefined)
# https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
CXXFLAGS(-fno-sanitize=function)
-ENDIF()
+ENDIF()
NO_LINT()
-
+
NO_COMPILER_WARNINGS()
PY_SRCS(
@@ -43,7 +43,7 @@ PY_SRCS(
grpc/_auth.py
grpc/_channel.py
grpc/_common.py
- grpc/_compression.py
+ grpc/_compression.py
grpc/_cython/__init__.py
grpc/_cython/_cygrpc/__init__.py
grpc/_cython/cygrpc.pyx
@@ -83,9 +83,9 @@ PY_SRCS(
grpc/framework/interfaces/face/utilities.py
)
-IF (PYTHON3)
- PY_SRCS(
- TOP_LEVEL
+IF (PYTHON3)
+ PY_SRCS(
+ TOP_LEVEL
grpc/_simple_stubs.py
grpc/aio/_base_call.py
grpc/aio/_base_channel.py
@@ -98,8 +98,8 @@ IF (PYTHON3)
grpc/aio/_server.py
grpc/aio/_typing.py
grpc/aio/_utils.py
- grpc/experimental/aio/__init__.py
- )
-ENDIF()
-
+ grpc/experimental/aio/__init__.py
+ )
+ENDIF()
+
END()
diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/README.rst b/contrib/libs/grpc/src/python/grpcio_channelz/README.rst
index d66d0c4f92..7a6a4845cd 100644
--- a/contrib/libs/grpc/src/python/grpcio_channelz/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio_channelz/README.rst
@@ -1,17 +1,17 @@
-gRPC Python Channelz package
-==============================
-
-Channelz is a live debug tool in gRPC Python.
-
-Supported Python Versions
--------------------------
-Python >= 3.5
-
-Deprecated Python Versions
---------------------------
-Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
-
-Dependencies
-------------
-
-Depends on the `grpcio` package, available from PyPI via `pip install grpcio`.
+gRPC Python Channelz package
+==============================
+
+Channelz is a live debug tool in gRPC Python.
+
+Supported Python Versions
+-------------------------
+Python >= 3.5
+
+Deprecated Python Versions
+--------------------------
+Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
+
+Dependencies
+------------
+
+Depends on the `grpcio` package, available from PyPI via `pip install grpcio`.
diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/setup.py b/contrib/libs/grpc/src/python/grpcio_channelz/setup.py
index 678b5ef13f..a6526b400d 100644
--- a/contrib/libs/grpc/src/python/grpcio_channelz/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_channelz/setup.py
@@ -18,9 +18,9 @@ import sys
import setuptools
-_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
-_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
-
+_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
+_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
+
# Ensure we're in the proper directory whether or not we're being used by pip.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
@@ -53,8 +53,8 @@ CLASSIFIERS = [
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: Apache Software License',
]
@@ -91,7 +91,7 @@ setuptools.setup(
version=grpc_version.VERSION,
license='Apache License 2.0',
description='Channel Level Live Debug Information Service for gRPC',
- long_description=open(_README_PATH, 'r').read(),
+ long_description=open(_README_PATH, 'r').read(),
author='The gRPC Authors',
author_email='grpc-io@googlegroups.com',
classifiers=CLASSIFIERS,
diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/ya.make b/contrib/libs/grpc/src/python/grpcio_channelz/ya.make
index 2703d70ab0..7c3506de6f 100644
--- a/contrib/libs/grpc/src/python/grpcio_channelz/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio_channelz/ya.make
@@ -1,51 +1,51 @@
-PY23_LIBRARY()
-
+PY23_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- dvshkurko
- g:contrib
- g:cpp-contrib
-)
-
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/python/six
-)
-
-IF (PYTHON2)
- PEERDIR(
- contrib/python/enum34
- contrib/python/futures
- )
-ENDIF()
-
-ADDINCL(
+OWNER(
+ akastornov
+ dvshkurko
+ g:contrib
+ g:cpp-contrib
+)
+
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/python/six
+)
+
+IF (PYTHON2)
+ PEERDIR(
+ contrib/python/enum34
+ contrib/python/futures
+ )
+ENDIF()
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
IF (SANITIZER_TYPE == undefined)
- # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
- CXXFLAGS(-fno-sanitize=function)
-ENDIF()
-
-NO_LINT()
-
-NO_COMPILER_WARNINGS()
-
-PY_SRCS(
- TOP_LEVEL
- grpc_channelz/__init__.py
- grpc_channelz/v1/__init__.py
+ # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
+ CXXFLAGS(-fno-sanitize=function)
+ENDIF()
+
+NO_LINT()
+
+NO_COMPILER_WARNINGS()
+
+PY_SRCS(
+ TOP_LEVEL
+ grpc_channelz/__init__.py
+ grpc_channelz/v1/__init__.py
grpc_channelz/v1/_servicer.py
- grpc_channelz/v1/channelz.py
-)
-
+ grpc_channelz/v1/channelz.py
+)
+
IF (PYTHON3)
PY_SRCS(
TOP_LEVEL
@@ -53,4 +53,4 @@ IF (PYTHON3)
)
ENDIF()
-END()
+END()
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/README.rst b/contrib/libs/grpc/src/python/grpcio_health_checking/README.rst
index 044377a582..0b43dac9b3 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/README.rst
@@ -3,14 +3,14 @@ gRPC Python Health Checking
Reference package for GRPC Python health checking.
-Supported Python Versions
--------------------------
-Python >= 3.5
-
-Deprecated Python Versions
---------------------------
-Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
-
+Supported Python Versions
+-------------------------
+Python >= 3.5
+
+Deprecated Python Versions
+--------------------------
+Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
+
Dependencies
------------
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py
index f7ee639ec8..50f125b851 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py
@@ -13,7 +13,7 @@
# limitations under the License.
"""Reference implementation for health checking in gRPC Python."""
-import collections
+import collections
import threading
import sys
import grpc
@@ -35,7 +35,7 @@ class _Watcher():
def __init__(self):
self._condition = threading.Condition()
- self._responses = collections.deque()
+ self._responses = collections.deque()
self._open = True
def __iter__(self):
@@ -46,7 +46,7 @@ class _Watcher():
while not self._responses and self._open:
self._condition.wait()
if self._responses:
- return self._responses.popleft()
+ return self._responses.popleft()
else:
raise StopIteration()
@@ -67,37 +67,37 @@ class _Watcher():
self._condition.notify()
-def _watcher_to_send_response_callback_adapter(watcher):
-
- def send_response_callback(response):
- if response is None:
- watcher.close()
- else:
- watcher.add(response)
-
- return send_response_callback
-
-
+def _watcher_to_send_response_callback_adapter(watcher):
+
+ def send_response_callback(response):
+ if response is None:
+ watcher.close()
+ else:
+ watcher.add(response)
+
+ return send_response_callback
+
+
class HealthServicer(_health_pb2_grpc.HealthServicer):
"""Servicer handling RPCs for service statuses."""
- def __init__(self,
- experimental_non_blocking=True,
- experimental_thread_pool=None):
+ def __init__(self,
+ experimental_non_blocking=True,
+ experimental_thread_pool=None):
self._lock = threading.RLock()
self._server_status = {"": _health_pb2.HealthCheckResponse.SERVING}
- self._send_response_callbacks = {}
- self.Watch.__func__.experimental_non_blocking = experimental_non_blocking
- self.Watch.__func__.experimental_thread_pool = experimental_thread_pool
- self._gracefully_shutting_down = False
+ self._send_response_callbacks = {}
+ self.Watch.__func__.experimental_non_blocking = experimental_non_blocking
+ self.Watch.__func__.experimental_thread_pool = experimental_thread_pool
+ self._gracefully_shutting_down = False
- def _on_close_callback(self, send_response_callback, service):
+ def _on_close_callback(self, send_response_callback, service):
def callback():
with self._lock:
- self._send_response_callbacks[service].remove(
- send_response_callback)
- send_response_callback(None)
+ self._send_response_callbacks[service].remove(
+ send_response_callback)
+ send_response_callback(None)
return callback
@@ -110,29 +110,29 @@ class HealthServicer(_health_pb2_grpc.HealthServicer):
else:
return _health_pb2.HealthCheckResponse(status=status)
- # pylint: disable=arguments-differ
- def Watch(self, request, context, send_response_callback=None):
- blocking_watcher = None
- if send_response_callback is None:
- # The server does not support the experimental_non_blocking
- # parameter. For backwards compatibility, return a blocking response
- # generator.
- blocking_watcher = _Watcher()
- send_response_callback = _watcher_to_send_response_callback_adapter(
- blocking_watcher)
+ # pylint: disable=arguments-differ
+ def Watch(self, request, context, send_response_callback=None):
+ blocking_watcher = None
+ if send_response_callback is None:
+ # The server does not support the experimental_non_blocking
+ # parameter. For backwards compatibility, return a blocking response
+ # generator.
+ blocking_watcher = _Watcher()
+ send_response_callback = _watcher_to_send_response_callback_adapter(
+ blocking_watcher)
service = request.service
with self._lock:
status = self._server_status.get(service)
if status is None:
status = _health_pb2.HealthCheckResponse.SERVICE_UNKNOWN # pylint: disable=no-member
- send_response_callback(
- _health_pb2.HealthCheckResponse(status=status))
- if service not in self._send_response_callbacks:
- self._send_response_callbacks[service] = set()
- self._send_response_callbacks[service].add(send_response_callback)
- context.add_callback(
- self._on_close_callback(send_response_callback, service))
- return blocking_watcher
+ send_response_callback(
+ _health_pb2.HealthCheckResponse(status=status))
+ if service not in self._send_response_callbacks:
+ self._send_response_callbacks[service] = set()
+ self._send_response_callbacks[service].add(send_response_callback)
+ context.add_callback(
+ self._on_close_callback(send_response_callback, service))
+ return blocking_watcher
def set(self, service, status):
"""Sets the status of a service.
@@ -143,30 +143,30 @@ class HealthServicer(_health_pb2_grpc.HealthServicer):
the service
"""
with self._lock:
- if self._gracefully_shutting_down:
- return
- else:
- self._server_status[service] = status
- if service in self._send_response_callbacks:
- for send_response_callback in self._send_response_callbacks[
- service]:
- send_response_callback(
- _health_pb2.HealthCheckResponse(status=status))
-
- def enter_graceful_shutdown(self):
- """Permanently sets the status of all services to NOT_SERVING.
-
- This should be invoked when the server is entering a graceful shutdown
- period. After this method is invoked, future attempts to set the status
- of a service will be ignored.
-
- This is an EXPERIMENTAL API.
- """
- with self._lock:
- if self._gracefully_shutting_down:
- return
- else:
- for service in self._server_status:
- self.set(service,
- _health_pb2.HealthCheckResponse.NOT_SERVING) # pylint: disable=no-member
- self._gracefully_shutting_down = True
+ if self._gracefully_shutting_down:
+ return
+ else:
+ self._server_status[service] = status
+ if service in self._send_response_callbacks:
+ for send_response_callback in self._send_response_callbacks[
+ service]:
+ send_response_callback(
+ _health_pb2.HealthCheckResponse(status=status))
+
+ def enter_graceful_shutdown(self):
+ """Permanently sets the status of all services to NOT_SERVING.
+
+ This should be invoked when the server is entering a graceful shutdown
+ period. After this method is invoked, future attempts to set the status
+ of a service will be ignored.
+
+ This is an EXPERIMENTAL API.
+ """
+ with self._lock:
+ if self._gracefully_shutting_down:
+ return
+ else:
+ for service in self._server_status:
+ self.set(service,
+ _health_pb2.HealthCheckResponse.NOT_SERVING) # pylint: disable=no-member
+ self._gracefully_shutting_down = True
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py b/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py
index fa1fbbd55a..c7259d1843 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py
@@ -17,9 +17,9 @@ import os
import setuptools
-_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
-_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
-
+_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
+_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
+
# Ensure we're in the proper directory whether or not we're being used by pip.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
@@ -52,8 +52,8 @@ CLASSIFIERS = [
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: Apache Software License',
]
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/ya.make b/contrib/libs/grpc/src/python/grpcio_health_checking/ya.make
index 4bab1758a5..696f0008b0 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/ya.make
@@ -1,48 +1,48 @@
-PY23_LIBRARY()
-
+PY23_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- dvshkurko
- g:contrib
- g:cpp-contrib
-)
-
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/python/six
-)
-
-IF (PYTHON2)
- PEERDIR(
- contrib/python/enum34
- contrib/python/futures
- )
-ENDIF()
-
-ADDINCL(
+OWNER(
+ akastornov
+ dvshkurko
+ g:contrib
+ g:cpp-contrib
+)
+
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/python/six
+)
+
+IF (PYTHON2)
+ PEERDIR(
+ contrib/python/enum34
+ contrib/python/futures
+ )
+ENDIF()
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
IF (SANITIZER_TYPE == undefined)
- # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
- CXXFLAGS(-fno-sanitize=function)
-ENDIF()
-
-NO_LINT()
-
-NO_COMPILER_WARNINGS()
-
-PY_SRCS(
- TOP_LEVEL
- grpc_health/__init__.py
- grpc_health/v1/__init__.py
- grpc_health/v1/health.py
-)
-
-END()
+ # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
+ CXXFLAGS(-fno-sanitize=function)
+ENDIF()
+
+NO_LINT()
+
+NO_COMPILER_WARNINGS()
+
+PY_SRCS(
+ TOP_LEVEL
+ grpc_health/__init__.py
+ grpc_health/v1/__init__.py
+ grpc_health/v1/health.py
+)
+
+END()
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/README.rst b/contrib/libs/grpc/src/python/grpcio_reflection/README.rst
index 56f9953373..d3a7633599 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/README.rst
@@ -3,14 +3,14 @@ gRPC Python Reflection package
Reference package for reflection in GRPC Python.
-Supported Python Versions
--------------------------
-Python >= 3.5
-
-Deprecated Python Versions
---------------------------
-Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
-
+Supported Python Versions
+-------------------------
+Python >= 3.5
+
+Deprecated Python Versions
+--------------------------
+Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
+
Dependencies
------------
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/setup.py b/contrib/libs/grpc/src/python/grpcio_reflection/setup.py
index 2d0a3fcdaa..b44ea9206c 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/setup.py
@@ -18,9 +18,9 @@ import sys
import setuptools
-_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
-_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
-
+_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
+_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
+
# Ensure we're in the proper directory whether or not we're being used by pip.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
@@ -53,8 +53,8 @@ CLASSIFIERS = [
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: Apache Software License',
]
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/ya.make b/contrib/libs/grpc/src/python/grpcio_reflection/ya.make
index c0f7d61dcc..8a15784d91 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/ya.make
@@ -1,52 +1,52 @@
-PY23_LIBRARY()
-
+PY23_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- dvshkurko
- g:contrib
- g:cpp-contrib
-)
-
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/python/six
+OWNER(
+ akastornov
+ dvshkurko
+ g:contrib
+ g:cpp-contrib
+)
+
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/python/six
contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
-)
-
-IF (PYTHON2)
- PEERDIR(
- contrib/python/enum34
- contrib/python/futures
- )
-ENDIF()
-
-ADDINCL(
+)
+
+IF (PYTHON2)
+ PEERDIR(
+ contrib/python/enum34
+ contrib/python/futures
+ )
+ENDIF()
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
IF (SANITIZER_TYPE == undefined)
- # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
- CXXFLAGS(-fno-sanitize=function)
-ENDIF()
-
-NO_LINT()
-
-NO_COMPILER_WARNINGS()
-
-PY_SRCS(
- TOP_LEVEL
- grpc_reflection/__init__.py
- grpc_reflection/v1alpha/__init__.py
+ # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
+ CXXFLAGS(-fno-sanitize=function)
+ENDIF()
+
+NO_LINT()
+
+NO_COMPILER_WARNINGS()
+
+PY_SRCS(
+ TOP_LEVEL
+ grpc_reflection/__init__.py
+ grpc_reflection/v1alpha/__init__.py
grpc_reflection/v1alpha/_base.py
- grpc_reflection/v1alpha/reflection.py
-)
-
+ grpc_reflection/v1alpha/reflection.py
+)
+
IF (PYTHON3)
PY_SRCS(
TOP_LEVEL
@@ -54,4 +54,4 @@ IF (PYTHON3)
)
ENDIF()
-END()
+END()
diff --git a/contrib/libs/grpc/src/python/grpcio_status/README.rst b/contrib/libs/grpc/src/python/grpcio_status/README.rst
index 16c59387a6..5774c5f696 100644
--- a/contrib/libs/grpc/src/python/grpcio_status/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio_status/README.rst
@@ -1,17 +1,17 @@
-gRPC Python Status Proto
-===========================
-
-Reference package for GRPC Python status proto mapping.
-
-Supported Python Versions
--------------------------
-Python >= 3.5
-
-Deprecated Python Versions
---------------------------
-Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
-
-Dependencies
-------------
-
-Depends on the `grpcio` package, available from PyPI via `pip install grpcio`.
+gRPC Python Status Proto
+===========================
+
+Reference package for GRPC Python status proto mapping.
+
+Supported Python Versions
+-------------------------
+Python >= 3.5
+
+Deprecated Python Versions
+--------------------------
+Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
+
+Dependencies
+------------
+
+Depends on the `grpcio` package, available from PyPI via `pip install grpcio`.
diff --git a/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py b/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py
index d0ec08e3a5..e6d3a98775 100644
--- a/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py
+++ b/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py
@@ -44,8 +44,8 @@ def from_call(call):
ValueError: If the gRPC call's code or details are inconsistent with the
status code and message inside of the google.rpc.status.Status.
"""
- if call.trailing_metadata() is None:
- return None
+ if call.trailing_metadata() is None:
+ return None
for key, value in call.trailing_metadata():
if key == GRPC_DETAILS_METADATA_KEY:
rich_status = status_pb2.Status.FromString(value)
diff --git a/contrib/libs/grpc/src/python/grpcio_status/setup.py b/contrib/libs/grpc/src/python/grpcio_status/setup.py
index eb49069c34..2262e2ae28 100644
--- a/contrib/libs/grpc/src/python/grpcio_status/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_status/setup.py
@@ -17,9 +17,9 @@ import os
import setuptools
-_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
-_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
-
+_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
+_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
+
# Ensure we're in the proper directory whether or not we're being used by pip.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
@@ -53,7 +53,7 @@ CLASSIFIERS = [
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: Apache Software License',
]
diff --git a/contrib/libs/grpc/src/python/grpcio_status/ya.make b/contrib/libs/grpc/src/python/grpcio_status/ya.make
index 61a3ee4336..68e8961a22 100644
--- a/contrib/libs/grpc/src/python/grpcio_status/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio_status/ya.make
@@ -1,51 +1,51 @@
-PY23_LIBRARY()
-
+PY23_LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-OWNER(
- akastornov
- dvshkurko
- g:contrib
- g:cpp-contrib
-)
-
-PEERDIR(
+OWNER(
+ akastornov
+ dvshkurko
+ g:contrib
+ g:cpp-contrib
+)
+
+PEERDIR(
contrib/python/google-api-core
- contrib/libs/grpc/grpc
- contrib/python/six
-)
-
-IF (PYTHON2)
- PEERDIR(
- contrib/python/enum34
- contrib/python/futures
- )
-ENDIF()
-
-ADDINCL(
+ contrib/libs/grpc/grpc
+ contrib/python/six
+)
+
+IF (PYTHON2)
+ PEERDIR(
+ contrib/python/enum34
+ contrib/python/futures
+ )
+ENDIF()
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
IF (SANITIZER_TYPE == undefined)
- # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
- CXXFLAGS(-fno-sanitize=function)
-ENDIF()
-
-NO_LINT()
-
-NO_COMPILER_WARNINGS()
-
-PY_SRCS(
- TOP_LEVEL
- grpc_status/__init__.py
+ # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
+ CXXFLAGS(-fno-sanitize=function)
+ENDIF()
+
+NO_LINT()
+
+NO_COMPILER_WARNINGS()
+
+PY_SRCS(
+ TOP_LEVEL
+ grpc_status/__init__.py
grpc_status/_common.py
grpc_status/rpc_status.py
-)
-
+)
+
IF (PYTHON3)
PY_SRCS(
TOP_LEVEL
@@ -53,4 +53,4 @@ IF (PYTHON3)
)
ENDIF()
-END()
+END()
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/README.rst b/contrib/libs/grpc/src/python/grpcio_testing/README.rst
index 968dec8507..4d7a594d90 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio_testing/README.rst
@@ -3,14 +3,14 @@ gRPC Python Testing Package
Testing utilities for gRPC Python
-Supported Python Versions
--------------------------
-Python >= 3.5
-
-Deprecated Python Versions
---------------------------
-Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
-
+Supported Python Versions
+-------------------------
+Python >= 3.5
+
+Deprecated Python Versions
+--------------------------
+Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
+
Dependencies
------------
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_service.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_service.py
index a65628a121..59d901491a 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_service.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_service.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import copy
+import copy
import grpc
@@ -60,7 +60,7 @@ def _stream_response(argument, implementation, rpc, servicer_context):
else:
while True:
try:
- response = copy.deepcopy(next(response_iterator))
+ response = copy.deepcopy(next(response_iterator))
except StopIteration:
rpc.stream_response_complete()
break
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py
index c63750f978..abf6c6b565 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py
@@ -56,9 +56,9 @@ class ServicerContext(grpc.ServicerContext):
def auth_context(self):
raise NotImplementedError()
- def set_compression(self):
- raise NotImplementedError()
-
+ def set_compression(self):
+ raise NotImplementedError()
+
def send_initial_metadata(self, initial_metadata):
initial_metadata_sent = self._rpc.send_initial_metadata(
_common.fuss_with_metadata(initial_metadata))
@@ -66,17 +66,17 @@ class ServicerContext(grpc.ServicerContext):
raise ValueError(
'ServicerContext.send_initial_metadata called too late!')
- def disable_next_message_compression(self):
- raise NotImplementedError()
-
+ def disable_next_message_compression(self):
+ raise NotImplementedError()
+
def set_trailing_metadata(self, trailing_metadata):
self._rpc.set_trailing_metadata(
_common.fuss_with_metadata(trailing_metadata))
def abort(self, code, details):
- with self._rpc._condition:
- self._rpc._abort(code, details)
- raise Exception()
+ with self._rpc._condition:
+ self._rpc._abort(code, details)
+ raise Exception()
def abort_with_status(self, status):
raise NotImplementedError()
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/setup.py b/contrib/libs/grpc/src/python/grpcio_testing/setup.py
index 1946793fe6..ff54dd72e6 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/setup.py
@@ -18,9 +18,9 @@ import sys
import setuptools
-_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
-_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
-
+_PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__))
+_README_PATH = os.path.join(_PACKAGE_PATH, 'README.rst')
+
# Ensure we're in the proper directory whether or not we're being used by pip.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/commands.py b/contrib/libs/grpc/src/python/grpcio_tests/commands.py
index 889b0bd9dc..d421d6fe61 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/commands.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/commands.py
@@ -1,111 +1,111 @@
-# Copyright 2015 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.
-"""Provides distutils command classes for the gRPC Python setup process."""
-
-from distutils import errors as _errors
-import glob
-import os
-import os.path
-import platform
-import re
-import shutil
-import sys
-
-import setuptools
-from setuptools.command import build_ext
-from setuptools.command import build_py
-from setuptools.command import easy_install
-from setuptools.command import install
-from setuptools.command import test
-
-PYTHON_STEM = os.path.dirname(os.path.abspath(__file__))
-GRPC_STEM = os.path.abspath(PYTHON_STEM + '../../../../')
-GRPC_PROTO_STEM = os.path.join(GRPC_STEM, 'src', 'proto')
-PROTO_STEM = os.path.join(PYTHON_STEM, 'src', 'proto')
-PYTHON_PROTO_TOP_LEVEL = os.path.join(PYTHON_STEM, 'src')
-
-
-class CommandError(object):
- pass
-
-
-class GatherProto(setuptools.Command):
-
- description = 'gather proto dependencies'
- user_options = []
-
- def initialize_options(self):
- pass
-
- def finalize_options(self):
- pass
-
- def run(self):
- # TODO(atash) ensure that we're running from the repository directory when
- # this command is used
- try:
- shutil.rmtree(PROTO_STEM)
- except Exception as error:
- # We don't care if this command fails
- pass
- shutil.copytree(GRPC_PROTO_STEM, PROTO_STEM)
- for root, _, _ in os.walk(PYTHON_PROTO_TOP_LEVEL):
- path = os.path.join(root, '__init__.py')
- open(path, 'a').close()
-
-
-class BuildPy(build_py.build_py):
- """Custom project build command."""
-
- def run(self):
- try:
- self.run_command('build_package_protos')
- except CommandError as error:
- sys.stderr.write('warning: %s\n' % error.message)
- build_py.build_py.run(self)
-
-
-class TestLite(setuptools.Command):
- """Command to run tests without fetching or building anything."""
-
- description = 'run tests without fetching or building anything.'
- user_options = []
-
- def initialize_options(self):
- pass
-
- def finalize_options(self):
- # distutils requires this override.
- pass
-
- def run(self):
- self._add_eggs_to_path()
-
- import tests
- loader = tests.Loader()
- loader.loadTestsFromNames(['tests'])
- runner = tests.Runner(dedicated_threads=True)
- result = runner.run(loader.suite)
- if not result.wasSuccessful():
- sys.exit('Test failure')
-
- def _add_eggs_to_path(self):
- """Fetch install and test requirements"""
- self.distribution.fetch_build_eggs(self.distribution.install_requires)
- self.distribution.fetch_build_eggs(self.distribution.tests_require)
-
-
+# Copyright 2015 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.
+"""Provides distutils command classes for the gRPC Python setup process."""
+
+from distutils import errors as _errors
+import glob
+import os
+import os.path
+import platform
+import re
+import shutil
+import sys
+
+import setuptools
+from setuptools.command import build_ext
+from setuptools.command import build_py
+from setuptools.command import easy_install
+from setuptools.command import install
+from setuptools.command import test
+
+PYTHON_STEM = os.path.dirname(os.path.abspath(__file__))
+GRPC_STEM = os.path.abspath(PYTHON_STEM + '../../../../')
+GRPC_PROTO_STEM = os.path.join(GRPC_STEM, 'src', 'proto')
+PROTO_STEM = os.path.join(PYTHON_STEM, 'src', 'proto')
+PYTHON_PROTO_TOP_LEVEL = os.path.join(PYTHON_STEM, 'src')
+
+
+class CommandError(object):
+ pass
+
+
+class GatherProto(setuptools.Command):
+
+ description = 'gather proto dependencies'
+ user_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ # TODO(atash) ensure that we're running from the repository directory when
+ # this command is used
+ try:
+ shutil.rmtree(PROTO_STEM)
+ except Exception as error:
+ # We don't care if this command fails
+ pass
+ shutil.copytree(GRPC_PROTO_STEM, PROTO_STEM)
+ for root, _, _ in os.walk(PYTHON_PROTO_TOP_LEVEL):
+ path = os.path.join(root, '__init__.py')
+ open(path, 'a').close()
+
+
+class BuildPy(build_py.build_py):
+ """Custom project build command."""
+
+ def run(self):
+ try:
+ self.run_command('build_package_protos')
+ except CommandError as error:
+ sys.stderr.write('warning: %s\n' % error.message)
+ build_py.build_py.run(self)
+
+
+class TestLite(setuptools.Command):
+ """Command to run tests without fetching or building anything."""
+
+ description = 'run tests without fetching or building anything.'
+ user_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ # distutils requires this override.
+ pass
+
+ def run(self):
+ self._add_eggs_to_path()
+
+ import tests
+ loader = tests.Loader()
+ loader.loadTestsFromNames(['tests'])
+ runner = tests.Runner(dedicated_threads=True)
+ result = runner.run(loader.suite)
+ if not result.wasSuccessful():
+ sys.exit('Test failure')
+
+ def _add_eggs_to_path(self):
+ """Fetch install and test requirements"""
+ self.distribution.fetch_build_eggs(self.distribution.install_requires)
+ self.distribution.fetch_build_eggs(self.distribution.tests_require)
+
+
class TestPy3Only(setuptools.Command):
"""Command to run tests for Python 3+ features.
@@ -137,170 +137,170 @@ class TestPy3Only(setuptools.Command):
self.distribution.fetch_build_eggs(self.distribution.tests_require)
-class TestAio(setuptools.Command):
- """Command to run aio tests without fetching or building anything."""
-
- description = 'run aio tests without fetching or building anything.'
- user_options = []
-
- def initialize_options(self):
- pass
-
- def finalize_options(self):
- pass
-
- def run(self):
- self._add_eggs_to_path()
-
- import tests
- loader = tests.Loader()
- loader.loadTestsFromNames(['tests_aio'])
- # Even without dedicated threads, the framework will somehow spawn a
- # new thread for tests to run upon. New thread doesn't have event loop
- # attached by default, so initialization is needed.
- runner = tests.Runner(dedicated_threads=False)
- result = runner.run(loader.suite)
- if not result.wasSuccessful():
- sys.exit('Test failure')
-
- def _add_eggs_to_path(self):
- """Fetch install and test requirements"""
- self.distribution.fetch_build_eggs(self.distribution.install_requires)
- self.distribution.fetch_build_eggs(self.distribution.tests_require)
-
-
-class TestGevent(setuptools.Command):
- """Command to run tests w/gevent."""
-
- BANNED_TESTS = (
- # Fork support is not compatible with gevent
- 'fork._fork_interop_test.ForkInteropTest',
- # These tests send a lot of RPCs and are really slow on gevent. They will
- # eventually succeed, but need to dig into performance issues.
- 'unit._cython._no_messages_server_completion_queue_per_call_test.Test.test_rpcs',
- 'unit._cython._no_messages_single_server_completion_queue_test.Test.test_rpcs',
- 'unit._compression_test',
- # TODO(https://github.com/grpc/grpc/issues/16890) enable this test
- 'unit._cython._channel_test.ChannelTest.test_multiple_channels_lonely_connectivity',
- # I have no idea why this doesn't work in gevent, but it shouldn't even be
- # using the c-core
- 'testing._client_test.ClientTest.test_infinite_request_stream_real_time',
- # TODO(https://github.com/grpc/grpc/issues/15743) enable this test
- 'unit._session_cache_test.SSLSessionCacheTest.testSSLSessionCacheLRU',
- # TODO(https://github.com/grpc/grpc/issues/14789) enable this test
- 'unit._server_ssl_cert_config_test',
- # TODO(https://github.com/grpc/grpc/issues/14901) enable this test
- 'protoc_plugin._python_plugin_test.PythonPluginTest',
+class TestAio(setuptools.Command):
+ """Command to run aio tests without fetching or building anything."""
+
+ description = 'run aio tests without fetching or building anything.'
+ user_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ self._add_eggs_to_path()
+
+ import tests
+ loader = tests.Loader()
+ loader.loadTestsFromNames(['tests_aio'])
+ # Even without dedicated threads, the framework will somehow spawn a
+ # new thread for tests to run upon. New thread doesn't have event loop
+ # attached by default, so initialization is needed.
+ runner = tests.Runner(dedicated_threads=False)
+ result = runner.run(loader.suite)
+ if not result.wasSuccessful():
+ sys.exit('Test failure')
+
+ def _add_eggs_to_path(self):
+ """Fetch install and test requirements"""
+ self.distribution.fetch_build_eggs(self.distribution.install_requires)
+ self.distribution.fetch_build_eggs(self.distribution.tests_require)
+
+
+class TestGevent(setuptools.Command):
+ """Command to run tests w/gevent."""
+
+ BANNED_TESTS = (
+ # Fork support is not compatible with gevent
+ 'fork._fork_interop_test.ForkInteropTest',
+ # These tests send a lot of RPCs and are really slow on gevent. They will
+ # eventually succeed, but need to dig into performance issues.
+ 'unit._cython._no_messages_server_completion_queue_per_call_test.Test.test_rpcs',
+ 'unit._cython._no_messages_single_server_completion_queue_test.Test.test_rpcs',
+ 'unit._compression_test',
+ # TODO(https://github.com/grpc/grpc/issues/16890) enable this test
+ 'unit._cython._channel_test.ChannelTest.test_multiple_channels_lonely_connectivity',
+ # I have no idea why this doesn't work in gevent, but it shouldn't even be
+ # using the c-core
+ 'testing._client_test.ClientTest.test_infinite_request_stream_real_time',
+ # TODO(https://github.com/grpc/grpc/issues/15743) enable this test
+ 'unit._session_cache_test.SSLSessionCacheTest.testSSLSessionCacheLRU',
+ # TODO(https://github.com/grpc/grpc/issues/14789) enable this test
+ 'unit._server_ssl_cert_config_test',
+ # TODO(https://github.com/grpc/grpc/issues/14901) enable this test
+ 'protoc_plugin._python_plugin_test.PythonPluginTest',
'protoc_plugin._python_plugin_test.SimpleStubsPluginTest',
- # Beta API is unsupported for gevent
- 'protoc_plugin.beta_python_plugin_test',
- 'unit.beta._beta_features_test',
- # TODO(https://github.com/grpc/grpc/issues/15411) unpin gevent version
- # This test will stuck while running higher version of gevent
- 'unit._auth_context_test.AuthContextTest.testSessionResumption',
- # TODO(https://github.com/grpc/grpc/issues/15411) enable these tests
- 'unit._channel_ready_future_test.ChannelReadyFutureTest.test_immediately_connectable_channel_connectivity',
- "unit._cython._channel_test.ChannelTest.test_single_channel_lonely_connectivity",
- 'unit._exit_test.ExitTest.test_in_flight_unary_unary_call',
- 'unit._exit_test.ExitTest.test_in_flight_unary_stream_call',
- 'unit._exit_test.ExitTest.test_in_flight_stream_unary_call',
- 'unit._exit_test.ExitTest.test_in_flight_stream_stream_call',
- 'unit._exit_test.ExitTest.test_in_flight_partial_unary_stream_call',
- 'unit._exit_test.ExitTest.test_in_flight_partial_stream_unary_call',
- 'unit._exit_test.ExitTest.test_in_flight_partial_stream_stream_call',
- # TODO(https://github.com/grpc/grpc/issues/18980): Reenable.
- 'unit._signal_handling_test.SignalHandlingTest',
- 'unit._metadata_flags_test',
- 'health_check._health_servicer_test.HealthServicerTest.test_cancelled_watch_removed_from_watch_list',
- # TODO(https://github.com/grpc/grpc/issues/17330) enable these three tests
- 'channelz._channelz_servicer_test.ChannelzServicerTest.test_many_subchannels',
- 'channelz._channelz_servicer_test.ChannelzServicerTest.test_many_subchannels_and_sockets',
- 'channelz._channelz_servicer_test.ChannelzServicerTest.test_streaming_rpc',
- # TODO(https://github.com/grpc/grpc/issues/15411) enable this test
- 'unit._cython._channel_test.ChannelTest.test_negative_deadline_connectivity',
- # TODO(https://github.com/grpc/grpc/issues/15411) enable this test
- 'unit._local_credentials_test.LocalCredentialsTest',
+ # Beta API is unsupported for gevent
+ 'protoc_plugin.beta_python_plugin_test',
+ 'unit.beta._beta_features_test',
+ # TODO(https://github.com/grpc/grpc/issues/15411) unpin gevent version
+ # This test will stuck while running higher version of gevent
+ 'unit._auth_context_test.AuthContextTest.testSessionResumption',
+ # TODO(https://github.com/grpc/grpc/issues/15411) enable these tests
+ 'unit._channel_ready_future_test.ChannelReadyFutureTest.test_immediately_connectable_channel_connectivity',
+ "unit._cython._channel_test.ChannelTest.test_single_channel_lonely_connectivity",
+ 'unit._exit_test.ExitTest.test_in_flight_unary_unary_call',
+ 'unit._exit_test.ExitTest.test_in_flight_unary_stream_call',
+ 'unit._exit_test.ExitTest.test_in_flight_stream_unary_call',
+ 'unit._exit_test.ExitTest.test_in_flight_stream_stream_call',
+ 'unit._exit_test.ExitTest.test_in_flight_partial_unary_stream_call',
+ 'unit._exit_test.ExitTest.test_in_flight_partial_stream_unary_call',
+ 'unit._exit_test.ExitTest.test_in_flight_partial_stream_stream_call',
+ # TODO(https://github.com/grpc/grpc/issues/18980): Reenable.
+ 'unit._signal_handling_test.SignalHandlingTest',
+ 'unit._metadata_flags_test',
+ 'health_check._health_servicer_test.HealthServicerTest.test_cancelled_watch_removed_from_watch_list',
+ # TODO(https://github.com/grpc/grpc/issues/17330) enable these three tests
+ 'channelz._channelz_servicer_test.ChannelzServicerTest.test_many_subchannels',
+ 'channelz._channelz_servicer_test.ChannelzServicerTest.test_many_subchannels_and_sockets',
+ 'channelz._channelz_servicer_test.ChannelzServicerTest.test_streaming_rpc',
+ # TODO(https://github.com/grpc/grpc/issues/15411) enable this test
+ 'unit._cython._channel_test.ChannelTest.test_negative_deadline_connectivity',
+ # TODO(https://github.com/grpc/grpc/issues/15411) enable this test
+ 'unit._local_credentials_test.LocalCredentialsTest',
# TODO(https://github.com/grpc/grpc/issues/22020) LocalCredentials
# aren't supported with custom io managers.
'unit._contextvars_propagation_test',
- 'testing._time_test.StrictRealTimeTest',
- )
- BANNED_WINDOWS_TESTS = (
- # TODO(https://github.com/grpc/grpc/pull/15411) enable this test
+ 'testing._time_test.StrictRealTimeTest',
+ )
+ BANNED_WINDOWS_TESTS = (
+ # TODO(https://github.com/grpc/grpc/pull/15411) enable this test
'unit._dns_resolver_test.DNSResolverTest.test_connect_loopback',
# TODO(https://github.com/grpc/grpc/pull/15411) enable this test
'unit._server_test.ServerTest.test_failed_port_binding_exception',
)
- description = 'run tests with gevent. Assumes grpc/gevent are installed'
- user_options = []
-
- def initialize_options(self):
- pass
-
- def finalize_options(self):
- # distutils requires this override.
- pass
-
- def run(self):
- from gevent import monkey
- monkey.patch_all()
-
- import tests
-
- import grpc.experimental.gevent
- grpc.experimental.gevent.init_gevent()
-
- import gevent
-
- import tests
- loader = tests.Loader()
- loader.loadTestsFromNames(['tests'])
- runner = tests.Runner()
- if sys.platform == 'win32':
- runner.skip_tests(self.BANNED_TESTS + self.BANNED_WINDOWS_TESTS)
- else:
- runner.skip_tests(self.BANNED_TESTS)
- result = gevent.spawn(runner.run, loader.suite)
- result.join()
- if not result.value.wasSuccessful():
- sys.exit('Test failure')
-
-
-class RunInterop(test.test):
-
- description = 'run interop test client/server'
+ description = 'run tests with gevent. Assumes grpc/gevent are installed'
+ user_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ # distutils requires this override.
+ pass
+
+ def run(self):
+ from gevent import monkey
+ monkey.patch_all()
+
+ import tests
+
+ import grpc.experimental.gevent
+ grpc.experimental.gevent.init_gevent()
+
+ import gevent
+
+ import tests
+ loader = tests.Loader()
+ loader.loadTestsFromNames(['tests'])
+ runner = tests.Runner()
+ if sys.platform == 'win32':
+ runner.skip_tests(self.BANNED_TESTS + self.BANNED_WINDOWS_TESTS)
+ else:
+ runner.skip_tests(self.BANNED_TESTS)
+ result = gevent.spawn(runner.run, loader.suite)
+ result.join()
+ if not result.value.wasSuccessful():
+ sys.exit('Test failure')
+
+
+class RunInterop(test.test):
+
+ description = 'run interop test client/server'
user_options = [
('args=', None, 'pass-thru arguments for the client/server'),
('client', None, 'flag indicating to run the client'),
('server', None, 'flag indicating to run the server'),
('use-asyncio', None, 'flag indicating to run the asyncio stack')
]
-
- def initialize_options(self):
- self.args = ''
- self.client = False
- self.server = False
+
+ def initialize_options(self):
+ self.args = ''
+ self.client = False
+ self.server = False
self.use_asyncio = False
-
- def finalize_options(self):
- if self.client and self.server:
- raise _errors.DistutilsOptionError(
- 'you may only specify one of client or server')
-
- def run(self):
- if self.distribution.install_requires:
- self.distribution.fetch_build_eggs(
- self.distribution.install_requires)
- if self.distribution.tests_require:
- self.distribution.fetch_build_eggs(self.distribution.tests_require)
- if self.client:
- self.run_client()
- elif self.server:
- self.run_server()
-
- def run_server(self):
- # We import here to ensure that our setuptools parent has had a chance to
- # edit the Python system path.
+
+ def finalize_options(self):
+ if self.client and self.server:
+ raise _errors.DistutilsOptionError(
+ 'you may only specify one of client or server')
+
+ def run(self):
+ if self.distribution.install_requires:
+ self.distribution.fetch_build_eggs(
+ self.distribution.install_requires)
+ if self.distribution.tests_require:
+ self.distribution.fetch_build_eggs(self.distribution.tests_require)
+ if self.client:
+ self.run_client()
+ elif self.server:
+ self.run_server()
+
+ def run_server(self):
+ # We import here to ensure that our setuptools parent has had a chance to
+ # edit the Python system path.
if self.use_asyncio:
import asyncio
from tests_aio.interop import server
@@ -310,35 +310,35 @@ class RunInterop(test.test):
from tests.interop import server
sys.argv[1:] = self.args.split()
server.serve()
-
- def run_client(self):
- # We import here to ensure that our setuptools parent has had a chance to
- # edit the Python system path.
- from tests.interop import client
- sys.argv[1:] = self.args.split()
- client.test_interoperability()
-
-
-class RunFork(test.test):
-
- description = 'run fork test client'
- user_options = [('args=', 'a', 'pass-thru arguments for the client')]
-
- def initialize_options(self):
- self.args = ''
-
- def finalize_options(self):
- # distutils requires this override.
- pass
-
- def run(self):
- if self.distribution.install_requires:
- self.distribution.fetch_build_eggs(
- self.distribution.install_requires)
- if self.distribution.tests_require:
- self.distribution.fetch_build_eggs(self.distribution.tests_require)
- # We import here to ensure that our setuptools parent has had a chance to
- # edit the Python system path.
- from tests.fork import client
- sys.argv[1:] = self.args.split()
- client.test_fork()
+
+ def run_client(self):
+ # We import here to ensure that our setuptools parent has had a chance to
+ # edit the Python system path.
+ from tests.interop import client
+ sys.argv[1:] = self.args.split()
+ client.test_interoperability()
+
+
+class RunFork(test.test):
+
+ description = 'run fork test client'
+ user_options = [('args=', 'a', 'pass-thru arguments for the client')]
+
+ def initialize_options(self):
+ self.args = ''
+
+ def finalize_options(self):
+ # distutils requires this override.
+ pass
+
+ def run(self):
+ if self.distribution.install_requires:
+ self.distribution.fetch_build_eggs(
+ self.distribution.install_requires)
+ if self.distribution.tests_require:
+ self.distribution.fetch_build_eggs(self.distribution.tests_require)
+ # We import here to ensure that our setuptools parent has had a chance to
+ # edit the Python system path.
+ from tests.fork import client
+ sys.argv[1:] = self.args.split()
+ client.test_fork()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/grpc_version.py b/contrib/libs/grpc/src/python/grpcio_tests/grpc_version.py
index 219b336a42..852194b4b0 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/grpc_version.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/grpc_version.py
@@ -1,17 +1,17 @@
-# Copyright 2016 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.
-
-# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_tests/grpc_version.py.template`!!!
-
+# Copyright 2016 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.
+
+# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_tests/grpc_version.py.template`!!!
+
VERSION = '1.33.2'
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/setup.py b/contrib/libs/grpc/src/python/grpcio_tests/setup.py
index 87cccda425..e4167f51dd 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/setup.py
@@ -1,99 +1,99 @@
-# Copyright 2015 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.
-"""A setup module for the gRPC Python package."""
-
+# Copyright 2015 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.
+"""A setup module for the gRPC Python package."""
+
import multiprocessing
-import os
-import os.path
-import sys
-
-import setuptools
-
-import grpc_tools.command
-
-PY3 = sys.version_info.major == 3
-
-# Ensure we're in the proper directory whether or not we're being used by pip.
-os.chdir(os.path.dirname(os.path.abspath(__file__)))
-
-# Break import-style to ensure we can actually find our in-repo dependencies.
-import commands
-import grpc_version
-
-LICENSE = 'Apache License 2.0'
-
-PACKAGE_DIRECTORIES = {
- '': '.',
-}
-
-INSTALL_REQUIRES = (
+import os
+import os.path
+import sys
+
+import setuptools
+
+import grpc_tools.command
+
+PY3 = sys.version_info.major == 3
+
+# Ensure we're in the proper directory whether or not we're being used by pip.
+os.chdir(os.path.dirname(os.path.abspath(__file__)))
+
+# Break import-style to ensure we can actually find our in-repo dependencies.
+import commands
+import grpc_version
+
+LICENSE = 'Apache License 2.0'
+
+PACKAGE_DIRECTORIES = {
+ '': '.',
+}
+
+INSTALL_REQUIRES = (
'coverage>=4.0', 'grpcio>={version}'.format(version=grpc_version.VERSION),
- 'grpcio-channelz>={version}'.format(version=grpc_version.VERSION),
- 'grpcio-status>={version}'.format(version=grpc_version.VERSION),
- 'grpcio-tools>={version}'.format(version=grpc_version.VERSION),
- 'grpcio-health-checking>={version}'.format(version=grpc_version.VERSION),
+ 'grpcio-channelz>={version}'.format(version=grpc_version.VERSION),
+ 'grpcio-status>={version}'.format(version=grpc_version.VERSION),
+ 'grpcio-tools>={version}'.format(version=grpc_version.VERSION),
+ 'grpcio-health-checking>={version}'.format(version=grpc_version.VERSION),
'oauth2client>=1.4.7', 'protobuf>=3.6.0', 'six>=1.10',
'google-auth>=1.17.2', 'requests>=2.14.2')
-
-if not PY3:
+
+if not PY3:
INSTALL_REQUIRES += ('futures>=2.2.0', 'enum34>=1.0.4')
-
-COMMAND_CLASS = {
- # Run `preprocess` *before* doing any packaging!
- 'preprocess': commands.GatherProto,
- 'build_package_protos': grpc_tools.command.BuildPackageProtos,
- 'build_py': commands.BuildPy,
- 'run_fork': commands.RunFork,
- 'run_interop': commands.RunInterop,
- 'test_lite': commands.TestLite,
- 'test_gevent': commands.TestGevent,
- 'test_aio': commands.TestAio,
+
+COMMAND_CLASS = {
+ # Run `preprocess` *before* doing any packaging!
+ 'preprocess': commands.GatherProto,
+ 'build_package_protos': grpc_tools.command.BuildPackageProtos,
+ 'build_py': commands.BuildPy,
+ 'run_fork': commands.RunFork,
+ 'run_interop': commands.RunInterop,
+ 'test_lite': commands.TestLite,
+ 'test_gevent': commands.TestGevent,
+ 'test_aio': commands.TestAio,
'test_py3_only': commands.TestPy3Only,
-}
-
-PACKAGE_DATA = {
- 'tests.interop': [
- 'credentials/ca.pem',
- 'credentials/server1.key',
- 'credentials/server1.pem',
- ],
+}
+
+PACKAGE_DATA = {
+ 'tests.interop': [
+ 'credentials/ca.pem',
+ 'credentials/server1.key',
+ 'credentials/server1.pem',
+ ],
'tests.protoc_plugin.protos.invocation_testing': ['same.proto',],
- 'tests.protoc_plugin.protos.invocation_testing.split_messages': [
- 'messages.proto',
- ],
- 'tests.protoc_plugin.protos.invocation_testing.split_services': [
- 'services.proto',
- ],
- 'tests.testing.proto': [
- 'requests.proto',
- 'services.proto',
- ],
- 'tests.unit': [
- 'credentials/ca.pem',
- 'credentials/server1.key',
- 'credentials/server1.pem',
- ],
- 'tests': ['tests.json'],
-}
-
-TEST_SUITE = 'tests'
-TEST_LOADER = 'tests:Loader'
-TEST_RUNNER = 'tests:Runner'
-TESTS_REQUIRE = INSTALL_REQUIRES
-
-PACKAGES = setuptools.find_packages('.')
-
+ 'tests.protoc_plugin.protos.invocation_testing.split_messages': [
+ 'messages.proto',
+ ],
+ 'tests.protoc_plugin.protos.invocation_testing.split_services': [
+ 'services.proto',
+ ],
+ 'tests.testing.proto': [
+ 'requests.proto',
+ 'services.proto',
+ ],
+ 'tests.unit': [
+ 'credentials/ca.pem',
+ 'credentials/server1.key',
+ 'credentials/server1.pem',
+ ],
+ 'tests': ['tests.json'],
+}
+
+TEST_SUITE = 'tests'
+TEST_LOADER = 'tests:Loader'
+TEST_RUNNER = 'tests:Runner'
+TESTS_REQUIRE = INSTALL_REQUIRES
+
+PACKAGES = setuptools.find_packages('.')
+
if __name__ == "__main__":
multiprocessing.freeze_support()
setuptools.setup(
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/__init__.py
index d2466fd022..ac7756c090 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/__init__.py
@@ -1,21 +1,21 @@
-# Copyright 2015 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.
-
-from __future__ import absolute_import
-
-from tests import _loader
-from tests import _runner
-
-Loader = _loader.Loader
-Runner = _runner.Runner
+# Copyright 2015 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.
+
+from __future__ import absolute_import
+
+from tests import _loader
+from tests import _runner
+
+Loader = _loader.Loader
+Runner = _runner.Runner
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/_loader.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/_loader.py
index 80c107aa8e..dfdbfc9fe0 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/_loader.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/_loader.py
@@ -1,106 +1,106 @@
-# Copyright 2015 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.
-
-from __future__ import absolute_import
-
-import importlib
-import pkgutil
-import re
-import unittest
-
-import coverage
-
-TEST_MODULE_REGEX = r'^.*_test$'
-
-
-class Loader(object):
- """Test loader for setuptools test suite support.
-
- Attributes:
- suite (unittest.TestSuite): All tests collected by the loader.
- loader (unittest.TestLoader): Standard Python unittest loader to be ran per
- module discovered.
- module_matcher (re.RegexObject): A regular expression object to match
- against module names and determine whether or not the discovered module
- contributes to the test suite.
- """
-
- def __init__(self):
- self.suite = unittest.TestSuite()
- self.loader = unittest.TestLoader()
- self.module_matcher = re.compile(TEST_MODULE_REGEX)
-
- def loadTestsFromNames(self, names, module=None):
- """Function mirroring TestLoader::loadTestsFromNames, as expected by
- setuptools.setup argument `test_loader`."""
- # ensure that we capture decorators and definitions (else our coverage
- # measure unnecessarily suffers)
- coverage_context = coverage.Coverage(data_suffix=True)
- coverage_context.start()
- imported_modules = tuple(
- importlib.import_module(name) for name in names)
- for imported_module in imported_modules:
- self.visit_module(imported_module)
- for imported_module in imported_modules:
- try:
- package_paths = imported_module.__path__
- except AttributeError:
- continue
- self.walk_packages(package_paths)
- coverage_context.stop()
- coverage_context.save()
- return self.suite
-
- def walk_packages(self, package_paths):
- """Walks over the packages, dispatching `visit_module` calls.
-
- Args:
- package_paths (list): A list of paths over which to walk through modules
- along.
- """
- for importer, module_name, is_package in (
- pkgutil.walk_packages(package_paths)):
- module = importer.find_module(module_name).load_module(module_name)
- self.visit_module(module)
-
- def visit_module(self, module):
- """Visits the module, adding discovered tests to the test suite.
-
- Args:
- module (module): Module to match against self.module_matcher; if matched
- it has its tests loaded via self.loader into self.suite.
- """
- if self.module_matcher.match(module.__name__):
- module_suite = self.loader.loadTestsFromModule(module)
- self.suite.addTest(module_suite)
-
-
-def iterate_suite_cases(suite):
- """Generator over all unittest.TestCases in a unittest.TestSuite.
-
- Args:
- suite (unittest.TestSuite): Suite to iterate over in the generator.
-
- Returns:
- generator: A generator over all unittest.TestCases in `suite`.
- """
- for item in suite:
- if isinstance(item, unittest.TestSuite):
- for child_item in iterate_suite_cases(item):
- yield child_item
- elif isinstance(item, unittest.TestCase):
- yield item
- else:
- raise ValueError('unexpected suite item of type {}'.format(
- type(item)))
+# Copyright 2015 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.
+
+from __future__ import absolute_import
+
+import importlib
+import pkgutil
+import re
+import unittest
+
+import coverage
+
+TEST_MODULE_REGEX = r'^.*_test$'
+
+
+class Loader(object):
+ """Test loader for setuptools test suite support.
+
+ Attributes:
+ suite (unittest.TestSuite): All tests collected by the loader.
+ loader (unittest.TestLoader): Standard Python unittest loader to be ran per
+ module discovered.
+ module_matcher (re.RegexObject): A regular expression object to match
+ against module names and determine whether or not the discovered module
+ contributes to the test suite.
+ """
+
+ def __init__(self):
+ self.suite = unittest.TestSuite()
+ self.loader = unittest.TestLoader()
+ self.module_matcher = re.compile(TEST_MODULE_REGEX)
+
+ def loadTestsFromNames(self, names, module=None):
+ """Function mirroring TestLoader::loadTestsFromNames, as expected by
+ setuptools.setup argument `test_loader`."""
+ # ensure that we capture decorators and definitions (else our coverage
+ # measure unnecessarily suffers)
+ coverage_context = coverage.Coverage(data_suffix=True)
+ coverage_context.start()
+ imported_modules = tuple(
+ importlib.import_module(name) for name in names)
+ for imported_module in imported_modules:
+ self.visit_module(imported_module)
+ for imported_module in imported_modules:
+ try:
+ package_paths = imported_module.__path__
+ except AttributeError:
+ continue
+ self.walk_packages(package_paths)
+ coverage_context.stop()
+ coverage_context.save()
+ return self.suite
+
+ def walk_packages(self, package_paths):
+ """Walks over the packages, dispatching `visit_module` calls.
+
+ Args:
+ package_paths (list): A list of paths over which to walk through modules
+ along.
+ """
+ for importer, module_name, is_package in (
+ pkgutil.walk_packages(package_paths)):
+ module = importer.find_module(module_name).load_module(module_name)
+ self.visit_module(module)
+
+ def visit_module(self, module):
+ """Visits the module, adding discovered tests to the test suite.
+
+ Args:
+ module (module): Module to match against self.module_matcher; if matched
+ it has its tests loaded via self.loader into self.suite.
+ """
+ if self.module_matcher.match(module.__name__):
+ module_suite = self.loader.loadTestsFromModule(module)
+ self.suite.addTest(module_suite)
+
+
+def iterate_suite_cases(suite):
+ """Generator over all unittest.TestCases in a unittest.TestSuite.
+
+ Args:
+ suite (unittest.TestSuite): Suite to iterate over in the generator.
+
+ Returns:
+ generator: A generator over all unittest.TestCases in `suite`.
+ """
+ for item in suite:
+ if isinstance(item, unittest.TestSuite):
+ for child_item in iterate_suite_cases(item):
+ yield child_item
+ elif isinstance(item, unittest.TestCase):
+ yield item
+ else:
+ raise ValueError('unexpected suite item of type {}'.format(
+ type(item)))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/_result.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/_result.py
index 389d5f4f96..c390fe9d69 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/_result.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/_result.py
@@ -1,111 +1,111 @@
-# Copyright 2015 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.
-
-from __future__ import absolute_import
-
-import collections
-import itertools
-import traceback
-import unittest
-from xml.etree import ElementTree
-
-import coverage
-from six import moves
-
-from tests import _loader
-
-
-class CaseResult(
- collections.namedtuple('CaseResult', [
- 'id', 'name', 'kind', 'stdout', 'stderr', 'skip_reason', 'traceback'
- ])):
- """A serializable result of a single test case.
-
- Attributes:
- id (object): Any serializable object used to denote the identity of this
- test case.
- name (str or None): A human-readable name of the test case.
- kind (CaseResult.Kind): The kind of test result.
- stdout (object or None): Output on stdout, or None if nothing was captured.
- stderr (object or None): Output on stderr, or None if nothing was captured.
- skip_reason (object or None): The reason the test was skipped. Must be
- something if self.kind is CaseResult.Kind.SKIP, else None.
- traceback (object or None): The traceback of the test. Must be something if
- self.kind is CaseResult.Kind.{ERROR, FAILURE, EXPECTED_FAILURE}, else
- None.
- """
-
- class Kind(object):
- UNTESTED = 'untested'
- RUNNING = 'running'
- ERROR = 'error'
- FAILURE = 'failure'
- SUCCESS = 'success'
- SKIP = 'skip'
- EXPECTED_FAILURE = 'expected failure'
- UNEXPECTED_SUCCESS = 'unexpected success'
-
- def __new__(cls,
- id=None,
- name=None,
- kind=None,
- stdout=None,
- stderr=None,
- skip_reason=None,
- traceback=None):
- """Helper keyword constructor for the namedtuple.
-
- See this class' attributes for information on the arguments."""
- assert id is not None
- assert name is None or isinstance(name, str)
- if kind is CaseResult.Kind.UNTESTED:
- pass
- elif kind is CaseResult.Kind.RUNNING:
- pass
- elif kind is CaseResult.Kind.ERROR:
- assert traceback is not None
- elif kind is CaseResult.Kind.FAILURE:
- assert traceback is not None
- elif kind is CaseResult.Kind.SUCCESS:
- pass
- elif kind is CaseResult.Kind.SKIP:
- assert skip_reason is not None
- elif kind is CaseResult.Kind.EXPECTED_FAILURE:
- assert traceback is not None
- elif kind is CaseResult.Kind.UNEXPECTED_SUCCESS:
- pass
- else:
- assert False
- return super(cls, CaseResult).__new__(cls, id, name, kind, stdout,
- stderr, skip_reason, traceback)
-
- def updated(self,
- name=None,
- kind=None,
- stdout=None,
- stderr=None,
- skip_reason=None,
- traceback=None):
- """Get a new validated CaseResult with the fields updated.
-
- See this class' attributes for information on the arguments."""
- name = self.name if name is None else name
- kind = self.kind if kind is None else kind
- stdout = self.stdout if stdout is None else stdout
- stderr = self.stderr if stderr is None else stderr
- skip_reason = self.skip_reason if skip_reason is None else skip_reason
- traceback = self.traceback if traceback is None else traceback
+# Copyright 2015 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.
+
+from __future__ import absolute_import
+
+import collections
+import itertools
+import traceback
+import unittest
+from xml.etree import ElementTree
+
+import coverage
+from six import moves
+
+from tests import _loader
+
+
+class CaseResult(
+ collections.namedtuple('CaseResult', [
+ 'id', 'name', 'kind', 'stdout', 'stderr', 'skip_reason', 'traceback'
+ ])):
+ """A serializable result of a single test case.
+
+ Attributes:
+ id (object): Any serializable object used to denote the identity of this
+ test case.
+ name (str or None): A human-readable name of the test case.
+ kind (CaseResult.Kind): The kind of test result.
+ stdout (object or None): Output on stdout, or None if nothing was captured.
+ stderr (object or None): Output on stderr, or None if nothing was captured.
+ skip_reason (object or None): The reason the test was skipped. Must be
+ something if self.kind is CaseResult.Kind.SKIP, else None.
+ traceback (object or None): The traceback of the test. Must be something if
+ self.kind is CaseResult.Kind.{ERROR, FAILURE, EXPECTED_FAILURE}, else
+ None.
+ """
+
+ class Kind(object):
+ UNTESTED = 'untested'
+ RUNNING = 'running'
+ ERROR = 'error'
+ FAILURE = 'failure'
+ SUCCESS = 'success'
+ SKIP = 'skip'
+ EXPECTED_FAILURE = 'expected failure'
+ UNEXPECTED_SUCCESS = 'unexpected success'
+
+ def __new__(cls,
+ id=None,
+ name=None,
+ kind=None,
+ stdout=None,
+ stderr=None,
+ skip_reason=None,
+ traceback=None):
+ """Helper keyword constructor for the namedtuple.
+
+ See this class' attributes for information on the arguments."""
+ assert id is not None
+ assert name is None or isinstance(name, str)
+ if kind is CaseResult.Kind.UNTESTED:
+ pass
+ elif kind is CaseResult.Kind.RUNNING:
+ pass
+ elif kind is CaseResult.Kind.ERROR:
+ assert traceback is not None
+ elif kind is CaseResult.Kind.FAILURE:
+ assert traceback is not None
+ elif kind is CaseResult.Kind.SUCCESS:
+ pass
+ elif kind is CaseResult.Kind.SKIP:
+ assert skip_reason is not None
+ elif kind is CaseResult.Kind.EXPECTED_FAILURE:
+ assert traceback is not None
+ elif kind is CaseResult.Kind.UNEXPECTED_SUCCESS:
+ pass
+ else:
+ assert False
+ return super(cls, CaseResult).__new__(cls, id, name, kind, stdout,
+ stderr, skip_reason, traceback)
+
+ def updated(self,
+ name=None,
+ kind=None,
+ stdout=None,
+ stderr=None,
+ skip_reason=None,
+ traceback=None):
+ """Get a new validated CaseResult with the fields updated.
+
+ See this class' attributes for information on the arguments."""
+ name = self.name if name is None else name
+ kind = self.kind if kind is None else kind
+ stdout = self.stdout if stdout is None else stdout
+ stderr = self.stderr if stderr is None else stderr
+ skip_reason = self.skip_reason if skip_reason is None else skip_reason
+ traceback = self.traceback if traceback is None else traceback
return CaseResult(id=self.id,
name=name,
kind=kind,
@@ -113,288 +113,288 @@ class CaseResult(
stderr=stderr,
skip_reason=skip_reason,
traceback=traceback)
-
-
-class AugmentedResult(unittest.TestResult):
- """unittest.Result that keeps track of additional information.
-
- Uses CaseResult objects to store test-case results, providing additional
- information beyond that of the standard Python unittest library, such as
- standard output.
-
- Attributes:
- id_map (callable): A unary callable mapping unittest.TestCase objects to
- unique identifiers.
- cases (dict): A dictionary mapping from the identifiers returned by id_map
- to CaseResult objects corresponding to those IDs.
- """
-
- def __init__(self, id_map):
- """Initialize the object with an identifier mapping.
-
- Arguments:
- id_map (callable): Corresponds to the attribute `id_map`."""
- super(AugmentedResult, self).__init__()
- self.id_map = id_map
- self.cases = None
-
- def startTestRun(self):
- """See unittest.TestResult.startTestRun."""
- super(AugmentedResult, self).startTestRun()
- self.cases = dict()
-
- def startTest(self, test):
- """See unittest.TestResult.startTest."""
- super(AugmentedResult, self).startTest(test)
- case_id = self.id_map(test)
+
+
+class AugmentedResult(unittest.TestResult):
+ """unittest.Result that keeps track of additional information.
+
+ Uses CaseResult objects to store test-case results, providing additional
+ information beyond that of the standard Python unittest library, such as
+ standard output.
+
+ Attributes:
+ id_map (callable): A unary callable mapping unittest.TestCase objects to
+ unique identifiers.
+ cases (dict): A dictionary mapping from the identifiers returned by id_map
+ to CaseResult objects corresponding to those IDs.
+ """
+
+ def __init__(self, id_map):
+ """Initialize the object with an identifier mapping.
+
+ Arguments:
+ id_map (callable): Corresponds to the attribute `id_map`."""
+ super(AugmentedResult, self).__init__()
+ self.id_map = id_map
+ self.cases = None
+
+ def startTestRun(self):
+ """See unittest.TestResult.startTestRun."""
+ super(AugmentedResult, self).startTestRun()
+ self.cases = dict()
+
+ def startTest(self, test):
+ """See unittest.TestResult.startTest."""
+ super(AugmentedResult, self).startTest(test)
+ case_id = self.id_map(test)
self.cases[case_id] = CaseResult(id=case_id,
name=test.id(),
kind=CaseResult.Kind.RUNNING)
-
- def addError(self, test, err):
- """See unittest.TestResult.addError."""
- super(AugmentedResult, self).addError(test, err)
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- kind=CaseResult.Kind.ERROR, traceback=err)
-
- def addFailure(self, test, err):
- """See unittest.TestResult.addFailure."""
- super(AugmentedResult, self).addFailure(test, err)
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- kind=CaseResult.Kind.FAILURE, traceback=err)
-
- def addSuccess(self, test):
- """See unittest.TestResult.addSuccess."""
- super(AugmentedResult, self).addSuccess(test)
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- kind=CaseResult.Kind.SUCCESS)
-
- def addSkip(self, test, reason):
- """See unittest.TestResult.addSkip."""
- super(AugmentedResult, self).addSkip(test, reason)
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- kind=CaseResult.Kind.SKIP, skip_reason=reason)
-
- def addExpectedFailure(self, test, err):
- """See unittest.TestResult.addExpectedFailure."""
- super(AugmentedResult, self).addExpectedFailure(test, err)
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- kind=CaseResult.Kind.EXPECTED_FAILURE, traceback=err)
-
- def addUnexpectedSuccess(self, test):
- """See unittest.TestResult.addUnexpectedSuccess."""
- super(AugmentedResult, self).addUnexpectedSuccess(test)
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- kind=CaseResult.Kind.UNEXPECTED_SUCCESS)
-
- def set_output(self, test, stdout, stderr):
- """Set the output attributes for the CaseResult corresponding to a test.
-
- Args:
- test (unittest.TestCase): The TestCase to set the outputs of.
- stdout (str): Output from stdout to assign to self.id_map(test).
- stderr (str): Output from stderr to assign to self.id_map(test).
- """
- case_id = self.id_map(test)
- self.cases[case_id] = self.cases[case_id].updated(
- stdout=stdout.decode(), stderr=stderr.decode())
-
- def augmented_results(self, filter):
- """Convenience method to retrieve filtered case results.
-
- Args:
- filter (callable): A unary predicate to filter over CaseResult objects.
- """
- return (self.cases[case_id]
- for case_id in self.cases
- if filter(self.cases[case_id]))
-
-
-class CoverageResult(AugmentedResult):
- """Extension to AugmentedResult adding coverage.py support per test.\
-
- Attributes:
- coverage_context (coverage.Coverage): coverage.py management object.
- """
-
- def __init__(self, id_map):
- """See AugmentedResult.__init__."""
- super(CoverageResult, self).__init__(id_map=id_map)
- self.coverage_context = None
-
- def startTest(self, test):
- """See unittest.TestResult.startTest.
-
- Additionally initializes and begins code coverage tracking."""
- super(CoverageResult, self).startTest(test)
- self.coverage_context = coverage.Coverage(data_suffix=True)
- self.coverage_context.start()
-
- def stopTest(self, test):
- """See unittest.TestResult.stopTest.
-
- Additionally stops and deinitializes code coverage tracking."""
- super(CoverageResult, self).stopTest(test)
- self.coverage_context.stop()
- self.coverage_context.save()
- self.coverage_context = None
-
-
-class _Colors(object):
- """Namespaced constants for terminal color magic numbers."""
- HEADER = '\033[95m'
- INFO = '\033[94m'
- OK = '\033[92m'
- WARN = '\033[93m'
- FAIL = '\033[91m'
- BOLD = '\033[1m'
- UNDERLINE = '\033[4m'
- END = '\033[0m'
-
-
-class TerminalResult(CoverageResult):
- """Extension to CoverageResult adding basic terminal reporting."""
-
- def __init__(self, out, id_map):
- """Initialize the result object.
-
- Args:
- out (file-like): Output file to which terminal-colored live results will
- be written.
- id_map (callable): See AugmentedResult.__init__.
- """
- super(TerminalResult, self).__init__(id_map=id_map)
- self.out = out
-
- def startTestRun(self):
- """See unittest.TestResult.startTestRun."""
- super(TerminalResult, self).startTestRun()
+
+ def addError(self, test, err):
+ """See unittest.TestResult.addError."""
+ super(AugmentedResult, self).addError(test, err)
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ kind=CaseResult.Kind.ERROR, traceback=err)
+
+ def addFailure(self, test, err):
+ """See unittest.TestResult.addFailure."""
+ super(AugmentedResult, self).addFailure(test, err)
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ kind=CaseResult.Kind.FAILURE, traceback=err)
+
+ def addSuccess(self, test):
+ """See unittest.TestResult.addSuccess."""
+ super(AugmentedResult, self).addSuccess(test)
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ kind=CaseResult.Kind.SUCCESS)
+
+ def addSkip(self, test, reason):
+ """See unittest.TestResult.addSkip."""
+ super(AugmentedResult, self).addSkip(test, reason)
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ kind=CaseResult.Kind.SKIP, skip_reason=reason)
+
+ def addExpectedFailure(self, test, err):
+ """See unittest.TestResult.addExpectedFailure."""
+ super(AugmentedResult, self).addExpectedFailure(test, err)
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ kind=CaseResult.Kind.EXPECTED_FAILURE, traceback=err)
+
+ def addUnexpectedSuccess(self, test):
+ """See unittest.TestResult.addUnexpectedSuccess."""
+ super(AugmentedResult, self).addUnexpectedSuccess(test)
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ kind=CaseResult.Kind.UNEXPECTED_SUCCESS)
+
+ def set_output(self, test, stdout, stderr):
+ """Set the output attributes for the CaseResult corresponding to a test.
+
+ Args:
+ test (unittest.TestCase): The TestCase to set the outputs of.
+ stdout (str): Output from stdout to assign to self.id_map(test).
+ stderr (str): Output from stderr to assign to self.id_map(test).
+ """
+ case_id = self.id_map(test)
+ self.cases[case_id] = self.cases[case_id].updated(
+ stdout=stdout.decode(), stderr=stderr.decode())
+
+ def augmented_results(self, filter):
+ """Convenience method to retrieve filtered case results.
+
+ Args:
+ filter (callable): A unary predicate to filter over CaseResult objects.
+ """
+ return (self.cases[case_id]
+ for case_id in self.cases
+ if filter(self.cases[case_id]))
+
+
+class CoverageResult(AugmentedResult):
+ """Extension to AugmentedResult adding coverage.py support per test.\
+
+ Attributes:
+ coverage_context (coverage.Coverage): coverage.py management object.
+ """
+
+ def __init__(self, id_map):
+ """See AugmentedResult.__init__."""
+ super(CoverageResult, self).__init__(id_map=id_map)
+ self.coverage_context = None
+
+ def startTest(self, test):
+ """See unittest.TestResult.startTest.
+
+ Additionally initializes and begins code coverage tracking."""
+ super(CoverageResult, self).startTest(test)
+ self.coverage_context = coverage.Coverage(data_suffix=True)
+ self.coverage_context.start()
+
+ def stopTest(self, test):
+ """See unittest.TestResult.stopTest.
+
+ Additionally stops and deinitializes code coverage tracking."""
+ super(CoverageResult, self).stopTest(test)
+ self.coverage_context.stop()
+ self.coverage_context.save()
+ self.coverage_context = None
+
+
+class _Colors(object):
+ """Namespaced constants for terminal color magic numbers."""
+ HEADER = '\033[95m'
+ INFO = '\033[94m'
+ OK = '\033[92m'
+ WARN = '\033[93m'
+ FAIL = '\033[91m'
+ BOLD = '\033[1m'
+ UNDERLINE = '\033[4m'
+ END = '\033[0m'
+
+
+class TerminalResult(CoverageResult):
+ """Extension to CoverageResult adding basic terminal reporting."""
+
+ def __init__(self, out, id_map):
+ """Initialize the result object.
+
+ Args:
+ out (file-like): Output file to which terminal-colored live results will
+ be written.
+ id_map (callable): See AugmentedResult.__init__.
+ """
+ super(TerminalResult, self).__init__(id_map=id_map)
+ self.out = out
+
+ def startTestRun(self):
+ """See unittest.TestResult.startTestRun."""
+ super(TerminalResult, self).startTestRun()
self.out.write(_Colors.HEADER + 'Testing gRPC Python...\n' +
_Colors.END)
-
- def stopTestRun(self):
- """See unittest.TestResult.stopTestRun."""
- super(TerminalResult, self).stopTestRun()
- self.out.write(summary(self))
- self.out.flush()
-
- def addError(self, test, err):
- """See unittest.TestResult.addError."""
- super(TerminalResult, self).addError(test, err)
+
+ def stopTestRun(self):
+ """See unittest.TestResult.stopTestRun."""
+ super(TerminalResult, self).stopTestRun()
+ self.out.write(summary(self))
+ self.out.flush()
+
+ def addError(self, test, err):
+ """See unittest.TestResult.addError."""
+ super(TerminalResult, self).addError(test, err)
self.out.write(_Colors.FAIL + 'ERROR {}\n'.format(test.id()) +
_Colors.END)
- self.out.flush()
-
- def addFailure(self, test, err):
- """See unittest.TestResult.addFailure."""
- super(TerminalResult, self).addFailure(test, err)
+ self.out.flush()
+
+ def addFailure(self, test, err):
+ """See unittest.TestResult.addFailure."""
+ super(TerminalResult, self).addFailure(test, err)
self.out.write(_Colors.FAIL + 'FAILURE {}\n'.format(test.id()) +
_Colors.END)
- self.out.flush()
-
- def addSuccess(self, test):
- """See unittest.TestResult.addSuccess."""
- super(TerminalResult, self).addSuccess(test)
+ self.out.flush()
+
+ def addSuccess(self, test):
+ """See unittest.TestResult.addSuccess."""
+ super(TerminalResult, self).addSuccess(test)
self.out.write(_Colors.OK + 'SUCCESS {}\n'.format(test.id()) +
_Colors.END)
- self.out.flush()
-
- def addSkip(self, test, reason):
- """See unittest.TestResult.addSkip."""
- super(TerminalResult, self).addSkip(test, reason)
+ self.out.flush()
+
+ def addSkip(self, test, reason):
+ """See unittest.TestResult.addSkip."""
+ super(TerminalResult, self).addSkip(test, reason)
self.out.write(_Colors.INFO + 'SKIP {}\n'.format(test.id()) +
_Colors.END)
- self.out.flush()
-
- def addExpectedFailure(self, test, err):
- """See unittest.TestResult.addExpectedFailure."""
- super(TerminalResult, self).addExpectedFailure(test, err)
+ self.out.flush()
+
+ def addExpectedFailure(self, test, err):
+ """See unittest.TestResult.addExpectedFailure."""
+ super(TerminalResult, self).addExpectedFailure(test, err)
self.out.write(_Colors.INFO + 'FAILURE_OK {}\n'.format(test.id()) +
_Colors.END)
- self.out.flush()
-
- def addUnexpectedSuccess(self, test):
- """See unittest.TestResult.addUnexpectedSuccess."""
- super(TerminalResult, self).addUnexpectedSuccess(test)
+ self.out.flush()
+
+ def addUnexpectedSuccess(self, test):
+ """See unittest.TestResult.addUnexpectedSuccess."""
+ super(TerminalResult, self).addUnexpectedSuccess(test)
self.out.write(_Colors.INFO + 'UNEXPECTED_OK {}\n'.format(test.id()) +
_Colors.END)
- self.out.flush()
-
-
-def _traceback_string(type, value, trace):
- """Generate a descriptive string of a Python exception traceback.
-
- Args:
- type (class): The type of the exception.
- value (Exception): The value of the exception.
- trace (traceback): Traceback of the exception.
-
- Returns:
- str: Formatted exception descriptive string.
- """
- buffer = moves.cStringIO()
- traceback.print_exception(type, value, trace, file=buffer)
- return buffer.getvalue()
-
-
-def summary(result):
- """A summary string of a result object.
-
- Args:
- result (AugmentedResult): The result object to get the summary of.
-
- Returns:
- str: The summary string.
- """
- assert isinstance(result, AugmentedResult)
- untested = list(
- result.augmented_results(
- lambda case_result: case_result.kind is CaseResult.Kind.UNTESTED))
- running = list(
- result.augmented_results(
- lambda case_result: case_result.kind is CaseResult.Kind.RUNNING))
- failures = list(
- result.augmented_results(
- lambda case_result: case_result.kind is CaseResult.Kind.FAILURE))
- errors = list(
- result.augmented_results(
- lambda case_result: case_result.kind is CaseResult.Kind.ERROR))
- successes = list(
- result.augmented_results(
- lambda case_result: case_result.kind is CaseResult.Kind.SUCCESS))
- skips = list(
- result.augmented_results(
- lambda case_result: case_result.kind is CaseResult.Kind.SKIP))
- expected_failures = list(
+ self.out.flush()
+
+
+def _traceback_string(type, value, trace):
+ """Generate a descriptive string of a Python exception traceback.
+
+ Args:
+ type (class): The type of the exception.
+ value (Exception): The value of the exception.
+ trace (traceback): Traceback of the exception.
+
+ Returns:
+ str: Formatted exception descriptive string.
+ """
+ buffer = moves.cStringIO()
+ traceback.print_exception(type, value, trace, file=buffer)
+ return buffer.getvalue()
+
+
+def summary(result):
+ """A summary string of a result object.
+
+ Args:
+ result (AugmentedResult): The result object to get the summary of.
+
+ Returns:
+ str: The summary string.
+ """
+ assert isinstance(result, AugmentedResult)
+ untested = list(
+ result.augmented_results(
+ lambda case_result: case_result.kind is CaseResult.Kind.UNTESTED))
+ running = list(
+ result.augmented_results(
+ lambda case_result: case_result.kind is CaseResult.Kind.RUNNING))
+ failures = list(
+ result.augmented_results(
+ lambda case_result: case_result.kind is CaseResult.Kind.FAILURE))
+ errors = list(
+ result.augmented_results(
+ lambda case_result: case_result.kind is CaseResult.Kind.ERROR))
+ successes = list(
+ result.augmented_results(
+ lambda case_result: case_result.kind is CaseResult.Kind.SUCCESS))
+ skips = list(
+ result.augmented_results(
+ lambda case_result: case_result.kind is CaseResult.Kind.SKIP))
+ expected_failures = list(
result.augmented_results(lambda case_result: case_result.kind is
CaseResult.Kind.EXPECTED_FAILURE))
- unexpected_successes = list(
+ unexpected_successes = list(
result.augmented_results(lambda case_result: case_result.kind is
CaseResult.Kind.UNEXPECTED_SUCCESS))
- running_names = [case.name for case in running]
- finished_count = (len(failures) + len(errors) + len(successes) +
- len(expected_failures) + len(unexpected_successes))
- statistics = ('{finished} tests finished:\n'
- '\t{successful} successful\n'
- '\t{unsuccessful} unsuccessful\n'
- '\t{skipped} skipped\n'
- '\t{expected_fail} expected failures\n'
- '\t{unexpected_successful} unexpected successes\n'
- 'Interrupted Tests:\n'
- '\t{interrupted}\n'.format(
- finished=finished_count,
- successful=len(successes),
- unsuccessful=(len(failures) + len(errors)),
- skipped=len(skips),
- expected_fail=len(expected_failures),
- unexpected_successful=len(unexpected_successes),
- interrupted=str(running_names)))
+ running_names = [case.name for case in running]
+ finished_count = (len(failures) + len(errors) + len(successes) +
+ len(expected_failures) + len(unexpected_successes))
+ statistics = ('{finished} tests finished:\n'
+ '\t{successful} successful\n'
+ '\t{unsuccessful} unsuccessful\n'
+ '\t{skipped} skipped\n'
+ '\t{expected_fail} expected failures\n'
+ '\t{unexpected_successful} unexpected successes\n'
+ 'Interrupted Tests:\n'
+ '\t{interrupted}\n'.format(
+ finished=finished_count,
+ successful=len(successes),
+ unsuccessful=(len(failures) + len(errors)),
+ skipped=len(skips),
+ expected_fail=len(expected_failures),
+ unexpected_successful=len(unexpected_successes),
+ interrupted=str(running_names)))
tracebacks = '\n\n'.join([
(_Colors.FAIL + '{test_name}' + _Colors.END + '\n' + _Colors.BOLD +
'traceback:' + _Colors.END + '\n' + '{traceback}\n' + _Colors.BOLD +
@@ -406,34 +406,34 @@ def summary(result):
stderr=result.stderr)
for result in itertools.chain(failures, errors)
])
- notes = 'Unexpected successes: {}\n'.format(
- [result.name for result in unexpected_successes])
- return statistics + '\nErrors/Failures: \n' + tracebacks + '\n' + notes
-
-
-def jenkins_junit_xml(result):
- """An XML tree object that when written is recognizable by Jenkins.
-
- Args:
- result (AugmentedResult): The result object to get the junit xml output of.
-
- Returns:
- ElementTree.ElementTree: The XML tree.
- """
- assert isinstance(result, AugmentedResult)
- root = ElementTree.Element('testsuites')
- suite = ElementTree.SubElement(root, 'testsuite', {
- 'name': 'Python gRPC tests',
- })
- for case in result.cases.values():
- if case.kind is CaseResult.Kind.SUCCESS:
- ElementTree.SubElement(suite, 'testcase', {
- 'name': case.name,
- })
- elif case.kind in (CaseResult.Kind.ERROR, CaseResult.Kind.FAILURE):
- case_xml = ElementTree.SubElement(suite, 'testcase', {
- 'name': case.name,
- })
- error_xml = ElementTree.SubElement(case_xml, 'error', {})
- error_xml.text = ''.format(case.stderr, case.traceback)
- return ElementTree.ElementTree(element=root)
+ notes = 'Unexpected successes: {}\n'.format(
+ [result.name for result in unexpected_successes])
+ return statistics + '\nErrors/Failures: \n' + tracebacks + '\n' + notes
+
+
+def jenkins_junit_xml(result):
+ """An XML tree object that when written is recognizable by Jenkins.
+
+ Args:
+ result (AugmentedResult): The result object to get the junit xml output of.
+
+ Returns:
+ ElementTree.ElementTree: The XML tree.
+ """
+ assert isinstance(result, AugmentedResult)
+ root = ElementTree.Element('testsuites')
+ suite = ElementTree.SubElement(root, 'testsuite', {
+ 'name': 'Python gRPC tests',
+ })
+ for case in result.cases.values():
+ if case.kind is CaseResult.Kind.SUCCESS:
+ ElementTree.SubElement(suite, 'testcase', {
+ 'name': case.name,
+ })
+ elif case.kind in (CaseResult.Kind.ERROR, CaseResult.Kind.FAILURE):
+ case_xml = ElementTree.SubElement(suite, 'testcase', {
+ 'name': case.name,
+ })
+ error_xml = ElementTree.SubElement(case_xml, 'error', {})
+ error_xml.text = ''.format(case.stderr, case.traceback)
+ return ElementTree.ElementTree(element=root)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/_runner.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/_runner.py
index 39da0399b0..7b1546a46c 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/_runner.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/_runner.py
@@ -1,239 +1,239 @@
-# Copyright 2015 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.
-
-from __future__ import absolute_import
-
-import collections
-import os
-import select
-import signal
-import sys
-import tempfile
-import threading
-import time
-import unittest
-import uuid
-
-import six
-from six import moves
-
-from tests import _loader
-from tests import _result
-
-
-class CaptureFile(object):
- """A context-managed file to redirect output to a byte array.
-
- Use by invoking `start` (`__enter__`) and at some point invoking `stop`
- (`__exit__`). At any point after the initial call to `start` call `output` to
- get the current redirected output. Note that we don't currently use file
- locking, so calling `output` between calls to `start` and `stop` may muddle
- the result (you should only be doing this during a Python-handled interrupt as
- a last ditch effort to provide output to the user).
-
- Attributes:
- _redirected_fd (int): File descriptor of file to redirect writes from.
- _saved_fd (int): A copy of the original value of the redirected file
- descriptor.
- _into_file (TemporaryFile or None): File to which writes are redirected.
- Only non-None when self is started.
- """
-
- def __init__(self, fd):
- self._redirected_fd = fd
- self._saved_fd = os.dup(self._redirected_fd)
- self._into_file = None
-
- def output(self):
- """Get all output from the redirected-to file if it exists."""
- if self._into_file:
- self._into_file.seek(0)
- return bytes(self._into_file.read())
- else:
- return bytes()
-
- def start(self):
- """Start redirection of writes to the file descriptor."""
- self._into_file = tempfile.TemporaryFile()
- os.dup2(self._into_file.fileno(), self._redirected_fd)
-
- def stop(self):
- """Stop redirection of writes to the file descriptor."""
- # n.b. this dup2 call auto-closes self._redirected_fd
- os.dup2(self._saved_fd, self._redirected_fd)
-
- def write_bypass(self, value):
- """Bypass the redirection and write directly to the original file.
-
- Arguments:
- value (str): What to write to the original file.
- """
- if six.PY3 and not isinstance(value, six.binary_type):
- value = bytes(value, 'ascii')
- if self._saved_fd is None:
- os.write(self._redirect_fd, value)
- else:
- os.write(self._saved_fd, value)
-
- def __enter__(self):
- self.start()
- return self
-
- def __exit__(self, type, value, traceback):
- self.stop()
-
- def close(self):
- """Close any resources used by self not closed by stop()."""
- os.close(self._saved_fd)
-
-
-class AugmentedCase(collections.namedtuple('AugmentedCase', ['case', 'id'])):
- """A test case with a guaranteed unique externally specified identifier.
-
- Attributes:
- case (unittest.TestCase): TestCase we're decorating with an additional
- identifier.
- id (object): Any identifier that may be considered 'unique' for testing
- purposes.
- """
-
- def __new__(cls, case, id=None):
- if id is None:
- id = uuid.uuid4()
- return super(cls, AugmentedCase).__new__(cls, case, id)
-
-
+# Copyright 2015 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.
+
+from __future__ import absolute_import
+
+import collections
+import os
+import select
+import signal
+import sys
+import tempfile
+import threading
+import time
+import unittest
+import uuid
+
+import six
+from six import moves
+
+from tests import _loader
+from tests import _result
+
+
+class CaptureFile(object):
+ """A context-managed file to redirect output to a byte array.
+
+ Use by invoking `start` (`__enter__`) and at some point invoking `stop`
+ (`__exit__`). At any point after the initial call to `start` call `output` to
+ get the current redirected output. Note that we don't currently use file
+ locking, so calling `output` between calls to `start` and `stop` may muddle
+ the result (you should only be doing this during a Python-handled interrupt as
+ a last ditch effort to provide output to the user).
+
+ Attributes:
+ _redirected_fd (int): File descriptor of file to redirect writes from.
+ _saved_fd (int): A copy of the original value of the redirected file
+ descriptor.
+ _into_file (TemporaryFile or None): File to which writes are redirected.
+ Only non-None when self is started.
+ """
+
+ def __init__(self, fd):
+ self._redirected_fd = fd
+ self._saved_fd = os.dup(self._redirected_fd)
+ self._into_file = None
+
+ def output(self):
+ """Get all output from the redirected-to file if it exists."""
+ if self._into_file:
+ self._into_file.seek(0)
+ return bytes(self._into_file.read())
+ else:
+ return bytes()
+
+ def start(self):
+ """Start redirection of writes to the file descriptor."""
+ self._into_file = tempfile.TemporaryFile()
+ os.dup2(self._into_file.fileno(), self._redirected_fd)
+
+ def stop(self):
+ """Stop redirection of writes to the file descriptor."""
+ # n.b. this dup2 call auto-closes self._redirected_fd
+ os.dup2(self._saved_fd, self._redirected_fd)
+
+ def write_bypass(self, value):
+ """Bypass the redirection and write directly to the original file.
+
+ Arguments:
+ value (str): What to write to the original file.
+ """
+ if six.PY3 and not isinstance(value, six.binary_type):
+ value = bytes(value, 'ascii')
+ if self._saved_fd is None:
+ os.write(self._redirect_fd, value)
+ else:
+ os.write(self._saved_fd, value)
+
+ def __enter__(self):
+ self.start()
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.stop()
+
+ def close(self):
+ """Close any resources used by self not closed by stop()."""
+ os.close(self._saved_fd)
+
+
+class AugmentedCase(collections.namedtuple('AugmentedCase', ['case', 'id'])):
+ """A test case with a guaranteed unique externally specified identifier.
+
+ Attributes:
+ case (unittest.TestCase): TestCase we're decorating with an additional
+ identifier.
+ id (object): Any identifier that may be considered 'unique' for testing
+ purposes.
+ """
+
+ def __new__(cls, case, id=None):
+ if id is None:
+ id = uuid.uuid4()
+ return super(cls, AugmentedCase).__new__(cls, case, id)
+
+
# NOTE(lidiz) This complex wrapper is not triggering setUpClass nor
# tearDownClass. Do not use those methods, or fix this wrapper!
-class Runner(object):
-
- def __init__(self, dedicated_threads=False):
- """Constructs the Runner object.
-
- Args:
- dedicated_threads: A bool indicates whether to spawn each unit test
- in separate thread or not.
- """
- self._skipped_tests = []
- self._dedicated_threads = dedicated_threads
-
- def skip_tests(self, tests):
- self._skipped_tests = tests
-
- def run(self, suite):
- """See setuptools' test_runner setup argument for information."""
- # only run test cases with id starting with given prefix
- testcase_filter = os.getenv('GRPC_PYTHON_TESTRUNNER_FILTER')
- filtered_cases = []
- for case in _loader.iterate_suite_cases(suite):
- if not testcase_filter or case.id().startswith(testcase_filter):
- filtered_cases.append(case)
-
- # Ensure that every test case has no collision with any other test case in
- # the augmented results.
- augmented_cases = [
- AugmentedCase(case, uuid.uuid4()) for case in filtered_cases
- ]
- case_id_by_case = dict((augmented_case.case, augmented_case.id)
- for augmented_case in augmented_cases)
- result_out = moves.cStringIO()
- result = _result.TerminalResult(
- result_out, id_map=lambda case: case_id_by_case[case])
- stdout_pipe = CaptureFile(sys.stdout.fileno())
- stderr_pipe = CaptureFile(sys.stderr.fileno())
- kill_flag = [False]
-
- def sigint_handler(signal_number, frame):
- if signal_number == signal.SIGINT:
- kill_flag[0] = True # Python 2.7 not having 'local'... :-(
- signal.signal(signal_number, signal.SIG_DFL)
-
- def fault_handler(signal_number, frame):
- stdout_pipe.write_bypass(
- 'Received fault signal {}\nstdout:\n{}\n\nstderr:{}\n'.format(
- signal_number, stdout_pipe.output(), stderr_pipe.output()))
- os._exit(1)
-
- def check_kill_self():
- if kill_flag[0]:
- stdout_pipe.write_bypass('Stopping tests short...')
- result.stopTestRun()
- stdout_pipe.write_bypass(result_out.getvalue())
- stdout_pipe.write_bypass('\ninterrupted stdout:\n{}\n'.format(
- stdout_pipe.output().decode()))
- stderr_pipe.write_bypass('\ninterrupted stderr:\n{}\n'.format(
- stderr_pipe.output().decode()))
- os._exit(1)
-
- def try_set_handler(name, handler):
- try:
- signal.signal(getattr(signal, name), handler)
- except AttributeError:
- pass
-
- try_set_handler('SIGINT', sigint_handler)
- try_set_handler('SIGBUS', fault_handler)
- try_set_handler('SIGABRT', fault_handler)
- try_set_handler('SIGFPE', fault_handler)
- try_set_handler('SIGILL', fault_handler)
- # Sometimes output will lag after a test has successfully finished; we
- # ignore such writes to our pipes.
- try_set_handler('SIGPIPE', signal.SIG_IGN)
-
- # Run the tests
- result.startTestRun()
- for augmented_case in augmented_cases:
- for skipped_test in self._skipped_tests:
- if skipped_test in augmented_case.case.id():
- break
- else:
- sys.stdout.write('Running {}\n'.format(
- augmented_case.case.id()))
- sys.stdout.flush()
- if self._dedicated_threads:
- # (Deprecated) Spawns dedicated thread for each test case.
- case_thread = threading.Thread(
- target=augmented_case.case.run, args=(result,))
- try:
- with stdout_pipe, stderr_pipe:
- case_thread.start()
- # If the thread is exited unexpected, stop testing.
- while case_thread.is_alive():
- check_kill_self()
- time.sleep(0)
- case_thread.join()
- except: # pylint: disable=try-except-raise
- # re-raise the exception after forcing the with-block to end
- raise
- # Records the result of the test case run.
- result.set_output(augmented_case.case, stdout_pipe.output(),
- stderr_pipe.output())
- sys.stdout.write(result_out.getvalue())
- sys.stdout.flush()
- result_out.truncate(0)
- check_kill_self()
- else:
- # Donates current thread to test case execution.
- augmented_case.case.run(result)
- result.stopTestRun()
- stdout_pipe.close()
- stderr_pipe.close()
-
- # Report results
- sys.stdout.write(result_out.getvalue())
- sys.stdout.flush()
- signal.signal(signal.SIGINT, signal.SIG_DFL)
- with open('report.xml', 'wb') as report_xml_file:
- _result.jenkins_junit_xml(result).write(report_xml_file)
- return result
+class Runner(object):
+
+ def __init__(self, dedicated_threads=False):
+ """Constructs the Runner object.
+
+ Args:
+ dedicated_threads: A bool indicates whether to spawn each unit test
+ in separate thread or not.
+ """
+ self._skipped_tests = []
+ self._dedicated_threads = dedicated_threads
+
+ def skip_tests(self, tests):
+ self._skipped_tests = tests
+
+ def run(self, suite):
+ """See setuptools' test_runner setup argument for information."""
+ # only run test cases with id starting with given prefix
+ testcase_filter = os.getenv('GRPC_PYTHON_TESTRUNNER_FILTER')
+ filtered_cases = []
+ for case in _loader.iterate_suite_cases(suite):
+ if not testcase_filter or case.id().startswith(testcase_filter):
+ filtered_cases.append(case)
+
+ # Ensure that every test case has no collision with any other test case in
+ # the augmented results.
+ augmented_cases = [
+ AugmentedCase(case, uuid.uuid4()) for case in filtered_cases
+ ]
+ case_id_by_case = dict((augmented_case.case, augmented_case.id)
+ for augmented_case in augmented_cases)
+ result_out = moves.cStringIO()
+ result = _result.TerminalResult(
+ result_out, id_map=lambda case: case_id_by_case[case])
+ stdout_pipe = CaptureFile(sys.stdout.fileno())
+ stderr_pipe = CaptureFile(sys.stderr.fileno())
+ kill_flag = [False]
+
+ def sigint_handler(signal_number, frame):
+ if signal_number == signal.SIGINT:
+ kill_flag[0] = True # Python 2.7 not having 'local'... :-(
+ signal.signal(signal_number, signal.SIG_DFL)
+
+ def fault_handler(signal_number, frame):
+ stdout_pipe.write_bypass(
+ 'Received fault signal {}\nstdout:\n{}\n\nstderr:{}\n'.format(
+ signal_number, stdout_pipe.output(), stderr_pipe.output()))
+ os._exit(1)
+
+ def check_kill_self():
+ if kill_flag[0]:
+ stdout_pipe.write_bypass('Stopping tests short...')
+ result.stopTestRun()
+ stdout_pipe.write_bypass(result_out.getvalue())
+ stdout_pipe.write_bypass('\ninterrupted stdout:\n{}\n'.format(
+ stdout_pipe.output().decode()))
+ stderr_pipe.write_bypass('\ninterrupted stderr:\n{}\n'.format(
+ stderr_pipe.output().decode()))
+ os._exit(1)
+
+ def try_set_handler(name, handler):
+ try:
+ signal.signal(getattr(signal, name), handler)
+ except AttributeError:
+ pass
+
+ try_set_handler('SIGINT', sigint_handler)
+ try_set_handler('SIGBUS', fault_handler)
+ try_set_handler('SIGABRT', fault_handler)
+ try_set_handler('SIGFPE', fault_handler)
+ try_set_handler('SIGILL', fault_handler)
+ # Sometimes output will lag after a test has successfully finished; we
+ # ignore such writes to our pipes.
+ try_set_handler('SIGPIPE', signal.SIG_IGN)
+
+ # Run the tests
+ result.startTestRun()
+ for augmented_case in augmented_cases:
+ for skipped_test in self._skipped_tests:
+ if skipped_test in augmented_case.case.id():
+ break
+ else:
+ sys.stdout.write('Running {}\n'.format(
+ augmented_case.case.id()))
+ sys.stdout.flush()
+ if self._dedicated_threads:
+ # (Deprecated) Spawns dedicated thread for each test case.
+ case_thread = threading.Thread(
+ target=augmented_case.case.run, args=(result,))
+ try:
+ with stdout_pipe, stderr_pipe:
+ case_thread.start()
+ # If the thread is exited unexpected, stop testing.
+ while case_thread.is_alive():
+ check_kill_self()
+ time.sleep(0)
+ case_thread.join()
+ except: # pylint: disable=try-except-raise
+ # re-raise the exception after forcing the with-block to end
+ raise
+ # Records the result of the test case run.
+ result.set_output(augmented_case.case, stdout_pipe.output(),
+ stderr_pipe.output())
+ sys.stdout.write(result_out.getvalue())
+ sys.stdout.flush()
+ result_out.truncate(0)
+ check_kill_self()
+ else:
+ # Donates current thread to test case execution.
+ augmented_case.case.run(result)
+ result.stopTestRun()
+ stdout_pipe.close()
+ stderr_pipe.close()
+
+ # Report results
+ sys.stdout.write(result_out.getvalue())
+ sys.stdout.flush()
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
+ with open('report.xml', 'wb') as report_xml_file:
+ _result.jenkins_junit_xml(result).write(report_xml_file)
+ return result
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/__init__.py
index 5772620b60..8d89990e82 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 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.
+# Copyright 2016 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/_sanity_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/_sanity_test.py
index 3aa92f37fb..0cd18af931 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/_sanity_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/_sanity/_sanity_test.py
@@ -1,48 +1,48 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import json
-import pkgutil
-import unittest
-
-import six
-
-import tests
-
-
-class SanityTest(unittest.TestCase):
-
- maxDiff = 32768
-
- TEST_PKG_MODULE_NAME = 'tests'
- TEST_PKG_PATH = 'tests'
-
- def testTestsJsonUpToDate(self):
- """Autodiscovers all test suites and checks that tests.json is up to date"""
- loader = tests.Loader()
- loader.loadTestsFromNames([self.TEST_PKG_MODULE_NAME])
- test_suite_names = sorted({
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import pkgutil
+import unittest
+
+import six
+
+import tests
+
+
+class SanityTest(unittest.TestCase):
+
+ maxDiff = 32768
+
+ TEST_PKG_MODULE_NAME = 'tests'
+ TEST_PKG_PATH = 'tests'
+
+ def testTestsJsonUpToDate(self):
+ """Autodiscovers all test suites and checks that tests.json is up to date"""
+ loader = tests.Loader()
+ loader.loadTestsFromNames([self.TEST_PKG_MODULE_NAME])
+ test_suite_names = sorted({
test_case_class.id().rsplit('.', 1)[0] for test_case_class in
tests._loader.iterate_suite_cases(loader.suite)
- })
-
- tests_json_string = pkgutil.get_data(self.TEST_PKG_PATH, 'tests.json')
+ })
+
+ tests_json_string = pkgutil.get_data(self.TEST_PKG_PATH, 'tests.json')
tests_json = json.loads(
tests_json_string.decode() if six.PY3 else tests_json_string)
-
- self.assertSequenceEqual(tests_json, test_suite_names)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+
+ self.assertSequenceEqual(tests_json, test_suite_names)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/bazel_namespace_package_hack.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/bazel_namespace_package_hack.py
index 994a8e1e80..d0a646536a 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/bazel_namespace_package_hack.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/bazel_namespace_package_hack.py
@@ -1,40 +1,40 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import os
-import site
-import sys
-
-_GRPC_BAZEL_RUNTIME_ENV = "GRPC_BAZEL_RUNTIME"
-
-
-# TODO(https://github.com/bazelbuild/bazel/issues/6844) Bazel failed to
-# interpret namespace packages correctly. This monkey patch will force the
-# Python process to parse the .pth file in the sys.path to resolve namespace
-# package in the right place.
-# Analysis in depth: https://github.com/bazelbuild/rules_python/issues/55
-def sys_path_to_site_dir_hack():
- """Add valid sys.path item to site directory to parse the .pth files."""
- # Only run within our Bazel environment
- if not os.environ.get(_GRPC_BAZEL_RUNTIME_ENV):
- return
- items = []
- for item in sys.path:
- if os.path.exists(item):
- # The only difference between sys.path and site-directory is
- # whether the .pth file will be parsed or not. A site-directory
- # will always exist in sys.path, but not another way around.
- items.append(item)
- for item in items:
- site.addsitedir(item)
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import site
+import sys
+
+_GRPC_BAZEL_RUNTIME_ENV = "GRPC_BAZEL_RUNTIME"
+
+
+# TODO(https://github.com/bazelbuild/bazel/issues/6844) Bazel failed to
+# interpret namespace packages correctly. This monkey patch will force the
+# Python process to parse the .pth file in the sys.path to resolve namespace
+# package in the right place.
+# Analysis in depth: https://github.com/bazelbuild/rules_python/issues/55
+def sys_path_to_site_dir_hack():
+ """Add valid sys.path item to site directory to parse the .pth files."""
+ # Only run within our Bazel environment
+ if not os.environ.get(_GRPC_BAZEL_RUNTIME_ENV):
+ return
+ items = []
+ for item in sys.path:
+ if os.path.exists(item):
+ # The only difference between sys.path and site-directory is
+ # whether the .pth file will be parsed or not. A site-directory
+ # will always exist in sys.path, but not another way around.
+ items.append(item)
+ for item in items:
+ site.addsitedir(item)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/__init__.py
index 38fdfc9c5c..10b401503b 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2018 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Copyright 2018 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/_channelz_servicer_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/_channelz_servicer_test.py
index 784307ae00..ccbe40df84 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/_channelz_servicer_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/channelz/_channelz_servicer_test.py
@@ -1,469 +1,469 @@
-# Copyright 2018 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of grpc_channelz.v1.channelz."""
-
-import unittest
-
-from concurrent import futures
-
-import grpc
-
-from grpc_channelz.v1 import channelz
-from grpc_channelz.v1 import channelz_pb2
-from grpc_channelz.v1 import channelz_pb2_grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_SUCCESSFUL_UNARY_UNARY = '/test/SuccessfulUnaryUnary'
-_FAILED_UNARY_UNARY = '/test/FailedUnaryUnary'
-_SUCCESSFUL_STREAM_STREAM = '/test/SuccessfulStreamStream'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x01\x01\x01'
-
-_DISABLE_REUSE_PORT = (('grpc.so_reuseport', 0),)
-_ENABLE_CHANNELZ = (('grpc.enable_channelz', 1),)
-_DISABLE_CHANNELZ = (('grpc.enable_channelz', 0),)
-
-
-def _successful_unary_unary(request, servicer_context):
- return _RESPONSE
-
-
-def _failed_unary_unary(request, servicer_context):
- servicer_context.set_code(grpc.StatusCode.INTERNAL)
- servicer_context.set_details("Channelz Test Intended Failure")
-
-
-def _successful_stream_stream(request_iterator, servicer_context):
- for _ in request_iterator:
- yield _RESPONSE
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _SUCCESSFUL_UNARY_UNARY:
- return grpc.unary_unary_rpc_method_handler(_successful_unary_unary)
- elif handler_call_details.method == _FAILED_UNARY_UNARY:
- return grpc.unary_unary_rpc_method_handler(_failed_unary_unary)
- elif handler_call_details.method == _SUCCESSFUL_STREAM_STREAM:
- return grpc.stream_stream_rpc_method_handler(
- _successful_stream_stream)
- else:
- return None
-
-
-class _ChannelServerPair(object):
-
- def __init__(self):
- # Server will enable channelz service
+# Copyright 2018 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests of grpc_channelz.v1.channelz."""
+
+import unittest
+
+from concurrent import futures
+
+import grpc
+
+from grpc_channelz.v1 import channelz
+from grpc_channelz.v1 import channelz_pb2
+from grpc_channelz.v1 import channelz_pb2_grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_SUCCESSFUL_UNARY_UNARY = '/test/SuccessfulUnaryUnary'
+_FAILED_UNARY_UNARY = '/test/FailedUnaryUnary'
+_SUCCESSFUL_STREAM_STREAM = '/test/SuccessfulStreamStream'
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x01\x01\x01'
+
+_DISABLE_REUSE_PORT = (('grpc.so_reuseport', 0),)
+_ENABLE_CHANNELZ = (('grpc.enable_channelz', 1),)
+_DISABLE_CHANNELZ = (('grpc.enable_channelz', 0),)
+
+
+def _successful_unary_unary(request, servicer_context):
+ return _RESPONSE
+
+
+def _failed_unary_unary(request, servicer_context):
+ servicer_context.set_code(grpc.StatusCode.INTERNAL)
+ servicer_context.set_details("Channelz Test Intended Failure")
+
+
+def _successful_stream_stream(request_iterator, servicer_context):
+ for _ in request_iterator:
+ yield _RESPONSE
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _SUCCESSFUL_UNARY_UNARY:
+ return grpc.unary_unary_rpc_method_handler(_successful_unary_unary)
+ elif handler_call_details.method == _FAILED_UNARY_UNARY:
+ return grpc.unary_unary_rpc_method_handler(_failed_unary_unary)
+ elif handler_call_details.method == _SUCCESSFUL_STREAM_STREAM:
+ return grpc.stream_stream_rpc_method_handler(
+ _successful_stream_stream)
+ else:
+ return None
+
+
+class _ChannelServerPair(object):
+
+ def __init__(self):
+ # Server will enable channelz service
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=3),
options=_DISABLE_REUSE_PORT +
_ENABLE_CHANNELZ)
- port = self.server.add_insecure_port('[::]:0')
- self.server.add_generic_rpc_handlers((_GenericHandler(),))
- self.server.start()
-
- # Channel will enable channelz service...
- self.channel = grpc.insecure_channel('localhost:%d' % port,
- _ENABLE_CHANNELZ)
-
-
-def _generate_channel_server_pairs(n):
- return [_ChannelServerPair() for i in range(n)]
-
-
-def _close_channel_server_pairs(pairs):
- for pair in pairs:
- pair.server.stop(None)
- pair.channel.close()
-
-
-class ChannelzServicerTest(unittest.TestCase):
-
- def _send_successful_unary_unary(self, idx):
- _, r = self._pairs[idx].channel.unary_unary(
- _SUCCESSFUL_UNARY_UNARY).with_call(_REQUEST)
- self.assertEqual(r.code(), grpc.StatusCode.OK)
-
- def _send_failed_unary_unary(self, idx):
- try:
- self._pairs[idx].channel.unary_unary(_FAILED_UNARY_UNARY).with_call(
- _REQUEST)
- except grpc.RpcError:
- return
- else:
- self.fail("This call supposed to fail")
-
- def _send_successful_stream_stream(self, idx):
- response_iterator = self._pairs[idx].channel.stream_stream(
- _SUCCESSFUL_STREAM_STREAM).__call__(
- iter([_REQUEST] * test_constants.STREAM_LENGTH))
- cnt = 0
- for _ in response_iterator:
- cnt += 1
- self.assertEqual(cnt, test_constants.STREAM_LENGTH)
-
- def _get_channel_id(self, idx):
- """Channel id may not be consecutive"""
- resp = self._channelz_stub.GetTopChannels(
- channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
- self.assertGreater(len(resp.channel), idx)
- return resp.channel[idx].ref.channel_id
-
- def setUp(self):
- self._pairs = []
- # This server is for Channelz info fetching only
- # It self should not enable Channelz
+ port = self.server.add_insecure_port('[::]:0')
+ self.server.add_generic_rpc_handlers((_GenericHandler(),))
+ self.server.start()
+
+ # Channel will enable channelz service...
+ self.channel = grpc.insecure_channel('localhost:%d' % port,
+ _ENABLE_CHANNELZ)
+
+
+def _generate_channel_server_pairs(n):
+ return [_ChannelServerPair() for i in range(n)]
+
+
+def _close_channel_server_pairs(pairs):
+ for pair in pairs:
+ pair.server.stop(None)
+ pair.channel.close()
+
+
+class ChannelzServicerTest(unittest.TestCase):
+
+ def _send_successful_unary_unary(self, idx):
+ _, r = self._pairs[idx].channel.unary_unary(
+ _SUCCESSFUL_UNARY_UNARY).with_call(_REQUEST)
+ self.assertEqual(r.code(), grpc.StatusCode.OK)
+
+ def _send_failed_unary_unary(self, idx):
+ try:
+ self._pairs[idx].channel.unary_unary(_FAILED_UNARY_UNARY).with_call(
+ _REQUEST)
+ except grpc.RpcError:
+ return
+ else:
+ self.fail("This call supposed to fail")
+
+ def _send_successful_stream_stream(self, idx):
+ response_iterator = self._pairs[idx].channel.stream_stream(
+ _SUCCESSFUL_STREAM_STREAM).__call__(
+ iter([_REQUEST] * test_constants.STREAM_LENGTH))
+ cnt = 0
+ for _ in response_iterator:
+ cnt += 1
+ self.assertEqual(cnt, test_constants.STREAM_LENGTH)
+
+ def _get_channel_id(self, idx):
+ """Channel id may not be consecutive"""
+ resp = self._channelz_stub.GetTopChannels(
+ channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
+ self.assertGreater(len(resp.channel), idx)
+ return resp.channel[idx].ref.channel_id
+
+ def setUp(self):
+ self._pairs = []
+ # This server is for Channelz info fetching only
+ # It self should not enable Channelz
self._server = grpc.server(futures.ThreadPoolExecutor(max_workers=3),
options=_DISABLE_REUSE_PORT +
_DISABLE_CHANNELZ)
- port = self._server.add_insecure_port('[::]:0')
- channelz.add_channelz_servicer(self._server)
- self._server.start()
-
- # This channel is used to fetch Channelz info only
- # Channelz should not be enabled
- self._channel = grpc.insecure_channel('localhost:%d' % port,
- _DISABLE_CHANNELZ)
- self._channelz_stub = channelz_pb2_grpc.ChannelzStub(self._channel)
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
- _close_channel_server_pairs(self._pairs)
-
- def test_get_top_channels_basic(self):
- self._pairs = _generate_channel_server_pairs(1)
- resp = self._channelz_stub.GetTopChannels(
- channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
- self.assertEqual(len(resp.channel), 1)
- self.assertEqual(resp.end, True)
-
- def test_get_top_channels_high_start_id(self):
- self._pairs = _generate_channel_server_pairs(1)
- resp = self._channelz_stub.GetTopChannels(
- channelz_pb2.GetTopChannelsRequest(start_channel_id=10000))
- self.assertEqual(len(resp.channel), 0)
- self.assertEqual(resp.end, True)
-
- def test_successful_request(self):
- self._pairs = _generate_channel_server_pairs(1)
- self._send_successful_unary_unary(0)
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
- self.assertEqual(resp.channel.data.calls_started, 1)
- self.assertEqual(resp.channel.data.calls_succeeded, 1)
- self.assertEqual(resp.channel.data.calls_failed, 0)
-
- def test_failed_request(self):
- self._pairs = _generate_channel_server_pairs(1)
- self._send_failed_unary_unary(0)
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
- self.assertEqual(resp.channel.data.calls_started, 1)
- self.assertEqual(resp.channel.data.calls_succeeded, 0)
- self.assertEqual(resp.channel.data.calls_failed, 1)
-
- def test_many_requests(self):
- self._pairs = _generate_channel_server_pairs(1)
- k_success = 7
- k_failed = 9
- for i in range(k_success):
- self._send_successful_unary_unary(0)
- for i in range(k_failed):
- self._send_failed_unary_unary(0)
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
- self.assertEqual(resp.channel.data.calls_started, k_success + k_failed)
- self.assertEqual(resp.channel.data.calls_succeeded, k_success)
- self.assertEqual(resp.channel.data.calls_failed, k_failed)
-
- def test_many_channel(self):
- k_channels = 4
- self._pairs = _generate_channel_server_pairs(k_channels)
- resp = self._channelz_stub.GetTopChannels(
- channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
- self.assertEqual(len(resp.channel), k_channels)
-
- def test_many_requests_many_channel(self):
- k_channels = 4
- self._pairs = _generate_channel_server_pairs(k_channels)
- k_success = 11
- k_failed = 13
- for i in range(k_success):
- self._send_successful_unary_unary(0)
- self._send_successful_unary_unary(2)
- for i in range(k_failed):
- self._send_failed_unary_unary(1)
- self._send_failed_unary_unary(2)
-
- # The first channel saw only successes
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
- self.assertEqual(resp.channel.data.calls_started, k_success)
- self.assertEqual(resp.channel.data.calls_succeeded, k_success)
- self.assertEqual(resp.channel.data.calls_failed, 0)
-
- # The second channel saw only failures
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(1)))
- self.assertEqual(resp.channel.data.calls_started, k_failed)
- self.assertEqual(resp.channel.data.calls_succeeded, 0)
- self.assertEqual(resp.channel.data.calls_failed, k_failed)
-
- # The third channel saw both successes and failures
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(2)))
- self.assertEqual(resp.channel.data.calls_started, k_success + k_failed)
- self.assertEqual(resp.channel.data.calls_succeeded, k_success)
- self.assertEqual(resp.channel.data.calls_failed, k_failed)
-
- # The fourth channel saw nothing
- resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(3)))
- self.assertEqual(resp.channel.data.calls_started, 0)
- self.assertEqual(resp.channel.data.calls_succeeded, 0)
- self.assertEqual(resp.channel.data.calls_failed, 0)
-
- def test_many_subchannels(self):
- k_channels = 4
- self._pairs = _generate_channel_server_pairs(k_channels)
- k_success = 17
- k_failed = 19
- for i in range(k_success):
- self._send_successful_unary_unary(0)
- self._send_successful_unary_unary(2)
- for i in range(k_failed):
- self._send_failed_unary_unary(1)
- self._send_failed_unary_unary(2)
-
- gtc_resp = self._channelz_stub.GetTopChannels(
- channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
- self.assertEqual(len(gtc_resp.channel), k_channels)
- for i in range(k_channels):
- # If no call performed in the channel, there shouldn't be any subchannel
- if gtc_resp.channel[i].data.calls_started == 0:
- self.assertEqual(len(gtc_resp.channel[i].subchannel_ref), 0)
- continue
-
- # Otherwise, the subchannel should exist
- self.assertGreater(len(gtc_resp.channel[i].subchannel_ref), 0)
- gsc_resp = self._channelz_stub.GetSubchannel(
- channelz_pb2.GetSubchannelRequest(
+ port = self._server.add_insecure_port('[::]:0')
+ channelz.add_channelz_servicer(self._server)
+ self._server.start()
+
+ # This channel is used to fetch Channelz info only
+ # Channelz should not be enabled
+ self._channel = grpc.insecure_channel('localhost:%d' % port,
+ _DISABLE_CHANNELZ)
+ self._channelz_stub = channelz_pb2_grpc.ChannelzStub(self._channel)
+
+ def tearDown(self):
+ self._server.stop(None)
+ self._channel.close()
+ _close_channel_server_pairs(self._pairs)
+
+ def test_get_top_channels_basic(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ resp = self._channelz_stub.GetTopChannels(
+ channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
+ self.assertEqual(len(resp.channel), 1)
+ self.assertEqual(resp.end, True)
+
+ def test_get_top_channels_high_start_id(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ resp = self._channelz_stub.GetTopChannels(
+ channelz_pb2.GetTopChannelsRequest(start_channel_id=10000))
+ self.assertEqual(len(resp.channel), 0)
+ self.assertEqual(resp.end, True)
+
+ def test_successful_request(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ self._send_successful_unary_unary(0)
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
+ self.assertEqual(resp.channel.data.calls_started, 1)
+ self.assertEqual(resp.channel.data.calls_succeeded, 1)
+ self.assertEqual(resp.channel.data.calls_failed, 0)
+
+ def test_failed_request(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ self._send_failed_unary_unary(0)
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
+ self.assertEqual(resp.channel.data.calls_started, 1)
+ self.assertEqual(resp.channel.data.calls_succeeded, 0)
+ self.assertEqual(resp.channel.data.calls_failed, 1)
+
+ def test_many_requests(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ k_success = 7
+ k_failed = 9
+ for i in range(k_success):
+ self._send_successful_unary_unary(0)
+ for i in range(k_failed):
+ self._send_failed_unary_unary(0)
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
+ self.assertEqual(resp.channel.data.calls_started, k_success + k_failed)
+ self.assertEqual(resp.channel.data.calls_succeeded, k_success)
+ self.assertEqual(resp.channel.data.calls_failed, k_failed)
+
+ def test_many_channel(self):
+ k_channels = 4
+ self._pairs = _generate_channel_server_pairs(k_channels)
+ resp = self._channelz_stub.GetTopChannels(
+ channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
+ self.assertEqual(len(resp.channel), k_channels)
+
+ def test_many_requests_many_channel(self):
+ k_channels = 4
+ self._pairs = _generate_channel_server_pairs(k_channels)
+ k_success = 11
+ k_failed = 13
+ for i in range(k_success):
+ self._send_successful_unary_unary(0)
+ self._send_successful_unary_unary(2)
+ for i in range(k_failed):
+ self._send_failed_unary_unary(1)
+ self._send_failed_unary_unary(2)
+
+ # The first channel saw only successes
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
+ self.assertEqual(resp.channel.data.calls_started, k_success)
+ self.assertEqual(resp.channel.data.calls_succeeded, k_success)
+ self.assertEqual(resp.channel.data.calls_failed, 0)
+
+ # The second channel saw only failures
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(1)))
+ self.assertEqual(resp.channel.data.calls_started, k_failed)
+ self.assertEqual(resp.channel.data.calls_succeeded, 0)
+ self.assertEqual(resp.channel.data.calls_failed, k_failed)
+
+ # The third channel saw both successes and failures
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(2)))
+ self.assertEqual(resp.channel.data.calls_started, k_success + k_failed)
+ self.assertEqual(resp.channel.data.calls_succeeded, k_success)
+ self.assertEqual(resp.channel.data.calls_failed, k_failed)
+
+ # The fourth channel saw nothing
+ resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(3)))
+ self.assertEqual(resp.channel.data.calls_started, 0)
+ self.assertEqual(resp.channel.data.calls_succeeded, 0)
+ self.assertEqual(resp.channel.data.calls_failed, 0)
+
+ def test_many_subchannels(self):
+ k_channels = 4
+ self._pairs = _generate_channel_server_pairs(k_channels)
+ k_success = 17
+ k_failed = 19
+ for i in range(k_success):
+ self._send_successful_unary_unary(0)
+ self._send_successful_unary_unary(2)
+ for i in range(k_failed):
+ self._send_failed_unary_unary(1)
+ self._send_failed_unary_unary(2)
+
+ gtc_resp = self._channelz_stub.GetTopChannels(
+ channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
+ self.assertEqual(len(gtc_resp.channel), k_channels)
+ for i in range(k_channels):
+ # If no call performed in the channel, there shouldn't be any subchannel
+ if gtc_resp.channel[i].data.calls_started == 0:
+ self.assertEqual(len(gtc_resp.channel[i].subchannel_ref), 0)
+ continue
+
+ # Otherwise, the subchannel should exist
+ self.assertGreater(len(gtc_resp.channel[i].subchannel_ref), 0)
+ gsc_resp = self._channelz_stub.GetSubchannel(
+ channelz_pb2.GetSubchannelRequest(
subchannel_id=gtc_resp.channel[i].subchannel_ref[0].
subchannel_id))
- self.assertEqual(gtc_resp.channel[i].data.calls_started,
- gsc_resp.subchannel.data.calls_started)
- self.assertEqual(gtc_resp.channel[i].data.calls_succeeded,
- gsc_resp.subchannel.data.calls_succeeded)
- self.assertEqual(gtc_resp.channel[i].data.calls_failed,
- gsc_resp.subchannel.data.calls_failed)
-
- def test_server_basic(self):
- self._pairs = _generate_channel_server_pairs(1)
- resp = self._channelz_stub.GetServers(
- channelz_pb2.GetServersRequest(start_server_id=0))
- self.assertEqual(len(resp.server), 1)
-
- def test_get_one_server(self):
- self._pairs = _generate_channel_server_pairs(1)
- gss_resp = self._channelz_stub.GetServers(
- channelz_pb2.GetServersRequest(start_server_id=0))
- self.assertEqual(len(gss_resp.server), 1)
- gs_resp = self._channelz_stub.GetServer(
- channelz_pb2.GetServerRequest(
- server_id=gss_resp.server[0].ref.server_id))
- self.assertEqual(gss_resp.server[0].ref.server_id,
- gs_resp.server.ref.server_id)
-
- def test_server_call(self):
- self._pairs = _generate_channel_server_pairs(1)
- k_success = 23
- k_failed = 29
- for i in range(k_success):
- self._send_successful_unary_unary(0)
- for i in range(k_failed):
- self._send_failed_unary_unary(0)
-
- resp = self._channelz_stub.GetServers(
- channelz_pb2.GetServersRequest(start_server_id=0))
- self.assertEqual(len(resp.server), 1)
- self.assertEqual(resp.server[0].data.calls_started,
- k_success + k_failed)
- self.assertEqual(resp.server[0].data.calls_succeeded, k_success)
- self.assertEqual(resp.server[0].data.calls_failed, k_failed)
-
- def test_many_subchannels_and_sockets(self):
- k_channels = 4
- self._pairs = _generate_channel_server_pairs(k_channels)
- k_success = 3
- k_failed = 5
- for i in range(k_success):
- self._send_successful_unary_unary(0)
- self._send_successful_unary_unary(2)
- for i in range(k_failed):
- self._send_failed_unary_unary(1)
- self._send_failed_unary_unary(2)
-
- gtc_resp = self._channelz_stub.GetTopChannels(
- channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
- self.assertEqual(len(gtc_resp.channel), k_channels)
- for i in range(k_channels):
- # If no call performed in the channel, there shouldn't be any subchannel
- if gtc_resp.channel[i].data.calls_started == 0:
- self.assertEqual(len(gtc_resp.channel[i].subchannel_ref), 0)
- continue
-
- # Otherwise, the subchannel should exist
- self.assertGreater(len(gtc_resp.channel[i].subchannel_ref), 0)
- gsc_resp = self._channelz_stub.GetSubchannel(
- channelz_pb2.GetSubchannelRequest(
+ self.assertEqual(gtc_resp.channel[i].data.calls_started,
+ gsc_resp.subchannel.data.calls_started)
+ self.assertEqual(gtc_resp.channel[i].data.calls_succeeded,
+ gsc_resp.subchannel.data.calls_succeeded)
+ self.assertEqual(gtc_resp.channel[i].data.calls_failed,
+ gsc_resp.subchannel.data.calls_failed)
+
+ def test_server_basic(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ resp = self._channelz_stub.GetServers(
+ channelz_pb2.GetServersRequest(start_server_id=0))
+ self.assertEqual(len(resp.server), 1)
+
+ def test_get_one_server(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ gss_resp = self._channelz_stub.GetServers(
+ channelz_pb2.GetServersRequest(start_server_id=0))
+ self.assertEqual(len(gss_resp.server), 1)
+ gs_resp = self._channelz_stub.GetServer(
+ channelz_pb2.GetServerRequest(
+ server_id=gss_resp.server[0].ref.server_id))
+ self.assertEqual(gss_resp.server[0].ref.server_id,
+ gs_resp.server.ref.server_id)
+
+ def test_server_call(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ k_success = 23
+ k_failed = 29
+ for i in range(k_success):
+ self._send_successful_unary_unary(0)
+ for i in range(k_failed):
+ self._send_failed_unary_unary(0)
+
+ resp = self._channelz_stub.GetServers(
+ channelz_pb2.GetServersRequest(start_server_id=0))
+ self.assertEqual(len(resp.server), 1)
+ self.assertEqual(resp.server[0].data.calls_started,
+ k_success + k_failed)
+ self.assertEqual(resp.server[0].data.calls_succeeded, k_success)
+ self.assertEqual(resp.server[0].data.calls_failed, k_failed)
+
+ def test_many_subchannels_and_sockets(self):
+ k_channels = 4
+ self._pairs = _generate_channel_server_pairs(k_channels)
+ k_success = 3
+ k_failed = 5
+ for i in range(k_success):
+ self._send_successful_unary_unary(0)
+ self._send_successful_unary_unary(2)
+ for i in range(k_failed):
+ self._send_failed_unary_unary(1)
+ self._send_failed_unary_unary(2)
+
+ gtc_resp = self._channelz_stub.GetTopChannels(
+ channelz_pb2.GetTopChannelsRequest(start_channel_id=0))
+ self.assertEqual(len(gtc_resp.channel), k_channels)
+ for i in range(k_channels):
+ # If no call performed in the channel, there shouldn't be any subchannel
+ if gtc_resp.channel[i].data.calls_started == 0:
+ self.assertEqual(len(gtc_resp.channel[i].subchannel_ref), 0)
+ continue
+
+ # Otherwise, the subchannel should exist
+ self.assertGreater(len(gtc_resp.channel[i].subchannel_ref), 0)
+ gsc_resp = self._channelz_stub.GetSubchannel(
+ channelz_pb2.GetSubchannelRequest(
subchannel_id=gtc_resp.channel[i].subchannel_ref[0].
subchannel_id))
- self.assertEqual(len(gsc_resp.subchannel.socket_ref), 1)
-
- gs_resp = self._channelz_stub.GetSocket(
- channelz_pb2.GetSocketRequest(
- socket_id=gsc_resp.subchannel.socket_ref[0].socket_id))
- self.assertEqual(gsc_resp.subchannel.data.calls_started,
- gs_resp.socket.data.streams_started)
- self.assertEqual(gsc_resp.subchannel.data.calls_started,
- gs_resp.socket.data.streams_succeeded)
- # Calls started == messages sent, only valid for unary calls
- self.assertEqual(gsc_resp.subchannel.data.calls_started,
- gs_resp.socket.data.messages_sent)
- # Only receive responses when the RPC was successful
- self.assertEqual(gsc_resp.subchannel.data.calls_succeeded,
- gs_resp.socket.data.messages_received)
-
- def test_streaming_rpc(self):
- self._pairs = _generate_channel_server_pairs(1)
- # In C++, the argument for _send_successful_stream_stream is message length.
- # Here the argument is still channel idx, to be consistent with the other two.
- self._send_successful_stream_stream(0)
-
- gc_resp = self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
- self.assertEqual(gc_resp.channel.data.calls_started, 1)
- self.assertEqual(gc_resp.channel.data.calls_succeeded, 1)
- self.assertEqual(gc_resp.channel.data.calls_failed, 0)
- # Subchannel exists
- self.assertGreater(len(gc_resp.channel.subchannel_ref), 0)
-
- gsc_resp = self._channelz_stub.GetSubchannel(
- channelz_pb2.GetSubchannelRequest(
- subchannel_id=gc_resp.channel.subchannel_ref[0].subchannel_id))
- self.assertEqual(gsc_resp.subchannel.data.calls_started, 1)
- self.assertEqual(gsc_resp.subchannel.data.calls_succeeded, 1)
- self.assertEqual(gsc_resp.subchannel.data.calls_failed, 0)
- # Socket exists
- self.assertEqual(len(gsc_resp.subchannel.socket_ref), 1)
-
- gs_resp = self._channelz_stub.GetSocket(
- channelz_pb2.GetSocketRequest(
- socket_id=gsc_resp.subchannel.socket_ref[0].socket_id))
- self.assertEqual(gs_resp.socket.data.streams_started, 1)
- self.assertEqual(gs_resp.socket.data.streams_succeeded, 1)
- self.assertEqual(gs_resp.socket.data.streams_failed, 0)
- self.assertEqual(gs_resp.socket.data.messages_sent,
- test_constants.STREAM_LENGTH)
- self.assertEqual(gs_resp.socket.data.messages_received,
- test_constants.STREAM_LENGTH)
-
- def test_server_sockets(self):
- self._pairs = _generate_channel_server_pairs(1)
- self._send_successful_unary_unary(0)
- self._send_failed_unary_unary(0)
-
- gs_resp = self._channelz_stub.GetServers(
- channelz_pb2.GetServersRequest(start_server_id=0))
- self.assertEqual(len(gs_resp.server), 1)
- self.assertEqual(gs_resp.server[0].data.calls_started, 2)
- self.assertEqual(gs_resp.server[0].data.calls_succeeded, 1)
- self.assertEqual(gs_resp.server[0].data.calls_failed, 1)
-
- gss_resp = self._channelz_stub.GetServerSockets(
- channelz_pb2.GetServerSocketsRequest(
- server_id=gs_resp.server[0].ref.server_id, start_socket_id=0))
- # If the RPC call failed, it will raise a grpc.RpcError
- # So, if there is no exception raised, considered pass
-
- def test_server_listen_sockets(self):
- self._pairs = _generate_channel_server_pairs(1)
-
- gss_resp = self._channelz_stub.GetServers(
- channelz_pb2.GetServersRequest(start_server_id=0))
- self.assertEqual(len(gss_resp.server), 1)
- self.assertEqual(len(gss_resp.server[0].listen_socket), 1)
-
- gs_resp = self._channelz_stub.GetSocket(
- channelz_pb2.GetSocketRequest(
- socket_id=gss_resp.server[0].listen_socket[0].socket_id))
- # If the RPC call failed, it will raise a grpc.RpcError
- # So, if there is no exception raised, considered pass
-
- def test_invalid_query_get_server(self):
- try:
- self._channelz_stub.GetServer(
- channelz_pb2.GetServerRequest(server_id=10000))
- except BaseException as e:
- self.assertIn('StatusCode.NOT_FOUND', str(e))
- else:
- self.fail('Invalid query not detected')
-
- def test_invalid_query_get_channel(self):
- try:
- self._channelz_stub.GetChannel(
- channelz_pb2.GetChannelRequest(channel_id=10000))
- except BaseException as e:
- self.assertIn('StatusCode.NOT_FOUND', str(e))
- else:
- self.fail('Invalid query not detected')
-
- def test_invalid_query_get_subchannel(self):
- try:
- self._channelz_stub.GetSubchannel(
- channelz_pb2.GetSubchannelRequest(subchannel_id=10000))
- except BaseException as e:
- self.assertIn('StatusCode.NOT_FOUND', str(e))
- else:
- self.fail('Invalid query not detected')
-
- def test_invalid_query_get_socket(self):
- try:
- self._channelz_stub.GetSocket(
- channelz_pb2.GetSocketRequest(socket_id=10000))
- except BaseException as e:
- self.assertIn('StatusCode.NOT_FOUND', str(e))
- else:
- self.fail('Invalid query not detected')
-
- def test_invalid_query_get_server_sockets(self):
- try:
- self._channelz_stub.GetServerSockets(
- channelz_pb2.GetServerSocketsRequest(
- server_id=10000,
- start_socket_id=0,
- ))
- except BaseException as e:
- self.assertIn('StatusCode.NOT_FOUND', str(e))
- else:
- self.fail('Invalid query not detected')
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ self.assertEqual(len(gsc_resp.subchannel.socket_ref), 1)
+
+ gs_resp = self._channelz_stub.GetSocket(
+ channelz_pb2.GetSocketRequest(
+ socket_id=gsc_resp.subchannel.socket_ref[0].socket_id))
+ self.assertEqual(gsc_resp.subchannel.data.calls_started,
+ gs_resp.socket.data.streams_started)
+ self.assertEqual(gsc_resp.subchannel.data.calls_started,
+ gs_resp.socket.data.streams_succeeded)
+ # Calls started == messages sent, only valid for unary calls
+ self.assertEqual(gsc_resp.subchannel.data.calls_started,
+ gs_resp.socket.data.messages_sent)
+ # Only receive responses when the RPC was successful
+ self.assertEqual(gsc_resp.subchannel.data.calls_succeeded,
+ gs_resp.socket.data.messages_received)
+
+ def test_streaming_rpc(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ # In C++, the argument for _send_successful_stream_stream is message length.
+ # Here the argument is still channel idx, to be consistent with the other two.
+ self._send_successful_stream_stream(0)
+
+ gc_resp = self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=self._get_channel_id(0)))
+ self.assertEqual(gc_resp.channel.data.calls_started, 1)
+ self.assertEqual(gc_resp.channel.data.calls_succeeded, 1)
+ self.assertEqual(gc_resp.channel.data.calls_failed, 0)
+ # Subchannel exists
+ self.assertGreater(len(gc_resp.channel.subchannel_ref), 0)
+
+ gsc_resp = self._channelz_stub.GetSubchannel(
+ channelz_pb2.GetSubchannelRequest(
+ subchannel_id=gc_resp.channel.subchannel_ref[0].subchannel_id))
+ self.assertEqual(gsc_resp.subchannel.data.calls_started, 1)
+ self.assertEqual(gsc_resp.subchannel.data.calls_succeeded, 1)
+ self.assertEqual(gsc_resp.subchannel.data.calls_failed, 0)
+ # Socket exists
+ self.assertEqual(len(gsc_resp.subchannel.socket_ref), 1)
+
+ gs_resp = self._channelz_stub.GetSocket(
+ channelz_pb2.GetSocketRequest(
+ socket_id=gsc_resp.subchannel.socket_ref[0].socket_id))
+ self.assertEqual(gs_resp.socket.data.streams_started, 1)
+ self.assertEqual(gs_resp.socket.data.streams_succeeded, 1)
+ self.assertEqual(gs_resp.socket.data.streams_failed, 0)
+ self.assertEqual(gs_resp.socket.data.messages_sent,
+ test_constants.STREAM_LENGTH)
+ self.assertEqual(gs_resp.socket.data.messages_received,
+ test_constants.STREAM_LENGTH)
+
+ def test_server_sockets(self):
+ self._pairs = _generate_channel_server_pairs(1)
+ self._send_successful_unary_unary(0)
+ self._send_failed_unary_unary(0)
+
+ gs_resp = self._channelz_stub.GetServers(
+ channelz_pb2.GetServersRequest(start_server_id=0))
+ self.assertEqual(len(gs_resp.server), 1)
+ self.assertEqual(gs_resp.server[0].data.calls_started, 2)
+ self.assertEqual(gs_resp.server[0].data.calls_succeeded, 1)
+ self.assertEqual(gs_resp.server[0].data.calls_failed, 1)
+
+ gss_resp = self._channelz_stub.GetServerSockets(
+ channelz_pb2.GetServerSocketsRequest(
+ server_id=gs_resp.server[0].ref.server_id, start_socket_id=0))
+ # If the RPC call failed, it will raise a grpc.RpcError
+ # So, if there is no exception raised, considered pass
+
+ def test_server_listen_sockets(self):
+ self._pairs = _generate_channel_server_pairs(1)
+
+ gss_resp = self._channelz_stub.GetServers(
+ channelz_pb2.GetServersRequest(start_server_id=0))
+ self.assertEqual(len(gss_resp.server), 1)
+ self.assertEqual(len(gss_resp.server[0].listen_socket), 1)
+
+ gs_resp = self._channelz_stub.GetSocket(
+ channelz_pb2.GetSocketRequest(
+ socket_id=gss_resp.server[0].listen_socket[0].socket_id))
+ # If the RPC call failed, it will raise a grpc.RpcError
+ # So, if there is no exception raised, considered pass
+
+ def test_invalid_query_get_server(self):
+ try:
+ self._channelz_stub.GetServer(
+ channelz_pb2.GetServerRequest(server_id=10000))
+ except BaseException as e:
+ self.assertIn('StatusCode.NOT_FOUND', str(e))
+ else:
+ self.fail('Invalid query not detected')
+
+ def test_invalid_query_get_channel(self):
+ try:
+ self._channelz_stub.GetChannel(
+ channelz_pb2.GetChannelRequest(channel_id=10000))
+ except BaseException as e:
+ self.assertIn('StatusCode.NOT_FOUND', str(e))
+ else:
+ self.fail('Invalid query not detected')
+
+ def test_invalid_query_get_subchannel(self):
+ try:
+ self._channelz_stub.GetSubchannel(
+ channelz_pb2.GetSubchannelRequest(subchannel_id=10000))
+ except BaseException as e:
+ self.assertIn('StatusCode.NOT_FOUND', str(e))
+ else:
+ self.fail('Invalid query not detected')
+
+ def test_invalid_query_get_socket(self):
+ try:
+ self._channelz_stub.GetSocket(
+ channelz_pb2.GetSocketRequest(socket_id=10000))
+ except BaseException as e:
+ self.assertIn('StatusCode.NOT_FOUND', str(e))
+ else:
+ self.fail('Invalid query not detected')
+
+ def test_invalid_query_get_server_sockets(self):
+ try:
+ self._channelz_stub.GetServerSockets(
+ channelz_pb2.GetServerSocketsRequest(
+ server_id=10000,
+ start_socket_id=0,
+ ))
+ except BaseException as e:
+ self.assertIn('StatusCode.NOT_FOUND', str(e))
+ else:
+ self.fail('Invalid query not detected')
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/__init__.py
index 9a26bac010..e9db7e5970 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2018 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.
+# Copyright 2018 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/_fork_interop_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/_fork_interop_test.py
index e2eff257fa..a1b77bb48e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/_fork_interop_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/_fork_interop_test.py
@@ -1,151 +1,151 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Client-side fork interop tests as a unit test."""
-
-import six
-import subprocess
-import sys
-import threading
-import unittest
-from grpc._cython import cygrpc
-from tests.fork import methods
-
-# New instance of multiprocessing.Process using fork without exec can and will
-# hang if the Python process has any other threads running. This includes the
-# additional thread spawned by our _runner.py class. So in order to test our
-# compatibility with multiprocessing, we first fork+exec a new process to ensure
-# we don't have any conflicting background threads.
-_CLIENT_FORK_SCRIPT_TEMPLATE = """if True:
- import os
- import sys
- from grpc._cython import cygrpc
- from tests.fork import methods
-
- cygrpc._GRPC_ENABLE_FORK_SUPPORT = True
- os.environ['GRPC_POLL_STRATEGY'] = 'epoll1'
- methods.TestCase.%s.run_test({
- 'server_host': 'localhost',
- 'server_port': %d,
- 'use_tls': False
- })
-"""
-_SUBPROCESS_TIMEOUT_S = 30
-
-
-@unittest.skipUnless(
- sys.platform.startswith("linux"),
- "not supported on windows, and fork+exec networking blocked on mac")
-@unittest.skipUnless(six.PY2, "https://github.com/grpc/grpc/issues/18075")
-class ForkInteropTest(unittest.TestCase):
-
- def setUp(self):
- start_server_script = """if True:
- import sys
- import time
-
- import grpc
- from src.proto.grpc.testing import test_pb2_grpc
- from tests.interop import service as interop_service
- from tests.unit import test_common
-
- server = test_common.test_server()
- test_pb2_grpc.add_TestServiceServicer_to_server(
- interop_service.TestService(), server)
- port = server.add_insecure_port('[::]:0')
- server.start()
- print(port)
- sys.stdout.flush()
- while True:
- time.sleep(1)
- """
- self._server_process = subprocess.Popen(
- [sys.executable, '-c', start_server_script],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
- timer = threading.Timer(_SUBPROCESS_TIMEOUT_S,
- self._server_process.kill)
- try:
- timer.start()
- self._port = int(self._server_process.stdout.readline())
- except ValueError:
- raise Exception('Failed to get port from server')
- finally:
- timer.cancel()
-
- def testConnectivityWatch(self):
- self._verifyTestCase(methods.TestCase.CONNECTIVITY_WATCH)
-
- def testCloseChannelBeforeFork(self):
- self._verifyTestCase(methods.TestCase.CLOSE_CHANNEL_BEFORE_FORK)
-
- def testAsyncUnarySameChannel(self):
- self._verifyTestCase(methods.TestCase.ASYNC_UNARY_SAME_CHANNEL)
-
- def testAsyncUnaryNewChannel(self):
- self._verifyTestCase(methods.TestCase.ASYNC_UNARY_NEW_CHANNEL)
-
- def testBlockingUnarySameChannel(self):
- self._verifyTestCase(methods.TestCase.BLOCKING_UNARY_SAME_CHANNEL)
-
- def testBlockingUnaryNewChannel(self):
- self._verifyTestCase(methods.TestCase.BLOCKING_UNARY_NEW_CHANNEL)
-
- def testInProgressBidiContinueCall(self):
- self._verifyTestCase(methods.TestCase.IN_PROGRESS_BIDI_CONTINUE_CALL)
-
- def testInProgressBidiSameChannelAsyncCall(self):
- self._verifyTestCase(
- methods.TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_ASYNC_CALL)
-
- def testInProgressBidiSameChannelBlockingCall(self):
- self._verifyTestCase(
- methods.TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_BLOCKING_CALL)
-
- def testInProgressBidiNewChannelAsyncCall(self):
- self._verifyTestCase(
- methods.TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_ASYNC_CALL)
-
- def testInProgressBidiNewChannelBlockingCall(self):
- self._verifyTestCase(
- methods.TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_BLOCKING_CALL)
-
- def tearDown(self):
- self._server_process.kill()
-
- def _verifyTestCase(self, test_case):
- script = _CLIENT_FORK_SCRIPT_TEMPLATE % (test_case.name, self._port)
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Client-side fork interop tests as a unit test."""
+
+import six
+import subprocess
+import sys
+import threading
+import unittest
+from grpc._cython import cygrpc
+from tests.fork import methods
+
+# New instance of multiprocessing.Process using fork without exec can and will
+# hang if the Python process has any other threads running. This includes the
+# additional thread spawned by our _runner.py class. So in order to test our
+# compatibility with multiprocessing, we first fork+exec a new process to ensure
+# we don't have any conflicting background threads.
+_CLIENT_FORK_SCRIPT_TEMPLATE = """if True:
+ import os
+ import sys
+ from grpc._cython import cygrpc
+ from tests.fork import methods
+
+ cygrpc._GRPC_ENABLE_FORK_SUPPORT = True
+ os.environ['GRPC_POLL_STRATEGY'] = 'epoll1'
+ methods.TestCase.%s.run_test({
+ 'server_host': 'localhost',
+ 'server_port': %d,
+ 'use_tls': False
+ })
+"""
+_SUBPROCESS_TIMEOUT_S = 30
+
+
+@unittest.skipUnless(
+ sys.platform.startswith("linux"),
+ "not supported on windows, and fork+exec networking blocked on mac")
+@unittest.skipUnless(six.PY2, "https://github.com/grpc/grpc/issues/18075")
+class ForkInteropTest(unittest.TestCase):
+
+ def setUp(self):
+ start_server_script = """if True:
+ import sys
+ import time
+
+ import grpc
+ from src.proto.grpc.testing import test_pb2_grpc
+ from tests.interop import service as interop_service
+ from tests.unit import test_common
+
+ server = test_common.test_server()
+ test_pb2_grpc.add_TestServiceServicer_to_server(
+ interop_service.TestService(), server)
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ print(port)
+ sys.stdout.flush()
+ while True:
+ time.sleep(1)
+ """
+ self._server_process = subprocess.Popen(
+ [sys.executable, '-c', start_server_script],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ timer = threading.Timer(_SUBPROCESS_TIMEOUT_S,
+ self._server_process.kill)
+ try:
+ timer.start()
+ self._port = int(self._server_process.stdout.readline())
+ except ValueError:
+ raise Exception('Failed to get port from server')
+ finally:
+ timer.cancel()
+
+ def testConnectivityWatch(self):
+ self._verifyTestCase(methods.TestCase.CONNECTIVITY_WATCH)
+
+ def testCloseChannelBeforeFork(self):
+ self._verifyTestCase(methods.TestCase.CLOSE_CHANNEL_BEFORE_FORK)
+
+ def testAsyncUnarySameChannel(self):
+ self._verifyTestCase(methods.TestCase.ASYNC_UNARY_SAME_CHANNEL)
+
+ def testAsyncUnaryNewChannel(self):
+ self._verifyTestCase(methods.TestCase.ASYNC_UNARY_NEW_CHANNEL)
+
+ def testBlockingUnarySameChannel(self):
+ self._verifyTestCase(methods.TestCase.BLOCKING_UNARY_SAME_CHANNEL)
+
+ def testBlockingUnaryNewChannel(self):
+ self._verifyTestCase(methods.TestCase.BLOCKING_UNARY_NEW_CHANNEL)
+
+ def testInProgressBidiContinueCall(self):
+ self._verifyTestCase(methods.TestCase.IN_PROGRESS_BIDI_CONTINUE_CALL)
+
+ def testInProgressBidiSameChannelAsyncCall(self):
+ self._verifyTestCase(
+ methods.TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_ASYNC_CALL)
+
+ def testInProgressBidiSameChannelBlockingCall(self):
+ self._verifyTestCase(
+ methods.TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_BLOCKING_CALL)
+
+ def testInProgressBidiNewChannelAsyncCall(self):
+ self._verifyTestCase(
+ methods.TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_ASYNC_CALL)
+
+ def testInProgressBidiNewChannelBlockingCall(self):
+ self._verifyTestCase(
+ methods.TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_BLOCKING_CALL)
+
+ def tearDown(self):
+ self._server_process.kill()
+
+ def _verifyTestCase(self, test_case):
+ script = _CLIENT_FORK_SCRIPT_TEMPLATE % (test_case.name, self._port)
process = subprocess.Popen([sys.executable, '-c', script],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
- timer = threading.Timer(_SUBPROCESS_TIMEOUT_S, process.kill)
- try:
- timer.start()
- try:
- out, err = process.communicate(timeout=_SUBPROCESS_TIMEOUT_S)
- except TypeError:
- # The timeout parameter was added in Python 3.3.
- out, err = process.communicate()
- except subprocess.TimeoutExpired:
- process.kill()
- raise RuntimeError('Process failed to terminate')
- finally:
- timer.cancel()
- self.assertEqual(
- 0, process.returncode,
- 'process failed with exit code %d (stdout: %s, stderr: %s)' %
- (process.returncode, out, err))
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ timer = threading.Timer(_SUBPROCESS_TIMEOUT_S, process.kill)
+ try:
+ timer.start()
+ try:
+ out, err = process.communicate(timeout=_SUBPROCESS_TIMEOUT_S)
+ except TypeError:
+ # The timeout parameter was added in Python 3.3.
+ out, err = process.communicate()
+ except subprocess.TimeoutExpired:
+ process.kill()
+ raise RuntimeError('Process failed to terminate')
+ finally:
+ timer.cancel()
+ self.assertEqual(
+ 0, process.returncode,
+ 'process failed with exit code %d (stdout: %s, stderr: %s)' %
+ (process.returncode, out, err))
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/client.py
index 852e6da4d6..f68e8f731d 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/client.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/client.py
@@ -1,35 +1,35 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""The Python implementation of the GRPC interoperability test client."""
-
-import argparse
-import logging
-import sys
-
-from tests.fork import methods
-
-
-def _args():
-
- def parse_bool(value):
- if value == 'true':
- return True
- if value == 'false':
- return False
- raise argparse.ArgumentTypeError('Only true/false allowed')
-
- parser = argparse.ArgumentParser()
+# Copyright 2018 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the GRPC interoperability test client."""
+
+import argparse
+import logging
+import sys
+
+from tests.fork import methods
+
+
+def _args():
+
+ def parse_bool(value):
+ if value == 'true':
+ return True
+ if value == 'false':
+ return False
+ raise argparse.ArgumentTypeError('Only true/false allowed')
+
+ parser = argparse.ArgumentParser()
parser.add_argument('--server_host',
default="localhost",
type=str,
@@ -46,27 +46,27 @@ def _args():
default=False,
type=parse_bool,
help='require a secure connection')
- return parser.parse_args()
-
-
-def _test_case_from_arg(test_case_arg):
- for test_case in methods.TestCase:
- if test_case_arg == test_case.value:
- return test_case
- else:
- raise ValueError('No test case "%s"!' % test_case_arg)
-
-
-def test_fork():
- logging.basicConfig(level=logging.INFO)
- args = vars(_args())
- if args['test_case'] == "all":
- for test_case in methods.TestCase:
- test_case.run_test(args)
- else:
- test_case = _test_case_from_arg(args['test_case'])
- test_case.run_test(args)
-
-
-if __name__ == '__main__':
- test_fork()
+ return parser.parse_args()
+
+
+def _test_case_from_arg(test_case_arg):
+ for test_case in methods.TestCase:
+ if test_case_arg == test_case.value:
+ return test_case
+ else:
+ raise ValueError('No test case "%s"!' % test_case_arg)
+
+
+def test_fork():
+ logging.basicConfig(level=logging.INFO)
+ args = vars(_args())
+ if args['test_case'] == "all":
+ for test_case in methods.TestCase:
+ test_case.run_test(args)
+ else:
+ test_case = _test_case_from_arg(args['test_case'])
+ test_case.run_test(args)
+
+
+if __name__ == '__main__':
+ test_fork()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/methods.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/methods.py
index 2123c69916..08674a5903 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/methods.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/fork/methods.py
@@ -1,451 +1,451 @@
-# Copyright 2018 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.
-"""Implementations of fork support test methods."""
-
-import enum
-import json
-import logging
-import multiprocessing
-import os
-import threading
-import time
-
-import grpc
-
-from six.moves import queue
-
-from src.proto.grpc.testing import empty_pb2
-from src.proto.grpc.testing import messages_pb2
-from src.proto.grpc.testing import test_pb2_grpc
-
-_LOGGER = logging.getLogger(__name__)
-_RPC_TIMEOUT_S = 10
-_CHILD_FINISH_TIMEOUT_S = 60
-
-
-def _channel(args):
- target = '{}:{}'.format(args['server_host'], args['server_port'])
- if args['use_tls']:
- channel_credentials = grpc.ssl_channel_credentials()
- channel = grpc.secure_channel(target, channel_credentials)
- else:
- channel = grpc.insecure_channel(target)
- return channel
-
-
-def _validate_payload_type_and_length(response, expected_type, expected_length):
- if response.payload.type is not expected_type:
- raise ValueError('expected payload type %s, got %s' %
- (expected_type, type(response.payload.type)))
- elif len(response.payload.body) != expected_length:
- raise ValueError('expected payload body size %d, got %d' %
- (expected_length, len(response.payload.body)))
-
-
-def _async_unary(stub):
- size = 314159
- request = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=size,
- payload=messages_pb2.Payload(body=b'\x00' * 271828))
- response_future = stub.UnaryCall.future(request, timeout=_RPC_TIMEOUT_S)
- response = response_future.result()
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
-
-
-def _blocking_unary(stub):
- size = 314159
- request = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=size,
- payload=messages_pb2.Payload(body=b'\x00' * 271828))
- response = stub.UnaryCall(request, timeout=_RPC_TIMEOUT_S)
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
-
-
-class _Pipe(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._values = []
- self._open = True
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self.next()
-
- def next(self):
- with self._condition:
- while not self._values and self._open:
- self._condition.wait()
- if self._values:
- return self._values.pop(0)
- else:
- raise StopIteration()
-
- def add(self, value):
- with self._condition:
- self._values.append(value)
- self._condition.notify()
-
- def close(self):
- with self._condition:
- self._open = False
- self._condition.notify()
-
- def __enter__(self):
- return self
-
- def __exit__(self, type, value, traceback):
- self.close()
-
-
-class _ChildProcess(object):
-
- def __init__(self, task, args=None):
- if args is None:
- args = ()
- self._exceptions = multiprocessing.Queue()
-
- def record_exceptions():
- try:
- task(*args)
- except grpc.RpcError as rpc_error:
- self._exceptions.put('RpcError: %s' % rpc_error)
- except Exception as e: # pylint: disable=broad-except
- self._exceptions.put(e)
-
- self._process = multiprocessing.Process(target=record_exceptions)
-
- def start(self):
- self._process.start()
-
- def finish(self):
- self._process.join(timeout=_CHILD_FINISH_TIMEOUT_S)
- if self._process.is_alive():
- raise RuntimeError('Child process did not terminate')
- if self._process.exitcode != 0:
- raise ValueError('Child process failed with exitcode %d' %
- self._process.exitcode)
- try:
- exception = self._exceptions.get(block=False)
- raise ValueError('Child process failed: %s' % exception)
- except queue.Empty:
- pass
-
-
-def _async_unary_same_channel(channel):
-
- def child_target():
- try:
- _async_unary(stub)
- raise Exception(
- 'Child should not be able to re-use channel after fork')
- except ValueError as expected_value_error:
- pass
-
- stub = test_pb2_grpc.TestServiceStub(channel)
- _async_unary(stub)
- child_process = _ChildProcess(child_target)
- child_process.start()
- _async_unary(stub)
- child_process.finish()
-
-
-def _async_unary_new_channel(channel, args):
-
- def child_target():
- with _channel(args) as child_channel:
- child_stub = test_pb2_grpc.TestServiceStub(child_channel)
- _async_unary(child_stub)
- child_channel.close()
-
- stub = test_pb2_grpc.TestServiceStub(channel)
- _async_unary(stub)
- child_process = _ChildProcess(child_target)
- child_process.start()
- _async_unary(stub)
- child_process.finish()
-
-
-def _blocking_unary_same_channel(channel):
-
- def child_target():
- try:
- _blocking_unary(stub)
- raise Exception(
- 'Child should not be able to re-use channel after fork')
- except ValueError as expected_value_error:
- pass
-
- stub = test_pb2_grpc.TestServiceStub(channel)
- _blocking_unary(stub)
- child_process = _ChildProcess(child_target)
- child_process.start()
- child_process.finish()
-
-
-def _blocking_unary_new_channel(channel, args):
-
- def child_target():
- with _channel(args) as child_channel:
- child_stub = test_pb2_grpc.TestServiceStub(child_channel)
- _blocking_unary(child_stub)
-
- stub = test_pb2_grpc.TestServiceStub(channel)
- _blocking_unary(stub)
- child_process = _ChildProcess(child_target)
- child_process.start()
- _blocking_unary(stub)
- child_process.finish()
-
-
-# Verify that the fork channel registry can handle already closed channels
-def _close_channel_before_fork(channel, args):
-
- def child_target():
- new_channel.close()
- with _channel(args) as child_channel:
- child_stub = test_pb2_grpc.TestServiceStub(child_channel)
- _blocking_unary(child_stub)
-
- stub = test_pb2_grpc.TestServiceStub(channel)
- _blocking_unary(stub)
- channel.close()
-
- with _channel(args) as new_channel:
- new_stub = test_pb2_grpc.TestServiceStub(new_channel)
- child_process = _ChildProcess(child_target)
- child_process.start()
- _blocking_unary(new_stub)
- child_process.finish()
-
-
-def _connectivity_watch(channel, args):
-
- parent_states = []
- parent_channel_ready_event = threading.Event()
-
- def child_target():
-
- child_channel_ready_event = threading.Event()
-
- def child_connectivity_callback(state):
- if state is grpc.ChannelConnectivity.READY:
- child_channel_ready_event.set()
-
- with _channel(args) as child_channel:
- child_stub = test_pb2_grpc.TestServiceStub(child_channel)
- child_channel.subscribe(child_connectivity_callback)
- _async_unary(child_stub)
- if not child_channel_ready_event.wait(timeout=_RPC_TIMEOUT_S):
- raise ValueError('Channel did not move to READY')
- if len(parent_states) > 1:
- raise ValueError(
- 'Received connectivity updates on parent callback',
- parent_states)
- child_channel.unsubscribe(child_connectivity_callback)
-
- def parent_connectivity_callback(state):
- parent_states.append(state)
- if state is grpc.ChannelConnectivity.READY:
- parent_channel_ready_event.set()
-
- channel.subscribe(parent_connectivity_callback)
- stub = test_pb2_grpc.TestServiceStub(channel)
- child_process = _ChildProcess(child_target)
- child_process.start()
- _async_unary(stub)
- if not parent_channel_ready_event.wait(timeout=_RPC_TIMEOUT_S):
- raise ValueError('Channel did not move to READY')
- channel.unsubscribe(parent_connectivity_callback)
- child_process.finish()
-
-
-def _ping_pong_with_child_processes_after_first_response(
- channel, args, child_target, run_after_close=True):
- request_response_sizes = (
- 31415,
- 9,
- 2653,
- 58979,
- )
- request_payload_sizes = (
- 27182,
- 8,
- 1828,
- 45904,
- )
- stub = test_pb2_grpc.TestServiceStub(channel)
- pipe = _Pipe()
- parent_bidi_call = stub.FullDuplexCall(pipe)
- child_processes = []
- first_message_received = False
- for response_size, payload_size in zip(request_response_sizes,
- request_payload_sizes):
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
+# Copyright 2018 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.
+"""Implementations of fork support test methods."""
+
+import enum
+import json
+import logging
+import multiprocessing
+import os
+import threading
+import time
+
+import grpc
+
+from six.moves import queue
+
+from src.proto.grpc.testing import empty_pb2
+from src.proto.grpc.testing import messages_pb2
+from src.proto.grpc.testing import test_pb2_grpc
+
+_LOGGER = logging.getLogger(__name__)
+_RPC_TIMEOUT_S = 10
+_CHILD_FINISH_TIMEOUT_S = 60
+
+
+def _channel(args):
+ target = '{}:{}'.format(args['server_host'], args['server_port'])
+ if args['use_tls']:
+ channel_credentials = grpc.ssl_channel_credentials()
+ channel = grpc.secure_channel(target, channel_credentials)
+ else:
+ channel = grpc.insecure_channel(target)
+ return channel
+
+
+def _validate_payload_type_and_length(response, expected_type, expected_length):
+ if response.payload.type is not expected_type:
+ raise ValueError('expected payload type %s, got %s' %
+ (expected_type, type(response.payload.type)))
+ elif len(response.payload.body) != expected_length:
+ raise ValueError('expected payload body size %d, got %d' %
+ (expected_length, len(response.payload.body)))
+
+
+def _async_unary(stub):
+ size = 314159
+ request = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=size,
+ payload=messages_pb2.Payload(body=b'\x00' * 271828))
+ response_future = stub.UnaryCall.future(request, timeout=_RPC_TIMEOUT_S)
+ response = response_future.result()
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
+
+
+def _blocking_unary(stub):
+ size = 314159
+ request = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=size,
+ payload=messages_pb2.Payload(body=b'\x00' * 271828))
+ response = stub.UnaryCall(request, timeout=_RPC_TIMEOUT_S)
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
+
+
+class _Pipe(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._values = []
+ self._open = True
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return self.next()
+
+ def next(self):
+ with self._condition:
+ while not self._values and self._open:
+ self._condition.wait()
+ if self._values:
+ return self._values.pop(0)
+ else:
+ raise StopIteration()
+
+ def add(self, value):
+ with self._condition:
+ self._values.append(value)
+ self._condition.notify()
+
+ def close(self):
+ with self._condition:
+ self._open = False
+ self._condition.notify()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+
+class _ChildProcess(object):
+
+ def __init__(self, task, args=None):
+ if args is None:
+ args = ()
+ self._exceptions = multiprocessing.Queue()
+
+ def record_exceptions():
+ try:
+ task(*args)
+ except grpc.RpcError as rpc_error:
+ self._exceptions.put('RpcError: %s' % rpc_error)
+ except Exception as e: # pylint: disable=broad-except
+ self._exceptions.put(e)
+
+ self._process = multiprocessing.Process(target=record_exceptions)
+
+ def start(self):
+ self._process.start()
+
+ def finish(self):
+ self._process.join(timeout=_CHILD_FINISH_TIMEOUT_S)
+ if self._process.is_alive():
+ raise RuntimeError('Child process did not terminate')
+ if self._process.exitcode != 0:
+ raise ValueError('Child process failed with exitcode %d' %
+ self._process.exitcode)
+ try:
+ exception = self._exceptions.get(block=False)
+ raise ValueError('Child process failed: %s' % exception)
+ except queue.Empty:
+ pass
+
+
+def _async_unary_same_channel(channel):
+
+ def child_target():
+ try:
+ _async_unary(stub)
+ raise Exception(
+ 'Child should not be able to re-use channel after fork')
+ except ValueError as expected_value_error:
+ pass
+
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _async_unary(stub)
+ child_process = _ChildProcess(child_target)
+ child_process.start()
+ _async_unary(stub)
+ child_process.finish()
+
+
+def _async_unary_new_channel(channel, args):
+
+ def child_target():
+ with _channel(args) as child_channel:
+ child_stub = test_pb2_grpc.TestServiceStub(child_channel)
+ _async_unary(child_stub)
+ child_channel.close()
+
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _async_unary(stub)
+ child_process = _ChildProcess(child_target)
+ child_process.start()
+ _async_unary(stub)
+ child_process.finish()
+
+
+def _blocking_unary_same_channel(channel):
+
+ def child_target():
+ try:
+ _blocking_unary(stub)
+ raise Exception(
+ 'Child should not be able to re-use channel after fork')
+ except ValueError as expected_value_error:
+ pass
+
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _blocking_unary(stub)
+ child_process = _ChildProcess(child_target)
+ child_process.start()
+ child_process.finish()
+
+
+def _blocking_unary_new_channel(channel, args):
+
+ def child_target():
+ with _channel(args) as child_channel:
+ child_stub = test_pb2_grpc.TestServiceStub(child_channel)
+ _blocking_unary(child_stub)
+
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _blocking_unary(stub)
+ child_process = _ChildProcess(child_target)
+ child_process.start()
+ _blocking_unary(stub)
+ child_process.finish()
+
+
+# Verify that the fork channel registry can handle already closed channels
+def _close_channel_before_fork(channel, args):
+
+ def child_target():
+ new_channel.close()
+ with _channel(args) as child_channel:
+ child_stub = test_pb2_grpc.TestServiceStub(child_channel)
+ _blocking_unary(child_stub)
+
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _blocking_unary(stub)
+ channel.close()
+
+ with _channel(args) as new_channel:
+ new_stub = test_pb2_grpc.TestServiceStub(new_channel)
+ child_process = _ChildProcess(child_target)
+ child_process.start()
+ _blocking_unary(new_stub)
+ child_process.finish()
+
+
+def _connectivity_watch(channel, args):
+
+ parent_states = []
+ parent_channel_ready_event = threading.Event()
+
+ def child_target():
+
+ child_channel_ready_event = threading.Event()
+
+ def child_connectivity_callback(state):
+ if state is grpc.ChannelConnectivity.READY:
+ child_channel_ready_event.set()
+
+ with _channel(args) as child_channel:
+ child_stub = test_pb2_grpc.TestServiceStub(child_channel)
+ child_channel.subscribe(child_connectivity_callback)
+ _async_unary(child_stub)
+ if not child_channel_ready_event.wait(timeout=_RPC_TIMEOUT_S):
+ raise ValueError('Channel did not move to READY')
+ if len(parent_states) > 1:
+ raise ValueError(
+ 'Received connectivity updates on parent callback',
+ parent_states)
+ child_channel.unsubscribe(child_connectivity_callback)
+
+ def parent_connectivity_callback(state):
+ parent_states.append(state)
+ if state is grpc.ChannelConnectivity.READY:
+ parent_channel_ready_event.set()
+
+ channel.subscribe(parent_connectivity_callback)
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ child_process = _ChildProcess(child_target)
+ child_process.start()
+ _async_unary(stub)
+ if not parent_channel_ready_event.wait(timeout=_RPC_TIMEOUT_S):
+ raise ValueError('Channel did not move to READY')
+ channel.unsubscribe(parent_connectivity_callback)
+ child_process.finish()
+
+
+def _ping_pong_with_child_processes_after_first_response(
+ channel, args, child_target, run_after_close=True):
+ request_response_sizes = (
+ 31415,
+ 9,
+ 2653,
+ 58979,
+ )
+ request_payload_sizes = (
+ 27182,
+ 8,
+ 1828,
+ 45904,
+ )
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ pipe = _Pipe()
+ parent_bidi_call = stub.FullDuplexCall(pipe)
+ child_processes = []
+ first_message_received = False
+ for response_size, payload_size in zip(request_response_sizes,
+ request_payload_sizes):
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(
size=response_size),),
- payload=messages_pb2.Payload(body=b'\x00' * payload_size))
- pipe.add(request)
- if first_message_received:
- child_process = _ChildProcess(child_target,
- (parent_bidi_call, channel, args))
- child_process.start()
- child_processes.append(child_process)
- response = next(parent_bidi_call)
- first_message_received = True
- child_process = _ChildProcess(child_target,
- (parent_bidi_call, channel, args))
- child_process.start()
- child_processes.append(child_process)
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
- response_size)
- pipe.close()
- if run_after_close:
- child_process = _ChildProcess(child_target,
- (parent_bidi_call, channel, args))
- child_process.start()
- child_processes.append(child_process)
- for child_process in child_processes:
- child_process.finish()
-
-
-def _in_progress_bidi_continue_call(channel):
-
- def child_target(parent_bidi_call, parent_channel, args):
- stub = test_pb2_grpc.TestServiceStub(parent_channel)
- try:
- _async_unary(stub)
- raise Exception(
- 'Child should not be able to re-use channel after fork')
- except ValueError as expected_value_error:
- pass
- inherited_code = parent_bidi_call.code()
- inherited_details = parent_bidi_call.details()
- if inherited_code != grpc.StatusCode.CANCELLED:
+ payload=messages_pb2.Payload(body=b'\x00' * payload_size))
+ pipe.add(request)
+ if first_message_received:
+ child_process = _ChildProcess(child_target,
+ (parent_bidi_call, channel, args))
+ child_process.start()
+ child_processes.append(child_process)
+ response = next(parent_bidi_call)
+ first_message_received = True
+ child_process = _ChildProcess(child_target,
+ (parent_bidi_call, channel, args))
+ child_process.start()
+ child_processes.append(child_process)
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
+ response_size)
+ pipe.close()
+ if run_after_close:
+ child_process = _ChildProcess(child_target,
+ (parent_bidi_call, channel, args))
+ child_process.start()
+ child_processes.append(child_process)
+ for child_process in child_processes:
+ child_process.finish()
+
+
+def _in_progress_bidi_continue_call(channel):
+
+ def child_target(parent_bidi_call, parent_channel, args):
+ stub = test_pb2_grpc.TestServiceStub(parent_channel)
+ try:
+ _async_unary(stub)
+ raise Exception(
+ 'Child should not be able to re-use channel after fork')
+ except ValueError as expected_value_error:
+ pass
+ inherited_code = parent_bidi_call.code()
+ inherited_details = parent_bidi_call.details()
+ if inherited_code != grpc.StatusCode.CANCELLED:
raise ValueError('Expected inherited code CANCELLED, got %s' %
inherited_code)
- if inherited_details != 'Channel closed due to fork':
- raise ValueError(
- 'Expected inherited details Channel closed due to fork, got %s'
- % inherited_details)
-
- # Don't run child_target after closing the parent call, as the call may have
- # received a status from the server before fork occurs.
+ if inherited_details != 'Channel closed due to fork':
+ raise ValueError(
+ 'Expected inherited details Channel closed due to fork, got %s'
+ % inherited_details)
+
+ # Don't run child_target after closing the parent call, as the call may have
+ # received a status from the server before fork occurs.
_ping_pong_with_child_processes_after_first_response(channel,
None,
child_target,
run_after_close=False)
-
-
-def _in_progress_bidi_same_channel_async_call(channel):
-
- def child_target(parent_bidi_call, parent_channel, args):
- stub = test_pb2_grpc.TestServiceStub(parent_channel)
- try:
- _async_unary(stub)
- raise Exception(
- 'Child should not be able to re-use channel after fork')
- except ValueError as expected_value_error:
- pass
-
- _ping_pong_with_child_processes_after_first_response(
- channel, None, child_target)
-
-
-def _in_progress_bidi_same_channel_blocking_call(channel):
-
- def child_target(parent_bidi_call, parent_channel, args):
- stub = test_pb2_grpc.TestServiceStub(parent_channel)
- try:
- _blocking_unary(stub)
- raise Exception(
- 'Child should not be able to re-use channel after fork')
- except ValueError as expected_value_error:
- pass
-
- _ping_pong_with_child_processes_after_first_response(
- channel, None, child_target)
-
-
-def _in_progress_bidi_new_channel_async_call(channel, args):
-
- def child_target(parent_bidi_call, parent_channel, args):
- with _channel(args) as channel:
- stub = test_pb2_grpc.TestServiceStub(channel)
- _async_unary(stub)
-
- _ping_pong_with_child_processes_after_first_response(
- channel, args, child_target)
-
-
-def _in_progress_bidi_new_channel_blocking_call(channel, args):
-
- def child_target(parent_bidi_call, parent_channel, args):
- with _channel(args) as channel:
- stub = test_pb2_grpc.TestServiceStub(channel)
- _blocking_unary(stub)
-
- _ping_pong_with_child_processes_after_first_response(
- channel, args, child_target)
-
-
-@enum.unique
-class TestCase(enum.Enum):
-
- CONNECTIVITY_WATCH = 'connectivity_watch'
- CLOSE_CHANNEL_BEFORE_FORK = 'close_channel_before_fork'
- ASYNC_UNARY_SAME_CHANNEL = 'async_unary_same_channel'
- ASYNC_UNARY_NEW_CHANNEL = 'async_unary_new_channel'
- BLOCKING_UNARY_SAME_CHANNEL = 'blocking_unary_same_channel'
- BLOCKING_UNARY_NEW_CHANNEL = 'blocking_unary_new_channel'
- IN_PROGRESS_BIDI_CONTINUE_CALL = 'in_progress_bidi_continue_call'
- IN_PROGRESS_BIDI_SAME_CHANNEL_ASYNC_CALL = 'in_progress_bidi_same_channel_async_call'
- IN_PROGRESS_BIDI_SAME_CHANNEL_BLOCKING_CALL = 'in_progress_bidi_same_channel_blocking_call'
- IN_PROGRESS_BIDI_NEW_CHANNEL_ASYNC_CALL = 'in_progress_bidi_new_channel_async_call'
- IN_PROGRESS_BIDI_NEW_CHANNEL_BLOCKING_CALL = 'in_progress_bidi_new_channel_blocking_call'
-
- def run_test(self, args):
- _LOGGER.info("Running %s", self)
- channel = _channel(args)
- if self is TestCase.ASYNC_UNARY_SAME_CHANNEL:
- _async_unary_same_channel(channel)
- elif self is TestCase.ASYNC_UNARY_NEW_CHANNEL:
- _async_unary_new_channel(channel, args)
- elif self is TestCase.BLOCKING_UNARY_SAME_CHANNEL:
- _blocking_unary_same_channel(channel)
- elif self is TestCase.BLOCKING_UNARY_NEW_CHANNEL:
- _blocking_unary_new_channel(channel, args)
- elif self is TestCase.CLOSE_CHANNEL_BEFORE_FORK:
- _close_channel_before_fork(channel, args)
- elif self is TestCase.CONNECTIVITY_WATCH:
- _connectivity_watch(channel, args)
- elif self is TestCase.IN_PROGRESS_BIDI_CONTINUE_CALL:
- _in_progress_bidi_continue_call(channel)
- elif self is TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_ASYNC_CALL:
- _in_progress_bidi_same_channel_async_call(channel)
- elif self is TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_BLOCKING_CALL:
- _in_progress_bidi_same_channel_blocking_call(channel)
- elif self is TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_ASYNC_CALL:
- _in_progress_bidi_new_channel_async_call(channel, args)
- elif self is TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_BLOCKING_CALL:
- _in_progress_bidi_new_channel_blocking_call(channel, args)
- else:
+
+
+def _in_progress_bidi_same_channel_async_call(channel):
+
+ def child_target(parent_bidi_call, parent_channel, args):
+ stub = test_pb2_grpc.TestServiceStub(parent_channel)
+ try:
+ _async_unary(stub)
+ raise Exception(
+ 'Child should not be able to re-use channel after fork')
+ except ValueError as expected_value_error:
+ pass
+
+ _ping_pong_with_child_processes_after_first_response(
+ channel, None, child_target)
+
+
+def _in_progress_bidi_same_channel_blocking_call(channel):
+
+ def child_target(parent_bidi_call, parent_channel, args):
+ stub = test_pb2_grpc.TestServiceStub(parent_channel)
+ try:
+ _blocking_unary(stub)
+ raise Exception(
+ 'Child should not be able to re-use channel after fork')
+ except ValueError as expected_value_error:
+ pass
+
+ _ping_pong_with_child_processes_after_first_response(
+ channel, None, child_target)
+
+
+def _in_progress_bidi_new_channel_async_call(channel, args):
+
+ def child_target(parent_bidi_call, parent_channel, args):
+ with _channel(args) as channel:
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _async_unary(stub)
+
+ _ping_pong_with_child_processes_after_first_response(
+ channel, args, child_target)
+
+
+def _in_progress_bidi_new_channel_blocking_call(channel, args):
+
+ def child_target(parent_bidi_call, parent_channel, args):
+ with _channel(args) as channel:
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ _blocking_unary(stub)
+
+ _ping_pong_with_child_processes_after_first_response(
+ channel, args, child_target)
+
+
+@enum.unique
+class TestCase(enum.Enum):
+
+ CONNECTIVITY_WATCH = 'connectivity_watch'
+ CLOSE_CHANNEL_BEFORE_FORK = 'close_channel_before_fork'
+ ASYNC_UNARY_SAME_CHANNEL = 'async_unary_same_channel'
+ ASYNC_UNARY_NEW_CHANNEL = 'async_unary_new_channel'
+ BLOCKING_UNARY_SAME_CHANNEL = 'blocking_unary_same_channel'
+ BLOCKING_UNARY_NEW_CHANNEL = 'blocking_unary_new_channel'
+ IN_PROGRESS_BIDI_CONTINUE_CALL = 'in_progress_bidi_continue_call'
+ IN_PROGRESS_BIDI_SAME_CHANNEL_ASYNC_CALL = 'in_progress_bidi_same_channel_async_call'
+ IN_PROGRESS_BIDI_SAME_CHANNEL_BLOCKING_CALL = 'in_progress_bidi_same_channel_blocking_call'
+ IN_PROGRESS_BIDI_NEW_CHANNEL_ASYNC_CALL = 'in_progress_bidi_new_channel_async_call'
+ IN_PROGRESS_BIDI_NEW_CHANNEL_BLOCKING_CALL = 'in_progress_bidi_new_channel_blocking_call'
+
+ def run_test(self, args):
+ _LOGGER.info("Running %s", self)
+ channel = _channel(args)
+ if self is TestCase.ASYNC_UNARY_SAME_CHANNEL:
+ _async_unary_same_channel(channel)
+ elif self is TestCase.ASYNC_UNARY_NEW_CHANNEL:
+ _async_unary_new_channel(channel, args)
+ elif self is TestCase.BLOCKING_UNARY_SAME_CHANNEL:
+ _blocking_unary_same_channel(channel)
+ elif self is TestCase.BLOCKING_UNARY_NEW_CHANNEL:
+ _blocking_unary_new_channel(channel, args)
+ elif self is TestCase.CLOSE_CHANNEL_BEFORE_FORK:
+ _close_channel_before_fork(channel, args)
+ elif self is TestCase.CONNECTIVITY_WATCH:
+ _connectivity_watch(channel, args)
+ elif self is TestCase.IN_PROGRESS_BIDI_CONTINUE_CALL:
+ _in_progress_bidi_continue_call(channel)
+ elif self is TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_ASYNC_CALL:
+ _in_progress_bidi_same_channel_async_call(channel)
+ elif self is TestCase.IN_PROGRESS_BIDI_SAME_CHANNEL_BLOCKING_CALL:
+ _in_progress_bidi_same_channel_blocking_call(channel)
+ elif self is TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_ASYNC_CALL:
+ _in_progress_bidi_new_channel_async_call(channel, args)
+ elif self is TestCase.IN_PROGRESS_BIDI_NEW_CHANNEL_BLOCKING_CALL:
+ _in_progress_bidi_new_channel_blocking_call(channel, args)
+ else:
raise NotImplementedError('Test case "%s" not implemented!' %
self.name)
- channel.close()
+ channel.close()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/__init__.py
index 5772620b60..8d89990e82 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 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.
+# Copyright 2016 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/_health_servicer_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/_health_servicer_test.py
index 01345aaca0..9484a9edde 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/_health_servicer_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/health_check/_health_servicer_test.py
@@ -1,282 +1,282 @@
-# Copyright 2016 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.
-"""Tests of grpc_health.v1.health."""
-
-import logging
-import threading
-import time
-import unittest
-
-import grpc
-
-from grpc_health.v1 import health
-from grpc_health.v1 import health_pb2
-from grpc_health.v1 import health_pb2_grpc
-
-from tests.unit import test_common
-from tests.unit import thread_pool
-from tests.unit.framework.common import test_constants
-
-from six.moves import queue
-
-_SERVING_SERVICE = 'grpc.test.TestServiceServing'
-_UNKNOWN_SERVICE = 'grpc.test.TestServiceUnknown'
-_NOT_SERVING_SERVICE = 'grpc.test.TestServiceNotServing'
-_WATCH_SERVICE = 'grpc.test.WatchService'
-
-
-def _consume_responses(response_iterator, response_queue):
- for response in response_iterator:
- response_queue.put(response)
-
-
-class BaseWatchTests(object):
-
- class WatchTests(unittest.TestCase):
-
- def start_server(self, non_blocking=False, thread_pool=None):
- self._thread_pool = thread_pool
- self._servicer = health.HealthServicer(
- experimental_non_blocking=non_blocking,
- experimental_thread_pool=thread_pool)
- self._servicer.set(_SERVING_SERVICE,
- health_pb2.HealthCheckResponse.SERVING)
- self._servicer.set(_UNKNOWN_SERVICE,
- health_pb2.HealthCheckResponse.UNKNOWN)
- self._servicer.set(_NOT_SERVING_SERVICE,
- health_pb2.HealthCheckResponse.NOT_SERVING)
- self._server = test_common.test_server()
- port = self._server.add_insecure_port('[::]:0')
- health_pb2_grpc.add_HealthServicer_to_server(
- self._servicer, self._server)
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
- self._stub = health_pb2_grpc.HealthStub(self._channel)
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def test_watch_empty_service(self):
- request = health_pb2.HealthCheckRequest(service='')
- response_queue = queue.Queue()
- rendezvous = self._stub.Watch(request)
+# Copyright 2016 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.
+"""Tests of grpc_health.v1.health."""
+
+import logging
+import threading
+import time
+import unittest
+
+import grpc
+
+from grpc_health.v1 import health
+from grpc_health.v1 import health_pb2
+from grpc_health.v1 import health_pb2_grpc
+
+from tests.unit import test_common
+from tests.unit import thread_pool
+from tests.unit.framework.common import test_constants
+
+from six.moves import queue
+
+_SERVING_SERVICE = 'grpc.test.TestServiceServing'
+_UNKNOWN_SERVICE = 'grpc.test.TestServiceUnknown'
+_NOT_SERVING_SERVICE = 'grpc.test.TestServiceNotServing'
+_WATCH_SERVICE = 'grpc.test.WatchService'
+
+
+def _consume_responses(response_iterator, response_queue):
+ for response in response_iterator:
+ response_queue.put(response)
+
+
+class BaseWatchTests(object):
+
+ class WatchTests(unittest.TestCase):
+
+ def start_server(self, non_blocking=False, thread_pool=None):
+ self._thread_pool = thread_pool
+ self._servicer = health.HealthServicer(
+ experimental_non_blocking=non_blocking,
+ experimental_thread_pool=thread_pool)
+ self._servicer.set(_SERVING_SERVICE,
+ health_pb2.HealthCheckResponse.SERVING)
+ self._servicer.set(_UNKNOWN_SERVICE,
+ health_pb2.HealthCheckResponse.UNKNOWN)
+ self._servicer.set(_NOT_SERVING_SERVICE,
+ health_pb2.HealthCheckResponse.NOT_SERVING)
+ self._server = test_common.test_server()
+ port = self._server.add_insecure_port('[::]:0')
+ health_pb2_grpc.add_HealthServicer_to_server(
+ self._servicer, self._server)
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+ self._stub = health_pb2_grpc.HealthStub(self._channel)
+
+ def tearDown(self):
+ self._server.stop(None)
+ self._channel.close()
+
+ def test_watch_empty_service(self):
+ request = health_pb2.HealthCheckRequest(service='')
+ response_queue = queue.Queue()
+ rendezvous = self._stub.Watch(request)
thread = threading.Thread(target=_consume_responses,
args=(rendezvous, response_queue))
- thread.start()
-
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
- response.status)
-
- rendezvous.cancel()
- thread.join()
- self.assertTrue(response_queue.empty())
-
- if self._thread_pool is not None:
- self.assertTrue(self._thread_pool.was_used())
-
- def test_watch_new_service(self):
- request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
- response_queue = queue.Queue()
- rendezvous = self._stub.Watch(request)
+ thread.start()
+
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
+ response.status)
+
+ rendezvous.cancel()
+ thread.join()
+ self.assertTrue(response_queue.empty())
+
+ if self._thread_pool is not None:
+ self.assertTrue(self._thread_pool.was_used())
+
+ def test_watch_new_service(self):
+ request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
+ response_queue = queue.Queue()
+ rendezvous = self._stub.Watch(request)
thread = threading.Thread(target=_consume_responses,
args=(rendezvous, response_queue))
- thread.start()
-
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
- response.status)
-
- self._servicer.set(_WATCH_SERVICE,
- health_pb2.HealthCheckResponse.SERVING)
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
- response.status)
-
- self._servicer.set(_WATCH_SERVICE,
- health_pb2.HealthCheckResponse.NOT_SERVING)
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.NOT_SERVING,
- response.status)
-
- rendezvous.cancel()
- thread.join()
- self.assertTrue(response_queue.empty())
-
- def test_watch_service_isolation(self):
- request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
- response_queue = queue.Queue()
- rendezvous = self._stub.Watch(request)
+ thread.start()
+
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
+ response.status)
+
+ self._servicer.set(_WATCH_SERVICE,
+ health_pb2.HealthCheckResponse.SERVING)
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
+ response.status)
+
+ self._servicer.set(_WATCH_SERVICE,
+ health_pb2.HealthCheckResponse.NOT_SERVING)
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.NOT_SERVING,
+ response.status)
+
+ rendezvous.cancel()
+ thread.join()
+ self.assertTrue(response_queue.empty())
+
+ def test_watch_service_isolation(self):
+ request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
+ response_queue = queue.Queue()
+ rendezvous = self._stub.Watch(request)
thread = threading.Thread(target=_consume_responses,
args=(rendezvous, response_queue))
- thread.start()
-
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
- response.status)
-
- self._servicer.set('some-other-service',
- health_pb2.HealthCheckResponse.SERVING)
- with self.assertRaises(queue.Empty):
- response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
-
- rendezvous.cancel()
- thread.join()
- self.assertTrue(response_queue.empty())
-
- def test_two_watchers(self):
- request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
- response_queue1 = queue.Queue()
- response_queue2 = queue.Queue()
- rendezvous1 = self._stub.Watch(request)
- rendezvous2 = self._stub.Watch(request)
+ thread.start()
+
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
+ response.status)
+
+ self._servicer.set('some-other-service',
+ health_pb2.HealthCheckResponse.SERVING)
+ with self.assertRaises(queue.Empty):
+ response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+
+ rendezvous.cancel()
+ thread.join()
+ self.assertTrue(response_queue.empty())
+
+ def test_two_watchers(self):
+ request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
+ response_queue1 = queue.Queue()
+ response_queue2 = queue.Queue()
+ rendezvous1 = self._stub.Watch(request)
+ rendezvous2 = self._stub.Watch(request)
thread1 = threading.Thread(target=_consume_responses,
args=(rendezvous1, response_queue1))
thread2 = threading.Thread(target=_consume_responses,
args=(rendezvous2, response_queue2))
- thread1.start()
- thread2.start()
-
- response1 = response_queue1.get(
- timeout=test_constants.SHORT_TIMEOUT)
- response2 = response_queue2.get(
- timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
- response1.status)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
- response2.status)
-
- self._servicer.set(_WATCH_SERVICE,
- health_pb2.HealthCheckResponse.SERVING)
- response1 = response_queue1.get(
- timeout=test_constants.SHORT_TIMEOUT)
- response2 = response_queue2.get(
- timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
- response1.status)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
- response2.status)
-
- rendezvous1.cancel()
- rendezvous2.cancel()
- thread1.join()
- thread2.join()
- self.assertTrue(response_queue1.empty())
- self.assertTrue(response_queue2.empty())
-
- @unittest.skip("https://github.com/grpc/grpc/issues/18127")
- def test_cancelled_watch_removed_from_watch_list(self):
- request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
- response_queue = queue.Queue()
- rendezvous = self._stub.Watch(request)
+ thread1.start()
+ thread2.start()
+
+ response1 = response_queue1.get(
+ timeout=test_constants.SHORT_TIMEOUT)
+ response2 = response_queue2.get(
+ timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
+ response1.status)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
+ response2.status)
+
+ self._servicer.set(_WATCH_SERVICE,
+ health_pb2.HealthCheckResponse.SERVING)
+ response1 = response_queue1.get(
+ timeout=test_constants.SHORT_TIMEOUT)
+ response2 = response_queue2.get(
+ timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
+ response1.status)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
+ response2.status)
+
+ rendezvous1.cancel()
+ rendezvous2.cancel()
+ thread1.join()
+ thread2.join()
+ self.assertTrue(response_queue1.empty())
+ self.assertTrue(response_queue2.empty())
+
+ @unittest.skip("https://github.com/grpc/grpc/issues/18127")
+ def test_cancelled_watch_removed_from_watch_list(self):
+ request = health_pb2.HealthCheckRequest(service=_WATCH_SERVICE)
+ response_queue = queue.Queue()
+ rendezvous = self._stub.Watch(request)
thread = threading.Thread(target=_consume_responses,
args=(rendezvous, response_queue))
- thread.start()
-
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
- response.status)
-
- rendezvous.cancel()
- self._servicer.set(_WATCH_SERVICE,
- health_pb2.HealthCheckResponse.SERVING)
- thread.join()
-
- # Wait, if necessary, for serving thread to process client cancellation
- timeout = time.time() + test_constants.TIME_ALLOWANCE
+ thread.start()
+
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVICE_UNKNOWN,
+ response.status)
+
+ rendezvous.cancel()
+ self._servicer.set(_WATCH_SERVICE,
+ health_pb2.HealthCheckResponse.SERVING)
+ thread.join()
+
+ # Wait, if necessary, for serving thread to process client cancellation
+ timeout = time.time() + test_constants.TIME_ALLOWANCE
while (time.time() < timeout and
self._servicer._send_response_callbacks[_WATCH_SERVICE]):
- time.sleep(1)
- self.assertFalse(
- self._servicer._send_response_callbacks[_WATCH_SERVICE],
- 'watch set should be empty')
- self.assertTrue(response_queue.empty())
-
- def test_graceful_shutdown(self):
- request = health_pb2.HealthCheckRequest(service='')
- response_queue = queue.Queue()
- rendezvous = self._stub.Watch(request)
+ time.sleep(1)
+ self.assertFalse(
+ self._servicer._send_response_callbacks[_WATCH_SERVICE],
+ 'watch set should be empty')
+ self.assertTrue(response_queue.empty())
+
+ def test_graceful_shutdown(self):
+ request = health_pb2.HealthCheckRequest(service='')
+ response_queue = queue.Queue()
+ rendezvous = self._stub.Watch(request)
thread = threading.Thread(target=_consume_responses,
args=(rendezvous, response_queue))
- thread.start()
-
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
- response.status)
-
- self._servicer.enter_graceful_shutdown()
- response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
- self.assertEqual(health_pb2.HealthCheckResponse.NOT_SERVING,
- response.status)
-
- # This should be a no-op.
- self._servicer.set('', health_pb2.HealthCheckResponse.SERVING)
-
- rendezvous.cancel()
- thread.join()
- self.assertTrue(response_queue.empty())
-
-
-class HealthServicerTest(BaseWatchTests.WatchTests):
-
- def setUp(self):
- self._thread_pool = thread_pool.RecordingThreadPool(max_workers=None)
+ thread.start()
+
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING,
+ response.status)
+
+ self._servicer.enter_graceful_shutdown()
+ response = response_queue.get(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertEqual(health_pb2.HealthCheckResponse.NOT_SERVING,
+ response.status)
+
+ # This should be a no-op.
+ self._servicer.set('', health_pb2.HealthCheckResponse.SERVING)
+
+ rendezvous.cancel()
+ thread.join()
+ self.assertTrue(response_queue.empty())
+
+
+class HealthServicerTest(BaseWatchTests.WatchTests):
+
+ def setUp(self):
+ self._thread_pool = thread_pool.RecordingThreadPool(max_workers=None)
super(HealthServicerTest,
self).start_server(non_blocking=True,
thread_pool=self._thread_pool)
-
- def test_check_empty_service(self):
- request = health_pb2.HealthCheckRequest()
- resp = self._stub.Check(request)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING, resp.status)
-
- def test_check_serving_service(self):
- request = health_pb2.HealthCheckRequest(service=_SERVING_SERVICE)
- resp = self._stub.Check(request)
- self.assertEqual(health_pb2.HealthCheckResponse.SERVING, resp.status)
-
- def test_check_unknown_service(self):
- request = health_pb2.HealthCheckRequest(service=_UNKNOWN_SERVICE)
- resp = self._stub.Check(request)
- self.assertEqual(health_pb2.HealthCheckResponse.UNKNOWN, resp.status)
-
- def test_check_not_serving_service(self):
- request = health_pb2.HealthCheckRequest(service=_NOT_SERVING_SERVICE)
- resp = self._stub.Check(request)
- self.assertEqual(health_pb2.HealthCheckResponse.NOT_SERVING,
- resp.status)
-
- def test_check_not_found_service(self):
- request = health_pb2.HealthCheckRequest(service='not-found')
- with self.assertRaises(grpc.RpcError) as context:
- resp = self._stub.Check(request)
-
- self.assertEqual(grpc.StatusCode.NOT_FOUND, context.exception.code())
-
- def test_health_service_name(self):
- self.assertEqual(health.SERVICE_NAME, 'grpc.health.v1.Health')
-
-
-class HealthServicerBackwardsCompatibleWatchTest(BaseWatchTests.WatchTests):
-
- def setUp(self):
+
+ def test_check_empty_service(self):
+ request = health_pb2.HealthCheckRequest()
+ resp = self._stub.Check(request)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING, resp.status)
+
+ def test_check_serving_service(self):
+ request = health_pb2.HealthCheckRequest(service=_SERVING_SERVICE)
+ resp = self._stub.Check(request)
+ self.assertEqual(health_pb2.HealthCheckResponse.SERVING, resp.status)
+
+ def test_check_unknown_service(self):
+ request = health_pb2.HealthCheckRequest(service=_UNKNOWN_SERVICE)
+ resp = self._stub.Check(request)
+ self.assertEqual(health_pb2.HealthCheckResponse.UNKNOWN, resp.status)
+
+ def test_check_not_serving_service(self):
+ request = health_pb2.HealthCheckRequest(service=_NOT_SERVING_SERVICE)
+ resp = self._stub.Check(request)
+ self.assertEqual(health_pb2.HealthCheckResponse.NOT_SERVING,
+ resp.status)
+
+ def test_check_not_found_service(self):
+ request = health_pb2.HealthCheckRequest(service='not-found')
+ with self.assertRaises(grpc.RpcError) as context:
+ resp = self._stub.Check(request)
+
+ self.assertEqual(grpc.StatusCode.NOT_FOUND, context.exception.code())
+
+ def test_health_service_name(self):
+ self.assertEqual(health.SERVICE_NAME, 'grpc.health.v1.Health')
+
+
+class HealthServicerBackwardsCompatibleWatchTest(BaseWatchTests.WatchTests):
+
+ def setUp(self):
super(HealthServicerBackwardsCompatibleWatchTest,
self).start_server(non_blocking=False, thread_pool=None)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/http2/negative_http2_client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/http2/negative_http2_client.py
index 0753872b5e..05e65243e1 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/http2/negative_http2_client.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/http2/negative_http2_client.py
@@ -1,131 +1,131 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""The Python client used to test negative http2 conditions."""
-
-import argparse
-
-import grpc
-import time
-from src.proto.grpc.testing import test_pb2_grpc
-from src.proto.grpc.testing import messages_pb2
-
-
-def _validate_payload_type_and_length(response, expected_type, expected_length):
- if response.payload.type is not expected_type:
- raise ValueError('expected payload type %s, got %s' %
- (expected_type, type(response.payload.type)))
- elif len(response.payload.body) != expected_length:
- raise ValueError('expected payload body size %d, got %d' %
- (expected_length, len(response.payload.body)))
-
-
-def _expect_status_code(call, expected_code):
- if call.code() != expected_code:
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python client used to test negative http2 conditions."""
+
+import argparse
+
+import grpc
+import time
+from src.proto.grpc.testing import test_pb2_grpc
+from src.proto.grpc.testing import messages_pb2
+
+
+def _validate_payload_type_and_length(response, expected_type, expected_length):
+ if response.payload.type is not expected_type:
+ raise ValueError('expected payload type %s, got %s' %
+ (expected_type, type(response.payload.type)))
+ elif len(response.payload.body) != expected_length:
+ raise ValueError('expected payload body size %d, got %d' %
+ (expected_length, len(response.payload.body)))
+
+
+def _expect_status_code(call, expected_code):
+ if call.code() != expected_code:
raise ValueError('expected code %s, got %s' %
(expected_code, call.code()))
-
-
-def _expect_status_details(call, expected_details):
- if call.details() != expected_details:
+
+
+def _expect_status_details(call, expected_details):
+ if call.details() != expected_details:
raise ValueError('expected message %s, got %s' %
(expected_details, call.details()))
-
-
-def _validate_status_code_and_details(call, expected_code, expected_details):
- _expect_status_code(call, expected_code)
- _expect_status_details(call, expected_details)
-
-
-# common requests
-_REQUEST_SIZE = 314159
-_RESPONSE_SIZE = 271828
-
-_SIMPLE_REQUEST = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=_RESPONSE_SIZE,
- payload=messages_pb2.Payload(body=b'\x00' * _REQUEST_SIZE))
-
-
-def _goaway(stub):
- first_response = stub.UnaryCall(_SIMPLE_REQUEST)
- _validate_payload_type_and_length(first_response, messages_pb2.COMPRESSABLE,
- _RESPONSE_SIZE)
- time.sleep(1)
- second_response = stub.UnaryCall(_SIMPLE_REQUEST)
- _validate_payload_type_and_length(second_response,
- messages_pb2.COMPRESSABLE, _RESPONSE_SIZE)
-
-
-def _rst_after_header(stub):
- resp_future = stub.UnaryCall.future(_SIMPLE_REQUEST)
- _validate_status_code_and_details(resp_future, grpc.StatusCode.INTERNAL,
- "Received RST_STREAM with error code 0")
-
-
-def _rst_during_data(stub):
- resp_future = stub.UnaryCall.future(_SIMPLE_REQUEST)
- _validate_status_code_and_details(resp_future, grpc.StatusCode.INTERNAL,
- "Received RST_STREAM with error code 0")
-
-
-def _rst_after_data(stub):
- resp_future = stub.UnaryCall.future(_SIMPLE_REQUEST)
- _validate_status_code_and_details(resp_future, grpc.StatusCode.INTERNAL,
- "Received RST_STREAM with error code 0")
-
-
-def _ping(stub):
- response = stub.UnaryCall(_SIMPLE_REQUEST)
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
- _RESPONSE_SIZE)
-
-
-def _max_streams(stub):
- # send one req to ensure server sets MAX_STREAMS
- response = stub.UnaryCall(_SIMPLE_REQUEST)
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
- _RESPONSE_SIZE)
-
- # give the streams a workout
- futures = []
- for _ in range(15):
- futures.append(stub.UnaryCall.future(_SIMPLE_REQUEST))
- for future in futures:
+
+
+def _validate_status_code_and_details(call, expected_code, expected_details):
+ _expect_status_code(call, expected_code)
+ _expect_status_details(call, expected_details)
+
+
+# common requests
+_REQUEST_SIZE = 314159
+_RESPONSE_SIZE = 271828
+
+_SIMPLE_REQUEST = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=_RESPONSE_SIZE,
+ payload=messages_pb2.Payload(body=b'\x00' * _REQUEST_SIZE))
+
+
+def _goaway(stub):
+ first_response = stub.UnaryCall(_SIMPLE_REQUEST)
+ _validate_payload_type_and_length(first_response, messages_pb2.COMPRESSABLE,
+ _RESPONSE_SIZE)
+ time.sleep(1)
+ second_response = stub.UnaryCall(_SIMPLE_REQUEST)
+ _validate_payload_type_and_length(second_response,
+ messages_pb2.COMPRESSABLE, _RESPONSE_SIZE)
+
+
+def _rst_after_header(stub):
+ resp_future = stub.UnaryCall.future(_SIMPLE_REQUEST)
+ _validate_status_code_and_details(resp_future, grpc.StatusCode.INTERNAL,
+ "Received RST_STREAM with error code 0")
+
+
+def _rst_during_data(stub):
+ resp_future = stub.UnaryCall.future(_SIMPLE_REQUEST)
+ _validate_status_code_and_details(resp_future, grpc.StatusCode.INTERNAL,
+ "Received RST_STREAM with error code 0")
+
+
+def _rst_after_data(stub):
+ resp_future = stub.UnaryCall.future(_SIMPLE_REQUEST)
+ _validate_status_code_and_details(resp_future, grpc.StatusCode.INTERNAL,
+ "Received RST_STREAM with error code 0")
+
+
+def _ping(stub):
+ response = stub.UnaryCall(_SIMPLE_REQUEST)
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
+ _RESPONSE_SIZE)
+
+
+def _max_streams(stub):
+ # send one req to ensure server sets MAX_STREAMS
+ response = stub.UnaryCall(_SIMPLE_REQUEST)
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
+ _RESPONSE_SIZE)
+
+ # give the streams a workout
+ futures = []
+ for _ in range(15):
+ futures.append(stub.UnaryCall.future(_SIMPLE_REQUEST))
+ for future in futures:
_validate_payload_type_and_length(future.result(),
messages_pb2.COMPRESSABLE,
_RESPONSE_SIZE)
-
-
-def _run_test_case(test_case, stub):
- if test_case == 'goaway':
- _goaway(stub)
- elif test_case == 'rst_after_header':
- _rst_after_header(stub)
- elif test_case == 'rst_during_data':
- _rst_during_data(stub)
- elif test_case == 'rst_after_data':
- _rst_after_data(stub)
- elif test_case == 'ping':
- _ping(stub)
- elif test_case == 'max_streams':
- _max_streams(stub)
- else:
- raise ValueError("Invalid test case: %s" % test_case)
-
-
-def _args():
- parser = argparse.ArgumentParser()
+
+
+def _run_test_case(test_case, stub):
+ if test_case == 'goaway':
+ _goaway(stub)
+ elif test_case == 'rst_after_header':
+ _rst_after_header(stub)
+ elif test_case == 'rst_during_data':
+ _rst_during_data(stub)
+ elif test_case == 'rst_after_data':
+ _rst_after_data(stub)
+ elif test_case == 'ping':
+ _ping(stub)
+ elif test_case == 'max_streams':
+ _max_streams(stub)
+ else:
+ raise ValueError("Invalid test case: %s" % test_case)
+
+
+def _args():
+ parser = argparse.ArgumentParser()
parser.add_argument('--server_host',
help='the host to which to connect',
type=str,
@@ -138,21 +138,21 @@ def _args():
help='the test case to execute',
type=str,
default="goaway")
- return parser.parse_args()
-
-
-def _stub(server_host, server_port):
- target = '{}:{}'.format(server_host, server_port)
- channel = grpc.insecure_channel(target)
- grpc.channel_ready_future(channel).result()
- return test_pb2_grpc.TestServiceStub(channel)
-
-
-def main():
- args = _args()
- stub = _stub(args.server_host, args.server_port)
- _run_test_case(args.test_case, stub)
-
-
-if __name__ == '__main__':
- main()
+ return parser.parse_args()
+
+
+def _stub(server_host, server_port):
+ target = '{}:{}'.format(server_host, server_port)
+ channel = grpc.insecure_channel(target)
+ grpc.channel_ready_future(channel).result()
+ return test_pb2_grpc.TestServiceStub(channel)
+
+
+def main():
+ args = _args()
+ stub = _stub(args.server_host, args.server_port)
+ _run_test_case(args.test_case, stub)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/__init__.py
index 5fb4f3c3cf..dc985eebb4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 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.
+# Copyright 2015 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py
index fecf31767a..ff89d9dc7f 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py
@@ -1,44 +1,44 @@
-# Copyright 2015 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.
-"""Insecure client-server interoperability as a unit test."""
-
-import unittest
-
-import grpc
-from src.proto.grpc.testing import test_pb2_grpc
-
-from tests.interop import _intraop_test_case
-from tests.interop import service
-from tests.interop import server
-from tests.unit import test_common
-
-
-class InsecureIntraopTest(_intraop_test_case.IntraopTestCase,
- unittest.TestCase):
-
- def setUp(self):
- self.server = test_common.test_server()
- test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
- self.server)
- port = self.server.add_insecure_port('[::]:0')
- self.server.start()
- self.stub = test_pb2_grpc.TestServiceStub(
- grpc.insecure_channel('localhost:{}'.format(port)))
-
- def tearDown(self):
- self.server.stop(None)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2015 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.
+"""Insecure client-server interoperability as a unit test."""
+
+import unittest
+
+import grpc
+from src.proto.grpc.testing import test_pb2_grpc
+
+from tests.interop import _intraop_test_case
+from tests.interop import service
+from tests.interop import server
+from tests.unit import test_common
+
+
+class InsecureIntraopTest(_intraop_test_case.IntraopTestCase,
+ unittest.TestCase):
+
+ def setUp(self):
+ self.server = test_common.test_server()
+ test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
+ self.server)
+ port = self.server.add_insecure_port('[::]:0')
+ self.server.start()
+ self.stub = test_pb2_grpc.TestServiceStub(
+ grpc.insecure_channel('localhost:{}'.format(port)))
+
+ def tearDown(self):
+ self.server.stop(None)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_intraop_test_case.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_intraop_test_case.py
index 007db7ab41..964d3a6269 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_intraop_test_case.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_intraop_test_case.py
@@ -1,51 +1,51 @@
-# Copyright 2015 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.
-"""Common code for unit tests of the interoperability test code."""
-
-from tests.interop import methods
-
-
-class IntraopTestCase(object):
- """Unit test methods.
-
- This class must be mixed in with unittest.TestCase and a class that defines
- setUp and tearDown methods that manage a stub attribute.
- """
-
- def testEmptyUnary(self):
- methods.TestCase.EMPTY_UNARY.test_interoperability(self.stub, None)
-
- def testLargeUnary(self):
- methods.TestCase.LARGE_UNARY.test_interoperability(self.stub, None)
-
- def testServerStreaming(self):
- methods.TestCase.SERVER_STREAMING.test_interoperability(self.stub, None)
-
- def testClientStreaming(self):
- methods.TestCase.CLIENT_STREAMING.test_interoperability(self.stub, None)
-
- def testPingPong(self):
- methods.TestCase.PING_PONG.test_interoperability(self.stub, None)
-
- def testCancelAfterBegin(self):
- methods.TestCase.CANCEL_AFTER_BEGIN.test_interoperability(
- self.stub, None)
-
- def testCancelAfterFirstResponse(self):
- methods.TestCase.CANCEL_AFTER_FIRST_RESPONSE.test_interoperability(
- self.stub, None)
-
- def testTimeoutOnSleepingServer(self):
- methods.TestCase.TIMEOUT_ON_SLEEPING_SERVER.test_interoperability(
- self.stub, None)
+# Copyright 2015 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.
+"""Common code for unit tests of the interoperability test code."""
+
+from tests.interop import methods
+
+
+class IntraopTestCase(object):
+ """Unit test methods.
+
+ This class must be mixed in with unittest.TestCase and a class that defines
+ setUp and tearDown methods that manage a stub attribute.
+ """
+
+ def testEmptyUnary(self):
+ methods.TestCase.EMPTY_UNARY.test_interoperability(self.stub, None)
+
+ def testLargeUnary(self):
+ methods.TestCase.LARGE_UNARY.test_interoperability(self.stub, None)
+
+ def testServerStreaming(self):
+ methods.TestCase.SERVER_STREAMING.test_interoperability(self.stub, None)
+
+ def testClientStreaming(self):
+ methods.TestCase.CLIENT_STREAMING.test_interoperability(self.stub, None)
+
+ def testPingPong(self):
+ methods.TestCase.PING_PONG.test_interoperability(self.stub, None)
+
+ def testCancelAfterBegin(self):
+ methods.TestCase.CANCEL_AFTER_BEGIN.test_interoperability(
+ self.stub, None)
+
+ def testCancelAfterFirstResponse(self):
+ methods.TestCase.CANCEL_AFTER_FIRST_RESPONSE.test_interoperability(
+ self.stub, None)
+
+ def testTimeoutOnSleepingServer(self):
+ methods.TestCase.TIMEOUT_ON_SLEEPING_SERVER.test_interoperability(
+ self.stub, None)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_secure_intraop_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_secure_intraop_test.py
index bf1f1b118b..af3a94e15a 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_secure_intraop_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/_secure_intraop_test.py
@@ -1,43 +1,43 @@
-# Copyright 2015 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.
-"""Secure client-server interoperability as a unit test."""
-
-import unittest
-
-import grpc
-from src.proto.grpc.testing import test_pb2_grpc
-
-from tests.interop import _intraop_test_case
-from tests.interop import service
-from tests.interop import resources
-from tests.unit import test_common
-
-_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
-
-
-class SecureIntraopTest(_intraop_test_case.IntraopTestCase, unittest.TestCase):
-
- def setUp(self):
- self.server = test_common.test_server()
- test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
- self.server)
- port = self.server.add_secure_port(
- '[::]:0',
- grpc.ssl_server_credentials([(resources.private_key(),
- resources.certificate_chain())]))
- self.server.start()
- self.stub = test_pb2_grpc.TestServiceStub(
+# Copyright 2015 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.
+"""Secure client-server interoperability as a unit test."""
+
+import unittest
+
+import grpc
+from src.proto.grpc.testing import test_pb2_grpc
+
+from tests.interop import _intraop_test_case
+from tests.interop import service
+from tests.interop import resources
+from tests.unit import test_common
+
+_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
+
+
+class SecureIntraopTest(_intraop_test_case.IntraopTestCase, unittest.TestCase):
+
+ def setUp(self):
+ self.server = test_common.test_server()
+ test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
+ self.server)
+ port = self.server.add_secure_port(
+ '[::]:0',
+ grpc.ssl_server_credentials([(resources.private_key(),
+ resources.certificate_chain())]))
+ self.server.start()
+ self.stub = test_pb2_grpc.TestServiceStub(
grpc.secure_channel(
'localhost:{}'.format(port),
grpc.ssl_channel_credentials(
@@ -45,10 +45,10 @@ class SecureIntraopTest(_intraop_test_case.IntraopTestCase, unittest.TestCase):
'grpc.ssl_target_name_override',
_SERVER_HOST_OVERRIDE,
),)))
-
- def tearDown(self):
- self.server.stop(None)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+
+ def tearDown(self):
+ self.server.stop(None)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/client.py
index 4d35f7ca32..a47b0834d0 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/client.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/client.py
@@ -1,32 +1,32 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""The Python implementation of the GRPC interoperability test client."""
-
-import argparse
-import os
-
-from google import auth as google_auth
-from google.auth import jwt as google_auth_jwt
-import grpc
-from src.proto.grpc.testing import test_pb2_grpc
-
-from tests.interop import methods
-from tests.interop import resources
-
-
+# Copyright 2015 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the GRPC interoperability test client."""
+
+import argparse
+import os
+
+from google import auth as google_auth
+from google.auth import jwt as google_auth_jwt
+import grpc
+from src.proto.grpc.testing import test_pb2_grpc
+
+from tests.interop import methods
+from tests.interop import resources
+
+
def parse_interop_client_args():
- parser = argparse.ArgumentParser()
+ parser = argparse.ArgumentParser()
parser.add_argument('--server_host',
default="localhost",
type=str,
@@ -72,29 +72,29 @@ def parse_interop_client_args():
+ "grpc::CreateTestChannel, that configures the grpclb LB policy " +
"with a child policy being the value of this flag (e.g. round_robin "
+ "or pick_first)."))
- return parser.parse_args()
-
-
+ return parser.parse_args()
+
+
def _create_call_credentials(args):
- if args.test_case == 'oauth2_auth_token':
- google_credentials, unused_project_id = google_auth.default(
- scopes=[args.oauth_scope])
- google_credentials.refresh(google_auth.transport.requests.Request())
+ if args.test_case == 'oauth2_auth_token':
+ google_credentials, unused_project_id = google_auth.default(
+ scopes=[args.oauth_scope])
+ google_credentials.refresh(google_auth.transport.requests.Request())
return grpc.access_token_call_credentials(google_credentials.token)
- elif args.test_case == 'compute_engine_creds':
- google_credentials, unused_project_id = google_auth.default(
- scopes=[args.oauth_scope])
+ elif args.test_case == 'compute_engine_creds':
+ google_credentials, unused_project_id = google_auth.default(
+ scopes=[args.oauth_scope])
return grpc.metadata_call_credentials(
- google_auth.transport.grpc.AuthMetadataPlugin(
- credentials=google_credentials,
- request=google_auth.transport.requests.Request()))
- elif args.test_case == 'jwt_token_creds':
- google_credentials = google_auth_jwt.OnDemandCredentials.from_service_account_file(
- os.environ[google_auth.environment_vars.CREDENTIALS])
+ google_auth.transport.grpc.AuthMetadataPlugin(
+ credentials=google_credentials,
+ request=google_auth.transport.requests.Request()))
+ elif args.test_case == 'jwt_token_creds':
+ google_credentials = google_auth_jwt.OnDemandCredentials.from_service_account_file(
+ os.environ[google_auth.environment_vars.CREDENTIALS])
return grpc.metadata_call_credentials(
- google_auth.transport.grpc.AuthMetadataPlugin(
- credentials=google_credentials, request=None))
- else:
+ google_auth.transport.grpc.AuthMetadataPlugin(
+ credentials=google_credentials, request=None))
+ else:
return None
@@ -151,30 +151,30 @@ def _create_channel(args):
return grpc.secure_channel(target, channel_credentials, options)
else:
return grpc.insecure_channel(target)
-
-
+
+
def create_stub(channel, args):
- if args.test_case == "unimplemented_service":
- return test_pb2_grpc.UnimplementedServiceStub(channel)
- else:
- return test_pb2_grpc.TestServiceStub(channel)
-
-
-def _test_case_from_arg(test_case_arg):
- for test_case in methods.TestCase:
- if test_case_arg == test_case.value:
- return test_case
- else:
- raise ValueError('No test case "%s"!' % test_case_arg)
-
-
-def test_interoperability():
+ if args.test_case == "unimplemented_service":
+ return test_pb2_grpc.UnimplementedServiceStub(channel)
+ else:
+ return test_pb2_grpc.TestServiceStub(channel)
+
+
+def _test_case_from_arg(test_case_arg):
+ for test_case in methods.TestCase:
+ if test_case_arg == test_case.value:
+ return test_case
+ else:
+ raise ValueError('No test case "%s"!' % test_case_arg)
+
+
+def test_interoperability():
args = parse_interop_client_args()
channel = _create_channel(args)
stub = create_stub(channel, args)
- test_case = _test_case_from_arg(args.test_case)
- test_case.test_interoperability(stub, args)
-
-
-if __name__ == '__main__':
- test_interoperability()
+ test_case = _test_case_from_arg(args.test_case)
+ test_case.test_interoperability(stub, args)
+
+
+if __name__ == '__main__':
+ test_interoperability()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/methods.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/methods.py
index 44a1c38bb9..c57093ea73 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/methods.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/methods.py
@@ -1,482 +1,482 @@
-# Copyright 2015 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.
-"""Implementations of interoperability test methods."""
-
-# NOTE(lidiz) This module only exists in Bazel BUILD file, for more details
-# please refer to comments in the "bazel_namespace_package_hack" module.
-try:
- from tests import bazel_namespace_package_hack
- bazel_namespace_package_hack.sys_path_to_site_dir_hack()
-except ImportError:
- pass
-
-import enum
-import json
-import os
-import threading
-import time
-
-from google import auth as google_auth
-from google.auth import environment_vars as google_auth_environment_vars
-from google.auth.transport import grpc as google_auth_transport_grpc
-from google.auth.transport import requests as google_auth_transport_requests
-import grpc
-
-from src.proto.grpc.testing import empty_pb2
-from src.proto.grpc.testing import messages_pb2
-
-_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
-_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
-
-
-def _expect_status_code(call, expected_code):
- if call.code() != expected_code:
+# Copyright 2015 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.
+"""Implementations of interoperability test methods."""
+
+# NOTE(lidiz) This module only exists in Bazel BUILD file, for more details
+# please refer to comments in the "bazel_namespace_package_hack" module.
+try:
+ from tests import bazel_namespace_package_hack
+ bazel_namespace_package_hack.sys_path_to_site_dir_hack()
+except ImportError:
+ pass
+
+import enum
+import json
+import os
+import threading
+import time
+
+from google import auth as google_auth
+from google.auth import environment_vars as google_auth_environment_vars
+from google.auth.transport import grpc as google_auth_transport_grpc
+from google.auth.transport import requests as google_auth_transport_requests
+import grpc
+
+from src.proto.grpc.testing import empty_pb2
+from src.proto.grpc.testing import messages_pb2
+
+_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
+_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
+
+
+def _expect_status_code(call, expected_code):
+ if call.code() != expected_code:
raise ValueError('expected code %s, got %s' %
(expected_code, call.code()))
-
-
-def _expect_status_details(call, expected_details):
- if call.details() != expected_details:
+
+
+def _expect_status_details(call, expected_details):
+ if call.details() != expected_details:
raise ValueError('expected message %s, got %s' %
(expected_details, call.details()))
-
-
-def _validate_status_code_and_details(call, expected_code, expected_details):
- _expect_status_code(call, expected_code)
- _expect_status_details(call, expected_details)
-
-
-def _validate_payload_type_and_length(response, expected_type, expected_length):
- if response.payload.type is not expected_type:
- raise ValueError('expected payload type %s, got %s' %
- (expected_type, type(response.payload.type)))
- elif len(response.payload.body) != expected_length:
- raise ValueError('expected payload body size %d, got %d' %
- (expected_length, len(response.payload.body)))
-
-
-def _large_unary_common_behavior(stub, fill_username, fill_oauth_scope,
- call_credentials):
- size = 314159
- request = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=size,
- payload=messages_pb2.Payload(body=b'\x00' * 271828),
- fill_username=fill_username,
- fill_oauth_scope=fill_oauth_scope)
+
+
+def _validate_status_code_and_details(call, expected_code, expected_details):
+ _expect_status_code(call, expected_code)
+ _expect_status_details(call, expected_details)
+
+
+def _validate_payload_type_and_length(response, expected_type, expected_length):
+ if response.payload.type is not expected_type:
+ raise ValueError('expected payload type %s, got %s' %
+ (expected_type, type(response.payload.type)))
+ elif len(response.payload.body) != expected_length:
+ raise ValueError('expected payload body size %d, got %d' %
+ (expected_length, len(response.payload.body)))
+
+
+def _large_unary_common_behavior(stub, fill_username, fill_oauth_scope,
+ call_credentials):
+ size = 314159
+ request = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=size,
+ payload=messages_pb2.Payload(body=b'\x00' * 271828),
+ fill_username=fill_username,
+ fill_oauth_scope=fill_oauth_scope)
response_future = stub.UnaryCall.future(request,
credentials=call_credentials)
- response = response_future.result()
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
- return response
-
-
-def _empty_unary(stub):
- response = stub.EmptyCall(empty_pb2.Empty())
- if not isinstance(response, empty_pb2.Empty):
+ response = response_future.result()
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
+ return response
+
+
+def _empty_unary(stub):
+ response = stub.EmptyCall(empty_pb2.Empty())
+ if not isinstance(response, empty_pb2.Empty):
raise TypeError('response is of type "%s", not empty_pb2.Empty!' %
type(response))
-
-
-def _large_unary(stub):
- _large_unary_common_behavior(stub, False, False, None)
-
-
-def _client_streaming(stub):
- payload_body_sizes = (
- 27182,
- 8,
- 1828,
- 45904,
- )
- payloads = (messages_pb2.Payload(body=b'\x00' * size)
- for size in payload_body_sizes)
- requests = (messages_pb2.StreamingInputCallRequest(payload=payload)
- for payload in payloads)
- response = stub.StreamingInputCall(requests)
- if response.aggregated_payload_size != 74922:
+
+
+def _large_unary(stub):
+ _large_unary_common_behavior(stub, False, False, None)
+
+
+def _client_streaming(stub):
+ payload_body_sizes = (
+ 27182,
+ 8,
+ 1828,
+ 45904,
+ )
+ payloads = (messages_pb2.Payload(body=b'\x00' * size)
+ for size in payload_body_sizes)
+ requests = (messages_pb2.StreamingInputCallRequest(payload=payload)
+ for payload in payloads)
+ response = stub.StreamingInputCall(requests)
+ if response.aggregated_payload_size != 74922:
raise ValueError('incorrect size %d!' %
response.aggregated_payload_size)
-
-
-def _server_streaming(stub):
- sizes = (
- 31415,
- 9,
- 2653,
- 58979,
- )
-
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_parameters=(
- messages_pb2.ResponseParameters(size=sizes[0]),
- messages_pb2.ResponseParameters(size=sizes[1]),
- messages_pb2.ResponseParameters(size=sizes[2]),
- messages_pb2.ResponseParameters(size=sizes[3]),
- ))
- response_iterator = stub.StreamingOutputCall(request)
- for index, response in enumerate(response_iterator):
- _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
- sizes[index])
-
-
-class _Pipe(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._values = []
- self._open = True
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self.next()
-
- def next(self):
- with self._condition:
- while not self._values and self._open:
- self._condition.wait()
- if self._values:
- return self._values.pop(0)
- else:
- raise StopIteration()
-
- def add(self, value):
- with self._condition:
- self._values.append(value)
- self._condition.notify()
-
- def close(self):
- with self._condition:
- self._open = False
- self._condition.notify()
-
- def __enter__(self):
- return self
-
- def __exit__(self, type, value, traceback):
- self.close()
-
-
-def _ping_pong(stub):
- request_response_sizes = (
- 31415,
- 9,
- 2653,
- 58979,
- )
- request_payload_sizes = (
- 27182,
- 8,
- 1828,
- 45904,
- )
-
- with _Pipe() as pipe:
- response_iterator = stub.FullDuplexCall(pipe)
- for response_size, payload_size in zip(request_response_sizes,
- request_payload_sizes):
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
+
+
+def _server_streaming(stub):
+ sizes = (
+ 31415,
+ 9,
+ 2653,
+ 58979,
+ )
+
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_parameters=(
+ messages_pb2.ResponseParameters(size=sizes[0]),
+ messages_pb2.ResponseParameters(size=sizes[1]),
+ messages_pb2.ResponseParameters(size=sizes[2]),
+ messages_pb2.ResponseParameters(size=sizes[3]),
+ ))
+ response_iterator = stub.StreamingOutputCall(request)
+ for index, response in enumerate(response_iterator):
+ _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
+ sizes[index])
+
+
+class _Pipe(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._values = []
+ self._open = True
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return self.next()
+
+ def next(self):
+ with self._condition:
+ while not self._values and self._open:
+ self._condition.wait()
+ if self._values:
+ return self._values.pop(0)
+ else:
+ raise StopIteration()
+
+ def add(self, value):
+ with self._condition:
+ self._values.append(value)
+ self._condition.notify()
+
+ def close(self):
+ with self._condition:
+ self._open = False
+ self._condition.notify()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+
+def _ping_pong(stub):
+ request_response_sizes = (
+ 31415,
+ 9,
+ 2653,
+ 58979,
+ )
+ request_payload_sizes = (
+ 27182,
+ 8,
+ 1828,
+ 45904,
+ )
+
+ with _Pipe() as pipe:
+ response_iterator = stub.FullDuplexCall(pipe)
+ for response_size, payload_size in zip(request_response_sizes,
+ request_payload_sizes):
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(
size=response_size),),
- payload=messages_pb2.Payload(body=b'\x00' * payload_size))
- pipe.add(request)
- response = next(response_iterator)
+ payload=messages_pb2.Payload(body=b'\x00' * payload_size))
+ pipe.add(request)
+ response = next(response_iterator)
_validate_payload_type_and_length(response,
messages_pb2.COMPRESSABLE,
response_size)
-
-
-def _cancel_after_begin(stub):
- with _Pipe() as pipe:
- response_future = stub.StreamingInputCall.future(pipe)
- response_future.cancel()
- if not response_future.cancelled():
- raise ValueError('expected cancelled method to return True')
- if response_future.code() is not grpc.StatusCode.CANCELLED:
- raise ValueError('expected status code CANCELLED')
-
-
-def _cancel_after_first_response(stub):
- request_response_sizes = (
- 31415,
- 9,
- 2653,
- 58979,
- )
- request_payload_sizes = (
- 27182,
- 8,
- 1828,
- 45904,
- )
- with _Pipe() as pipe:
- response_iterator = stub.FullDuplexCall(pipe)
-
- response_size = request_response_sizes[0]
- payload_size = request_payload_sizes[0]
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
+
+
+def _cancel_after_begin(stub):
+ with _Pipe() as pipe:
+ response_future = stub.StreamingInputCall.future(pipe)
+ response_future.cancel()
+ if not response_future.cancelled():
+ raise ValueError('expected cancelled method to return True')
+ if response_future.code() is not grpc.StatusCode.CANCELLED:
+ raise ValueError('expected status code CANCELLED')
+
+
+def _cancel_after_first_response(stub):
+ request_response_sizes = (
+ 31415,
+ 9,
+ 2653,
+ 58979,
+ )
+ request_payload_sizes = (
+ 27182,
+ 8,
+ 1828,
+ 45904,
+ )
+ with _Pipe() as pipe:
+ response_iterator = stub.FullDuplexCall(pipe)
+
+ response_size = request_response_sizes[0]
+ payload_size = request_payload_sizes[0]
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(
size=response_size),),
- payload=messages_pb2.Payload(body=b'\x00' * payload_size))
- pipe.add(request)
- response = next(response_iterator)
- # We test the contents of `response` in the Ping Pong test - don't check
- # them here.
- response_iterator.cancel()
-
- try:
- next(response_iterator)
- except grpc.RpcError as rpc_error:
- if rpc_error.code() is not grpc.StatusCode.CANCELLED:
- raise
- else:
- raise ValueError('expected call to be cancelled')
-
-
-def _timeout_on_sleeping_server(stub):
- request_payload_size = 27182
- with _Pipe() as pipe:
- response_iterator = stub.FullDuplexCall(pipe, timeout=0.001)
-
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
- payload=messages_pb2.Payload(body=b'\x00' * request_payload_size))
- pipe.add(request)
- try:
- next(response_iterator)
- except grpc.RpcError as rpc_error:
- if rpc_error.code() is not grpc.StatusCode.DEADLINE_EXCEEDED:
- raise
- else:
- raise ValueError('expected call to exceed deadline')
-
-
-def _empty_stream(stub):
- with _Pipe() as pipe:
- response_iterator = stub.FullDuplexCall(pipe)
- pipe.close()
- try:
- next(response_iterator)
- raise ValueError('expected exactly 0 responses')
- except StopIteration:
- pass
-
-
-def _status_code_and_message(stub):
- details = 'test status message'
- code = 2
- status = grpc.StatusCode.UNKNOWN # code = 2
-
- # Test with a UnaryCall
- request = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=1,
- payload=messages_pb2.Payload(body=b'\x00'),
- response_status=messages_pb2.EchoStatus(code=code, message=details))
- response_future = stub.UnaryCall.future(request)
- _validate_status_code_and_details(response_future, status, details)
-
- # Test with a FullDuplexCall
- with _Pipe() as pipe:
- response_iterator = stub.FullDuplexCall(pipe)
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_parameters=(messages_pb2.ResponseParameters(size=1),),
- payload=messages_pb2.Payload(body=b'\x00'),
- response_status=messages_pb2.EchoStatus(code=code, message=details))
- pipe.add(request) # sends the initial request.
+ payload=messages_pb2.Payload(body=b'\x00' * payload_size))
+ pipe.add(request)
+ response = next(response_iterator)
+ # We test the contents of `response` in the Ping Pong test - don't check
+ # them here.
+ response_iterator.cancel()
+
+ try:
+ next(response_iterator)
+ except grpc.RpcError as rpc_error:
+ if rpc_error.code() is not grpc.StatusCode.CANCELLED:
+ raise
+ else:
+ raise ValueError('expected call to be cancelled')
+
+
+def _timeout_on_sleeping_server(stub):
+ request_payload_size = 27182
+ with _Pipe() as pipe:
+ response_iterator = stub.FullDuplexCall(pipe, timeout=0.001)
+
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ payload=messages_pb2.Payload(body=b'\x00' * request_payload_size))
+ pipe.add(request)
+ try:
+ next(response_iterator)
+ except grpc.RpcError as rpc_error:
+ if rpc_error.code() is not grpc.StatusCode.DEADLINE_EXCEEDED:
+ raise
+ else:
+ raise ValueError('expected call to exceed deadline')
+
+
+def _empty_stream(stub):
+ with _Pipe() as pipe:
+ response_iterator = stub.FullDuplexCall(pipe)
+ pipe.close()
+ try:
+ next(response_iterator)
+ raise ValueError('expected exactly 0 responses')
+ except StopIteration:
+ pass
+
+
+def _status_code_and_message(stub):
+ details = 'test status message'
+ code = 2
+ status = grpc.StatusCode.UNKNOWN # code = 2
+
+ # Test with a UnaryCall
+ request = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=1,
+ payload=messages_pb2.Payload(body=b'\x00'),
+ response_status=messages_pb2.EchoStatus(code=code, message=details))
+ response_future = stub.UnaryCall.future(request)
+ _validate_status_code_and_details(response_future, status, details)
+
+ # Test with a FullDuplexCall
+ with _Pipe() as pipe:
+ response_iterator = stub.FullDuplexCall(pipe)
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_parameters=(messages_pb2.ResponseParameters(size=1),),
+ payload=messages_pb2.Payload(body=b'\x00'),
+ response_status=messages_pb2.EchoStatus(code=code, message=details))
+ pipe.add(request) # sends the initial request.
try:
next(response_iterator)
except grpc.RpcError as rpc_error:
assert rpc_error.code() == status
- # Dropping out of with block closes the pipe
- _validate_status_code_and_details(response_iterator, status, details)
-
-
-def _unimplemented_method(test_service_stub):
- response_future = (test_service_stub.UnimplementedCall.future(
- empty_pb2.Empty()))
- _expect_status_code(response_future, grpc.StatusCode.UNIMPLEMENTED)
-
-
-def _unimplemented_service(unimplemented_service_stub):
- response_future = (unimplemented_service_stub.UnimplementedCall.future(
- empty_pb2.Empty()))
- _expect_status_code(response_future, grpc.StatusCode.UNIMPLEMENTED)
-
-
-def _custom_metadata(stub):
- initial_metadata_value = "test_initial_metadata_value"
- trailing_metadata_value = b"\x0a\x0b\x0a\x0b\x0a\x0b"
- metadata = ((_INITIAL_METADATA_KEY, initial_metadata_value),
- (_TRAILING_METADATA_KEY, trailing_metadata_value))
-
- def _validate_metadata(response):
- initial_metadata = dict(response.initial_metadata())
- if initial_metadata[_INITIAL_METADATA_KEY] != initial_metadata_value:
- raise ValueError('expected initial metadata %s, got %s' %
- (initial_metadata_value,
- initial_metadata[_INITIAL_METADATA_KEY]))
- trailing_metadata = dict(response.trailing_metadata())
- if trailing_metadata[_TRAILING_METADATA_KEY] != trailing_metadata_value:
- raise ValueError('expected trailing metadata %s, got %s' %
- (trailing_metadata_value,
- trailing_metadata[_TRAILING_METADATA_KEY]))
-
- # Testing with UnaryCall
- request = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=1,
- payload=messages_pb2.Payload(body=b'\x00'))
- response_future = stub.UnaryCall.future(request, metadata=metadata)
- _validate_metadata(response_future)
-
- # Testing with FullDuplexCall
- with _Pipe() as pipe:
- response_iterator = stub.FullDuplexCall(pipe, metadata=metadata)
- request = messages_pb2.StreamingOutputCallRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_parameters=(messages_pb2.ResponseParameters(size=1),))
- pipe.add(request) # Sends the request
- next(response_iterator) # Causes server to send trailing metadata
- # Dropping out of the with block closes the pipe
- _validate_metadata(response_iterator)
-
-
-def _compute_engine_creds(stub, args):
- response = _large_unary_common_behavior(stub, True, True, None)
- if args.default_service_account != response.username:
- raise ValueError('expected username %s, got %s' %
- (args.default_service_account, response.username))
-
-
-def _oauth2_auth_token(stub, args):
- json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
- wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
- response = _large_unary_common_behavior(stub, True, True, None)
- if wanted_email != response.username:
+ # Dropping out of with block closes the pipe
+ _validate_status_code_and_details(response_iterator, status, details)
+
+
+def _unimplemented_method(test_service_stub):
+ response_future = (test_service_stub.UnimplementedCall.future(
+ empty_pb2.Empty()))
+ _expect_status_code(response_future, grpc.StatusCode.UNIMPLEMENTED)
+
+
+def _unimplemented_service(unimplemented_service_stub):
+ response_future = (unimplemented_service_stub.UnimplementedCall.future(
+ empty_pb2.Empty()))
+ _expect_status_code(response_future, grpc.StatusCode.UNIMPLEMENTED)
+
+
+def _custom_metadata(stub):
+ initial_metadata_value = "test_initial_metadata_value"
+ trailing_metadata_value = b"\x0a\x0b\x0a\x0b\x0a\x0b"
+ metadata = ((_INITIAL_METADATA_KEY, initial_metadata_value),
+ (_TRAILING_METADATA_KEY, trailing_metadata_value))
+
+ def _validate_metadata(response):
+ initial_metadata = dict(response.initial_metadata())
+ if initial_metadata[_INITIAL_METADATA_KEY] != initial_metadata_value:
+ raise ValueError('expected initial metadata %s, got %s' %
+ (initial_metadata_value,
+ initial_metadata[_INITIAL_METADATA_KEY]))
+ trailing_metadata = dict(response.trailing_metadata())
+ if trailing_metadata[_TRAILING_METADATA_KEY] != trailing_metadata_value:
+ raise ValueError('expected trailing metadata %s, got %s' %
+ (trailing_metadata_value,
+ trailing_metadata[_TRAILING_METADATA_KEY]))
+
+ # Testing with UnaryCall
+ request = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=1,
+ payload=messages_pb2.Payload(body=b'\x00'))
+ response_future = stub.UnaryCall.future(request, metadata=metadata)
+ _validate_metadata(response_future)
+
+ # Testing with FullDuplexCall
+ with _Pipe() as pipe:
+ response_iterator = stub.FullDuplexCall(pipe, metadata=metadata)
+ request = messages_pb2.StreamingOutputCallRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_parameters=(messages_pb2.ResponseParameters(size=1),))
+ pipe.add(request) # Sends the request
+ next(response_iterator) # Causes server to send trailing metadata
+ # Dropping out of the with block closes the pipe
+ _validate_metadata(response_iterator)
+
+
+def _compute_engine_creds(stub, args):
+ response = _large_unary_common_behavior(stub, True, True, None)
+ if args.default_service_account != response.username:
+ raise ValueError('expected username %s, got %s' %
+ (args.default_service_account, response.username))
+
+
+def _oauth2_auth_token(stub, args):
+ json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
+ wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
+ response = _large_unary_common_behavior(stub, True, True, None)
+ if wanted_email != response.username:
raise ValueError('expected username %s, got %s' %
(wanted_email, response.username))
- if args.oauth_scope.find(response.oauth_scope) == -1:
- raise ValueError(
- 'expected to find oauth scope "{}" in received "{}"'.format(
- response.oauth_scope, args.oauth_scope))
-
-
-def _jwt_token_creds(stub, args):
- json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
- wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
- response = _large_unary_common_behavior(stub, True, False, None)
- if wanted_email != response.username:
+ if args.oauth_scope.find(response.oauth_scope) == -1:
+ raise ValueError(
+ 'expected to find oauth scope "{}" in received "{}"'.format(
+ response.oauth_scope, args.oauth_scope))
+
+
+def _jwt_token_creds(stub, args):
+ json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
+ wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
+ response = _large_unary_common_behavior(stub, True, False, None)
+ if wanted_email != response.username:
raise ValueError('expected username %s, got %s' %
(wanted_email, response.username))
-
-
-def _per_rpc_creds(stub, args):
- json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
- wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
- google_credentials, unused_project_id = google_auth.default(
- scopes=[args.oauth_scope])
- call_credentials = grpc.metadata_call_credentials(
- google_auth_transport_grpc.AuthMetadataPlugin(
- credentials=google_credentials,
- request=google_auth_transport_requests.Request()))
- response = _large_unary_common_behavior(stub, True, False, call_credentials)
- if wanted_email != response.username:
+
+
+def _per_rpc_creds(stub, args):
+ json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
+ wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
+ google_credentials, unused_project_id = google_auth.default(
+ scopes=[args.oauth_scope])
+ call_credentials = grpc.metadata_call_credentials(
+ google_auth_transport_grpc.AuthMetadataPlugin(
+ credentials=google_credentials,
+ request=google_auth_transport_requests.Request()))
+ response = _large_unary_common_behavior(stub, True, False, call_credentials)
+ if wanted_email != response.username:
raise ValueError('expected username %s, got %s' %
(wanted_email, response.username))
-
-
-def _special_status_message(stub, args):
- details = b'\t\ntest with whitespace\r\nand Unicode BMP \xe2\x98\xba and non-BMP \xf0\x9f\x98\x88\t\n'.decode(
- 'utf-8')
- code = 2
- status = grpc.StatusCode.UNKNOWN # code = 2
-
- # Test with a UnaryCall
- request = messages_pb2.SimpleRequest(
- response_type=messages_pb2.COMPRESSABLE,
- response_size=1,
- payload=messages_pb2.Payload(body=b'\x00'),
- response_status=messages_pb2.EchoStatus(code=code, message=details))
- response_future = stub.UnaryCall.future(request)
- _validate_status_code_and_details(response_future, status, details)
-
-
-@enum.unique
-class TestCase(enum.Enum):
- EMPTY_UNARY = 'empty_unary'
- LARGE_UNARY = 'large_unary'
- SERVER_STREAMING = 'server_streaming'
- CLIENT_STREAMING = 'client_streaming'
- PING_PONG = 'ping_pong'
- CANCEL_AFTER_BEGIN = 'cancel_after_begin'
- CANCEL_AFTER_FIRST_RESPONSE = 'cancel_after_first_response'
- EMPTY_STREAM = 'empty_stream'
- STATUS_CODE_AND_MESSAGE = 'status_code_and_message'
- UNIMPLEMENTED_METHOD = 'unimplemented_method'
- UNIMPLEMENTED_SERVICE = 'unimplemented_service'
- CUSTOM_METADATA = "custom_metadata"
- COMPUTE_ENGINE_CREDS = 'compute_engine_creds'
- OAUTH2_AUTH_TOKEN = 'oauth2_auth_token'
- JWT_TOKEN_CREDS = 'jwt_token_creds'
- PER_RPC_CREDS = 'per_rpc_creds'
- TIMEOUT_ON_SLEEPING_SERVER = 'timeout_on_sleeping_server'
- SPECIAL_STATUS_MESSAGE = 'special_status_message'
-
- def test_interoperability(self, stub, args):
- if self is TestCase.EMPTY_UNARY:
- _empty_unary(stub)
- elif self is TestCase.LARGE_UNARY:
- _large_unary(stub)
- elif self is TestCase.SERVER_STREAMING:
- _server_streaming(stub)
- elif self is TestCase.CLIENT_STREAMING:
- _client_streaming(stub)
- elif self is TestCase.PING_PONG:
- _ping_pong(stub)
- elif self is TestCase.CANCEL_AFTER_BEGIN:
- _cancel_after_begin(stub)
- elif self is TestCase.CANCEL_AFTER_FIRST_RESPONSE:
- _cancel_after_first_response(stub)
- elif self is TestCase.TIMEOUT_ON_SLEEPING_SERVER:
- _timeout_on_sleeping_server(stub)
- elif self is TestCase.EMPTY_STREAM:
- _empty_stream(stub)
- elif self is TestCase.STATUS_CODE_AND_MESSAGE:
- _status_code_and_message(stub)
- elif self is TestCase.UNIMPLEMENTED_METHOD:
- _unimplemented_method(stub)
- elif self is TestCase.UNIMPLEMENTED_SERVICE:
- _unimplemented_service(stub)
- elif self is TestCase.CUSTOM_METADATA:
- _custom_metadata(stub)
- elif self is TestCase.COMPUTE_ENGINE_CREDS:
- _compute_engine_creds(stub, args)
- elif self is TestCase.OAUTH2_AUTH_TOKEN:
- _oauth2_auth_token(stub, args)
- elif self is TestCase.JWT_TOKEN_CREDS:
- _jwt_token_creds(stub, args)
- elif self is TestCase.PER_RPC_CREDS:
- _per_rpc_creds(stub, args)
- elif self is TestCase.SPECIAL_STATUS_MESSAGE:
- _special_status_message(stub, args)
- else:
+
+
+def _special_status_message(stub, args):
+ details = b'\t\ntest with whitespace\r\nand Unicode BMP \xe2\x98\xba and non-BMP \xf0\x9f\x98\x88\t\n'.decode(
+ 'utf-8')
+ code = 2
+ status = grpc.StatusCode.UNKNOWN # code = 2
+
+ # Test with a UnaryCall
+ request = messages_pb2.SimpleRequest(
+ response_type=messages_pb2.COMPRESSABLE,
+ response_size=1,
+ payload=messages_pb2.Payload(body=b'\x00'),
+ response_status=messages_pb2.EchoStatus(code=code, message=details))
+ response_future = stub.UnaryCall.future(request)
+ _validate_status_code_and_details(response_future, status, details)
+
+
+@enum.unique
+class TestCase(enum.Enum):
+ EMPTY_UNARY = 'empty_unary'
+ LARGE_UNARY = 'large_unary'
+ SERVER_STREAMING = 'server_streaming'
+ CLIENT_STREAMING = 'client_streaming'
+ PING_PONG = 'ping_pong'
+ CANCEL_AFTER_BEGIN = 'cancel_after_begin'
+ CANCEL_AFTER_FIRST_RESPONSE = 'cancel_after_first_response'
+ EMPTY_STREAM = 'empty_stream'
+ STATUS_CODE_AND_MESSAGE = 'status_code_and_message'
+ UNIMPLEMENTED_METHOD = 'unimplemented_method'
+ UNIMPLEMENTED_SERVICE = 'unimplemented_service'
+ CUSTOM_METADATA = "custom_metadata"
+ COMPUTE_ENGINE_CREDS = 'compute_engine_creds'
+ OAUTH2_AUTH_TOKEN = 'oauth2_auth_token'
+ JWT_TOKEN_CREDS = 'jwt_token_creds'
+ PER_RPC_CREDS = 'per_rpc_creds'
+ TIMEOUT_ON_SLEEPING_SERVER = 'timeout_on_sleeping_server'
+ SPECIAL_STATUS_MESSAGE = 'special_status_message'
+
+ def test_interoperability(self, stub, args):
+ if self is TestCase.EMPTY_UNARY:
+ _empty_unary(stub)
+ elif self is TestCase.LARGE_UNARY:
+ _large_unary(stub)
+ elif self is TestCase.SERVER_STREAMING:
+ _server_streaming(stub)
+ elif self is TestCase.CLIENT_STREAMING:
+ _client_streaming(stub)
+ elif self is TestCase.PING_PONG:
+ _ping_pong(stub)
+ elif self is TestCase.CANCEL_AFTER_BEGIN:
+ _cancel_after_begin(stub)
+ elif self is TestCase.CANCEL_AFTER_FIRST_RESPONSE:
+ _cancel_after_first_response(stub)
+ elif self is TestCase.TIMEOUT_ON_SLEEPING_SERVER:
+ _timeout_on_sleeping_server(stub)
+ elif self is TestCase.EMPTY_STREAM:
+ _empty_stream(stub)
+ elif self is TestCase.STATUS_CODE_AND_MESSAGE:
+ _status_code_and_message(stub)
+ elif self is TestCase.UNIMPLEMENTED_METHOD:
+ _unimplemented_method(stub)
+ elif self is TestCase.UNIMPLEMENTED_SERVICE:
+ _unimplemented_service(stub)
+ elif self is TestCase.CUSTOM_METADATA:
+ _custom_metadata(stub)
+ elif self is TestCase.COMPUTE_ENGINE_CREDS:
+ _compute_engine_creds(stub, args)
+ elif self is TestCase.OAUTH2_AUTH_TOKEN:
+ _oauth2_auth_token(stub, args)
+ elif self is TestCase.JWT_TOKEN_CREDS:
+ _jwt_token_creds(stub, args)
+ elif self is TestCase.PER_RPC_CREDS:
+ _per_rpc_creds(stub, args)
+ elif self is TestCase.SPECIAL_STATUS_MESSAGE:
+ _special_status_message(stub, args)
+ else:
raise NotImplementedError('Test case "%s" not implemented!' %
self.name)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/resources.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/resources.py
index a55919a60a..ddded80a3f 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/resources.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/resources.py
@@ -1,42 +1,42 @@
-# Copyright 2015 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.
-"""Constants and functions for data used in interoperability testing."""
-
-import argparse
-import pkgutil
-import os
-
-_ROOT_CERTIFICATES_RESOURCE_PATH = 'credentials/ca.pem'
-_PRIVATE_KEY_RESOURCE_PATH = 'credentials/server1.key'
-_CERTIFICATE_CHAIN_RESOURCE_PATH = 'credentials/server1.pem'
-
-
-def test_root_certificates():
- return pkgutil.get_data(__name__, _ROOT_CERTIFICATES_RESOURCE_PATH)
-
-
-def private_key():
- return pkgutil.get_data(__name__, _PRIVATE_KEY_RESOURCE_PATH)
-
-
-def certificate_chain():
- return pkgutil.get_data(__name__, _CERTIFICATE_CHAIN_RESOURCE_PATH)
-
-
-def parse_bool(value):
- if value == 'true':
- return True
- if value == 'false':
- return False
- raise argparse.ArgumentTypeError('Only true/false allowed')
+# Copyright 2015 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.
+"""Constants and functions for data used in interoperability testing."""
+
+import argparse
+import pkgutil
+import os
+
+_ROOT_CERTIFICATES_RESOURCE_PATH = 'credentials/ca.pem'
+_PRIVATE_KEY_RESOURCE_PATH = 'credentials/server1.key'
+_CERTIFICATE_CHAIN_RESOURCE_PATH = 'credentials/server1.pem'
+
+
+def test_root_certificates():
+ return pkgutil.get_data(__name__, _ROOT_CERTIFICATES_RESOURCE_PATH)
+
+
+def private_key():
+ return pkgutil.get_data(__name__, _PRIVATE_KEY_RESOURCE_PATH)
+
+
+def certificate_chain():
+ return pkgutil.get_data(__name__, _CERTIFICATE_CHAIN_RESOURCE_PATH)
+
+
+def parse_bool(value):
+ if value == 'true':
+ return True
+ if value == 'false':
+ return False
+ raise argparse.ArgumentTypeError('Only true/false allowed')
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/server.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/server.py
index c85adb0b0b..5ac6983e58 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/server.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/server.py
@@ -1,35 +1,35 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""The Python implementation of the GRPC interoperability test server."""
-
-import argparse
-from concurrent import futures
-import logging
-
-import grpc
-from src.proto.grpc.testing import test_pb2_grpc
-
-from tests.interop import service
-from tests.interop import resources
-from tests.unit import test_common
-
-logging.basicConfig()
-_LOGGER = logging.getLogger(__name__)
-
-
+# Copyright 2015 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the GRPC interoperability test server."""
+
+import argparse
+from concurrent import futures
+import logging
+
+import grpc
+from src.proto.grpc.testing import test_pb2_grpc
+
+from tests.interop import service
+from tests.interop import resources
+from tests.unit import test_common
+
+logging.basicConfig()
+_LOGGER = logging.getLogger(__name__)
+
+
def parse_interop_server_arguments():
- parser = argparse.ArgumentParser()
+ parser = argparse.ArgumentParser()
parser.add_argument('--port',
type=int,
required=True,
@@ -43,7 +43,7 @@ def parse_interop_server_arguments():
type=resources.parse_bool,
help='require an ALTS connection')
return parser.parse_args()
-
+
def get_server_credentials(use_tls):
if use_tls:
@@ -57,20 +57,20 @@ def get_server_credentials(use_tls):
def serve():
args = parse_interop_server_arguments()
- server = test_common.test_server()
- test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
- server)
+ server = test_common.test_server()
+ test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
+ server)
if args.use_tls or args.use_alts:
credentials = get_server_credentials(args.use_tls)
- server.add_secure_port('[::]:{}'.format(args.port), credentials)
- else:
- server.add_insecure_port('[::]:{}'.format(args.port))
-
- server.start()
- _LOGGER.info('Server serving.')
- server.wait_for_termination()
- _LOGGER.info('Server stopped; exiting.')
-
-
-if __name__ == '__main__':
- serve()
+ server.add_secure_port('[::]:{}'.format(args.port), credentials)
+ else:
+ server.add_insecure_port('[::]:{}'.format(args.port))
+
+ server.start()
+ _LOGGER.info('Server serving.')
+ server.wait_for_termination()
+ _LOGGER.info('Server stopped; exiting.')
+
+
+if __name__ == '__main__':
+ serve()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/service.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/service.py
index 08bb0c45a2..1b29f7adbf 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/service.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/interop/service.py
@@ -1,96 +1,96 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""The Python implementation of the TestServicer."""
-
-import time
-
-import grpc
-
-from src.proto.grpc.testing import empty_pb2
-from src.proto.grpc.testing import messages_pb2
-from src.proto.grpc.testing import test_pb2_grpc
-
-_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
-_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
-_US_IN_A_SECOND = 1000 * 1000
-
-
-def _maybe_echo_metadata(servicer_context):
- """Copies metadata from request to response if it is present."""
- invocation_metadata = dict(servicer_context.invocation_metadata())
- if _INITIAL_METADATA_KEY in invocation_metadata:
- initial_metadatum = (_INITIAL_METADATA_KEY,
- invocation_metadata[_INITIAL_METADATA_KEY])
- servicer_context.send_initial_metadata((initial_metadatum,))
- if _TRAILING_METADATA_KEY in invocation_metadata:
- trailing_metadatum = (_TRAILING_METADATA_KEY,
- invocation_metadata[_TRAILING_METADATA_KEY])
- servicer_context.set_trailing_metadata((trailing_metadatum,))
-
-
-def _maybe_echo_status_and_message(request, servicer_context):
- """Sets the response context code and details if the request asks for them"""
- if request.HasField('response_status'):
- servicer_context.set_code(request.response_status.code)
- servicer_context.set_details(request.response_status.message)
-
-
-class TestService(test_pb2_grpc.TestServiceServicer):
-
- def EmptyCall(self, request, context):
- _maybe_echo_metadata(context)
- return empty_pb2.Empty()
-
- def UnaryCall(self, request, context):
- _maybe_echo_metadata(context)
- _maybe_echo_status_and_message(request, context)
- return messages_pb2.SimpleResponse(
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the TestServicer."""
+
+import time
+
+import grpc
+
+from src.proto.grpc.testing import empty_pb2
+from src.proto.grpc.testing import messages_pb2
+from src.proto.grpc.testing import test_pb2_grpc
+
+_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
+_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
+_US_IN_A_SECOND = 1000 * 1000
+
+
+def _maybe_echo_metadata(servicer_context):
+ """Copies metadata from request to response if it is present."""
+ invocation_metadata = dict(servicer_context.invocation_metadata())
+ if _INITIAL_METADATA_KEY in invocation_metadata:
+ initial_metadatum = (_INITIAL_METADATA_KEY,
+ invocation_metadata[_INITIAL_METADATA_KEY])
+ servicer_context.send_initial_metadata((initial_metadatum,))
+ if _TRAILING_METADATA_KEY in invocation_metadata:
+ trailing_metadatum = (_TRAILING_METADATA_KEY,
+ invocation_metadata[_TRAILING_METADATA_KEY])
+ servicer_context.set_trailing_metadata((trailing_metadatum,))
+
+
+def _maybe_echo_status_and_message(request, servicer_context):
+ """Sets the response context code and details if the request asks for them"""
+ if request.HasField('response_status'):
+ servicer_context.set_code(request.response_status.code)
+ servicer_context.set_details(request.response_status.message)
+
+
+class TestService(test_pb2_grpc.TestServiceServicer):
+
+ def EmptyCall(self, request, context):
+ _maybe_echo_metadata(context)
+ return empty_pb2.Empty()
+
+ def UnaryCall(self, request, context):
+ _maybe_echo_metadata(context)
+ _maybe_echo_status_and_message(request, context)
+ return messages_pb2.SimpleResponse(
payload=messages_pb2.Payload(type=messages_pb2.COMPRESSABLE,
body=b'\x00' * request.response_size))
-
- def StreamingOutputCall(self, request, context):
- _maybe_echo_status_and_message(request, context)
- for response_parameters in request.response_parameters:
- if response_parameters.interval_us != 0:
- time.sleep(response_parameters.interval_us / _US_IN_A_SECOND)
- yield messages_pb2.StreamingOutputCallResponse(
+
+ def StreamingOutputCall(self, request, context):
+ _maybe_echo_status_and_message(request, context)
+ for response_parameters in request.response_parameters:
+ if response_parameters.interval_us != 0:
+ time.sleep(response_parameters.interval_us / _US_IN_A_SECOND)
+ yield messages_pb2.StreamingOutputCallResponse(
payload=messages_pb2.Payload(type=request.response_type,
body=b'\x00' *
response_parameters.size))
-
- def StreamingInputCall(self, request_iterator, context):
- aggregate_size = 0
- for request in request_iterator:
- if request.payload is not None and request.payload.body:
- aggregate_size += len(request.payload.body)
- return messages_pb2.StreamingInputCallResponse(
- aggregated_payload_size=aggregate_size)
-
- def FullDuplexCall(self, request_iterator, context):
- _maybe_echo_metadata(context)
- for request in request_iterator:
- _maybe_echo_status_and_message(request, context)
- for response_parameters in request.response_parameters:
- if response_parameters.interval_us != 0:
+
+ def StreamingInputCall(self, request_iterator, context):
+ aggregate_size = 0
+ for request in request_iterator:
+ if request.payload is not None and request.payload.body:
+ aggregate_size += len(request.payload.body)
+ return messages_pb2.StreamingInputCallResponse(
+ aggregated_payload_size=aggregate_size)
+
+ def FullDuplexCall(self, request_iterator, context):
+ _maybe_echo_metadata(context)
+ for request in request_iterator:
+ _maybe_echo_status_and_message(request, context)
+ for response_parameters in request.response_parameters:
+ if response_parameters.interval_us != 0:
time.sleep(response_parameters.interval_us /
_US_IN_A_SECOND)
- yield messages_pb2.StreamingOutputCallResponse(
+ yield messages_pb2.StreamingOutputCallResponse(
payload=messages_pb2.Payload(type=request.payload.type,
body=b'\x00' *
response_parameters.size))
-
- # NOTE(nathaniel): Apparently this is the same as the full-duplex call?
- # NOTE(atash): It isn't even called in the interop spec (Oct 22 2015)...
- def HalfDuplexCall(self, request_iterator, context):
- return self.FullDuplexCall(request_iterator, context)
+
+ # NOTE(nathaniel): Apparently this is the same as the full-duplex call?
+ # NOTE(atash): It isn't even called in the interop spec (Oct 22 2015)...
+ def HalfDuplexCall(self, request_iterator, context):
+ return self.FullDuplexCall(request_iterator, context)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/__init__.py
index 5772620b60..8d89990e82 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 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.
+# Copyright 2016 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_client.py
index 17835e7c0d..60ac8f02b9 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_client.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_client.py
@@ -1,202 +1,202 @@
-# Copyright 2016 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.
-"""Defines test client behaviors (UNARY/STREAMING) (SYNC/ASYNC)."""
-
-import abc
-import threading
-import time
-
-from concurrent import futures
-from six.moves import queue
-
-import grpc
-from src.proto.grpc.testing import messages_pb2
-from src.proto.grpc.testing import benchmark_service_pb2_grpc
-from tests.unit import resources
-from tests.unit import test_common
-
-_TIMEOUT = 60 * 60 * 24
-
-
-class GenericStub(object):
-
- def __init__(self, channel):
- self.UnaryCall = channel.unary_unary(
- '/grpc.testing.BenchmarkService/UnaryCall')
- self.StreamingCall = channel.stream_stream(
- '/grpc.testing.BenchmarkService/StreamingCall')
-
-
-class BenchmarkClient:
- """Benchmark client interface that exposes a non-blocking send_request()."""
-
- __metaclass__ = abc.ABCMeta
-
- def __init__(self, server, config, hist):
- # Create the stub
- if config.HasField('security_params'):
- creds = grpc.ssl_channel_credentials(
- resources.test_root_certificates())
- channel = test_common.test_secure_channel(
- server, creds, config.security_params.server_host_override)
- else:
- channel = grpc.insecure_channel(server)
-
- # waits for the channel to be ready before we start sending messages
- grpc.channel_ready_future(channel).result()
-
- if config.payload_config.WhichOneof('payload') == 'simple_params':
- self._generic = False
- self._stub = benchmark_service_pb2_grpc.BenchmarkServiceStub(
- channel)
- payload = messages_pb2.Payload(
+# Copyright 2016 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.
+"""Defines test client behaviors (UNARY/STREAMING) (SYNC/ASYNC)."""
+
+import abc
+import threading
+import time
+
+from concurrent import futures
+from six.moves import queue
+
+import grpc
+from src.proto.grpc.testing import messages_pb2
+from src.proto.grpc.testing import benchmark_service_pb2_grpc
+from tests.unit import resources
+from tests.unit import test_common
+
+_TIMEOUT = 60 * 60 * 24
+
+
+class GenericStub(object):
+
+ def __init__(self, channel):
+ self.UnaryCall = channel.unary_unary(
+ '/grpc.testing.BenchmarkService/UnaryCall')
+ self.StreamingCall = channel.stream_stream(
+ '/grpc.testing.BenchmarkService/StreamingCall')
+
+
+class BenchmarkClient:
+ """Benchmark client interface that exposes a non-blocking send_request()."""
+
+ __metaclass__ = abc.ABCMeta
+
+ def __init__(self, server, config, hist):
+ # Create the stub
+ if config.HasField('security_params'):
+ creds = grpc.ssl_channel_credentials(
+ resources.test_root_certificates())
+ channel = test_common.test_secure_channel(
+ server, creds, config.security_params.server_host_override)
+ else:
+ channel = grpc.insecure_channel(server)
+
+ # waits for the channel to be ready before we start sending messages
+ grpc.channel_ready_future(channel).result()
+
+ if config.payload_config.WhichOneof('payload') == 'simple_params':
+ self._generic = False
+ self._stub = benchmark_service_pb2_grpc.BenchmarkServiceStub(
+ channel)
+ payload = messages_pb2.Payload(
body=bytes(b'\0' *
config.payload_config.simple_params.req_size))
- self._request = messages_pb2.SimpleRequest(
- payload=payload,
- response_size=config.payload_config.simple_params.resp_size)
- else:
- self._generic = True
- self._stub = GenericStub(channel)
+ self._request = messages_pb2.SimpleRequest(
+ payload=payload,
+ response_size=config.payload_config.simple_params.resp_size)
+ else:
+ self._generic = True
+ self._stub = GenericStub(channel)
self._request = bytes(b'\0' *
config.payload_config.bytebuf_params.req_size)
-
- self._hist = hist
- self._response_callbacks = []
-
- def add_response_callback(self, callback):
- """callback will be invoked as callback(client, query_time)"""
- self._response_callbacks.append(callback)
-
- @abc.abstractmethod
- def send_request(self):
- """Non-blocking wrapper for a client's request operation."""
- raise NotImplementedError()
-
- def start(self):
- pass
-
- def stop(self):
- pass
-
- def _handle_response(self, client, query_time):
- self._hist.add(query_time * 1e9) # Report times in nanoseconds
- for callback in self._response_callbacks:
- callback(client, query_time)
-
-
-class UnarySyncBenchmarkClient(BenchmarkClient):
-
- def __init__(self, server, config, hist):
- super(UnarySyncBenchmarkClient, self).__init__(server, config, hist)
- self._pool = futures.ThreadPoolExecutor(
- max_workers=config.outstanding_rpcs_per_channel)
-
- def send_request(self):
- # Send requests in separate threads to support multiple outstanding rpcs
- # (See src/proto/grpc/testing/control.proto)
- self._pool.submit(self._dispatch_request)
-
- def stop(self):
- self._pool.shutdown(wait=True)
- self._stub = None
-
- def _dispatch_request(self):
- start_time = time.time()
- self._stub.UnaryCall(self._request, _TIMEOUT)
- end_time = time.time()
- self._handle_response(self, end_time - start_time)
-
-
-class UnaryAsyncBenchmarkClient(BenchmarkClient):
-
- def send_request(self):
- # Use the Future callback api to support multiple outstanding rpcs
- start_time = time.time()
- response_future = self._stub.UnaryCall.future(self._request, _TIMEOUT)
- response_future.add_done_callback(
- lambda resp: self._response_received(start_time, resp))
-
- def _response_received(self, start_time, resp):
- resp.result()
- end_time = time.time()
- self._handle_response(self, end_time - start_time)
-
- def stop(self):
- self._stub = None
-
-
-class _SyncStream(object):
-
- def __init__(self, stub, generic, request, handle_response):
- self._stub = stub
- self._generic = generic
- self._request = request
- self._handle_response = handle_response
- self._is_streaming = False
- self._request_queue = queue.Queue()
- self._send_time_queue = queue.Queue()
-
- def send_request(self):
- self._send_time_queue.put(time.time())
- self._request_queue.put(self._request)
-
- def start(self):
- self._is_streaming = True
- response_stream = self._stub.StreamingCall(self._request_generator(),
- _TIMEOUT)
- for _ in response_stream:
- self._handle_response(
- self,
- time.time() - self._send_time_queue.get_nowait())
-
- def stop(self):
- self._is_streaming = False
-
- def _request_generator(self):
- while self._is_streaming:
- try:
- request = self._request_queue.get(block=True, timeout=1.0)
- yield request
- except queue.Empty:
- pass
-
-
-class StreamingSyncBenchmarkClient(BenchmarkClient):
-
- def __init__(self, server, config, hist):
- super(StreamingSyncBenchmarkClient, self).__init__(server, config, hist)
- self._pool = futures.ThreadPoolExecutor(
- max_workers=config.outstanding_rpcs_per_channel)
- self._streams = [
- _SyncStream(self._stub, self._generic, self._request,
- self._handle_response)
- for _ in range(config.outstanding_rpcs_per_channel)
- ]
- self._curr_stream = 0
-
- def send_request(self):
- # Use a round_robin scheduler to determine what stream to send on
- self._streams[self._curr_stream].send_request()
- self._curr_stream = (self._curr_stream + 1) % len(self._streams)
-
- def start(self):
- for stream in self._streams:
- self._pool.submit(stream.start)
-
- def stop(self):
- for stream in self._streams:
- stream.stop()
- self._pool.shutdown(wait=True)
- self._stub = None
+
+ self._hist = hist
+ self._response_callbacks = []
+
+ def add_response_callback(self, callback):
+ """callback will be invoked as callback(client, query_time)"""
+ self._response_callbacks.append(callback)
+
+ @abc.abstractmethod
+ def send_request(self):
+ """Non-blocking wrapper for a client's request operation."""
+ raise NotImplementedError()
+
+ def start(self):
+ pass
+
+ def stop(self):
+ pass
+
+ def _handle_response(self, client, query_time):
+ self._hist.add(query_time * 1e9) # Report times in nanoseconds
+ for callback in self._response_callbacks:
+ callback(client, query_time)
+
+
+class UnarySyncBenchmarkClient(BenchmarkClient):
+
+ def __init__(self, server, config, hist):
+ super(UnarySyncBenchmarkClient, self).__init__(server, config, hist)
+ self._pool = futures.ThreadPoolExecutor(
+ max_workers=config.outstanding_rpcs_per_channel)
+
+ def send_request(self):
+ # Send requests in separate threads to support multiple outstanding rpcs
+ # (See src/proto/grpc/testing/control.proto)
+ self._pool.submit(self._dispatch_request)
+
+ def stop(self):
+ self._pool.shutdown(wait=True)
+ self._stub = None
+
+ def _dispatch_request(self):
+ start_time = time.time()
+ self._stub.UnaryCall(self._request, _TIMEOUT)
+ end_time = time.time()
+ self._handle_response(self, end_time - start_time)
+
+
+class UnaryAsyncBenchmarkClient(BenchmarkClient):
+
+ def send_request(self):
+ # Use the Future callback api to support multiple outstanding rpcs
+ start_time = time.time()
+ response_future = self._stub.UnaryCall.future(self._request, _TIMEOUT)
+ response_future.add_done_callback(
+ lambda resp: self._response_received(start_time, resp))
+
+ def _response_received(self, start_time, resp):
+ resp.result()
+ end_time = time.time()
+ self._handle_response(self, end_time - start_time)
+
+ def stop(self):
+ self._stub = None
+
+
+class _SyncStream(object):
+
+ def __init__(self, stub, generic, request, handle_response):
+ self._stub = stub
+ self._generic = generic
+ self._request = request
+ self._handle_response = handle_response
+ self._is_streaming = False
+ self._request_queue = queue.Queue()
+ self._send_time_queue = queue.Queue()
+
+ def send_request(self):
+ self._send_time_queue.put(time.time())
+ self._request_queue.put(self._request)
+
+ def start(self):
+ self._is_streaming = True
+ response_stream = self._stub.StreamingCall(self._request_generator(),
+ _TIMEOUT)
+ for _ in response_stream:
+ self._handle_response(
+ self,
+ time.time() - self._send_time_queue.get_nowait())
+
+ def stop(self):
+ self._is_streaming = False
+
+ def _request_generator(self):
+ while self._is_streaming:
+ try:
+ request = self._request_queue.get(block=True, timeout=1.0)
+ yield request
+ except queue.Empty:
+ pass
+
+
+class StreamingSyncBenchmarkClient(BenchmarkClient):
+
+ def __init__(self, server, config, hist):
+ super(StreamingSyncBenchmarkClient, self).__init__(server, config, hist)
+ self._pool = futures.ThreadPoolExecutor(
+ max_workers=config.outstanding_rpcs_per_channel)
+ self._streams = [
+ _SyncStream(self._stub, self._generic, self._request,
+ self._handle_response)
+ for _ in range(config.outstanding_rpcs_per_channel)
+ ]
+ self._curr_stream = 0
+
+ def send_request(self):
+ # Use a round_robin scheduler to determine what stream to send on
+ self._streams[self._curr_stream].send_request()
+ self._curr_stream = (self._curr_stream + 1) % len(self._streams)
+
+ def start(self):
+ for stream in self._streams:
+ self._pool.submit(stream.start)
+
+ def stop(self):
+ for stream in self._streams:
+ stream.stop()
+ self._pool.shutdown(wait=True)
+ self._stub = None
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_server.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_server.py
index 75280bd771..6b6b9ea380 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_server.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/benchmark_server.py
@@ -1,44 +1,44 @@
-# Copyright 2016 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.
-
-from src.proto.grpc.testing import messages_pb2
-from src.proto.grpc.testing import benchmark_service_pb2_grpc
-
-
-class BenchmarkServer(benchmark_service_pb2_grpc.BenchmarkServiceServicer):
- """Synchronous Server implementation for the Benchmark service."""
-
- def UnaryCall(self, request, context):
+# Copyright 2016 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.
+
+from src.proto.grpc.testing import messages_pb2
+from src.proto.grpc.testing import benchmark_service_pb2_grpc
+
+
+class BenchmarkServer(benchmark_service_pb2_grpc.BenchmarkServiceServicer):
+ """Synchronous Server implementation for the Benchmark service."""
+
+ def UnaryCall(self, request, context):
payload = messages_pb2.Payload(body=b'\0' * request.response_size)
- return messages_pb2.SimpleResponse(payload=payload)
-
- def StreamingCall(self, request_iterator, context):
- for request in request_iterator:
+ return messages_pb2.SimpleResponse(payload=payload)
+
+ def StreamingCall(self, request_iterator, context):
+ for request in request_iterator:
payload = messages_pb2.Payload(body=b'\0' * request.response_size)
- yield messages_pb2.SimpleResponse(payload=payload)
-
-
+ yield messages_pb2.SimpleResponse(payload=payload)
+
+
class GenericBenchmarkServer(benchmark_service_pb2_grpc.BenchmarkServiceServicer
):
- """Generic Server implementation for the Benchmark service."""
-
- def __init__(self, resp_size):
+ """Generic Server implementation for the Benchmark service."""
+
+ def __init__(self, resp_size):
self._response = b'\0' * resp_size
-
- def UnaryCall(self, request, context):
- return self._response
-
- def StreamingCall(self, request_iterator, context):
- for request in request_iterator:
- yield self._response
+
+ def UnaryCall(self, request, context):
+ return self._response
+
+ def StreamingCall(self, request_iterator, context):
+ for request in request_iterator:
+ yield self._response
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/client_runner.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/client_runner.py
index c5d299f646..c8c48183ac 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/client_runner.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/client_runner.py
@@ -1,90 +1,90 @@
-# Copyright 2016 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.
-"""Defines behavior for WHEN clients send requests.
-
-Each client exposes a non-blocking send_request() method that the
-ClientRunner invokes either periodically or in response to some event.
-"""
-
-import abc
-import threading
-import time
-
-
-class ClientRunner:
- """Abstract interface for sending requests from clients."""
-
- __metaclass__ = abc.ABCMeta
-
- def __init__(self, client):
- self._client = client
-
- @abc.abstractmethod
- def start(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def stop(self):
- raise NotImplementedError()
-
-
-class OpenLoopClientRunner(ClientRunner):
-
- def __init__(self, client, interval_generator):
- super(OpenLoopClientRunner, self).__init__(client)
- self._is_running = False
- self._interval_generator = interval_generator
+# Copyright 2016 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.
+"""Defines behavior for WHEN clients send requests.
+
+Each client exposes a non-blocking send_request() method that the
+ClientRunner invokes either periodically or in response to some event.
+"""
+
+import abc
+import threading
+import time
+
+
+class ClientRunner:
+ """Abstract interface for sending requests from clients."""
+
+ __metaclass__ = abc.ABCMeta
+
+ def __init__(self, client):
+ self._client = client
+
+ @abc.abstractmethod
+ def start(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def stop(self):
+ raise NotImplementedError()
+
+
+class OpenLoopClientRunner(ClientRunner):
+
+ def __init__(self, client, interval_generator):
+ super(OpenLoopClientRunner, self).__init__(client)
+ self._is_running = False
+ self._interval_generator = interval_generator
self._dispatch_thread = threading.Thread(target=self._dispatch_requests,
args=())
-
- def start(self):
- self._is_running = True
- self._client.start()
- self._dispatch_thread.start()
-
- def stop(self):
- self._is_running = False
- self._client.stop()
- self._dispatch_thread.join()
- self._client = None
-
- def _dispatch_requests(self):
- while self._is_running:
- self._client.send_request()
- time.sleep(next(self._interval_generator))
-
-
-class ClosedLoopClientRunner(ClientRunner):
-
- def __init__(self, client, request_count):
- super(ClosedLoopClientRunner, self).__init__(client)
- self._is_running = False
- self._request_count = request_count
- # Send a new request on each response for closed loop
- self._client.add_response_callback(self._send_request)
-
- def start(self):
- self._is_running = True
- self._client.start()
- for _ in range(self._request_count):
- self._client.send_request()
-
- def stop(self):
- self._is_running = False
- self._client.stop()
- self._client = None
-
- def _send_request(self, client, response_time):
- if self._is_running:
- client.send_request()
+
+ def start(self):
+ self._is_running = True
+ self._client.start()
+ self._dispatch_thread.start()
+
+ def stop(self):
+ self._is_running = False
+ self._client.stop()
+ self._dispatch_thread.join()
+ self._client = None
+
+ def _dispatch_requests(self):
+ while self._is_running:
+ self._client.send_request()
+ time.sleep(next(self._interval_generator))
+
+
+class ClosedLoopClientRunner(ClientRunner):
+
+ def __init__(self, client, request_count):
+ super(ClosedLoopClientRunner, self).__init__(client)
+ self._is_running = False
+ self._request_count = request_count
+ # Send a new request on each response for closed loop
+ self._client.add_response_callback(self._send_request)
+
+ def start(self):
+ self._is_running = True
+ self._client.start()
+ for _ in range(self._request_count):
+ self._client.send_request()
+
+ def stop(self):
+ self._is_running = False
+ self._client.stop()
+ self._client = None
+
+ def _send_request(self, client, response_time):
+ if self._is_running:
+ client.send_request()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/histogram.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/histogram.py
index 8139a6ee2f..33ef27961e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/histogram.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/histogram.py
@@ -1,70 +1,70 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import math
-import threading
-
-from src.proto.grpc.testing import stats_pb2
-
-
-class Histogram(object):
- """Histogram class used for recording performance testing data.
-
- This class is thread safe.
- """
-
- def __init__(self, resolution, max_possible):
- self._lock = threading.Lock()
- self._resolution = resolution
- self._max_possible = max_possible
- self._sum = 0
- self._sum_of_squares = 0
- self.multiplier = 1.0 + self._resolution
- self._count = 0
- self._min = self._max_possible
- self._max = 0
- self._buckets = [0] * (self._bucket_for(self._max_possible) + 1)
-
- def reset(self):
- with self._lock:
- self._sum = 0
- self._sum_of_squares = 0
- self._count = 0
- self._min = self._max_possible
- self._max = 0
- self._buckets = [0] * (self._bucket_for(self._max_possible) + 1)
-
- def add(self, val):
- with self._lock:
- self._sum += val
- self._sum_of_squares += val * val
- self._count += 1
- self._min = min(self._min, val)
- self._max = max(self._max, val)
- self._buckets[self._bucket_for(val)] += 1
-
- def get_data(self):
- with self._lock:
- data = stats_pb2.HistogramData()
- data.bucket.extend(self._buckets)
- data.min_seen = self._min
- data.max_seen = self._max
- data.sum = self._sum
- data.sum_of_squares = self._sum_of_squares
- data.count = self._count
- return data
-
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+import threading
+
+from src.proto.grpc.testing import stats_pb2
+
+
+class Histogram(object):
+ """Histogram class used for recording performance testing data.
+
+ This class is thread safe.
+ """
+
+ def __init__(self, resolution, max_possible):
+ self._lock = threading.Lock()
+ self._resolution = resolution
+ self._max_possible = max_possible
+ self._sum = 0
+ self._sum_of_squares = 0
+ self.multiplier = 1.0 + self._resolution
+ self._count = 0
+ self._min = self._max_possible
+ self._max = 0
+ self._buckets = [0] * (self._bucket_for(self._max_possible) + 1)
+
+ def reset(self):
+ with self._lock:
+ self._sum = 0
+ self._sum_of_squares = 0
+ self._count = 0
+ self._min = self._max_possible
+ self._max = 0
+ self._buckets = [0] * (self._bucket_for(self._max_possible) + 1)
+
+ def add(self, val):
+ with self._lock:
+ self._sum += val
+ self._sum_of_squares += val * val
+ self._count += 1
+ self._min = min(self._min, val)
+ self._max = max(self._max, val)
+ self._buckets[self._bucket_for(val)] += 1
+
+ def get_data(self):
+ with self._lock:
+ data = stats_pb2.HistogramData()
+ data.bucket.extend(self._buckets)
+ data.min_seen = self._min
+ data.max_seen = self._max
+ data.sum = self._sum
+ data.sum_of_squares = self._sum_of_squares
+ data.count = self._count
+ return data
+
def merge(self, another_data):
with self._lock:
for i in range(len(self._buckets)):
@@ -75,6 +75,6 @@ class Histogram(object):
self._sum_of_squares += another_data.sum_of_squares
self._count += another_data.count
- def _bucket_for(self, val):
- val = min(val, self._max_possible)
- return int(math.log(val, self.multiplier))
+ def _bucket_for(self, val):
+ val = min(val, self._max_possible)
+ return int(math.log(val, self.multiplier))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/qps_worker.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/qps_worker.py
index a7e692821a..a78751bda1 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/qps_worker.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/qps_worker.py
@@ -1,46 +1,46 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""The entry point for the qps worker."""
-
-import argparse
-import time
-
-import grpc
-from src.proto.grpc.testing import worker_service_pb2_grpc
-
-from tests.qps import worker_server
-from tests.unit import test_common
-
-
-def run_worker_server(port):
- server = test_common.test_server()
- servicer = worker_server.WorkerServer()
- worker_service_pb2_grpc.add_WorkerServiceServicer_to_server(
- servicer, server)
- server.add_insecure_port('[::]:{}'.format(port))
- server.start()
- servicer.wait_for_quit()
- server.stop(0)
-
-
-if __name__ == '__main__':
- parser = argparse.ArgumentParser(
- description='gRPC Python performance testing worker')
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The entry point for the qps worker."""
+
+import argparse
+import time
+
+import grpc
+from src.proto.grpc.testing import worker_service_pb2_grpc
+
+from tests.qps import worker_server
+from tests.unit import test_common
+
+
+def run_worker_server(port):
+ server = test_common.test_server()
+ servicer = worker_server.WorkerServer()
+ worker_service_pb2_grpc.add_WorkerServiceServicer_to_server(
+ servicer, server)
+ server.add_insecure_port('[::]:{}'.format(port))
+ server.start()
+ servicer.wait_for_quit()
+ server.stop(0)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(
+ description='gRPC Python performance testing worker')
parser.add_argument('--driver_port',
type=int,
dest='port',
help='The port the worker should listen on')
- args = parser.parse_args()
-
- run_worker_server(args.port)
+ args = parser.parse_args()
+
+ run_worker_server(args.port)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/worker_server.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/worker_server.py
index 65b081e5d1..c6c1ed27d8 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/worker_server.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/qps/worker_server.py
@@ -1,186 +1,186 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import multiprocessing
-import random
-import threading
-import time
-
-from concurrent import futures
-import grpc
-from src.proto.grpc.testing import control_pb2
-from src.proto.grpc.testing import benchmark_service_pb2_grpc
-from src.proto.grpc.testing import worker_service_pb2_grpc
-from src.proto.grpc.testing import stats_pb2
-
-from tests.qps import benchmark_client
-from tests.qps import benchmark_server
-from tests.qps import client_runner
-from tests.qps import histogram
-from tests.unit import resources
-from tests.unit import test_common
-
-
-class WorkerServer(worker_service_pb2_grpc.WorkerServiceServicer):
- """Python Worker Server implementation."""
-
- def __init__(self):
- self._quit_event = threading.Event()
-
- def RunServer(self, request_iterator, context):
- config = next(request_iterator).setup #pylint: disable=stop-iteration-return
- server, port = self._create_server(config)
- cores = multiprocessing.cpu_count()
- server.start()
- start_time = time.time()
- yield self._get_server_status(start_time, start_time, port, cores)
-
- for request in request_iterator:
- end_time = time.time()
- status = self._get_server_status(start_time, end_time, port, cores)
- if request.mark.reset:
- start_time = end_time
- yield status
- server.stop(None)
-
- def _get_server_status(self, start_time, end_time, port, cores):
- end_time = time.time()
- elapsed_time = end_time - start_time
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import multiprocessing
+import random
+import threading
+import time
+
+from concurrent import futures
+import grpc
+from src.proto.grpc.testing import control_pb2
+from src.proto.grpc.testing import benchmark_service_pb2_grpc
+from src.proto.grpc.testing import worker_service_pb2_grpc
+from src.proto.grpc.testing import stats_pb2
+
+from tests.qps import benchmark_client
+from tests.qps import benchmark_server
+from tests.qps import client_runner
+from tests.qps import histogram
+from tests.unit import resources
+from tests.unit import test_common
+
+
+class WorkerServer(worker_service_pb2_grpc.WorkerServiceServicer):
+ """Python Worker Server implementation."""
+
+ def __init__(self):
+ self._quit_event = threading.Event()
+
+ def RunServer(self, request_iterator, context):
+ config = next(request_iterator).setup #pylint: disable=stop-iteration-return
+ server, port = self._create_server(config)
+ cores = multiprocessing.cpu_count()
+ server.start()
+ start_time = time.time()
+ yield self._get_server_status(start_time, start_time, port, cores)
+
+ for request in request_iterator:
+ end_time = time.time()
+ status = self._get_server_status(start_time, end_time, port, cores)
+ if request.mark.reset:
+ start_time = end_time
+ yield status
+ server.stop(None)
+
+ def _get_server_status(self, start_time, end_time, port, cores):
+ end_time = time.time()
+ elapsed_time = end_time - start_time
stats = stats_pb2.ServerStats(time_elapsed=elapsed_time,
time_user=elapsed_time,
time_system=elapsed_time)
- return control_pb2.ServerStatus(stats=stats, port=port, cores=cores)
-
- def _create_server(self, config):
- if config.async_server_threads == 0:
- # This is the default concurrent.futures thread pool size, but
- # None doesn't seem to work
- server_threads = multiprocessing.cpu_count() * 5
- else:
- server_threads = config.async_server_threads
- server = test_common.test_server(max_workers=server_threads)
- if config.server_type == control_pb2.ASYNC_SERVER:
- servicer = benchmark_server.BenchmarkServer()
- benchmark_service_pb2_grpc.add_BenchmarkServiceServicer_to_server(
- servicer, server)
- elif config.server_type == control_pb2.ASYNC_GENERIC_SERVER:
- resp_size = config.payload_config.bytebuf_params.resp_size
- servicer = benchmark_server.GenericBenchmarkServer(resp_size)
- method_implementations = {
- 'StreamingCall':
+ return control_pb2.ServerStatus(stats=stats, port=port, cores=cores)
+
+ def _create_server(self, config):
+ if config.async_server_threads == 0:
+ # This is the default concurrent.futures thread pool size, but
+ # None doesn't seem to work
+ server_threads = multiprocessing.cpu_count() * 5
+ else:
+ server_threads = config.async_server_threads
+ server = test_common.test_server(max_workers=server_threads)
+ if config.server_type == control_pb2.ASYNC_SERVER:
+ servicer = benchmark_server.BenchmarkServer()
+ benchmark_service_pb2_grpc.add_BenchmarkServiceServicer_to_server(
+ servicer, server)
+ elif config.server_type == control_pb2.ASYNC_GENERIC_SERVER:
+ resp_size = config.payload_config.bytebuf_params.resp_size
+ servicer = benchmark_server.GenericBenchmarkServer(resp_size)
+ method_implementations = {
+ 'StreamingCall':
grpc.stream_stream_rpc_method_handler(servicer.StreamingCall
),
- 'UnaryCall':
+ 'UnaryCall':
grpc.unary_unary_rpc_method_handler(servicer.UnaryCall),
- }
- handler = grpc.method_handlers_generic_handler(
- 'grpc.testing.BenchmarkService', method_implementations)
- server.add_generic_rpc_handlers((handler,))
- else:
- raise Exception('Unsupported server type {}'.format(
- config.server_type))
-
- if config.HasField('security_params'): # Use SSL
- server_creds = grpc.ssl_server_credentials(
- ((resources.private_key(), resources.certificate_chain()),))
- port = server.add_secure_port('[::]:{}'.format(config.port),
- server_creds)
- else:
- port = server.add_insecure_port('[::]:{}'.format(config.port))
-
- return (server, port)
-
- def RunClient(self, request_iterator, context):
- config = next(request_iterator).setup #pylint: disable=stop-iteration-return
- client_runners = []
- qps_data = histogram.Histogram(config.histogram_params.resolution,
- config.histogram_params.max_possible)
- start_time = time.time()
-
- # Create a client for each channel
- for i in range(config.client_channels):
- server = config.server_targets[i % len(config.server_targets)]
- runner = self._create_client_runner(server, config, qps_data)
- client_runners.append(runner)
- runner.start()
-
- end_time = time.time()
- yield self._get_client_status(start_time, end_time, qps_data)
-
- # Respond to stat requests
- for request in request_iterator:
- end_time = time.time()
- status = self._get_client_status(start_time, end_time, qps_data)
- if request.mark.reset:
- qps_data.reset()
- start_time = time.time()
- yield status
-
- # Cleanup the clients
- for runner in client_runners:
- runner.stop()
-
- def _get_client_status(self, start_time, end_time, qps_data):
- latencies = qps_data.get_data()
- end_time = time.time()
- elapsed_time = end_time - start_time
+ }
+ handler = grpc.method_handlers_generic_handler(
+ 'grpc.testing.BenchmarkService', method_implementations)
+ server.add_generic_rpc_handlers((handler,))
+ else:
+ raise Exception('Unsupported server type {}'.format(
+ config.server_type))
+
+ if config.HasField('security_params'): # Use SSL
+ server_creds = grpc.ssl_server_credentials(
+ ((resources.private_key(), resources.certificate_chain()),))
+ port = server.add_secure_port('[::]:{}'.format(config.port),
+ server_creds)
+ else:
+ port = server.add_insecure_port('[::]:{}'.format(config.port))
+
+ return (server, port)
+
+ def RunClient(self, request_iterator, context):
+ config = next(request_iterator).setup #pylint: disable=stop-iteration-return
+ client_runners = []
+ qps_data = histogram.Histogram(config.histogram_params.resolution,
+ config.histogram_params.max_possible)
+ start_time = time.time()
+
+ # Create a client for each channel
+ for i in range(config.client_channels):
+ server = config.server_targets[i % len(config.server_targets)]
+ runner = self._create_client_runner(server, config, qps_data)
+ client_runners.append(runner)
+ runner.start()
+
+ end_time = time.time()
+ yield self._get_client_status(start_time, end_time, qps_data)
+
+ # Respond to stat requests
+ for request in request_iterator:
+ end_time = time.time()
+ status = self._get_client_status(start_time, end_time, qps_data)
+ if request.mark.reset:
+ qps_data.reset()
+ start_time = time.time()
+ yield status
+
+ # Cleanup the clients
+ for runner in client_runners:
+ runner.stop()
+
+ def _get_client_status(self, start_time, end_time, qps_data):
+ latencies = qps_data.get_data()
+ end_time = time.time()
+ elapsed_time = end_time - start_time
stats = stats_pb2.ClientStats(latencies=latencies,
time_elapsed=elapsed_time,
time_user=elapsed_time,
time_system=elapsed_time)
- return control_pb2.ClientStatus(stats=stats)
-
- def _create_client_runner(self, server, config, qps_data):
- if config.client_type == control_pb2.SYNC_CLIENT:
- if config.rpc_type == control_pb2.UNARY:
- client = benchmark_client.UnarySyncBenchmarkClient(
- server, config, qps_data)
- elif config.rpc_type == control_pb2.STREAMING:
- client = benchmark_client.StreamingSyncBenchmarkClient(
- server, config, qps_data)
- elif config.client_type == control_pb2.ASYNC_CLIENT:
- if config.rpc_type == control_pb2.UNARY:
- client = benchmark_client.UnaryAsyncBenchmarkClient(
- server, config, qps_data)
- else:
- raise Exception('Async streaming client not supported')
- else:
- raise Exception('Unsupported client type {}'.format(
- config.client_type))
-
- # In multi-channel tests, we split the load across all channels
- load_factor = float(config.client_channels)
- if config.load_params.WhichOneof('load') == 'closed_loop':
- runner = client_runner.ClosedLoopClientRunner(
- client, config.outstanding_rpcs_per_channel)
- else: # Open loop Poisson
- alpha = config.load_params.poisson.offered_load / load_factor
-
- def poisson():
- while True:
- yield random.expovariate(alpha)
-
- runner = client_runner.OpenLoopClientRunner(client, poisson())
-
- return runner
-
- def CoreCount(self, request, context):
- return control_pb2.CoreResponse(cores=multiprocessing.cpu_count())
-
- def QuitWorker(self, request, context):
- self._quit_event.set()
- return control_pb2.Void()
-
- def wait_for_quit(self):
- self._quit_event.wait()
+ return control_pb2.ClientStatus(stats=stats)
+
+ def _create_client_runner(self, server, config, qps_data):
+ if config.client_type == control_pb2.SYNC_CLIENT:
+ if config.rpc_type == control_pb2.UNARY:
+ client = benchmark_client.UnarySyncBenchmarkClient(
+ server, config, qps_data)
+ elif config.rpc_type == control_pb2.STREAMING:
+ client = benchmark_client.StreamingSyncBenchmarkClient(
+ server, config, qps_data)
+ elif config.client_type == control_pb2.ASYNC_CLIENT:
+ if config.rpc_type == control_pb2.UNARY:
+ client = benchmark_client.UnaryAsyncBenchmarkClient(
+ server, config, qps_data)
+ else:
+ raise Exception('Async streaming client not supported')
+ else:
+ raise Exception('Unsupported client type {}'.format(
+ config.client_type))
+
+ # In multi-channel tests, we split the load across all channels
+ load_factor = float(config.client_channels)
+ if config.load_params.WhichOneof('load') == 'closed_loop':
+ runner = client_runner.ClosedLoopClientRunner(
+ client, config.outstanding_rpcs_per_channel)
+ else: # Open loop Poisson
+ alpha = config.load_params.poisson.offered_load / load_factor
+
+ def poisson():
+ while True:
+ yield random.expovariate(alpha)
+
+ runner = client_runner.OpenLoopClientRunner(client, poisson())
+
+ return runner
+
+ def CoreCount(self, request, context):
+ return control_pb2.CoreResponse(cores=multiprocessing.cpu_count())
+
+ def QuitWorker(self, request, context):
+ self._quit_event.set()
+ return control_pb2.Void()
+
+ def wait_for_quit(self):
+ self._quit_event.wait()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/__init__.py
index 5772620b60..8d89990e82 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 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.
+# Copyright 2016 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py
index 169e55022d..2650da3d7d 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py
@@ -1,195 +1,195 @@
-# Copyright 2016 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.
-"""Tests of grpc_reflection.v1alpha.reflection."""
-
-import unittest
-
-import grpc
-
-from grpc_reflection.v1alpha import reflection
-from grpc_reflection.v1alpha import reflection_pb2
-from grpc_reflection.v1alpha import reflection_pb2_grpc
-
-from google.protobuf import descriptor_pool
-from google.protobuf import descriptor_pb2
-
-from src.proto.grpc.testing import empty_pb2
-from src.proto.grpc.testing.proto2 import empty2_extensions_pb2
-
-from tests.unit import test_common
-
-_EMPTY_PROTO_FILE_NAME = 'src/proto/grpc/testing/empty.proto'
-_EMPTY_PROTO_SYMBOL_NAME = 'grpc.testing.Empty'
-_SERVICE_NAMES = ('Angstrom', 'Bohr', 'Curie', 'Dyson', 'Einstein', 'Feynman',
- 'Galilei')
-_EMPTY_EXTENSIONS_SYMBOL_NAME = 'grpc.testing.proto2.EmptyWithExtensions'
-_EMPTY_EXTENSIONS_NUMBERS = (
- 124,
- 125,
- 126,
- 127,
- 128,
-)
-
-
-def _file_descriptor_to_proto(descriptor):
- proto = descriptor_pb2.FileDescriptorProto()
- descriptor.CopyToProto(proto)
- return proto.SerializeToString()
-
-
-class ReflectionServicerTest(unittest.TestCase):
-
- # TODO(https://github.com/grpc/grpc/issues/17844)
- # Bazel + Python 3 will result in creating two different instance of
- # DESCRIPTOR for each message. So, the equal comparison between protobuf
- # returned by stub and manually crafted protobuf will always fail.
- def _assert_sequence_of_proto_equal(self, x, y):
- self.assertSequenceEqual(
- tuple(proto.SerializeToString() for proto in x),
- tuple(proto.SerializeToString() for proto in y),
- )
-
- def setUp(self):
- self._server = test_common.test_server()
- reflection.enable_server_reflection(_SERVICE_NAMES, self._server)
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
- self._stub = reflection_pb2_grpc.ServerReflectionStub(self._channel)
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def testFileByName(self):
- requests = (
- reflection_pb2.ServerReflectionRequest(
- file_by_filename=_EMPTY_PROTO_FILE_NAME),
- reflection_pb2.ServerReflectionRequest(
- file_by_filename='i-donut-exist'),
- )
- responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
- expected_responses = (
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- file_descriptor_response=reflection_pb2.FileDescriptorResponse(
- file_descriptor_proto=(
- _file_descriptor_to_proto(empty_pb2.DESCRIPTOR),))),
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- error_response=reflection_pb2.ErrorResponse(
- error_code=grpc.StatusCode.NOT_FOUND.value[0],
- error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
- )),
- )
- self._assert_sequence_of_proto_equal(expected_responses, responses)
-
- def testFileBySymbol(self):
- requests = (
- reflection_pb2.ServerReflectionRequest(
- file_containing_symbol=_EMPTY_PROTO_SYMBOL_NAME),
- reflection_pb2.ServerReflectionRequest(
- file_containing_symbol='i.donut.exist.co.uk.org.net.me.name.foo'
- ),
- )
- responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
- expected_responses = (
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- file_descriptor_response=reflection_pb2.FileDescriptorResponse(
- file_descriptor_proto=(
- _file_descriptor_to_proto(empty_pb2.DESCRIPTOR),))),
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- error_response=reflection_pb2.ErrorResponse(
- error_code=grpc.StatusCode.NOT_FOUND.value[0],
- error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
- )),
- )
- self._assert_sequence_of_proto_equal(expected_responses, responses)
-
- def testFileContainingExtension(self):
- requests = (
- reflection_pb2.ServerReflectionRequest(
- file_containing_extension=reflection_pb2.ExtensionRequest(
- containing_type=_EMPTY_EXTENSIONS_SYMBOL_NAME,
- extension_number=125,
- ),),
- reflection_pb2.ServerReflectionRequest(
- file_containing_extension=reflection_pb2.ExtensionRequest(
- containing_type='i.donut.exist.co.uk.org.net.me.name.foo',
- extension_number=55,
- ),),
- )
- responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
- expected_responses = (
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- file_descriptor_response=reflection_pb2.FileDescriptorResponse(
- file_descriptor_proto=(_file_descriptor_to_proto(
- empty2_extensions_pb2.DESCRIPTOR),))),
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- error_response=reflection_pb2.ErrorResponse(
- error_code=grpc.StatusCode.NOT_FOUND.value[0],
- error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
- )),
- )
- self._assert_sequence_of_proto_equal(expected_responses, responses)
-
- def testExtensionNumbersOfType(self):
- requests = (
- reflection_pb2.ServerReflectionRequest(
- all_extension_numbers_of_type=_EMPTY_EXTENSIONS_SYMBOL_NAME),
- reflection_pb2.ServerReflectionRequest(
- all_extension_numbers_of_type='i.donut.exist.co.uk.net.name.foo'
- ),
- )
- responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
- expected_responses = (
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- all_extension_numbers_response=reflection_pb2.
- ExtensionNumberResponse(
- base_type_name=_EMPTY_EXTENSIONS_SYMBOL_NAME,
- extension_number=_EMPTY_EXTENSIONS_NUMBERS)),
- reflection_pb2.ServerReflectionResponse(
- valid_host='',
- error_response=reflection_pb2.ErrorResponse(
- error_code=grpc.StatusCode.NOT_FOUND.value[0],
- error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
- )),
- )
- self._assert_sequence_of_proto_equal(expected_responses, responses)
-
- def testListServices(self):
- requests = (reflection_pb2.ServerReflectionRequest(list_services='',),)
- responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
- expected_responses = (reflection_pb2.ServerReflectionResponse(
- valid_host='',
- list_services_response=reflection_pb2.ListServiceResponse(
- service=tuple(
- reflection_pb2.ServiceResponse(name=name)
- for name in _SERVICE_NAMES))),)
- self._assert_sequence_of_proto_equal(expected_responses, responses)
-
- def testReflectionServiceName(self):
- self.assertEqual(reflection.SERVICE_NAME,
- 'grpc.reflection.v1alpha.ServerReflection')
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2016 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.
+"""Tests of grpc_reflection.v1alpha.reflection."""
+
+import unittest
+
+import grpc
+
+from grpc_reflection.v1alpha import reflection
+from grpc_reflection.v1alpha import reflection_pb2
+from grpc_reflection.v1alpha import reflection_pb2_grpc
+
+from google.protobuf import descriptor_pool
+from google.protobuf import descriptor_pb2
+
+from src.proto.grpc.testing import empty_pb2
+from src.proto.grpc.testing.proto2 import empty2_extensions_pb2
+
+from tests.unit import test_common
+
+_EMPTY_PROTO_FILE_NAME = 'src/proto/grpc/testing/empty.proto'
+_EMPTY_PROTO_SYMBOL_NAME = 'grpc.testing.Empty'
+_SERVICE_NAMES = ('Angstrom', 'Bohr', 'Curie', 'Dyson', 'Einstein', 'Feynman',
+ 'Galilei')
+_EMPTY_EXTENSIONS_SYMBOL_NAME = 'grpc.testing.proto2.EmptyWithExtensions'
+_EMPTY_EXTENSIONS_NUMBERS = (
+ 124,
+ 125,
+ 126,
+ 127,
+ 128,
+)
+
+
+def _file_descriptor_to_proto(descriptor):
+ proto = descriptor_pb2.FileDescriptorProto()
+ descriptor.CopyToProto(proto)
+ return proto.SerializeToString()
+
+
+class ReflectionServicerTest(unittest.TestCase):
+
+ # TODO(https://github.com/grpc/grpc/issues/17844)
+ # Bazel + Python 3 will result in creating two different instance of
+ # DESCRIPTOR for each message. So, the equal comparison between protobuf
+ # returned by stub and manually crafted protobuf will always fail.
+ def _assert_sequence_of_proto_equal(self, x, y):
+ self.assertSequenceEqual(
+ tuple(proto.SerializeToString() for proto in x),
+ tuple(proto.SerializeToString() for proto in y),
+ )
+
+ def setUp(self):
+ self._server = test_common.test_server()
+ reflection.enable_server_reflection(_SERVICE_NAMES, self._server)
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+ self._stub = reflection_pb2_grpc.ServerReflectionStub(self._channel)
+
+ def tearDown(self):
+ self._server.stop(None)
+ self._channel.close()
+
+ def testFileByName(self):
+ requests = (
+ reflection_pb2.ServerReflectionRequest(
+ file_by_filename=_EMPTY_PROTO_FILE_NAME),
+ reflection_pb2.ServerReflectionRequest(
+ file_by_filename='i-donut-exist'),
+ )
+ responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
+ expected_responses = (
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ file_descriptor_response=reflection_pb2.FileDescriptorResponse(
+ file_descriptor_proto=(
+ _file_descriptor_to_proto(empty_pb2.DESCRIPTOR),))),
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ error_response=reflection_pb2.ErrorResponse(
+ error_code=grpc.StatusCode.NOT_FOUND.value[0],
+ error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
+ )),
+ )
+ self._assert_sequence_of_proto_equal(expected_responses, responses)
+
+ def testFileBySymbol(self):
+ requests = (
+ reflection_pb2.ServerReflectionRequest(
+ file_containing_symbol=_EMPTY_PROTO_SYMBOL_NAME),
+ reflection_pb2.ServerReflectionRequest(
+ file_containing_symbol='i.donut.exist.co.uk.org.net.me.name.foo'
+ ),
+ )
+ responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
+ expected_responses = (
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ file_descriptor_response=reflection_pb2.FileDescriptorResponse(
+ file_descriptor_proto=(
+ _file_descriptor_to_proto(empty_pb2.DESCRIPTOR),))),
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ error_response=reflection_pb2.ErrorResponse(
+ error_code=grpc.StatusCode.NOT_FOUND.value[0],
+ error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
+ )),
+ )
+ self._assert_sequence_of_proto_equal(expected_responses, responses)
+
+ def testFileContainingExtension(self):
+ requests = (
+ reflection_pb2.ServerReflectionRequest(
+ file_containing_extension=reflection_pb2.ExtensionRequest(
+ containing_type=_EMPTY_EXTENSIONS_SYMBOL_NAME,
+ extension_number=125,
+ ),),
+ reflection_pb2.ServerReflectionRequest(
+ file_containing_extension=reflection_pb2.ExtensionRequest(
+ containing_type='i.donut.exist.co.uk.org.net.me.name.foo',
+ extension_number=55,
+ ),),
+ )
+ responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
+ expected_responses = (
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ file_descriptor_response=reflection_pb2.FileDescriptorResponse(
+ file_descriptor_proto=(_file_descriptor_to_proto(
+ empty2_extensions_pb2.DESCRIPTOR),))),
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ error_response=reflection_pb2.ErrorResponse(
+ error_code=grpc.StatusCode.NOT_FOUND.value[0],
+ error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
+ )),
+ )
+ self._assert_sequence_of_proto_equal(expected_responses, responses)
+
+ def testExtensionNumbersOfType(self):
+ requests = (
+ reflection_pb2.ServerReflectionRequest(
+ all_extension_numbers_of_type=_EMPTY_EXTENSIONS_SYMBOL_NAME),
+ reflection_pb2.ServerReflectionRequest(
+ all_extension_numbers_of_type='i.donut.exist.co.uk.net.name.foo'
+ ),
+ )
+ responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
+ expected_responses = (
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ all_extension_numbers_response=reflection_pb2.
+ ExtensionNumberResponse(
+ base_type_name=_EMPTY_EXTENSIONS_SYMBOL_NAME,
+ extension_number=_EMPTY_EXTENSIONS_NUMBERS)),
+ reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ error_response=reflection_pb2.ErrorResponse(
+ error_code=grpc.StatusCode.NOT_FOUND.value[0],
+ error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(),
+ )),
+ )
+ self._assert_sequence_of_proto_equal(expected_responses, responses)
+
+ def testListServices(self):
+ requests = (reflection_pb2.ServerReflectionRequest(list_services='',),)
+ responses = tuple(self._stub.ServerReflectionInfo(iter(requests)))
+ expected_responses = (reflection_pb2.ServerReflectionResponse(
+ valid_host='',
+ list_services_response=reflection_pb2.ListServiceResponse(
+ service=tuple(
+ reflection_pb2.ServiceResponse(name=name)
+ for name in _SERVICE_NAMES))),)
+ self._assert_sequence_of_proto_equal(expected_responses, responses)
+
+ def testReflectionServiceName(self):
+ self.assertEqual(reflection.SERVICE_NAME,
+ 'grpc.reflection.v1alpha.ServerReflection')
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/status/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/status/__init__.py
index 38fdfc9c5c..10b401503b 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/status/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/status/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2018 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Copyright 2018 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/status/_grpc_status_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/status/_grpc_status_test.py
index 54a3b62420..186ea21095 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/status/_grpc_status_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/status/_grpc_status_test.py
@@ -1,180 +1,180 @@
-# Copyright 2018 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of grpc_status."""
-
-# NOTE(lidiz) This module only exists in Bazel BUILD file, for more details
-# please refer to comments in the "bazel_namespace_package_hack" module.
-try:
- from tests import bazel_namespace_package_hack
- bazel_namespace_package_hack.sys_path_to_site_dir_hack()
-except ImportError:
- pass
-
-import unittest
-
-import logging
-import traceback
-
-import grpc
-from grpc_status import rpc_status
-
-from tests.unit import test_common
-
-from google.protobuf import any_pb2
-from google.rpc import code_pb2, status_pb2, error_details_pb2
-
-_STATUS_OK = '/test/StatusOK'
-_STATUS_NOT_OK = '/test/StatusNotOk'
-_ERROR_DETAILS = '/test/ErrorDetails'
-_INCONSISTENT = '/test/Inconsistent'
-_INVALID_CODE = '/test/InvalidCode'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x01\x01\x01'
-
-_GRPC_DETAILS_METADATA_KEY = 'grpc-status-details-bin'
-
-_STATUS_DETAILS = 'This is an error detail'
-_STATUS_DETAILS_ANOTHER = 'This is another error detail'
-
-
-def _ok_unary_unary(request, servicer_context):
- return _RESPONSE
-
-
-def _not_ok_unary_unary(request, servicer_context):
- servicer_context.abort(grpc.StatusCode.INTERNAL, _STATUS_DETAILS)
-
-
-def _error_details_unary_unary(request, servicer_context):
- details = any_pb2.Any()
- details.Pack(
+# Copyright 2018 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests of grpc_status."""
+
+# NOTE(lidiz) This module only exists in Bazel BUILD file, for more details
+# please refer to comments in the "bazel_namespace_package_hack" module.
+try:
+ from tests import bazel_namespace_package_hack
+ bazel_namespace_package_hack.sys_path_to_site_dir_hack()
+except ImportError:
+ pass
+
+import unittest
+
+import logging
+import traceback
+
+import grpc
+from grpc_status import rpc_status
+
+from tests.unit import test_common
+
+from google.protobuf import any_pb2
+from google.rpc import code_pb2, status_pb2, error_details_pb2
+
+_STATUS_OK = '/test/StatusOK'
+_STATUS_NOT_OK = '/test/StatusNotOk'
+_ERROR_DETAILS = '/test/ErrorDetails'
+_INCONSISTENT = '/test/Inconsistent'
+_INVALID_CODE = '/test/InvalidCode'
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x01\x01\x01'
+
+_GRPC_DETAILS_METADATA_KEY = 'grpc-status-details-bin'
+
+_STATUS_DETAILS = 'This is an error detail'
+_STATUS_DETAILS_ANOTHER = 'This is another error detail'
+
+
+def _ok_unary_unary(request, servicer_context):
+ return _RESPONSE
+
+
+def _not_ok_unary_unary(request, servicer_context):
+ servicer_context.abort(grpc.StatusCode.INTERNAL, _STATUS_DETAILS)
+
+
+def _error_details_unary_unary(request, servicer_context):
+ details = any_pb2.Any()
+ details.Pack(
error_details_pb2.DebugInfo(stack_entries=traceback.format_stack(),
detail='Intentionally invoked'))
- rich_status = status_pb2.Status(
- code=code_pb2.INTERNAL,
- message=_STATUS_DETAILS,
- details=[details],
- )
- servicer_context.abort_with_status(rpc_status.to_status(rich_status))
-
-
-def _inconsistent_unary_unary(request, servicer_context):
- rich_status = status_pb2.Status(
- code=code_pb2.INTERNAL,
- message=_STATUS_DETAILS,
- )
- servicer_context.set_code(grpc.StatusCode.NOT_FOUND)
- servicer_context.set_details(_STATUS_DETAILS_ANOTHER)
- # User put inconsistent status information in trailing metadata
+ rich_status = status_pb2.Status(
+ code=code_pb2.INTERNAL,
+ message=_STATUS_DETAILS,
+ details=[details],
+ )
+ servicer_context.abort_with_status(rpc_status.to_status(rich_status))
+
+
+def _inconsistent_unary_unary(request, servicer_context):
+ rich_status = status_pb2.Status(
+ code=code_pb2.INTERNAL,
+ message=_STATUS_DETAILS,
+ )
+ servicer_context.set_code(grpc.StatusCode.NOT_FOUND)
+ servicer_context.set_details(_STATUS_DETAILS_ANOTHER)
+ # User put inconsistent status information in trailing metadata
servicer_context.set_trailing_metadata(
((_GRPC_DETAILS_METADATA_KEY, rich_status.SerializeToString()),))
-
-
-def _invalid_code_unary_unary(request, servicer_context):
- rich_status = status_pb2.Status(
- code=42,
- message='Invalid code',
- )
- servicer_context.abort_with_status(rpc_status.to_status(rich_status))
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _STATUS_OK:
- return grpc.unary_unary_rpc_method_handler(_ok_unary_unary)
- elif handler_call_details.method == _STATUS_NOT_OK:
- return grpc.unary_unary_rpc_method_handler(_not_ok_unary_unary)
- elif handler_call_details.method == _ERROR_DETAILS:
- return grpc.unary_unary_rpc_method_handler(
- _error_details_unary_unary)
- elif handler_call_details.method == _INCONSISTENT:
- return grpc.unary_unary_rpc_method_handler(
- _inconsistent_unary_unary)
- elif handler_call_details.method == _INVALID_CODE:
- return grpc.unary_unary_rpc_method_handler(
- _invalid_code_unary_unary)
- else:
- return None
-
-
-class StatusTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers((_GenericHandler(),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def test_status_ok(self):
- _, call = self._channel.unary_unary(_STATUS_OK).with_call(_REQUEST)
-
- # Succeed RPC doesn't have status
- status = rpc_status.from_call(call)
- self.assertIs(status, None)
-
- def test_status_not_ok(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_STATUS_NOT_OK).with_call(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
- # Failed RPC doesn't automatically generate status
- status = rpc_status.from_call(rpc_error)
- self.assertIs(status, None)
-
- def test_error_details(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_ERROR_DETAILS).with_call(_REQUEST)
- rpc_error = exception_context.exception
-
- status = rpc_status.from_call(rpc_error)
- self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
- self.assertEqual(status.code, code_pb2.Code.Value('INTERNAL'))
-
- # Check if the underlying proto message is intact
+
+
+def _invalid_code_unary_unary(request, servicer_context):
+ rich_status = status_pb2.Status(
+ code=42,
+ message='Invalid code',
+ )
+ servicer_context.abort_with_status(rpc_status.to_status(rich_status))
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _STATUS_OK:
+ return grpc.unary_unary_rpc_method_handler(_ok_unary_unary)
+ elif handler_call_details.method == _STATUS_NOT_OK:
+ return grpc.unary_unary_rpc_method_handler(_not_ok_unary_unary)
+ elif handler_call_details.method == _ERROR_DETAILS:
+ return grpc.unary_unary_rpc_method_handler(
+ _error_details_unary_unary)
+ elif handler_call_details.method == _INCONSISTENT:
+ return grpc.unary_unary_rpc_method_handler(
+ _inconsistent_unary_unary)
+ elif handler_call_details.method == _INVALID_CODE:
+ return grpc.unary_unary_rpc_method_handler(
+ _invalid_code_unary_unary)
+ else:
+ return None
+
+
+class StatusTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
+ self._server.add_generic_rpc_handlers((_GenericHandler(),))
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._server.stop(None)
+ self._channel.close()
+
+ def test_status_ok(self):
+ _, call = self._channel.unary_unary(_STATUS_OK).with_call(_REQUEST)
+
+ # Succeed RPC doesn't have status
+ status = rpc_status.from_call(call)
+ self.assertIs(status, None)
+
+ def test_status_not_ok(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_STATUS_NOT_OK).with_call(_REQUEST)
+ rpc_error = exception_context.exception
+
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
+ # Failed RPC doesn't automatically generate status
+ status = rpc_status.from_call(rpc_error)
+ self.assertIs(status, None)
+
+ def test_error_details(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_ERROR_DETAILS).with_call(_REQUEST)
+ rpc_error = exception_context.exception
+
+ status = rpc_status.from_call(rpc_error)
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
+ self.assertEqual(status.code, code_pb2.Code.Value('INTERNAL'))
+
+ # Check if the underlying proto message is intact
self.assertEqual(
status.details[0].Is(error_details_pb2.DebugInfo.DESCRIPTOR), True)
- info = error_details_pb2.DebugInfo()
- status.details[0].Unpack(info)
- self.assertIn('_error_details_unary_unary', info.stack_entries[-1])
-
- def test_code_message_validation(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_INCONSISTENT).with_call(_REQUEST)
- rpc_error = exception_context.exception
- self.assertEqual(rpc_error.code(), grpc.StatusCode.NOT_FOUND)
-
- # Code/Message validation failed
- self.assertRaises(ValueError, rpc_status.from_call, rpc_error)
-
- def test_invalid_code(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_INVALID_CODE).with_call(_REQUEST)
- rpc_error = exception_context.exception
- self.assertEqual(rpc_error.code(), grpc.StatusCode.UNKNOWN)
- # Invalid status code exception raised during coversion
- self.assertIn('Invalid status code', rpc_error.details())
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ info = error_details_pb2.DebugInfo()
+ status.details[0].Unpack(info)
+ self.assertIn('_error_details_unary_unary', info.stack_entries[-1])
+
+ def test_code_message_validation(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_INCONSISTENT).with_call(_REQUEST)
+ rpc_error = exception_context.exception
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.NOT_FOUND)
+
+ # Code/Message validation failed
+ self.assertRaises(ValueError, rpc_status.from_call, rpc_error)
+
+ def test_invalid_code(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_INVALID_CODE).with_call(_REQUEST)
+ rpc_error = exception_context.exception
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.UNKNOWN)
+ # Invalid status code exception raised during coversion
+ self.assertIn('Invalid status code', rpc_error.details())
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/__init__.py
index 5772620b60..8d89990e82 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 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.
+# Copyright 2016 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/client.py
index 01c14ba3e2..5fe2d03605 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/client.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/client.py
@@ -1,47 +1,47 @@
-# Copyright 2016 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.
-"""Entry point for running stress tests."""
-
-import argparse
-from concurrent import futures
-import threading
-
-import grpc
-from six.moves import queue
-from src.proto.grpc.testing import metrics_pb2_grpc
-from src.proto.grpc.testing import test_pb2_grpc
-
-from tests.interop import methods
-from tests.interop import resources
-from tests.qps import histogram
-from tests.stress import metrics_server
-from tests.stress import test_runner
-
-
-def _args():
- parser = argparse.ArgumentParser(
- description='gRPC Python stress test client')
- parser.add_argument(
- '--server_addresses',
- help='comma separated list of hostname:port to run servers on',
- default='localhost:8080',
- type=str)
- parser.add_argument(
- '--test_cases',
- help='comma separated list of testcase:weighting of tests to run',
- default='large_unary:100',
- type=str)
+# Copyright 2016 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.
+"""Entry point for running stress tests."""
+
+import argparse
+from concurrent import futures
+import threading
+
+import grpc
+from six.moves import queue
+from src.proto.grpc.testing import metrics_pb2_grpc
+from src.proto.grpc.testing import test_pb2_grpc
+
+from tests.interop import methods
+from tests.interop import resources
+from tests.qps import histogram
+from tests.stress import metrics_server
+from tests.stress import test_runner
+
+
+def _args():
+ parser = argparse.ArgumentParser(
+ description='gRPC Python stress test client')
+ parser.add_argument(
+ '--server_addresses',
+ help='comma separated list of hostname:port to run servers on',
+ default='localhost:8080',
+ type=str)
+ parser.add_argument(
+ '--test_cases',
+ help='comma separated list of testcase:weighting of tests to run',
+ default='large_unary:100',
+ type=str)
parser.add_argument('--test_duration_secs',
help='number of seconds to run the stress test',
default=-1,
@@ -58,11 +58,11 @@ def _args():
help='the port to listen for metrics requests on',
default=8081,
type=int)
- parser.add_argument(
- '--use_test_ca',
- help='Whether to use our fake CA. Requires --use_tls=true',
- default=False,
- type=bool)
+ parser.add_argument(
+ '--use_test_ca',
+ help='Whether to use our fake CA. Requires --use_tls=true',
+ default=False,
+ type=bool)
parser.add_argument('--use_tls',
help='Whether to use TLS',
default=False,
@@ -70,90 +70,90 @@ def _args():
parser.add_argument('--server_host_override',
help='the server host to which to claim to connect',
type=str)
- return parser.parse_args()
-
-
-def _test_case_from_arg(test_case_arg):
- for test_case in methods.TestCase:
- if test_case_arg == test_case.value:
- return test_case
- else:
- raise ValueError('No test case {}!'.format(test_case_arg))
-
-
-def _parse_weighted_test_cases(test_case_args):
- weighted_test_cases = {}
- for test_case_arg in test_case_args.split(','):
- name, weight = test_case_arg.split(':', 1)
- test_case = _test_case_from_arg(name)
- weighted_test_cases[test_case] = int(weight)
- return weighted_test_cases
-
-
-def _get_channel(target, args):
- if args.use_tls:
- if args.use_test_ca:
- root_certificates = resources.test_root_certificates()
- else:
- root_certificates = None # will load default roots.
- channel_credentials = grpc.ssl_channel_credentials(
- root_certificates=root_certificates)
- options = ((
- 'grpc.ssl_target_name_override',
- args.server_host_override,
- ),)
+ return parser.parse_args()
+
+
+def _test_case_from_arg(test_case_arg):
+ for test_case in methods.TestCase:
+ if test_case_arg == test_case.value:
+ return test_case
+ else:
+ raise ValueError('No test case {}!'.format(test_case_arg))
+
+
+def _parse_weighted_test_cases(test_case_args):
+ weighted_test_cases = {}
+ for test_case_arg in test_case_args.split(','):
+ name, weight = test_case_arg.split(':', 1)
+ test_case = _test_case_from_arg(name)
+ weighted_test_cases[test_case] = int(weight)
+ return weighted_test_cases
+
+
+def _get_channel(target, args):
+ if args.use_tls:
+ if args.use_test_ca:
+ root_certificates = resources.test_root_certificates()
+ else:
+ root_certificates = None # will load default roots.
+ channel_credentials = grpc.ssl_channel_credentials(
+ root_certificates=root_certificates)
+ options = ((
+ 'grpc.ssl_target_name_override',
+ args.server_host_override,
+ ),)
channel = grpc.secure_channel(target,
channel_credentials,
options=options)
- else:
- channel = grpc.insecure_channel(target)
-
- # waits for the channel to be ready before we start sending messages
- grpc.channel_ready_future(channel).result()
- return channel
-
-
-def run_test(args):
- test_cases = _parse_weighted_test_cases(args.test_cases)
- test_server_targets = args.server_addresses.split(',')
- # Propagate any client exceptions with a queue
- exception_queue = queue.Queue()
- stop_event = threading.Event()
- hist = histogram.Histogram(1, 1)
- runners = []
-
- server = grpc.server(futures.ThreadPoolExecutor(max_workers=25))
- metrics_pb2_grpc.add_MetricsServiceServicer_to_server(
- metrics_server.MetricsServer(hist), server)
- server.add_insecure_port('[::]:{}'.format(args.metrics_port))
- server.start()
-
- for test_server_target in test_server_targets:
- for _ in range(args.num_channels_per_server):
- channel = _get_channel(test_server_target, args)
- for _ in range(args.num_stubs_per_channel):
- stub = test_pb2_grpc.TestServiceStub(channel)
- runner = test_runner.TestRunner(stub, test_cases, hist,
- exception_queue, stop_event)
- runners.append(runner)
-
- for runner in runners:
- runner.start()
- try:
- timeout_secs = args.test_duration_secs
- if timeout_secs < 0:
- timeout_secs = None
- raise exception_queue.get(block=True, timeout=timeout_secs)
- except queue.Empty:
- # No exceptions thrown, success
- pass
- finally:
- stop_event.set()
- for runner in runners:
- runner.join()
- runner = None
- server.stop(None)
-
-
-if __name__ == '__main__':
- run_test(_args())
+ else:
+ channel = grpc.insecure_channel(target)
+
+ # waits for the channel to be ready before we start sending messages
+ grpc.channel_ready_future(channel).result()
+ return channel
+
+
+def run_test(args):
+ test_cases = _parse_weighted_test_cases(args.test_cases)
+ test_server_targets = args.server_addresses.split(',')
+ # Propagate any client exceptions with a queue
+ exception_queue = queue.Queue()
+ stop_event = threading.Event()
+ hist = histogram.Histogram(1, 1)
+ runners = []
+
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=25))
+ metrics_pb2_grpc.add_MetricsServiceServicer_to_server(
+ metrics_server.MetricsServer(hist), server)
+ server.add_insecure_port('[::]:{}'.format(args.metrics_port))
+ server.start()
+
+ for test_server_target in test_server_targets:
+ for _ in range(args.num_channels_per_server):
+ channel = _get_channel(test_server_target, args)
+ for _ in range(args.num_stubs_per_channel):
+ stub = test_pb2_grpc.TestServiceStub(channel)
+ runner = test_runner.TestRunner(stub, test_cases, hist,
+ exception_queue, stop_event)
+ runners.append(runner)
+
+ for runner in runners:
+ runner.start()
+ try:
+ timeout_secs = args.test_duration_secs
+ if timeout_secs < 0:
+ timeout_secs = None
+ raise exception_queue.get(block=True, timeout=timeout_secs)
+ except queue.Empty:
+ # No exceptions thrown, success
+ pass
+ finally:
+ stop_event.set()
+ for runner in runners:
+ runner.join()
+ runner = None
+ server.stop(None)
+
+
+if __name__ == '__main__':
+ run_test(_args())
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/metrics_server.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/metrics_server.py
index 33a74b4a38..5adbe9e5b3 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/metrics_server.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/metrics_server.py
@@ -1,45 +1,45 @@
-# Copyright 2016 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.
-"""MetricsService for publishing stress test qps data."""
-
-import time
-
-from src.proto.grpc.testing import metrics_pb2
-from src.proto.grpc.testing import metrics_pb2_grpc
-
-GAUGE_NAME = 'python_overall_qps'
-
-
-class MetricsServer(metrics_pb2_grpc.MetricsServiceServicer):
-
- def __init__(self, histogram):
- self._start_time = time.time()
- self._histogram = histogram
-
- def _get_qps(self):
- count = self._histogram.get_data().count
- delta = time.time() - self._start_time
- self._histogram.reset()
- self._start_time = time.time()
- return int(count / delta)
-
- def GetAllGauges(self, request, context):
- qps = self._get_qps()
- return [metrics_pb2.GaugeResponse(name=GAUGE_NAME, long_value=qps)]
-
- def GetGauge(self, request, context):
- if request.name != GAUGE_NAME:
- raise Exception('Gauge {} does not exist'.format(request.name))
- qps = self._get_qps()
- return metrics_pb2.GaugeResponse(name=GAUGE_NAME, long_value=qps)
+# Copyright 2016 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.
+"""MetricsService for publishing stress test qps data."""
+
+import time
+
+from src.proto.grpc.testing import metrics_pb2
+from src.proto.grpc.testing import metrics_pb2_grpc
+
+GAUGE_NAME = 'python_overall_qps'
+
+
+class MetricsServer(metrics_pb2_grpc.MetricsServiceServicer):
+
+ def __init__(self, histogram):
+ self._start_time = time.time()
+ self._histogram = histogram
+
+ def _get_qps(self):
+ count = self._histogram.get_data().count
+ delta = time.time() - self._start_time
+ self._histogram.reset()
+ self._start_time = time.time()
+ return int(count / delta)
+
+ def GetAllGauges(self, request, context):
+ qps = self._get_qps()
+ return [metrics_pb2.GaugeResponse(name=GAUGE_NAME, long_value=qps)]
+
+ def GetGauge(self, request, context):
+ if request.name != GAUGE_NAME:
+ raise Exception('Gauge {} does not exist'.format(request.name))
+ qps = self._get_qps()
+ return metrics_pb2.GaugeResponse(name=GAUGE_NAME, long_value=qps)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/test_runner.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/test_runner.py
index 1b6003fc69..e672473177 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/test_runner.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/test_runner.py
@@ -1,58 +1,58 @@
-# Copyright 2016 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.
-"""Thread that sends random weighted requests on a TestService stub."""
-
-import random
-import threading
-import time
-import traceback
-
-
-def _weighted_test_case_generator(weighted_cases):
- weight_sum = sum(weighted_cases.itervalues())
-
- while True:
- val = random.uniform(0, weight_sum)
- partial_sum = 0
- for case in weighted_cases:
- partial_sum += weighted_cases[case]
- if val <= partial_sum:
- yield case
- break
-
-
-class TestRunner(threading.Thread):
-
- def __init__(self, stub, test_cases, hist, exception_queue, stop_event):
- super(TestRunner, self).__init__()
- self._exception_queue = exception_queue
- self._stop_event = stop_event
- self._stub = stub
- self._test_cases = _weighted_test_case_generator(test_cases)
- self._histogram = hist
-
- def run(self):
- while not self._stop_event.is_set():
- try:
- test_case = next(self._test_cases)
- start_time = time.time()
- test_case.test_interoperability(self._stub, None)
- end_time = time.time()
- self._histogram.add((end_time - start_time) * 1e9)
- except Exception as e: # pylint: disable=broad-except
- traceback.print_exc()
- self._exception_queue.put(
+# Copyright 2016 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.
+"""Thread that sends random weighted requests on a TestService stub."""
+
+import random
+import threading
+import time
+import traceback
+
+
+def _weighted_test_case_generator(weighted_cases):
+ weight_sum = sum(weighted_cases.itervalues())
+
+ while True:
+ val = random.uniform(0, weight_sum)
+ partial_sum = 0
+ for case in weighted_cases:
+ partial_sum += weighted_cases[case]
+ if val <= partial_sum:
+ yield case
+ break
+
+
+class TestRunner(threading.Thread):
+
+ def __init__(self, stub, test_cases, hist, exception_queue, stop_event):
+ super(TestRunner, self).__init__()
+ self._exception_queue = exception_queue
+ self._stop_event = stop_event
+ self._stub = stub
+ self._test_cases = _weighted_test_case_generator(test_cases)
+ self._histogram = hist
+
+ def run(self):
+ while not self._stop_event.is_set():
+ try:
+ test_case = next(self._test_cases)
+ start_time = time.time()
+ test_case.test_interoperability(self._stub, None)
+ end_time = time.time()
+ self._histogram.add((end_time - start_time) * 1e9)
+ except Exception as e: # pylint: disable=broad-except
+ traceback.print_exc()
+ self._exception_queue.put(
Exception(
"An exception occurred during test {}".format(
test_case), e))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/unary_stream_benchmark.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/unary_stream_benchmark.py
index cd872ece29..717ad58c60 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/unary_stream_benchmark.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/stress/unary_stream_benchmark.py
@@ -1,102 +1,102 @@
-# Copyright 2019 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import datetime
-import threading
-import grpc
-import grpc.experimental
-import subprocess
-import sys
-import time
-import contextlib
-
-_PORT = 5741
-_MESSAGE_SIZE = 4
-_RESPONSE_COUNT = 32 * 1024
-
-_SERVER_CODE = """
-import datetime
-import threading
-import grpc
-from concurrent import futures
-from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2
-from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2_grpc
-
-class Handler(unary_stream_benchmark_pb2_grpc.UnaryStreamBenchmarkServiceServicer):
-
- def Benchmark(self, request, context):
- payload = b'\\x00\\x01' * int(request.message_size / 2)
- for _ in range(request.response_count):
- yield unary_stream_benchmark_pb2.BenchmarkResponse(response=payload)
-
-
-server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
-server.add_insecure_port('[::]:%d')
-unary_stream_benchmark_pb2_grpc.add_UnaryStreamBenchmarkServiceServicer_to_server(Handler(), server)
-server.start()
-server.wait_for_termination()
-""" % _PORT
-
-try:
- from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2
- from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2_grpc
-
- _GRPC_CHANNEL_OPTIONS = [
- ('grpc.max_metadata_size', 16 * 1024 * 1024),
- ('grpc.max_receive_message_length', 64 * 1024 * 1024),
- (grpc.experimental.ChannelOptions.SingleThreadedUnaryStream, 1),
- ]
-
- @contextlib.contextmanager
- def _running_server():
+# Copyright 2019 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import datetime
+import threading
+import grpc
+import grpc.experimental
+import subprocess
+import sys
+import time
+import contextlib
+
+_PORT = 5741
+_MESSAGE_SIZE = 4
+_RESPONSE_COUNT = 32 * 1024
+
+_SERVER_CODE = """
+import datetime
+import threading
+import grpc
+from concurrent import futures
+from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2
+from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2_grpc
+
+class Handler(unary_stream_benchmark_pb2_grpc.UnaryStreamBenchmarkServiceServicer):
+
+ def Benchmark(self, request, context):
+ payload = b'\\x00\\x01' * int(request.message_size / 2)
+ for _ in range(request.response_count):
+ yield unary_stream_benchmark_pb2.BenchmarkResponse(response=payload)
+
+
+server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
+server.add_insecure_port('[::]:%d')
+unary_stream_benchmark_pb2_grpc.add_UnaryStreamBenchmarkServiceServicer_to_server(Handler(), server)
+server.start()
+server.wait_for_termination()
+""" % _PORT
+
+try:
+ from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2
+ from src.python.grpcio_tests.tests.stress import unary_stream_benchmark_pb2_grpc
+
+ _GRPC_CHANNEL_OPTIONS = [
+ ('grpc.max_metadata_size', 16 * 1024 * 1024),
+ ('grpc.max_receive_message_length', 64 * 1024 * 1024),
+ (grpc.experimental.ChannelOptions.SingleThreadedUnaryStream, 1),
+ ]
+
+ @contextlib.contextmanager
+ def _running_server():
server_process = subprocess.Popen([sys.executable, '-c', _SERVER_CODE],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
- try:
- yield
- finally:
- server_process.terminate()
- server_process.wait()
- sys.stdout.write("stdout: {}".format(server_process.stdout.read()))
- sys.stdout.flush()
- sys.stdout.write("stderr: {}".format(server_process.stderr.read()))
- sys.stdout.flush()
-
- def profile(message_size, response_count):
- request = unary_stream_benchmark_pb2.BenchmarkRequest(
- message_size=message_size, response_count=response_count)
+ try:
+ yield
+ finally:
+ server_process.terminate()
+ server_process.wait()
+ sys.stdout.write("stdout: {}".format(server_process.stdout.read()))
+ sys.stdout.flush()
+ sys.stdout.write("stderr: {}".format(server_process.stderr.read()))
+ sys.stdout.flush()
+
+ def profile(message_size, response_count):
+ request = unary_stream_benchmark_pb2.BenchmarkRequest(
+ message_size=message_size, response_count=response_count)
with grpc.insecure_channel('[::]:{}'.format(_PORT),
options=_GRPC_CHANNEL_OPTIONS) as channel:
- stub = unary_stream_benchmark_pb2_grpc.UnaryStreamBenchmarkServiceStub(
- channel)
- start = datetime.datetime.now()
- call = stub.Benchmark(request, wait_for_ready=True)
- for message in call:
- pass
- end = datetime.datetime.now()
- return end - start
-
- def main():
- with _running_server():
- for i in range(1000):
- latency = profile(_MESSAGE_SIZE, 1024)
- sys.stdout.write("{}\n".format(latency.total_seconds()))
- sys.stdout.flush()
-
- if __name__ == '__main__':
- main()
-
-except ImportError:
- # NOTE(rbellevi): The test runner should not load this module.
- pass
+ stub = unary_stream_benchmark_pb2_grpc.UnaryStreamBenchmarkServiceStub(
+ channel)
+ start = datetime.datetime.now()
+ call = stub.Benchmark(request, wait_for_ready=True)
+ for message in call:
+ pass
+ end = datetime.datetime.now()
+ return end - start
+
+ def main():
+ with _running_server():
+ for i in range(1000):
+ latency = profile(_MESSAGE_SIZE, 1024)
+ sys.stdout.write("{}\n".format(latency.total_seconds()))
+ sys.stdout.flush()
+
+ if __name__ == '__main__':
+ main()
+
+except ImportError:
+ # NOTE(rbellevi): The test runner should not load this module.
+ pass
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/__init__.py
index 1e120359cf..0030911829 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2017 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.
+# Copyright 2017 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_common.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_common.py
index 3226d1fb02..19fe21b71b 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_common.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_common.py
@@ -1,43 +1,43 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""An example gRPC Python-using application's common code elements."""
-
-from tests.testing.proto import requests_pb2
-from tests.testing.proto import services_pb2
-
-SERVICE_NAME = 'tests_of_grpc_testing.FirstService'
-UNARY_UNARY_METHOD_NAME = 'UnUn'
-UNARY_STREAM_METHOD_NAME = 'UnStre'
-STREAM_UNARY_METHOD_NAME = 'StreUn'
-STREAM_STREAM_METHOD_NAME = 'StreStre'
-
-UNARY_UNARY_REQUEST = requests_pb2.Up(first_up_field=2)
-ERRONEOUS_UNARY_UNARY_REQUEST = requests_pb2.Up(first_up_field=3)
-UNARY_UNARY_RESPONSE = services_pb2.Down(first_down_field=5)
-ERRONEOUS_UNARY_UNARY_RESPONSE = services_pb2.Down(first_down_field=7)
-UNARY_STREAM_REQUEST = requests_pb2.Charm(first_charm_field=11)
-STREAM_UNARY_REQUEST = requests_pb2.Charm(first_charm_field=13)
-STREAM_UNARY_RESPONSE = services_pb2.Strange(first_strange_field=17)
-STREAM_STREAM_REQUEST = requests_pb2.Top(first_top_field=19)
-STREAM_STREAM_RESPONSE = services_pb2.Bottom(first_bottom_field=23)
-TWO_STREAM_STREAM_RESPONSES = (STREAM_STREAM_RESPONSE,) * 2
-ABORT_REQUEST = requests_pb2.Up(first_up_field=42)
-ABORT_SUCCESS_QUERY = requests_pb2.Up(first_up_field=43)
-ABORT_NO_STATUS_RESPONSE = services_pb2.Down(first_down_field=50)
-ABORT_SUCCESS_RESPONSE = services_pb2.Down(first_down_field=51)
-ABORT_FAILURE_RESPONSE = services_pb2.Down(first_down_field=52)
-STREAM_STREAM_MUTATING_REQUEST = requests_pb2.Top(first_top_field=24601)
-STREAM_STREAM_MUTATING_COUNT = 2
-
-INFINITE_REQUEST_STREAM_TIMEOUT = 0.2
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""An example gRPC Python-using application's common code elements."""
+
+from tests.testing.proto import requests_pb2
+from tests.testing.proto import services_pb2
+
+SERVICE_NAME = 'tests_of_grpc_testing.FirstService'
+UNARY_UNARY_METHOD_NAME = 'UnUn'
+UNARY_STREAM_METHOD_NAME = 'UnStre'
+STREAM_UNARY_METHOD_NAME = 'StreUn'
+STREAM_STREAM_METHOD_NAME = 'StreStre'
+
+UNARY_UNARY_REQUEST = requests_pb2.Up(first_up_field=2)
+ERRONEOUS_UNARY_UNARY_REQUEST = requests_pb2.Up(first_up_field=3)
+UNARY_UNARY_RESPONSE = services_pb2.Down(first_down_field=5)
+ERRONEOUS_UNARY_UNARY_RESPONSE = services_pb2.Down(first_down_field=7)
+UNARY_STREAM_REQUEST = requests_pb2.Charm(first_charm_field=11)
+STREAM_UNARY_REQUEST = requests_pb2.Charm(first_charm_field=13)
+STREAM_UNARY_RESPONSE = services_pb2.Strange(first_strange_field=17)
+STREAM_STREAM_REQUEST = requests_pb2.Top(first_top_field=19)
+STREAM_STREAM_RESPONSE = services_pb2.Bottom(first_bottom_field=23)
+TWO_STREAM_STREAM_RESPONSES = (STREAM_STREAM_RESPONSE,) * 2
+ABORT_REQUEST = requests_pb2.Up(first_up_field=42)
+ABORT_SUCCESS_QUERY = requests_pb2.Up(first_up_field=43)
+ABORT_NO_STATUS_RESPONSE = services_pb2.Down(first_down_field=50)
+ABORT_SUCCESS_RESPONSE = services_pb2.Down(first_down_field=51)
+ABORT_FAILURE_RESPONSE = services_pb2.Down(first_down_field=52)
+STREAM_STREAM_MUTATING_REQUEST = requests_pb2.Top(first_top_field=24601)
+STREAM_STREAM_MUTATING_COUNT = 2
+
+INFINITE_REQUEST_STREAM_TIMEOUT = 0.2
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_testing_common.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_testing_common.py
index 9c9e485a78..73a4552428 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_testing_common.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_application_testing_common.py
@@ -1,33 +1,33 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import grpc_testing
-
-from tests.testing.proto import requests_pb2
-from tests.testing.proto import services_pb2
-
-# TODO(https://github.com/grpc/grpc/issues/11657): Eliminate this entirely.
-# TODO(https://github.com/google/protobuf/issues/3452): Eliminate this if/else.
-if services_pb2.DESCRIPTOR.services_by_name.get('FirstService') is None:
- FIRST_SERVICE = 'Fix protobuf issue 3452!'
- FIRST_SERVICE_UNUN = 'Fix protobuf issue 3452!'
- FIRST_SERVICE_UNSTRE = 'Fix protobuf issue 3452!'
- FIRST_SERVICE_STREUN = 'Fix protobuf issue 3452!'
- FIRST_SERVICE_STRESTRE = 'Fix protobuf issue 3452!'
-else:
- FIRST_SERVICE = services_pb2.DESCRIPTOR.services_by_name['FirstService']
- FIRST_SERVICE_UNUN = FIRST_SERVICE.methods_by_name['UnUn']
- FIRST_SERVICE_UNSTRE = FIRST_SERVICE.methods_by_name['UnStre']
- FIRST_SERVICE_STREUN = FIRST_SERVICE.methods_by_name['StreUn']
- FIRST_SERVICE_STRESTRE = FIRST_SERVICE.methods_by_name['StreStre']
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import grpc_testing
+
+from tests.testing.proto import requests_pb2
+from tests.testing.proto import services_pb2
+
+# TODO(https://github.com/grpc/grpc/issues/11657): Eliminate this entirely.
+# TODO(https://github.com/google/protobuf/issues/3452): Eliminate this if/else.
+if services_pb2.DESCRIPTOR.services_by_name.get('FirstService') is None:
+ FIRST_SERVICE = 'Fix protobuf issue 3452!'
+ FIRST_SERVICE_UNUN = 'Fix protobuf issue 3452!'
+ FIRST_SERVICE_UNSTRE = 'Fix protobuf issue 3452!'
+ FIRST_SERVICE_STREUN = 'Fix protobuf issue 3452!'
+ FIRST_SERVICE_STRESTRE = 'Fix protobuf issue 3452!'
+else:
+ FIRST_SERVICE = services_pb2.DESCRIPTOR.services_by_name['FirstService']
+ FIRST_SERVICE_UNUN = FIRST_SERVICE.methods_by_name['UnUn']
+ FIRST_SERVICE_UNSTRE = FIRST_SERVICE.methods_by_name['UnStre']
+ FIRST_SERVICE_STREUN = FIRST_SERVICE.methods_by_name['StreUn']
+ FIRST_SERVICE_STRESTRE = FIRST_SERVICE.methods_by_name['StreStre']
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_application.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_application.py
index 57fa510913..9b36945501 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_application.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_application.py
@@ -1,236 +1,236 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""An example gRPC Python-using client-side application."""
-
-import collections
-import enum
-import threading
-import time
-
-import grpc
-from tests.unit.framework.common import test_constants
-
-from tests.testing.proto import requests_pb2
-from tests.testing.proto import services_pb2
-from tests.testing.proto import services_pb2_grpc
-
-from tests.testing import _application_common
-
-
-@enum.unique
-class Scenario(enum.Enum):
- UNARY_UNARY = 'unary unary'
- UNARY_STREAM = 'unary stream'
- STREAM_UNARY = 'stream unary'
- STREAM_STREAM = 'stream stream'
- CONCURRENT_STREAM_UNARY = 'concurrent stream unary'
- CONCURRENT_STREAM_STREAM = 'concurrent stream stream'
- CANCEL_UNARY_UNARY = 'cancel unary unary'
- CANCEL_UNARY_STREAM = 'cancel unary stream'
- INFINITE_REQUEST_STREAM = 'infinite request stream'
-
-
-class Outcome(collections.namedtuple('Outcome', ('kind', 'code', 'details'))):
- """Outcome of a client application scenario.
-
- Attributes:
- kind: A Kind value describing the overall kind of scenario execution.
- code: A grpc.StatusCode value. Only valid if kind is Kind.RPC_ERROR.
- details: A status details string. Only valid if kind is Kind.RPC_ERROR.
- """
-
- @enum.unique
- class Kind(enum.Enum):
- SATISFACTORY = 'satisfactory'
- UNSATISFACTORY = 'unsatisfactory'
- RPC_ERROR = 'rpc error'
-
-
-_SATISFACTORY_OUTCOME = Outcome(Outcome.Kind.SATISFACTORY, None, None)
-_UNSATISFACTORY_OUTCOME = Outcome(Outcome.Kind.UNSATISFACTORY, None, None)
-
-
-class _Pipe(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._values = []
- self._open = True
-
- def __iter__(self):
- return self
-
- def _next(self):
- with self._condition:
- while True:
- if self._values:
- return self._values.pop(0)
- elif not self._open:
- raise StopIteration()
- else:
- self._condition.wait()
-
- def __next__(self): # (Python 3 Iterator Protocol)
- return self._next()
-
- def next(self): # (Python 2 Iterator Protocol)
- return self._next()
-
- def add(self, value):
- with self._condition:
- self._values.append(value)
- self._condition.notify_all()
-
- def close(self):
- with self._condition:
- self._open = False
- self._condition.notify_all()
-
-
-def _run_unary_unary(stub):
- response = stub.UnUn(_application_common.UNARY_UNARY_REQUEST)
- if _application_common.UNARY_UNARY_RESPONSE == response:
- return _SATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
-
-
-def _run_unary_stream(stub):
- response_iterator = stub.UnStre(_application_common.UNARY_STREAM_REQUEST)
- try:
- next(response_iterator)
- except StopIteration:
- return _SATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
-
-
-def _run_stream_unary(stub):
- response, call = stub.StreUn.with_call(
- iter((_application_common.STREAM_UNARY_REQUEST,) * 3))
- if (_application_common.STREAM_UNARY_RESPONSE == response and
- call.code() is grpc.StatusCode.OK):
- return _SATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
-
-
-def _run_stream_stream(stub):
- request_pipe = _Pipe()
- response_iterator = stub.StreStre(iter(request_pipe))
- request_pipe.add(_application_common.STREAM_STREAM_REQUEST)
- first_responses = next(response_iterator), next(response_iterator)
- request_pipe.add(_application_common.STREAM_STREAM_REQUEST)
- second_responses = next(response_iterator), next(response_iterator)
- request_pipe.close()
- try:
- next(response_iterator)
- except StopIteration:
- unexpected_extra_response = False
- else:
- unexpected_extra_response = True
- if (first_responses == _application_common.TWO_STREAM_STREAM_RESPONSES and
- second_responses == _application_common.TWO_STREAM_STREAM_RESPONSES
- and not unexpected_extra_response):
- return _SATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
-
-
-def _run_concurrent_stream_unary(stub):
- future_calls = tuple(
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""An example gRPC Python-using client-side application."""
+
+import collections
+import enum
+import threading
+import time
+
+import grpc
+from tests.unit.framework.common import test_constants
+
+from tests.testing.proto import requests_pb2
+from tests.testing.proto import services_pb2
+from tests.testing.proto import services_pb2_grpc
+
+from tests.testing import _application_common
+
+
+@enum.unique
+class Scenario(enum.Enum):
+ UNARY_UNARY = 'unary unary'
+ UNARY_STREAM = 'unary stream'
+ STREAM_UNARY = 'stream unary'
+ STREAM_STREAM = 'stream stream'
+ CONCURRENT_STREAM_UNARY = 'concurrent stream unary'
+ CONCURRENT_STREAM_STREAM = 'concurrent stream stream'
+ CANCEL_UNARY_UNARY = 'cancel unary unary'
+ CANCEL_UNARY_STREAM = 'cancel unary stream'
+ INFINITE_REQUEST_STREAM = 'infinite request stream'
+
+
+class Outcome(collections.namedtuple('Outcome', ('kind', 'code', 'details'))):
+ """Outcome of a client application scenario.
+
+ Attributes:
+ kind: A Kind value describing the overall kind of scenario execution.
+ code: A grpc.StatusCode value. Only valid if kind is Kind.RPC_ERROR.
+ details: A status details string. Only valid if kind is Kind.RPC_ERROR.
+ """
+
+ @enum.unique
+ class Kind(enum.Enum):
+ SATISFACTORY = 'satisfactory'
+ UNSATISFACTORY = 'unsatisfactory'
+ RPC_ERROR = 'rpc error'
+
+
+_SATISFACTORY_OUTCOME = Outcome(Outcome.Kind.SATISFACTORY, None, None)
+_UNSATISFACTORY_OUTCOME = Outcome(Outcome.Kind.UNSATISFACTORY, None, None)
+
+
+class _Pipe(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._values = []
+ self._open = True
+
+ def __iter__(self):
+ return self
+
+ def _next(self):
+ with self._condition:
+ while True:
+ if self._values:
+ return self._values.pop(0)
+ elif not self._open:
+ raise StopIteration()
+ else:
+ self._condition.wait()
+
+ def __next__(self): # (Python 3 Iterator Protocol)
+ return self._next()
+
+ def next(self): # (Python 2 Iterator Protocol)
+ return self._next()
+
+ def add(self, value):
+ with self._condition:
+ self._values.append(value)
+ self._condition.notify_all()
+
+ def close(self):
+ with self._condition:
+ self._open = False
+ self._condition.notify_all()
+
+
+def _run_unary_unary(stub):
+ response = stub.UnUn(_application_common.UNARY_UNARY_REQUEST)
+ if _application_common.UNARY_UNARY_RESPONSE == response:
+ return _SATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+
+
+def _run_unary_stream(stub):
+ response_iterator = stub.UnStre(_application_common.UNARY_STREAM_REQUEST)
+ try:
+ next(response_iterator)
+ except StopIteration:
+ return _SATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+
+
+def _run_stream_unary(stub):
+ response, call = stub.StreUn.with_call(
+ iter((_application_common.STREAM_UNARY_REQUEST,) * 3))
+ if (_application_common.STREAM_UNARY_RESPONSE == response and
+ call.code() is grpc.StatusCode.OK):
+ return _SATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+
+
+def _run_stream_stream(stub):
+ request_pipe = _Pipe()
+ response_iterator = stub.StreStre(iter(request_pipe))
+ request_pipe.add(_application_common.STREAM_STREAM_REQUEST)
+ first_responses = next(response_iterator), next(response_iterator)
+ request_pipe.add(_application_common.STREAM_STREAM_REQUEST)
+ second_responses = next(response_iterator), next(response_iterator)
+ request_pipe.close()
+ try:
+ next(response_iterator)
+ except StopIteration:
+ unexpected_extra_response = False
+ else:
+ unexpected_extra_response = True
+ if (first_responses == _application_common.TWO_STREAM_STREAM_RESPONSES and
+ second_responses == _application_common.TWO_STREAM_STREAM_RESPONSES
+ and not unexpected_extra_response):
+ return _SATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+
+
+def _run_concurrent_stream_unary(stub):
+ future_calls = tuple(
stub.StreUn.future(iter((_application_common.STREAM_UNARY_REQUEST,) *
3))
- for _ in range(test_constants.THREAD_CONCURRENCY))
- for future_call in future_calls:
- if future_call.code() is grpc.StatusCode.OK:
- response = future_call.result()
- if _application_common.STREAM_UNARY_RESPONSE != response:
- return _UNSATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
- else:
- return _SATISFACTORY_OUTCOME
-
-
-def _run_concurrent_stream_stream(stub):
- condition = threading.Condition()
- outcomes = [None] * test_constants.RPC_CONCURRENCY
-
- def run_stream_stream(index):
- outcome = _run_stream_stream(stub)
- with condition:
- outcomes[index] = outcome
- condition.notify()
-
- for index in range(test_constants.RPC_CONCURRENCY):
- thread = threading.Thread(target=run_stream_stream, args=(index,))
- thread.start()
- with condition:
- while True:
- if all(outcomes):
- for outcome in outcomes:
- if outcome.kind is not Outcome.Kind.SATISFACTORY:
- return _UNSATISFACTORY_OUTCOME
- else:
- return _SATISFACTORY_OUTCOME
- else:
- condition.wait()
-
-
-def _run_cancel_unary_unary(stub):
- response_future_call = stub.UnUn.future(
- _application_common.UNARY_UNARY_REQUEST)
- initial_metadata = response_future_call.initial_metadata()
- cancelled = response_future_call.cancel()
- if initial_metadata is not None and cancelled:
- return _SATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
-
-
-def _run_infinite_request_stream(stub):
-
- def infinite_request_iterator():
- while True:
- yield _application_common.STREAM_UNARY_REQUEST
-
- response_future_call = stub.StreUn.future(
- infinite_request_iterator(),
- timeout=_application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
- if response_future_call.code() is grpc.StatusCode.DEADLINE_EXCEEDED:
- return _SATISFACTORY_OUTCOME
- else:
- return _UNSATISFACTORY_OUTCOME
-
-
-_IMPLEMENTATIONS = {
- Scenario.UNARY_UNARY: _run_unary_unary,
- Scenario.UNARY_STREAM: _run_unary_stream,
- Scenario.STREAM_UNARY: _run_stream_unary,
- Scenario.STREAM_STREAM: _run_stream_stream,
- Scenario.CONCURRENT_STREAM_UNARY: _run_concurrent_stream_unary,
- Scenario.CONCURRENT_STREAM_STREAM: _run_concurrent_stream_stream,
- Scenario.CANCEL_UNARY_UNARY: _run_cancel_unary_unary,
- Scenario.INFINITE_REQUEST_STREAM: _run_infinite_request_stream,
-}
-
-
-def run(scenario, channel):
- stub = services_pb2_grpc.FirstServiceStub(channel)
- try:
- return _IMPLEMENTATIONS[scenario](stub)
- except grpc.RpcError as rpc_error:
- return Outcome(Outcome.Kind.RPC_ERROR, rpc_error.code(),
- rpc_error.details())
+ for _ in range(test_constants.THREAD_CONCURRENCY))
+ for future_call in future_calls:
+ if future_call.code() is grpc.StatusCode.OK:
+ response = future_call.result()
+ if _application_common.STREAM_UNARY_RESPONSE != response:
+ return _UNSATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+ else:
+ return _SATISFACTORY_OUTCOME
+
+
+def _run_concurrent_stream_stream(stub):
+ condition = threading.Condition()
+ outcomes = [None] * test_constants.RPC_CONCURRENCY
+
+ def run_stream_stream(index):
+ outcome = _run_stream_stream(stub)
+ with condition:
+ outcomes[index] = outcome
+ condition.notify()
+
+ for index in range(test_constants.RPC_CONCURRENCY):
+ thread = threading.Thread(target=run_stream_stream, args=(index,))
+ thread.start()
+ with condition:
+ while True:
+ if all(outcomes):
+ for outcome in outcomes:
+ if outcome.kind is not Outcome.Kind.SATISFACTORY:
+ return _UNSATISFACTORY_OUTCOME
+ else:
+ return _SATISFACTORY_OUTCOME
+ else:
+ condition.wait()
+
+
+def _run_cancel_unary_unary(stub):
+ response_future_call = stub.UnUn.future(
+ _application_common.UNARY_UNARY_REQUEST)
+ initial_metadata = response_future_call.initial_metadata()
+ cancelled = response_future_call.cancel()
+ if initial_metadata is not None and cancelled:
+ return _SATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+
+
+def _run_infinite_request_stream(stub):
+
+ def infinite_request_iterator():
+ while True:
+ yield _application_common.STREAM_UNARY_REQUEST
+
+ response_future_call = stub.StreUn.future(
+ infinite_request_iterator(),
+ timeout=_application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
+ if response_future_call.code() is grpc.StatusCode.DEADLINE_EXCEEDED:
+ return _SATISFACTORY_OUTCOME
+ else:
+ return _UNSATISFACTORY_OUTCOME
+
+
+_IMPLEMENTATIONS = {
+ Scenario.UNARY_UNARY: _run_unary_unary,
+ Scenario.UNARY_STREAM: _run_unary_stream,
+ Scenario.STREAM_UNARY: _run_stream_unary,
+ Scenario.STREAM_STREAM: _run_stream_stream,
+ Scenario.CONCURRENT_STREAM_UNARY: _run_concurrent_stream_unary,
+ Scenario.CONCURRENT_STREAM_STREAM: _run_concurrent_stream_stream,
+ Scenario.CANCEL_UNARY_UNARY: _run_cancel_unary_unary,
+ Scenario.INFINITE_REQUEST_STREAM: _run_infinite_request_stream,
+}
+
+
+def run(scenario, channel):
+ stub = services_pb2_grpc.FirstServiceStub(channel)
+ try:
+ return _IMPLEMENTATIONS[scenario](stub)
+ except grpc.RpcError as rpc_error:
+ return Outcome(Outcome.Kind.RPC_ERROR, rpc_error.code(),
+ rpc_error.details())
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_test.py
index 5b051c3939..b3173ba6f5 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_client_test.py
@@ -1,308 +1,308 @@
-# Copyright 2017 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.
-
-from concurrent import futures
-import time
-import unittest
-
-import grpc
-from grpc.framework.foundation import logging_pool
-from tests.unit.framework.common import test_constants
-import grpc_testing
-
-from tests.testing import _application_common
-from tests.testing import _application_testing_common
-from tests.testing import _client_application
-from tests.testing.proto import requests_pb2
-from tests.testing.proto import services_pb2
-
-
-# TODO(https://github.com/google/protobuf/issues/3452): Drop this skip.
-@unittest.skipIf(
- services_pb2.DESCRIPTOR.services_by_name.get('FirstService') is None,
- 'Fix protobuf issue 3452!')
-class ClientTest(unittest.TestCase):
-
- def setUp(self):
- # In this test the client-side application under test executes in
- # a separate thread while we retain use of the test thread to "play
- # server".
- self._client_execution_thread_pool = logging_pool.pool(1)
-
- self._fake_time = grpc_testing.strict_fake_time(time.time())
- self._real_time = grpc_testing.strict_real_time()
- self._fake_time_channel = grpc_testing.channel(
- services_pb2.DESCRIPTOR.services_by_name.values(), self._fake_time)
- self._real_time_channel = grpc_testing.channel(
- services_pb2.DESCRIPTOR.services_by_name.values(), self._real_time)
-
- def tearDown(self):
- self._client_execution_thread_pool.shutdown(wait=True)
-
- def test_successful_unary_unary(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.UNARY_UNARY,
- self._real_time_channel)
- invocation_metadata, request, rpc = (
- self._real_time_channel.take_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN))
- rpc.send_initial_metadata(())
- rpc.terminate(_application_common.UNARY_UNARY_RESPONSE, (),
- grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.UNARY_UNARY_REQUEST, request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
- def test_successful_unary_stream(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.UNARY_STREAM,
- self._fake_time_channel)
- invocation_metadata, request, rpc = (
- self._fake_time_channel.take_unary_stream(
- _application_testing_common.FIRST_SERVICE_UNSTRE))
- rpc.send_initial_metadata(())
- rpc.terminate((), grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.UNARY_STREAM_REQUEST, request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
- def test_successful_stream_unary(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.STREAM_UNARY,
- self._real_time_channel)
- invocation_metadata, rpc = self._real_time_channel.take_stream_unary(
- _application_testing_common.FIRST_SERVICE_STREUN)
- rpc.send_initial_metadata(())
- first_request = rpc.take_request()
- second_request = rpc.take_request()
- third_request = rpc.take_request()
- rpc.requests_closed()
- rpc.terminate(_application_common.STREAM_UNARY_RESPONSE, (),
- grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
- first_request)
- self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
- second_request)
- self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
- third_request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
- def test_successful_stream_stream(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.STREAM_STREAM,
- self._fake_time_channel)
- invocation_metadata, rpc = self._fake_time_channel.take_stream_stream(
- _application_testing_common.FIRST_SERVICE_STRESTRE)
- first_request = rpc.take_request()
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- second_request = rpc.take_request()
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.requests_closed()
- rpc.terminate((), grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- first_request)
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- second_request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
- def test_concurrent_stream_stream(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run,
- _client_application.Scenario.CONCURRENT_STREAM_STREAM,
- self._real_time_channel)
- rpcs = []
- for _ in range(test_constants.RPC_CONCURRENCY):
- invocation_metadata, rpc = (
- self._real_time_channel.take_stream_stream(
- _application_testing_common.FIRST_SERVICE_STRESTRE))
- rpcs.append(rpc)
- requests = {}
- for rpc in rpcs:
- requests[rpc] = [rpc.take_request()]
- for rpc in rpcs:
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- for rpc in rpcs:
- requests[rpc].append(rpc.take_request())
- for rpc in rpcs:
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- for rpc in rpcs:
- rpc.requests_closed()
- for rpc in rpcs:
- rpc.terminate((), grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- for requests_of_one_rpc in requests.values():
- for request in requests_of_one_rpc:
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
- def test_cancelled_unary_unary(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run,
- _client_application.Scenario.CANCEL_UNARY_UNARY,
- self._fake_time_channel)
- invocation_metadata, request, rpc = (
- self._fake_time_channel.take_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN))
- rpc.send_initial_metadata(())
- rpc.cancelled()
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.UNARY_UNARY_REQUEST, request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
- def test_status_stream_unary(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run,
- _client_application.Scenario.CONCURRENT_STREAM_UNARY,
- self._fake_time_channel)
- rpcs = tuple(
- self._fake_time_channel.take_stream_unary(
- _application_testing_common.FIRST_SERVICE_STREUN)[1]
- for _ in range(test_constants.THREAD_CONCURRENCY))
- for rpc in rpcs:
- rpc.take_request()
- rpc.take_request()
- rpc.take_request()
- rpc.requests_closed()
- rpc.send_initial_metadata(((
- 'my_metadata_key',
- 'My Metadata Value!',
- ),))
- for rpc in rpcs[:-1]:
- rpc.terminate(_application_common.STREAM_UNARY_RESPONSE, (),
- grpc.StatusCode.OK, '')
- rpcs[-1].terminate(_application_common.STREAM_UNARY_RESPONSE, (),
- grpc.StatusCode.RESOURCE_EXHAUSTED,
- 'nope; not able to handle all those RPCs!')
- application_return_value = application_future.result()
-
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.UNSATISFACTORY)
-
- def test_status_stream_stream(self):
- code = grpc.StatusCode.DEADLINE_EXCEEDED
- details = 'test deadline exceeded!'
-
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.STREAM_STREAM,
- self._real_time_channel)
- invocation_metadata, rpc = self._real_time_channel.take_stream_stream(
- _application_testing_common.FIRST_SERVICE_STRESTRE)
- first_request = rpc.take_request()
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- second_request = rpc.take_request()
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.requests_closed()
- rpc.terminate((), code, details)
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- first_request)
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- second_request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.RPC_ERROR)
- self.assertIs(application_return_value.code, code)
- self.assertEqual(application_return_value.details, details)
-
- def test_misbehaving_server_unary_unary(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.UNARY_UNARY,
- self._fake_time_channel)
- invocation_metadata, request, rpc = (
- self._fake_time_channel.take_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN))
- rpc.send_initial_metadata(())
- rpc.terminate(_application_common.ERRONEOUS_UNARY_UNARY_RESPONSE, (),
- grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.UNARY_UNARY_REQUEST, request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.UNSATISFACTORY)
-
- def test_misbehaving_server_stream_stream(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run, _client_application.Scenario.STREAM_STREAM,
- self._real_time_channel)
- invocation_metadata, rpc = self._real_time_channel.take_stream_stream(
- _application_testing_common.FIRST_SERVICE_STRESTRE)
- first_request = rpc.take_request()
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- second_request = rpc.take_request()
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
- rpc.requests_closed()
- rpc.terminate((), grpc.StatusCode.OK, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- first_request)
- self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
- second_request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.UNSATISFACTORY)
-
- def test_infinite_request_stream_real_time(self):
- application_future = self._client_execution_thread_pool.submit(
- _client_application.run,
- _client_application.Scenario.INFINITE_REQUEST_STREAM,
- self._real_time_channel)
- invocation_metadata, rpc = self._real_time_channel.take_stream_unary(
- _application_testing_common.FIRST_SERVICE_STREUN)
- rpc.send_initial_metadata(())
- first_request = rpc.take_request()
- second_request = rpc.take_request()
- third_request = rpc.take_request()
- self._real_time.sleep_for(
- _application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
- rpc.terminate(_application_common.STREAM_UNARY_RESPONSE, (),
- grpc.StatusCode.DEADLINE_EXCEEDED, '')
- application_return_value = application_future.result()
-
- self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
- first_request)
- self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
- second_request)
- self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
- third_request)
- self.assertIs(application_return_value.kind,
- _client_application.Outcome.Kind.SATISFACTORY)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2017 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.
+
+from concurrent import futures
+import time
+import unittest
+
+import grpc
+from grpc.framework.foundation import logging_pool
+from tests.unit.framework.common import test_constants
+import grpc_testing
+
+from tests.testing import _application_common
+from tests.testing import _application_testing_common
+from tests.testing import _client_application
+from tests.testing.proto import requests_pb2
+from tests.testing.proto import services_pb2
+
+
+# TODO(https://github.com/google/protobuf/issues/3452): Drop this skip.
+@unittest.skipIf(
+ services_pb2.DESCRIPTOR.services_by_name.get('FirstService') is None,
+ 'Fix protobuf issue 3452!')
+class ClientTest(unittest.TestCase):
+
+ def setUp(self):
+ # In this test the client-side application under test executes in
+ # a separate thread while we retain use of the test thread to "play
+ # server".
+ self._client_execution_thread_pool = logging_pool.pool(1)
+
+ self._fake_time = grpc_testing.strict_fake_time(time.time())
+ self._real_time = grpc_testing.strict_real_time()
+ self._fake_time_channel = grpc_testing.channel(
+ services_pb2.DESCRIPTOR.services_by_name.values(), self._fake_time)
+ self._real_time_channel = grpc_testing.channel(
+ services_pb2.DESCRIPTOR.services_by_name.values(), self._real_time)
+
+ def tearDown(self):
+ self._client_execution_thread_pool.shutdown(wait=True)
+
+ def test_successful_unary_unary(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.UNARY_UNARY,
+ self._real_time_channel)
+ invocation_metadata, request, rpc = (
+ self._real_time_channel.take_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN))
+ rpc.send_initial_metadata(())
+ rpc.terminate(_application_common.UNARY_UNARY_RESPONSE, (),
+ grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.UNARY_UNARY_REQUEST, request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+ def test_successful_unary_stream(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.UNARY_STREAM,
+ self._fake_time_channel)
+ invocation_metadata, request, rpc = (
+ self._fake_time_channel.take_unary_stream(
+ _application_testing_common.FIRST_SERVICE_UNSTRE))
+ rpc.send_initial_metadata(())
+ rpc.terminate((), grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.UNARY_STREAM_REQUEST, request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+ def test_successful_stream_unary(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.STREAM_UNARY,
+ self._real_time_channel)
+ invocation_metadata, rpc = self._real_time_channel.take_stream_unary(
+ _application_testing_common.FIRST_SERVICE_STREUN)
+ rpc.send_initial_metadata(())
+ first_request = rpc.take_request()
+ second_request = rpc.take_request()
+ third_request = rpc.take_request()
+ rpc.requests_closed()
+ rpc.terminate(_application_common.STREAM_UNARY_RESPONSE, (),
+ grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
+ first_request)
+ self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
+ second_request)
+ self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
+ third_request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+ def test_successful_stream_stream(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.STREAM_STREAM,
+ self._fake_time_channel)
+ invocation_metadata, rpc = self._fake_time_channel.take_stream_stream(
+ _application_testing_common.FIRST_SERVICE_STRESTRE)
+ first_request = rpc.take_request()
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ second_request = rpc.take_request()
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.requests_closed()
+ rpc.terminate((), grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ first_request)
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ second_request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+ def test_concurrent_stream_stream(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run,
+ _client_application.Scenario.CONCURRENT_STREAM_STREAM,
+ self._real_time_channel)
+ rpcs = []
+ for _ in range(test_constants.RPC_CONCURRENCY):
+ invocation_metadata, rpc = (
+ self._real_time_channel.take_stream_stream(
+ _application_testing_common.FIRST_SERVICE_STRESTRE))
+ rpcs.append(rpc)
+ requests = {}
+ for rpc in rpcs:
+ requests[rpc] = [rpc.take_request()]
+ for rpc in rpcs:
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ for rpc in rpcs:
+ requests[rpc].append(rpc.take_request())
+ for rpc in rpcs:
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ for rpc in rpcs:
+ rpc.requests_closed()
+ for rpc in rpcs:
+ rpc.terminate((), grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ for requests_of_one_rpc in requests.values():
+ for request in requests_of_one_rpc:
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+ def test_cancelled_unary_unary(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run,
+ _client_application.Scenario.CANCEL_UNARY_UNARY,
+ self._fake_time_channel)
+ invocation_metadata, request, rpc = (
+ self._fake_time_channel.take_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN))
+ rpc.send_initial_metadata(())
+ rpc.cancelled()
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.UNARY_UNARY_REQUEST, request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+ def test_status_stream_unary(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run,
+ _client_application.Scenario.CONCURRENT_STREAM_UNARY,
+ self._fake_time_channel)
+ rpcs = tuple(
+ self._fake_time_channel.take_stream_unary(
+ _application_testing_common.FIRST_SERVICE_STREUN)[1]
+ for _ in range(test_constants.THREAD_CONCURRENCY))
+ for rpc in rpcs:
+ rpc.take_request()
+ rpc.take_request()
+ rpc.take_request()
+ rpc.requests_closed()
+ rpc.send_initial_metadata(((
+ 'my_metadata_key',
+ 'My Metadata Value!',
+ ),))
+ for rpc in rpcs[:-1]:
+ rpc.terminate(_application_common.STREAM_UNARY_RESPONSE, (),
+ grpc.StatusCode.OK, '')
+ rpcs[-1].terminate(_application_common.STREAM_UNARY_RESPONSE, (),
+ grpc.StatusCode.RESOURCE_EXHAUSTED,
+ 'nope; not able to handle all those RPCs!')
+ application_return_value = application_future.result()
+
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.UNSATISFACTORY)
+
+ def test_status_stream_stream(self):
+ code = grpc.StatusCode.DEADLINE_EXCEEDED
+ details = 'test deadline exceeded!'
+
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.STREAM_STREAM,
+ self._real_time_channel)
+ invocation_metadata, rpc = self._real_time_channel.take_stream_stream(
+ _application_testing_common.FIRST_SERVICE_STRESTRE)
+ first_request = rpc.take_request()
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ second_request = rpc.take_request()
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.requests_closed()
+ rpc.terminate((), code, details)
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ first_request)
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ second_request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.RPC_ERROR)
+ self.assertIs(application_return_value.code, code)
+ self.assertEqual(application_return_value.details, details)
+
+ def test_misbehaving_server_unary_unary(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.UNARY_UNARY,
+ self._fake_time_channel)
+ invocation_metadata, request, rpc = (
+ self._fake_time_channel.take_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN))
+ rpc.send_initial_metadata(())
+ rpc.terminate(_application_common.ERRONEOUS_UNARY_UNARY_RESPONSE, (),
+ grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.UNARY_UNARY_REQUEST, request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.UNSATISFACTORY)
+
+ def test_misbehaving_server_stream_stream(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run, _client_application.Scenario.STREAM_STREAM,
+ self._real_time_channel)
+ invocation_metadata, rpc = self._real_time_channel.take_stream_stream(
+ _application_testing_common.FIRST_SERVICE_STRESTRE)
+ first_request = rpc.take_request()
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ second_request = rpc.take_request()
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.send_response(_application_common.STREAM_STREAM_RESPONSE)
+ rpc.requests_closed()
+ rpc.terminate((), grpc.StatusCode.OK, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ first_request)
+ self.assertEqual(_application_common.STREAM_STREAM_REQUEST,
+ second_request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.UNSATISFACTORY)
+
+ def test_infinite_request_stream_real_time(self):
+ application_future = self._client_execution_thread_pool.submit(
+ _client_application.run,
+ _client_application.Scenario.INFINITE_REQUEST_STREAM,
+ self._real_time_channel)
+ invocation_metadata, rpc = self._real_time_channel.take_stream_unary(
+ _application_testing_common.FIRST_SERVICE_STREUN)
+ rpc.send_initial_metadata(())
+ first_request = rpc.take_request()
+ second_request = rpc.take_request()
+ third_request = rpc.take_request()
+ self._real_time.sleep_for(
+ _application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
+ rpc.terminate(_application_common.STREAM_UNARY_RESPONSE, (),
+ grpc.StatusCode.DEADLINE_EXCEEDED, '')
+ application_return_value = application_future.result()
+
+ self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
+ first_request)
+ self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
+ second_request)
+ self.assertEqual(_application_common.STREAM_UNARY_REQUEST,
+ third_request)
+ self.assertIs(application_return_value.kind,
+ _client_application.Outcome.Kind.SATISFACTORY)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_application.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_application.py
index 51ed977b8f..6268e4d997 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_application.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_application.py
@@ -1,95 +1,95 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""An example gRPC Python-using server-side application."""
-
-import grpc
-
-import threading
-
-# requests_pb2 is a semantic dependency of this module.
-from tests.testing import _application_common
-from tests.testing.proto import requests_pb2 # pylint: disable=unused-import
-from tests.testing.proto import services_pb2
-from tests.testing.proto import services_pb2_grpc
-
-
-class FirstServiceServicer(services_pb2_grpc.FirstServiceServicer):
- """Services RPCs."""
-
- def __init__(self):
- self._abort_lock = threading.RLock()
- self._abort_response = _application_common.ABORT_NO_STATUS_RESPONSE
-
- def UnUn(self, request, context):
- if request == _application_common.UNARY_UNARY_REQUEST:
- return _application_common.UNARY_UNARY_RESPONSE
- elif request == _application_common.ABORT_REQUEST:
- with self._abort_lock:
- try:
- context.abort(grpc.StatusCode.PERMISSION_DENIED,
- "Denying permission to test abort.")
- except Exception as e: # pylint: disable=broad-except
- self._abort_response = _application_common.ABORT_SUCCESS_RESPONSE
- else:
- self._abort_status = _application_common.ABORT_FAILURE_RESPONSE
- return None # NOTE: For the linter.
- elif request == _application_common.ABORT_SUCCESS_QUERY:
- with self._abort_lock:
- return self._abort_response
- else:
- context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
- context.set_details('Something is wrong with your request!')
- return services_pb2.Down()
-
- def UnStre(self, request, context):
- if _application_common.UNARY_STREAM_REQUEST != request:
- context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
- context.set_details('Something is wrong with your request!')
- return
- yield services_pb2.Strange() # pylint: disable=unreachable
-
- def StreUn(self, request_iterator, context):
- context.send_initial_metadata(((
- 'server_application_metadata_key',
- 'Hi there!',
- ),))
- for request in request_iterator:
- if request != _application_common.STREAM_UNARY_REQUEST:
- context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
- context.set_details('Something is wrong with your request!')
- return services_pb2.Strange()
- elif not context.is_active():
- return services_pb2.Strange()
- else:
- return _application_common.STREAM_UNARY_RESPONSE
-
- def StreStre(self, request_iterator, context):
- valid_requests = (_application_common.STREAM_STREAM_REQUEST,
- _application_common.STREAM_STREAM_MUTATING_REQUEST)
- for request in request_iterator:
- if request not in valid_requests:
- context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
- context.set_details('Something is wrong with your request!')
- return
- elif not context.is_active():
- return
- elif request == _application_common.STREAM_STREAM_REQUEST:
- yield _application_common.STREAM_STREAM_RESPONSE
- yield _application_common.STREAM_STREAM_RESPONSE
- elif request == _application_common.STREAM_STREAM_MUTATING_REQUEST:
- response = services_pb2.Bottom()
- for i in range(
- _application_common.STREAM_STREAM_MUTATING_COUNT):
- response.first_bottom_field = i
- yield response
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""An example gRPC Python-using server-side application."""
+
+import grpc
+
+import threading
+
+# requests_pb2 is a semantic dependency of this module.
+from tests.testing import _application_common
+from tests.testing.proto import requests_pb2 # pylint: disable=unused-import
+from tests.testing.proto import services_pb2
+from tests.testing.proto import services_pb2_grpc
+
+
+class FirstServiceServicer(services_pb2_grpc.FirstServiceServicer):
+ """Services RPCs."""
+
+ def __init__(self):
+ self._abort_lock = threading.RLock()
+ self._abort_response = _application_common.ABORT_NO_STATUS_RESPONSE
+
+ def UnUn(self, request, context):
+ if request == _application_common.UNARY_UNARY_REQUEST:
+ return _application_common.UNARY_UNARY_RESPONSE
+ elif request == _application_common.ABORT_REQUEST:
+ with self._abort_lock:
+ try:
+ context.abort(grpc.StatusCode.PERMISSION_DENIED,
+ "Denying permission to test abort.")
+ except Exception as e: # pylint: disable=broad-except
+ self._abort_response = _application_common.ABORT_SUCCESS_RESPONSE
+ else:
+ self._abort_status = _application_common.ABORT_FAILURE_RESPONSE
+ return None # NOTE: For the linter.
+ elif request == _application_common.ABORT_SUCCESS_QUERY:
+ with self._abort_lock:
+ return self._abort_response
+ else:
+ context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
+ context.set_details('Something is wrong with your request!')
+ return services_pb2.Down()
+
+ def UnStre(self, request, context):
+ if _application_common.UNARY_STREAM_REQUEST != request:
+ context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
+ context.set_details('Something is wrong with your request!')
+ return
+ yield services_pb2.Strange() # pylint: disable=unreachable
+
+ def StreUn(self, request_iterator, context):
+ context.send_initial_metadata(((
+ 'server_application_metadata_key',
+ 'Hi there!',
+ ),))
+ for request in request_iterator:
+ if request != _application_common.STREAM_UNARY_REQUEST:
+ context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
+ context.set_details('Something is wrong with your request!')
+ return services_pb2.Strange()
+ elif not context.is_active():
+ return services_pb2.Strange()
+ else:
+ return _application_common.STREAM_UNARY_RESPONSE
+
+ def StreStre(self, request_iterator, context):
+ valid_requests = (_application_common.STREAM_STREAM_REQUEST,
+ _application_common.STREAM_STREAM_MUTATING_REQUEST)
+ for request in request_iterator:
+ if request not in valid_requests:
+ context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
+ context.set_details('Something is wrong with your request!')
+ return
+ elif not context.is_active():
+ return
+ elif request == _application_common.STREAM_STREAM_REQUEST:
+ yield _application_common.STREAM_STREAM_RESPONSE
+ yield _application_common.STREAM_STREAM_RESPONSE
+ elif request == _application_common.STREAM_STREAM_MUTATING_REQUEST:
+ response = services_pb2.Bottom()
+ for i in range(
+ _application_common.STREAM_STREAM_MUTATING_COUNT):
+ response.first_bottom_field = i
+ yield response
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_test.py
index 617a41b7e5..dd8b258468 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_server_test.py
@@ -1,207 +1,207 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import time
-import unittest
-
-import grpc
-import grpc_testing
-
-from tests.testing import _application_common
-from tests.testing import _application_testing_common
-from tests.testing import _server_application
-from tests.testing.proto import services_pb2
-
-
-class FirstServiceServicerTest(unittest.TestCase):
-
- def setUp(self):
- self._real_time = grpc_testing.strict_real_time()
- self._fake_time = grpc_testing.strict_fake_time(time.time())
- servicer = _server_application.FirstServiceServicer()
- descriptors_to_servicers = {
- _application_testing_common.FIRST_SERVICE: servicer
- }
- self._real_time_server = grpc_testing.server_from_dictionary(
- descriptors_to_servicers, self._real_time)
- self._fake_time_server = grpc_testing.server_from_dictionary(
- descriptors_to_servicers, self._fake_time)
-
- def test_successful_unary_unary(self):
- rpc = self._real_time_server.invoke_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN, (),
- _application_common.UNARY_UNARY_REQUEST, None)
- initial_metadata = rpc.initial_metadata()
- response, trailing_metadata, code, details = rpc.termination()
-
- self.assertEqual(_application_common.UNARY_UNARY_RESPONSE, response)
- self.assertIs(code, grpc.StatusCode.OK)
-
- def test_successful_unary_stream(self):
- rpc = self._real_time_server.invoke_unary_stream(
- _application_testing_common.FIRST_SERVICE_UNSTRE, (),
- _application_common.UNARY_STREAM_REQUEST, None)
- initial_metadata = rpc.initial_metadata()
- trailing_metadata, code, details = rpc.termination()
-
- self.assertIs(code, grpc.StatusCode.OK)
-
- def test_successful_stream_unary(self):
- rpc = self._real_time_server.invoke_stream_unary(
- _application_testing_common.FIRST_SERVICE_STREUN, (), None)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.requests_closed()
- initial_metadata = rpc.initial_metadata()
- response, trailing_metadata, code, details = rpc.termination()
-
- self.assertEqual(_application_common.STREAM_UNARY_RESPONSE, response)
- self.assertIs(code, grpc.StatusCode.OK)
-
- def test_successful_stream_stream(self):
- rpc = self._real_time_server.invoke_stream_stream(
- _application_testing_common.FIRST_SERVICE_STRESTRE, (), None)
- rpc.send_request(_application_common.STREAM_STREAM_REQUEST)
- initial_metadata = rpc.initial_metadata()
- responses = [
- rpc.take_response(),
- rpc.take_response(),
- ]
- rpc.send_request(_application_common.STREAM_STREAM_REQUEST)
- rpc.send_request(_application_common.STREAM_STREAM_REQUEST)
- responses.extend([
- rpc.take_response(),
- rpc.take_response(),
- rpc.take_response(),
- rpc.take_response(),
- ])
- rpc.requests_closed()
- trailing_metadata, code, details = rpc.termination()
-
- for response in responses:
- self.assertEqual(_application_common.STREAM_STREAM_RESPONSE,
- response)
- self.assertIs(code, grpc.StatusCode.OK)
-
- def test_mutating_stream_stream(self):
- rpc = self._real_time_server.invoke_stream_stream(
- _application_testing_common.FIRST_SERVICE_STRESTRE, (), None)
- rpc.send_request(_application_common.STREAM_STREAM_MUTATING_REQUEST)
- initial_metadata = rpc.initial_metadata()
- responses = [
- rpc.take_response()
- for _ in range(_application_common.STREAM_STREAM_MUTATING_COUNT)
- ]
- rpc.send_request(_application_common.STREAM_STREAM_MUTATING_REQUEST)
- responses.extend([
- rpc.take_response()
- for _ in range(_application_common.STREAM_STREAM_MUTATING_COUNT)
- ])
- rpc.requests_closed()
- _, _, _ = rpc.termination()
- expected_responses = (
- services_pb2.Bottom(first_bottom_field=0),
- services_pb2.Bottom(first_bottom_field=1),
- services_pb2.Bottom(first_bottom_field=0),
- services_pb2.Bottom(first_bottom_field=1),
- )
- self.assertSequenceEqual(expected_responses, responses)
-
- def test_server_rpc_idempotence(self):
- rpc = self._real_time_server.invoke_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN, (),
- _application_common.UNARY_UNARY_REQUEST, None)
- first_initial_metadata = rpc.initial_metadata()
- second_initial_metadata = rpc.initial_metadata()
- third_initial_metadata = rpc.initial_metadata()
- first_termination = rpc.termination()
- second_termination = rpc.termination()
- third_termination = rpc.termination()
-
- for later_initial_metadata in (
- second_initial_metadata,
- third_initial_metadata,
- ):
- self.assertEqual(first_initial_metadata, later_initial_metadata)
- response = first_termination[0]
- terminal_metadata = first_termination[1]
- code = first_termination[2]
- details = first_termination[3]
- for later_termination in (
- second_termination,
- third_termination,
- ):
- self.assertEqual(response, later_termination[0])
- self.assertEqual(terminal_metadata, later_termination[1])
- self.assertIs(code, later_termination[2])
- self.assertEqual(details, later_termination[3])
- self.assertEqual(_application_common.UNARY_UNARY_RESPONSE, response)
- self.assertIs(code, grpc.StatusCode.OK)
-
- def test_misbehaving_client_unary_unary(self):
- rpc = self._real_time_server.invoke_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN, (),
- _application_common.ERRONEOUS_UNARY_UNARY_REQUEST, None)
- initial_metadata = rpc.initial_metadata()
- response, trailing_metadata, code, details = rpc.termination()
-
- self.assertIsNot(code, grpc.StatusCode.OK)
-
- def test_infinite_request_stream_real_time(self):
- rpc = self._real_time_server.invoke_stream_unary(
- _application_testing_common.FIRST_SERVICE_STREUN, (),
- _application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- initial_metadata = rpc.initial_metadata()
- self._real_time.sleep_for(
- _application_common.INFINITE_REQUEST_STREAM_TIMEOUT * 2)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- response, trailing_metadata, code, details = rpc.termination()
-
- self.assertIs(code, grpc.StatusCode.DEADLINE_EXCEEDED)
-
- def test_infinite_request_stream_fake_time(self):
- rpc = self._fake_time_server.invoke_stream_unary(
- _application_testing_common.FIRST_SERVICE_STREUN, (),
- _application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- initial_metadata = rpc.initial_metadata()
- self._fake_time.sleep_for(
- _application_common.INFINITE_REQUEST_STREAM_TIMEOUT * 2)
- rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
- response, trailing_metadata, code, details = rpc.termination()
-
- self.assertIs(code, grpc.StatusCode.DEADLINE_EXCEEDED)
-
- def test_servicer_context_abort(self):
- rpc = self._real_time_server.invoke_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN, (),
- _application_common.ABORT_REQUEST, None)
- _, _, code, _ = rpc.termination()
- self.assertIs(code, grpc.StatusCode.PERMISSION_DENIED)
- rpc = self._real_time_server.invoke_unary_unary(
- _application_testing_common.FIRST_SERVICE_UNUN, (),
- _application_common.ABORT_SUCCESS_QUERY, None)
- response, _, code, _ = rpc.termination()
- self.assertEqual(_application_common.ABORT_SUCCESS_RESPONSE, response)
- self.assertIs(code, grpc.StatusCode.OK)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import time
+import unittest
+
+import grpc
+import grpc_testing
+
+from tests.testing import _application_common
+from tests.testing import _application_testing_common
+from tests.testing import _server_application
+from tests.testing.proto import services_pb2
+
+
+class FirstServiceServicerTest(unittest.TestCase):
+
+ def setUp(self):
+ self._real_time = grpc_testing.strict_real_time()
+ self._fake_time = grpc_testing.strict_fake_time(time.time())
+ servicer = _server_application.FirstServiceServicer()
+ descriptors_to_servicers = {
+ _application_testing_common.FIRST_SERVICE: servicer
+ }
+ self._real_time_server = grpc_testing.server_from_dictionary(
+ descriptors_to_servicers, self._real_time)
+ self._fake_time_server = grpc_testing.server_from_dictionary(
+ descriptors_to_servicers, self._fake_time)
+
+ def test_successful_unary_unary(self):
+ rpc = self._real_time_server.invoke_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN, (),
+ _application_common.UNARY_UNARY_REQUEST, None)
+ initial_metadata = rpc.initial_metadata()
+ response, trailing_metadata, code, details = rpc.termination()
+
+ self.assertEqual(_application_common.UNARY_UNARY_RESPONSE, response)
+ self.assertIs(code, grpc.StatusCode.OK)
+
+ def test_successful_unary_stream(self):
+ rpc = self._real_time_server.invoke_unary_stream(
+ _application_testing_common.FIRST_SERVICE_UNSTRE, (),
+ _application_common.UNARY_STREAM_REQUEST, None)
+ initial_metadata = rpc.initial_metadata()
+ trailing_metadata, code, details = rpc.termination()
+
+ self.assertIs(code, grpc.StatusCode.OK)
+
+ def test_successful_stream_unary(self):
+ rpc = self._real_time_server.invoke_stream_unary(
+ _application_testing_common.FIRST_SERVICE_STREUN, (), None)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.requests_closed()
+ initial_metadata = rpc.initial_metadata()
+ response, trailing_metadata, code, details = rpc.termination()
+
+ self.assertEqual(_application_common.STREAM_UNARY_RESPONSE, response)
+ self.assertIs(code, grpc.StatusCode.OK)
+
+ def test_successful_stream_stream(self):
+ rpc = self._real_time_server.invoke_stream_stream(
+ _application_testing_common.FIRST_SERVICE_STRESTRE, (), None)
+ rpc.send_request(_application_common.STREAM_STREAM_REQUEST)
+ initial_metadata = rpc.initial_metadata()
+ responses = [
+ rpc.take_response(),
+ rpc.take_response(),
+ ]
+ rpc.send_request(_application_common.STREAM_STREAM_REQUEST)
+ rpc.send_request(_application_common.STREAM_STREAM_REQUEST)
+ responses.extend([
+ rpc.take_response(),
+ rpc.take_response(),
+ rpc.take_response(),
+ rpc.take_response(),
+ ])
+ rpc.requests_closed()
+ trailing_metadata, code, details = rpc.termination()
+
+ for response in responses:
+ self.assertEqual(_application_common.STREAM_STREAM_RESPONSE,
+ response)
+ self.assertIs(code, grpc.StatusCode.OK)
+
+ def test_mutating_stream_stream(self):
+ rpc = self._real_time_server.invoke_stream_stream(
+ _application_testing_common.FIRST_SERVICE_STRESTRE, (), None)
+ rpc.send_request(_application_common.STREAM_STREAM_MUTATING_REQUEST)
+ initial_metadata = rpc.initial_metadata()
+ responses = [
+ rpc.take_response()
+ for _ in range(_application_common.STREAM_STREAM_MUTATING_COUNT)
+ ]
+ rpc.send_request(_application_common.STREAM_STREAM_MUTATING_REQUEST)
+ responses.extend([
+ rpc.take_response()
+ for _ in range(_application_common.STREAM_STREAM_MUTATING_COUNT)
+ ])
+ rpc.requests_closed()
+ _, _, _ = rpc.termination()
+ expected_responses = (
+ services_pb2.Bottom(first_bottom_field=0),
+ services_pb2.Bottom(first_bottom_field=1),
+ services_pb2.Bottom(first_bottom_field=0),
+ services_pb2.Bottom(first_bottom_field=1),
+ )
+ self.assertSequenceEqual(expected_responses, responses)
+
+ def test_server_rpc_idempotence(self):
+ rpc = self._real_time_server.invoke_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN, (),
+ _application_common.UNARY_UNARY_REQUEST, None)
+ first_initial_metadata = rpc.initial_metadata()
+ second_initial_metadata = rpc.initial_metadata()
+ third_initial_metadata = rpc.initial_metadata()
+ first_termination = rpc.termination()
+ second_termination = rpc.termination()
+ third_termination = rpc.termination()
+
+ for later_initial_metadata in (
+ second_initial_metadata,
+ third_initial_metadata,
+ ):
+ self.assertEqual(first_initial_metadata, later_initial_metadata)
+ response = first_termination[0]
+ terminal_metadata = first_termination[1]
+ code = first_termination[2]
+ details = first_termination[3]
+ for later_termination in (
+ second_termination,
+ third_termination,
+ ):
+ self.assertEqual(response, later_termination[0])
+ self.assertEqual(terminal_metadata, later_termination[1])
+ self.assertIs(code, later_termination[2])
+ self.assertEqual(details, later_termination[3])
+ self.assertEqual(_application_common.UNARY_UNARY_RESPONSE, response)
+ self.assertIs(code, grpc.StatusCode.OK)
+
+ def test_misbehaving_client_unary_unary(self):
+ rpc = self._real_time_server.invoke_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN, (),
+ _application_common.ERRONEOUS_UNARY_UNARY_REQUEST, None)
+ initial_metadata = rpc.initial_metadata()
+ response, trailing_metadata, code, details = rpc.termination()
+
+ self.assertIsNot(code, grpc.StatusCode.OK)
+
+ def test_infinite_request_stream_real_time(self):
+ rpc = self._real_time_server.invoke_stream_unary(
+ _application_testing_common.FIRST_SERVICE_STREUN, (),
+ _application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ initial_metadata = rpc.initial_metadata()
+ self._real_time.sleep_for(
+ _application_common.INFINITE_REQUEST_STREAM_TIMEOUT * 2)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ response, trailing_metadata, code, details = rpc.termination()
+
+ self.assertIs(code, grpc.StatusCode.DEADLINE_EXCEEDED)
+
+ def test_infinite_request_stream_fake_time(self):
+ rpc = self._fake_time_server.invoke_stream_unary(
+ _application_testing_common.FIRST_SERVICE_STREUN, (),
+ _application_common.INFINITE_REQUEST_STREAM_TIMEOUT)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ initial_metadata = rpc.initial_metadata()
+ self._fake_time.sleep_for(
+ _application_common.INFINITE_REQUEST_STREAM_TIMEOUT * 2)
+ rpc.send_request(_application_common.STREAM_UNARY_REQUEST)
+ response, trailing_metadata, code, details = rpc.termination()
+
+ self.assertIs(code, grpc.StatusCode.DEADLINE_EXCEEDED)
+
+ def test_servicer_context_abort(self):
+ rpc = self._real_time_server.invoke_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN, (),
+ _application_common.ABORT_REQUEST, None)
+ _, _, code, _ = rpc.termination()
+ self.assertIs(code, grpc.StatusCode.PERMISSION_DENIED)
+ rpc = self._real_time_server.invoke_unary_unary(
+ _application_testing_common.FIRST_SERVICE_UNUN, (),
+ _application_common.ABORT_SUCCESS_QUERY, None)
+ response, _, code, _ = rpc.termination()
+ self.assertEqual(_application_common.ABORT_SUCCESS_RESPONSE, response)
+ self.assertIs(code, grpc.StatusCode.OK)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_time_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_time_test.py
index cab665c045..4f1495a5f0 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_time_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/_time_test.py
@@ -1,165 +1,165 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import random
-import threading
-import time
-import unittest
-
-import grpc_testing
-
-_QUANTUM = 0.3
-_MANY = 10000
-# Tests that run in real time can either wait for the scheduler to
-# eventually run what needs to be run (and risk timing out) or declare
-# that the scheduler didn't schedule work reasonably fast enough. We
-# choose the latter for this test.
-_PATHOLOGICAL_SCHEDULING = 'pathological thread scheduling!'
-
-
-class _TimeNoter(object):
-
- def __init__(self, time):
- self._condition = threading.Condition()
- self._time = time
- self._call_times = []
-
- def __call__(self):
- with self._condition:
- self._call_times.append(self._time.time())
-
- def call_times(self):
- with self._condition:
- return tuple(self._call_times)
-
-
-class TimeTest(object):
-
- def test_sleep_for(self):
- start_time = self._time.time()
- self._time.sleep_for(_QUANTUM)
- end_time = self._time.time()
-
- self.assertLessEqual(start_time + _QUANTUM, end_time)
-
- def test_sleep_until(self):
- start_time = self._time.time()
- self._time.sleep_until(start_time + _QUANTUM)
- end_time = self._time.time()
-
- self.assertLessEqual(start_time + _QUANTUM, end_time)
-
- def test_call_in(self):
- time_noter = _TimeNoter(self._time)
-
- start_time = self._time.time()
- self._time.call_in(time_noter, _QUANTUM)
- self._time.sleep_for(_QUANTUM * 2)
- call_times = time_noter.call_times()
-
- self.assertTrue(call_times, msg=_PATHOLOGICAL_SCHEDULING)
- self.assertLessEqual(start_time + _QUANTUM, call_times[0])
-
- def test_call_at(self):
- time_noter = _TimeNoter(self._time)
-
- start_time = self._time.time()
- self._time.call_at(time_noter, self._time.time() + _QUANTUM)
- self._time.sleep_for(_QUANTUM * 2)
- call_times = time_noter.call_times()
-
- self.assertTrue(call_times, msg=_PATHOLOGICAL_SCHEDULING)
- self.assertLessEqual(start_time + _QUANTUM, call_times[0])
-
- def test_cancel(self):
- time_noter = _TimeNoter(self._time)
-
- future = self._time.call_in(time_noter, _QUANTUM * 2)
- self._time.sleep_for(_QUANTUM)
- cancelled = future.cancel()
- self._time.sleep_for(_QUANTUM * 2)
- call_times = time_noter.call_times()
-
- self.assertFalse(call_times, msg=_PATHOLOGICAL_SCHEDULING)
- self.assertTrue(cancelled)
- self.assertTrue(future.cancelled())
-
- def test_many(self):
- test_events = tuple(threading.Event() for _ in range(_MANY))
- possibly_cancelled_futures = {}
- background_noise_futures = []
-
- for test_event in test_events:
- possibly_cancelled_futures[test_event] = self._time.call_in(
- test_event.set, _QUANTUM * (2 + random.random()))
- for _ in range(_MANY):
- background_noise_futures.append(
- self._time.call_in(threading.Event().set,
- _QUANTUM * 1000 * random.random()))
- self._time.sleep_for(_QUANTUM)
- cancelled = set()
- for test_event, test_future in possibly_cancelled_futures.items():
- if bool(random.randint(0, 1)) and test_future.cancel():
- cancelled.add(test_event)
- self._time.sleep_for(_QUANTUM * 3)
-
- for test_event in test_events:
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import random
+import threading
+import time
+import unittest
+
+import grpc_testing
+
+_QUANTUM = 0.3
+_MANY = 10000
+# Tests that run in real time can either wait for the scheduler to
+# eventually run what needs to be run (and risk timing out) or declare
+# that the scheduler didn't schedule work reasonably fast enough. We
+# choose the latter for this test.
+_PATHOLOGICAL_SCHEDULING = 'pathological thread scheduling!'
+
+
+class _TimeNoter(object):
+
+ def __init__(self, time):
+ self._condition = threading.Condition()
+ self._time = time
+ self._call_times = []
+
+ def __call__(self):
+ with self._condition:
+ self._call_times.append(self._time.time())
+
+ def call_times(self):
+ with self._condition:
+ return tuple(self._call_times)
+
+
+class TimeTest(object):
+
+ def test_sleep_for(self):
+ start_time = self._time.time()
+ self._time.sleep_for(_QUANTUM)
+ end_time = self._time.time()
+
+ self.assertLessEqual(start_time + _QUANTUM, end_time)
+
+ def test_sleep_until(self):
+ start_time = self._time.time()
+ self._time.sleep_until(start_time + _QUANTUM)
+ end_time = self._time.time()
+
+ self.assertLessEqual(start_time + _QUANTUM, end_time)
+
+ def test_call_in(self):
+ time_noter = _TimeNoter(self._time)
+
+ start_time = self._time.time()
+ self._time.call_in(time_noter, _QUANTUM)
+ self._time.sleep_for(_QUANTUM * 2)
+ call_times = time_noter.call_times()
+
+ self.assertTrue(call_times, msg=_PATHOLOGICAL_SCHEDULING)
+ self.assertLessEqual(start_time + _QUANTUM, call_times[0])
+
+ def test_call_at(self):
+ time_noter = _TimeNoter(self._time)
+
+ start_time = self._time.time()
+ self._time.call_at(time_noter, self._time.time() + _QUANTUM)
+ self._time.sleep_for(_QUANTUM * 2)
+ call_times = time_noter.call_times()
+
+ self.assertTrue(call_times, msg=_PATHOLOGICAL_SCHEDULING)
+ self.assertLessEqual(start_time + _QUANTUM, call_times[0])
+
+ def test_cancel(self):
+ time_noter = _TimeNoter(self._time)
+
+ future = self._time.call_in(time_noter, _QUANTUM * 2)
+ self._time.sleep_for(_QUANTUM)
+ cancelled = future.cancel()
+ self._time.sleep_for(_QUANTUM * 2)
+ call_times = time_noter.call_times()
+
+ self.assertFalse(call_times, msg=_PATHOLOGICAL_SCHEDULING)
+ self.assertTrue(cancelled)
+ self.assertTrue(future.cancelled())
+
+ def test_many(self):
+ test_events = tuple(threading.Event() for _ in range(_MANY))
+ possibly_cancelled_futures = {}
+ background_noise_futures = []
+
+ for test_event in test_events:
+ possibly_cancelled_futures[test_event] = self._time.call_in(
+ test_event.set, _QUANTUM * (2 + random.random()))
+ for _ in range(_MANY):
+ background_noise_futures.append(
+ self._time.call_in(threading.Event().set,
+ _QUANTUM * 1000 * random.random()))
+ self._time.sleep_for(_QUANTUM)
+ cancelled = set()
+ for test_event, test_future in possibly_cancelled_futures.items():
+ if bool(random.randint(0, 1)) and test_future.cancel():
+ cancelled.add(test_event)
+ self._time.sleep_for(_QUANTUM * 3)
+
+ for test_event in test_events:
(self.assertFalse if test_event in cancelled else self.assertTrue)(
test_event.is_set())
- for background_noise_future in background_noise_futures:
- background_noise_future.cancel()
-
- def test_same_behavior_used_several_times(self):
- time_noter = _TimeNoter(self._time)
-
- start_time = self._time.time()
- first_future_at_one = self._time.call_in(time_noter, _QUANTUM)
- second_future_at_one = self._time.call_in(time_noter, _QUANTUM)
- first_future_at_three = self._time.call_in(time_noter, _QUANTUM * 3)
- second_future_at_three = self._time.call_in(time_noter, _QUANTUM * 3)
- self._time.sleep_for(_QUANTUM * 2)
- first_future_at_one_cancelled = first_future_at_one.cancel()
- second_future_at_one_cancelled = second_future_at_one.cancel()
- first_future_at_three_cancelled = first_future_at_three.cancel()
- self._time.sleep_for(_QUANTUM * 2)
- second_future_at_three_cancelled = second_future_at_three.cancel()
- first_future_at_three_cancelled_again = first_future_at_three.cancel()
- call_times = time_noter.call_times()
-
- self.assertEqual(3, len(call_times), msg=_PATHOLOGICAL_SCHEDULING)
- self.assertFalse(first_future_at_one_cancelled)
- self.assertFalse(second_future_at_one_cancelled)
- self.assertTrue(first_future_at_three_cancelled)
- self.assertFalse(second_future_at_three_cancelled)
- self.assertTrue(first_future_at_three_cancelled_again)
- self.assertLessEqual(start_time + _QUANTUM, call_times[0])
- self.assertLessEqual(start_time + _QUANTUM, call_times[1])
- self.assertLessEqual(start_time + _QUANTUM * 3, call_times[2])
-
-
-class StrictRealTimeTest(TimeTest, unittest.TestCase):
-
- def setUp(self):
- self._time = grpc_testing.strict_real_time()
-
-
-class StrictFakeTimeTest(TimeTest, unittest.TestCase):
-
- def setUp(self):
- self._time = grpc_testing.strict_fake_time(
- random.randint(0, int(time.time())))
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ for background_noise_future in background_noise_futures:
+ background_noise_future.cancel()
+
+ def test_same_behavior_used_several_times(self):
+ time_noter = _TimeNoter(self._time)
+
+ start_time = self._time.time()
+ first_future_at_one = self._time.call_in(time_noter, _QUANTUM)
+ second_future_at_one = self._time.call_in(time_noter, _QUANTUM)
+ first_future_at_three = self._time.call_in(time_noter, _QUANTUM * 3)
+ second_future_at_three = self._time.call_in(time_noter, _QUANTUM * 3)
+ self._time.sleep_for(_QUANTUM * 2)
+ first_future_at_one_cancelled = first_future_at_one.cancel()
+ second_future_at_one_cancelled = second_future_at_one.cancel()
+ first_future_at_three_cancelled = first_future_at_three.cancel()
+ self._time.sleep_for(_QUANTUM * 2)
+ second_future_at_three_cancelled = second_future_at_three.cancel()
+ first_future_at_three_cancelled_again = first_future_at_three.cancel()
+ call_times = time_noter.call_times()
+
+ self.assertEqual(3, len(call_times), msg=_PATHOLOGICAL_SCHEDULING)
+ self.assertFalse(first_future_at_one_cancelled)
+ self.assertFalse(second_future_at_one_cancelled)
+ self.assertTrue(first_future_at_three_cancelled)
+ self.assertFalse(second_future_at_three_cancelled)
+ self.assertTrue(first_future_at_three_cancelled_again)
+ self.assertLessEqual(start_time + _QUANTUM, call_times[0])
+ self.assertLessEqual(start_time + _QUANTUM, call_times[1])
+ self.assertLessEqual(start_time + _QUANTUM * 3, call_times[2])
+
+
+class StrictRealTimeTest(TimeTest, unittest.TestCase):
+
+ def setUp(self):
+ self._time = grpc_testing.strict_real_time()
+
+
+class StrictFakeTimeTest(TimeTest, unittest.TestCase):
+
+ def setUp(self):
+ self._time = grpc_testing.strict_fake_time(
+ random.randint(0, int(time.time())))
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/proto/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/proto/__init__.py
index 1e120359cf..0030911829 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/proto/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/testing/proto/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2017 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.
+# Copyright 2017 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py
index 5fb4f3c3cf..dc985eebb4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 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.
+# Copyright 2015 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py
index d2eaf97d5f..ff16091c50 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py
@@ -1,154 +1,154 @@
-# Copyright 2018 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.
-"""Tests server context abort mechanism"""
-
-import unittest
-import collections
-import gc
-import logging
-import weakref
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_ABORT = '/test/abort'
-_ABORT_WITH_STATUS = '/test/AbortWithStatus'
-_INVALID_CODE = '/test/InvalidCode'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_ABORT_DETAILS = 'Abandon ship!'
-_ABORT_METADATA = (('a-trailing-metadata', '42'),)
-
-
-class _Status(
+# Copyright 2018 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.
+"""Tests server context abort mechanism"""
+
+import unittest
+import collections
+import gc
+import logging
+import weakref
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_ABORT = '/test/abort'
+_ABORT_WITH_STATUS = '/test/AbortWithStatus'
+_INVALID_CODE = '/test/InvalidCode'
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+_ABORT_DETAILS = 'Abandon ship!'
+_ABORT_METADATA = (('a-trailing-metadata', '42'),)
+
+
+class _Status(
collections.namedtuple('_Status',
('code', 'details', 'trailing_metadata')),
grpc.Status):
- pass
-
-
-class _Object(object):
- pass
-
-
-do_not_leak_me = _Object()
-
-
-def abort_unary_unary(request, servicer_context):
- this_should_not_be_leaked = do_not_leak_me
- servicer_context.abort(
- grpc.StatusCode.INTERNAL,
- _ABORT_DETAILS,
- )
- raise Exception('This line should not be executed!')
-
-
-def abort_with_status_unary_unary(request, servicer_context):
- servicer_context.abort_with_status(
- _Status(
- code=grpc.StatusCode.INTERNAL,
- details=_ABORT_DETAILS,
- trailing_metadata=_ABORT_METADATA,
- ))
- raise Exception('This line should not be executed!')
-
-
-def invalid_code_unary_unary(request, servicer_context):
- servicer_context.abort(
- 42,
- _ABORT_DETAILS,
- )
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _ABORT:
- return grpc.unary_unary_rpc_method_handler(abort_unary_unary)
- elif handler_call_details.method == _ABORT_WITH_STATUS:
- return grpc.unary_unary_rpc_method_handler(
- abort_with_status_unary_unary)
- elif handler_call_details.method == _INVALID_CODE:
- return grpc.stream_stream_rpc_method_handler(
- invalid_code_unary_unary)
- else:
- return None
-
-
-class AbortTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._channel.close()
- self._server.stop(0)
-
- def test_abort(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_ABORT)(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
- self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
-
- # This test ensures that abort() does not store the raised exception, which
- # on Python 3 (via the `__traceback__` attribute) holds a reference to
- # all local vars. Storing the raised exception can prevent GC and stop the
- # grpc_call from being unref'ed, even after server shutdown.
- @unittest.skip("https://github.com/grpc/grpc/issues/17927")
- def test_abort_does_not_leak_local_vars(self):
- global do_not_leak_me # pylint: disable=global-statement
- weak_ref = weakref.ref(do_not_leak_me)
-
- # Servicer will abort() after creating a local ref to do_not_leak_me.
- with self.assertRaises(grpc.RpcError):
- self._channel.unary_unary(_ABORT)(_REQUEST)
-
- # Server may still have a stack frame reference to the exception even
- # after client sees error, so ensure server has shutdown.
- self._server.stop(None)
- do_not_leak_me = None
- self.assertIsNone(weak_ref())
-
- def test_abort_with_status(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_ABORT_WITH_STATUS)(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
- self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
- self.assertEqual(rpc_error.trailing_metadata(), _ABORT_METADATA)
-
- def test_invalid_code(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_INVALID_CODE)(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.UNKNOWN)
- self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ pass
+
+
+class _Object(object):
+ pass
+
+
+do_not_leak_me = _Object()
+
+
+def abort_unary_unary(request, servicer_context):
+ this_should_not_be_leaked = do_not_leak_me
+ servicer_context.abort(
+ grpc.StatusCode.INTERNAL,
+ _ABORT_DETAILS,
+ )
+ raise Exception('This line should not be executed!')
+
+
+def abort_with_status_unary_unary(request, servicer_context):
+ servicer_context.abort_with_status(
+ _Status(
+ code=grpc.StatusCode.INTERNAL,
+ details=_ABORT_DETAILS,
+ trailing_metadata=_ABORT_METADATA,
+ ))
+ raise Exception('This line should not be executed!')
+
+
+def invalid_code_unary_unary(request, servicer_context):
+ servicer_context.abort(
+ 42,
+ _ABORT_DETAILS,
+ )
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _ABORT:
+ return grpc.unary_unary_rpc_method_handler(abort_unary_unary)
+ elif handler_call_details.method == _ABORT_WITH_STATUS:
+ return grpc.unary_unary_rpc_method_handler(
+ abort_with_status_unary_unary)
+ elif handler_call_details.method == _INVALID_CODE:
+ return grpc.stream_stream_rpc_method_handler(
+ invalid_code_unary_unary)
+ else:
+ return None
+
+
+class AbortTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.add_generic_rpc_handlers((_GenericHandler(),))
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._channel.close()
+ self._server.stop(0)
+
+ def test_abort(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_ABORT)(_REQUEST)
+ rpc_error = exception_context.exception
+
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
+ self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
+
+ # This test ensures that abort() does not store the raised exception, which
+ # on Python 3 (via the `__traceback__` attribute) holds a reference to
+ # all local vars. Storing the raised exception can prevent GC and stop the
+ # grpc_call from being unref'ed, even after server shutdown.
+ @unittest.skip("https://github.com/grpc/grpc/issues/17927")
+ def test_abort_does_not_leak_local_vars(self):
+ global do_not_leak_me # pylint: disable=global-statement
+ weak_ref = weakref.ref(do_not_leak_me)
+
+ # Servicer will abort() after creating a local ref to do_not_leak_me.
+ with self.assertRaises(grpc.RpcError):
+ self._channel.unary_unary(_ABORT)(_REQUEST)
+
+ # Server may still have a stack frame reference to the exception even
+ # after client sees error, so ensure server has shutdown.
+ self._server.stop(None)
+ do_not_leak_me = None
+ self.assertIsNone(weak_ref())
+
+ def test_abort_with_status(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_ABORT_WITH_STATUS)(_REQUEST)
+ rpc_error = exception_context.exception
+
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
+ self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
+ self.assertEqual(rpc_error.trailing_metadata(), _ABORT_METADATA)
+
+ def test_invalid_code(self):
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._channel.unary_unary(_INVALID_CODE)(_REQUEST)
+ rpc_error = exception_context.exception
+
+ self.assertEqual(rpc_error.code(), grpc.StatusCode.UNKNOWN)
+ self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py
index a459ee6e19..7f82dfb2a3 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py
@@ -1,118 +1,118 @@
-# Copyright 2016 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.
-"""Test of gRPC Python's application-layer API."""
-
-import unittest
-import logging
-
-import six
-
-import grpc
-
-from tests.unit import _from_grpc_import_star
-
-
-class AllTest(unittest.TestCase):
-
- def testAll(self):
- expected_grpc_code_elements = (
- 'FutureTimeoutError',
- 'FutureCancelledError',
- 'Future',
- 'ChannelConnectivity',
- 'Compression',
- 'StatusCode',
- 'Status',
- 'RpcError',
- 'RpcContext',
- 'Call',
- 'ChannelCredentials',
- 'CallCredentials',
- 'AuthMetadataContext',
- 'AuthMetadataPluginCallback',
- 'AuthMetadataPlugin',
- 'ServerCertificateConfiguration',
- 'ServerCredentials',
- 'UnaryUnaryMultiCallable',
- 'UnaryStreamMultiCallable',
- 'StreamUnaryMultiCallable',
- 'StreamStreamMultiCallable',
- 'UnaryUnaryClientInterceptor',
- 'UnaryStreamClientInterceptor',
- 'StreamUnaryClientInterceptor',
- 'StreamStreamClientInterceptor',
- 'Channel',
- 'ServicerContext',
- 'RpcMethodHandler',
- 'HandlerCallDetails',
- 'GenericRpcHandler',
- 'ServiceRpcHandler',
- 'Server',
- 'ServerInterceptor',
- 'LocalConnectionType',
- 'local_channel_credentials',
- 'local_server_credentials',
+# Copyright 2016 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.
+"""Test of gRPC Python's application-layer API."""
+
+import unittest
+import logging
+
+import six
+
+import grpc
+
+from tests.unit import _from_grpc_import_star
+
+
+class AllTest(unittest.TestCase):
+
+ def testAll(self):
+ expected_grpc_code_elements = (
+ 'FutureTimeoutError',
+ 'FutureCancelledError',
+ 'Future',
+ 'ChannelConnectivity',
+ 'Compression',
+ 'StatusCode',
+ 'Status',
+ 'RpcError',
+ 'RpcContext',
+ 'Call',
+ 'ChannelCredentials',
+ 'CallCredentials',
+ 'AuthMetadataContext',
+ 'AuthMetadataPluginCallback',
+ 'AuthMetadataPlugin',
+ 'ServerCertificateConfiguration',
+ 'ServerCredentials',
+ 'UnaryUnaryMultiCallable',
+ 'UnaryStreamMultiCallable',
+ 'StreamUnaryMultiCallable',
+ 'StreamStreamMultiCallable',
+ 'UnaryUnaryClientInterceptor',
+ 'UnaryStreamClientInterceptor',
+ 'StreamUnaryClientInterceptor',
+ 'StreamStreamClientInterceptor',
+ 'Channel',
+ 'ServicerContext',
+ 'RpcMethodHandler',
+ 'HandlerCallDetails',
+ 'GenericRpcHandler',
+ 'ServiceRpcHandler',
+ 'Server',
+ 'ServerInterceptor',
+ 'LocalConnectionType',
+ 'local_channel_credentials',
+ 'local_server_credentials',
'alts_channel_credentials',
'alts_server_credentials',
- 'unary_unary_rpc_method_handler',
- 'unary_stream_rpc_method_handler',
- 'stream_unary_rpc_method_handler',
- 'ClientCallDetails',
- 'stream_stream_rpc_method_handler',
- 'method_handlers_generic_handler',
- 'ssl_channel_credentials',
- 'metadata_call_credentials',
- 'access_token_call_credentials',
- 'composite_call_credentials',
- 'composite_channel_credentials',
- 'ssl_server_credentials',
- 'ssl_server_certificate_configuration',
- 'dynamic_ssl_server_credentials',
- 'channel_ready_future',
- 'insecure_channel',
- 'secure_channel',
- 'intercept_channel',
- 'server',
+ 'unary_unary_rpc_method_handler',
+ 'unary_stream_rpc_method_handler',
+ 'stream_unary_rpc_method_handler',
+ 'ClientCallDetails',
+ 'stream_stream_rpc_method_handler',
+ 'method_handlers_generic_handler',
+ 'ssl_channel_credentials',
+ 'metadata_call_credentials',
+ 'access_token_call_credentials',
+ 'composite_call_credentials',
+ 'composite_channel_credentials',
+ 'ssl_server_credentials',
+ 'ssl_server_certificate_configuration',
+ 'dynamic_ssl_server_credentials',
+ 'channel_ready_future',
+ 'insecure_channel',
+ 'secure_channel',
+ 'intercept_channel',
+ 'server',
'protos',
'services',
'protos_and_services',
- )
-
- six.assertCountEqual(self, expected_grpc_code_elements,
- _from_grpc_import_star.GRPC_ELEMENTS)
-
-
-class ChannelConnectivityTest(unittest.TestCase):
-
- def testChannelConnectivity(self):
- self.assertSequenceEqual((
- grpc.ChannelConnectivity.IDLE,
- grpc.ChannelConnectivity.CONNECTING,
- grpc.ChannelConnectivity.READY,
- grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- grpc.ChannelConnectivity.SHUTDOWN,
- ), tuple(grpc.ChannelConnectivity))
-
-
-class ChannelTest(unittest.TestCase):
-
- def test_secure_channel(self):
- channel_credentials = grpc.ssl_channel_credentials()
- channel = grpc.secure_channel('google.com:443', channel_credentials)
- channel.close()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ )
+
+ six.assertCountEqual(self, expected_grpc_code_elements,
+ _from_grpc_import_star.GRPC_ELEMENTS)
+
+
+class ChannelConnectivityTest(unittest.TestCase):
+
+ def testChannelConnectivity(self):
+ self.assertSequenceEqual((
+ grpc.ChannelConnectivity.IDLE,
+ grpc.ChannelConnectivity.CONNECTING,
+ grpc.ChannelConnectivity.READY,
+ grpc.ChannelConnectivity.TRANSIENT_FAILURE,
+ grpc.ChannelConnectivity.SHUTDOWN,
+ ), tuple(grpc.ChannelConnectivity))
+
+
+class ChannelTest(unittest.TestCase):
+
+ def test_secure_channel(self):
+ channel_credentials = grpc.ssl_channel_credentials()
+ channel = grpc.secure_channel('google.com:443', channel_credentials)
+ channel.close()
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_context_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_context_test.py
index 817c528237..cba350e781 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_context_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_context_test.py
@@ -1,193 +1,193 @@
-# Copyright 2017 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.
-"""Tests exposure of SSL auth context"""
-
-import pickle
-import unittest
-import logging
-
-import grpc
-from grpc import _channel
-from grpc.experimental import session_cache
-import six
-
-from tests.unit import test_common
-from tests.unit import resources
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-
-_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
-_CLIENT_IDS = (
- b'*.test.google.fr',
- b'waterzooi.test.google.be',
- b'*.test.youtube.com',
- b'192.168.1.3',
-)
-_ID = 'id'
-_ID_KEY = 'id_key'
-_AUTH_CTX = 'auth_ctx'
-
-_PRIVATE_KEY = resources.private_key()
-_CERTIFICATE_CHAIN = resources.certificate_chain()
-_TEST_ROOT_CERTIFICATES = resources.test_root_certificates()
-_SERVER_CERTS = ((_PRIVATE_KEY, _CERTIFICATE_CHAIN),)
-_PROPERTY_OPTIONS = ((
- 'grpc.ssl_target_name_override',
- _SERVER_HOST_OVERRIDE,
-),)
-
-
-def handle_unary_unary(request, servicer_context):
- return pickle.dumps({
- _ID: servicer_context.peer_identities(),
- _ID_KEY: servicer_context.peer_identity_key(),
- _AUTH_CTX: servicer_context.auth_context()
- })
-
-
-class AuthContextTest(unittest.TestCase):
-
- def testInsecure(self):
- handler = grpc.method_handlers_generic_handler('test', {
- 'UnaryUnary':
+# Copyright 2017 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.
+"""Tests exposure of SSL auth context"""
+
+import pickle
+import unittest
+import logging
+
+import grpc
+from grpc import _channel
+from grpc.experimental import session_cache
+import six
+
+from tests.unit import test_common
+from tests.unit import resources
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+
+_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
+_CLIENT_IDS = (
+ b'*.test.google.fr',
+ b'waterzooi.test.google.be',
+ b'*.test.youtube.com',
+ b'192.168.1.3',
+)
+_ID = 'id'
+_ID_KEY = 'id_key'
+_AUTH_CTX = 'auth_ctx'
+
+_PRIVATE_KEY = resources.private_key()
+_CERTIFICATE_CHAIN = resources.certificate_chain()
+_TEST_ROOT_CERTIFICATES = resources.test_root_certificates()
+_SERVER_CERTS = ((_PRIVATE_KEY, _CERTIFICATE_CHAIN),)
+_PROPERTY_OPTIONS = ((
+ 'grpc.ssl_target_name_override',
+ _SERVER_HOST_OVERRIDE,
+),)
+
+
+def handle_unary_unary(request, servicer_context):
+ return pickle.dumps({
+ _ID: servicer_context.peer_identities(),
+ _ID_KEY: servicer_context.peer_identity_key(),
+ _AUTH_CTX: servicer_context.auth_context()
+ })
+
+
+class AuthContextTest(unittest.TestCase):
+
+ def testInsecure(self):
+ handler = grpc.method_handlers_generic_handler('test', {
+ 'UnaryUnary':
grpc.unary_unary_rpc_method_handler(handle_unary_unary)
- })
- server = test_common.test_server()
- server.add_generic_rpc_handlers((handler,))
- port = server.add_insecure_port('[::]:0')
- server.start()
-
- with grpc.insecure_channel('localhost:%d' % port) as channel:
- response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- server.stop(None)
-
- auth_data = pickle.loads(response)
- self.assertIsNone(auth_data[_ID])
- self.assertIsNone(auth_data[_ID_KEY])
- self.assertDictEqual({}, auth_data[_AUTH_CTX])
-
- def testSecureNoCert(self):
- handler = grpc.method_handlers_generic_handler('test', {
- 'UnaryUnary':
+ })
+ server = test_common.test_server()
+ server.add_generic_rpc_handlers((handler,))
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+
+ with grpc.insecure_channel('localhost:%d' % port) as channel:
+ response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
+ server.stop(None)
+
+ auth_data = pickle.loads(response)
+ self.assertIsNone(auth_data[_ID])
+ self.assertIsNone(auth_data[_ID_KEY])
+ self.assertDictEqual({}, auth_data[_AUTH_CTX])
+
+ def testSecureNoCert(self):
+ handler = grpc.method_handlers_generic_handler('test', {
+ 'UnaryUnary':
grpc.unary_unary_rpc_method_handler(handle_unary_unary)
- })
- server = test_common.test_server()
- server.add_generic_rpc_handlers((handler,))
- server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
- port = server.add_secure_port('[::]:0', server_cred)
- server.start()
-
- channel_creds = grpc.ssl_channel_credentials(
- root_certificates=_TEST_ROOT_CERTIFICATES)
+ })
+ server = test_common.test_server()
+ server.add_generic_rpc_handlers((handler,))
+ server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
+ port = server.add_secure_port('[::]:0', server_cred)
+ server.start()
+
+ channel_creds = grpc.ssl_channel_credentials(
+ root_certificates=_TEST_ROOT_CERTIFICATES)
channel = grpc.secure_channel('localhost:{}'.format(port),
channel_creds,
options=_PROPERTY_OPTIONS)
- response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- channel.close()
- server.stop(None)
-
- auth_data = pickle.loads(response)
- self.assertIsNone(auth_data[_ID])
- self.assertIsNone(auth_data[_ID_KEY])
+ response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
+ channel.close()
+ server.stop(None)
+
+ auth_data = pickle.loads(response)
+ self.assertIsNone(auth_data[_ID])
+ self.assertIsNone(auth_data[_ID_KEY])
self.assertDictEqual(
{
'security_level': [b'TSI_PRIVACY_AND_INTEGRITY'],
'transport_security_type': [b'ssl'],
'ssl_session_reused': [b'false'],
}, auth_data[_AUTH_CTX])
-
- def testSecureClientCert(self):
- handler = grpc.method_handlers_generic_handler('test', {
- 'UnaryUnary':
+
+ def testSecureClientCert(self):
+ handler = grpc.method_handlers_generic_handler('test', {
+ 'UnaryUnary':
grpc.unary_unary_rpc_method_handler(handle_unary_unary)
- })
- server = test_common.test_server()
- server.add_generic_rpc_handlers((handler,))
- server_cred = grpc.ssl_server_credentials(
- _SERVER_CERTS,
- root_certificates=_TEST_ROOT_CERTIFICATES,
- require_client_auth=True)
- port = server.add_secure_port('[::]:0', server_cred)
- server.start()
-
- channel_creds = grpc.ssl_channel_credentials(
- root_certificates=_TEST_ROOT_CERTIFICATES,
- private_key=_PRIVATE_KEY,
- certificate_chain=_CERTIFICATE_CHAIN)
+ })
+ server = test_common.test_server()
+ server.add_generic_rpc_handlers((handler,))
+ server_cred = grpc.ssl_server_credentials(
+ _SERVER_CERTS,
+ root_certificates=_TEST_ROOT_CERTIFICATES,
+ require_client_auth=True)
+ port = server.add_secure_port('[::]:0', server_cred)
+ server.start()
+
+ channel_creds = grpc.ssl_channel_credentials(
+ root_certificates=_TEST_ROOT_CERTIFICATES,
+ private_key=_PRIVATE_KEY,
+ certificate_chain=_CERTIFICATE_CHAIN)
channel = grpc.secure_channel('localhost:{}'.format(port),
channel_creds,
options=_PROPERTY_OPTIONS)
-
- response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- channel.close()
- server.stop(None)
-
- auth_data = pickle.loads(response)
- auth_ctx = auth_data[_AUTH_CTX]
- six.assertCountEqual(self, _CLIENT_IDS, auth_data[_ID])
- self.assertEqual('x509_subject_alternative_name', auth_data[_ID_KEY])
- self.assertSequenceEqual([b'ssl'], auth_ctx['transport_security_type'])
- self.assertSequenceEqual([b'*.test.google.com'],
- auth_ctx['x509_common_name'])
-
- def _do_one_shot_client_rpc(self, channel_creds, channel_options, port,
- expect_ssl_session_reused):
+
+ response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
+ channel.close()
+ server.stop(None)
+
+ auth_data = pickle.loads(response)
+ auth_ctx = auth_data[_AUTH_CTX]
+ six.assertCountEqual(self, _CLIENT_IDS, auth_data[_ID])
+ self.assertEqual('x509_subject_alternative_name', auth_data[_ID_KEY])
+ self.assertSequenceEqual([b'ssl'], auth_ctx['transport_security_type'])
+ self.assertSequenceEqual([b'*.test.google.com'],
+ auth_ctx['x509_common_name'])
+
+ def _do_one_shot_client_rpc(self, channel_creds, channel_options, port,
+ expect_ssl_session_reused):
channel = grpc.secure_channel('localhost:{}'.format(port),
channel_creds,
options=channel_options)
- response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- auth_data = pickle.loads(response)
- self.assertEqual(expect_ssl_session_reused,
- auth_data[_AUTH_CTX]['ssl_session_reused'])
- channel.close()
-
- def testSessionResumption(self):
- # Set up a secure server
- handler = grpc.method_handlers_generic_handler('test', {
- 'UnaryUnary':
+ response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
+ auth_data = pickle.loads(response)
+ self.assertEqual(expect_ssl_session_reused,
+ auth_data[_AUTH_CTX]['ssl_session_reused'])
+ channel.close()
+
+ def testSessionResumption(self):
+ # Set up a secure server
+ handler = grpc.method_handlers_generic_handler('test', {
+ 'UnaryUnary':
grpc.unary_unary_rpc_method_handler(handle_unary_unary)
- })
- server = test_common.test_server()
- server.add_generic_rpc_handlers((handler,))
- server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
- port = server.add_secure_port('[::]:0', server_cred)
- server.start()
-
- # Create a cache for TLS session tickets
- cache = session_cache.ssl_session_cache_lru(1)
- channel_creds = grpc.ssl_channel_credentials(
- root_certificates=_TEST_ROOT_CERTIFICATES)
- channel_options = _PROPERTY_OPTIONS + (
- ('grpc.ssl_session_cache', cache),)
-
- # Initial connection has no session to resume
+ })
+ server = test_common.test_server()
+ server.add_generic_rpc_handlers((handler,))
+ server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
+ port = server.add_secure_port('[::]:0', server_cred)
+ server.start()
+
+ # Create a cache for TLS session tickets
+ cache = session_cache.ssl_session_cache_lru(1)
+ channel_creds = grpc.ssl_channel_credentials(
+ root_certificates=_TEST_ROOT_CERTIFICATES)
+ channel_options = _PROPERTY_OPTIONS + (
+ ('grpc.ssl_session_cache', cache),)
+
+ # Initial connection has no session to resume
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port,
expect_ssl_session_reused=[b'false'])
-
- # Subsequent connections resume sessions
+
+ # Subsequent connections resume sessions
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port,
expect_ssl_session_reused=[b'true'])
- server.stop(None)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ server.stop(None)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py
index d9df2add4f..cdeeb19ab8 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py
@@ -1,82 +1,82 @@
-# Copyright 2016 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.
-"""Tests of standard AuthMetadataPlugins."""
-
-import collections
-import threading
-import unittest
-import logging
-
-from grpc import _auth
-
-
-class MockGoogleCreds(object):
-
- def get_access_token(self):
- token = collections.namedtuple('MockAccessTokenInfo',
- ('access_token', 'expires_in'))
- token.access_token = 'token'
- return token
-
-
-class MockExceptionGoogleCreds(object):
-
- def get_access_token(self):
- raise Exception()
-
-
-class GoogleCallCredentialsTest(unittest.TestCase):
-
- def test_google_call_credentials_success(self):
- callback_event = threading.Event()
-
- def mock_callback(metadata, error):
- self.assertEqual(metadata, (('authorization', 'Bearer token'),))
- self.assertIsNone(error)
- callback_event.set()
-
- call_creds = _auth.GoogleCallCredentials(MockGoogleCreds())
- call_creds(None, mock_callback)
- self.assertTrue(callback_event.wait(1.0))
-
- def test_google_call_credentials_error(self):
- callback_event = threading.Event()
-
- def mock_callback(metadata, error):
- self.assertIsNotNone(error)
- callback_event.set()
-
- call_creds = _auth.GoogleCallCredentials(MockExceptionGoogleCreds())
- call_creds(None, mock_callback)
- self.assertTrue(callback_event.wait(1.0))
-
-
-class AccessTokenAuthMetadataPluginTest(unittest.TestCase):
-
- def test_google_call_credentials_success(self):
- callback_event = threading.Event()
-
- def mock_callback(metadata, error):
- self.assertEqual(metadata, (('authorization', 'Bearer token'),))
- self.assertIsNone(error)
- callback_event.set()
-
- metadata_plugin = _auth.AccessTokenAuthMetadataPlugin('token')
- metadata_plugin(None, mock_callback)
- self.assertTrue(callback_event.wait(1.0))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2016 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.
+"""Tests of standard AuthMetadataPlugins."""
+
+import collections
+import threading
+import unittest
+import logging
+
+from grpc import _auth
+
+
+class MockGoogleCreds(object):
+
+ def get_access_token(self):
+ token = collections.namedtuple('MockAccessTokenInfo',
+ ('access_token', 'expires_in'))
+ token.access_token = 'token'
+ return token
+
+
+class MockExceptionGoogleCreds(object):
+
+ def get_access_token(self):
+ raise Exception()
+
+
+class GoogleCallCredentialsTest(unittest.TestCase):
+
+ def test_google_call_credentials_success(self):
+ callback_event = threading.Event()
+
+ def mock_callback(metadata, error):
+ self.assertEqual(metadata, (('authorization', 'Bearer token'),))
+ self.assertIsNone(error)
+ callback_event.set()
+
+ call_creds = _auth.GoogleCallCredentials(MockGoogleCreds())
+ call_creds(None, mock_callback)
+ self.assertTrue(callback_event.wait(1.0))
+
+ def test_google_call_credentials_error(self):
+ callback_event = threading.Event()
+
+ def mock_callback(metadata, error):
+ self.assertIsNotNone(error)
+ callback_event.set()
+
+ call_creds = _auth.GoogleCallCredentials(MockExceptionGoogleCreds())
+ call_creds(None, mock_callback)
+ self.assertTrue(callback_event.wait(1.0))
+
+
+class AccessTokenAuthMetadataPluginTest(unittest.TestCase):
+
+ def test_google_call_credentials_success(self):
+ callback_event = threading.Event()
+
+ def mock_callback(metadata, error):
+ self.assertEqual(metadata, (('authorization', 'Bearer token'),))
+ self.assertIsNone(error)
+ callback_event.set()
+
+ metadata_plugin = _auth.AccessTokenAuthMetadataPlugin('token')
+ metadata_plugin(None, mock_callback)
+ self.assertTrue(callback_event.wait(1.0))
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py
index 2f2eea61db..df5a18b978 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py
@@ -1,65 +1,65 @@
-# Copyright 2016 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.
+# Copyright 2016 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.
"""Tests of channel arguments on client/server side."""
-
-from concurrent import futures
-import unittest
-import logging
-
-import grpc
-
-
-class TestPointerWrapper(object):
-
- def __int__(self):
- return 123456
-
-
-TEST_CHANNEL_ARGS = (
- ('arg1', b'bytes_val'),
- ('arg2', 'str_val'),
- ('arg3', 1),
- (b'arg4', 'str_val'),
- ('arg6', TestPointerWrapper()),
-)
-
-INVALID_TEST_CHANNEL_ARGS = [
- {
- 'foo': 'bar'
- },
- (('key',),),
- 'str',
-]
-
-
-class ChannelArgsTest(unittest.TestCase):
-
- def test_client(self):
- grpc.insecure_channel('localhost:8080', options=TEST_CHANNEL_ARGS)
-
- def test_server(self):
+
+from concurrent import futures
+import unittest
+import logging
+
+import grpc
+
+
+class TestPointerWrapper(object):
+
+ def __int__(self):
+ return 123456
+
+
+TEST_CHANNEL_ARGS = (
+ ('arg1', b'bytes_val'),
+ ('arg2', 'str_val'),
+ ('arg3', 1),
+ (b'arg4', 'str_val'),
+ ('arg6', TestPointerWrapper()),
+)
+
+INVALID_TEST_CHANNEL_ARGS = [
+ {
+ 'foo': 'bar'
+ },
+ (('key',),),
+ 'str',
+]
+
+
+class ChannelArgsTest(unittest.TestCase):
+
+ def test_client(self):
+ grpc.insecure_channel('localhost:8080', options=TEST_CHANNEL_ARGS)
+
+ def test_server(self):
grpc.server(futures.ThreadPoolExecutor(max_workers=1),
options=TEST_CHANNEL_ARGS)
-
- def test_invalid_client_args(self):
- for invalid_arg in INVALID_TEST_CHANNEL_ARGS:
+
+ def test_invalid_client_args(self):
+ for invalid_arg in INVALID_TEST_CHANNEL_ARGS:
self.assertRaises(ValueError,
grpc.insecure_channel,
'localhost:8080',
options=invalid_arg)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py
index 47f52b4890..912738eb48 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py
@@ -1,220 +1,220 @@
-# Copyright 2018 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.
-"""Tests server and client side compression."""
-
-import itertools
-import logging
-import threading
-import time
-import unittest
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_BEAT = 0.5
-_SOME_TIME = 5
-_MORE_TIME = 10
-
-_STREAM_URI = 'Meffod'
-_UNARY_URI = 'MeffodMan'
-
-
-class _StreamingMethodHandler(grpc.RpcMethodHandler):
-
- request_streaming = True
- response_streaming = True
- request_deserializer = None
- response_serializer = None
-
- def stream_stream(self, request_iterator, servicer_context):
- for request in request_iterator:
- yield request * 2
-
-
-class _UnaryMethodHandler(grpc.RpcMethodHandler):
-
- request_streaming = False
- response_streaming = False
- request_deserializer = None
- response_serializer = None
-
- def unary_unary(self, request, servicer_context):
- return request * 2
-
-
-_STREAMING_METHOD_HANDLER = _StreamingMethodHandler()
-_UNARY_METHOD_HANDLER = _UnaryMethodHandler()
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _STREAM_URI:
- return _STREAMING_METHOD_HANDLER
- else:
- return _UNARY_METHOD_HANDLER
-
-
-_GENERIC_HANDLER = _GenericHandler()
-
-
-class _Pipe(object):
-
- def __init__(self, values):
- self._condition = threading.Condition()
- self._values = list(values)
- self._open = True
-
- def __iter__(self):
- return self
-
- def _next(self):
- with self._condition:
- while not self._values and self._open:
- self._condition.wait()
- if self._values:
- return self._values.pop(0)
- else:
- raise StopIteration()
-
- def next(self):
- return self._next()
-
- def __next__(self):
- return self._next()
-
- def add(self, value):
- with self._condition:
- self._values.append(value)
- self._condition.notify()
-
- def close(self):
- with self._condition:
- self._open = False
- self._condition.notify()
-
- def __enter__(self):
- return self
-
- def __exit__(self, type, value, traceback):
- self.close()
-
-
-class ChannelCloseTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server(
- max_workers=test_constants.THREAD_CONCURRENCY)
- self._server.add_generic_rpc_handlers((_GENERIC_HANDLER,))
- self._port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- def tearDown(self):
- self._server.stop(None)
-
- def test_close_immediately_after_call_invocation(self):
- channel = grpc.insecure_channel('localhost:{}'.format(self._port))
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe(())
- response_iterator = multi_callable(request_iterator)
- channel.close()
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_close_while_call_active(self):
- channel = grpc.insecure_channel('localhost:{}'.format(self._port))
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe((b'abc',))
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- channel.close()
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_context_manager_close_while_call_active(self):
- with grpc.insecure_channel('localhost:{}'.format(
- self._port)) as channel: # pylint: disable=bad-continuation
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe((b'abc',))
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_context_manager_close_while_many_calls_active(self):
- with grpc.insecure_channel('localhost:{}'.format(
- self._port)) as channel: # pylint: disable=bad-continuation
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterators = tuple(
- _Pipe((b'abc',))
- for _ in range(test_constants.THREAD_CONCURRENCY))
- response_iterators = []
- for request_iterator in request_iterators:
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- response_iterators.append(response_iterator)
- for request_iterator in request_iterators:
- request_iterator.close()
-
- for response_iterator in response_iterators:
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_many_concurrent_closes(self):
- channel = grpc.insecure_channel('localhost:{}'.format(self._port))
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe((b'abc',))
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- start = time.time()
- end = start + _MORE_TIME
-
- def sleep_some_time_then_close():
- time.sleep(_SOME_TIME)
- channel.close()
-
- for _ in range(test_constants.THREAD_CONCURRENCY):
- close_thread = threading.Thread(target=sleep_some_time_then_close)
- close_thread.start()
- while True:
- request_iterator.add(b'def')
- time.sleep(_BEAT)
- if end < time.time():
- break
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_exception_in_callback(self):
- with grpc.insecure_channel('localhost:{}'.format(
- self._port)) as channel:
- stream_multi_callable = channel.stream_stream(_STREAM_URI)
- endless_iterator = itertools.repeat(b'abc')
- stream_response_iterator = stream_multi_callable(endless_iterator)
- future = channel.unary_unary(_UNARY_URI).future(b'abc')
-
- def on_done_callback(future):
- raise Exception("This should not cause a deadlock.")
-
- future.add_done_callback(on_done_callback)
- future.result()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2018 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.
+"""Tests server and client side compression."""
+
+import itertools
+import logging
+import threading
+import time
+import unittest
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_BEAT = 0.5
+_SOME_TIME = 5
+_MORE_TIME = 10
+
+_STREAM_URI = 'Meffod'
+_UNARY_URI = 'MeffodMan'
+
+
+class _StreamingMethodHandler(grpc.RpcMethodHandler):
+
+ request_streaming = True
+ response_streaming = True
+ request_deserializer = None
+ response_serializer = None
+
+ def stream_stream(self, request_iterator, servicer_context):
+ for request in request_iterator:
+ yield request * 2
+
+
+class _UnaryMethodHandler(grpc.RpcMethodHandler):
+
+ request_streaming = False
+ response_streaming = False
+ request_deserializer = None
+ response_serializer = None
+
+ def unary_unary(self, request, servicer_context):
+ return request * 2
+
+
+_STREAMING_METHOD_HANDLER = _StreamingMethodHandler()
+_UNARY_METHOD_HANDLER = _UnaryMethodHandler()
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _STREAM_URI:
+ return _STREAMING_METHOD_HANDLER
+ else:
+ return _UNARY_METHOD_HANDLER
+
+
+_GENERIC_HANDLER = _GenericHandler()
+
+
+class _Pipe(object):
+
+ def __init__(self, values):
+ self._condition = threading.Condition()
+ self._values = list(values)
+ self._open = True
+
+ def __iter__(self):
+ return self
+
+ def _next(self):
+ with self._condition:
+ while not self._values and self._open:
+ self._condition.wait()
+ if self._values:
+ return self._values.pop(0)
+ else:
+ raise StopIteration()
+
+ def next(self):
+ return self._next()
+
+ def __next__(self):
+ return self._next()
+
+ def add(self, value):
+ with self._condition:
+ self._values.append(value)
+ self._condition.notify()
+
+ def close(self):
+ with self._condition:
+ self._open = False
+ self._condition.notify()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+
+class ChannelCloseTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server(
+ max_workers=test_constants.THREAD_CONCURRENCY)
+ self._server.add_generic_rpc_handlers((_GENERIC_HANDLER,))
+ self._port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+
+ def tearDown(self):
+ self._server.stop(None)
+
+ def test_close_immediately_after_call_invocation(self):
+ channel = grpc.insecure_channel('localhost:{}'.format(self._port))
+ multi_callable = channel.stream_stream(_STREAM_URI)
+ request_iterator = _Pipe(())
+ response_iterator = multi_callable(request_iterator)
+ channel.close()
+ request_iterator.close()
+
+ self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
+
+ def test_close_while_call_active(self):
+ channel = grpc.insecure_channel('localhost:{}'.format(self._port))
+ multi_callable = channel.stream_stream(_STREAM_URI)
+ request_iterator = _Pipe((b'abc',))
+ response_iterator = multi_callable(request_iterator)
+ next(response_iterator)
+ channel.close()
+ request_iterator.close()
+
+ self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
+
+ def test_context_manager_close_while_call_active(self):
+ with grpc.insecure_channel('localhost:{}'.format(
+ self._port)) as channel: # pylint: disable=bad-continuation
+ multi_callable = channel.stream_stream(_STREAM_URI)
+ request_iterator = _Pipe((b'abc',))
+ response_iterator = multi_callable(request_iterator)
+ next(response_iterator)
+ request_iterator.close()
+
+ self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
+
+ def test_context_manager_close_while_many_calls_active(self):
+ with grpc.insecure_channel('localhost:{}'.format(
+ self._port)) as channel: # pylint: disable=bad-continuation
+ multi_callable = channel.stream_stream(_STREAM_URI)
+ request_iterators = tuple(
+ _Pipe((b'abc',))
+ for _ in range(test_constants.THREAD_CONCURRENCY))
+ response_iterators = []
+ for request_iterator in request_iterators:
+ response_iterator = multi_callable(request_iterator)
+ next(response_iterator)
+ response_iterators.append(response_iterator)
+ for request_iterator in request_iterators:
+ request_iterator.close()
+
+ for response_iterator in response_iterators:
+ self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
+
+ def test_many_concurrent_closes(self):
+ channel = grpc.insecure_channel('localhost:{}'.format(self._port))
+ multi_callable = channel.stream_stream(_STREAM_URI)
+ request_iterator = _Pipe((b'abc',))
+ response_iterator = multi_callable(request_iterator)
+ next(response_iterator)
+ start = time.time()
+ end = start + _MORE_TIME
+
+ def sleep_some_time_then_close():
+ time.sleep(_SOME_TIME)
+ channel.close()
+
+ for _ in range(test_constants.THREAD_CONCURRENCY):
+ close_thread = threading.Thread(target=sleep_some_time_then_close)
+ close_thread.start()
+ while True:
+ request_iterator.add(b'def')
+ time.sleep(_BEAT)
+ if end < time.time():
+ break
+ request_iterator.close()
+
+ self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
+
+ def test_exception_in_callback(self):
+ with grpc.insecure_channel('localhost:{}'.format(
+ self._port)) as channel:
+ stream_multi_callable = channel.stream_stream(_STREAM_URI)
+ endless_iterator = itertools.repeat(b'abc')
+ stream_response_iterator = stream_multi_callable(endless_iterator)
+ future = channel.unary_unary(_UNARY_URI).future(b'abc')
+
+ def on_done_callback(future):
+ raise Exception("This should not cause a deadlock.")
+
+ future.add_done_callback(on_done_callback)
+ future.result()
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py
index d1b4c3c932..d1c2c2201e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py
@@ -1,155 +1,155 @@
-# Copyright 2015 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.
-"""Tests of grpc._channel.Channel connectivity."""
-
-import logging
-import threading
-import time
-import unittest
-
-import grpc
-from tests.unit.framework.common import test_constants
-from tests.unit import thread_pool
-
-
-def _ready_in_connectivities(connectivities):
- return grpc.ChannelConnectivity.READY in connectivities
-
-
-def _last_connectivity_is_not_ready(connectivities):
- return connectivities[-1] is not grpc.ChannelConnectivity.READY
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._connectivities = []
-
- def update(self, connectivity):
- with self._condition:
- self._connectivities.append(connectivity)
- self._condition.notify()
-
- def connectivities(self):
- with self._condition:
- return tuple(self._connectivities)
-
- def block_until_connectivities_satisfy(self, predicate):
- with self._condition:
- while True:
- connectivities = tuple(self._connectivities)
- if predicate(connectivities):
- return connectivities
- else:
- self._condition.wait()
-
-
-class ChannelConnectivityTest(unittest.TestCase):
-
- def test_lonely_channel_connectivity(self):
- callback = _Callback()
-
- channel = grpc.insecure_channel('localhost:12345')
- channel.subscribe(callback.update, try_to_connect=False)
- first_connectivities = callback.block_until_connectivities_satisfy(bool)
- channel.subscribe(callback.update, try_to_connect=True)
- second_connectivities = callback.block_until_connectivities_satisfy(
- lambda connectivities: 2 <= len(connectivities))
- # Wait for a connection that will never happen.
- time.sleep(test_constants.SHORT_TIMEOUT)
- third_connectivities = callback.connectivities()
- channel.unsubscribe(callback.update)
- fourth_connectivities = callback.connectivities()
- channel.unsubscribe(callback.update)
- fifth_connectivities = callback.connectivities()
-
- channel.close()
-
- self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
- first_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, second_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, third_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, fourth_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, fifth_connectivities)
-
- def test_immediately_connectable_channel_connectivity(self):
- recording_thread_pool = thread_pool.RecordingThreadPool(
- max_workers=None)
+# Copyright 2015 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.
+"""Tests of grpc._channel.Channel connectivity."""
+
+import logging
+import threading
+import time
+import unittest
+
+import grpc
+from tests.unit.framework.common import test_constants
+from tests.unit import thread_pool
+
+
+def _ready_in_connectivities(connectivities):
+ return grpc.ChannelConnectivity.READY in connectivities
+
+
+def _last_connectivity_is_not_ready(connectivities):
+ return connectivities[-1] is not grpc.ChannelConnectivity.READY
+
+
+class _Callback(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._connectivities = []
+
+ def update(self, connectivity):
+ with self._condition:
+ self._connectivities.append(connectivity)
+ self._condition.notify()
+
+ def connectivities(self):
+ with self._condition:
+ return tuple(self._connectivities)
+
+ def block_until_connectivities_satisfy(self, predicate):
+ with self._condition:
+ while True:
+ connectivities = tuple(self._connectivities)
+ if predicate(connectivities):
+ return connectivities
+ else:
+ self._condition.wait()
+
+
+class ChannelConnectivityTest(unittest.TestCase):
+
+ def test_lonely_channel_connectivity(self):
+ callback = _Callback()
+
+ channel = grpc.insecure_channel('localhost:12345')
+ channel.subscribe(callback.update, try_to_connect=False)
+ first_connectivities = callback.block_until_connectivities_satisfy(bool)
+ channel.subscribe(callback.update, try_to_connect=True)
+ second_connectivities = callback.block_until_connectivities_satisfy(
+ lambda connectivities: 2 <= len(connectivities))
+ # Wait for a connection that will never happen.
+ time.sleep(test_constants.SHORT_TIMEOUT)
+ third_connectivities = callback.connectivities()
+ channel.unsubscribe(callback.update)
+ fourth_connectivities = callback.connectivities()
+ channel.unsubscribe(callback.update)
+ fifth_connectivities = callback.connectivities()
+
+ channel.close()
+
+ self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
+ first_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.READY, second_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.READY, third_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.READY, fourth_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.READY, fifth_connectivities)
+
+ def test_immediately_connectable_channel_connectivity(self):
+ recording_thread_pool = thread_pool.RecordingThreadPool(
+ max_workers=None)
server = grpc.server(recording_thread_pool,
options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- first_callback = _Callback()
- second_callback = _Callback()
-
- channel = grpc.insecure_channel('localhost:{}'.format(port))
- channel.subscribe(first_callback.update, try_to_connect=False)
- first_connectivities = first_callback.block_until_connectivities_satisfy(
- bool)
- # Wait for a connection that will never happen because try_to_connect=True
- # has not yet been passed.
- time.sleep(test_constants.SHORT_TIMEOUT)
- second_connectivities = first_callback.connectivities()
- channel.subscribe(second_callback.update, try_to_connect=True)
- third_connectivities = first_callback.block_until_connectivities_satisfy(
- lambda connectivities: 2 <= len(connectivities))
- fourth_connectivities = second_callback.block_until_connectivities_satisfy(
- bool)
- # Wait for a connection that will happen (or may already have happened).
- first_callback.block_until_connectivities_satisfy(
- _ready_in_connectivities)
- second_callback.block_until_connectivities_satisfy(
- _ready_in_connectivities)
- channel.close()
- server.stop(None)
-
- self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
- first_connectivities)
- self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
- second_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- third_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.SHUTDOWN,
- third_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- fourth_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.SHUTDOWN,
- fourth_connectivities)
- self.assertFalse(recording_thread_pool.was_used())
-
- def test_reachable_then_unreachable_channel_connectivity(self):
- recording_thread_pool = thread_pool.RecordingThreadPool(
- max_workers=None)
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ first_callback = _Callback()
+ second_callback = _Callback()
+
+ channel = grpc.insecure_channel('localhost:{}'.format(port))
+ channel.subscribe(first_callback.update, try_to_connect=False)
+ first_connectivities = first_callback.block_until_connectivities_satisfy(
+ bool)
+ # Wait for a connection that will never happen because try_to_connect=True
+ # has not yet been passed.
+ time.sleep(test_constants.SHORT_TIMEOUT)
+ second_connectivities = first_callback.connectivities()
+ channel.subscribe(second_callback.update, try_to_connect=True)
+ third_connectivities = first_callback.block_until_connectivities_satisfy(
+ lambda connectivities: 2 <= len(connectivities))
+ fourth_connectivities = second_callback.block_until_connectivities_satisfy(
+ bool)
+ # Wait for a connection that will happen (or may already have happened).
+ first_callback.block_until_connectivities_satisfy(
+ _ready_in_connectivities)
+ second_callback.block_until_connectivities_satisfy(
+ _ready_in_connectivities)
+ channel.close()
+ server.stop(None)
+
+ self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
+ first_connectivities)
+ self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
+ second_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.TRANSIENT_FAILURE,
+ third_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.SHUTDOWN,
+ third_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.TRANSIENT_FAILURE,
+ fourth_connectivities)
+ self.assertNotIn(grpc.ChannelConnectivity.SHUTDOWN,
+ fourth_connectivities)
+ self.assertFalse(recording_thread_pool.was_used())
+
+ def test_reachable_then_unreachable_channel_connectivity(self):
+ recording_thread_pool = thread_pool.RecordingThreadPool(
+ max_workers=None)
server = grpc.server(recording_thread_pool,
options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- callback = _Callback()
-
- channel = grpc.insecure_channel('localhost:{}'.format(port))
- channel.subscribe(callback.update, try_to_connect=True)
- callback.block_until_connectivities_satisfy(_ready_in_connectivities)
- # Now take down the server and confirm that channel readiness is repudiated.
- server.stop(None)
- callback.block_until_connectivities_satisfy(
- _last_connectivity_is_not_ready)
- channel.unsubscribe(callback.update)
- channel.close()
- self.assertFalse(recording_thread_pool.was_used())
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ callback = _Callback()
+
+ channel = grpc.insecure_channel('localhost:{}'.format(port))
+ channel.subscribe(callback.update, try_to_connect=True)
+ callback.block_until_connectivities_satisfy(_ready_in_connectivities)
+ # Now take down the server and confirm that channel readiness is repudiated.
+ server.stop(None)
+ callback.block_until_connectivities_satisfy(
+ _last_connectivity_is_not_ready)
+ channel.unsubscribe(callback.update)
+ channel.close()
+ self.assertFalse(recording_thread_pool.was_used())
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py
index ca9ebc16fe..35c8fd7ff3 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py
@@ -1,97 +1,97 @@
-# Copyright 2015 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.
-"""Tests of grpc.channel_ready_future."""
-
-import threading
-import unittest
-import logging
-
-import grpc
-from tests.unit.framework.common import test_constants
-from tests.unit import thread_pool
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
-
- def accept_value(self, value):
- with self._condition:
- self._value = value
- self._condition.notify_all()
-
- def block_until_called(self):
- with self._condition:
- while self._value is None:
- self._condition.wait()
- return self._value
-
-
-class ChannelReadyFutureTest(unittest.TestCase):
-
- def test_lonely_channel_connectivity(self):
- channel = grpc.insecure_channel('localhost:12345')
- callback = _Callback()
-
- ready_future = grpc.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- with self.assertRaises(grpc.FutureTimeoutError):
- ready_future.result(timeout=test_constants.SHORT_TIMEOUT)
- self.assertFalse(ready_future.cancelled())
- self.assertFalse(ready_future.done())
- self.assertTrue(ready_future.running())
- ready_future.cancel()
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertTrue(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
-
- channel.close()
-
- def test_immediately_connectable_channel_connectivity(self):
- recording_thread_pool = thread_pool.RecordingThreadPool(
- max_workers=None)
+# Copyright 2015 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.
+"""Tests of grpc.channel_ready_future."""
+
+import threading
+import unittest
+import logging
+
+import grpc
+from tests.unit.framework.common import test_constants
+from tests.unit import thread_pool
+
+
+class _Callback(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._value = None
+
+ def accept_value(self, value):
+ with self._condition:
+ self._value = value
+ self._condition.notify_all()
+
+ def block_until_called(self):
+ with self._condition:
+ while self._value is None:
+ self._condition.wait()
+ return self._value
+
+
+class ChannelReadyFutureTest(unittest.TestCase):
+
+ def test_lonely_channel_connectivity(self):
+ channel = grpc.insecure_channel('localhost:12345')
+ callback = _Callback()
+
+ ready_future = grpc.channel_ready_future(channel)
+ ready_future.add_done_callback(callback.accept_value)
+ with self.assertRaises(grpc.FutureTimeoutError):
+ ready_future.result(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertFalse(ready_future.cancelled())
+ self.assertFalse(ready_future.done())
+ self.assertTrue(ready_future.running())
+ ready_future.cancel()
+ value_passed_to_callback = callback.block_until_called()
+ self.assertIs(ready_future, value_passed_to_callback)
+ self.assertTrue(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+
+ channel.close()
+
+ def test_immediately_connectable_channel_connectivity(self):
+ recording_thread_pool = thread_pool.RecordingThreadPool(
+ max_workers=None)
server = grpc.server(recording_thread_pool,
options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- channel = grpc.insecure_channel('localhost:{}'.format(port))
- callback = _Callback()
-
- ready_future = grpc.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- self.assertIsNone(
- ready_future.result(timeout=test_constants.LONG_TIMEOUT))
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- # Cancellation after maturity has no effect.
- ready_future.cancel()
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- self.assertFalse(recording_thread_pool.was_used())
-
- channel.close()
- server.stop(None)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ channel = grpc.insecure_channel('localhost:{}'.format(port))
+ callback = _Callback()
+
+ ready_future = grpc.channel_ready_future(channel)
+ ready_future.add_done_callback(callback.accept_value)
+ self.assertIsNone(
+ ready_future.result(timeout=test_constants.LONG_TIMEOUT))
+ value_passed_to_callback = callback.block_until_called()
+ self.assertIs(ready_future, value_passed_to_callback)
+ self.assertFalse(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+ # Cancellation after maturity has no effect.
+ ready_future.cancel()
+ self.assertFalse(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+ self.assertFalse(recording_thread_pool.was_used())
+
+ channel.close()
+ server.stop(None)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_compression_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_compression_test.py
index bc58e1032c..c1de279a7d 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_compression_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_compression_test.py
@@ -1,382 +1,382 @@
-# Copyright 2016 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.
-"""Tests server and client side compression."""
-
-import unittest
-
-import contextlib
-from concurrent import futures
-import functools
-import itertools
-import logging
-import os
-
-import grpc
-from grpc import _grpcio_metadata
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit import _tcp_proxy
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-# Cut down on test time.
-_STREAM_LENGTH = test_constants.STREAM_LENGTH // 16
-
-_HOST = 'localhost'
-
-_REQUEST = b'\x00' * 100
-_COMPRESSION_RATIO_THRESHOLD = 0.05
-_COMPRESSION_METHODS = (
- None,
- # Disabled for test tractability.
- # grpc.Compression.NoCompression,
- # grpc.Compression.Deflate,
- grpc.Compression.Gzip,
-)
-_COMPRESSION_NAMES = {
- None: 'Uncompressed',
- grpc.Compression.NoCompression: 'NoCompression',
- grpc.Compression.Deflate: 'DeflateCompression',
- grpc.Compression.Gzip: 'GzipCompression',
-}
-
-_TEST_OPTIONS = {
- 'client_streaming': (True, False),
- 'server_streaming': (True, False),
- 'channel_compression': _COMPRESSION_METHODS,
- 'multicallable_compression': _COMPRESSION_METHODS,
- 'server_compression': _COMPRESSION_METHODS,
- 'server_call_compression': _COMPRESSION_METHODS,
-}
-
-
-def _make_handle_unary_unary(pre_response_callback):
-
- def _handle_unary(request, servicer_context):
- if pre_response_callback:
- pre_response_callback(request, servicer_context)
- return request
-
- return _handle_unary
-
-
-def _make_handle_unary_stream(pre_response_callback):
-
- def _handle_unary_stream(request, servicer_context):
- if pre_response_callback:
- pre_response_callback(request, servicer_context)
- for _ in range(_STREAM_LENGTH):
- yield request
-
- return _handle_unary_stream
-
-
-def _make_handle_stream_unary(pre_response_callback):
-
- def _handle_stream_unary(request_iterator, servicer_context):
- if pre_response_callback:
- pre_response_callback(request_iterator, servicer_context)
- response = None
- for request in request_iterator:
- if not response:
- response = request
- return response
-
- return _handle_stream_unary
-
-
-def _make_handle_stream_stream(pre_response_callback):
-
- def _handle_stream(request_iterator, servicer_context):
- # TODO(issue:#6891) We should be able to remove this loop,
- # and replace with return; yield
- for request in request_iterator:
- if pre_response_callback:
- pre_response_callback(request, servicer_context)
- yield request
-
- return _handle_stream
-
-
-def set_call_compression(compression_method, request_or_iterator,
- servicer_context):
- del request_or_iterator
- servicer_context.set_compression(compression_method)
-
-
-def disable_next_compression(request, servicer_context):
- del request
- servicer_context.disable_next_message_compression()
-
-
-def disable_first_compression(request, servicer_context):
- if int(request.decode('ascii')) == 0:
- servicer_context.disable_next_message_compression()
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming,
- pre_response_callback):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
-
- if self.request_streaming and self.response_streaming:
- self.stream_stream = _make_handle_stream_stream(
- pre_response_callback)
- elif not self.request_streaming and not self.response_streaming:
- self.unary_unary = _make_handle_unary_unary(pre_response_callback)
- elif not self.request_streaming and self.response_streaming:
- self.unary_stream = _make_handle_unary_stream(pre_response_callback)
- else:
- self.stream_unary = _make_handle_stream_unary(pre_response_callback)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, pre_response_callback):
- self._pre_response_callback = pre_response_callback
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False, self._pre_response_callback)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True, self._pre_response_callback)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False, self._pre_response_callback)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True, self._pre_response_callback)
- else:
- return None
-
-
-@contextlib.contextmanager
-def _instrumented_client_server_pair(channel_kwargs, server_kwargs,
- server_handler):
- server = grpc.server(futures.ThreadPoolExecutor(), **server_kwargs)
- server.add_generic_rpc_handlers((server_handler,))
- server_port = server.add_insecure_port('{}:0'.format(_HOST))
- server.start()
- with _tcp_proxy.TcpProxy(_HOST, _HOST, server_port) as proxy:
- proxy_port = proxy.get_port()
- with grpc.insecure_channel('{}:{}'.format(_HOST, proxy_port),
- **channel_kwargs) as client_channel:
- try:
- yield client_channel, proxy, server
- finally:
- server.stop(None)
-
-
-def _get_byte_counts(channel_kwargs, multicallable_kwargs, client_function,
- server_kwargs, server_handler, message):
- with _instrumented_client_server_pair(channel_kwargs, server_kwargs,
- server_handler) as pipeline:
- client_channel, proxy, server = pipeline
- client_function(client_channel, multicallable_kwargs, message)
- return proxy.get_byte_count()
-
-
-def _get_compression_ratios(client_function, first_channel_kwargs,
- first_multicallable_kwargs, first_server_kwargs,
- first_server_handler, second_channel_kwargs,
- second_multicallable_kwargs, second_server_kwargs,
- second_server_handler, message):
- try:
- # This test requires the byte length of each connection to be deterministic. As
- # it turns out, flow control puts bytes on the wire in a nondeterministic
- # manner. We disable it here in order to measure compression ratios
- # deterministically.
- os.environ['GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL'] = 'true'
- first_bytes_sent, first_bytes_received = _get_byte_counts(
- first_channel_kwargs, first_multicallable_kwargs, client_function,
- first_server_kwargs, first_server_handler, message)
- second_bytes_sent, second_bytes_received = _get_byte_counts(
- second_channel_kwargs, second_multicallable_kwargs, client_function,
- second_server_kwargs, second_server_handler, message)
+# Copyright 2016 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.
+"""Tests server and client side compression."""
+
+import unittest
+
+import contextlib
+from concurrent import futures
+import functools
+import itertools
+import logging
+import os
+
+import grpc
+from grpc import _grpcio_metadata
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+from tests.unit import _tcp_proxy
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+# Cut down on test time.
+_STREAM_LENGTH = test_constants.STREAM_LENGTH // 16
+
+_HOST = 'localhost'
+
+_REQUEST = b'\x00' * 100
+_COMPRESSION_RATIO_THRESHOLD = 0.05
+_COMPRESSION_METHODS = (
+ None,
+ # Disabled for test tractability.
+ # grpc.Compression.NoCompression,
+ # grpc.Compression.Deflate,
+ grpc.Compression.Gzip,
+)
+_COMPRESSION_NAMES = {
+ None: 'Uncompressed',
+ grpc.Compression.NoCompression: 'NoCompression',
+ grpc.Compression.Deflate: 'DeflateCompression',
+ grpc.Compression.Gzip: 'GzipCompression',
+}
+
+_TEST_OPTIONS = {
+ 'client_streaming': (True, False),
+ 'server_streaming': (True, False),
+ 'channel_compression': _COMPRESSION_METHODS,
+ 'multicallable_compression': _COMPRESSION_METHODS,
+ 'server_compression': _COMPRESSION_METHODS,
+ 'server_call_compression': _COMPRESSION_METHODS,
+}
+
+
+def _make_handle_unary_unary(pre_response_callback):
+
+ def _handle_unary(request, servicer_context):
+ if pre_response_callback:
+ pre_response_callback(request, servicer_context)
+ return request
+
+ return _handle_unary
+
+
+def _make_handle_unary_stream(pre_response_callback):
+
+ def _handle_unary_stream(request, servicer_context):
+ if pre_response_callback:
+ pre_response_callback(request, servicer_context)
+ for _ in range(_STREAM_LENGTH):
+ yield request
+
+ return _handle_unary_stream
+
+
+def _make_handle_stream_unary(pre_response_callback):
+
+ def _handle_stream_unary(request_iterator, servicer_context):
+ if pre_response_callback:
+ pre_response_callback(request_iterator, servicer_context)
+ response = None
+ for request in request_iterator:
+ if not response:
+ response = request
+ return response
+
+ return _handle_stream_unary
+
+
+def _make_handle_stream_stream(pre_response_callback):
+
+ def _handle_stream(request_iterator, servicer_context):
+ # TODO(issue:#6891) We should be able to remove this loop,
+ # and replace with return; yield
+ for request in request_iterator:
+ if pre_response_callback:
+ pre_response_callback(request, servicer_context)
+ yield request
+
+ return _handle_stream
+
+
+def set_call_compression(compression_method, request_or_iterator,
+ servicer_context):
+ del request_or_iterator
+ servicer_context.set_compression(compression_method)
+
+
+def disable_next_compression(request, servicer_context):
+ del request
+ servicer_context.disable_next_message_compression()
+
+
+def disable_first_compression(request, servicer_context):
+ if int(request.decode('ascii')) == 0:
+ servicer_context.disable_next_message_compression()
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, request_streaming, response_streaming,
+ pre_response_callback):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_unary = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+
+ if self.request_streaming and self.response_streaming:
+ self.stream_stream = _make_handle_stream_stream(
+ pre_response_callback)
+ elif not self.request_streaming and not self.response_streaming:
+ self.unary_unary = _make_handle_unary_unary(pre_response_callback)
+ elif not self.request_streaming and self.response_streaming:
+ self.unary_stream = _make_handle_unary_stream(pre_response_callback)
+ else:
+ self.stream_unary = _make_handle_stream_unary(pre_response_callback)
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, pre_response_callback):
+ self._pre_response_callback = pre_response_callback
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(False, False, self._pre_response_callback)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(False, True, self._pre_response_callback)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(True, False, self._pre_response_callback)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(True, True, self._pre_response_callback)
+ else:
+ return None
+
+
+@contextlib.contextmanager
+def _instrumented_client_server_pair(channel_kwargs, server_kwargs,
+ server_handler):
+ server = grpc.server(futures.ThreadPoolExecutor(), **server_kwargs)
+ server.add_generic_rpc_handlers((server_handler,))
+ server_port = server.add_insecure_port('{}:0'.format(_HOST))
+ server.start()
+ with _tcp_proxy.TcpProxy(_HOST, _HOST, server_port) as proxy:
+ proxy_port = proxy.get_port()
+ with grpc.insecure_channel('{}:{}'.format(_HOST, proxy_port),
+ **channel_kwargs) as client_channel:
+ try:
+ yield client_channel, proxy, server
+ finally:
+ server.stop(None)
+
+
+def _get_byte_counts(channel_kwargs, multicallable_kwargs, client_function,
+ server_kwargs, server_handler, message):
+ with _instrumented_client_server_pair(channel_kwargs, server_kwargs,
+ server_handler) as pipeline:
+ client_channel, proxy, server = pipeline
+ client_function(client_channel, multicallable_kwargs, message)
+ return proxy.get_byte_count()
+
+
+def _get_compression_ratios(client_function, first_channel_kwargs,
+ first_multicallable_kwargs, first_server_kwargs,
+ first_server_handler, second_channel_kwargs,
+ second_multicallable_kwargs, second_server_kwargs,
+ second_server_handler, message):
+ try:
+ # This test requires the byte length of each connection to be deterministic. As
+ # it turns out, flow control puts bytes on the wire in a nondeterministic
+ # manner. We disable it here in order to measure compression ratios
+ # deterministically.
+ os.environ['GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL'] = 'true'
+ first_bytes_sent, first_bytes_received = _get_byte_counts(
+ first_channel_kwargs, first_multicallable_kwargs, client_function,
+ first_server_kwargs, first_server_handler, message)
+ second_bytes_sent, second_bytes_received = _get_byte_counts(
+ second_channel_kwargs, second_multicallable_kwargs, client_function,
+ second_server_kwargs, second_server_handler, message)
return ((second_bytes_sent - first_bytes_sent) /
float(first_bytes_sent),
- (second_bytes_received - first_bytes_received) /
- float(first_bytes_received))
- finally:
- del os.environ['GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL']
-
-
-def _unary_unary_client(channel, multicallable_kwargs, message):
- multi_callable = channel.unary_unary(_UNARY_UNARY)
- response = multi_callable(message, **multicallable_kwargs)
- if response != message:
- raise RuntimeError("Request '{}' != Response '{}'".format(
- message, response))
-
-
-def _unary_stream_client(channel, multicallable_kwargs, message):
- multi_callable = channel.unary_stream(_UNARY_STREAM)
- response_iterator = multi_callable(message, **multicallable_kwargs)
- for response in response_iterator:
- if response != message:
- raise RuntimeError("Request '{}' != Response '{}'".format(
- message, response))
-
-
-def _stream_unary_client(channel, multicallable_kwargs, message):
- multi_callable = channel.stream_unary(_STREAM_UNARY)
- requests = (_REQUEST for _ in range(_STREAM_LENGTH))
- response = multi_callable(requests, **multicallable_kwargs)
- if response != message:
- raise RuntimeError("Request '{}' != Response '{}'".format(
- message, response))
-
-
-def _stream_stream_client(channel, multicallable_kwargs, message):
- multi_callable = channel.stream_stream(_STREAM_STREAM)
- request_prefix = str(0).encode('ascii') * 100
- requests = (
- request_prefix + str(i).encode('ascii') for i in range(_STREAM_LENGTH))
- response_iterator = multi_callable(requests, **multicallable_kwargs)
- for i, response in enumerate(response_iterator):
- if int(response.decode('ascii')) != i:
- raise RuntimeError("Request '{}' != Response '{}'".format(
- i, response))
-
-
-class CompressionTest(unittest.TestCase):
-
- def assertCompressed(self, compression_ratio):
- self.assertLess(
- compression_ratio,
- -1.0 * _COMPRESSION_RATIO_THRESHOLD,
- msg='Actual compression ratio: {}'.format(compression_ratio))
-
- def assertNotCompressed(self, compression_ratio):
- self.assertGreaterEqual(
- compression_ratio,
- -1.0 * _COMPRESSION_RATIO_THRESHOLD,
- msg='Actual compession ratio: {}'.format(compression_ratio))
-
+ (second_bytes_received - first_bytes_received) /
+ float(first_bytes_received))
+ finally:
+ del os.environ['GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL']
+
+
+def _unary_unary_client(channel, multicallable_kwargs, message):
+ multi_callable = channel.unary_unary(_UNARY_UNARY)
+ response = multi_callable(message, **multicallable_kwargs)
+ if response != message:
+ raise RuntimeError("Request '{}' != Response '{}'".format(
+ message, response))
+
+
+def _unary_stream_client(channel, multicallable_kwargs, message):
+ multi_callable = channel.unary_stream(_UNARY_STREAM)
+ response_iterator = multi_callable(message, **multicallable_kwargs)
+ for response in response_iterator:
+ if response != message:
+ raise RuntimeError("Request '{}' != Response '{}'".format(
+ message, response))
+
+
+def _stream_unary_client(channel, multicallable_kwargs, message):
+ multi_callable = channel.stream_unary(_STREAM_UNARY)
+ requests = (_REQUEST for _ in range(_STREAM_LENGTH))
+ response = multi_callable(requests, **multicallable_kwargs)
+ if response != message:
+ raise RuntimeError("Request '{}' != Response '{}'".format(
+ message, response))
+
+
+def _stream_stream_client(channel, multicallable_kwargs, message):
+ multi_callable = channel.stream_stream(_STREAM_STREAM)
+ request_prefix = str(0).encode('ascii') * 100
+ requests = (
+ request_prefix + str(i).encode('ascii') for i in range(_STREAM_LENGTH))
+ response_iterator = multi_callable(requests, **multicallable_kwargs)
+ for i, response in enumerate(response_iterator):
+ if int(response.decode('ascii')) != i:
+ raise RuntimeError("Request '{}' != Response '{}'".format(
+ i, response))
+
+
+class CompressionTest(unittest.TestCase):
+
+ def assertCompressed(self, compression_ratio):
+ self.assertLess(
+ compression_ratio,
+ -1.0 * _COMPRESSION_RATIO_THRESHOLD,
+ msg='Actual compression ratio: {}'.format(compression_ratio))
+
+ def assertNotCompressed(self, compression_ratio):
+ self.assertGreaterEqual(
+ compression_ratio,
+ -1.0 * _COMPRESSION_RATIO_THRESHOLD,
+ msg='Actual compession ratio: {}'.format(compression_ratio))
+
def assertConfigurationCompressed(self, client_streaming, server_streaming,
channel_compression,
multicallable_compression,
server_compression,
server_call_compression):
- client_side_compressed = channel_compression or multicallable_compression
- server_side_compressed = server_compression or server_call_compression
- channel_kwargs = {
- 'compression': channel_compression,
- } if channel_compression else {}
- multicallable_kwargs = {
- 'compression': multicallable_compression,
- } if multicallable_compression else {}
-
- client_function = None
- if not client_streaming and not server_streaming:
- client_function = _unary_unary_client
- elif not client_streaming and server_streaming:
- client_function = _unary_stream_client
- elif client_streaming and not server_streaming:
- client_function = _stream_unary_client
- else:
- client_function = _stream_stream_client
-
- server_kwargs = {
- 'compression': server_compression,
- } if server_compression else {}
- server_handler = _GenericHandler(
- functools.partial(set_call_compression, grpc.Compression.Gzip)
- ) if server_call_compression else _GenericHandler(None)
- sent_ratio, received_ratio = _get_compression_ratios(
- client_function, {}, {}, {}, _GenericHandler(None), channel_kwargs,
- multicallable_kwargs, server_kwargs, server_handler, _REQUEST)
-
- if client_side_compressed:
- self.assertCompressed(sent_ratio)
- else:
- self.assertNotCompressed(sent_ratio)
-
- if server_side_compressed:
- self.assertCompressed(received_ratio)
- else:
- self.assertNotCompressed(received_ratio)
-
- def testDisableNextCompressionStreaming(self):
- server_kwargs = {
- 'compression': grpc.Compression.Deflate,
- }
- _, received_ratio = _get_compression_ratios(
- _stream_stream_client, {}, {}, {}, _GenericHandler(None), {}, {},
- server_kwargs, _GenericHandler(disable_next_compression), _REQUEST)
- self.assertNotCompressed(received_ratio)
-
- def testDisableNextCompressionStreamingResets(self):
- server_kwargs = {
- 'compression': grpc.Compression.Deflate,
- }
- _, received_ratio = _get_compression_ratios(
- _stream_stream_client, {}, {}, {}, _GenericHandler(None), {}, {},
- server_kwargs, _GenericHandler(disable_first_compression), _REQUEST)
- self.assertCompressed(received_ratio)
-
-
-def _get_compression_str(name, value):
- return '{}{}'.format(name, _COMPRESSION_NAMES[value])
-
-
-def _get_compression_test_name(client_streaming, server_streaming,
- channel_compression, multicallable_compression,
- server_compression, server_call_compression):
- client_arity = 'Stream' if client_streaming else 'Unary'
- server_arity = 'Stream' if server_streaming else 'Unary'
- arity = '{}{}'.format(client_arity, server_arity)
- channel_compression_str = _get_compression_str('Channel',
- channel_compression)
- multicallable_compression_str = _get_compression_str(
- 'Multicallable', multicallable_compression)
- server_compression_str = _get_compression_str('Server', server_compression)
- server_call_compression_str = _get_compression_str('ServerCall',
- server_call_compression)
+ client_side_compressed = channel_compression or multicallable_compression
+ server_side_compressed = server_compression or server_call_compression
+ channel_kwargs = {
+ 'compression': channel_compression,
+ } if channel_compression else {}
+ multicallable_kwargs = {
+ 'compression': multicallable_compression,
+ } if multicallable_compression else {}
+
+ client_function = None
+ if not client_streaming and not server_streaming:
+ client_function = _unary_unary_client
+ elif not client_streaming and server_streaming:
+ client_function = _unary_stream_client
+ elif client_streaming and not server_streaming:
+ client_function = _stream_unary_client
+ else:
+ client_function = _stream_stream_client
+
+ server_kwargs = {
+ 'compression': server_compression,
+ } if server_compression else {}
+ server_handler = _GenericHandler(
+ functools.partial(set_call_compression, grpc.Compression.Gzip)
+ ) if server_call_compression else _GenericHandler(None)
+ sent_ratio, received_ratio = _get_compression_ratios(
+ client_function, {}, {}, {}, _GenericHandler(None), channel_kwargs,
+ multicallable_kwargs, server_kwargs, server_handler, _REQUEST)
+
+ if client_side_compressed:
+ self.assertCompressed(sent_ratio)
+ else:
+ self.assertNotCompressed(sent_ratio)
+
+ if server_side_compressed:
+ self.assertCompressed(received_ratio)
+ else:
+ self.assertNotCompressed(received_ratio)
+
+ def testDisableNextCompressionStreaming(self):
+ server_kwargs = {
+ 'compression': grpc.Compression.Deflate,
+ }
+ _, received_ratio = _get_compression_ratios(
+ _stream_stream_client, {}, {}, {}, _GenericHandler(None), {}, {},
+ server_kwargs, _GenericHandler(disable_next_compression), _REQUEST)
+ self.assertNotCompressed(received_ratio)
+
+ def testDisableNextCompressionStreamingResets(self):
+ server_kwargs = {
+ 'compression': grpc.Compression.Deflate,
+ }
+ _, received_ratio = _get_compression_ratios(
+ _stream_stream_client, {}, {}, {}, _GenericHandler(None), {}, {},
+ server_kwargs, _GenericHandler(disable_first_compression), _REQUEST)
+ self.assertCompressed(received_ratio)
+
+
+def _get_compression_str(name, value):
+ return '{}{}'.format(name, _COMPRESSION_NAMES[value])
+
+
+def _get_compression_test_name(client_streaming, server_streaming,
+ channel_compression, multicallable_compression,
+ server_compression, server_call_compression):
+ client_arity = 'Stream' if client_streaming else 'Unary'
+ server_arity = 'Stream' if server_streaming else 'Unary'
+ arity = '{}{}'.format(client_arity, server_arity)
+ channel_compression_str = _get_compression_str('Channel',
+ channel_compression)
+ multicallable_compression_str = _get_compression_str(
+ 'Multicallable', multicallable_compression)
+ server_compression_str = _get_compression_str('Server', server_compression)
+ server_call_compression_str = _get_compression_str('ServerCall',
+ server_call_compression)
return 'test{}{}{}{}{}'.format(arity, channel_compression_str,
multicallable_compression_str,
server_compression_str,
server_call_compression_str)
-
-
-def _test_options():
- for test_parameters in itertools.product(*_TEST_OPTIONS.values()):
- yield dict(zip(_TEST_OPTIONS.keys(), test_parameters))
-
-
-for options in _test_options():
-
- def test_compression(**kwargs):
-
- def _test_compression(self):
- self.assertConfigurationCompressed(**kwargs)
-
- return _test_compression
-
- setattr(CompressionTest, _get_compression_test_name(**options),
- test_compression(**options))
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+
+def _test_options():
+ for test_parameters in itertools.product(*_TEST_OPTIONS.values()):
+ yield dict(zip(_TEST_OPTIONS.keys(), test_parameters))
+
+
+for options in _test_options():
+
+ def test_compression(**kwargs):
+
+ def _test_compression(self):
+ self.assertConfigurationCompressed(**kwargs)
+
+ return _test_compression
+
+ setattr(CompressionTest, _get_compression_test_name(**options),
+ test_compression(**options))
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py
index 187a6f0388..cf44ed464a 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py
@@ -1,70 +1,70 @@
-# Copyright 2016 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.
-"""Tests of credentials."""
-
-import unittest
-import logging
-import six
-
-import grpc
-
-
-class CredentialsTest(unittest.TestCase):
-
- def test_call_credentials_composition(self):
- first = grpc.access_token_call_credentials('abc')
- second = grpc.access_token_call_credentials('def')
- third = grpc.access_token_call_credentials('ghi')
-
- first_and_second = grpc.composite_call_credentials(first, second)
- first_second_and_third = grpc.composite_call_credentials(
- first, second, third)
-
- self.assertIsInstance(first_and_second, grpc.CallCredentials)
- self.assertIsInstance(first_second_and_third, grpc.CallCredentials)
-
- def test_channel_credentials_composition(self):
- first_call_credentials = grpc.access_token_call_credentials('abc')
- second_call_credentials = grpc.access_token_call_credentials('def')
- third_call_credentials = grpc.access_token_call_credentials('ghi')
- channel_credentials = grpc.ssl_channel_credentials()
-
- channel_and_first = grpc.composite_channel_credentials(
- channel_credentials, first_call_credentials)
- channel_first_and_second = grpc.composite_channel_credentials(
- channel_credentials, first_call_credentials,
- second_call_credentials)
- channel_first_second_and_third = grpc.composite_channel_credentials(
- channel_credentials, first_call_credentials,
- second_call_credentials, third_call_credentials)
-
- self.assertIsInstance(channel_and_first, grpc.ChannelCredentials)
- self.assertIsInstance(channel_first_and_second, grpc.ChannelCredentials)
- self.assertIsInstance(channel_first_second_and_third,
- grpc.ChannelCredentials)
-
- @unittest.skipIf(six.PY2, 'only invalid in Python3')
- def test_invalid_string_certificate(self):
- self.assertRaises(
- TypeError,
- grpc.ssl_channel_credentials,
- root_certificates='A Certificate',
- private_key=None,
- certificate_chain=None,
- )
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2016 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.
+"""Tests of credentials."""
+
+import unittest
+import logging
+import six
+
+import grpc
+
+
+class CredentialsTest(unittest.TestCase):
+
+ def test_call_credentials_composition(self):
+ first = grpc.access_token_call_credentials('abc')
+ second = grpc.access_token_call_credentials('def')
+ third = grpc.access_token_call_credentials('ghi')
+
+ first_and_second = grpc.composite_call_credentials(first, second)
+ first_second_and_third = grpc.composite_call_credentials(
+ first, second, third)
+
+ self.assertIsInstance(first_and_second, grpc.CallCredentials)
+ self.assertIsInstance(first_second_and_third, grpc.CallCredentials)
+
+ def test_channel_credentials_composition(self):
+ first_call_credentials = grpc.access_token_call_credentials('abc')
+ second_call_credentials = grpc.access_token_call_credentials('def')
+ third_call_credentials = grpc.access_token_call_credentials('ghi')
+ channel_credentials = grpc.ssl_channel_credentials()
+
+ channel_and_first = grpc.composite_channel_credentials(
+ channel_credentials, first_call_credentials)
+ channel_first_and_second = grpc.composite_channel_credentials(
+ channel_credentials, first_call_credentials,
+ second_call_credentials)
+ channel_first_second_and_third = grpc.composite_channel_credentials(
+ channel_credentials, first_call_credentials,
+ second_call_credentials, third_call_credentials)
+
+ self.assertIsInstance(channel_and_first, grpc.ChannelCredentials)
+ self.assertIsInstance(channel_first_and_second, grpc.ChannelCredentials)
+ self.assertIsInstance(channel_first_second_and_third,
+ grpc.ChannelCredentials)
+
+ @unittest.skipIf(six.PY2, 'only invalid in Python3')
+ def test_invalid_string_certificate(self):
+ self.assertRaises(
+ TypeError,
+ grpc.ssl_channel_credentials,
+ root_certificates='A Certificate',
+ private_key=None,
+ certificate_chain=None,
+ )
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py
index 5fb4f3c3cf..dc985eebb4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 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.
+# Copyright 2015 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py
index b279f3d07c..478f56ad2f 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py
@@ -1,223 +1,223 @@
-# Copyright 2016 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.
-"""Test making many calls and immediately cancelling most of them."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-from grpc.framework.foundation import logging_pool
-from tests.unit.framework.common import test_constants
-from tests.unit._cython import test_utilities
-
-_EMPTY_FLAGS = 0
-_EMPTY_METADATA = ()
-
-_SERVER_SHUTDOWN_TAG = 'server_shutdown'
-_REQUEST_CALL_TAG = 'request_call'
-_RECEIVE_CLOSE_ON_SERVER_TAG = 'receive_close_on_server'
-_RECEIVE_MESSAGE_TAG = 'receive_message'
-_SERVER_COMPLETE_CALL_TAG = 'server_complete_call'
-
-_SUCCESS_CALL_FRACTION = 1.0 / 8.0
-_SUCCESSFUL_CALLS = int(test_constants.RPC_CONCURRENCY * _SUCCESS_CALL_FRACTION)
-_UNSUCCESSFUL_CALLS = test_constants.RPC_CONCURRENCY - _SUCCESSFUL_CALLS
-
-
-class _State(object):
-
- def __init__(self):
- self.condition = threading.Condition()
- self.handlers_released = False
- self.parked_handlers = 0
- self.handled_rpcs = 0
-
-
-def _is_cancellation_event(event):
- return (event.tag is _RECEIVE_CLOSE_ON_SERVER_TAG and
- event.batch_operations[0].cancelled())
-
-
-class _Handler(object):
-
- def __init__(self, state, completion_queue, rpc_event):
- self._state = state
- self._lock = threading.Lock()
- self._completion_queue = completion_queue
- self._call = rpc_event.call
-
- def __call__(self):
- with self._state.condition:
- self._state.parked_handlers += 1
- if self._state.parked_handlers == test_constants.THREAD_CONCURRENCY:
- self._state.condition.notify_all()
- while not self._state.handlers_released:
- self._state.condition.wait()
-
- with self._lock:
- self._call.start_server_batch(
- (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
- _RECEIVE_CLOSE_ON_SERVER_TAG)
- self._call.start_server_batch(
- (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
- _RECEIVE_MESSAGE_TAG)
- first_event = self._completion_queue.poll()
- if _is_cancellation_event(first_event):
- self._completion_queue.poll()
- else:
- with self._lock:
- operations = (
- cygrpc.SendInitialMetadataOperation(_EMPTY_METADATA,
- _EMPTY_FLAGS),
- cygrpc.SendMessageOperation(b'\x79\x57', _EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- _EMPTY_METADATA, cygrpc.StatusCode.ok, b'test details!',
- _EMPTY_FLAGS),
- )
- self._call.start_server_batch(operations,
- _SERVER_COMPLETE_CALL_TAG)
- self._completion_queue.poll()
- self._completion_queue.poll()
-
-
-def _serve(state, server, server_completion_queue, thread_pool):
- for _ in range(test_constants.RPC_CONCURRENCY):
- call_completion_queue = cygrpc.CompletionQueue()
- server.request_call(call_completion_queue, server_completion_queue,
- _REQUEST_CALL_TAG)
- rpc_event = server_completion_queue.poll()
- thread_pool.submit(_Handler(state, call_completion_queue, rpc_event))
- with state.condition:
- state.handled_rpcs += 1
- if test_constants.RPC_CONCURRENCY <= state.handled_rpcs:
- state.condition.notify_all()
- server_completion_queue.poll()
-
-
-class _QueueDriver(object):
-
- def __init__(self, condition, completion_queue, due):
- self._condition = condition
- self._completion_queue = completion_queue
- self._due = due
- self._events = []
- self._returned = False
-
- def start(self):
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events.append(event)
- self._due.remove(event.tag)
- self._condition.notify_all()
- if not self._due:
- self._returned = True
- return
-
- thread = threading.Thread(target=in_thread)
- thread.start()
-
- def events(self, at_least):
- with self._condition:
- while len(self._events) < at_least:
- self._condition.wait()
- return tuple(self._events)
-
-
-class CancelManyCallsTest(unittest.TestCase):
-
- def testCancelManyCalls(self):
- server_thread_pool = logging_pool.pool(
- test_constants.THREAD_CONCURRENCY)
-
- server_completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server([
- (
- b'grpc.so_reuseport',
- 0,
- ),
- ])
- server.register_completion_queue(server_completion_queue)
- port = server.add_http2_port(b'[::]:0')
- server.start()
- channel = cygrpc.Channel('localhost:{}'.format(port).encode(), None,
- None)
-
- state = _State()
-
- server_thread_args = (
- state,
- server,
- server_completion_queue,
- server_thread_pool,
- )
- server_thread = threading.Thread(target=_serve, args=server_thread_args)
- server_thread.start()
-
- client_condition = threading.Condition()
- client_due = set()
-
- with client_condition:
- client_calls = []
- for index in range(test_constants.RPC_CONCURRENCY):
- tag = 'client_complete_call_{0:04d}_tag'.format(index)
- client_call = channel.integrated_call(
- _EMPTY_FLAGS, b'/twinkies', None, None, _EMPTY_METADATA,
- None, ((
- (
- cygrpc.SendInitialMetadataOperation(
- _EMPTY_METADATA, _EMPTY_FLAGS),
- cygrpc.SendMessageOperation(b'\x45\x56',
- _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(
- _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ),
- tag,
- ),))
- client_due.add(tag)
- client_calls.append(client_call)
-
+# Copyright 2016 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.
+"""Test making many calls and immediately cancelling most of them."""
+
+import threading
+import unittest
+
+from grpc._cython import cygrpc
+from grpc.framework.foundation import logging_pool
+from tests.unit.framework.common import test_constants
+from tests.unit._cython import test_utilities
+
+_EMPTY_FLAGS = 0
+_EMPTY_METADATA = ()
+
+_SERVER_SHUTDOWN_TAG = 'server_shutdown'
+_REQUEST_CALL_TAG = 'request_call'
+_RECEIVE_CLOSE_ON_SERVER_TAG = 'receive_close_on_server'
+_RECEIVE_MESSAGE_TAG = 'receive_message'
+_SERVER_COMPLETE_CALL_TAG = 'server_complete_call'
+
+_SUCCESS_CALL_FRACTION = 1.0 / 8.0
+_SUCCESSFUL_CALLS = int(test_constants.RPC_CONCURRENCY * _SUCCESS_CALL_FRACTION)
+_UNSUCCESSFUL_CALLS = test_constants.RPC_CONCURRENCY - _SUCCESSFUL_CALLS
+
+
+class _State(object):
+
+ def __init__(self):
+ self.condition = threading.Condition()
+ self.handlers_released = False
+ self.parked_handlers = 0
+ self.handled_rpcs = 0
+
+
+def _is_cancellation_event(event):
+ return (event.tag is _RECEIVE_CLOSE_ON_SERVER_TAG and
+ event.batch_operations[0].cancelled())
+
+
+class _Handler(object):
+
+ def __init__(self, state, completion_queue, rpc_event):
+ self._state = state
+ self._lock = threading.Lock()
+ self._completion_queue = completion_queue
+ self._call = rpc_event.call
+
+ def __call__(self):
+ with self._state.condition:
+ self._state.parked_handlers += 1
+ if self._state.parked_handlers == test_constants.THREAD_CONCURRENCY:
+ self._state.condition.notify_all()
+ while not self._state.handlers_released:
+ self._state.condition.wait()
+
+ with self._lock:
+ self._call.start_server_batch(
+ (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
+ _RECEIVE_CLOSE_ON_SERVER_TAG)
+ self._call.start_server_batch(
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+ _RECEIVE_MESSAGE_TAG)
+ first_event = self._completion_queue.poll()
+ if _is_cancellation_event(first_event):
+ self._completion_queue.poll()
+ else:
+ with self._lock:
+ operations = (
+ cygrpc.SendInitialMetadataOperation(_EMPTY_METADATA,
+ _EMPTY_FLAGS),
+ cygrpc.SendMessageOperation(b'\x79\x57', _EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(
+ _EMPTY_METADATA, cygrpc.StatusCode.ok, b'test details!',
+ _EMPTY_FLAGS),
+ )
+ self._call.start_server_batch(operations,
+ _SERVER_COMPLETE_CALL_TAG)
+ self._completion_queue.poll()
+ self._completion_queue.poll()
+
+
+def _serve(state, server, server_completion_queue, thread_pool):
+ for _ in range(test_constants.RPC_CONCURRENCY):
+ call_completion_queue = cygrpc.CompletionQueue()
+ server.request_call(call_completion_queue, server_completion_queue,
+ _REQUEST_CALL_TAG)
+ rpc_event = server_completion_queue.poll()
+ thread_pool.submit(_Handler(state, call_completion_queue, rpc_event))
+ with state.condition:
+ state.handled_rpcs += 1
+ if test_constants.RPC_CONCURRENCY <= state.handled_rpcs:
+ state.condition.notify_all()
+ server_completion_queue.poll()
+
+
+class _QueueDriver(object):
+
+ def __init__(self, condition, completion_queue, due):
+ self._condition = condition
+ self._completion_queue = completion_queue
+ self._due = due
+ self._events = []
+ self._returned = False
+
+ def start(self):
+
+ def in_thread():
+ while True:
+ event = self._completion_queue.poll()
+ with self._condition:
+ self._events.append(event)
+ self._due.remove(event.tag)
+ self._condition.notify_all()
+ if not self._due:
+ self._returned = True
+ return
+
+ thread = threading.Thread(target=in_thread)
+ thread.start()
+
+ def events(self, at_least):
+ with self._condition:
+ while len(self._events) < at_least:
+ self._condition.wait()
+ return tuple(self._events)
+
+
+class CancelManyCallsTest(unittest.TestCase):
+
+ def testCancelManyCalls(self):
+ server_thread_pool = logging_pool.pool(
+ test_constants.THREAD_CONCURRENCY)
+
+ server_completion_queue = cygrpc.CompletionQueue()
+ server = cygrpc.Server([
+ (
+ b'grpc.so_reuseport',
+ 0,
+ ),
+ ])
+ server.register_completion_queue(server_completion_queue)
+ port = server.add_http2_port(b'[::]:0')
+ server.start()
+ channel = cygrpc.Channel('localhost:{}'.format(port).encode(), None,
+ None)
+
+ state = _State()
+
+ server_thread_args = (
+ state,
+ server,
+ server_completion_queue,
+ server_thread_pool,
+ )
+ server_thread = threading.Thread(target=_serve, args=server_thread_args)
+ server_thread.start()
+
+ client_condition = threading.Condition()
+ client_due = set()
+
+ with client_condition:
+ client_calls = []
+ for index in range(test_constants.RPC_CONCURRENCY):
+ tag = 'client_complete_call_{0:04d}_tag'.format(index)
+ client_call = channel.integrated_call(
+ _EMPTY_FLAGS, b'/twinkies', None, None, _EMPTY_METADATA,
+ None, ((
+ (
+ cygrpc.SendInitialMetadataOperation(
+ _EMPTY_METADATA, _EMPTY_FLAGS),
+ cygrpc.SendMessageOperation(b'\x45\x56',
+ _EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveInitialMetadataOperation(
+ _EMPTY_FLAGS),
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ ),
+ tag,
+ ),))
+ client_due.add(tag)
+ client_calls.append(client_call)
+
client_events_future = test_utilities.SimpleFuture(lambda: tuple(
channel.next_call_event() for _ in range(_SUCCESSFUL_CALLS)))
-
- with state.condition:
- while True:
- if state.parked_handlers < test_constants.THREAD_CONCURRENCY:
- state.condition.wait()
- elif state.handled_rpcs < test_constants.RPC_CONCURRENCY:
- state.condition.wait()
- else:
- state.handlers_released = True
- state.condition.notify_all()
- break
-
- client_events_future.result()
- with client_condition:
- for client_call in client_calls:
- client_call.cancel(cygrpc.StatusCode.cancelled, 'Cancelled!')
- for _ in range(_UNSUCCESSFUL_CALLS):
- channel.next_call_event()
-
- channel.close(cygrpc.StatusCode.unknown, 'Cancelled on channel close!')
- with state.condition:
- server.shutdown(server_completion_queue, _SERVER_SHUTDOWN_TAG)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+
+ with state.condition:
+ while True:
+ if state.parked_handlers < test_constants.THREAD_CONCURRENCY:
+ state.condition.wait()
+ elif state.handled_rpcs < test_constants.RPC_CONCURRENCY:
+ state.condition.wait()
+ else:
+ state.handlers_released = True
+ state.condition.notify_all()
+ break
+
+ client_events_future.result()
+ with client_condition:
+ for client_call in client_calls:
+ client_call.cancel(cygrpc.StatusCode.cancelled, 'Cancelled!')
+ for _ in range(_UNSUCCESSFUL_CALLS):
+ channel.next_call_event()
+
+ channel.close(cygrpc.StatusCode.unknown, 'Cancelled on channel close!')
+ with state.condition:
+ server.shutdown(server_completion_queue, _SERVER_SHUTDOWN_TAG)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py
index 54f620523e..67d352df6e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py
@@ -1,70 +1,70 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import time
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit.framework.common import test_constants
-
-
-def _channel():
- return cygrpc.Channel(b'localhost:54321', (), None)
-
-
-def _connectivity_loop(channel):
- for _ in range(100):
- connectivity = channel.check_connectivity_state(True)
- channel.watch_connectivity_state(connectivity, time.time() + 0.2)
-
-
-def _create_loop_destroy():
- channel = _channel()
- _connectivity_loop(channel)
- channel.close(cygrpc.StatusCode.ok, 'Channel close!')
-
-
-def _in_parallel(behavior, arguments):
- threads = tuple(
- threading.Thread(target=behavior, args=arguments)
- for _ in range(test_constants.THREAD_CONCURRENCY))
- for thread in threads:
- thread.start()
- for thread in threads:
- thread.join()
-
-
-class ChannelTest(unittest.TestCase):
-
- def test_single_channel_lonely_connectivity(self):
- channel = _channel()
- _connectivity_loop(channel)
- channel.close(cygrpc.StatusCode.ok, 'Channel close!')
-
- def test_multiple_channels_lonely_connectivity(self):
- _in_parallel(_create_loop_destroy, ())
-
- def test_negative_deadline_connectivity(self):
- channel = _channel()
- connectivity = channel.check_connectivity_state(True)
- channel.watch_connectivity_state(connectivity, -3.14)
- channel.close(cygrpc.StatusCode.ok, 'Channel close!')
- # NOTE(lidiz) The negative timeout should not trigger SIGABRT.
- # Bug report: https://github.com/grpc/grpc/issues/18244
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import time
+import threading
+import unittest
+
+from grpc._cython import cygrpc
+
+from tests.unit.framework.common import test_constants
+
+
+def _channel():
+ return cygrpc.Channel(b'localhost:54321', (), None)
+
+
+def _connectivity_loop(channel):
+ for _ in range(100):
+ connectivity = channel.check_connectivity_state(True)
+ channel.watch_connectivity_state(connectivity, time.time() + 0.2)
+
+
+def _create_loop_destroy():
+ channel = _channel()
+ _connectivity_loop(channel)
+ channel.close(cygrpc.StatusCode.ok, 'Channel close!')
+
+
+def _in_parallel(behavior, arguments):
+ threads = tuple(
+ threading.Thread(target=behavior, args=arguments)
+ for _ in range(test_constants.THREAD_CONCURRENCY))
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+
+class ChannelTest(unittest.TestCase):
+
+ def test_single_channel_lonely_connectivity(self):
+ channel = _channel()
+ _connectivity_loop(channel)
+ channel.close(cygrpc.StatusCode.ok, 'Channel close!')
+
+ def test_multiple_channels_lonely_connectivity(self):
+ _in_parallel(_create_loop_destroy, ())
+
+ def test_negative_deadline_connectivity(self):
+ channel = _channel()
+ connectivity = channel.check_connectivity_state(True)
+ channel.watch_connectivity_state(connectivity, -3.14)
+ channel.close(cygrpc.StatusCode.ok, 'Channel close!')
+ # NOTE(lidiz) The negative timeout should not trigger SIGABRT.
+ # Bug report: https://github.com/grpc/grpc/issues/18244
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py
index d8210f36f8..23813ba2ee 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py
@@ -1,123 +1,123 @@
-# Copyright 2017 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.
-"""Common utilities for tests of the Cython layer of gRPC Python."""
-
-import collections
-import threading
-
-from grpc._cython import cygrpc
-
-RPC_COUNT = 4000
-
-EMPTY_FLAGS = 0
-
-INVOCATION_METADATA = (
- ('client-md-key', 'client-md-key'),
- ('client-md-key-bin', b'\x00\x01' * 3000),
-)
-
-INITIAL_METADATA = (
- ('server-initial-md-key', 'server-initial-md-value'),
- ('server-initial-md-key-bin', b'\x00\x02' * 3000),
-)
-
-TRAILING_METADATA = (
- ('server-trailing-md-key', 'server-trailing-md-value'),
- ('server-trailing-md-key-bin', b'\x00\x03' * 3000),
-)
-
-
-class QueueDriver(object):
-
- def __init__(self, condition, completion_queue):
- self._condition = condition
- self._completion_queue = completion_queue
- self._due = collections.defaultdict(int)
- self._events = collections.defaultdict(list)
-
- def add_due(self, tags):
- if not self._due:
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events[event.tag].append(event)
- self._due[event.tag] -= 1
- self._condition.notify_all()
- if self._due[event.tag] <= 0:
- self._due.pop(event.tag)
- if not self._due:
- return
-
- thread = threading.Thread(target=in_thread)
- thread.start()
- for tag in tags:
- self._due[tag] += 1
-
- def event_with_tag(self, tag):
- with self._condition:
- while True:
- if self._events[tag]:
- return self._events[tag].pop(0)
- else:
- self._condition.wait()
-
-
-def execute_many_times(behavior):
- return tuple(behavior() for _ in range(RPC_COUNT))
-
-
-class OperationResult(
- collections.namedtuple('OperationResult', (
- 'start_batch_result',
- 'completion_type',
- 'success',
- ))):
- pass
-
-
-SUCCESSFUL_OPERATION_RESULT = OperationResult(
- cygrpc.CallError.ok, cygrpc.CompletionType.operation_complete, True)
-
-
-class RpcTest(object):
-
- def setUp(self):
- self.server_completion_queue = cygrpc.CompletionQueue()
- self.server = cygrpc.Server([(b'grpc.so_reuseport', 0)])
- self.server.register_completion_queue(self.server_completion_queue)
- port = self.server.add_http2_port(b'[::]:0')
- self.server.start()
- self.channel = cygrpc.Channel('localhost:{}'.format(port).encode(), [],
- None)
-
- self._server_shutdown_tag = 'server_shutdown_tag'
- self.server_condition = threading.Condition()
- self.server_driver = QueueDriver(self.server_condition,
- self.server_completion_queue)
- with self.server_condition:
- self.server_driver.add_due({
- self._server_shutdown_tag,
- })
-
- self.client_condition = threading.Condition()
- self.client_completion_queue = cygrpc.CompletionQueue()
- self.client_driver = QueueDriver(self.client_condition,
- self.client_completion_queue)
-
- def tearDown(self):
- self.server.shutdown(self.server_completion_queue,
- self._server_shutdown_tag)
- self.server.cancel_all_calls()
+# Copyright 2017 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.
+"""Common utilities for tests of the Cython layer of gRPC Python."""
+
+import collections
+import threading
+
+from grpc._cython import cygrpc
+
+RPC_COUNT = 4000
+
+EMPTY_FLAGS = 0
+
+INVOCATION_METADATA = (
+ ('client-md-key', 'client-md-key'),
+ ('client-md-key-bin', b'\x00\x01' * 3000),
+)
+
+INITIAL_METADATA = (
+ ('server-initial-md-key', 'server-initial-md-value'),
+ ('server-initial-md-key-bin', b'\x00\x02' * 3000),
+)
+
+TRAILING_METADATA = (
+ ('server-trailing-md-key', 'server-trailing-md-value'),
+ ('server-trailing-md-key-bin', b'\x00\x03' * 3000),
+)
+
+
+class QueueDriver(object):
+
+ def __init__(self, condition, completion_queue):
+ self._condition = condition
+ self._completion_queue = completion_queue
+ self._due = collections.defaultdict(int)
+ self._events = collections.defaultdict(list)
+
+ def add_due(self, tags):
+ if not self._due:
+
+ def in_thread():
+ while True:
+ event = self._completion_queue.poll()
+ with self._condition:
+ self._events[event.tag].append(event)
+ self._due[event.tag] -= 1
+ self._condition.notify_all()
+ if self._due[event.tag] <= 0:
+ self._due.pop(event.tag)
+ if not self._due:
+ return
+
+ thread = threading.Thread(target=in_thread)
+ thread.start()
+ for tag in tags:
+ self._due[tag] += 1
+
+ def event_with_tag(self, tag):
+ with self._condition:
+ while True:
+ if self._events[tag]:
+ return self._events[tag].pop(0)
+ else:
+ self._condition.wait()
+
+
+def execute_many_times(behavior):
+ return tuple(behavior() for _ in range(RPC_COUNT))
+
+
+class OperationResult(
+ collections.namedtuple('OperationResult', (
+ 'start_batch_result',
+ 'completion_type',
+ 'success',
+ ))):
+ pass
+
+
+SUCCESSFUL_OPERATION_RESULT = OperationResult(
+ cygrpc.CallError.ok, cygrpc.CompletionType.operation_complete, True)
+
+
+class RpcTest(object):
+
+ def setUp(self):
+ self.server_completion_queue = cygrpc.CompletionQueue()
+ self.server = cygrpc.Server([(b'grpc.so_reuseport', 0)])
+ self.server.register_completion_queue(self.server_completion_queue)
+ port = self.server.add_http2_port(b'[::]:0')
+ self.server.start()
+ self.channel = cygrpc.Channel('localhost:{}'.format(port).encode(), [],
+ None)
+
+ self._server_shutdown_tag = 'server_shutdown_tag'
+ self.server_condition = threading.Condition()
+ self.server_driver = QueueDriver(self.server_condition,
+ self.server_completion_queue)
+ with self.server_condition:
+ self.server_driver.add_due({
+ self._server_shutdown_tag,
+ })
+
+ self.client_condition = threading.Condition()
+ self.client_completion_queue = cygrpc.CompletionQueue()
+ self.client_driver = QueueDriver(self.client_condition,
+ self.client_completion_queue)
+
+ def tearDown(self):
+ self.server.shutdown(self.server_completion_queue,
+ self._server_shutdown_tag)
+ self.server.cancel_all_calls()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py
index 5a5dedd5f2..37a0bf1d92 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py
@@ -1,72 +1,72 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import os
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-
-def _get_number_active_threads():
- return cygrpc._fork_state.active_thread_count._num_active_threads
-
-
-@unittest.skipIf(os.name == 'nt', 'Posix-specific tests')
-class ForkPosixTester(unittest.TestCase):
-
- def setUp(self):
- self._saved_fork_support_flag = cygrpc._GRPC_ENABLE_FORK_SUPPORT
- cygrpc._GRPC_ENABLE_FORK_SUPPORT = True
-
- def testForkManagedThread(self):
-
- def cb():
- self.assertEqual(1, _get_number_active_threads())
-
- thread = cygrpc.ForkManagedThread(cb)
- thread.start()
- thread.join()
- self.assertEqual(0, _get_number_active_threads())
-
- def testForkManagedThreadThrowsException(self):
-
- def cb():
- self.assertEqual(1, _get_number_active_threads())
- raise Exception("expected exception")
-
- thread = cygrpc.ForkManagedThread(cb)
- thread.start()
- thread.join()
- self.assertEqual(0, _get_number_active_threads())
-
- def tearDown(self):
- cygrpc._GRPC_ENABLE_FORK_SUPPORT = self._saved_fork_support_flag
-
-
-@unittest.skipUnless(os.name == 'nt', 'Windows-specific tests')
-class ForkWindowsTester(unittest.TestCase):
-
- def testForkManagedThreadIsNoOp(self):
-
- def cb():
- pass
-
- thread = cygrpc.ForkManagedThread(cb)
- thread.start()
- thread.join()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2018 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import threading
+import unittest
+
+from grpc._cython import cygrpc
+
+
+def _get_number_active_threads():
+ return cygrpc._fork_state.active_thread_count._num_active_threads
+
+
+@unittest.skipIf(os.name == 'nt', 'Posix-specific tests')
+class ForkPosixTester(unittest.TestCase):
+
+ def setUp(self):
+ self._saved_fork_support_flag = cygrpc._GRPC_ENABLE_FORK_SUPPORT
+ cygrpc._GRPC_ENABLE_FORK_SUPPORT = True
+
+ def testForkManagedThread(self):
+
+ def cb():
+ self.assertEqual(1, _get_number_active_threads())
+
+ thread = cygrpc.ForkManagedThread(cb)
+ thread.start()
+ thread.join()
+ self.assertEqual(0, _get_number_active_threads())
+
+ def testForkManagedThreadThrowsException(self):
+
+ def cb():
+ self.assertEqual(1, _get_number_active_threads())
+ raise Exception("expected exception")
+
+ thread = cygrpc.ForkManagedThread(cb)
+ thread.start()
+ thread.join()
+ self.assertEqual(0, _get_number_active_threads())
+
+ def tearDown(self):
+ cygrpc._GRPC_ENABLE_FORK_SUPPORT = self._saved_fork_support_flag
+
+
+@unittest.skipUnless(os.name == 'nt', 'Windows-specific tests')
+class ForkWindowsTester(unittest.TestCase):
+
+ def testForkManagedThreadIsNoOp(self):
+
+ def cb():
+ pass
+
+ thread = cygrpc.ForkManagedThread(cb)
+ thread.start()
+ thread.join()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
index 144a2fcae3..b09c9d61a9 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
@@ -1,132 +1,132 @@
-# Copyright 2017 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.
-"""Test a corner-case at the level of the Cython API."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit._cython import _common
-from tests.unit._cython import test_utilities
-
-
-class Test(_common.RpcTest, unittest.TestCase):
-
- def _do_rpcs(self):
- server_call_condition = threading.Condition()
- server_call_completion_queue = cygrpc.CompletionQueue()
- server_call_driver = _common.QueueDriver(server_call_condition,
- server_call_completion_queue)
-
- server_request_call_tag = 'server_request_call_tag'
- server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
- server_complete_rpc_tag = 'server_complete_rpc_tag'
-
- with self.server_condition:
- server_request_call_start_batch_result = self.server.request_call(
- server_call_completion_queue, self.server_completion_queue,
- server_request_call_tag)
- self.server_driver.add_due({
- server_request_call_tag,
- })
-
- client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
- client_complete_rpc_tag = 'client_complete_rpc_tag'
- client_call = self.channel.integrated_call(
- _common.EMPTY_FLAGS, b'/twinkies', None, None,
- _common.INVOCATION_METADATA, None, [(
- [
- cygrpc.ReceiveInitialMetadataOperation(_common.EMPTY_FLAGS),
- ],
- client_receive_initial_metadata_tag,
- )])
- client_call.operate([
- cygrpc.SendInitialMetadataOperation(_common.INVOCATION_METADATA,
- _common.EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_common.EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_common.EMPTY_FLAGS),
- ], client_complete_rpc_tag)
-
+# Copyright 2017 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.
+"""Test a corner-case at the level of the Cython API."""
+
+import threading
+import unittest
+
+from grpc._cython import cygrpc
+
+from tests.unit._cython import _common
+from tests.unit._cython import test_utilities
+
+
+class Test(_common.RpcTest, unittest.TestCase):
+
+ def _do_rpcs(self):
+ server_call_condition = threading.Condition()
+ server_call_completion_queue = cygrpc.CompletionQueue()
+ server_call_driver = _common.QueueDriver(server_call_condition,
+ server_call_completion_queue)
+
+ server_request_call_tag = 'server_request_call_tag'
+ server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
+ server_complete_rpc_tag = 'server_complete_rpc_tag'
+
+ with self.server_condition:
+ server_request_call_start_batch_result = self.server.request_call(
+ server_call_completion_queue, self.server_completion_queue,
+ server_request_call_tag)
+ self.server_driver.add_due({
+ server_request_call_tag,
+ })
+
+ client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
+ client_complete_rpc_tag = 'client_complete_rpc_tag'
+ client_call = self.channel.integrated_call(
+ _common.EMPTY_FLAGS, b'/twinkies', None, None,
+ _common.INVOCATION_METADATA, None, [(
+ [
+ cygrpc.ReceiveInitialMetadataOperation(_common.EMPTY_FLAGS),
+ ],
+ client_receive_initial_metadata_tag,
+ )])
+ client_call.operate([
+ cygrpc.SendInitialMetadataOperation(_common.INVOCATION_METADATA,
+ _common.EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_common.EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_common.EMPTY_FLAGS),
+ ], client_complete_rpc_tag)
+
client_events_future = test_utilities.SimpleFuture(lambda: [
self.channel.next_call_event(),
self.channel.next_call_event(),
])
-
- server_request_call_event = self.server_driver.event_with_tag(
- server_request_call_tag)
-
- with server_call_condition:
- server_send_initial_metadata_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(
- _common.INITIAL_METADATA, _common.EMPTY_FLAGS),
- ], server_send_initial_metadata_tag))
- server_call_driver.add_due({
- server_send_initial_metadata_tag,
- })
- server_send_initial_metadata_event = server_call_driver.event_with_tag(
- server_send_initial_metadata_tag)
-
- with server_call_condition:
- server_complete_rpc_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.ReceiveCloseOnServerOperation(_common.EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- _common.TRAILING_METADATA, cygrpc.StatusCode.ok,
- b'test details', _common.EMPTY_FLAGS),
- ], server_complete_rpc_tag))
- server_call_driver.add_due({
- server_complete_rpc_tag,
- })
- server_complete_rpc_event = server_call_driver.event_with_tag(
- server_complete_rpc_tag)
-
- client_events = client_events_future.result()
- if client_events[0].tag is client_receive_initial_metadata_tag:
- client_receive_initial_metadata_event = client_events[0]
- client_complete_rpc_event = client_events[1]
- else:
- client_complete_rpc_event = client_events[0]
- client_receive_initial_metadata_event = client_events[1]
-
- return (
- _common.OperationResult(server_request_call_start_batch_result,
- server_request_call_event.completion_type,
- server_request_call_event.success),
- _common.OperationResult(
- cygrpc.CallError.ok,
- client_receive_initial_metadata_event.completion_type,
- client_receive_initial_metadata_event.success),
- _common.OperationResult(cygrpc.CallError.ok,
- client_complete_rpc_event.completion_type,
- client_complete_rpc_event.success),
- _common.OperationResult(
- server_send_initial_metadata_start_batch_result,
- server_send_initial_metadata_event.completion_type,
- server_send_initial_metadata_event.success),
- _common.OperationResult(server_complete_rpc_start_batch_result,
- server_complete_rpc_event.completion_type,
- server_complete_rpc_event.success),
- )
-
- def test_rpcs(self):
+
+ server_request_call_event = self.server_driver.event_with_tag(
+ server_request_call_tag)
+
+ with server_call_condition:
+ server_send_initial_metadata_start_batch_result = (
+ server_request_call_event.call.start_server_batch([
+ cygrpc.SendInitialMetadataOperation(
+ _common.INITIAL_METADATA, _common.EMPTY_FLAGS),
+ ], server_send_initial_metadata_tag))
+ server_call_driver.add_due({
+ server_send_initial_metadata_tag,
+ })
+ server_send_initial_metadata_event = server_call_driver.event_with_tag(
+ server_send_initial_metadata_tag)
+
+ with server_call_condition:
+ server_complete_rpc_start_batch_result = (
+ server_request_call_event.call.start_server_batch([
+ cygrpc.ReceiveCloseOnServerOperation(_common.EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(
+ _common.TRAILING_METADATA, cygrpc.StatusCode.ok,
+ b'test details', _common.EMPTY_FLAGS),
+ ], server_complete_rpc_tag))
+ server_call_driver.add_due({
+ server_complete_rpc_tag,
+ })
+ server_complete_rpc_event = server_call_driver.event_with_tag(
+ server_complete_rpc_tag)
+
+ client_events = client_events_future.result()
+ if client_events[0].tag is client_receive_initial_metadata_tag:
+ client_receive_initial_metadata_event = client_events[0]
+ client_complete_rpc_event = client_events[1]
+ else:
+ client_complete_rpc_event = client_events[0]
+ client_receive_initial_metadata_event = client_events[1]
+
+ return (
+ _common.OperationResult(server_request_call_start_batch_result,
+ server_request_call_event.completion_type,
+ server_request_call_event.success),
+ _common.OperationResult(
+ cygrpc.CallError.ok,
+ client_receive_initial_metadata_event.completion_type,
+ client_receive_initial_metadata_event.success),
+ _common.OperationResult(cygrpc.CallError.ok,
+ client_complete_rpc_event.completion_type,
+ client_complete_rpc_event.success),
+ _common.OperationResult(
+ server_send_initial_metadata_start_batch_result,
+ server_send_initial_metadata_event.completion_type,
+ server_send_initial_metadata_event.success),
+ _common.OperationResult(server_complete_rpc_start_batch_result,
+ server_complete_rpc_event.completion_type,
+ server_complete_rpc_event.success),
+ )
+
+ def test_rpcs(self):
expecteds = [(_common.SUCCESSFUL_OPERATION_RESULT,) * 5
] * _common.RPC_COUNT
- actuallys = _common.execute_many_times(self._do_rpcs)
- self.assertSequenceEqual(expecteds, actuallys)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ actuallys = _common.execute_many_times(self._do_rpcs)
+ self.assertSequenceEqual(expecteds, actuallys)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
index 38964768db..c586c340a2 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
@@ -1,126 +1,126 @@
-# Copyright 2017 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.
-"""Test a corner-case at the level of the Cython API."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit._cython import _common
-from tests.unit._cython import test_utilities
-
-
-class Test(_common.RpcTest, unittest.TestCase):
-
- def _do_rpcs(self):
- server_request_call_tag = 'server_request_call_tag'
- server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
- server_complete_rpc_tag = 'server_complete_rpc_tag'
-
- with self.server_condition:
- server_request_call_start_batch_result = self.server.request_call(
- self.server_completion_queue, self.server_completion_queue,
- server_request_call_tag)
- self.server_driver.add_due({
- server_request_call_tag,
- })
-
- client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
- client_complete_rpc_tag = 'client_complete_rpc_tag'
- client_call = self.channel.integrated_call(
- _common.EMPTY_FLAGS, b'/twinkies', None, None,
- _common.INVOCATION_METADATA, None, [
- (
- [
- cygrpc.SendInitialMetadataOperation(
- _common.INVOCATION_METADATA, _common.EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(
- _common.EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(
- _common.EMPTY_FLAGS),
- ],
- client_complete_rpc_tag,
- ),
- ])
- client_call.operate([
- cygrpc.ReceiveInitialMetadataOperation(_common.EMPTY_FLAGS),
- ], client_receive_initial_metadata_tag)
-
+# Copyright 2017 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.
+"""Test a corner-case at the level of the Cython API."""
+
+import threading
+import unittest
+
+from grpc._cython import cygrpc
+
+from tests.unit._cython import _common
+from tests.unit._cython import test_utilities
+
+
+class Test(_common.RpcTest, unittest.TestCase):
+
+ def _do_rpcs(self):
+ server_request_call_tag = 'server_request_call_tag'
+ server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
+ server_complete_rpc_tag = 'server_complete_rpc_tag'
+
+ with self.server_condition:
+ server_request_call_start_batch_result = self.server.request_call(
+ self.server_completion_queue, self.server_completion_queue,
+ server_request_call_tag)
+ self.server_driver.add_due({
+ server_request_call_tag,
+ })
+
+ client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
+ client_complete_rpc_tag = 'client_complete_rpc_tag'
+ client_call = self.channel.integrated_call(
+ _common.EMPTY_FLAGS, b'/twinkies', None, None,
+ _common.INVOCATION_METADATA, None, [
+ (
+ [
+ cygrpc.SendInitialMetadataOperation(
+ _common.INVOCATION_METADATA, _common.EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(
+ _common.EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(
+ _common.EMPTY_FLAGS),
+ ],
+ client_complete_rpc_tag,
+ ),
+ ])
+ client_call.operate([
+ cygrpc.ReceiveInitialMetadataOperation(_common.EMPTY_FLAGS),
+ ], client_receive_initial_metadata_tag)
+
client_events_future = test_utilities.SimpleFuture(lambda: [
self.channel.next_call_event(),
self.channel.next_call_event(),
])
- server_request_call_event = self.server_driver.event_with_tag(
- server_request_call_tag)
-
- with self.server_condition:
- server_send_initial_metadata_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(
- _common.INITIAL_METADATA, _common.EMPTY_FLAGS),
- ], server_send_initial_metadata_tag))
- self.server_driver.add_due({
- server_send_initial_metadata_tag,
- })
- server_send_initial_metadata_event = self.server_driver.event_with_tag(
- server_send_initial_metadata_tag)
-
- with self.server_condition:
- server_complete_rpc_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.ReceiveCloseOnServerOperation(_common.EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- _common.TRAILING_METADATA, cygrpc.StatusCode.ok,
- 'test details', _common.EMPTY_FLAGS),
- ], server_complete_rpc_tag))
- self.server_driver.add_due({
- server_complete_rpc_tag,
- })
- server_complete_rpc_event = self.server_driver.event_with_tag(
- server_complete_rpc_tag)
-
- client_events = client_events_future.result()
- client_receive_initial_metadata_event = client_events[0]
- client_complete_rpc_event = client_events[1]
-
- return (
- _common.OperationResult(server_request_call_start_batch_result,
- server_request_call_event.completion_type,
- server_request_call_event.success),
- _common.OperationResult(
- cygrpc.CallError.ok,
- client_receive_initial_metadata_event.completion_type,
- client_receive_initial_metadata_event.success),
- _common.OperationResult(cygrpc.CallError.ok,
- client_complete_rpc_event.completion_type,
- client_complete_rpc_event.success),
- _common.OperationResult(
- server_send_initial_metadata_start_batch_result,
- server_send_initial_metadata_event.completion_type,
- server_send_initial_metadata_event.success),
- _common.OperationResult(server_complete_rpc_start_batch_result,
- server_complete_rpc_event.completion_type,
- server_complete_rpc_event.success),
- )
-
- def test_rpcs(self):
+ server_request_call_event = self.server_driver.event_with_tag(
+ server_request_call_tag)
+
+ with self.server_condition:
+ server_send_initial_metadata_start_batch_result = (
+ server_request_call_event.call.start_server_batch([
+ cygrpc.SendInitialMetadataOperation(
+ _common.INITIAL_METADATA, _common.EMPTY_FLAGS),
+ ], server_send_initial_metadata_tag))
+ self.server_driver.add_due({
+ server_send_initial_metadata_tag,
+ })
+ server_send_initial_metadata_event = self.server_driver.event_with_tag(
+ server_send_initial_metadata_tag)
+
+ with self.server_condition:
+ server_complete_rpc_start_batch_result = (
+ server_request_call_event.call.start_server_batch([
+ cygrpc.ReceiveCloseOnServerOperation(_common.EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(
+ _common.TRAILING_METADATA, cygrpc.StatusCode.ok,
+ 'test details', _common.EMPTY_FLAGS),
+ ], server_complete_rpc_tag))
+ self.server_driver.add_due({
+ server_complete_rpc_tag,
+ })
+ server_complete_rpc_event = self.server_driver.event_with_tag(
+ server_complete_rpc_tag)
+
+ client_events = client_events_future.result()
+ client_receive_initial_metadata_event = client_events[0]
+ client_complete_rpc_event = client_events[1]
+
+ return (
+ _common.OperationResult(server_request_call_start_batch_result,
+ server_request_call_event.completion_type,
+ server_request_call_event.success),
+ _common.OperationResult(
+ cygrpc.CallError.ok,
+ client_receive_initial_metadata_event.completion_type,
+ client_receive_initial_metadata_event.success),
+ _common.OperationResult(cygrpc.CallError.ok,
+ client_complete_rpc_event.completion_type,
+ client_complete_rpc_event.success),
+ _common.OperationResult(
+ server_send_initial_metadata_start_batch_result,
+ server_send_initial_metadata_event.completion_type,
+ server_send_initial_metadata_event.success),
+ _common.OperationResult(server_complete_rpc_start_batch_result,
+ server_complete_rpc_event.completion_type,
+ server_complete_rpc_event.success),
+ )
+
+ def test_rpcs(self):
expecteds = [(_common.SUCCESSFUL_OPERATION_RESULT,) * 5
] * _common.RPC_COUNT
- actuallys = _common.execute_many_times(self._do_rpcs)
- self.assertSequenceEqual(expecteds, actuallys)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ actuallys = _common.execute_many_times(self._do_rpcs)
+ self.assertSequenceEqual(expecteds, actuallys)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py
index 8a903bfaf9..efd047c9ad 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py
@@ -1,240 +1,240 @@
-# Copyright 2016 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.
-"""Test a corner-case at the level of the Cython API."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-from tests.unit._cython import test_utilities
-
-_EMPTY_FLAGS = 0
-_EMPTY_METADATA = ()
-
-
-class _ServerDriver(object):
-
- def __init__(self, completion_queue, shutdown_tag):
- self._condition = threading.Condition()
- self._completion_queue = completion_queue
- self._shutdown_tag = shutdown_tag
- self._events = []
- self._saw_shutdown_tag = False
-
- def start(self):
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events.append(event)
- self._condition.notify()
- if event.tag is self._shutdown_tag:
- self._saw_shutdown_tag = True
- break
-
- thread = threading.Thread(target=in_thread)
- thread.start()
-
- def done(self):
- with self._condition:
- return self._saw_shutdown_tag
-
- def first_event(self):
- with self._condition:
- while not self._events:
- self._condition.wait()
- return self._events[0]
-
- def events(self):
- with self._condition:
- while not self._saw_shutdown_tag:
- self._condition.wait()
- return tuple(self._events)
-
-
-class _QueueDriver(object):
-
- def __init__(self, condition, completion_queue, due):
- self._condition = condition
- self._completion_queue = completion_queue
- self._due = due
- self._events = []
- self._returned = False
-
- def start(self):
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events.append(event)
- self._due.remove(event.tag)
- self._condition.notify_all()
- if not self._due:
- self._returned = True
- return
-
- thread = threading.Thread(target=in_thread)
- thread.start()
-
- def done(self):
- with self._condition:
- return self._returned
-
- def event_with_tag(self, tag):
- with self._condition:
- while True:
- for event in self._events:
- if event.tag is tag:
- return event
- self._condition.wait()
-
- def events(self):
- with self._condition:
- while not self._returned:
- self._condition.wait()
- return tuple(self._events)
-
-
-class ReadSomeButNotAllResponsesTest(unittest.TestCase):
-
- def testReadSomeButNotAllResponses(self):
- server_completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server([(
- b'grpc.so_reuseport',
- 0,
- )])
- server.register_completion_queue(server_completion_queue)
- port = server.add_http2_port(b'[::]:0')
- server.start()
- channel = cygrpc.Channel('localhost:{}'.format(port).encode(), set(),
- None)
-
- server_shutdown_tag = 'server_shutdown_tag'
- server_driver = _ServerDriver(server_completion_queue,
- server_shutdown_tag)
- server_driver.start()
-
- client_condition = threading.Condition()
- client_due = set()
-
- server_call_condition = threading.Condition()
- server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
- server_send_first_message_tag = 'server_send_first_message_tag'
- server_send_second_message_tag = 'server_send_second_message_tag'
- server_complete_rpc_tag = 'server_complete_rpc_tag'
- server_call_due = set((
- server_send_initial_metadata_tag,
- server_send_first_message_tag,
- server_send_second_message_tag,
- server_complete_rpc_tag,
- ))
- server_call_completion_queue = cygrpc.CompletionQueue()
- server_call_driver = _QueueDriver(server_call_condition,
- server_call_completion_queue,
- server_call_due)
- server_call_driver.start()
-
- server_rpc_tag = 'server_rpc_tag'
- request_call_result = server.request_call(server_call_completion_queue,
- server_completion_queue,
- server_rpc_tag)
-
- client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
- client_complete_rpc_tag = 'client_complete_rpc_tag'
- client_call = channel.segregated_call(
- _EMPTY_FLAGS, b'/twinkies', None, None, _EMPTY_METADATA, None, (
- (
- [
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- ],
- client_receive_initial_metadata_tag,
- ),
- (
- [
- cygrpc.SendInitialMetadataOperation(
- _EMPTY_METADATA, _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ],
- client_complete_rpc_tag,
- ),
- ))
- client_receive_initial_metadata_event_future = test_utilities.SimpleFuture(
- client_call.next_event)
-
- server_rpc_event = server_driver.first_event()
-
- with server_call_condition:
- server_send_initial_metadata_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(_EMPTY_METADATA,
- _EMPTY_FLAGS),
- ], server_send_initial_metadata_tag))
- server_send_first_message_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.SendMessageOperation(b'\x07', _EMPTY_FLAGS),
- ], server_send_first_message_tag))
- server_send_initial_metadata_event = server_call_driver.event_with_tag(
- server_send_initial_metadata_tag)
- server_send_first_message_event = server_call_driver.event_with_tag(
- server_send_first_message_tag)
- with server_call_condition:
- server_send_second_message_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.SendMessageOperation(b'\x07', _EMPTY_FLAGS),
- ], server_send_second_message_tag))
- server_complete_rpc_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- (), cygrpc.StatusCode.ok, b'test details',
- _EMPTY_FLAGS),
- ], server_complete_rpc_tag))
- server_send_second_message_event = server_call_driver.event_with_tag(
- server_send_second_message_tag)
- server_complete_rpc_event = server_call_driver.event_with_tag(
- server_complete_rpc_tag)
- server_call_driver.events()
-
- client_recieve_initial_metadata_event = client_receive_initial_metadata_event_future.result(
- )
-
- client_receive_first_message_tag = 'client_receive_first_message_tag'
- client_call.operate([
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- ], client_receive_first_message_tag)
- client_receive_first_message_event = client_call.next_event()
-
- client_call_cancel_result = client_call.cancel(
- cygrpc.StatusCode.cancelled, 'Cancelled during test!')
- client_complete_rpc_event = client_call.next_event()
-
- channel.close(cygrpc.StatusCode.unknown, 'Channel closed!')
- server.shutdown(server_completion_queue, server_shutdown_tag)
- server.cancel_all_calls()
- server_driver.events()
-
- self.assertEqual(cygrpc.CallError.ok, request_call_result)
- self.assertEqual(cygrpc.CallError.ok,
- server_send_initial_metadata_start_batch_result)
- self.assertIs(server_rpc_tag, server_rpc_event.tag)
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- server_rpc_event.completion_type)
- self.assertIsInstance(server_rpc_event.call, cygrpc.Call)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2016 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.
+"""Test a corner-case at the level of the Cython API."""
+
+import threading
+import unittest
+
+from grpc._cython import cygrpc
+from tests.unit._cython import test_utilities
+
+_EMPTY_FLAGS = 0
+_EMPTY_METADATA = ()
+
+
+class _ServerDriver(object):
+
+ def __init__(self, completion_queue, shutdown_tag):
+ self._condition = threading.Condition()
+ self._completion_queue = completion_queue
+ self._shutdown_tag = shutdown_tag
+ self._events = []
+ self._saw_shutdown_tag = False
+
+ def start(self):
+
+ def in_thread():
+ while True:
+ event = self._completion_queue.poll()
+ with self._condition:
+ self._events.append(event)
+ self._condition.notify()
+ if event.tag is self._shutdown_tag:
+ self._saw_shutdown_tag = True
+ break
+
+ thread = threading.Thread(target=in_thread)
+ thread.start()
+
+ def done(self):
+ with self._condition:
+ return self._saw_shutdown_tag
+
+ def first_event(self):
+ with self._condition:
+ while not self._events:
+ self._condition.wait()
+ return self._events[0]
+
+ def events(self):
+ with self._condition:
+ while not self._saw_shutdown_tag:
+ self._condition.wait()
+ return tuple(self._events)
+
+
+class _QueueDriver(object):
+
+ def __init__(self, condition, completion_queue, due):
+ self._condition = condition
+ self._completion_queue = completion_queue
+ self._due = due
+ self._events = []
+ self._returned = False
+
+ def start(self):
+
+ def in_thread():
+ while True:
+ event = self._completion_queue.poll()
+ with self._condition:
+ self._events.append(event)
+ self._due.remove(event.tag)
+ self._condition.notify_all()
+ if not self._due:
+ self._returned = True
+ return
+
+ thread = threading.Thread(target=in_thread)
+ thread.start()
+
+ def done(self):
+ with self._condition:
+ return self._returned
+
+ def event_with_tag(self, tag):
+ with self._condition:
+ while True:
+ for event in self._events:
+ if event.tag is tag:
+ return event
+ self._condition.wait()
+
+ def events(self):
+ with self._condition:
+ while not self._returned:
+ self._condition.wait()
+ return tuple(self._events)
+
+
+class ReadSomeButNotAllResponsesTest(unittest.TestCase):
+
+ def testReadSomeButNotAllResponses(self):
+ server_completion_queue = cygrpc.CompletionQueue()
+ server = cygrpc.Server([(
+ b'grpc.so_reuseport',
+ 0,
+ )])
+ server.register_completion_queue(server_completion_queue)
+ port = server.add_http2_port(b'[::]:0')
+ server.start()
+ channel = cygrpc.Channel('localhost:{}'.format(port).encode(), set(),
+ None)
+
+ server_shutdown_tag = 'server_shutdown_tag'
+ server_driver = _ServerDriver(server_completion_queue,
+ server_shutdown_tag)
+ server_driver.start()
+
+ client_condition = threading.Condition()
+ client_due = set()
+
+ server_call_condition = threading.Condition()
+ server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
+ server_send_first_message_tag = 'server_send_first_message_tag'
+ server_send_second_message_tag = 'server_send_second_message_tag'
+ server_complete_rpc_tag = 'server_complete_rpc_tag'
+ server_call_due = set((
+ server_send_initial_metadata_tag,
+ server_send_first_message_tag,
+ server_send_second_message_tag,
+ server_complete_rpc_tag,
+ ))
+ server_call_completion_queue = cygrpc.CompletionQueue()
+ server_call_driver = _QueueDriver(server_call_condition,
+ server_call_completion_queue,
+ server_call_due)
+ server_call_driver.start()
+
+ server_rpc_tag = 'server_rpc_tag'
+ request_call_result = server.request_call(server_call_completion_queue,
+ server_completion_queue,
+ server_rpc_tag)
+
+ client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
+ client_complete_rpc_tag = 'client_complete_rpc_tag'
+ client_call = channel.segregated_call(
+ _EMPTY_FLAGS, b'/twinkies', None, None, _EMPTY_METADATA, None, (
+ (
+ [
+ cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
+ ],
+ client_receive_initial_metadata_tag,
+ ),
+ (
+ [
+ cygrpc.SendInitialMetadataOperation(
+ _EMPTY_METADATA, _EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ ],
+ client_complete_rpc_tag,
+ ),
+ ))
+ client_receive_initial_metadata_event_future = test_utilities.SimpleFuture(
+ client_call.next_event)
+
+ server_rpc_event = server_driver.first_event()
+
+ with server_call_condition:
+ server_send_initial_metadata_start_batch_result = (
+ server_rpc_event.call.start_server_batch([
+ cygrpc.SendInitialMetadataOperation(_EMPTY_METADATA,
+ _EMPTY_FLAGS),
+ ], server_send_initial_metadata_tag))
+ server_send_first_message_start_batch_result = (
+ server_rpc_event.call.start_server_batch([
+ cygrpc.SendMessageOperation(b'\x07', _EMPTY_FLAGS),
+ ], server_send_first_message_tag))
+ server_send_initial_metadata_event = server_call_driver.event_with_tag(
+ server_send_initial_metadata_tag)
+ server_send_first_message_event = server_call_driver.event_with_tag(
+ server_send_first_message_tag)
+ with server_call_condition:
+ server_send_second_message_start_batch_result = (
+ server_rpc_event.call.start_server_batch([
+ cygrpc.SendMessageOperation(b'\x07', _EMPTY_FLAGS),
+ ], server_send_second_message_tag))
+ server_complete_rpc_start_batch_result = (
+ server_rpc_event.call.start_server_batch([
+ cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(
+ (), cygrpc.StatusCode.ok, b'test details',
+ _EMPTY_FLAGS),
+ ], server_complete_rpc_tag))
+ server_send_second_message_event = server_call_driver.event_with_tag(
+ server_send_second_message_tag)
+ server_complete_rpc_event = server_call_driver.event_with_tag(
+ server_complete_rpc_tag)
+ server_call_driver.events()
+
+ client_recieve_initial_metadata_event = client_receive_initial_metadata_event_future.result(
+ )
+
+ client_receive_first_message_tag = 'client_receive_first_message_tag'
+ client_call.operate([
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ ], client_receive_first_message_tag)
+ client_receive_first_message_event = client_call.next_event()
+
+ client_call_cancel_result = client_call.cancel(
+ cygrpc.StatusCode.cancelled, 'Cancelled during test!')
+ client_complete_rpc_event = client_call.next_event()
+
+ channel.close(cygrpc.StatusCode.unknown, 'Channel closed!')
+ server.shutdown(server_completion_queue, server_shutdown_tag)
+ server.cancel_all_calls()
+ server_driver.events()
+
+ self.assertEqual(cygrpc.CallError.ok, request_call_result)
+ self.assertEqual(cygrpc.CallError.ok,
+ server_send_initial_metadata_start_batch_result)
+ self.assertIs(server_rpc_tag, server_rpc_event.tag)
+ self.assertEqual(cygrpc.CompletionType.operation_complete,
+ server_rpc_event.completion_type)
+ self.assertIsInstance(server_rpc_event.call, cygrpc.Call)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py
index bbd25457b3..f89fc49d20 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py
@@ -1,49 +1,49 @@
-# Copyright 2017 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.
-"""Test servers at the level of the Cython API."""
-
-import threading
-import time
-import unittest
-
-from grpc._cython import cygrpc
-
-
-class Test(unittest.TestCase):
-
- def test_lonely_server(self):
- server_call_completion_queue = cygrpc.CompletionQueue()
- server_shutdown_completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server(None)
- server.register_completion_queue(server_call_completion_queue)
- server.register_completion_queue(server_shutdown_completion_queue)
- port = server.add_http2_port(b'[::]:0')
- server.start()
-
- server_request_call_tag = 'server_request_call_tag'
- server_request_call_start_batch_result = server.request_call(
- server_call_completion_queue, server_call_completion_queue,
- server_request_call_tag)
-
- time.sleep(4)
-
- server_shutdown_tag = 'server_shutdown_tag'
- server_shutdown_result = server.shutdown(
- server_shutdown_completion_queue, server_shutdown_tag)
- server_request_call_event = server_call_completion_queue.poll()
- server_shutdown_event = server_shutdown_completion_queue.poll()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2017 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.
+"""Test servers at the level of the Cython API."""
+
+import threading
+import time
+import unittest
+
+from grpc._cython import cygrpc
+
+
+class Test(unittest.TestCase):
+
+ def test_lonely_server(self):
+ server_call_completion_queue = cygrpc.CompletionQueue()
+ server_shutdown_completion_queue = cygrpc.CompletionQueue()
+ server = cygrpc.Server(None)
+ server.register_completion_queue(server_call_completion_queue)
+ server.register_completion_queue(server_shutdown_completion_queue)
+ port = server.add_http2_port(b'[::]:0')
+ server.start()
+
+ server_request_call_tag = 'server_request_call_tag'
+ server_request_call_start_batch_result = server.request_call(
+ server_call_completion_queue, server_call_completion_queue,
+ server_request_call_tag)
+
+ time.sleep(4)
+
+ server_shutdown_tag = 'server_shutdown_tag'
+ server_shutdown_result = server.shutdown(
+ server_shutdown_completion_queue, server_shutdown_tag)
+ server_request_call_event = server_call_completion_queue.poll()
+ server_shutdown_event = server_shutdown_completion_queue.poll()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py
index 1182f83a42..a5e0003c42 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py
@@ -1,335 +1,335 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import time
-import threading
-import unittest
-import platform
-
-from grpc._cython import cygrpc
-from tests.unit._cython import test_utilities
-from tests.unit import test_common
-from tests.unit import resources
-
-_SSL_HOST_OVERRIDE = b'foo.test.google.fr'
-_CALL_CREDENTIALS_METADATA_KEY = 'call-creds-key'
-_CALL_CREDENTIALS_METADATA_VALUE = 'call-creds-value'
-_EMPTY_FLAGS = 0
-
-
-def _metadata_plugin(context, callback):
- callback(((
- _CALL_CREDENTIALS_METADATA_KEY,
- _CALL_CREDENTIALS_METADATA_VALUE,
- ),), cygrpc.StatusCode.ok, b'')
-
-
-class TypeSmokeTest(unittest.TestCase):
-
- def testCompletionQueueUpDown(self):
- completion_queue = cygrpc.CompletionQueue()
- del completion_queue
-
- def testServerUpDown(self):
- server = cygrpc.Server(set([
- (
- b'grpc.so_reuseport',
- 0,
- ),
- ]))
- del server
-
- def testChannelUpDown(self):
- channel = cygrpc.Channel(b'[::]:0', None, None)
- channel.close(cygrpc.StatusCode.cancelled, 'Test method anyway!')
-
- def test_metadata_plugin_call_credentials_up_down(self):
- cygrpc.MetadataPluginCallCredentials(_metadata_plugin,
- b'test plugin name!')
-
- def testServerStartNoExplicitShutdown(self):
- server = cygrpc.Server([
- (
- b'grpc.so_reuseport',
- 0,
- ),
- ])
- completion_queue = cygrpc.CompletionQueue()
- server.register_completion_queue(completion_queue)
- port = server.add_http2_port(b'[::]:0')
- self.assertIsInstance(port, int)
- server.start()
- del server
-
- def testServerStartShutdown(self):
- completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server([
- (
- b'grpc.so_reuseport',
- 0,
- ),
- ])
- server.add_http2_port(b'[::]:0')
- server.register_completion_queue(completion_queue)
- server.start()
- shutdown_tag = object()
- server.shutdown(completion_queue, shutdown_tag)
- event = completion_queue.poll()
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- event.completion_type)
- self.assertIs(shutdown_tag, event.tag)
- del server
- del completion_queue
-
-
-class ServerClientMixin(object):
-
- def setUpMixin(self, server_credentials, client_credentials, host_override):
- self.server_completion_queue = cygrpc.CompletionQueue()
- self.server = cygrpc.Server([
- (
- b'grpc.so_reuseport',
- 0,
- ),
- ])
- self.server.register_completion_queue(self.server_completion_queue)
- if server_credentials:
- self.port = self.server.add_http2_port(b'[::]:0',
- server_credentials)
- else:
- self.port = self.server.add_http2_port(b'[::]:0')
- self.server.start()
- self.client_completion_queue = cygrpc.CompletionQueue()
- if client_credentials:
- client_channel_arguments = ((
- cygrpc.ChannelArgKey.ssl_target_name_override,
- host_override,
- ),)
+# Copyright 2015 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import time
+import threading
+import unittest
+import platform
+
+from grpc._cython import cygrpc
+from tests.unit._cython import test_utilities
+from tests.unit import test_common
+from tests.unit import resources
+
+_SSL_HOST_OVERRIDE = b'foo.test.google.fr'
+_CALL_CREDENTIALS_METADATA_KEY = 'call-creds-key'
+_CALL_CREDENTIALS_METADATA_VALUE = 'call-creds-value'
+_EMPTY_FLAGS = 0
+
+
+def _metadata_plugin(context, callback):
+ callback(((
+ _CALL_CREDENTIALS_METADATA_KEY,
+ _CALL_CREDENTIALS_METADATA_VALUE,
+ ),), cygrpc.StatusCode.ok, b'')
+
+
+class TypeSmokeTest(unittest.TestCase):
+
+ def testCompletionQueueUpDown(self):
+ completion_queue = cygrpc.CompletionQueue()
+ del completion_queue
+
+ def testServerUpDown(self):
+ server = cygrpc.Server(set([
+ (
+ b'grpc.so_reuseport',
+ 0,
+ ),
+ ]))
+ del server
+
+ def testChannelUpDown(self):
+ channel = cygrpc.Channel(b'[::]:0', None, None)
+ channel.close(cygrpc.StatusCode.cancelled, 'Test method anyway!')
+
+ def test_metadata_plugin_call_credentials_up_down(self):
+ cygrpc.MetadataPluginCallCredentials(_metadata_plugin,
+ b'test plugin name!')
+
+ def testServerStartNoExplicitShutdown(self):
+ server = cygrpc.Server([
+ (
+ b'grpc.so_reuseport',
+ 0,
+ ),
+ ])
+ completion_queue = cygrpc.CompletionQueue()
+ server.register_completion_queue(completion_queue)
+ port = server.add_http2_port(b'[::]:0')
+ self.assertIsInstance(port, int)
+ server.start()
+ del server
+
+ def testServerStartShutdown(self):
+ completion_queue = cygrpc.CompletionQueue()
+ server = cygrpc.Server([
+ (
+ b'grpc.so_reuseport',
+ 0,
+ ),
+ ])
+ server.add_http2_port(b'[::]:0')
+ server.register_completion_queue(completion_queue)
+ server.start()
+ shutdown_tag = object()
+ server.shutdown(completion_queue, shutdown_tag)
+ event = completion_queue.poll()
+ self.assertEqual(cygrpc.CompletionType.operation_complete,
+ event.completion_type)
+ self.assertIs(shutdown_tag, event.tag)
+ del server
+ del completion_queue
+
+
+class ServerClientMixin(object):
+
+ def setUpMixin(self, server_credentials, client_credentials, host_override):
+ self.server_completion_queue = cygrpc.CompletionQueue()
+ self.server = cygrpc.Server([
+ (
+ b'grpc.so_reuseport',
+ 0,
+ ),
+ ])
+ self.server.register_completion_queue(self.server_completion_queue)
+ if server_credentials:
+ self.port = self.server.add_http2_port(b'[::]:0',
+ server_credentials)
+ else:
+ self.port = self.server.add_http2_port(b'[::]:0')
+ self.server.start()
+ self.client_completion_queue = cygrpc.CompletionQueue()
+ if client_credentials:
+ client_channel_arguments = ((
+ cygrpc.ChannelArgKey.ssl_target_name_override,
+ host_override,
+ ),)
self.client_channel = cygrpc.Channel(
'localhost:{}'.format(self.port).encode(),
client_channel_arguments, client_credentials)
- else:
+ else:
self.client_channel = cygrpc.Channel(
'localhost:{}'.format(self.port).encode(), set(), None)
- if host_override:
- self.host_argument = None # default host
- self.expected_host = host_override
- else:
- # arbitrary host name necessitating no further identification
- self.host_argument = b'hostess'
- self.expected_host = self.host_argument
-
- def tearDownMixin(self):
- self.client_channel.close(cygrpc.StatusCode.ok, 'test being torn down!')
- del self.client_channel
- del self.server
- del self.client_completion_queue
- del self.server_completion_queue
-
- def _perform_queue_operations(self, operations, call, queue, deadline,
- description):
- """Perform the operations with given call, queue, and deadline.
-
- Invocation errors are reported with as an exception with `description`
- in the message. Performs the operations asynchronously, returning a
- future.
- """
-
- def performer():
- tag = object()
- try:
- call_result = call.start_client_batch(operations, tag)
- self.assertEqual(cygrpc.CallError.ok, call_result)
- event = queue.poll(deadline=deadline)
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- event.completion_type)
- self.assertTrue(event.success)
- self.assertIs(tag, event.tag)
- except Exception as error:
- raise Exception("Error in '{}': {}".format(
- description, error.message))
- return event
-
- return test_utilities.SimpleFuture(performer)
-
- def test_echo(self):
- DEADLINE = time.time() + 5
- DEADLINE_TOLERANCE = 0.25
- CLIENT_METADATA_ASCII_KEY = 'key'
- CLIENT_METADATA_ASCII_VALUE = 'val'
- CLIENT_METADATA_BIN_KEY = 'key-bin'
- CLIENT_METADATA_BIN_VALUE = b'\0' * 1000
- SERVER_INITIAL_METADATA_KEY = 'init_me_me_me'
- SERVER_INITIAL_METADATA_VALUE = 'whodawha?'
- SERVER_TRAILING_METADATA_KEY = 'california_is_in_a_drought'
- SERVER_TRAILING_METADATA_VALUE = 'zomg it is'
- SERVER_STATUS_CODE = cygrpc.StatusCode.ok
- SERVER_STATUS_DETAILS = 'our work is never over'
- REQUEST = b'in death a member of project mayhem has a name'
- RESPONSE = b'his name is robert paulson'
- METHOD = b'twinkies'
-
- server_request_tag = object()
- request_call_result = self.server.request_call(
- self.server_completion_queue, self.server_completion_queue,
- server_request_tag)
-
- self.assertEqual(cygrpc.CallError.ok, request_call_result)
-
- client_call_tag = object()
- client_initial_metadata = (
- (
- CLIENT_METADATA_ASCII_KEY,
- CLIENT_METADATA_ASCII_VALUE,
- ),
- (
- CLIENT_METADATA_BIN_KEY,
- CLIENT_METADATA_BIN_VALUE,
- ),
- )
- client_call = self.client_channel.integrated_call(
- 0, METHOD, self.host_argument, DEADLINE, client_initial_metadata,
- None, [
- (
- [
- cygrpc.SendInitialMetadataOperation(
- client_initial_metadata, _EMPTY_FLAGS),
- cygrpc.SendMessageOperation(REQUEST, _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ],
- client_call_tag,
- ),
- ])
- client_event_future = test_utilities.SimpleFuture(
- self.client_channel.next_call_event)
-
- request_event = self.server_completion_queue.poll(deadline=DEADLINE)
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- request_event.completion_type)
- self.assertIsInstance(request_event.call, cygrpc.Call)
- self.assertIs(server_request_tag, request_event.tag)
- self.assertTrue(
- test_common.metadata_transmitted(client_initial_metadata,
- request_event.invocation_metadata))
- self.assertEqual(METHOD, request_event.call_details.method)
- self.assertEqual(self.expected_host, request_event.call_details.host)
+ if host_override:
+ self.host_argument = None # default host
+ self.expected_host = host_override
+ else:
+ # arbitrary host name necessitating no further identification
+ self.host_argument = b'hostess'
+ self.expected_host = self.host_argument
+
+ def tearDownMixin(self):
+ self.client_channel.close(cygrpc.StatusCode.ok, 'test being torn down!')
+ del self.client_channel
+ del self.server
+ del self.client_completion_queue
+ del self.server_completion_queue
+
+ def _perform_queue_operations(self, operations, call, queue, deadline,
+ description):
+ """Perform the operations with given call, queue, and deadline.
+
+ Invocation errors are reported with as an exception with `description`
+ in the message. Performs the operations asynchronously, returning a
+ future.
+ """
+
+ def performer():
+ tag = object()
+ try:
+ call_result = call.start_client_batch(operations, tag)
+ self.assertEqual(cygrpc.CallError.ok, call_result)
+ event = queue.poll(deadline=deadline)
+ self.assertEqual(cygrpc.CompletionType.operation_complete,
+ event.completion_type)
+ self.assertTrue(event.success)
+ self.assertIs(tag, event.tag)
+ except Exception as error:
+ raise Exception("Error in '{}': {}".format(
+ description, error.message))
+ return event
+
+ return test_utilities.SimpleFuture(performer)
+
+ def test_echo(self):
+ DEADLINE = time.time() + 5
+ DEADLINE_TOLERANCE = 0.25
+ CLIENT_METADATA_ASCII_KEY = 'key'
+ CLIENT_METADATA_ASCII_VALUE = 'val'
+ CLIENT_METADATA_BIN_KEY = 'key-bin'
+ CLIENT_METADATA_BIN_VALUE = b'\0' * 1000
+ SERVER_INITIAL_METADATA_KEY = 'init_me_me_me'
+ SERVER_INITIAL_METADATA_VALUE = 'whodawha?'
+ SERVER_TRAILING_METADATA_KEY = 'california_is_in_a_drought'
+ SERVER_TRAILING_METADATA_VALUE = 'zomg it is'
+ SERVER_STATUS_CODE = cygrpc.StatusCode.ok
+ SERVER_STATUS_DETAILS = 'our work is never over'
+ REQUEST = b'in death a member of project mayhem has a name'
+ RESPONSE = b'his name is robert paulson'
+ METHOD = b'twinkies'
+
+ server_request_tag = object()
+ request_call_result = self.server.request_call(
+ self.server_completion_queue, self.server_completion_queue,
+ server_request_tag)
+
+ self.assertEqual(cygrpc.CallError.ok, request_call_result)
+
+ client_call_tag = object()
+ client_initial_metadata = (
+ (
+ CLIENT_METADATA_ASCII_KEY,
+ CLIENT_METADATA_ASCII_VALUE,
+ ),
+ (
+ CLIENT_METADATA_BIN_KEY,
+ CLIENT_METADATA_BIN_VALUE,
+ ),
+ )
+ client_call = self.client_channel.integrated_call(
+ 0, METHOD, self.host_argument, DEADLINE, client_initial_metadata,
+ None, [
+ (
+ [
+ cygrpc.SendInitialMetadataOperation(
+ client_initial_metadata, _EMPTY_FLAGS),
+ cygrpc.SendMessageOperation(REQUEST, _EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ ],
+ client_call_tag,
+ ),
+ ])
+ client_event_future = test_utilities.SimpleFuture(
+ self.client_channel.next_call_event)
+
+ request_event = self.server_completion_queue.poll(deadline=DEADLINE)
+ self.assertEqual(cygrpc.CompletionType.operation_complete,
+ request_event.completion_type)
+ self.assertIsInstance(request_event.call, cygrpc.Call)
+ self.assertIs(server_request_tag, request_event.tag)
+ self.assertTrue(
+ test_common.metadata_transmitted(client_initial_metadata,
+ request_event.invocation_metadata))
+ self.assertEqual(METHOD, request_event.call_details.method)
+ self.assertEqual(self.expected_host, request_event.call_details.host)
self.assertLess(abs(DEADLINE - request_event.call_details.deadline),
DEADLINE_TOLERANCE)
-
- server_call_tag = object()
- server_call = request_event.call
- server_initial_metadata = ((
- SERVER_INITIAL_METADATA_KEY,
- SERVER_INITIAL_METADATA_VALUE,
- ),)
- server_trailing_metadata = ((
- SERVER_TRAILING_METADATA_KEY,
- SERVER_TRAILING_METADATA_VALUE,
- ),)
- server_start_batch_result = server_call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(server_initial_metadata,
- _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.SendMessageOperation(RESPONSE, _EMPTY_FLAGS),
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- server_trailing_metadata, SERVER_STATUS_CODE,
- SERVER_STATUS_DETAILS, _EMPTY_FLAGS)
- ], server_call_tag)
- self.assertEqual(cygrpc.CallError.ok, server_start_batch_result)
-
- server_event = self.server_completion_queue.poll(deadline=DEADLINE)
- client_event = client_event_future.result()
-
- self.assertEqual(6, len(client_event.batch_operations))
- found_client_op_types = set()
- for client_result in client_event.batch_operations:
- # we expect each op type to be unique
- self.assertNotIn(client_result.type(), found_client_op_types)
- found_client_op_types.add(client_result.type())
- if client_result.type(
- ) == cygrpc.OperationType.receive_initial_metadata:
- self.assertTrue(
- test_common.metadata_transmitted(
- server_initial_metadata,
- client_result.initial_metadata()))
- elif client_result.type() == cygrpc.OperationType.receive_message:
- self.assertEqual(RESPONSE, client_result.message())
- elif client_result.type(
- ) == cygrpc.OperationType.receive_status_on_client:
- self.assertTrue(
- test_common.metadata_transmitted(
- server_trailing_metadata,
- client_result.trailing_metadata()))
- self.assertEqual(SERVER_STATUS_DETAILS, client_result.details())
- self.assertEqual(SERVER_STATUS_CODE, client_result.code())
- self.assertEqual(
- set([
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.send_message,
- cygrpc.OperationType.send_close_from_client,
- cygrpc.OperationType.receive_initial_metadata,
- cygrpc.OperationType.receive_message,
- cygrpc.OperationType.receive_status_on_client
- ]), found_client_op_types)
-
- self.assertEqual(5, len(server_event.batch_operations))
- found_server_op_types = set()
- for server_result in server_event.batch_operations:
- self.assertNotIn(server_result.type(), found_server_op_types)
- found_server_op_types.add(server_result.type())
- if server_result.type() == cygrpc.OperationType.receive_message:
- self.assertEqual(REQUEST, server_result.message())
- elif server_result.type(
- ) == cygrpc.OperationType.receive_close_on_server:
- self.assertFalse(server_result.cancelled())
- self.assertEqual(
- set([
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.receive_message,
- cygrpc.OperationType.send_message,
- cygrpc.OperationType.receive_close_on_server,
- cygrpc.OperationType.send_status_from_server
- ]), found_server_op_types)
-
- del client_call
- del server_call
-
- def test_6522(self):
- DEADLINE = time.time() + 5
- DEADLINE_TOLERANCE = 0.25
- METHOD = b'twinkies'
-
- empty_metadata = ()
-
- # Prologue
- server_request_tag = object()
- self.server.request_call(self.server_completion_queue,
- self.server_completion_queue,
- server_request_tag)
- client_call = self.client_channel.segregated_call(
+
+ server_call_tag = object()
+ server_call = request_event.call
+ server_initial_metadata = ((
+ SERVER_INITIAL_METADATA_KEY,
+ SERVER_INITIAL_METADATA_VALUE,
+ ),)
+ server_trailing_metadata = ((
+ SERVER_TRAILING_METADATA_KEY,
+ SERVER_TRAILING_METADATA_VALUE,
+ ),)
+ server_start_batch_result = server_call.start_server_batch([
+ cygrpc.SendInitialMetadataOperation(server_initial_metadata,
+ _EMPTY_FLAGS),
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ cygrpc.SendMessageOperation(RESPONSE, _EMPTY_FLAGS),
+ cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(
+ server_trailing_metadata, SERVER_STATUS_CODE,
+ SERVER_STATUS_DETAILS, _EMPTY_FLAGS)
+ ], server_call_tag)
+ self.assertEqual(cygrpc.CallError.ok, server_start_batch_result)
+
+ server_event = self.server_completion_queue.poll(deadline=DEADLINE)
+ client_event = client_event_future.result()
+
+ self.assertEqual(6, len(client_event.batch_operations))
+ found_client_op_types = set()
+ for client_result in client_event.batch_operations:
+ # we expect each op type to be unique
+ self.assertNotIn(client_result.type(), found_client_op_types)
+ found_client_op_types.add(client_result.type())
+ if client_result.type(
+ ) == cygrpc.OperationType.receive_initial_metadata:
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ server_initial_metadata,
+ client_result.initial_metadata()))
+ elif client_result.type() == cygrpc.OperationType.receive_message:
+ self.assertEqual(RESPONSE, client_result.message())
+ elif client_result.type(
+ ) == cygrpc.OperationType.receive_status_on_client:
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ server_trailing_metadata,
+ client_result.trailing_metadata()))
+ self.assertEqual(SERVER_STATUS_DETAILS, client_result.details())
+ self.assertEqual(SERVER_STATUS_CODE, client_result.code())
+ self.assertEqual(
+ set([
+ cygrpc.OperationType.send_initial_metadata,
+ cygrpc.OperationType.send_message,
+ cygrpc.OperationType.send_close_from_client,
+ cygrpc.OperationType.receive_initial_metadata,
+ cygrpc.OperationType.receive_message,
+ cygrpc.OperationType.receive_status_on_client
+ ]), found_client_op_types)
+
+ self.assertEqual(5, len(server_event.batch_operations))
+ found_server_op_types = set()
+ for server_result in server_event.batch_operations:
+ self.assertNotIn(server_result.type(), found_server_op_types)
+ found_server_op_types.add(server_result.type())
+ if server_result.type() == cygrpc.OperationType.receive_message:
+ self.assertEqual(REQUEST, server_result.message())
+ elif server_result.type(
+ ) == cygrpc.OperationType.receive_close_on_server:
+ self.assertFalse(server_result.cancelled())
+ self.assertEqual(
+ set([
+ cygrpc.OperationType.send_initial_metadata,
+ cygrpc.OperationType.receive_message,
+ cygrpc.OperationType.send_message,
+ cygrpc.OperationType.receive_close_on_server,
+ cygrpc.OperationType.send_status_from_server
+ ]), found_server_op_types)
+
+ del client_call
+ del server_call
+
+ def test_6522(self):
+ DEADLINE = time.time() + 5
+ DEADLINE_TOLERANCE = 0.25
+ METHOD = b'twinkies'
+
+ empty_metadata = ()
+
+ # Prologue
+ server_request_tag = object()
+ self.server.request_call(self.server_completion_queue,
+ self.server_completion_queue,
+ server_request_tag)
+ client_call = self.client_channel.segregated_call(
0, METHOD, self.host_argument, DEADLINE, None, None,
([(
- [
- cygrpc.SendInitialMetadataOperation(empty_metadata,
- _EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- ],
- object(),
+ [
+ cygrpc.SendInitialMetadataOperation(empty_metadata,
+ _EMPTY_FLAGS),
+ cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
+ ],
+ object(),
),
(
[
@@ -337,86 +337,86 @@ class ServerClientMixin(object):
],
object(),
)]))
-
- client_initial_metadata_event_future = test_utilities.SimpleFuture(
- client_call.next_event)
-
- request_event = self.server_completion_queue.poll(deadline=DEADLINE)
- server_call = request_event.call
-
- def perform_server_operations(operations, description):
- return self._perform_queue_operations(operations, server_call,
- self.server_completion_queue,
- DEADLINE, description)
-
- server_event_future = perform_server_operations([
- cygrpc.SendInitialMetadataOperation(empty_metadata, _EMPTY_FLAGS),
- ], "Server prologue")
-
- client_initial_metadata_event_future.result() # force completion
- server_event_future.result()
-
- # Messaging
- for _ in range(10):
- client_call.operate([
- cygrpc.SendMessageOperation(b'', _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- ], "Client message")
- client_message_event_future = test_utilities.SimpleFuture(
- client_call.next_event)
- server_event_future = perform_server_operations([
- cygrpc.SendMessageOperation(b'', _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- ], "Server receive")
-
- client_message_event_future.result() # force completion
- server_event_future.result()
-
- # Epilogue
- client_call.operate([
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- ], "Client epilogue")
- # One for ReceiveStatusOnClient, one for SendCloseFromClient.
+
+ client_initial_metadata_event_future = test_utilities.SimpleFuture(
+ client_call.next_event)
+
+ request_event = self.server_completion_queue.poll(deadline=DEADLINE)
+ server_call = request_event.call
+
+ def perform_server_operations(operations, description):
+ return self._perform_queue_operations(operations, server_call,
+ self.server_completion_queue,
+ DEADLINE, description)
+
+ server_event_future = perform_server_operations([
+ cygrpc.SendInitialMetadataOperation(empty_metadata, _EMPTY_FLAGS),
+ ], "Server prologue")
+
+ client_initial_metadata_event_future.result() # force completion
+ server_event_future.result()
+
+ # Messaging
+ for _ in range(10):
+ client_call.operate([
+ cygrpc.SendMessageOperation(b'', _EMPTY_FLAGS),
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ ], "Client message")
+ client_message_event_future = test_utilities.SimpleFuture(
+ client_call.next_event)
+ server_event_future = perform_server_operations([
+ cygrpc.SendMessageOperation(b'', _EMPTY_FLAGS),
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ ], "Server receive")
+
+ client_message_event_future.result() # force completion
+ server_event_future.result()
+
+ # Epilogue
+ client_call.operate([
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+ ], "Client epilogue")
+ # One for ReceiveStatusOnClient, one for SendCloseFromClient.
client_events_future = test_utilities.SimpleFuture(lambda: {
client_call.next_event(),
client_call.next_event(),
})
-
- server_event_future = perform_server_operations([
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- empty_metadata, cygrpc.StatusCode.ok, b'', _EMPTY_FLAGS)
- ], "Server epilogue")
-
- client_events_future.result() # force completion
- server_event_future.result()
-
-
-class InsecureServerInsecureClient(unittest.TestCase, ServerClientMixin):
-
- def setUp(self):
- self.setUpMixin(None, None, None)
-
- def tearDown(self):
- self.tearDownMixin()
-
-
-class SecureServerSecureClient(unittest.TestCase, ServerClientMixin):
-
- def setUp(self):
- server_credentials = cygrpc.server_credentials_ssl(
- None, [
- cygrpc.SslPemKeyCertPair(resources.private_key(),
- resources.certificate_chain())
- ], False)
- client_credentials = cygrpc.SSLChannelCredentials(
- resources.test_root_certificates(), None, None)
- self.setUpMixin(server_credentials, client_credentials,
- _SSL_HOST_OVERRIDE)
-
- def tearDown(self):
- self.tearDownMixin()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+
+ server_event_future = perform_server_operations([
+ cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(
+ empty_metadata, cygrpc.StatusCode.ok, b'', _EMPTY_FLAGS)
+ ], "Server epilogue")
+
+ client_events_future.result() # force completion
+ server_event_future.result()
+
+
+class InsecureServerInsecureClient(unittest.TestCase, ServerClientMixin):
+
+ def setUp(self):
+ self.setUpMixin(None, None, None)
+
+ def tearDown(self):
+ self.tearDownMixin()
+
+
+class SecureServerSecureClient(unittest.TestCase, ServerClientMixin):
+
+ def setUp(self):
+ server_credentials = cygrpc.server_credentials_ssl(
+ None, [
+ cygrpc.SslPemKeyCertPair(resources.private_key(),
+ resources.certificate_chain())
+ ], False)
+ client_credentials = cygrpc.SSLChannelCredentials(
+ resources.test_root_certificates(), None, None)
+ self.setUpMixin(server_credentials, client_credentials,
+ _SSL_HOST_OVERRIDE)
+
+ def tearDown(self):
+ self.tearDownMixin()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py
index 7d5eaaaa84..6e01588b0c 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py
@@ -1,52 +1,52 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import threading
-
-from grpc._cython import cygrpc
-
-
-class SimpleFuture(object):
- """A simple future mechanism."""
-
- def __init__(self, function, *args, **kwargs):
-
- def wrapped_function():
- try:
- self._result = function(*args, **kwargs)
- except Exception as error: # pylint: disable=broad-except
- self._error = error
-
- self._result = None
- self._error = None
- self._thread = threading.Thread(target=wrapped_function)
- self._thread.start()
-
- def result(self):
- """The resulting value of this future.
-
- Re-raises any exceptions.
- """
- self._thread.join()
- if self._error:
- # TODO(atash): re-raise exceptions in a way that preserves tracebacks
- raise self._error # pylint: disable=raising-bad-type
- return self._result
-
-
-class CompletionQueuePollFuture(SimpleFuture):
-
- def __init__(self, completion_queue, deadline):
- super(CompletionQueuePollFuture,
- self).__init__(lambda: completion_queue.poll(deadline=deadline))
+# Copyright 2015 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import threading
+
+from grpc._cython import cygrpc
+
+
+class SimpleFuture(object):
+ """A simple future mechanism."""
+
+ def __init__(self, function, *args, **kwargs):
+
+ def wrapped_function():
+ try:
+ self._result = function(*args, **kwargs)
+ except Exception as error: # pylint: disable=broad-except
+ self._error = error
+
+ self._result = None
+ self._error = None
+ self._thread = threading.Thread(target=wrapped_function)
+ self._thread.start()
+
+ def result(self):
+ """The resulting value of this future.
+
+ Re-raises any exceptions.
+ """
+ self._thread.join()
+ if self._error:
+ # TODO(atash): re-raise exceptions in a way that preserves tracebacks
+ raise self._error # pylint: disable=raising-bad-type
+ return self._result
+
+
+class CompletionQueuePollFuture(SimpleFuture):
+
+ def __init__(self, completion_queue, deadline):
+ super(CompletionQueuePollFuture,
+ self).__init__(lambda: completion_queue.poll(deadline=deadline))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py
index 43141255f1..b8cad97712 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py
@@ -1,63 +1,63 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests for an actual dns resolution."""
-
-import unittest
-import logging
-import six
-
-import grpc
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_METHOD = '/ANY/METHOD'
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = _REQUEST
-
-
-class GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, unused_handler_details):
- return grpc.unary_unary_rpc_method_handler(
- lambda request, unused_context: request,
- )
-
-
-class DNSResolverTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers((GenericHandler(),))
- self._port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- def tearDown(self):
- self._server.stop(None)
-
- def test_connect_loopback(self):
- # NOTE(https://github.com/grpc/grpc/issues/18422)
- # In short, Gevent + C-Ares = Segfault. The C-Ares driver is not
- # supported by custom io manager like "gevent" or "libuv".
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests for an actual dns resolution."""
+
+import unittest
+import logging
+import six
+
+import grpc
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_METHOD = '/ANY/METHOD'
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = _REQUEST
+
+
+class GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, unused_handler_details):
+ return grpc.unary_unary_rpc_method_handler(
+ lambda request, unused_context: request,
+ )
+
+
+class DNSResolverTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
+ self._server.add_generic_rpc_handlers((GenericHandler(),))
+ self._port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+
+ def tearDown(self):
+ self._server.stop(None)
+
+ def test_connect_loopback(self):
+ # NOTE(https://github.com/grpc/grpc/issues/18422)
+ # In short, Gevent + C-Ares = Segfault. The C-Ares driver is not
+ # supported by custom io manager like "gevent" or "libuv".
with grpc.insecure_channel('loopback4.unittest.grpc.io:%d' %
self._port) as channel:
- self.assertEqual(
- channel.unary_unary(_METHOD)(
- _REQUEST,
- timeout=test_constants.SHORT_TIMEOUT,
- ), _RESPONSE)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ self.assertEqual(
+ channel.unary_unary(_METHOD)(
+ _REQUEST,
+ timeout=test_constants.SHORT_TIMEOUT,
+ ), _RESPONSE)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py
index f27ea422d0..99f8e414a7 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py
@@ -1,124 +1,124 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import unittest
-import logging
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_REQUEST = b''
-_RESPONSE = b''
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-def handle_unary_unary(request, servicer_context):
- return _RESPONSE
-
-
-def handle_unary_stream(request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(request_iterator, servicer_context):
- for request in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(request_iterator, servicer_context):
- for request in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = handle_stream_stream
- elif self.request_streaming:
- self.stream_unary = handle_stream_unary
- elif self.response_streaming:
- self.unary_stream = handle_unary_stream
- else:
- self.unary_unary = handle_unary_unary
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True)
- else:
- return None
-
-
-class EmptyMessageTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers((_GenericHandler(),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testUnaryUnary(self):
- response = self._channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- self.assertEqual(_RESPONSE, response)
-
- def testUnaryStream(self):
- response_iterator = self._channel.unary_stream(_UNARY_STREAM)(_REQUEST)
- self.assertSequenceEqual([_RESPONSE] * test_constants.STREAM_LENGTH,
- list(response_iterator))
-
- def testStreamUnary(self):
- response = self._channel.stream_unary(_STREAM_UNARY)(iter(
- [_REQUEST] * test_constants.STREAM_LENGTH))
- self.assertEqual(_RESPONSE, response)
-
- def testStreamStream(self):
- response_iterator = self._channel.stream_stream(_STREAM_STREAM)(iter(
- [_REQUEST] * test_constants.STREAM_LENGTH))
- self.assertSequenceEqual([_RESPONSE] * test_constants.STREAM_LENGTH,
- list(response_iterator))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+import logging
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_REQUEST = b''
+_RESPONSE = b''
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+
+def handle_unary_unary(request, servicer_context):
+ return _RESPONSE
+
+
+def handle_unary_stream(request, servicer_context):
+ for _ in range(test_constants.STREAM_LENGTH):
+ yield _RESPONSE
+
+
+def handle_stream_unary(request_iterator, servicer_context):
+ for request in request_iterator:
+ pass
+ return _RESPONSE
+
+
+def handle_stream_stream(request_iterator, servicer_context):
+ for request in request_iterator:
+ yield _RESPONSE
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, request_streaming, response_streaming):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_unary = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+ if self.request_streaming and self.response_streaming:
+ self.stream_stream = handle_stream_stream
+ elif self.request_streaming:
+ self.stream_unary = handle_stream_unary
+ elif self.response_streaming:
+ self.unary_stream = handle_unary_stream
+ else:
+ self.unary_unary = handle_unary_unary
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(False, False)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(False, True)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(True, False)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(True, True)
+ else:
+ return None
+
+
+class EmptyMessageTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
+ self._server.add_generic_rpc_handlers((_GenericHandler(),))
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._server.stop(0)
+ self._channel.close()
+
+ def testUnaryUnary(self):
+ response = self._channel.unary_unary(_UNARY_UNARY)(_REQUEST)
+ self.assertEqual(_RESPONSE, response)
+
+ def testUnaryStream(self):
+ response_iterator = self._channel.unary_stream(_UNARY_STREAM)(_REQUEST)
+ self.assertSequenceEqual([_RESPONSE] * test_constants.STREAM_LENGTH,
+ list(response_iterator))
+
+ def testStreamUnary(self):
+ response = self._channel.stream_unary(_STREAM_UNARY)(iter(
+ [_REQUEST] * test_constants.STREAM_LENGTH))
+ self.assertEqual(_RESPONSE, response)
+
+ def testStreamStream(self):
+ response_iterator = self._channel.stream_stream(_STREAM_STREAM)(iter(
+ [_REQUEST] * test_constants.STREAM_LENGTH))
+ self.assertSequenceEqual([_RESPONSE] * test_constants.STREAM_LENGTH,
+ list(response_iterator))
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py
index e58007ad3e..1b04e87c35 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py
@@ -1,87 +1,87 @@
-# Copyright 2018 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.
-"""Tests 'utf-8' encoded error message."""
-
-import unittest
-import weakref
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_UNICODE_ERROR_MESSAGES = [
- b'\xe2\x80\x9d'.decode('utf-8'),
- b'abc\x80\xd0\xaf'.decode('latin-1'),
- b'\xc3\xa9'.decode('utf-8'),
-]
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming=None, response_streaming=None):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
-
- def unary_unary(self, request, servicer_context):
- servicer_context.set_code(grpc.StatusCode.UNKNOWN)
- servicer_context.set_details(request.decode('utf-8'))
- return _RESPONSE
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, test):
- self._test = test
-
- def service(self, handler_call_details):
- return _MethodHandler()
-
-
-class ErrorMessageEncodingTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
+# Copyright 2018 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.
+"""Tests 'utf-8' encoded error message."""
+
+import unittest
+import weakref
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_UNICODE_ERROR_MESSAGES = [
+ b'\xe2\x80\x9d'.decode('utf-8'),
+ b'abc\x80\xd0\xaf'.decode('latin-1'),
+ b'\xc3\xa9'.decode('utf-8'),
+]
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, request_streaming=None, response_streaming=None):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+
+ def unary_unary(self, request, servicer_context):
+ servicer_context.set_code(grpc.StatusCode.UNKNOWN)
+ servicer_context.set_details(request.decode('utf-8'))
+ return _RESPONSE
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, test):
+ self._test = test
+
+ def service(self, handler_call_details):
+ return _MethodHandler()
+
+
+class ErrorMessageEncodingTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
self._server.add_generic_rpc_handlers(
(_GenericHandler(weakref.proxy(self)),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testMessageEncoding(self):
- for message in _UNICODE_ERROR_MESSAGES:
- multi_callable = self._channel.unary_unary(_UNARY_UNARY)
- with self.assertRaises(grpc.RpcError) as cm:
- multi_callable(message.encode('utf-8'))
-
- self.assertEqual(cm.exception.code(), grpc.StatusCode.UNKNOWN)
- self.assertEqual(cm.exception.details(), message)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._server.stop(0)
+ self._channel.close()
+
+ def testMessageEncoding(self):
+ for message in _UNICODE_ERROR_MESSAGES:
+ multi_callable = self._channel.unary_unary(_UNARY_UNARY)
+ with self.assertRaises(grpc.RpcError) as cm:
+ multi_callable(message.encode('utf-8'))
+
+ self.assertEqual(cm.exception.code(), grpc.StatusCode.UNKNOWN)
+ self.assertEqual(cm.exception.details(), message)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py
index 48ea054d2d..b57af76d87 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py
@@ -1,236 +1,236 @@
-# Copyright 2016 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.
-"""Defines a number of module-scope gRPC scenarios to test clean exit."""
-
-import argparse
-import threading
-import time
-import logging
-
-import grpc
-
-from tests.unit.framework.common import test_constants
-
-WAIT_TIME = 1000
-
-REQUEST = b'request'
-
-UNSTARTED_SERVER = 'unstarted_server'
-RUNNING_SERVER = 'running_server'
-POLL_CONNECTIVITY_NO_SERVER = 'poll_connectivity_no_server'
-POLL_CONNECTIVITY = 'poll_connectivity'
-IN_FLIGHT_UNARY_UNARY_CALL = 'in_flight_unary_unary_call'
-IN_FLIGHT_UNARY_STREAM_CALL = 'in_flight_unary_stream_call'
-IN_FLIGHT_STREAM_UNARY_CALL = 'in_flight_stream_unary_call'
-IN_FLIGHT_STREAM_STREAM_CALL = 'in_flight_stream_stream_call'
-IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL = 'in_flight_partial_unary_stream_call'
-IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL = 'in_flight_partial_stream_unary_call'
-IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL = 'in_flight_partial_stream_stream_call'
-
-UNARY_UNARY = b'/test/UnaryUnary'
-UNARY_STREAM = b'/test/UnaryStream'
-STREAM_UNARY = b'/test/StreamUnary'
-STREAM_STREAM = b'/test/StreamStream'
-PARTIAL_UNARY_STREAM = b'/test/PartialUnaryStream'
-PARTIAL_STREAM_UNARY = b'/test/PartialStreamUnary'
-PARTIAL_STREAM_STREAM = b'/test/PartialStreamStream'
-
-TEST_TO_METHOD = {
- IN_FLIGHT_UNARY_UNARY_CALL: UNARY_UNARY,
- IN_FLIGHT_UNARY_STREAM_CALL: UNARY_STREAM,
- IN_FLIGHT_STREAM_UNARY_CALL: STREAM_UNARY,
- IN_FLIGHT_STREAM_STREAM_CALL: STREAM_STREAM,
- IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL: PARTIAL_UNARY_STREAM,
- IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL: PARTIAL_STREAM_UNARY,
- IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL: PARTIAL_STREAM_STREAM,
-}
-
-
-def hang_unary_unary(request, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_unary_stream(request, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_partial_unary_stream(request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH // 2):
- yield request
- time.sleep(WAIT_TIME)
-
-
-def hang_stream_unary(request_iterator, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_partial_stream_unary(request_iterator, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH // 2):
- next(request_iterator)
- time.sleep(WAIT_TIME)
-
-
-def hang_stream_stream(request_iterator, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_partial_stream_stream(request_iterator, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH // 2):
- yield next(request_iterator) #pylint: disable=stop-iteration-return
- time.sleep(WAIT_TIME)
-
-
-class MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming, partial_hang):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- if partial_hang:
- self.stream_stream = hang_partial_stream_stream
- else:
- self.stream_stream = hang_stream_stream
- elif self.request_streaming:
- if partial_hang:
- self.stream_unary = hang_partial_stream_unary
- else:
- self.stream_unary = hang_stream_unary
- elif self.response_streaming:
- if partial_hang:
- self.unary_stream = hang_partial_unary_stream
- else:
- self.unary_stream = hang_unary_stream
- else:
- self.unary_unary = hang_unary_unary
-
-
-class GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == UNARY_UNARY:
- return MethodHandler(False, False, False)
- elif handler_call_details.method == UNARY_STREAM:
- return MethodHandler(False, True, False)
- elif handler_call_details.method == STREAM_UNARY:
- return MethodHandler(True, False, False)
- elif handler_call_details.method == STREAM_STREAM:
- return MethodHandler(True, True, False)
- elif handler_call_details.method == PARTIAL_UNARY_STREAM:
- return MethodHandler(False, True, True)
- elif handler_call_details.method == PARTIAL_STREAM_UNARY:
- return MethodHandler(True, False, True)
- elif handler_call_details.method == PARTIAL_STREAM_STREAM:
- return MethodHandler(True, True, True)
- else:
- return None
-
-
-# Traditional executors will not exit until all their
-# current jobs complete. Because we submit jobs that will
-# never finish, we don't want to block exit on these jobs.
-class DaemonPool(object):
-
- def submit(self, fn, *args, **kwargs):
- thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
- thread.daemon = True
- thread.start()
-
- def shutdown(self, wait=True):
- pass
-
-
-def infinite_request_iterator():
- while True:
- yield REQUEST
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- parser = argparse.ArgumentParser()
- parser.add_argument('scenario', type=str)
+# Copyright 2016 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.
+"""Defines a number of module-scope gRPC scenarios to test clean exit."""
+
+import argparse
+import threading
+import time
+import logging
+
+import grpc
+
+from tests.unit.framework.common import test_constants
+
+WAIT_TIME = 1000
+
+REQUEST = b'request'
+
+UNSTARTED_SERVER = 'unstarted_server'
+RUNNING_SERVER = 'running_server'
+POLL_CONNECTIVITY_NO_SERVER = 'poll_connectivity_no_server'
+POLL_CONNECTIVITY = 'poll_connectivity'
+IN_FLIGHT_UNARY_UNARY_CALL = 'in_flight_unary_unary_call'
+IN_FLIGHT_UNARY_STREAM_CALL = 'in_flight_unary_stream_call'
+IN_FLIGHT_STREAM_UNARY_CALL = 'in_flight_stream_unary_call'
+IN_FLIGHT_STREAM_STREAM_CALL = 'in_flight_stream_stream_call'
+IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL = 'in_flight_partial_unary_stream_call'
+IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL = 'in_flight_partial_stream_unary_call'
+IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL = 'in_flight_partial_stream_stream_call'
+
+UNARY_UNARY = b'/test/UnaryUnary'
+UNARY_STREAM = b'/test/UnaryStream'
+STREAM_UNARY = b'/test/StreamUnary'
+STREAM_STREAM = b'/test/StreamStream'
+PARTIAL_UNARY_STREAM = b'/test/PartialUnaryStream'
+PARTIAL_STREAM_UNARY = b'/test/PartialStreamUnary'
+PARTIAL_STREAM_STREAM = b'/test/PartialStreamStream'
+
+TEST_TO_METHOD = {
+ IN_FLIGHT_UNARY_UNARY_CALL: UNARY_UNARY,
+ IN_FLIGHT_UNARY_STREAM_CALL: UNARY_STREAM,
+ IN_FLIGHT_STREAM_UNARY_CALL: STREAM_UNARY,
+ IN_FLIGHT_STREAM_STREAM_CALL: STREAM_STREAM,
+ IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL: PARTIAL_UNARY_STREAM,
+ IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL: PARTIAL_STREAM_UNARY,
+ IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL: PARTIAL_STREAM_STREAM,
+}
+
+
+def hang_unary_unary(request, servicer_context):
+ time.sleep(WAIT_TIME)
+
+
+def hang_unary_stream(request, servicer_context):
+ time.sleep(WAIT_TIME)
+
+
+def hang_partial_unary_stream(request, servicer_context):
+ for _ in range(test_constants.STREAM_LENGTH // 2):
+ yield request
+ time.sleep(WAIT_TIME)
+
+
+def hang_stream_unary(request_iterator, servicer_context):
+ time.sleep(WAIT_TIME)
+
+
+def hang_partial_stream_unary(request_iterator, servicer_context):
+ for _ in range(test_constants.STREAM_LENGTH // 2):
+ next(request_iterator)
+ time.sleep(WAIT_TIME)
+
+
+def hang_stream_stream(request_iterator, servicer_context):
+ time.sleep(WAIT_TIME)
+
+
+def hang_partial_stream_stream(request_iterator, servicer_context):
+ for _ in range(test_constants.STREAM_LENGTH // 2):
+ yield next(request_iterator) #pylint: disable=stop-iteration-return
+ time.sleep(WAIT_TIME)
+
+
+class MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, request_streaming, response_streaming, partial_hang):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_unary = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+ if self.request_streaming and self.response_streaming:
+ if partial_hang:
+ self.stream_stream = hang_partial_stream_stream
+ else:
+ self.stream_stream = hang_stream_stream
+ elif self.request_streaming:
+ if partial_hang:
+ self.stream_unary = hang_partial_stream_unary
+ else:
+ self.stream_unary = hang_stream_unary
+ elif self.response_streaming:
+ if partial_hang:
+ self.unary_stream = hang_partial_unary_stream
+ else:
+ self.unary_stream = hang_unary_stream
+ else:
+ self.unary_unary = hang_unary_unary
+
+
+class GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == UNARY_UNARY:
+ return MethodHandler(False, False, False)
+ elif handler_call_details.method == UNARY_STREAM:
+ return MethodHandler(False, True, False)
+ elif handler_call_details.method == STREAM_UNARY:
+ return MethodHandler(True, False, False)
+ elif handler_call_details.method == STREAM_STREAM:
+ return MethodHandler(True, True, False)
+ elif handler_call_details.method == PARTIAL_UNARY_STREAM:
+ return MethodHandler(False, True, True)
+ elif handler_call_details.method == PARTIAL_STREAM_UNARY:
+ return MethodHandler(True, False, True)
+ elif handler_call_details.method == PARTIAL_STREAM_STREAM:
+ return MethodHandler(True, True, True)
+ else:
+ return None
+
+
+# Traditional executors will not exit until all their
+# current jobs complete. Because we submit jobs that will
+# never finish, we don't want to block exit on these jobs.
+class DaemonPool(object):
+
+ def submit(self, fn, *args, **kwargs):
+ thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
+ thread.daemon = True
+ thread.start()
+
+ def shutdown(self, wait=True):
+ pass
+
+
+def infinite_request_iterator():
+ while True:
+ yield REQUEST
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ parser = argparse.ArgumentParser()
+ parser.add_argument('scenario', type=str)
parser.add_argument('--wait_for_interrupt',
dest='wait_for_interrupt',
action='store_true')
- args = parser.parse_args()
-
- if args.scenario == UNSTARTED_SERVER:
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
- elif args.scenario == RUNNING_SERVER:
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
- elif args.scenario == POLL_CONNECTIVITY_NO_SERVER:
- channel = grpc.insecure_channel('localhost:12345')
-
- def connectivity_callback(connectivity):
- pass
-
- channel.subscribe(connectivity_callback, try_to_connect=True)
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
- elif args.scenario == POLL_CONNECTIVITY:
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- channel = grpc.insecure_channel('localhost:%d' % port)
-
- def connectivity_callback(connectivity):
- pass
-
- channel.subscribe(connectivity_callback, try_to_connect=True)
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
-
- else:
- handler = GenericHandler()
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.add_generic_rpc_handlers((handler,))
- server.start()
- channel = grpc.insecure_channel('localhost:%d' % port)
-
- method = TEST_TO_METHOD[args.scenario]
-
- if args.scenario == IN_FLIGHT_UNARY_UNARY_CALL:
- multi_callable = channel.unary_unary(method)
- future = multi_callable.future(REQUEST)
- result, call = multi_callable.with_call(REQUEST)
- elif (args.scenario == IN_FLIGHT_UNARY_STREAM_CALL or
- args.scenario == IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL):
- multi_callable = channel.unary_stream(method)
- response_iterator = multi_callable(REQUEST)
- for response in response_iterator:
- pass
- elif (args.scenario == IN_FLIGHT_STREAM_UNARY_CALL or
- args.scenario == IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL):
- multi_callable = channel.stream_unary(method)
- future = multi_callable.future(infinite_request_iterator())
- result, call = multi_callable.with_call(
- iter([REQUEST] * test_constants.STREAM_LENGTH))
- elif (args.scenario == IN_FLIGHT_STREAM_STREAM_CALL or
- args.scenario == IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL):
- multi_callable = channel.stream_stream(method)
- response_iterator = multi_callable(infinite_request_iterator())
- for response in response_iterator:
- pass
+ args = parser.parse_args()
+
+ if args.scenario == UNSTARTED_SERVER:
+ server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
+ if args.wait_for_interrupt:
+ time.sleep(WAIT_TIME)
+ elif args.scenario == RUNNING_SERVER:
+ server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ if args.wait_for_interrupt:
+ time.sleep(WAIT_TIME)
+ elif args.scenario == POLL_CONNECTIVITY_NO_SERVER:
+ channel = grpc.insecure_channel('localhost:12345')
+
+ def connectivity_callback(connectivity):
+ pass
+
+ channel.subscribe(connectivity_callback, try_to_connect=True)
+ if args.wait_for_interrupt:
+ time.sleep(WAIT_TIME)
+ elif args.scenario == POLL_CONNECTIVITY:
+ server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def connectivity_callback(connectivity):
+ pass
+
+ channel.subscribe(connectivity_callback, try_to_connect=True)
+ if args.wait_for_interrupt:
+ time.sleep(WAIT_TIME)
+
+ else:
+ handler = GenericHandler()
+ server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
+ port = server.add_insecure_port('[::]:0')
+ server.add_generic_rpc_handlers((handler,))
+ server.start()
+ channel = grpc.insecure_channel('localhost:%d' % port)
+
+ method = TEST_TO_METHOD[args.scenario]
+
+ if args.scenario == IN_FLIGHT_UNARY_UNARY_CALL:
+ multi_callable = channel.unary_unary(method)
+ future = multi_callable.future(REQUEST)
+ result, call = multi_callable.with_call(REQUEST)
+ elif (args.scenario == IN_FLIGHT_UNARY_STREAM_CALL or
+ args.scenario == IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL):
+ multi_callable = channel.unary_stream(method)
+ response_iterator = multi_callable(REQUEST)
+ for response in response_iterator:
+ pass
+ elif (args.scenario == IN_FLIGHT_STREAM_UNARY_CALL or
+ args.scenario == IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL):
+ multi_callable = channel.stream_unary(method)
+ future = multi_callable.future(infinite_request_iterator())
+ result, call = multi_callable.with_call(
+ iter([REQUEST] * test_constants.STREAM_LENGTH))
+ elif (args.scenario == IN_FLIGHT_STREAM_STREAM_CALL or
+ args.scenario == IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL):
+ multi_callable = channel.stream_stream(method)
+ response_iterator = multi_callable(infinite_request_iterator())
+ for response in response_iterator:
+ pass
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py
index 4cf5ab63bd..06b32af34e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py
@@ -1,65 +1,65 @@
-# Copyright 2016 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.
-"""Tests clean exit of server/client on Python Interpreter exit/sigint.
-
-The tests in this module spawn a subprocess for each test case, the
-test is considered successful if it doesn't hang/timeout.
-"""
-
-import atexit
-import os
-import signal
-import six
-import subprocess
-import sys
-import threading
+# Copyright 2016 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.
+"""Tests clean exit of server/client on Python Interpreter exit/sigint.
+
+The tests in this module spawn a subprocess for each test case, the
+test is considered successful if it doesn't hang/timeout.
+"""
+
+import atexit
+import os
+import signal
+import six
+import subprocess
+import sys
+import threading
import datetime
-import time
-import unittest
-import logging
-
-from tests.unit import _exit_scenarios
-
-# SCENARIO_FILE = os.path.abspath(
+import time
+import unittest
+import logging
+
+from tests.unit import _exit_scenarios
+
+# SCENARIO_FILE = os.path.abspath(
# os.path.join(os.path.dirname(os.path.realpath(__file__)),
# '_exit_scenarios.py'))
-INTERPRETER = sys.executable
-BASE_COMMAND = [INTERPRETER, '-m', 'tests.unit._exit_scenarios']
-BASE_SIGTERM_COMMAND = BASE_COMMAND + ['--wait_for_interrupt']
-
+INTERPRETER = sys.executable
+BASE_COMMAND = [INTERPRETER, '-m', 'tests.unit._exit_scenarios']
+BASE_SIGTERM_COMMAND = BASE_COMMAND + ['--wait_for_interrupt']
+
INIT_TIME = datetime.timedelta(seconds=1)
WAIT_CHECK_INTERVAL = datetime.timedelta(milliseconds=100)
WAIT_CHECK_DEFAULT_TIMEOUT = datetime.timedelta(seconds=5)
-
-processes = []
-process_lock = threading.Lock()
-
-
-# Make sure we attempt to clean up any
-# processes we may have left running
-def cleanup_processes():
- with process_lock:
- for process in processes:
- try:
- process.kill()
- except Exception: # pylint: disable=broad-except
- pass
-
-
-atexit.register(cleanup_processes)
-
-
+
+processes = []
+process_lock = threading.Lock()
+
+
+# Make sure we attempt to clean up any
+# processes we may have left running
+def cleanup_processes():
+ with process_lock:
+ for process in processes:
+ try:
+ process.kill()
+ except Exception: # pylint: disable=broad-except
+ pass
+
+
+atexit.register(cleanup_processes)
+
+
def _process_wait_with_timeout(process, timeout=WAIT_CHECK_DEFAULT_TIMEOUT):
"""A funciton to mimic 3.3+ only timeout argument in process.wait."""
deadline = datetime.datetime.now() + timeout
@@ -69,193 +69,193 @@ def _process_wait_with_timeout(process, timeout=WAIT_CHECK_DEFAULT_TIMEOUT):
raise RuntimeError('Process failed to exit within %s' % timeout)
-def interrupt_and_wait(process):
- with process_lock:
- processes.append(process)
+def interrupt_and_wait(process):
+ with process_lock:
+ processes.append(process)
time.sleep(INIT_TIME.total_seconds())
- os.kill(process.pid, signal.SIGINT)
+ os.kill(process.pid, signal.SIGINT)
_process_wait_with_timeout(process)
-
-
-def wait(process):
- with process_lock:
- processes.append(process)
+
+
+def wait(process):
+ with process_lock:
+ processes.append(process)
_process_wait_with_timeout(process)
-
-
+
+
# TODO(lidiz) enable exit tests once the root cause found.
@unittest.skip('https://github.com/grpc/grpc/issues/23982')
@unittest.skip('https://github.com/grpc/grpc/issues/23028')
-class ExitTest(unittest.TestCase):
-
- def test_unstarted_server(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+class ExitTest(unittest.TestCase):
+
+ def test_unstarted_server(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_COMMAND +
[_exit_scenarios.UNSTARTED_SERVER],
stdout=sys.stdout,
stderr=sys.stderr,
env=env)
- wait(process)
-
- def test_unstarted_server_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ wait(process)
+
+ def test_unstarted_server_terminate(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_SIGTERM_COMMAND +
[_exit_scenarios.UNSTARTED_SERVER],
stdout=sys.stdout,
env=env)
- interrupt_and_wait(process)
-
- def test_running_server(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ interrupt_and_wait(process)
+
+ def test_running_server(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_COMMAND +
[_exit_scenarios.RUNNING_SERVER],
stdout=sys.stdout,
stderr=sys.stderr,
env=env)
- wait(process)
-
- def test_running_server_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ wait(process)
+
+ def test_running_server_terminate(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_SIGTERM_COMMAND +
[_exit_scenarios.RUNNING_SERVER],
stdout=sys.stdout,
stderr=sys.stderr,
env=env)
- interrupt_and_wait(process)
-
- def test_poll_connectivity_no_server(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.POLL_CONNECTIVITY_NO_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_poll_connectivity_no_server_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_SIGTERM_COMMAND +
- [_exit_scenarios.POLL_CONNECTIVITY_NO_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- def test_poll_connectivity(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ interrupt_and_wait(process)
+
+ def test_poll_connectivity_no_server(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_exit_scenarios.POLL_CONNECTIVITY_NO_SERVER],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ wait(process)
+
+ def test_poll_connectivity_no_server_terminate(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_SIGTERM_COMMAND +
+ [_exit_scenarios.POLL_CONNECTIVITY_NO_SERVER],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+ def test_poll_connectivity(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_COMMAND +
[_exit_scenarios.POLL_CONNECTIVITY],
stdout=sys.stdout,
stderr=sys.stderr,
env=env)
- wait(process)
-
- def test_poll_connectivity_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ wait(process)
+
+ def test_poll_connectivity_terminate(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_SIGTERM_COMMAND +
[_exit_scenarios.POLL_CONNECTIVITY],
stdout=sys.stdout,
stderr=sys.stderr,
env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_unary_unary_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_unary_unary_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen(BASE_COMMAND +
[_exit_scenarios.IN_FLIGHT_UNARY_UNARY_CALL],
stdout=sys.stdout,
stderr=sys.stderr,
env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_unary_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_UNARY_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_stream_unary_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_STREAM_UNARY_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_stream_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_STREAM_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_partial_unary_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_partial_stream_unary_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_partial_stream_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
-
-if __name__ == '__main__':
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_unary_stream_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_UNARY_STREAM_CALL],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_stream_unary_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_STREAM_UNARY_CALL],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_stream_stream_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_STREAM_STREAM_CALL],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_partial_unary_stream_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND +
+ [_exit_scenarios.IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_partial_stream_unary_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND +
+ [_exit_scenarios.IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'os.kill does not have required permission on Windows')
+ def test_in_flight_partial_stream_stream_call(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND +
+ [_exit_scenarios.IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ interrupt_and_wait(process)
+
+
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py
index 1ada25382d..022ec3aa2a 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py
@@ -1,23 +1,23 @@
-# Copyright 2016 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.
-
-_BEFORE_IMPORT = tuple(globals())
-
-from grpc import * # pylint: disable=wildcard-import,unused-wildcard-import
-
-_AFTER_IMPORT = tuple(globals())
-
-GRPC_ELEMENTS = tuple(
- element for element in _AFTER_IMPORT
- if element not in _BEFORE_IMPORT and element != '_BEFORE_IMPORT')
+# Copyright 2016 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.
+
+_BEFORE_IMPORT = tuple(globals())
+
+from grpc import * # pylint: disable=wildcard-import,unused-wildcard-import
+
+_AFTER_IMPORT = tuple(globals())
+
+GRPC_ELEMENTS = tuple(
+ element for element in _AFTER_IMPORT
+ if element not in _BEFORE_IMPORT and element != '_BEFORE_IMPORT')
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py
index 1c4890b97f..3a2bed66c0 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py
@@ -1,54 +1,54 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests the gRPC Core shutdown path."""
-
-import time
-import threading
-import unittest
-import datetime
-
-import grpc
-
-_TIMEOUT_FOR_SEGFAULT = datetime.timedelta(seconds=10)
-
-
-class GrpcShutdownTest(unittest.TestCase):
-
- def test_channel_close_with_connectivity_watcher(self):
- """Originated by https://github.com/grpc/grpc/issues/20299.
-
- The grpc_shutdown happens synchronously, but there might be Core object
- references left in Cython which might lead to ABORT or SIGSEGV.
- """
- connection_failed = threading.Event()
-
- def on_state_change(state):
- if state in (grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- grpc.ChannelConnectivity.SHUTDOWN):
- connection_failed.set()
-
- # Connects to an void address, and subscribes state changes
- channel = grpc.insecure_channel("0.1.1.1:12345")
- channel.subscribe(on_state_change, True)
-
- deadline = datetime.datetime.now() + _TIMEOUT_FOR_SEGFAULT
-
- while datetime.datetime.now() < deadline:
- time.sleep(0.1)
- if connection_failed.is_set():
- channel.close()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests the gRPC Core shutdown path."""
+
+import time
+import threading
+import unittest
+import datetime
+
+import grpc
+
+_TIMEOUT_FOR_SEGFAULT = datetime.timedelta(seconds=10)
+
+
+class GrpcShutdownTest(unittest.TestCase):
+
+ def test_channel_close_with_connectivity_watcher(self):
+ """Originated by https://github.com/grpc/grpc/issues/20299.
+
+ The grpc_shutdown happens synchronously, but there might be Core object
+ references left in Cython which might lead to ABORT or SIGSEGV.
+ """
+ connection_failed = threading.Event()
+
+ def on_state_change(state):
+ if state in (grpc.ChannelConnectivity.TRANSIENT_FAILURE,
+ grpc.ChannelConnectivity.SHUTDOWN):
+ connection_failed.set()
+
+ # Connects to an void address, and subscribes state changes
+ channel = grpc.insecure_channel("0.1.1.1:12345")
+ channel.subscribe(on_state_change, True)
+
+ deadline = datetime.datetime.now() + _TIMEOUT_FOR_SEGFAULT
+
+ while datetime.datetime.now() < deadline:
+ time.sleep(0.1)
+ if connection_failed.is_set():
+ channel.close()
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py
index 619db7b3ff..621a9efc70 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py
@@ -1,356 +1,356 @@
-# Copyright 2017 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.
-"""Test of gRPC Python interceptors."""
-
-import collections
-import itertools
-import threading
-import unittest
-import logging
-import os
-from concurrent import futures
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_EXCEPTION_REQUEST = b'\x09\x0a'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-class _ApplicationErrorStandin(Exception):
- pass
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
- self._called = False
-
- def __call__(self, value):
- with self._condition:
- self._value = value
- self._called = True
- self._condition.notify_all()
-
- def value(self):
- with self._condition:
- while not self._called:
- self._condition.wait()
- return self._value
-
-
-class _Handler(object):
-
- def __init__(self, control):
- self._control = control
-
- def handle_unary_unary(self, request, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- if request == _EXCEPTION_REQUEST:
- raise _ApplicationErrorStandin()
- return request
-
- def handle_unary_stream(self, request, servicer_context):
- if request == _EXCEPTION_REQUEST:
- raise _ApplicationErrorStandin()
- for _ in range(test_constants.STREAM_LENGTH):
- self._control.control()
- yield request
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
-
- def handle_stream_unary(self, request_iterator, servicer_context):
- if servicer_context is not None:
- servicer_context.invocation_metadata()
- self._control.control()
- response_elements = []
- for request in request_iterator:
- self._control.control()
- response_elements.append(request)
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- if _EXCEPTION_REQUEST in response_elements:
- raise _ApplicationErrorStandin()
- return b''.join(response_elements)
-
- def handle_stream_stream(self, request_iterator, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- for request in request_iterator:
- if request == _EXCEPTION_REQUEST:
- raise _ApplicationErrorStandin()
- self._control.control()
- yield request
- self._control.control()
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming,
- request_deserializer, response_serializer, unary_unary,
- unary_stream, stream_unary, stream_stream):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = request_deserializer
- self.response_serializer = response_serializer
- self.unary_unary = unary_unary
- self.unary_stream = unary_stream
- self.stream_unary = stream_unary
- self.stream_stream = stream_stream
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, handler):
- self._handler = handler
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False, None, None,
- self._handler.handle_unary_unary, None, None,
- None)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None,
- self._handler.handle_unary_stream, None, None)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None, None,
- self._handler.handle_stream_unary, None)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True, None, None, None, None, None,
- self._handler.handle_stream_stream)
- else:
- return None
-
-
-def _unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def _unary_stream_multi_callable(channel):
+# Copyright 2017 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.
+"""Test of gRPC Python interceptors."""
+
+import collections
+import itertools
+import threading
+import unittest
+import logging
+import os
+from concurrent import futures
+
+import grpc
+from grpc.framework.foundation import logging_pool
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+from tests.unit.framework.common import test_control
+
+_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
+_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
+_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
+_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
+
+_EXCEPTION_REQUEST = b'\x09\x0a'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+
+class _ApplicationErrorStandin(Exception):
+ pass
+
+
+class _Callback(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._value = None
+ self._called = False
+
+ def __call__(self, value):
+ with self._condition:
+ self._value = value
+ self._called = True
+ self._condition.notify_all()
+
+ def value(self):
+ with self._condition:
+ while not self._called:
+ self._condition.wait()
+ return self._value
+
+
+class _Handler(object):
+
+ def __init__(self, control):
+ self._control = control
+
+ def handle_unary_unary(self, request, servicer_context):
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+ if request == _EXCEPTION_REQUEST:
+ raise _ApplicationErrorStandin()
+ return request
+
+ def handle_unary_stream(self, request, servicer_context):
+ if request == _EXCEPTION_REQUEST:
+ raise _ApplicationErrorStandin()
+ for _ in range(test_constants.STREAM_LENGTH):
+ self._control.control()
+ yield request
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+
+ def handle_stream_unary(self, request_iterator, servicer_context):
+ if servicer_context is not None:
+ servicer_context.invocation_metadata()
+ self._control.control()
+ response_elements = []
+ for request in request_iterator:
+ self._control.control()
+ response_elements.append(request)
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+ if _EXCEPTION_REQUEST in response_elements:
+ raise _ApplicationErrorStandin()
+ return b''.join(response_elements)
+
+ def handle_stream_stream(self, request_iterator, servicer_context):
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+ for request in request_iterator:
+ if request == _EXCEPTION_REQUEST:
+ raise _ApplicationErrorStandin()
+ self._control.control()
+ yield request
+ self._control.control()
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, request_streaming, response_streaming,
+ request_deserializer, response_serializer, unary_unary,
+ unary_stream, stream_unary, stream_stream):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = request_deserializer
+ self.response_serializer = response_serializer
+ self.unary_unary = unary_unary
+ self.unary_stream = unary_stream
+ self.stream_unary = stream_unary
+ self.stream_stream = stream_stream
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(False, False, None, None,
+ self._handler.handle_unary_unary, None, None,
+ None)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
+ _SERIALIZE_RESPONSE, None,
+ self._handler.handle_unary_stream, None, None)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
+ _SERIALIZE_RESPONSE, None, None,
+ self._handler.handle_stream_unary, None)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(True, True, None, None, None, None, None,
+ self._handler.handle_stream_stream)
+ else:
+ return None
+
+
+def _unary_unary_multi_callable(channel):
+ return channel.unary_unary(_UNARY_UNARY)
+
+
+def _unary_stream_multi_callable(channel):
return channel.unary_stream(_UNARY_STREAM,
request_serializer=_SERIALIZE_REQUEST,
response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_unary_multi_callable(channel):
+
+
+def _stream_unary_multi_callable(channel):
return channel.stream_unary(_STREAM_UNARY,
request_serializer=_SERIALIZE_REQUEST,
response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-class _ClientCallDetails(
- collections.namedtuple(
- '_ClientCallDetails',
- ('method', 'timeout', 'metadata', 'credentials')),
- grpc.ClientCallDetails):
- pass
-
-
+
+
+def _stream_stream_multi_callable(channel):
+ return channel.stream_stream(_STREAM_STREAM)
+
+
+class _ClientCallDetails(
+ collections.namedtuple(
+ '_ClientCallDetails',
+ ('method', 'timeout', 'metadata', 'credentials')),
+ grpc.ClientCallDetails):
+ pass
+
+
class _GenericClientInterceptor(grpc.UnaryUnaryClientInterceptor,
grpc.UnaryStreamClientInterceptor,
grpc.StreamUnaryClientInterceptor,
grpc.StreamStreamClientInterceptor):
-
- def __init__(self, interceptor_function):
- self._fn = interceptor_function
-
- def intercept_unary_unary(self, continuation, client_call_details, request):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, iter((request,)), False, False)
- response = continuation(new_details, next(new_request_iterator))
- return postprocess(response) if postprocess else response
-
- def intercept_unary_stream(self, continuation, client_call_details,
- request):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, iter((request,)), False, True)
- response_it = continuation(new_details, new_request_iterator)
- return postprocess(response_it) if postprocess else response_it
-
- def intercept_stream_unary(self, continuation, client_call_details,
- request_iterator):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, request_iterator, True, False)
- response = continuation(new_details, next(new_request_iterator))
- return postprocess(response) if postprocess else response
-
- def intercept_stream_stream(self, continuation, client_call_details,
- request_iterator):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, request_iterator, True, True)
- response_it = continuation(new_details, new_request_iterator)
- return postprocess(response_it) if postprocess else response_it
-
-
+
+ def __init__(self, interceptor_function):
+ self._fn = interceptor_function
+
+ def intercept_unary_unary(self, continuation, client_call_details, request):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, iter((request,)), False, False)
+ response = continuation(new_details, next(new_request_iterator))
+ return postprocess(response) if postprocess else response
+
+ def intercept_unary_stream(self, continuation, client_call_details,
+ request):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, iter((request,)), False, True)
+ response_it = continuation(new_details, new_request_iterator)
+ return postprocess(response_it) if postprocess else response_it
+
+ def intercept_stream_unary(self, continuation, client_call_details,
+ request_iterator):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, request_iterator, True, False)
+ response = continuation(new_details, next(new_request_iterator))
+ return postprocess(response) if postprocess else response
+
+ def intercept_stream_stream(self, continuation, client_call_details,
+ request_iterator):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, request_iterator, True, True)
+ response_it = continuation(new_details, new_request_iterator)
+ return postprocess(response_it) if postprocess else response_it
+
+
class _LoggingInterceptor(grpc.ServerInterceptor,
grpc.UnaryUnaryClientInterceptor,
grpc.UnaryStreamClientInterceptor,
grpc.StreamUnaryClientInterceptor,
grpc.StreamStreamClientInterceptor):
-
- def __init__(self, tag, record):
- self.tag = tag
- self.record = record
-
- def intercept_service(self, continuation, handler_call_details):
- self.record.append(self.tag + ':intercept_service')
- return continuation(handler_call_details)
-
- def intercept_unary_unary(self, continuation, client_call_details, request):
- self.record.append(self.tag + ':intercept_unary_unary')
- result = continuation(client_call_details, request)
- assert isinstance(
- result,
- grpc.Call), '{} ({}) is not an instance of grpc.Call'.format(
- result, type(result))
- assert isinstance(
- result,
- grpc.Future), '{} ({}) is not an instance of grpc.Future'.format(
- result, type(result))
- return result
-
- def intercept_unary_stream(self, continuation, client_call_details,
- request):
- self.record.append(self.tag + ':intercept_unary_stream')
- return continuation(client_call_details, request)
-
- def intercept_stream_unary(self, continuation, client_call_details,
- request_iterator):
- self.record.append(self.tag + ':intercept_stream_unary')
- result = continuation(client_call_details, request_iterator)
- assert isinstance(
- result,
- grpc.Call), '{} is not an instance of grpc.Call'.format(result)
- assert isinstance(
- result,
- grpc.Future), '{} is not an instance of grpc.Future'.format(result)
- return result
-
- def intercept_stream_stream(self, continuation, client_call_details,
- request_iterator):
- self.record.append(self.tag + ':intercept_stream_stream')
- return continuation(client_call_details, request_iterator)
-
-
-class _DefectiveClientInterceptor(grpc.UnaryUnaryClientInterceptor):
-
- def intercept_unary_unary(self, ignored_continuation,
- ignored_client_call_details, ignored_request):
- raise test_control.Defect()
-
-
-def _wrap_request_iterator_stream_interceptor(wrapper):
-
- def intercept_call(client_call_details, request_iterator, request_streaming,
- ignored_response_streaming):
- if request_streaming:
- return client_call_details, wrapper(request_iterator), None
- else:
- return client_call_details, request_iterator, None
-
- return _GenericClientInterceptor(intercept_call)
-
-
-def _append_request_header_interceptor(header, value):
-
- def intercept_call(client_call_details, request_iterator,
- ignored_request_streaming, ignored_response_streaming):
- metadata = []
- if client_call_details.metadata:
- metadata = list(client_call_details.metadata)
- metadata.append((
- header,
- value,
- ))
- client_call_details = _ClientCallDetails(
- client_call_details.method, client_call_details.timeout, metadata,
- client_call_details.credentials)
- return client_call_details, request_iterator, None
-
- return _GenericClientInterceptor(intercept_call)
-
-
-class _GenericServerInterceptor(grpc.ServerInterceptor):
-
- def __init__(self, fn):
- self._fn = fn
-
- def intercept_service(self, continuation, handler_call_details):
- return self._fn(continuation, handler_call_details)
-
-
-def _filter_server_interceptor(condition, interceptor):
-
- def intercept_service(continuation, handler_call_details):
- if condition(handler_call_details):
- return interceptor.intercept_service(continuation,
- handler_call_details)
- return continuation(handler_call_details)
-
- return _GenericServerInterceptor(intercept_service)
-
-
-class InterceptorTest(unittest.TestCase):
-
- def setUp(self):
- self._control = test_control.PauseFailControl()
- self._handler = _Handler(self._control)
- self._server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
-
- self._record = []
- conditional_interceptor = _filter_server_interceptor(
- lambda x: ('secret', '42') in x.invocation_metadata,
- _LoggingInterceptor('s3', self._record))
-
+
+ def __init__(self, tag, record):
+ self.tag = tag
+ self.record = record
+
+ def intercept_service(self, continuation, handler_call_details):
+ self.record.append(self.tag + ':intercept_service')
+ return continuation(handler_call_details)
+
+ def intercept_unary_unary(self, continuation, client_call_details, request):
+ self.record.append(self.tag + ':intercept_unary_unary')
+ result = continuation(client_call_details, request)
+ assert isinstance(
+ result,
+ grpc.Call), '{} ({}) is not an instance of grpc.Call'.format(
+ result, type(result))
+ assert isinstance(
+ result,
+ grpc.Future), '{} ({}) is not an instance of grpc.Future'.format(
+ result, type(result))
+ return result
+
+ def intercept_unary_stream(self, continuation, client_call_details,
+ request):
+ self.record.append(self.tag + ':intercept_unary_stream')
+ return continuation(client_call_details, request)
+
+ def intercept_stream_unary(self, continuation, client_call_details,
+ request_iterator):
+ self.record.append(self.tag + ':intercept_stream_unary')
+ result = continuation(client_call_details, request_iterator)
+ assert isinstance(
+ result,
+ grpc.Call), '{} is not an instance of grpc.Call'.format(result)
+ assert isinstance(
+ result,
+ grpc.Future), '{} is not an instance of grpc.Future'.format(result)
+ return result
+
+ def intercept_stream_stream(self, continuation, client_call_details,
+ request_iterator):
+ self.record.append(self.tag + ':intercept_stream_stream')
+ return continuation(client_call_details, request_iterator)
+
+
+class _DefectiveClientInterceptor(grpc.UnaryUnaryClientInterceptor):
+
+ def intercept_unary_unary(self, ignored_continuation,
+ ignored_client_call_details, ignored_request):
+ raise test_control.Defect()
+
+
+def _wrap_request_iterator_stream_interceptor(wrapper):
+
+ def intercept_call(client_call_details, request_iterator, request_streaming,
+ ignored_response_streaming):
+ if request_streaming:
+ return client_call_details, wrapper(request_iterator), None
+ else:
+ return client_call_details, request_iterator, None
+
+ return _GenericClientInterceptor(intercept_call)
+
+
+def _append_request_header_interceptor(header, value):
+
+ def intercept_call(client_call_details, request_iterator,
+ ignored_request_streaming, ignored_response_streaming):
+ metadata = []
+ if client_call_details.metadata:
+ metadata = list(client_call_details.metadata)
+ metadata.append((
+ header,
+ value,
+ ))
+ client_call_details = _ClientCallDetails(
+ client_call_details.method, client_call_details.timeout, metadata,
+ client_call_details.credentials)
+ return client_call_details, request_iterator, None
+
+ return _GenericClientInterceptor(intercept_call)
+
+
+class _GenericServerInterceptor(grpc.ServerInterceptor):
+
+ def __init__(self, fn):
+ self._fn = fn
+
+ def intercept_service(self, continuation, handler_call_details):
+ return self._fn(continuation, handler_call_details)
+
+
+def _filter_server_interceptor(condition, interceptor):
+
+ def intercept_service(continuation, handler_call_details):
+ if condition(handler_call_details):
+ return interceptor.intercept_service(continuation,
+ handler_call_details)
+ return continuation(handler_call_details)
+
+ return _GenericServerInterceptor(intercept_service)
+
+
+class InterceptorTest(unittest.TestCase):
+
+ def setUp(self):
+ self._control = test_control.PauseFailControl()
+ self._handler = _Handler(self._control)
+ self._server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
+
+ self._record = []
+ conditional_interceptor = _filter_server_interceptor(
+ lambda x: ('secret', '42') in x.invocation_metadata,
+ _LoggingInterceptor('s3', self._record))
+
self._server = grpc.server(self._server_pool,
options=(('grpc.so_reuseport', 0),),
interceptors=(
@@ -358,351 +358,351 @@ class InterceptorTest(unittest.TestCase):
conditional_interceptor,
_LoggingInterceptor('s2', self._record),
))
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(None)
- self._server_pool.shutdown(wait=True)
- self._channel.close()
-
- def testTripleRequestMessagesClientInterceptor(self):
-
- def triple(request_iterator):
- while True:
- try:
- item = next(request_iterator)
- yield item
- yield item
- yield item
- except StopIteration:
- break
-
- interceptor = _wrap_request_iterator_stream_interceptor(triple)
- channel = grpc.intercept_channel(self._channel, interceptor)
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
-
- multi_callable = _stream_stream_multi_callable(channel)
- response_iterator = multi_callable(
- iter(requests),
- metadata=(
- ('test',
- 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
-
- responses = tuple(response_iterator)
- self.assertEqual(len(responses), 3 * test_constants.STREAM_LENGTH)
-
- multi_callable = _stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- iter(requests),
- metadata=(
- ('test',
- 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
-
- responses = tuple(response_iterator)
- self.assertEqual(len(responses), test_constants.STREAM_LENGTH)
-
- def testDefectiveClientInterceptor(self):
- interceptor = _DefectiveClientInterceptor()
- defective_channel = grpc.intercept_channel(self._channel, interceptor)
-
- request = b'\x07\x08'
-
- multi_callable = _unary_unary_multi_callable(defective_channel)
- call_future = multi_callable.future(
- request,
- metadata=(('test',
- 'InterceptedUnaryRequestBlockingUnaryResponse'),))
-
- self.assertIsNotNone(call_future.exception())
- self.assertEqual(call_future.code(), grpc.StatusCode.INTERNAL)
-
- def testInterceptedHeaderManipulationWithServerSideVerification(self):
- request = b'\x07\x08'
-
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._server.stop(None)
+ self._server_pool.shutdown(wait=True)
+ self._channel.close()
+
+ def testTripleRequestMessagesClientInterceptor(self):
+
+ def triple(request_iterator):
+ while True:
+ try:
+ item = next(request_iterator)
+ yield item
+ yield item
+ yield item
+ except StopIteration:
+ break
+
+ interceptor = _wrap_request_iterator_stream_interceptor(triple)
+ channel = grpc.intercept_channel(self._channel, interceptor)
+ requests = tuple(
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+
+ multi_callable = _stream_stream_multi_callable(channel)
+ response_iterator = multi_callable(
+ iter(requests),
+ metadata=(
+ ('test',
+ 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
+
+ responses = tuple(response_iterator)
+ self.assertEqual(len(responses), 3 * test_constants.STREAM_LENGTH)
+
+ multi_callable = _stream_stream_multi_callable(self._channel)
+ response_iterator = multi_callable(
+ iter(requests),
+ metadata=(
+ ('test',
+ 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
+
+ responses = tuple(response_iterator)
+ self.assertEqual(len(responses), test_constants.STREAM_LENGTH)
+
+ def testDefectiveClientInterceptor(self):
+ interceptor = _DefectiveClientInterceptor()
+ defective_channel = grpc.intercept_channel(self._channel, interceptor)
+
+ request = b'\x07\x08'
+
+ multi_callable = _unary_unary_multi_callable(defective_channel)
+ call_future = multi_callable.future(
+ request,
+ metadata=(('test',
+ 'InterceptedUnaryRequestBlockingUnaryResponse'),))
+
+ self.assertIsNotNone(call_future.exception())
+ self.assertEqual(call_future.code(), grpc.StatusCode.INTERNAL)
+
+ def testInterceptedHeaderManipulationWithServerSideVerification(self):
+ request = b'\x07\x08'
+
channel = grpc.intercept_channel(
self._channel, _append_request_header_interceptor('secret', '42'))
channel = grpc.intercept_channel(
channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- self._record[:] = []
-
- multi_callable = _unary_unary_multi_callable(channel)
- multi_callable.with_call(
- request,
- metadata=(
- ('test',
- 'InterceptedUnaryRequestBlockingUnaryResponseWithCall'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's3:intercept_service',
- 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestBlockingUnaryResponse(self):
- request = b'\x07\x08'
-
- self._record[:] = []
-
+
+ self._record[:] = []
+
+ multi_callable = _unary_unary_multi_callable(channel)
+ multi_callable.with_call(
+ request,
+ metadata=(
+ ('test',
+ 'InterceptedUnaryRequestBlockingUnaryResponseWithCall'),))
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
+ 's1:intercept_service', 's3:intercept_service',
+ 's2:intercept_service'
+ ])
+
+ def testInterceptedUnaryRequestBlockingUnaryResponse(self):
+ request = b'\x07\x08'
+
+ self._record[:] = []
+
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_unary_multi_callable(channel)
- multi_callable(
- request,
- metadata=(('test',
- 'InterceptedUnaryRequestBlockingUnaryResponse'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestBlockingUnaryResponseWithError(self):
- request = _EXCEPTION_REQUEST
-
- self._record[:] = []
-
+
+ multi_callable = _unary_unary_multi_callable(channel)
+ multi_callable(
+ request,
+ metadata=(('test',
+ 'InterceptedUnaryRequestBlockingUnaryResponse'),))
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedUnaryRequestBlockingUnaryResponseWithError(self):
+ request = _EXCEPTION_REQUEST
+
+ self._record[:] = []
+
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_unary_multi_callable(channel)
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(
- request,
- metadata=(('test',
- 'InterceptedUnaryRequestBlockingUnaryResponse'),))
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
- def testInterceptedUnaryRequestBlockingUnaryResponseWithCall(self):
- request = b'\x07\x08'
-
+
+ multi_callable = _unary_unary_multi_callable(channel)
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ multi_callable(
+ request,
+ metadata=(('test',
+ 'InterceptedUnaryRequestBlockingUnaryResponse'),))
+ exception = exception_context.exception
+ self.assertFalse(exception.cancelled())
+ self.assertFalse(exception.running())
+ self.assertTrue(exception.done())
+ with self.assertRaises(grpc.RpcError):
+ exception.result()
+ self.assertIsInstance(exception.exception(), grpc.RpcError)
+
+ def testInterceptedUnaryRequestBlockingUnaryResponseWithCall(self):
+ request = b'\x07\x08'
+
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- self._record[:] = []
-
- multi_callable = _unary_unary_multi_callable(channel)
- multi_callable.with_call(
- request,
- metadata=(
- ('test',
- 'InterceptedUnaryRequestBlockingUnaryResponseWithCall'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestFutureUnaryResponse(self):
- request = b'\x07\x08'
-
- self._record[:] = []
+
+ self._record[:] = []
+
+ multi_callable = _unary_unary_multi_callable(channel)
+ multi_callable.with_call(
+ request,
+ metadata=(
+ ('test',
+ 'InterceptedUnaryRequestBlockingUnaryResponseWithCall'),))
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedUnaryRequestFutureUnaryResponse(self):
+ request = b'\x07\x08'
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_unary_multi_callable(channel)
- response_future = multi_callable.future(
- request,
- metadata=(('test', 'InterceptedUnaryRequestFutureUnaryResponse'),))
- response_future.result()
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestStreamResponse(self):
- request = b'\x37\x58'
-
- self._record[:] = []
+
+ multi_callable = _unary_unary_multi_callable(channel)
+ response_future = multi_callable.future(
+ request,
+ metadata=(('test', 'InterceptedUnaryRequestFutureUnaryResponse'),))
+ response_future.result()
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedUnaryRequestStreamResponse(self):
+ request = b'\x37\x58'
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'InterceptedUnaryRequestStreamResponse'),))
- tuple(response_iterator)
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_stream', 'c2:intercept_unary_stream',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestStreamResponseWithError(self):
- request = _EXCEPTION_REQUEST
-
- self._record[:] = []
+
+ multi_callable = _unary_stream_multi_callable(channel)
+ response_iterator = multi_callable(
+ request,
+ metadata=(('test', 'InterceptedUnaryRequestStreamResponse'),))
+ tuple(response_iterator)
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_unary_stream', 'c2:intercept_unary_stream',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedUnaryRequestStreamResponseWithError(self):
+ request = _EXCEPTION_REQUEST
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'InterceptedUnaryRequestStreamResponse'),))
- with self.assertRaises(grpc.RpcError) as exception_context:
- tuple(response_iterator)
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
- def testInterceptedStreamRequestBlockingUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
+
+ multi_callable = _unary_stream_multi_callable(channel)
+ response_iterator = multi_callable(
+ request,
+ metadata=(('test', 'InterceptedUnaryRequestStreamResponse'),))
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ tuple(response_iterator)
+ exception = exception_context.exception
+ self.assertFalse(exception.cancelled())
+ self.assertFalse(exception.running())
+ self.assertTrue(exception.done())
+ with self.assertRaises(grpc.RpcError):
+ exception.result()
+ self.assertIsInstance(exception.exception(), grpc.RpcError)
+
+ def testInterceptedStreamRequestBlockingUnaryResponse(self):
+ requests = tuple(
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ request_iterator = iter(requests)
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- multi_callable(
- request_iterator,
- metadata=(('test',
- 'InterceptedStreamRequestBlockingUnaryResponse'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestBlockingUnaryResponseWithCall(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
+
+ multi_callable = _stream_unary_multi_callable(channel)
+ multi_callable(
+ request_iterator,
+ metadata=(('test',
+ 'InterceptedStreamRequestBlockingUnaryResponse'),))
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedStreamRequestBlockingUnaryResponseWithCall(self):
+ requests = tuple(
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ request_iterator = iter(requests)
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- multi_callable.with_call(
- request_iterator,
- metadata=(
- ('test',
- 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestFutureUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
+
+ multi_callable = _stream_unary_multi_callable(channel)
+ multi_callable.with_call(
+ request_iterator,
+ metadata=(
+ ('test',
+ 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedStreamRequestFutureUnaryResponse(self):
+ requests = tuple(
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ request_iterator = iter(requests)
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestFutureUnaryResponse'),))
- response_future.result()
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestFutureUnaryResponseWithError(self):
- requests = tuple(
- _EXCEPTION_REQUEST for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
+
+ multi_callable = _stream_unary_multi_callable(channel)
+ response_future = multi_callable.future(
+ request_iterator,
+ metadata=(('test', 'InterceptedStreamRequestFutureUnaryResponse'),))
+ response_future.result()
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedStreamRequestFutureUnaryResponseWithError(self):
+ requests = tuple(
+ _EXCEPTION_REQUEST for _ in range(test_constants.STREAM_LENGTH))
+ request_iterator = iter(requests)
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestFutureUnaryResponse'),))
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
- def testInterceptedStreamRequestStreamResponse(self):
- requests = tuple(
- b'\x77\x58' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
+
+ multi_callable = _stream_unary_multi_callable(channel)
+ response_future = multi_callable.future(
+ request_iterator,
+ metadata=(('test', 'InterceptedStreamRequestFutureUnaryResponse'),))
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ response_future.result()
+ exception = exception_context.exception
+ self.assertFalse(exception.cancelled())
+ self.assertFalse(exception.running())
+ self.assertTrue(exception.done())
+ with self.assertRaises(grpc.RpcError):
+ exception.result()
+ self.assertIsInstance(exception.exception(), grpc.RpcError)
+
+ def testInterceptedStreamRequestStreamResponse(self):
+ requests = tuple(
+ b'\x77\x58' for _ in range(test_constants.STREAM_LENGTH))
+ request_iterator = iter(requests)
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestStreamResponse'),))
- tuple(response_iterator)
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_stream', 'c2:intercept_stream_stream',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestStreamResponseWithError(self):
- requests = tuple(
- _EXCEPTION_REQUEST for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
+
+ multi_callable = _stream_stream_multi_callable(channel)
+ response_iterator = multi_callable(
+ request_iterator,
+ metadata=(('test', 'InterceptedStreamRequestStreamResponse'),))
+ tuple(response_iterator)
+
+ self.assertSequenceEqual(self._record, [
+ 'c1:intercept_stream_stream', 'c2:intercept_stream_stream',
+ 's1:intercept_service', 's2:intercept_service'
+ ])
+
+ def testInterceptedStreamRequestStreamResponseWithError(self):
+ requests = tuple(
+ _EXCEPTION_REQUEST for _ in range(test_constants.STREAM_LENGTH))
+ request_iterator = iter(requests)
+
+ self._record[:] = []
channel = grpc.intercept_channel(
self._channel, _LoggingInterceptor('c1', self._record),
_LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestStreamResponse'),))
- with self.assertRaises(grpc.RpcError) as exception_context:
- tuple(response_iterator)
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+ multi_callable = _stream_stream_multi_callable(channel)
+ response_iterator = multi_callable(
+ request_iterator,
+ metadata=(('test', 'InterceptedStreamRequestStreamResponse'),))
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ tuple(response_iterator)
+ exception = exception_context.exception
+ self.assertFalse(exception.cancelled())
+ self.assertFalse(exception.running())
+ self.assertTrue(exception.done())
+ with self.assertRaises(grpc.RpcError):
+ exception.result()
+ self.assertIsInstance(exception.exception(), grpc.RpcError)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py
index d1f1499d8c..70fbe81043 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py
@@ -1,140 +1,140 @@
-# Copyright 2016 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.
-"""Test of RPCs made against gRPC Python's application-layer API."""
-
-import unittest
-import logging
-
-import grpc
-
-from tests.unit.framework.common import test_constants
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-def _unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def _unary_stream_multi_callable(channel):
+# Copyright 2016 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.
+"""Test of RPCs made against gRPC Python's application-layer API."""
+
+import unittest
+import logging
+
+import grpc
+
+from tests.unit.framework.common import test_constants
+
+_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
+_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
+_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
+_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+
+def _unary_unary_multi_callable(channel):
+ return channel.unary_unary(_UNARY_UNARY)
+
+
+def _unary_stream_multi_callable(channel):
return channel.unary_stream(_UNARY_STREAM,
request_serializer=_SERIALIZE_REQUEST,
response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_unary_multi_callable(channel):
+
+
+def _stream_unary_multi_callable(channel):
return channel.stream_unary(_STREAM_UNARY,
request_serializer=_SERIALIZE_REQUEST,
response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-class InvalidMetadataTest(unittest.TestCase):
-
- def setUp(self):
- self._channel = grpc.insecure_channel('localhost:8080')
- self._unary_unary = _unary_unary_multi_callable(self._channel)
- self._unary_stream = _unary_stream_multi_callable(self._channel)
- self._stream_unary = _stream_unary_multi_callable(self._channel)
- self._stream_stream = _stream_stream_multi_callable(self._channel)
-
- def tearDown(self):
- self._channel.close()
-
- def testUnaryRequestBlockingUnaryResponse(self):
- request = b'\x07\x08'
- metadata = (('InVaLiD', 'UnaryRequestBlockingUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_unary(request, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testUnaryRequestBlockingUnaryResponseWithCall(self):
- request = b'\x07\x08'
- metadata = (('InVaLiD', 'UnaryRequestBlockingUnaryResponseWithCall'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_unary.with_call(request, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testUnaryRequestFutureUnaryResponse(self):
- request = b'\x07\x08'
- metadata = (('InVaLiD', 'UnaryRequestFutureUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_unary.future(request, metadata=metadata)
-
- def testUnaryRequestStreamResponse(self):
- request = b'\x37\x58'
- metadata = (('InVaLiD', 'UnaryRequestStreamResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_stream(request, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestBlockingUnaryResponse(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestBlockingUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._stream_unary(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestBlockingUnaryResponseWithCall(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestBlockingUnaryResponseWithCall'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- multi_callable = _stream_unary_multi_callable(self._channel)
- with self.assertRaises(ValueError) as exception_context:
- multi_callable.with_call(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestFutureUnaryResponse(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestFutureUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._stream_unary.future(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestStreamResponse(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestStreamResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._stream_stream(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testInvalidMetadata(self):
- self.assertRaises(TypeError, self._unary_unary, b'', metadata=42)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+
+def _stream_stream_multi_callable(channel):
+ return channel.stream_stream(_STREAM_STREAM)
+
+
+class InvalidMetadataTest(unittest.TestCase):
+
+ def setUp(self):
+ self._channel = grpc.insecure_channel('localhost:8080')
+ self._unary_unary = _unary_unary_multi_callable(self._channel)
+ self._unary_stream = _unary_stream_multi_callable(self._channel)
+ self._stream_unary = _stream_unary_multi_callable(self._channel)
+ self._stream_stream = _stream_stream_multi_callable(self._channel)
+
+ def tearDown(self):
+ self._channel.close()
+
+ def testUnaryRequestBlockingUnaryResponse(self):
+ request = b'\x07\x08'
+ metadata = (('InVaLiD', 'UnaryRequestBlockingUnaryResponse'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._unary_unary(request, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testUnaryRequestBlockingUnaryResponseWithCall(self):
+ request = b'\x07\x08'
+ metadata = (('InVaLiD', 'UnaryRequestBlockingUnaryResponseWithCall'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._unary_unary.with_call(request, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testUnaryRequestFutureUnaryResponse(self):
+ request = b'\x07\x08'
+ metadata = (('InVaLiD', 'UnaryRequestFutureUnaryResponse'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._unary_unary.future(request, metadata=metadata)
+
+ def testUnaryRequestStreamResponse(self):
+ request = b'\x37\x58'
+ metadata = (('InVaLiD', 'UnaryRequestStreamResponse'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._unary_stream(request, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testStreamRequestBlockingUnaryResponse(self):
+ request_iterator = (
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ metadata = (('InVaLiD', 'StreamRequestBlockingUnaryResponse'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._stream_unary(request_iterator, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testStreamRequestBlockingUnaryResponseWithCall(self):
+ request_iterator = (
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ metadata = (('InVaLiD', 'StreamRequestBlockingUnaryResponseWithCall'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ multi_callable = _stream_unary_multi_callable(self._channel)
+ with self.assertRaises(ValueError) as exception_context:
+ multi_callable.with_call(request_iterator, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testStreamRequestFutureUnaryResponse(self):
+ request_iterator = (
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ metadata = (('InVaLiD', 'StreamRequestFutureUnaryResponse'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._stream_unary.future(request_iterator, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testStreamRequestStreamResponse(self):
+ request_iterator = (
+ b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
+ metadata = (('InVaLiD', 'StreamRequestStreamResponse'),)
+ expected_error_details = "metadata was invalid: %s" % metadata
+ with self.assertRaises(ValueError) as exception_context:
+ self._stream_stream(request_iterator, metadata=metadata)
+ self.assertIn(expected_error_details, str(exception_context.exception))
+
+ def testInvalidMetadata(self):
+ self.assertRaises(TypeError, self._unary_unary, b'', metadata=42)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py
index a0208b51df..e926a77569 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py
@@ -1,266 +1,266 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import unittest
-import logging
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-_DEFECTIVE_GENERIC_RPC_HANDLER = '/test/DefectiveGenericRpcHandler'
-
-
-class _Handler(object):
-
- def __init__(self, control):
- self._control = control
-
- def handle_unary_unary(self, request, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- return request
-
- def handle_unary_stream(self, request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- self._control.control()
- yield request
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
-
- def handle_stream_unary(self, request_iterator, servicer_context):
- if servicer_context is not None:
- servicer_context.invocation_metadata()
- self._control.control()
- response_elements = []
- for request in request_iterator:
- self._control.control()
- response_elements.append(request)
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- return b''.join(response_elements)
-
- def handle_stream_stream(self, request_iterator, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- for request in request_iterator:
- self._control.control()
- yield request
- self._control.control()
-
- def defective_generic_rpc_handler(self):
- raise test_control.Defect()
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming,
- request_deserializer, response_serializer, unary_unary,
- unary_stream, stream_unary, stream_stream):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = request_deserializer
- self.response_serializer = response_serializer
- self.unary_unary = unary_unary
- self.unary_stream = unary_stream
- self.stream_unary = stream_unary
- self.stream_stream = stream_stream
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, handler):
- self._handler = handler
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False, None, None,
- self._handler.handle_unary_unary, None, None,
- None)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None,
- self._handler.handle_unary_stream, None, None)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None, None,
- self._handler.handle_stream_unary, None)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True, None, None, None, None, None,
- self._handler.handle_stream_stream)
- elif handler_call_details.method == _DEFECTIVE_GENERIC_RPC_HANDLER:
- return self._handler.defective_generic_rpc_handler()
- else:
- return None
-
-
-class FailAfterFewIterationsCounter(object):
-
- def __init__(self, high, bytestring):
- self._current = 0
- self._high = high
- self._bytestring = bytestring
-
- def __iter__(self):
- return self
-
- def __next__(self):
- if self._current >= self._high:
- raise test_control.Defect()
- else:
- self._current += 1
- return self._bytestring
-
- next = __next__
-
-
-def _unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def _unary_stream_multi_callable(channel):
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+import logging
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+from tests.unit.framework.common import test_control
+
+_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
+_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
+_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
+_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+_DEFECTIVE_GENERIC_RPC_HANDLER = '/test/DefectiveGenericRpcHandler'
+
+
+class _Handler(object):
+
+ def __init__(self, control):
+ self._control = control
+
+ def handle_unary_unary(self, request, servicer_context):
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+ return request
+
+ def handle_unary_stream(self, request, servicer_context):
+ for _ in range(test_constants.STREAM_LENGTH):
+ self._control.control()
+ yield request
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+
+ def handle_stream_unary(self, request_iterator, servicer_context):
+ if servicer_context is not None:
+ servicer_context.invocation_metadata()
+ self._control.control()
+ response_elements = []
+ for request in request_iterator:
+ self._control.control()
+ response_elements.append(request)
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+ return b''.join(response_elements)
+
+ def handle_stream_stream(self, request_iterator, servicer_context):
+ self._control.control()
+ if servicer_context is not None:
+ servicer_context.set_trailing_metadata(((
+ 'testkey',
+ 'testvalue',
+ ),))
+ for request in request_iterator:
+ self._control.control()
+ yield request
+ self._control.control()
+
+ def defective_generic_rpc_handler(self):
+ raise test_control.Defect()
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, request_streaming, response_streaming,
+ request_deserializer, response_serializer, unary_unary,
+ unary_stream, stream_unary, stream_stream):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = request_deserializer
+ self.response_serializer = response_serializer
+ self.unary_unary = unary_unary
+ self.unary_stream = unary_stream
+ self.stream_unary = stream_unary
+ self.stream_stream = stream_stream
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(False, False, None, None,
+ self._handler.handle_unary_unary, None, None,
+ None)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
+ _SERIALIZE_RESPONSE, None,
+ self._handler.handle_unary_stream, None, None)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
+ _SERIALIZE_RESPONSE, None, None,
+ self._handler.handle_stream_unary, None)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(True, True, None, None, None, None, None,
+ self._handler.handle_stream_stream)
+ elif handler_call_details.method == _DEFECTIVE_GENERIC_RPC_HANDLER:
+ return self._handler.defective_generic_rpc_handler()
+ else:
+ return None
+
+
+class FailAfterFewIterationsCounter(object):
+
+ def __init__(self, high, bytestring):
+ self._current = 0
+ self._high = high
+ self._bytestring = bytestring
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if self._current >= self._high:
+ raise test_control.Defect()
+ else:
+ self._current += 1
+ return self._bytestring
+
+ next = __next__
+
+
+def _unary_unary_multi_callable(channel):
+ return channel.unary_unary(_UNARY_UNARY)
+
+
+def _unary_stream_multi_callable(channel):
return channel.unary_stream(_UNARY_STREAM,
request_serializer=_SERIALIZE_REQUEST,
response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_unary_multi_callable(channel):
+
+
+def _stream_unary_multi_callable(channel):
return channel.stream_unary(_STREAM_UNARY,
request_serializer=_SERIALIZE_REQUEST,
response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-def _defective_handler_multi_callable(channel):
- return channel.unary_unary(_DEFECTIVE_GENERIC_RPC_HANDLER)
-
-
-class InvocationDefectsTest(unittest.TestCase):
+
+
+def _stream_stream_multi_callable(channel):
+ return channel.stream_stream(_STREAM_STREAM)
+
+
+def _defective_handler_multi_callable(channel):
+ return channel.unary_unary(_DEFECTIVE_GENERIC_RPC_HANDLER)
+
+
+class InvocationDefectsTest(unittest.TestCase):
"""Tests the handling of exception-raising user code on the client-side."""
-
- def setUp(self):
- self._control = test_control.PauseFailControl()
- self._handler = _Handler(self._control)
-
- self._server = test_common.test_server()
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testIterableStreamRequestBlockingUnaryResponse(self):
+
+ def setUp(self):
+ self._control = test_control.PauseFailControl()
+ self._handler = _Handler(self._control)
+
+ self._server = test_common.test_server()
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._server.stop(0)
+ self._channel.close()
+
+ def testIterableStreamRequestBlockingUnaryResponse(self):
requests = object()
- multi_callable = _stream_unary_multi_callable(self._channel)
-
+ multi_callable = _stream_unary_multi_callable(self._channel)
+
with self.assertRaises(grpc.RpcError) as exception_context:
multi_callable(
- requests,
- metadata=(('test',
- 'IterableStreamRequestBlockingUnaryResponse'),))
-
+ requests,
+ metadata=(('test',
+ 'IterableStreamRequestBlockingUnaryResponse'),))
+
self.assertIs(grpc.StatusCode.UNKNOWN,
exception_context.exception.code())
- def testIterableStreamRequestFutureUnaryResponse(self):
+ def testIterableStreamRequestFutureUnaryResponse(self):
requests = object()
- multi_callable = _stream_unary_multi_callable(self._channel)
- response_future = multi_callable.future(
- requests,
- metadata=(('test', 'IterableStreamRequestFutureUnaryResponse'),))
-
+ multi_callable = _stream_unary_multi_callable(self._channel)
+ response_future = multi_callable.future(
+ requests,
+ metadata=(('test', 'IterableStreamRequestFutureUnaryResponse'),))
+
with self.assertRaises(grpc.RpcError) as exception_context:
response_future.result()
-
+
self.assertIs(grpc.StatusCode.UNKNOWN,
exception_context.exception.code())
- def testIterableStreamRequestStreamResponse(self):
+ def testIterableStreamRequestStreamResponse(self):
requests = object()
- multi_callable = _stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- requests,
- metadata=(('test', 'IterableStreamRequestStreamResponse'),))
-
+ multi_callable = _stream_stream_multi_callable(self._channel)
+ response_iterator = multi_callable(
+ requests,
+ metadata=(('test', 'IterableStreamRequestStreamResponse'),))
+
with self.assertRaises(grpc.RpcError) as exception_context:
- next(response_iterator)
-
+ next(response_iterator)
+
self.assertIs(grpc.StatusCode.UNKNOWN,
exception_context.exception.code())
- def testIteratorStreamRequestStreamResponse(self):
- requests_iterator = FailAfterFewIterationsCounter(
- test_constants.STREAM_LENGTH // 2, b'\x07\x08')
- multi_callable = _stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- requests_iterator,
- metadata=(('test', 'IteratorStreamRequestStreamResponse'),))
-
+ def testIteratorStreamRequestStreamResponse(self):
+ requests_iterator = FailAfterFewIterationsCounter(
+ test_constants.STREAM_LENGTH // 2, b'\x07\x08')
+ multi_callable = _stream_stream_multi_callable(self._channel)
+ response_iterator = multi_callable(
+ requests_iterator,
+ metadata=(('test', 'IteratorStreamRequestStreamResponse'),))
+
with self.assertRaises(grpc.RpcError) as exception_context:
- for _ in range(test_constants.STREAM_LENGTH // 2 + 1):
- next(response_iterator)
-
+ for _ in range(test_constants.STREAM_LENGTH // 2 + 1):
+ next(response_iterator)
+
self.assertIs(grpc.StatusCode.UNKNOWN,
exception_context.exception.code())
- def testDefectiveGenericRpcHandlerUnaryResponse(self):
- request = b'\x07\x08'
- multi_callable = _defective_handler_multi_callable(self._channel)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
+ def testDefectiveGenericRpcHandlerUnaryResponse(self):
+ request = b'\x07\x08'
+ multi_callable = _defective_handler_multi_callable(self._channel)
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
multi_callable(request,
metadata=(('test',
'DefectiveGenericRpcHandlerUnary'),))
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+ self.assertIs(grpc.StatusCode.UNKNOWN,
+ exception_context.exception.code())
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py
index cd1f71dbee..b85353ab49 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py
@@ -1,77 +1,77 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of RPCs made using local credentials."""
-
-import unittest
-import os
-from concurrent.futures import ThreadPoolExecutor
-import grpc
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- return grpc.unary_unary_rpc_method_handler(
- lambda request, unused_context: request)
-
-
-class LocalCredentialsTest(unittest.TestCase):
-
- def _create_server(self):
- server = grpc.server(ThreadPoolExecutor())
- server.add_generic_rpc_handlers((_GenericHandler(),))
- return server
-
- @unittest.skipIf(os.name == 'nt',
- 'TODO(https://github.com/grpc/grpc/issues/20078)')
- def test_local_tcp(self):
- server_addr = 'localhost:{}'
- channel_creds = grpc.local_channel_credentials(
- grpc.LocalConnectionType.LOCAL_TCP)
- server_creds = grpc.local_server_credentials(
- grpc.LocalConnectionType.LOCAL_TCP)
-
- server = self._create_server()
- port = server.add_secure_port(server_addr.format(0), server_creds)
- server.start()
- with grpc.secure_channel(server_addr.format(port),
- channel_creds) as channel:
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Test of RPCs made using local credentials."""
+
+import unittest
+import os
+from concurrent.futures import ThreadPoolExecutor
+import grpc
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ return grpc.unary_unary_rpc_method_handler(
+ lambda request, unused_context: request)
+
+
+class LocalCredentialsTest(unittest.TestCase):
+
+ def _create_server(self):
+ server = grpc.server(ThreadPoolExecutor())
+ server.add_generic_rpc_handlers((_GenericHandler(),))
+ return server
+
+ @unittest.skipIf(os.name == 'nt',
+ 'TODO(https://github.com/grpc/grpc/issues/20078)')
+ def test_local_tcp(self):
+ server_addr = 'localhost:{}'
+ channel_creds = grpc.local_channel_credentials(
+ grpc.LocalConnectionType.LOCAL_TCP)
+ server_creds = grpc.local_server_credentials(
+ grpc.LocalConnectionType.LOCAL_TCP)
+
+ server = self._create_server()
+ port = server.add_secure_port(server_addr.format(0), server_creds)
+ server.start()
+ with grpc.secure_channel(server_addr.format(port),
+ channel_creds) as channel:
self.assertEqual(
b'abc',
channel.unary_unary('/test/method')(b'abc',
wait_for_ready=True))
- server.stop(None)
-
- @unittest.skipIf(os.name == 'nt',
- 'Unix Domain Socket is not supported on Windows')
- def test_uds(self):
- server_addr = 'unix:/tmp/grpc_fullstack_test'
- channel_creds = grpc.local_channel_credentials(
- grpc.LocalConnectionType.UDS)
- server_creds = grpc.local_server_credentials(
- grpc.LocalConnectionType.UDS)
-
- server = self._create_server()
- server.add_secure_port(server_addr, server_creds)
- server.start()
- with grpc.secure_channel(server_addr, channel_creds) as channel:
+ server.stop(None)
+
+ @unittest.skipIf(os.name == 'nt',
+ 'Unix Domain Socket is not supported on Windows')
+ def test_uds(self):
+ server_addr = 'unix:/tmp/grpc_fullstack_test'
+ channel_creds = grpc.local_channel_credentials(
+ grpc.LocalConnectionType.UDS)
+ server_creds = grpc.local_server_credentials(
+ grpc.LocalConnectionType.UDS)
+
+ server = self._create_server()
+ server.add_secure_port(server_addr, server_creds)
+ server.start()
+ with grpc.secure_channel(server_addr, channel_creds) as channel:
self.assertEqual(
b'abc',
channel.unary_unary('/test/method')(b'abc',
wait_for_ready=True))
- server.stop(None)
-
-
-if __name__ == '__main__':
- unittest.main()
+ server.stop(None)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py
index 1304bb5587..8b83e2d784 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py
@@ -1,103 +1,103 @@
-# Copyright 2018 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.
-"""Test of gRPC Python's interaction with the python logging module"""
-
-import unittest
-import logging
-import grpc
-import os
-import subprocess
-import sys
-
-INTERPRETER = sys.executable
-
-
-class LoggingTest(unittest.TestCase):
-
- def test_logger_not_occupied(self):
- script = """if True:
- import logging
-
- import grpc
-
- if len(logging.getLogger().handlers) != 0:
- raise Exception('expected 0 logging handlers')
-
- """
- self._verifyScriptSucceeds(script)
-
- def test_handler_found(self):
- script = """if True:
- import logging
-
- import grpc
- """
- out, err = self._verifyScriptSucceeds(script)
- self.assertEqual(0, len(err), 'unexpected output to stderr')
-
- def test_can_configure_logger(self):
- script = """if True:
- import logging
- import six
-
- import grpc
-
-
- intended_stream = six.StringIO()
- logging.basicConfig(stream=intended_stream)
-
- if len(logging.getLogger().handlers) != 1:
- raise Exception('expected 1 logging handler')
-
- if logging.getLogger().handlers[0].stream is not intended_stream:
- raise Exception('wrong handler stream')
-
- """
- self._verifyScriptSucceeds(script)
-
- def test_grpc_logger(self):
- script = """if True:
- import logging
-
- import grpc
-
- if "grpc" not in logging.Logger.manager.loggerDict:
- raise Exception('grpc logger not found')
-
- root_logger = logging.getLogger("grpc")
- if len(root_logger.handlers) != 1:
- raise Exception('expected 1 root logger handler')
- if not isinstance(root_logger.handlers[0], logging.NullHandler):
- raise Exception('expected logging.NullHandler')
-
- """
- self._verifyScriptSucceeds(script)
-
- def _verifyScriptSucceeds(self, script):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
+# Copyright 2018 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.
+"""Test of gRPC Python's interaction with the python logging module"""
+
+import unittest
+import logging
+import grpc
+import os
+import subprocess
+import sys
+
+INTERPRETER = sys.executable
+
+
+class LoggingTest(unittest.TestCase):
+
+ def test_logger_not_occupied(self):
+ script = """if True:
+ import logging
+
+ import grpc
+
+ if len(logging.getLogger().handlers) != 0:
+ raise Exception('expected 0 logging handlers')
+
+ """
+ self._verifyScriptSucceeds(script)
+
+ def test_handler_found(self):
+ script = """if True:
+ import logging
+
+ import grpc
+ """
+ out, err = self._verifyScriptSucceeds(script)
+ self.assertEqual(0, len(err), 'unexpected output to stderr')
+
+ def test_can_configure_logger(self):
+ script = """if True:
+ import logging
+ import six
+
+ import grpc
+
+
+ intended_stream = six.StringIO()
+ logging.basicConfig(stream=intended_stream)
+
+ if len(logging.getLogger().handlers) != 1:
+ raise Exception('expected 1 logging handler')
+
+ if logging.getLogger().handlers[0].stream is not intended_stream:
+ raise Exception('wrong handler stream')
+
+ """
+ self._verifyScriptSucceeds(script)
+
+ def test_grpc_logger(self):
+ script = """if True:
+ import logging
+
+ import grpc
+
+ if "grpc" not in logging.Logger.manager.loggerDict:
+ raise Exception('grpc logger not found')
+
+ root_logger = logging.getLogger("grpc")
+ if len(root_logger.handlers) != 1:
+ raise Exception('expected 1 root logger handler')
+ if not isinstance(root_logger.handlers[0], logging.NullHandler):
+ raise Exception('expected logging.NullHandler')
+
+ """
+ self._verifyScriptSucceeds(script)
+
+ def _verifyScriptSucceeds(self, script):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
process = subprocess.Popen([INTERPRETER, '-c', script],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env)
- out, err = process.communicate()
- self.assertEqual(
- 0, process.returncode,
- 'process failed with exit code %d (stdout: %s, stderr: %s)' %
- (process.returncode, out, err))
- return out, err
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ out, err = process.communicate()
+ self.assertEqual(
+ 0, process.returncode,
+ 'process failed with exit code %d (stdout: %s, stderr: %s)' %
+ (process.returncode, out, err))
+ return out, err
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py
index 5b06eb2bfe..801d15937d 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py
@@ -1,213 +1,213 @@
-# Copyright 2016 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.
-"""Tests application-provided metadata, status code, and details."""
-
-import threading
-import unittest
-import logging
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZED_REQUEST = b'\x46\x47\x48'
-_SERIALIZED_RESPONSE = b'\x49\x50\x51'
-
-_REQUEST_SERIALIZER = lambda unused_request: _SERIALIZED_REQUEST
-_REQUEST_DESERIALIZER = lambda unused_serialized_request: object()
-_RESPONSE_SERIALIZER = lambda unused_response: _SERIALIZED_RESPONSE
-_RESPONSE_DESERIALIZER = lambda unused_serialized_response: object()
-
-_SERVICE = 'test.TestService'
-_UNARY_UNARY = 'UnaryUnary'
-_UNARY_STREAM = 'UnaryStream'
-_STREAM_UNARY = 'StreamUnary'
-_STREAM_STREAM = 'StreamStream'
-
-_CLIENT_METADATA = (('client-md-key', 'client-md-key'), ('client-md-key-bin',
- b'\x00\x01'))
-
-_SERVER_INITIAL_METADATA = (('server-initial-md-key',
- 'server-initial-md-value'),
- ('server-initial-md-key-bin', b'\x00\x02'))
-
-_SERVER_TRAILING_METADATA = (('server-trailing-md-key',
- 'server-trailing-md-value'),
- ('server-trailing-md-key-bin', b'\x00\x03'))
-
-_NON_OK_CODE = grpc.StatusCode.NOT_FOUND
-_DETAILS = 'Test details!'
-
-# calling abort should always fail an RPC, even for "invalid" codes
-_ABORT_CODES = (_NON_OK_CODE, 3, grpc.StatusCode.OK)
-_EXPECTED_CLIENT_CODES = (_NON_OK_CODE, grpc.StatusCode.UNKNOWN,
- grpc.StatusCode.UNKNOWN)
-_EXPECTED_DETAILS = (_DETAILS, _DETAILS, '')
-
-
-class _Servicer(object):
-
- def __init__(self):
- self._lock = threading.Lock()
- self._abort_call = False
- self._code = None
- self._details = None
- self._exception = False
- self._return_none = False
- self._received_client_metadata = None
-
- def unary_unary(self, request, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- if self._exception:
- raise test_control.Defect()
- else:
- return None if self._return_none else object()
-
- def unary_stream(self, request, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- for _ in range(test_constants.STREAM_LENGTH // 2):
- yield _SERIALIZED_RESPONSE
- if self._exception:
- raise test_control.Defect()
-
- def stream_unary(self, request_iterator, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- # TODO(https://github.com/grpc/grpc/issues/6891): just ignore the
- # request iterator.
- list(request_iterator)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- if self._exception:
- raise test_control.Defect()
- else:
- return None if self._return_none else _SERIALIZED_RESPONSE
-
- def stream_stream(self, request_iterator, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- # TODO(https://github.com/grpc/grpc/issues/6891): just ignore the
- # request iterator.
- list(request_iterator)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- for _ in range(test_constants.STREAM_LENGTH // 3):
- yield object()
- if self._exception:
- raise test_control.Defect()
-
- def set_abort_call(self):
- with self._lock:
- self._abort_call = True
-
- def set_code(self, code):
- with self._lock:
- self._code = code
-
- def set_details(self, details):
- with self._lock:
- self._details = details
-
- def set_exception(self):
- with self._lock:
- self._exception = True
-
- def set_return_none(self):
- with self._lock:
- self._return_none = True
-
- def received_client_metadata(self):
- with self._lock:
- return self._received_client_metadata
-
-
-def _generic_handler(servicer):
- method_handlers = {
- _UNARY_UNARY:
+# Copyright 2016 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.
+"""Tests application-provided metadata, status code, and details."""
+
+import threading
+import unittest
+import logging
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+from tests.unit.framework.common import test_control
+
+_SERIALIZED_REQUEST = b'\x46\x47\x48'
+_SERIALIZED_RESPONSE = b'\x49\x50\x51'
+
+_REQUEST_SERIALIZER = lambda unused_request: _SERIALIZED_REQUEST
+_REQUEST_DESERIALIZER = lambda unused_serialized_request: object()
+_RESPONSE_SERIALIZER = lambda unused_response: _SERIALIZED_RESPONSE
+_RESPONSE_DESERIALIZER = lambda unused_serialized_response: object()
+
+_SERVICE = 'test.TestService'
+_UNARY_UNARY = 'UnaryUnary'
+_UNARY_STREAM = 'UnaryStream'
+_STREAM_UNARY = 'StreamUnary'
+_STREAM_STREAM = 'StreamStream'
+
+_CLIENT_METADATA = (('client-md-key', 'client-md-key'), ('client-md-key-bin',
+ b'\x00\x01'))
+
+_SERVER_INITIAL_METADATA = (('server-initial-md-key',
+ 'server-initial-md-value'),
+ ('server-initial-md-key-bin', b'\x00\x02'))
+
+_SERVER_TRAILING_METADATA = (('server-trailing-md-key',
+ 'server-trailing-md-value'),
+ ('server-trailing-md-key-bin', b'\x00\x03'))
+
+_NON_OK_CODE = grpc.StatusCode.NOT_FOUND
+_DETAILS = 'Test details!'
+
+# calling abort should always fail an RPC, even for "invalid" codes
+_ABORT_CODES = (_NON_OK_CODE, 3, grpc.StatusCode.OK)
+_EXPECTED_CLIENT_CODES = (_NON_OK_CODE, grpc.StatusCode.UNKNOWN,
+ grpc.StatusCode.UNKNOWN)
+_EXPECTED_DETAILS = (_DETAILS, _DETAILS, '')
+
+
+class _Servicer(object):
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._abort_call = False
+ self._code = None
+ self._details = None
+ self._exception = False
+ self._return_none = False
+ self._received_client_metadata = None
+
+ def unary_unary(self, request, context):
+ with self._lock:
+ self._received_client_metadata = context.invocation_metadata()
+ context.send_initial_metadata(_SERVER_INITIAL_METADATA)
+ context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
+ if self._abort_call:
+ context.abort(self._code, self._details)
+ else:
+ if self._code is not None:
+ context.set_code(self._code)
+ if self._details is not None:
+ context.set_details(self._details)
+ if self._exception:
+ raise test_control.Defect()
+ else:
+ return None if self._return_none else object()
+
+ def unary_stream(self, request, context):
+ with self._lock:
+ self._received_client_metadata = context.invocation_metadata()
+ context.send_initial_metadata(_SERVER_INITIAL_METADATA)
+ context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
+ if self._abort_call:
+ context.abort(self._code, self._details)
+ else:
+ if self._code is not None:
+ context.set_code(self._code)
+ if self._details is not None:
+ context.set_details(self._details)
+ for _ in range(test_constants.STREAM_LENGTH // 2):
+ yield _SERIALIZED_RESPONSE
+ if self._exception:
+ raise test_control.Defect()
+
+ def stream_unary(self, request_iterator, context):
+ with self._lock:
+ self._received_client_metadata = context.invocation_metadata()
+ context.send_initial_metadata(_SERVER_INITIAL_METADATA)
+ context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
+ # TODO(https://github.com/grpc/grpc/issues/6891): just ignore the
+ # request iterator.
+ list(request_iterator)
+ if self._abort_call:
+ context.abort(self._code, self._details)
+ else:
+ if self._code is not None:
+ context.set_code(self._code)
+ if self._details is not None:
+ context.set_details(self._details)
+ if self._exception:
+ raise test_control.Defect()
+ else:
+ return None if self._return_none else _SERIALIZED_RESPONSE
+
+ def stream_stream(self, request_iterator, context):
+ with self._lock:
+ self._received_client_metadata = context.invocation_metadata()
+ context.send_initial_metadata(_SERVER_INITIAL_METADATA)
+ context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
+ # TODO(https://github.com/grpc/grpc/issues/6891): just ignore the
+ # request iterator.
+ list(request_iterator)
+ if self._abort_call:
+ context.abort(self._code, self._details)
+ else:
+ if self._code is not None:
+ context.set_code(self._code)
+ if self._details is not None:
+ context.set_details(self._details)
+ for _ in range(test_constants.STREAM_LENGTH // 3):
+ yield object()
+ if self._exception:
+ raise test_control.Defect()
+
+ def set_abort_call(self):
+ with self._lock:
+ self._abort_call = True
+
+ def set_code(self, code):
+ with self._lock:
+ self._code = code
+
+ def set_details(self, details):
+ with self._lock:
+ self._details = details
+
+ def set_exception(self):
+ with self._lock:
+ self._exception = True
+
+ def set_return_none(self):
+ with self._lock:
+ self._return_none = True
+
+ def received_client_metadata(self):
+ with self._lock:
+ return self._received_client_metadata
+
+
+def _generic_handler(servicer):
+ method_handlers = {
+ _UNARY_UNARY:
grpc.unary_unary_rpc_method_handler(
servicer.unary_unary,
request_deserializer=_REQUEST_DESERIALIZER,
response_serializer=_RESPONSE_SERIALIZER),
- _UNARY_STREAM:
+ _UNARY_STREAM:
grpc.unary_stream_rpc_method_handler(servicer.unary_stream),
- _STREAM_UNARY:
+ _STREAM_UNARY:
grpc.stream_unary_rpc_method_handler(servicer.stream_unary),
- _STREAM_STREAM:
+ _STREAM_STREAM:
grpc.stream_stream_rpc_method_handler(
servicer.stream_stream,
request_deserializer=_REQUEST_DESERIALIZER,
response_serializer=_RESPONSE_SERIALIZER),
- }
- return grpc.method_handlers_generic_handler(_SERVICE, method_handlers)
-
-
-class MetadataCodeDetailsTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _Servicer()
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers(
- (_generic_handler(self._servicer),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:{}'.format(port))
- self._unary_unary = self._channel.unary_unary(
- '/'.join((
- '',
- _SERVICE,
- _UNARY_UNARY,
- )),
- request_serializer=_REQUEST_SERIALIZER,
- response_deserializer=_RESPONSE_DESERIALIZER,
- )
+ }
+ return grpc.method_handlers_generic_handler(_SERVICE, method_handlers)
+
+
+class MetadataCodeDetailsTest(unittest.TestCase):
+
+ def setUp(self):
+ self._servicer = _Servicer()
+ self._server = test_common.test_server()
+ self._server.add_generic_rpc_handlers(
+ (_generic_handler(self._servicer),))
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+
+ self._channel = grpc.insecure_channel('localhost:{}'.format(port))
+ self._unary_unary = self._channel.unary_unary(
+ '/'.join((
+ '',
+ _SERVICE,
+ _UNARY_UNARY,
+ )),
+ request_serializer=_REQUEST_SERIALIZER,
+ response_deserializer=_RESPONSE_DESERIALIZER,
+ )
self._unary_stream = self._channel.unary_stream(
'/'.join((
'',
@@ -220,444 +220,444 @@ class MetadataCodeDetailsTest(unittest.TestCase):
_SERVICE,
_STREAM_UNARY,
)),)
- self._stream_stream = self._channel.stream_stream(
- '/'.join((
- '',
- _SERVICE,
- _STREAM_STREAM,
- )),
- request_serializer=_REQUEST_SERIALIZER,
- response_deserializer=_RESPONSE_DESERIALIZER,
- )
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def testSuccessfulUnaryUnary(self):
- self._servicer.set_details(_DETAILS)
-
- unused_response, call = self._unary_unary.with_call(
- object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_TRAILING_METADATA,
- call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, call.code())
-
- def testSuccessfulUnaryStream(self):
- self._servicer.set_details(_DETAILS)
-
+ self._stream_stream = self._channel.stream_stream(
+ '/'.join((
+ '',
+ _SERVICE,
+ _STREAM_STREAM,
+ )),
+ request_serializer=_REQUEST_SERIALIZER,
+ response_deserializer=_RESPONSE_DESERIALIZER,
+ )
+
+ def tearDown(self):
+ self._server.stop(None)
+ self._channel.close()
+
+ def testSuccessfulUnaryUnary(self):
+ self._servicer.set_details(_DETAILS)
+
+ unused_response, call = self._unary_unary.with_call(
+ object(), metadata=_CLIENT_METADATA)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ call.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_TRAILING_METADATA,
+ call.trailing_metadata()))
+ self.assertIs(grpc.StatusCode.OK, call.code())
+
+ def testSuccessfulUnaryStream(self):
+ self._servicer.set_details(_DETAILS)
+
response_iterator_call = self._unary_stream(_SERIALIZED_REQUEST,
metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, response_iterator_call.code())
-
- def testSuccessfulStreamUnary(self):
- self._servicer.set_details(_DETAILS)
-
- unused_response, call = self._stream_unary.with_call(
- iter([_SERIALIZED_REQUEST] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_TRAILING_METADATA,
- call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, call.code())
-
- def testSuccessfulStreamStream(self):
- self._servicer.set_details(_DETAILS)
-
+ received_initial_metadata = response_iterator_call.initial_metadata()
+ list(response_iterator_call)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(grpc.StatusCode.OK, response_iterator_call.code())
+
+ def testSuccessfulStreamUnary(self):
+ self._servicer.set_details(_DETAILS)
+
+ unused_response, call = self._stream_unary.with_call(
+ iter([_SERIALIZED_REQUEST] * test_constants.STREAM_LENGTH),
+ metadata=_CLIENT_METADATA)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ call.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_TRAILING_METADATA,
+ call.trailing_metadata()))
+ self.assertIs(grpc.StatusCode.OK, call.code())
+
+ def testSuccessfulStreamStream(self):
+ self._servicer.set_details(_DETAILS)
+
response_iterator_call = self._stream_stream(iter(
[object()] * test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, response_iterator_call.code())
-
- def testAbortedUnaryUnary(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(expected_code, exception_context.exception.code())
- self.assertEqual(expected_details,
- exception_context.exception.details())
-
- def testAbortedUnaryStream(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- response_iterator_call = self._unary_stream(
- _SERIALIZED_REQUEST, metadata=_CLIENT_METADATA)
- received_initial_metadata = \
- response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- self.assertEqual(len(list(response_iterator_call)), 0)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(expected_code, response_iterator_call.code())
- self.assertEqual(expected_details, response_iterator_call.details())
-
- def testAbortedStreamUnary(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
+ received_initial_metadata = response_iterator_call.initial_metadata()
+ list(response_iterator_call)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(grpc.StatusCode.OK, response_iterator_call.code())
+
+ def testAbortedUnaryUnary(self):
+ test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
+ _EXPECTED_DETAILS)
+ for abort_code, expected_code, expected_details in test_cases:
+ self._servicer.set_code(abort_code)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_abort_call()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA,
+ self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(expected_code, exception_context.exception.code())
+ self.assertEqual(expected_details,
+ exception_context.exception.details())
+
+ def testAbortedUnaryStream(self):
+ test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
+ _EXPECTED_DETAILS)
+ for abort_code, expected_code, expected_details in test_cases:
+ self._servicer.set_code(abort_code)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_abort_call()
+
+ response_iterator_call = self._unary_stream(
+ _SERIALIZED_REQUEST, metadata=_CLIENT_METADATA)
+ received_initial_metadata = \
+ response_iterator_call.initial_metadata()
+ with self.assertRaises(grpc.RpcError):
+ self.assertEqual(len(list(response_iterator_call)), 0)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA,
+ self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(expected_code, response_iterator_call.code())
+ self.assertEqual(expected_details, response_iterator_call.details())
+
+ def testAbortedStreamUnary(self):
+ test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
+ _EXPECTED_DETAILS)
+ for abort_code, expected_code, expected_details in test_cases:
+ self._servicer.set_code(abort_code)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_abort_call()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(expected_code, exception_context.exception.code())
- self.assertEqual(expected_details,
- exception_context.exception.details())
-
- def testAbortedStreamStream(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- response_iterator_call = self._stream_stream(
- iter([object()] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
- received_initial_metadata = \
- response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- self.assertEqual(len(list(response_iterator_call)), 0)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(expected_code, response_iterator_call.code())
- self.assertEqual(expected_details, response_iterator_call.details())
-
- def testCustomCodeUnaryUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeUnaryStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA,
+ self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(expected_code, exception_context.exception.code())
+ self.assertEqual(expected_details,
+ exception_context.exception.details())
+
+ def testAbortedStreamStream(self):
+ test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
+ _EXPECTED_DETAILS)
+ for abort_code, expected_code, expected_details in test_cases:
+ self._servicer.set_code(abort_code)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_abort_call()
+
+ response_iterator_call = self._stream_stream(
+ iter([object()] * test_constants.STREAM_LENGTH),
+ metadata=_CLIENT_METADATA)
+ received_initial_metadata = \
+ response_iterator_call.initial_metadata()
+ with self.assertRaises(grpc.RpcError):
+ self.assertEqual(len(list(response_iterator_call)), 0)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA,
+ self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(expected_code, response_iterator_call.code())
+ self.assertEqual(expected_details, response_iterator_call.details())
+
+ def testCustomCodeUnaryUnary(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+ def testCustomCodeUnaryStream(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+
response_iterator_call = self._unary_stream(_SERIALIZED_REQUEST,
metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, response_iterator_call.code())
- self.assertEqual(_DETAILS, response_iterator_call.details())
-
- def testCustomCodeStreamUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
+ received_initial_metadata = response_iterator_call.initial_metadata()
+ with self.assertRaises(grpc.RpcError):
+ list(response_iterator_call)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, response_iterator_call.code())
+ self.assertEqual(_DETAILS, response_iterator_call.details())
+
+ def testCustomCodeStreamUnary(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeStreamStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+ def testCustomCodeStreamStream(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+
response_iterator_call = self._stream_stream(iter(
[object()] * test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError) as exception_context:
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeExceptionUnaryUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeExceptionUnaryStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
+ received_initial_metadata = response_iterator_call.initial_metadata()
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ list(response_iterator_call)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+ def testCustomCodeExceptionUnaryUnary(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_exception()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+ def testCustomCodeExceptionUnaryStream(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_exception()
+
response_iterator_call = self._unary_stream(_SERIALIZED_REQUEST,
metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, response_iterator_call.code())
- self.assertEqual(_DETAILS, response_iterator_call.details())
-
- def testCustomCodeExceptionStreamUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
+ received_initial_metadata = response_iterator_call.initial_metadata()
+ with self.assertRaises(grpc.RpcError):
+ list(response_iterator_call)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, response_iterator_call.code())
+ self.assertEqual(_DETAILS, response_iterator_call.details())
+
+ def testCustomCodeExceptionStreamUnary(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_exception()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeExceptionStreamStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+ def testCustomCodeExceptionStreamStream(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_exception()
+
response_iterator_call = self._stream_stream(iter(
[object()] * test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, response_iterator_call.code())
- self.assertEqual(_DETAILS, response_iterator_call.details())
-
- def testCustomCodeReturnNoneUnaryUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_return_none()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeReturnNoneStreamUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_return_none()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
+ received_initial_metadata = response_iterator_call.initial_metadata()
+ with self.assertRaises(grpc.RpcError):
+ list(response_iterator_call)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
+ received_initial_metadata))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ response_iterator_call.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, response_iterator_call.code())
+ self.assertEqual(_DETAILS, response_iterator_call.details())
+
+ def testCustomCodeReturnNoneUnaryUnary(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_return_none()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+ def testCustomCodeReturnNoneStreamUnary(self):
+ self._servicer.set_code(_NON_OK_CODE)
+ self._servicer.set_details(_DETAILS)
+ self._servicer.set_return_none()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
test_constants.STREAM_LENGTH),
metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _CLIENT_METADATA, self._servicer.received_client_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_INITIAL_METADATA,
+ exception_context.exception.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(
+ _SERVER_TRAILING_METADATA,
+ exception_context.exception.trailing_metadata()))
+ self.assertIs(_NON_OK_CODE, exception_context.exception.code())
+ self.assertEqual(_DETAILS, exception_context.exception.details())
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py
index e2b36b1c70..9347970e49 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py
@@ -1,211 +1,211 @@
-# Copyright 2018 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.
-"""Tests metadata flags feature by testing wait-for-ready semantics"""
-
-import time
-import weakref
-import unittest
-import threading
+# Copyright 2018 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.
+"""Tests metadata flags feature by testing wait-for-ready semantics"""
+
+import time
+import weakref
+import unittest
+import threading
import logging
-import socket
-from six.moves import queue
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-import tests.unit.framework.common
+import socket
+from six.moves import queue
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+import tests.unit.framework.common
from tests.unit.framework.common import get_socket
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-
-def handle_unary_unary(test, request, servicer_context):
- return _RESPONSE
-
-
-def handle_unary_stream(test, request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(test, request_iterator, servicer_context):
- for _ in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(test, request_iterator, servicer_context):
- for _ in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, test, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+
+def handle_unary_unary(test, request, servicer_context):
+ return _RESPONSE
+
+
+def handle_unary_stream(test, request, servicer_context):
+ for _ in range(test_constants.STREAM_LENGTH):
+ yield _RESPONSE
+
+
+def handle_stream_unary(test, request_iterator, servicer_context):
+ for _ in request_iterator:
+ pass
+ return _RESPONSE
+
+
+def handle_stream_stream(test, request_iterator, servicer_context):
+ for _ in request_iterator:
+ yield _RESPONSE
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, test, request_streaming, response_streaming):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_unary = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+ if self.request_streaming and self.response_streaming:
self.stream_stream = lambda req, ctx: handle_stream_stream(
test, req, ctx)
- elif self.request_streaming:
+ elif self.request_streaming:
self.stream_unary = lambda req, ctx: handle_stream_unary(
test, req, ctx)
- elif self.response_streaming:
+ elif self.response_streaming:
self.unary_stream = lambda req, ctx: handle_unary_stream(
test, req, ctx)
- else:
+ else:
self.unary_unary = lambda req, ctx: handle_unary_unary(
test, req, ctx)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, test):
- self._test = test
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(self._test, False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(self._test, False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(self._test, True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(self._test, True, True)
- else:
- return None
-
-
-def create_dummy_channel():
- """Creating dummy channels is a workaround for retries"""
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, test):
+ self._test = test
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(self._test, False, False)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(self._test, False, True)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(self._test, True, False)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(self._test, True, True)
+ else:
+ return None
+
+
+def create_dummy_channel():
+ """Creating dummy channels is a workaround for retries"""
host, port, sock = get_socket(sock_options=(socket.SO_REUSEADDR,))
sock.close()
return grpc.insecure_channel('{}:{}'.format(host, port))
-
-
-def perform_unary_unary_call(channel, wait_for_ready=None):
- channel.unary_unary(_UNARY_UNARY).__call__(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_unary_unary_with_call(channel, wait_for_ready=None):
- channel.unary_unary(_UNARY_UNARY).with_call(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_unary_unary_future(channel, wait_for_ready=None):
- channel.unary_unary(_UNARY_UNARY).future(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready).result(
- timeout=test_constants.LONG_TIMEOUT)
-
-
-def perform_unary_stream_call(channel, wait_for_ready=None):
- response_iterator = channel.unary_stream(_UNARY_STREAM).__call__(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
- for _ in response_iterator:
- pass
-
-
-def perform_stream_unary_call(channel, wait_for_ready=None):
- channel.stream_unary(_STREAM_UNARY).__call__(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_stream_unary_with_call(channel, wait_for_ready=None):
- channel.stream_unary(_STREAM_UNARY).with_call(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_stream_unary_future(channel, wait_for_ready=None):
- channel.stream_unary(_STREAM_UNARY).future(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready).result(
- timeout=test_constants.LONG_TIMEOUT)
-
-
-def perform_stream_stream_call(channel, wait_for_ready=None):
- response_iterator = channel.stream_stream(_STREAM_STREAM).__call__(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
- for _ in response_iterator:
- pass
-
-
-_ALL_CALL_CASES = [
- perform_unary_unary_call, perform_unary_unary_with_call,
- perform_unary_unary_future, perform_unary_stream_call,
- perform_stream_unary_call, perform_stream_unary_with_call,
- perform_stream_unary_future, perform_stream_stream_call
-]
-
-
-class MetadataFlagsTest(unittest.TestCase):
-
- def check_connection_does_failfast(self, fn, channel, wait_for_ready=None):
- try:
- fn(channel, wait_for_ready)
- self.fail("The Call should fail")
- except BaseException as e: # pylint: disable=broad-except
- self.assertIs(grpc.StatusCode.UNAVAILABLE, e.code())
-
- def test_call_wait_for_ready_default(self):
- for perform_call in _ALL_CALL_CASES:
- with create_dummy_channel() as channel:
- self.check_connection_does_failfast(perform_call, channel)
-
- def test_call_wait_for_ready_disabled(self):
- for perform_call in _ALL_CALL_CASES:
- with create_dummy_channel() as channel:
+
+
+def perform_unary_unary_call(channel, wait_for_ready=None):
+ channel.unary_unary(_UNARY_UNARY).__call__(
+ _REQUEST,
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready)
+
+
+def perform_unary_unary_with_call(channel, wait_for_ready=None):
+ channel.unary_unary(_UNARY_UNARY).with_call(
+ _REQUEST,
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready)
+
+
+def perform_unary_unary_future(channel, wait_for_ready=None):
+ channel.unary_unary(_UNARY_UNARY).future(
+ _REQUEST,
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready).result(
+ timeout=test_constants.LONG_TIMEOUT)
+
+
+def perform_unary_stream_call(channel, wait_for_ready=None):
+ response_iterator = channel.unary_stream(_UNARY_STREAM).__call__(
+ _REQUEST,
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready)
+ for _ in response_iterator:
+ pass
+
+
+def perform_stream_unary_call(channel, wait_for_ready=None):
+ channel.stream_unary(_STREAM_UNARY).__call__(
+ iter([_REQUEST] * test_constants.STREAM_LENGTH),
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready)
+
+
+def perform_stream_unary_with_call(channel, wait_for_ready=None):
+ channel.stream_unary(_STREAM_UNARY).with_call(
+ iter([_REQUEST] * test_constants.STREAM_LENGTH),
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready)
+
+
+def perform_stream_unary_future(channel, wait_for_ready=None):
+ channel.stream_unary(_STREAM_UNARY).future(
+ iter([_REQUEST] * test_constants.STREAM_LENGTH),
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready).result(
+ timeout=test_constants.LONG_TIMEOUT)
+
+
+def perform_stream_stream_call(channel, wait_for_ready=None):
+ response_iterator = channel.stream_stream(_STREAM_STREAM).__call__(
+ iter([_REQUEST] * test_constants.STREAM_LENGTH),
+ timeout=test_constants.LONG_TIMEOUT,
+ wait_for_ready=wait_for_ready)
+ for _ in response_iterator:
+ pass
+
+
+_ALL_CALL_CASES = [
+ perform_unary_unary_call, perform_unary_unary_with_call,
+ perform_unary_unary_future, perform_unary_stream_call,
+ perform_stream_unary_call, perform_stream_unary_with_call,
+ perform_stream_unary_future, perform_stream_stream_call
+]
+
+
+class MetadataFlagsTest(unittest.TestCase):
+
+ def check_connection_does_failfast(self, fn, channel, wait_for_ready=None):
+ try:
+ fn(channel, wait_for_ready)
+ self.fail("The Call should fail")
+ except BaseException as e: # pylint: disable=broad-except
+ self.assertIs(grpc.StatusCode.UNAVAILABLE, e.code())
+
+ def test_call_wait_for_ready_default(self):
+ for perform_call in _ALL_CALL_CASES:
+ with create_dummy_channel() as channel:
+ self.check_connection_does_failfast(perform_call, channel)
+
+ def test_call_wait_for_ready_disabled(self):
+ for perform_call in _ALL_CALL_CASES:
+ with create_dummy_channel() as channel:
self.check_connection_does_failfast(perform_call,
channel,
wait_for_ready=False)
-
- def test_call_wait_for_ready_enabled(self):
- # To test the wait mechanism, Python thread is required to make
- # client set up first without handling them case by case.
- # Also, Python thread don't pass the unhandled exceptions to
- # main thread. So, it need another method to store the
- # exceptions and raise them again in main thread.
- unhandled_exceptions = queue.Queue()
-
+
+ def test_call_wait_for_ready_enabled(self):
+ # To test the wait mechanism, Python thread is required to make
+ # client set up first without handling them case by case.
+ # Also, Python thread don't pass the unhandled exceptions to
+ # main thread. So, it need another method to store the
+ # exceptions and raise them again in main thread.
+ unhandled_exceptions = queue.Queue()
+
# We just need an unused TCP port
host, port, sock = get_socket(sock_options=(socket.SO_REUSEADDR,))
sock.close()
@@ -226,9 +226,9 @@ class MetadataFlagsTest(unittest.TestCase):
# If the call failed, the thread would be destroyed. The
# channel object can be collected before calling the
# callback, which will result in a deadlock.
- wg.done()
+ wg.done()
unhandled_exceptions.put(e, True)
-
+
test_threads = []
for perform_call in _ALL_CALL_CASES:
test_thread = threading.Thread(target=test_call,
@@ -237,24 +237,24 @@ class MetadataFlagsTest(unittest.TestCase):
test_thread.exception = None
test_thread.start()
test_threads.append(test_thread)
-
+
# Start the server after the connections are waiting
wg.wait()
server = test_common.test_server(reuse_port=True)
server.add_generic_rpc_handlers((_GenericHandler(weakref.proxy(self)),))
server.add_insecure_port(addr)
server.start()
-
+
for test_thread in test_threads:
test_thread.join()
-
+
# Stop the server to make test end properly
server.stop(0)
-
+
if not unhandled_exceptions.empty():
raise unhandled_exceptions.get(True)
-
-
-if __name__ == '__main__':
+
+
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py
index 3e7717b04c..1de9b7fd86 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py
@@ -1,242 +1,242 @@
-# Copyright 2016 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.
-"""Tests server and client side metadata API."""
-
-import unittest
-import weakref
-import logging
-
-import grpc
-from grpc import _channel
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_CHANNEL_ARGS = (('grpc.primary_user_agent', 'primary-agent'),
- ('grpc.secondary_user_agent', 'secondary-agent'))
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-_INVOCATION_METADATA = (
- (
- b'invocation-md-key',
- u'invocation-md-value',
- ),
- (
- u'invocation-md-key-bin',
- b'\x00\x01',
- ),
-)
-_EXPECTED_INVOCATION_METADATA = (
- (
- 'invocation-md-key',
- 'invocation-md-value',
- ),
- (
- 'invocation-md-key-bin',
- b'\x00\x01',
- ),
-)
-
-_INITIAL_METADATA = ((b'initial-md-key', u'initial-md-value'),
- (u'initial-md-key-bin', b'\x00\x02'))
-_EXPECTED_INITIAL_METADATA = (
- (
- 'initial-md-key',
- 'initial-md-value',
- ),
- (
- 'initial-md-key-bin',
- b'\x00\x02',
- ),
-)
-
-_TRAILING_METADATA = (
- (
- 'server-trailing-md-key',
- 'server-trailing-md-value',
- ),
- (
- 'server-trailing-md-key-bin',
- b'\x00\x03',
- ),
-)
-_EXPECTED_TRAILING_METADATA = _TRAILING_METADATA
-
-
-def _user_agent(metadata):
- for key, val in metadata:
- if key == 'user-agent':
- return val
- raise KeyError('No user agent!')
-
-
-def validate_client_metadata(test, servicer_context):
- invocation_metadata = servicer_context.invocation_metadata()
- test.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INVOCATION_METADATA,
- invocation_metadata))
- user_agent = _user_agent(invocation_metadata)
- test.assertTrue(
- user_agent.startswith('primary-agent ' + _channel._USER_AGENT))
- test.assertTrue(user_agent.endswith('secondary-agent'))
-
-
-def handle_unary_unary(test, request, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- return _RESPONSE
-
-
-def handle_unary_stream(test, request, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(test, request_iterator, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- # TODO(issue:#6891) We should be able to remove this loop
- for request in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(test, request_iterator, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- # TODO(issue:#6891) We should be able to remove this loop,
- # and replace with return; yield
- for request in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, test, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = lambda x, y: handle_stream_stream(test, x, y)
- elif self.request_streaming:
- self.stream_unary = lambda x, y: handle_stream_unary(test, x, y)
- elif self.response_streaming:
- self.unary_stream = lambda x, y: handle_unary_stream(test, x, y)
- else:
- self.unary_unary = lambda x, y: handle_unary_unary(test, x, y)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, test):
- self._test = test
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(self._test, False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(self._test, False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(self._test, True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(self._test, True, True)
- else:
- return None
-
-
-class MetadataTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
+# Copyright 2016 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.
+"""Tests server and client side metadata API."""
+
+import unittest
+import weakref
+import logging
+
+import grpc
+from grpc import _channel
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_CHANNEL_ARGS = (('grpc.primary_user_agent', 'primary-agent'),
+ ('grpc.secondary_user_agent', 'secondary-agent'))
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+_INVOCATION_METADATA = (
+ (
+ b'invocation-md-key',
+ u'invocation-md-value',
+ ),
+ (
+ u'invocation-md-key-bin',
+ b'\x00\x01',
+ ),
+)
+_EXPECTED_INVOCATION_METADATA = (
+ (
+ 'invocation-md-key',
+ 'invocation-md-value',
+ ),
+ (
+ 'invocation-md-key-bin',
+ b'\x00\x01',
+ ),
+)
+
+_INITIAL_METADATA = ((b'initial-md-key', u'initial-md-value'),
+ (u'initial-md-key-bin', b'\x00\x02'))
+_EXPECTED_INITIAL_METADATA = (
+ (
+ 'initial-md-key',
+ 'initial-md-value',
+ ),
+ (
+ 'initial-md-key-bin',
+ b'\x00\x02',
+ ),
+)
+
+_TRAILING_METADATA = (
+ (
+ 'server-trailing-md-key',
+ 'server-trailing-md-value',
+ ),
+ (
+ 'server-trailing-md-key-bin',
+ b'\x00\x03',
+ ),
+)
+_EXPECTED_TRAILING_METADATA = _TRAILING_METADATA
+
+
+def _user_agent(metadata):
+ for key, val in metadata:
+ if key == 'user-agent':
+ return val
+ raise KeyError('No user agent!')
+
+
+def validate_client_metadata(test, servicer_context):
+ invocation_metadata = servicer_context.invocation_metadata()
+ test.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_INVOCATION_METADATA,
+ invocation_metadata))
+ user_agent = _user_agent(invocation_metadata)
+ test.assertTrue(
+ user_agent.startswith('primary-agent ' + _channel._USER_AGENT))
+ test.assertTrue(user_agent.endswith('secondary-agent'))
+
+
+def handle_unary_unary(test, request, servicer_context):
+ validate_client_metadata(test, servicer_context)
+ servicer_context.send_initial_metadata(_INITIAL_METADATA)
+ servicer_context.set_trailing_metadata(_TRAILING_METADATA)
+ return _RESPONSE
+
+
+def handle_unary_stream(test, request, servicer_context):
+ validate_client_metadata(test, servicer_context)
+ servicer_context.send_initial_metadata(_INITIAL_METADATA)
+ servicer_context.set_trailing_metadata(_TRAILING_METADATA)
+ for _ in range(test_constants.STREAM_LENGTH):
+ yield _RESPONSE
+
+
+def handle_stream_unary(test, request_iterator, servicer_context):
+ validate_client_metadata(test, servicer_context)
+ servicer_context.send_initial_metadata(_INITIAL_METADATA)
+ servicer_context.set_trailing_metadata(_TRAILING_METADATA)
+ # TODO(issue:#6891) We should be able to remove this loop
+ for request in request_iterator:
+ pass
+ return _RESPONSE
+
+
+def handle_stream_stream(test, request_iterator, servicer_context):
+ validate_client_metadata(test, servicer_context)
+ servicer_context.send_initial_metadata(_INITIAL_METADATA)
+ servicer_context.set_trailing_metadata(_TRAILING_METADATA)
+ # TODO(issue:#6891) We should be able to remove this loop,
+ # and replace with return; yield
+ for request in request_iterator:
+ yield _RESPONSE
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, test, request_streaming, response_streaming):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_unary = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+ if self.request_streaming and self.response_streaming:
+ self.stream_stream = lambda x, y: handle_stream_stream(test, x, y)
+ elif self.request_streaming:
+ self.stream_unary = lambda x, y: handle_stream_unary(test, x, y)
+ elif self.response_streaming:
+ self.unary_stream = lambda x, y: handle_unary_stream(test, x, y)
+ else:
+ self.unary_unary = lambda x, y: handle_unary_unary(test, x, y)
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, test):
+ self._test = test
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(self._test, False, False)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(self._test, False, True)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(self._test, True, False)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(self._test, True, True)
+ else:
+ return None
+
+
+class MetadataTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
self._server.add_generic_rpc_handlers(
(_GenericHandler(weakref.proxy(self)),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
self._channel = grpc.insecure_channel('localhost:%d' % port,
options=_CHANNEL_ARGS)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testUnaryUnary(self):
- multi_callable = self._channel.unary_unary(_UNARY_UNARY)
- unused_response, call = multi_callable.with_call(
- _REQUEST, metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
- def testUnaryStream(self):
- multi_callable = self._channel.unary_stream(_UNARY_STREAM)
- call = multi_callable(_REQUEST, metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- for _ in call:
- pass
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
- def testStreamUnary(self):
- multi_callable = self._channel.stream_unary(_STREAM_UNARY)
- unused_response, call = multi_callable.with_call(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
- def testStreamStream(self):
- multi_callable = self._channel.stream_stream(_STREAM_STREAM)
+
+ def tearDown(self):
+ self._server.stop(0)
+ self._channel.close()
+
+ def testUnaryUnary(self):
+ multi_callable = self._channel.unary_unary(_UNARY_UNARY)
+ unused_response, call = multi_callable.with_call(
+ _REQUEST, metadata=_INVOCATION_METADATA)
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
+ call.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
+ call.trailing_metadata()))
+
+ def testUnaryStream(self):
+ multi_callable = self._channel.unary_stream(_UNARY_STREAM)
+ call = multi_callable(_REQUEST, metadata=_INVOCATION_METADATA)
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
+ call.initial_metadata()))
+ for _ in call:
+ pass
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
+ call.trailing_metadata()))
+
+ def testStreamUnary(self):
+ multi_callable = self._channel.stream_unary(_STREAM_UNARY)
+ unused_response, call = multi_callable.with_call(
+ iter([_REQUEST] * test_constants.STREAM_LENGTH),
+ metadata=_INVOCATION_METADATA)
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
+ call.initial_metadata()))
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
+ call.trailing_metadata()))
+
+ def testStreamStream(self):
+ multi_callable = self._channel.stream_stream(_STREAM_STREAM)
call = multi_callable(iter([_REQUEST] * test_constants.STREAM_LENGTH),
metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- for _ in call:
- pass
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
+ call.initial_metadata()))
+ for _ in call:
+ pass
+ self.assertTrue(
+ test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
+ call.trailing_metadata()))
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py
index 16feb4b1ff..c3318bf7df 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py
@@ -1,69 +1,69 @@
-# Copyright 2017 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.
-"""Tests that a channel will reconnect if a connection is dropped"""
-
-import socket
-import time
-import logging
-import unittest
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import bound_socket
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x01'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-
-
-def _handle_unary_unary(unused_request, unused_servicer_context):
- return _RESPONSE
-
-
-class ReconnectTest(unittest.TestCase):
-
- def test_reconnect(self):
- server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
- handler = grpc.method_handlers_generic_handler('test', {
- 'UnaryUnary':
+# Copyright 2017 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.
+"""Tests that a channel will reconnect if a connection is dropped"""
+
+import socket
+import time
+import logging
+import unittest
+
+import grpc
+from grpc.framework.foundation import logging_pool
+
+from tests.unit.framework.common import test_constants
+from tests.unit.framework.common import bound_socket
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x01'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+
+
+def _handle_unary_unary(unused_request, unused_servicer_context):
+ return _RESPONSE
+
+
+class ReconnectTest(unittest.TestCase):
+
+ def test_reconnect(self):
+ server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
+ handler = grpc.method_handlers_generic_handler('test', {
+ 'UnaryUnary':
grpc.unary_unary_rpc_method_handler(_handle_unary_unary)
- })
- options = (('grpc.so_reuseport', 1),)
- with bound_socket() as (host, port):
- addr = '{}:{}'.format(host, port)
- server = grpc.server(server_pool, (handler,), options=options)
- server.add_insecure_port(addr)
- server.start()
- channel = grpc.insecure_channel(addr)
- multi_callable = channel.unary_unary(_UNARY_UNARY)
- self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
- server.stop(None)
- # By default, the channel connectivity is checked every 5s
- # GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS can be set to change
- # this.
- time.sleep(5.1)
- server = grpc.server(server_pool, (handler,), options=options)
- server.add_insecure_port(addr)
- server.start()
- self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
- server.stop(None)
- channel.close()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ })
+ options = (('grpc.so_reuseport', 1),)
+ with bound_socket() as (host, port):
+ addr = '{}:{}'.format(host, port)
+ server = grpc.server(server_pool, (handler,), options=options)
+ server.add_insecure_port(addr)
+ server.start()
+ channel = grpc.insecure_channel(addr)
+ multi_callable = channel.unary_unary(_UNARY_UNARY)
+ self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
+ server.stop(None)
+ # By default, the channel connectivity is checked every 5s
+ # GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS can be set to change
+ # this.
+ time.sleep(5.1)
+ server = grpc.server(server_pool, (handler,), options=options)
+ server.add_insecure_port(addr)
+ server.start()
+ self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
+ server.stop(None)
+ channel.close()
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py
index ecd2ccadbd..cd3036dd6b 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py
@@ -1,259 +1,259 @@
-# Copyright 2017 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.
-"""Tests server responding with RESOURCE_EXHAUSTED."""
-
-import threading
-import unittest
-import logging
-
-import grpc
-from grpc import _channel
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-class _TestTrigger(object):
-
- def __init__(self, total_call_count):
- self._total_call_count = total_call_count
- self._pending_calls = 0
- self._triggered = False
- self._finish_condition = threading.Condition()
- self._start_condition = threading.Condition()
-
- # Wait for all calls be blocked in their handler
- def await_calls(self):
- with self._start_condition:
- while self._pending_calls < self._total_call_count:
- self._start_condition.wait()
-
- # Block in a response handler and wait for a trigger
- def await_trigger(self):
- with self._start_condition:
- self._pending_calls += 1
- self._start_condition.notify()
-
- with self._finish_condition:
- if not self._triggered:
- self._finish_condition.wait()
-
- # Finish all response handlers
- def trigger(self):
- with self._finish_condition:
- self._triggered = True
- self._finish_condition.notify_all()
-
-
-def handle_unary_unary(trigger, request, servicer_context):
- trigger.await_trigger()
- return _RESPONSE
-
-
-def handle_unary_stream(trigger, request, servicer_context):
- trigger.await_trigger()
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(trigger, request_iterator, servicer_context):
- trigger.await_trigger()
- # TODO(issue:#6891) We should be able to remove this loop
- for request in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(trigger, request_iterator, servicer_context):
- trigger.await_trigger()
- # TODO(issue:#6891) We should be able to remove this loop,
- # and replace with return; yield
- for request in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, trigger, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = (
- lambda x, y: handle_stream_stream(trigger, x, y))
- elif self.request_streaming:
- self.stream_unary = lambda x, y: handle_stream_unary(trigger, x, y)
- elif self.response_streaming:
- self.unary_stream = lambda x, y: handle_unary_stream(trigger, x, y)
- else:
- self.unary_unary = lambda x, y: handle_unary_unary(trigger, x, y)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, trigger):
- self._trigger = trigger
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(self._trigger, False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(self._trigger, False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(self._trigger, True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(self._trigger, True, True)
- else:
- return None
-
-
-class ResourceExhaustedTest(unittest.TestCase):
-
- def setUp(self):
- self._server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
- self._trigger = _TestTrigger(test_constants.THREAD_CONCURRENCY)
- self._server = grpc.server(
- self._server_pool,
- handlers=(_GenericHandler(self._trigger),),
- options=(('grpc.so_reuseport', 0),),
- maximum_concurrent_rpcs=test_constants.THREAD_CONCURRENCY)
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testUnaryUnary(self):
- multi_callable = self._channel.unary_unary(_UNARY_UNARY)
- futures = []
- for _ in range(test_constants.THREAD_CONCURRENCY):
- futures.append(multi_callable.future(_REQUEST))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(_REQUEST)
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- future_exception = multi_callable.future(_REQUEST)
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- future_exception.exception().code())
-
- self._trigger.trigger()
- for future in futures:
- self.assertEqual(_RESPONSE, future.result())
-
- # Ensure a new request can be handled
- self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
-
- def testUnaryStream(self):
- multi_callable = self._channel.unary_stream(_UNARY_STREAM)
- calls = []
- for _ in range(test_constants.THREAD_CONCURRENCY):
- calls.append(multi_callable(_REQUEST))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- next(multi_callable(_REQUEST))
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- self._trigger.trigger()
-
- for call in calls:
- for response in call:
- self.assertEqual(_RESPONSE, response)
-
- # Ensure a new request can be handled
- new_call = multi_callable(_REQUEST)
- for response in new_call:
- self.assertEqual(_RESPONSE, response)
-
- def testStreamUnary(self):
- multi_callable = self._channel.stream_unary(_STREAM_UNARY)
- futures = []
- request = iter([_REQUEST] * test_constants.STREAM_LENGTH)
- for _ in range(test_constants.THREAD_CONCURRENCY):
- futures.append(multi_callable.future(request))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(request)
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- future_exception = multi_callable.future(request)
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- future_exception.exception().code())
-
- self._trigger.trigger()
-
- for future in futures:
- self.assertEqual(_RESPONSE, future.result())
-
- # Ensure a new request can be handled
- self.assertEqual(_RESPONSE, multi_callable(request))
-
- def testStreamStream(self):
- multi_callable = self._channel.stream_stream(_STREAM_STREAM)
- calls = []
- request = iter([_REQUEST] * test_constants.STREAM_LENGTH)
- for _ in range(test_constants.THREAD_CONCURRENCY):
- calls.append(multi_callable(request))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- next(multi_callable(request))
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- self._trigger.trigger()
-
- for call in calls:
- for response in call:
- self.assertEqual(_RESPONSE, response)
-
- # Ensure a new request can be handled
- new_call = multi_callable(request)
- for response in new_call:
- self.assertEqual(_RESPONSE, response)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2017 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.
+"""Tests server responding with RESOURCE_EXHAUSTED."""
+
+import threading
+import unittest
+import logging
+
+import grpc
+from grpc import _channel
+from grpc.framework.foundation import logging_pool
+
+from tests.unit import test_common
+from tests.unit.framework.common import test_constants
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+_UNARY_STREAM = '/test/UnaryStream'
+_STREAM_UNARY = '/test/StreamUnary'
+_STREAM_STREAM = '/test/StreamStream'
+
+
+class _TestTrigger(object):
+
+ def __init__(self, total_call_count):
+ self._total_call_count = total_call_count
+ self._pending_calls = 0
+ self._triggered = False
+ self._finish_condition = threading.Condition()
+ self._start_condition = threading.Condition()
+
+ # Wait for all calls be blocked in their handler
+ def await_calls(self):
+ with self._start_condition:
+ while self._pending_calls < self._total_call_count:
+ self._start_condition.wait()
+
+ # Block in a response handler and wait for a trigger
+ def await_trigger(self):
+ with self._start_condition:
+ self._pending_calls += 1
+ self._start_condition.notify()
+
+ with self._finish_condition:
+ if not self._triggered:
+ self._finish_condition.wait()
+
+ # Finish all response handlers
+ def trigger(self):
+ with self._finish_condition:
+ self._triggered = True
+ self._finish_condition.notify_all()
+
+
+def handle_unary_unary(trigger, request, servicer_context):
+ trigger.await_trigger()
+ return _RESPONSE
+
+
+def handle_unary_stream(trigger, request, servicer_context):
+ trigger.await_trigger()
+ for _ in range(test_constants.STREAM_LENGTH):
+ yield _RESPONSE
+
+
+def handle_stream_unary(trigger, request_iterator, servicer_context):
+ trigger.await_trigger()
+ # TODO(issue:#6891) We should be able to remove this loop
+ for request in request_iterator:
+ pass
+ return _RESPONSE
+
+
+def handle_stream_stream(trigger, request_iterator, servicer_context):
+ trigger.await_trigger()
+ # TODO(issue:#6891) We should be able to remove this loop,
+ # and replace with return; yield
+ for request in request_iterator:
+ yield _RESPONSE
+
+
+class _MethodHandler(grpc.RpcMethodHandler):
+
+ def __init__(self, trigger, request_streaming, response_streaming):
+ self.request_streaming = request_streaming
+ self.response_streaming = response_streaming
+ self.request_deserializer = None
+ self.response_serializer = None
+ self.unary_unary = None
+ self.unary_stream = None
+ self.stream_unary = None
+ self.stream_stream = None
+ if self.request_streaming and self.response_streaming:
+ self.stream_stream = (
+ lambda x, y: handle_stream_stream(trigger, x, y))
+ elif self.request_streaming:
+ self.stream_unary = lambda x, y: handle_stream_unary(trigger, x, y)
+ elif self.response_streaming:
+ self.unary_stream = lambda x, y: handle_unary_stream(trigger, x, y)
+ else:
+ self.unary_unary = lambda x, y: handle_unary_unary(trigger, x, y)
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self, trigger):
+ self._trigger = trigger
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _UNARY_UNARY:
+ return _MethodHandler(self._trigger, False, False)
+ elif handler_call_details.method == _UNARY_STREAM:
+ return _MethodHandler(self._trigger, False, True)
+ elif handler_call_details.method == _STREAM_UNARY:
+ return _MethodHandler(self._trigger, True, False)
+ elif handler_call_details.method == _STREAM_STREAM:
+ return _MethodHandler(self._trigger, True, True)
+ else:
+ return None
+
+
+class ResourceExhaustedTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
+ self._trigger = _TestTrigger(test_constants.THREAD_CONCURRENCY)
+ self._server = grpc.server(
+ self._server_pool,
+ handlers=(_GenericHandler(self._trigger),),
+ options=(('grpc.so_reuseport', 0),),
+ maximum_concurrent_rpcs=test_constants.THREAD_CONCURRENCY)
+ port = self._server.add_insecure_port('[::]:0')
+ self._server.start()
+ self._channel = grpc.insecure_channel('localhost:%d' % port)
+
+ def tearDown(self):
+ self._server.stop(0)
+ self._channel.close()
+
+ def testUnaryUnary(self):
+ multi_callable = self._channel.unary_unary(_UNARY_UNARY)
+ futures = []
+ for _ in range(test_constants.THREAD_CONCURRENCY):
+ futures.append(multi_callable.future(_REQUEST))
+
+ self._trigger.await_calls()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ multi_callable(_REQUEST)
+
+ self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
+ exception_context.exception.code())
+
+ future_exception = multi_callable.future(_REQUEST)
+ self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
+ future_exception.exception().code())
+
+ self._trigger.trigger()
+ for future in futures:
+ self.assertEqual(_RESPONSE, future.result())
+
+ # Ensure a new request can be handled
+ self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
+
+ def testUnaryStream(self):
+ multi_callable = self._channel.unary_stream(_UNARY_STREAM)
+ calls = []
+ for _ in range(test_constants.THREAD_CONCURRENCY):
+ calls.append(multi_callable(_REQUEST))
+
+ self._trigger.await_calls()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ next(multi_callable(_REQUEST))
+
+ self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
+ exception_context.exception.code())
+
+ self._trigger.trigger()
+
+ for call in calls:
+ for response in call:
+ self.assertEqual(_RESPONSE, response)
+
+ # Ensure a new request can be handled
+ new_call = multi_callable(_REQUEST)
+ for response in new_call:
+ self.assertEqual(_RESPONSE, response)
+
+ def testStreamUnary(self):
+ multi_callable = self._channel.stream_unary(_STREAM_UNARY)
+ futures = []
+ request = iter([_REQUEST] * test_constants.STREAM_LENGTH)
+ for _ in range(test_constants.THREAD_CONCURRENCY):
+ futures.append(multi_callable.future(request))
+
+ self._trigger.await_calls()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ multi_callable(request)
+
+ self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
+ exception_context.exception.code())
+
+ future_exception = multi_callable.future(request)
+ self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
+ future_exception.exception().code())
+
+ self._trigger.trigger()
+
+ for future in futures:
+ self.assertEqual(_RESPONSE, future.result())
+
+ # Ensure a new request can be handled
+ self.assertEqual(_RESPONSE, multi_callable(request))
+
+ def testStreamStream(self):
+ multi_callable = self._channel.stream_stream(_STREAM_STREAM)
+ calls = []
+ request = iter([_REQUEST] * test_constants.STREAM_LENGTH)
+ for _ in range(test_constants.THREAD_CONCURRENCY):
+ calls.append(multi_callable(request))
+
+ self._trigger.await_calls()
+
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ next(multi_callable(request))
+
+ self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
+ exception_context.exception.code())
+
+ self._trigger.trigger()
+
+ for call in calls:
+ for response in call:
+ self.assertEqual(_RESPONSE, response)
+
+ # Ensure a new request can be handled
+ new_call = multi_callable(request)
+ for response in new_call:
+ self.assertEqual(_RESPONSE, response)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py
index 1d1fdba11e..fbbb6cf000 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py
@@ -1,97 +1,97 @@
-# Copyright 2018 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.
-"""Defines a number of module-scope gRPC scenarios to test server shutdown."""
-
-import argparse
-import os
-import threading
-import time
-import logging
-
-import grpc
-from tests.unit import test_common
-
-from concurrent import futures
-from six.moves import queue
-
-WAIT_TIME = 1000
-
-REQUEST = b'request'
-RESPONSE = b'response'
-
-SERVER_RAISES_EXCEPTION = 'server_raises_exception'
-SERVER_DEALLOCATED = 'server_deallocated'
-SERVER_FORK_CAN_EXIT = 'server_fork_can_exit'
-
-FORK_EXIT = '/test/ForkExit'
-
-
-def fork_and_exit(request, servicer_context):
- pid = os.fork()
- if pid == 0:
- os._exit(0)
- return RESPONSE
-
-
-class GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == FORK_EXIT:
- return grpc.unary_unary_rpc_method_handler(fork_and_exit)
- else:
- return None
-
-
-def run_server(port_queue):
- server = test_common.test_server()
- port = server.add_insecure_port('[::]:0')
- port_queue.put(port)
- server.add_generic_rpc_handlers((GenericHandler(),))
- server.start()
- # threading.Event.wait() does not exhibit the bug identified in
- # https://github.com/grpc/grpc/issues/17093, sleep instead
- time.sleep(WAIT_TIME)
-
-
-def run_test(args):
- if args.scenario == SERVER_RAISES_EXCEPTION:
- server = test_common.test_server()
- server.start()
- raise Exception()
- elif args.scenario == SERVER_DEALLOCATED:
- server = test_common.test_server()
- server.start()
- server.__del__()
- while server._state.stage != grpc._server._ServerStage.STOPPED:
- pass
- elif args.scenario == SERVER_FORK_CAN_EXIT:
- port_queue = queue.Queue()
- thread = threading.Thread(target=run_server, args=(port_queue,))
- thread.daemon = True
- thread.start()
- port = port_queue.get()
- channel = grpc.insecure_channel('localhost:%d' % port)
- multi_callable = channel.unary_unary(FORK_EXIT)
- result, call = multi_callable.with_call(REQUEST, wait_for_ready=True)
- os.wait()
- else:
- raise ValueError('unknown test scenario')
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- parser = argparse.ArgumentParser()
- parser.add_argument('scenario', type=str)
- args = parser.parse_args()
- run_test(args)
+# Copyright 2018 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.
+"""Defines a number of module-scope gRPC scenarios to test server shutdown."""
+
+import argparse
+import os
+import threading
+import time
+import logging
+
+import grpc
+from tests.unit import test_common
+
+from concurrent import futures
+from six.moves import queue
+
+WAIT_TIME = 1000
+
+REQUEST = b'request'
+RESPONSE = b'response'
+
+SERVER_RAISES_EXCEPTION = 'server_raises_exception'
+SERVER_DEALLOCATED = 'server_deallocated'
+SERVER_FORK_CAN_EXIT = 'server_fork_can_exit'
+
+FORK_EXIT = '/test/ForkExit'
+
+
+def fork_and_exit(request, servicer_context):
+ pid = os.fork()
+ if pid == 0:
+ os._exit(0)
+ return RESPONSE
+
+
+class GenericHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == FORK_EXIT:
+ return grpc.unary_unary_rpc_method_handler(fork_and_exit)
+ else:
+ return None
+
+
+def run_server(port_queue):
+ server = test_common.test_server()
+ port = server.add_insecure_port('[::]:0')
+ port_queue.put(port)
+ server.add_generic_rpc_handlers((GenericHandler(),))
+ server.start()
+ # threading.Event.wait() does not exhibit the bug identified in
+ # https://github.com/grpc/grpc/issues/17093, sleep instead
+ time.sleep(WAIT_TIME)
+
+
+def run_test(args):
+ if args.scenario == SERVER_RAISES_EXCEPTION:
+ server = test_common.test_server()
+ server.start()
+ raise Exception()
+ elif args.scenario == SERVER_DEALLOCATED:
+ server = test_common.test_server()
+ server.start()
+ server.__del__()
+ while server._state.stage != grpc._server._ServerStage.STOPPED:
+ pass
+ elif args.scenario == SERVER_FORK_CAN_EXIT:
+ port_queue = queue.Queue()
+ thread = threading.Thread(target=run_server, args=(port_queue,))
+ thread.daemon = True
+ thread.start()
+ port = port_queue.get()
+ channel = grpc.insecure_channel('localhost:%d' % port)
+ multi_callable = channel.unary_unary(FORK_EXIT)
+ result, call = multi_callable.with_call(REQUEST, wait_for_ready=True)
+ os.wait()
+ else:
+ raise ValueError('unknown test scenario')
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ parser = argparse.ArgumentParser()
+ parser.add_argument('scenario', type=str)
+ args = parser.parse_args()
+ run_test(args)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py
index c1dc7585f8..0fe0340985 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py
@@ -1,95 +1,95 @@
-# Copyright 2018 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.
-"""Tests clean shutdown of server on various interpreter exit conditions.
-
-The tests in this module spawn a subprocess for each test case, the
-test is considered successful if it doesn't hang/timeout.
-"""
-
-import atexit
-import os
-import subprocess
-import sys
-import threading
-import unittest
-import logging
-
-from tests.unit import _server_shutdown_scenarios
-
-INTERPRETER = sys.executable
-BASE_COMMAND = [INTERPRETER, '-m', 'tests.unit._server_shutdown_scenarios']
-
-processes = []
-process_lock = threading.Lock()
-
-
-# Make sure we attempt to clean up any
-# processes we may have left running
-def cleanup_processes():
- with process_lock:
- for process in processes:
- try:
- process.kill()
- except Exception: # pylint: disable=broad-except
- pass
-
-
-atexit.register(cleanup_processes)
-
-
-def wait(process):
- with process_lock:
- processes.append(process)
- process.wait()
-
-
-class ServerShutdown(unittest.TestCase):
-
- # Currently we shut down a server (if possible) after the Python server
- # instance is garbage collected. This behavior may change in the future.
- def test_deallocated_server_stops(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_server_shutdown_scenarios.SERVER_DEALLOCATED],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_server_exception_exits(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_server_shutdown_scenarios.SERVER_RAISES_EXCEPTION],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- @unittest.skipIf(os.name == 'nt', 'fork not supported on windows')
- def test_server_fork_can_exit(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_server_shutdown_scenarios.SERVER_FORK_CAN_EXIT],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2018 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.
+"""Tests clean shutdown of server on various interpreter exit conditions.
+
+The tests in this module spawn a subprocess for each test case, the
+test is considered successful if it doesn't hang/timeout.
+"""
+
+import atexit
+import os
+import subprocess
+import sys
+import threading
+import unittest
+import logging
+
+from tests.unit import _server_shutdown_scenarios
+
+INTERPRETER = sys.executable
+BASE_COMMAND = [INTERPRETER, '-m', 'tests.unit._server_shutdown_scenarios']
+
+processes = []
+process_lock = threading.Lock()
+
+
+# Make sure we attempt to clean up any
+# processes we may have left running
+def cleanup_processes():
+ with process_lock:
+ for process in processes:
+ try:
+ process.kill()
+ except Exception: # pylint: disable=broad-except
+ pass
+
+
+atexit.register(cleanup_processes)
+
+
+def wait(process):
+ with process_lock:
+ processes.append(process)
+ process.wait()
+
+
+class ServerShutdown(unittest.TestCase):
+
+ # Currently we shut down a server (if possible) after the Python server
+ # instance is garbage collected. This behavior may change in the future.
+ def test_deallocated_server_stops(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_server_shutdown_scenarios.SERVER_DEALLOCATED],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ wait(process)
+
+ def test_server_exception_exits(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_server_shutdown_scenarios.SERVER_RAISES_EXCEPTION],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ wait(process)
+
+ @unittest.skipIf(os.name == 'nt', 'fork not supported on windows')
+ def test_server_fork_can_exit(self):
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ process = subprocess.Popen(
+ BASE_COMMAND + [_server_shutdown_scenarios.SERVER_FORK_CAN_EXIT],
+ stdout=sys.stdout,
+ stderr=sys.stderr,
+ env=env)
+ wait(process)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py
index 35d992a33d..afe0294930 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py
@@ -1,166 +1,166 @@
-# Copyright 2017 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.
-"""Tests server certificate rotation.
-
-Here we test various aspects of gRPC Python, and in some cases gRPC
-Core by extension, support for server certificate rotation.
-
-* ServerSSLCertReloadTestWithClientAuth: test ability to rotate
- server's SSL cert for use in future channels with clients while not
- affecting any existing channel. The server requires client
- authentication.
-
-* ServerSSLCertReloadTestWithoutClientAuth: like
- ServerSSLCertReloadTestWithClientAuth except that the server does
- not authenticate the client.
-
-* ServerSSLCertReloadTestCertConfigReuse: tests gRPC Python's ability
- to deal with user's reuse of ServerCertificateConfiguration instances.
-"""
-
-import abc
-import collections
-import os
-import six
-import threading
-import unittest
-import logging
-
-from concurrent import futures
-
-import grpc
-from tests.unit import resources
-from tests.unit import test_common
-from tests.testing import _application_common
-from tests.testing import _server_application
-from tests.testing.proto import services_pb2_grpc
-
-CA_1_PEM = resources.cert_hier_1_root_ca_cert()
-CA_2_PEM = resources.cert_hier_2_root_ca_cert()
-
-CLIENT_KEY_1_PEM = resources.cert_hier_1_client_1_key()
-CLIENT_CERT_CHAIN_1_PEM = (resources.cert_hier_1_client_1_cert() +
- resources.cert_hier_1_intermediate_ca_cert())
-
-CLIENT_KEY_2_PEM = resources.cert_hier_2_client_1_key()
-CLIENT_CERT_CHAIN_2_PEM = (resources.cert_hier_2_client_1_cert() +
- resources.cert_hier_2_intermediate_ca_cert())
-
-SERVER_KEY_1_PEM = resources.cert_hier_1_server_1_key()
-SERVER_CERT_CHAIN_1_PEM = (resources.cert_hier_1_server_1_cert() +
- resources.cert_hier_1_intermediate_ca_cert())
-
-SERVER_KEY_2_PEM = resources.cert_hier_2_server_1_key()
-SERVER_CERT_CHAIN_2_PEM = (resources.cert_hier_2_server_1_cert() +
- resources.cert_hier_2_intermediate_ca_cert())
-
-# for use with the CertConfigFetcher. Roughly a simple custom mock
-# implementation
-Call = collections.namedtuple('Call', ['did_raise', 'returned_cert_config'])
-
-
-def _create_channel(port, credentials):
- return grpc.secure_channel('localhost:{}'.format(port), credentials)
-
-
-def _create_client_stub(channel, expect_success):
- if expect_success:
- # per Nathaniel: there's some robustness issue if we start
- # using a channel without waiting for it to be actually ready
- grpc.channel_ready_future(channel).result(timeout=10)
- return services_pb2_grpc.FirstServiceStub(channel)
-
-
-class CertConfigFetcher(object):
-
- def __init__(self):
- self._lock = threading.Lock()
- self._calls = []
- self._should_raise = False
- self._cert_config = None
-
- def reset(self):
- with self._lock:
- self._calls = []
- self._should_raise = False
- self._cert_config = None
-
- def configure(self, should_raise, cert_config):
- assert not (should_raise and cert_config), (
- "should not specify both should_raise and a cert_config at the same time"
- )
- with self._lock:
- self._should_raise = should_raise
- self._cert_config = cert_config
-
- def getCalls(self):
- with self._lock:
- return self._calls
-
- def __call__(self):
- with self._lock:
- if self._should_raise:
- self._calls.append(Call(True, None))
- raise ValueError('just for fun, should not affect the test')
- else:
- self._calls.append(Call(False, self._cert_config))
- return self._cert_config
-
-
-class _ServerSSLCertReloadTest(
- six.with_metaclass(abc.ABCMeta, unittest.TestCase)):
-
- def __init__(self, *args, **kwargs):
- super(_ServerSSLCertReloadTest, self).__init__(*args, **kwargs)
- self.server = None
- self.port = None
-
- @abc.abstractmethod
- def require_client_auth(self):
- raise NotImplementedError()
-
- def setUp(self):
- self.server = test_common.test_server()
- services_pb2_grpc.add_FirstServiceServicer_to_server(
- _server_application.FirstServiceServicer(), self.server)
- switch_cert_on_client_num = 10
- initial_cert_config = grpc.ssl_server_certificate_configuration(
- [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)],
- root_certificates=CA_2_PEM)
- self.cert_config_fetcher = CertConfigFetcher()
- server_credentials = grpc.dynamic_ssl_server_credentials(
- initial_cert_config,
- self.cert_config_fetcher,
- require_client_authentication=self.require_client_auth())
- self.port = self.server.add_secure_port('[::]:0', server_credentials)
- self.server.start()
-
- def tearDown(self):
- if self.server:
- self.server.stop(None)
-
- def _perform_rpc(self, client_stub, expect_success):
- # we don't care about the actual response of the rpc; only
- # whether we can perform it or not, and if not, the status
- # code must be UNAVAILABLE
- request = _application_common.UNARY_UNARY_REQUEST
- if expect_success:
- response = client_stub.UnUn(request)
- self.assertEqual(response, _application_common.UNARY_UNARY_RESPONSE)
- else:
- with self.assertRaises(grpc.RpcError) as exception_context:
- client_stub.UnUn(request)
+# Copyright 2017 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.
+"""Tests server certificate rotation.
+
+Here we test various aspects of gRPC Python, and in some cases gRPC
+Core by extension, support for server certificate rotation.
+
+* ServerSSLCertReloadTestWithClientAuth: test ability to rotate
+ server's SSL cert for use in future channels with clients while not
+ affecting any existing channel. The server requires client
+ authentication.
+
+* ServerSSLCertReloadTestWithoutClientAuth: like
+ ServerSSLCertReloadTestWithClientAuth except that the server does
+ not authenticate the client.
+
+* ServerSSLCertReloadTestCertConfigReuse: tests gRPC Python's ability
+ to deal with user's reuse of ServerCertificateConfiguration instances.
+"""
+
+import abc
+import collections
+import os
+import six
+import threading
+import unittest
+import logging
+
+from concurrent import futures
+
+import grpc
+from tests.unit import resources
+from tests.unit import test_common
+from tests.testing import _application_common
+from tests.testing import _server_application
+from tests.testing.proto import services_pb2_grpc
+
+CA_1_PEM = resources.cert_hier_1_root_ca_cert()
+CA_2_PEM = resources.cert_hier_2_root_ca_cert()
+
+CLIENT_KEY_1_PEM = resources.cert_hier_1_client_1_key()
+CLIENT_CERT_CHAIN_1_PEM = (resources.cert_hier_1_client_1_cert() +
+ resources.cert_hier_1_intermediate_ca_cert())
+
+CLIENT_KEY_2_PEM = resources.cert_hier_2_client_1_key()
+CLIENT_CERT_CHAIN_2_PEM = (resources.cert_hier_2_client_1_cert() +
+ resources.cert_hier_2_intermediate_ca_cert())
+
+SERVER_KEY_1_PEM = resources.cert_hier_1_server_1_key()
+SERVER_CERT_CHAIN_1_PEM = (resources.cert_hier_1_server_1_cert() +
+ resources.cert_hier_1_intermediate_ca_cert())
+
+SERVER_KEY_2_PEM = resources.cert_hier_2_server_1_key()
+SERVER_CERT_CHAIN_2_PEM = (resources.cert_hier_2_server_1_cert() +
+ resources.cert_hier_2_intermediate_ca_cert())
+
+# for use with the CertConfigFetcher. Roughly a simple custom mock
+# implementation
+Call = collections.namedtuple('Call', ['did_raise', 'returned_cert_config'])
+
+
+def _create_channel(port, credentials):
+ return grpc.secure_channel('localhost:{}'.format(port), credentials)
+
+
+def _create_client_stub(channel, expect_success):
+ if expect_success:
+ # per Nathaniel: there's some robustness issue if we start
+ # using a channel without waiting for it to be actually ready
+ grpc.channel_ready_future(channel).result(timeout=10)
+ return services_pb2_grpc.FirstServiceStub(channel)
+
+
+class CertConfigFetcher(object):
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._calls = []
+ self._should_raise = False
+ self._cert_config = None
+
+ def reset(self):
+ with self._lock:
+ self._calls = []
+ self._should_raise = False
+ self._cert_config = None
+
+ def configure(self, should_raise, cert_config):
+ assert not (should_raise and cert_config), (
+ "should not specify both should_raise and a cert_config at the same time"
+ )
+ with self._lock:
+ self._should_raise = should_raise
+ self._cert_config = cert_config
+
+ def getCalls(self):
+ with self._lock:
+ return self._calls
+
+ def __call__(self):
+ with self._lock:
+ if self._should_raise:
+ self._calls.append(Call(True, None))
+ raise ValueError('just for fun, should not affect the test')
+ else:
+ self._calls.append(Call(False, self._cert_config))
+ return self._cert_config
+
+
+class _ServerSSLCertReloadTest(
+ six.with_metaclass(abc.ABCMeta, unittest.TestCase)):
+
+ def __init__(self, *args, **kwargs):
+ super(_ServerSSLCertReloadTest, self).__init__(*args, **kwargs)
+ self.server = None
+ self.port = None
+
+ @abc.abstractmethod
+ def require_client_auth(self):
+ raise NotImplementedError()
+
+ def setUp(self):
+ self.server = test_common.test_server()
+ services_pb2_grpc.add_FirstServiceServicer_to_server(
+ _server_application.FirstServiceServicer(), self.server)
+ switch_cert_on_client_num = 10
+ initial_cert_config = grpc.ssl_server_certificate_configuration(
+ [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)],
+ root_certificates=CA_2_PEM)
+ self.cert_config_fetcher = CertConfigFetcher()
+ server_credentials = grpc.dynamic_ssl_server_credentials(
+ initial_cert_config,
+ self.cert_config_fetcher,
+ require_client_authentication=self.require_client_auth())
+ self.port = self.server.add_secure_port('[::]:0', server_credentials)
+ self.server.start()
+
+ def tearDown(self):
+ if self.server:
+ self.server.stop(None)
+
+ def _perform_rpc(self, client_stub, expect_success):
+ # we don't care about the actual response of the rpc; only
+ # whether we can perform it or not, and if not, the status
+ # code must be UNAVAILABLE
+ request = _application_common.UNARY_UNARY_REQUEST
+ if expect_success:
+ response = client_stub.UnUn(request)
+ self.assertEqual(response, _application_common.UNARY_UNARY_RESPONSE)
+ else:
+ with self.assertRaises(grpc.RpcError) as exception_context:
+ client_stub.UnUn(request)
# If TLS 1.2 is used, then the client receives an alert message
# before the handshake is complete, so the status is UNAVAILABLE. If
# TLS 1.3 is used, then the client receives the alert message after
@@ -169,343 +169,343 @@ class _ServerSSLCertReloadTest(
# corresponding status code, so this yields an UNKNOWN status.
self.assertTrue(exception_context.exception.code(
) in [grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.UNKNOWN])
-
- def _do_one_shot_client_rpc(self,
- expect_success,
- root_certificates=None,
- private_key=None,
- certificate_chain=None):
- credentials = grpc.ssl_channel_credentials(
- root_certificates=root_certificates,
- private_key=private_key,
- certificate_chain=certificate_chain)
- with _create_channel(self.port, credentials) as client_channel:
- client_stub = _create_client_stub(client_channel, expect_success)
- self._perform_rpc(client_stub, expect_success)
-
- def _test(self):
- # things should work...
- self.cert_config_fetcher.configure(False, None)
+
+ def _do_one_shot_client_rpc(self,
+ expect_success,
+ root_certificates=None,
+ private_key=None,
+ certificate_chain=None):
+ credentials = grpc.ssl_channel_credentials(
+ root_certificates=root_certificates,
+ private_key=private_key,
+ certificate_chain=certificate_chain)
+ with _create_channel(self.port, credentials) as client_channel:
+ client_stub = _create_client_stub(client_channel, expect_success)
+ self._perform_rpc(client_stub, expect_success)
+
+ def _test(self):
+ # things should work...
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(True,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertIsNone(actual_calls[0].returned_cert_config)
-
- # client should reject server...
- # fails because client trusts ca2 and so will reject server
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertIsNone(actual_calls[0].returned_cert_config)
+
+ # client should reject server...
+ # fails because client trusts ca2 and so will reject server
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(False,
root_certificates=CA_2_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
-
- # should work again...
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(True, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
+
+ # should work again...
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(True, None)
self._do_one_shot_client_rpc(True,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertTrue(actual_calls[0].did_raise)
- self.assertIsNone(actual_calls[0].returned_cert_config)
-
- # if with_client_auth, then client should be rejected by
- # server because client uses key/cert1, but server trusts ca2,
- # so server will reject
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertTrue(actual_calls[0].did_raise)
+ self.assertIsNone(actual_calls[0].returned_cert_config)
+
+ # if with_client_auth, then client should be rejected by
+ # server because client uses key/cert1, but server trusts ca2,
+ # so server will reject
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(not self.require_client_auth(),
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_1_PEM,
certificate_chain=CLIENT_CERT_CHAIN_1_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
-
- # should work again...
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
+
+ # should work again...
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(True,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertIsNone(actual_calls[0].returned_cert_config)
-
- # now create the "persistent" clients
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
- channel_A = _create_channel(
- self.port,
- grpc.ssl_channel_credentials(
- root_certificates=CA_1_PEM,
- private_key=CLIENT_KEY_2_PEM,
- certificate_chain=CLIENT_CERT_CHAIN_2_PEM))
- persistent_client_stub_A = _create_client_stub(channel_A, True)
- self._perform_rpc(persistent_client_stub_A, True)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertIsNone(actual_calls[0].returned_cert_config)
-
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
- channel_B = _create_channel(
- self.port,
- grpc.ssl_channel_credentials(
- root_certificates=CA_1_PEM,
- private_key=CLIENT_KEY_2_PEM,
- certificate_chain=CLIENT_CERT_CHAIN_2_PEM))
- persistent_client_stub_B = _create_client_stub(channel_B, True)
- self._perform_rpc(persistent_client_stub_B, True)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertIsNone(actual_calls[0].returned_cert_config)
-
- # moment of truth!! client should reject server because the
- # server switch cert...
- cert_config = grpc.ssl_server_certificate_configuration(
- [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)],
- root_certificates=CA_1_PEM)
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, cert_config)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertIsNone(actual_calls[0].returned_cert_config)
+
+ # now create the "persistent" clients
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
+ channel_A = _create_channel(
+ self.port,
+ grpc.ssl_channel_credentials(
+ root_certificates=CA_1_PEM,
+ private_key=CLIENT_KEY_2_PEM,
+ certificate_chain=CLIENT_CERT_CHAIN_2_PEM))
+ persistent_client_stub_A = _create_client_stub(channel_A, True)
+ self._perform_rpc(persistent_client_stub_A, True)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertIsNone(actual_calls[0].returned_cert_config)
+
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
+ channel_B = _create_channel(
+ self.port,
+ grpc.ssl_channel_credentials(
+ root_certificates=CA_1_PEM,
+ private_key=CLIENT_KEY_2_PEM,
+ certificate_chain=CLIENT_CERT_CHAIN_2_PEM))
+ persistent_client_stub_B = _create_client_stub(channel_B, True)
+ self._perform_rpc(persistent_client_stub_B, True)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertIsNone(actual_calls[0].returned_cert_config)
+
+ # moment of truth!! client should reject server because the
+ # server switch cert...
+ cert_config = grpc.ssl_server_certificate_configuration(
+ [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)],
+ root_certificates=CA_1_PEM)
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, cert_config)
self._do_one_shot_client_rpc(False,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertEqual(call.returned_cert_config, cert_config,
- 'i= {}'.format(i))
-
- # now should work again...
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertEqual(call.returned_cert_config, cert_config,
+ 'i= {}'.format(i))
+
+ # now should work again...
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(True,
root_certificates=CA_2_PEM,
private_key=CLIENT_KEY_1_PEM,
certificate_chain=CLIENT_CERT_CHAIN_1_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertIsNone(actual_calls[0].returned_cert_config)
-
- # client should be rejected by server if with_client_auth
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertIsNone(actual_calls[0].returned_cert_config)
+
+ # client should be rejected by server if with_client_auth
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(not self.require_client_auth(),
root_certificates=CA_2_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
-
- # here client should reject server...
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
+
+ # here client should reject server...
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
self._do_one_shot_client_rpc(False,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
-
- # persistent clients should continue to work
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
- self._perform_rpc(persistent_client_stub_A, True)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 0)
-
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, None)
- self._perform_rpc(persistent_client_stub_B, True)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 0)
-
- channel_A.close()
- channel_B.close()
-
-
-class ServerSSLCertConfigFetcherParamsChecks(unittest.TestCase):
-
- def test_check_on_initial_config(self):
- with self.assertRaises(TypeError):
- grpc.dynamic_ssl_server_credentials(None, str)
- with self.assertRaises(TypeError):
- grpc.dynamic_ssl_server_credentials(1, str)
-
- def test_check_on_config_fetcher(self):
- cert_config = grpc.ssl_server_certificate_configuration(
- [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)],
- root_certificates=CA_1_PEM)
- with self.assertRaises(TypeError):
- grpc.dynamic_ssl_server_credentials(cert_config, None)
- with self.assertRaises(TypeError):
- grpc.dynamic_ssl_server_credentials(cert_config, 1)
-
-
-class ServerSSLCertReloadTestWithClientAuth(_ServerSSLCertReloadTest):
-
- def require_client_auth(self):
- return True
-
- test = _ServerSSLCertReloadTest._test
-
-
-class ServerSSLCertReloadTestWithoutClientAuth(_ServerSSLCertReloadTest):
-
- def require_client_auth(self):
- return False
-
- test = _ServerSSLCertReloadTest._test
-
-
-class ServerSSLCertReloadTestCertConfigReuse(_ServerSSLCertReloadTest):
- """Ensures that `ServerCertificateConfiguration` instances can be reused.
-
- Because gRPC Core takes ownership of the
- `grpc_ssl_server_certificate_config` encapsulated by
- `ServerCertificateConfiguration`, this test reuses the same
- `ServerCertificateConfiguration` instances multiple times to make sure
- gRPC Python takes care of maintaining the validity of
- `ServerCertificateConfiguration` instances, so that such instances can be
- re-used by user application.
- """
-
- def require_client_auth(self):
- return True
-
- def setUp(self):
- self.server = test_common.test_server()
- services_pb2_grpc.add_FirstServiceServicer_to_server(
- _server_application.FirstServiceServicer(), self.server)
- self.cert_config_A = grpc.ssl_server_certificate_configuration(
- [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)],
- root_certificates=CA_2_PEM)
- self.cert_config_B = grpc.ssl_server_certificate_configuration(
- [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)],
- root_certificates=CA_1_PEM)
- self.cert_config_fetcher = CertConfigFetcher()
- server_credentials = grpc.dynamic_ssl_server_credentials(
- self.cert_config_A,
- self.cert_config_fetcher,
- require_client_authentication=True)
- self.port = self.server.add_secure_port('[::]:0', server_credentials)
- self.server.start()
-
- def test_cert_config_reuse(self):
-
- # succeed with A
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, self.cert_config_A)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i))
+
+ # persistent clients should continue to work
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
+ self._perform_rpc(persistent_client_stub_A, True)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 0)
+
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, None)
+ self._perform_rpc(persistent_client_stub_B, True)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 0)
+
+ channel_A.close()
+ channel_B.close()
+
+
+class ServerSSLCertConfigFetcherParamsChecks(unittest.TestCase):
+
+ def test_check_on_initial_config(self):
+ with self.assertRaises(TypeError):
+ grpc.dynamic_ssl_server_credentials(None, str)
+ with self.assertRaises(TypeError):
+ grpc.dynamic_ssl_server_credentials(1, str)
+
+ def test_check_on_config_fetcher(self):
+ cert_config = grpc.ssl_server_certificate_configuration(
+ [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)],
+ root_certificates=CA_1_PEM)
+ with self.assertRaises(TypeError):
+ grpc.dynamic_ssl_server_credentials(cert_config, None)
+ with self.assertRaises(TypeError):
+ grpc.dynamic_ssl_server_credentials(cert_config, 1)
+
+
+class ServerSSLCertReloadTestWithClientAuth(_ServerSSLCertReloadTest):
+
+ def require_client_auth(self):
+ return True
+
+ test = _ServerSSLCertReloadTest._test
+
+
+class ServerSSLCertReloadTestWithoutClientAuth(_ServerSSLCertReloadTest):
+
+ def require_client_auth(self):
+ return False
+
+ test = _ServerSSLCertReloadTest._test
+
+
+class ServerSSLCertReloadTestCertConfigReuse(_ServerSSLCertReloadTest):
+ """Ensures that `ServerCertificateConfiguration` instances can be reused.
+
+ Because gRPC Core takes ownership of the
+ `grpc_ssl_server_certificate_config` encapsulated by
+ `ServerCertificateConfiguration`, this test reuses the same
+ `ServerCertificateConfiguration` instances multiple times to make sure
+ gRPC Python takes care of maintaining the validity of
+ `ServerCertificateConfiguration` instances, so that such instances can be
+ re-used by user application.
+ """
+
+ def require_client_auth(self):
+ return True
+
+ def setUp(self):
+ self.server = test_common.test_server()
+ services_pb2_grpc.add_FirstServiceServicer_to_server(
+ _server_application.FirstServiceServicer(), self.server)
+ self.cert_config_A = grpc.ssl_server_certificate_configuration(
+ [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)],
+ root_certificates=CA_2_PEM)
+ self.cert_config_B = grpc.ssl_server_certificate_configuration(
+ [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)],
+ root_certificates=CA_1_PEM)
+ self.cert_config_fetcher = CertConfigFetcher()
+ server_credentials = grpc.dynamic_ssl_server_credentials(
+ self.cert_config_A,
+ self.cert_config_fetcher,
+ require_client_authentication=True)
+ self.port = self.server.add_secure_port('[::]:0', server_credentials)
+ self.server.start()
+
+ def test_cert_config_reuse(self):
+
+ # succeed with A
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, self.cert_config_A)
self._do_one_shot_client_rpc(True,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertEqual(actual_calls[0].returned_cert_config,
- self.cert_config_A)
-
- # fail with A
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, self.cert_config_A)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertEqual(actual_calls[0].returned_cert_config,
+ self.cert_config_A)
+
+ # fail with A
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, self.cert_config_A)
self._do_one_shot_client_rpc(False,
root_certificates=CA_2_PEM,
private_key=CLIENT_KEY_1_PEM,
certificate_chain=CLIENT_CERT_CHAIN_1_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertEqual(call.returned_cert_config, self.cert_config_A,
- 'i= {}'.format(i))
-
- # succeed again with A
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, self.cert_config_A)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertEqual(call.returned_cert_config, self.cert_config_A,
+ 'i= {}'.format(i))
+
+ # succeed again with A
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, self.cert_config_A)
self._do_one_shot_client_rpc(True,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertEqual(actual_calls[0].returned_cert_config,
- self.cert_config_A)
-
- # succeed with B
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, self.cert_config_B)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertEqual(actual_calls[0].returned_cert_config,
+ self.cert_config_A)
+
+ # succeed with B
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, self.cert_config_B)
self._do_one_shot_client_rpc(True,
root_certificates=CA_2_PEM,
private_key=CLIENT_KEY_1_PEM,
certificate_chain=CLIENT_CERT_CHAIN_1_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertEqual(actual_calls[0].returned_cert_config,
- self.cert_config_B)
-
- # fail with B
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, self.cert_config_B)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertEqual(actual_calls[0].returned_cert_config,
+ self.cert_config_B)
+
+ # fail with B
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, self.cert_config_B)
self._do_one_shot_client_rpc(False,
root_certificates=CA_1_PEM,
private_key=CLIENT_KEY_2_PEM,
certificate_chain=CLIENT_CERT_CHAIN_2_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertGreaterEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- for i, call in enumerate(actual_calls):
- self.assertFalse(call.did_raise, 'i= {}'.format(i))
- self.assertEqual(call.returned_cert_config, self.cert_config_B,
- 'i= {}'.format(i))
-
- # succeed again with B
- self.cert_config_fetcher.reset()
- self.cert_config_fetcher.configure(False, self.cert_config_B)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertGreaterEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ for i, call in enumerate(actual_calls):
+ self.assertFalse(call.did_raise, 'i= {}'.format(i))
+ self.assertEqual(call.returned_cert_config, self.cert_config_B,
+ 'i= {}'.format(i))
+
+ # succeed again with B
+ self.cert_config_fetcher.reset()
+ self.cert_config_fetcher.configure(False, self.cert_config_B)
self._do_one_shot_client_rpc(True,
root_certificates=CA_2_PEM,
private_key=CLIENT_KEY_1_PEM,
certificate_chain=CLIENT_CERT_CHAIN_1_PEM)
- actual_calls = self.cert_config_fetcher.getCalls()
- self.assertEqual(len(actual_calls), 1)
- self.assertFalse(actual_calls[0].did_raise)
- self.assertEqual(actual_calls[0].returned_cert_config,
- self.cert_config_B)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ actual_calls = self.cert_config_fetcher.getCalls()
+ self.assertEqual(len(actual_calls), 1)
+ self.assertFalse(actual_calls[0].did_raise)
+ self.assertEqual(actual_calls[0].returned_cert_config,
+ self.cert_config_B)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py
index 3c519219d5..4907f74d1f 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py
@@ -1,59 +1,59 @@
-# Copyright 2018 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from concurrent import futures
-import unittest
-import logging
-
-import grpc
-
+# Copyright 2018 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from concurrent import futures
+import unittest
+import logging
+
+import grpc
+
from tests.unit import resources
+
-
-class _ActualGenericRpcHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- return None
-
-
-class ServerTest(unittest.TestCase):
-
- def test_not_a_generic_rpc_handler_at_construction(self):
- with self.assertRaises(AttributeError) as exception_context:
+class _ActualGenericRpcHandler(grpc.GenericRpcHandler):
+
+ def service(self, handler_call_details):
+ return None
+
+
+class ServerTest(unittest.TestCase):
+
+ def test_not_a_generic_rpc_handler_at_construction(self):
+ with self.assertRaises(AttributeError) as exception_context:
grpc.server(futures.ThreadPoolExecutor(max_workers=5),
handlers=[
_ActualGenericRpcHandler(),
object(),
])
- self.assertIn('grpc.GenericRpcHandler',
- str(exception_context.exception))
-
- def test_not_a_generic_rpc_handler_after_construction(self):
- server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
- with self.assertRaises(AttributeError) as exception_context:
- server.add_generic_rpc_handlers([
- _ActualGenericRpcHandler(),
- object(),
- ])
- self.assertIn('grpc.GenericRpcHandler',
- str(exception_context.exception))
-
+ self.assertIn('grpc.GenericRpcHandler',
+ str(exception_context.exception))
+
+ def test_not_a_generic_rpc_handler_after_construction(self):
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
+ with self.assertRaises(AttributeError) as exception_context:
+ server.add_generic_rpc_handlers([
+ _ActualGenericRpcHandler(),
+ object(),
+ ])
+ self.assertIn('grpc.GenericRpcHandler',
+ str(exception_context.exception))
+
def test_failed_port_binding_exception(self):
server = grpc.server(None, options=(('grpc.so_reuseport', 0),))
port = server.add_insecure_port('localhost:0')
bind_address = "localhost:%d" % port
-
+
with self.assertRaises(RuntimeError):
server.add_insecure_port(bind_address)
@@ -64,6 +64,6 @@ class ServerTest(unittest.TestCase):
server.add_secure_port(bind_address, server_credentials)
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py
index 3dd95ea8bf..7f9fc1a9a5 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py
@@ -1,91 +1,91 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from __future__ import division
-
-import datetime
-from concurrent import futures
-import unittest
-import time
-import threading
-import six
-
-import grpc
-from tests.unit.framework.common import test_constants
-
-_WAIT_FOR_BLOCKING = datetime.timedelta(seconds=1)
-
-
-def _block_on_waiting(server, termination_event, timeout=None):
- server.start()
- server.wait_for_termination(timeout=timeout)
- termination_event.set()
-
-
-class ServerWaitForTerminationTest(unittest.TestCase):
-
- def test_unblock_by_invoking_stop(self):
- termination_event = threading.Event()
- server = grpc.server(futures.ThreadPoolExecutor())
-
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import division
+
+import datetime
+from concurrent import futures
+import unittest
+import time
+import threading
+import six
+
+import grpc
+from tests.unit.framework.common import test_constants
+
+_WAIT_FOR_BLOCKING = datetime.timedelta(seconds=1)
+
+
+def _block_on_waiting(server, termination_event, timeout=None):
+ server.start()
+ server.wait_for_termination(timeout=timeout)
+ termination_event.set()
+
+
+class ServerWaitForTerminationTest(unittest.TestCase):
+
+ def test_unblock_by_invoking_stop(self):
+ termination_event = threading.Event()
+ server = grpc.server(futures.ThreadPoolExecutor())
+
wait_thread = threading.Thread(target=_block_on_waiting,
args=(
server,
termination_event,
))
- wait_thread.daemon = True
- wait_thread.start()
- time.sleep(_WAIT_FOR_BLOCKING.total_seconds())
-
- server.stop(None)
- termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
- self.assertTrue(termination_event.is_set())
-
- def test_unblock_by_del(self):
- termination_event = threading.Event()
- server = grpc.server(futures.ThreadPoolExecutor())
-
+ wait_thread.daemon = True
+ wait_thread.start()
+ time.sleep(_WAIT_FOR_BLOCKING.total_seconds())
+
+ server.stop(None)
+ termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertTrue(termination_event.is_set())
+
+ def test_unblock_by_del(self):
+ termination_event = threading.Event()
+ server = grpc.server(futures.ThreadPoolExecutor())
+
wait_thread = threading.Thread(target=_block_on_waiting,
args=(
server,
termination_event,
))
- wait_thread.daemon = True
- wait_thread.start()
- time.sleep(_WAIT_FOR_BLOCKING.total_seconds())
-
- # Invoke manually here, in Python 2 it will be invoked by GC sometime.
- server.__del__()
- termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
- self.assertTrue(termination_event.is_set())
-
- def test_unblock_by_timeout(self):
- termination_event = threading.Event()
- server = grpc.server(futures.ThreadPoolExecutor())
-
+ wait_thread.daemon = True
+ wait_thread.start()
+ time.sleep(_WAIT_FOR_BLOCKING.total_seconds())
+
+ # Invoke manually here, in Python 2 it will be invoked by GC sometime.
+ server.__del__()
+ termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertTrue(termination_event.is_set())
+
+ def test_unblock_by_timeout(self):
+ termination_event = threading.Event()
+ server = grpc.server(futures.ThreadPoolExecutor())
+
wait_thread = threading.Thread(target=_block_on_waiting,
args=(
server,
termination_event,
test_constants.SHORT_TIMEOUT / 2,
))
- wait_thread.daemon = True
- wait_thread.start()
-
- termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
- self.assertTrue(termination_event.is_set())
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ wait_thread.daemon = True
+ wait_thread.start()
+
+ termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertTrue(termination_event.is_set())
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_session_cache_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_session_cache_test.py
index 9bff4d2af0..95a0c87e89 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_session_cache_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_session_cache_test.py
@@ -1,106 +1,106 @@
-# Copyright 2018 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.
-"""Tests experimental TLS Session Resumption API"""
-
-import pickle
-import unittest
-import logging
-
-import grpc
-from grpc import _channel
-from grpc.experimental import session_cache
-
-from tests.unit import test_common
-from tests.unit import resources
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-
-_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
-_ID = 'id'
-_ID_KEY = 'id_key'
-_AUTH_CTX = 'auth_ctx'
-
-_PRIVATE_KEY = resources.private_key()
-_CERTIFICATE_CHAIN = resources.certificate_chain()
-_TEST_ROOT_CERTIFICATES = resources.test_root_certificates()
-_SERVER_CERTS = ((_PRIVATE_KEY, _CERTIFICATE_CHAIN),)
-_PROPERTY_OPTIONS = ((
- 'grpc.ssl_target_name_override',
- _SERVER_HOST_OVERRIDE,
-),)
-
-
-def handle_unary_unary(request, servicer_context):
- return pickle.dumps({
- _ID: servicer_context.peer_identities(),
- _ID_KEY: servicer_context.peer_identity_key(),
- _AUTH_CTX: servicer_context.auth_context()
- })
-
-
-def start_secure_server():
+# Copyright 2018 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.
+"""Tests experimental TLS Session Resumption API"""
+
+import pickle
+import unittest
+import logging
+
+import grpc
+from grpc import _channel
+from grpc.experimental import session_cache
+
+from tests.unit import test_common
+from tests.unit import resources
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x00\x00\x00'
+
+_UNARY_UNARY = '/test/UnaryUnary'
+
+_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
+_ID = 'id'
+_ID_KEY = 'id_key'
+_AUTH_CTX = 'auth_ctx'
+
+_PRIVATE_KEY = resources.private_key()
+_CERTIFICATE_CHAIN = resources.certificate_chain()
+_TEST_ROOT_CERTIFICATES = resources.test_root_certificates()
+_SERVER_CERTS = ((_PRIVATE_KEY, _CERTIFICATE_CHAIN),)
+_PROPERTY_OPTIONS = ((
+ 'grpc.ssl_target_name_override',
+ _SERVER_HOST_OVERRIDE,
+),)
+
+
+def handle_unary_unary(request, servicer_context):
+ return pickle.dumps({
+ _ID: servicer_context.peer_identities(),
+ _ID_KEY: servicer_context.peer_identity_key(),
+ _AUTH_CTX: servicer_context.auth_context()
+ })
+
+
+def start_secure_server():
handler = grpc.method_handlers_generic_handler(
'test',
{'UnaryUnary': grpc.unary_unary_rpc_method_handler(handle_unary_unary)})
- server = test_common.test_server()
- server.add_generic_rpc_handlers((handler,))
- server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
- port = server.add_secure_port('[::]:0', server_cred)
- server.start()
-
- return server, port
-
-
-class SSLSessionCacheTest(unittest.TestCase):
-
- def _do_one_shot_client_rpc(self, channel_creds, channel_options, port,
- expect_ssl_session_reused):
+ server = test_common.test_server()
+ server.add_generic_rpc_handlers((handler,))
+ server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
+ port = server.add_secure_port('[::]:0', server_cred)
+ server.start()
+
+ return server, port
+
+
+class SSLSessionCacheTest(unittest.TestCase):
+
+ def _do_one_shot_client_rpc(self, channel_creds, channel_options, port,
+ expect_ssl_session_reused):
channel = grpc.secure_channel('localhost:{}'.format(port),
channel_creds,
options=channel_options)
- response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- auth_data = pickle.loads(response)
- self.assertEqual(expect_ssl_session_reused,
- auth_data[_AUTH_CTX]['ssl_session_reused'])
- channel.close()
-
- def testSSLSessionCacheLRU(self):
- server_1, port_1 = start_secure_server()
-
- cache = session_cache.ssl_session_cache_lru(1)
- channel_creds = grpc.ssl_channel_credentials(
- root_certificates=_TEST_ROOT_CERTIFICATES)
- channel_options = _PROPERTY_OPTIONS + (
- ('grpc.ssl_session_cache', cache),)
-
- # Initial connection has no session to resume
+ response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
+ auth_data = pickle.loads(response)
+ self.assertEqual(expect_ssl_session_reused,
+ auth_data[_AUTH_CTX]['ssl_session_reused'])
+ channel.close()
+
+ def testSSLSessionCacheLRU(self):
+ server_1, port_1 = start_secure_server()
+
+ cache = session_cache.ssl_session_cache_lru(1)
+ channel_creds = grpc.ssl_channel_credentials(
+ root_certificates=_TEST_ROOT_CERTIFICATES)
+ channel_options = _PROPERTY_OPTIONS + (
+ ('grpc.ssl_session_cache', cache),)
+
+ # Initial connection has no session to resume
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port_1,
expect_ssl_session_reused=[b'false'])
-
- # Connection to server_1 resumes from initial session
+
+ # Connection to server_1 resumes from initial session
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port_1,
expect_ssl_session_reused=[b'true'])
-
- # Connection to a different server with the same name overwrites the cache entry
- server_2, port_2 = start_secure_server()
+
+ # Connection to a different server with the same name overwrites the cache entry
+ server_2, port_2 = start_secure_server()
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port_2,
@@ -109,32 +109,32 @@ class SSLSessionCacheTest(unittest.TestCase):
channel_options,
port_2,
expect_ssl_session_reused=[b'true'])
- server_2.stop(None)
-
- # Connection to server_1 now falls back to full TLS handshake
+ server_2.stop(None)
+
+ # Connection to server_1 now falls back to full TLS handshake
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port_1,
expect_ssl_session_reused=[b'false'])
-
- # Re-creating server_1 causes old sessions to become invalid
- server_1.stop(None)
- server_1, port_1 = start_secure_server()
-
- # Old sessions should no longer be valid
+
+ # Re-creating server_1 causes old sessions to become invalid
+ server_1.stop(None)
+ server_1, port_1 = start_secure_server()
+
+ # Old sessions should no longer be valid
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port_1,
expect_ssl_session_reused=[b'false'])
-
- # Resumption should work for subsequent connections
+
+ # Resumption should work for subsequent connections
self._do_one_shot_client_rpc(channel_creds,
channel_options,
port_1,
expect_ssl_session_reused=[b'true'])
- server_1.stop(None)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+ server_1.stop(None)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py
index 0be1270749..9d8c17c851 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py
@@ -1,119 +1,119 @@
-# Copyright 2019 the gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Client for testing responsiveness to signals."""
-
-from __future__ import print_function
-
-import argparse
-import functools
-import logging
-import signal
-import sys
-
-import grpc
-
-SIGTERM_MESSAGE = "Handling sigterm!"
-
-UNARY_UNARY = "/test/Unary"
-UNARY_STREAM = "/test/ServerStreaming"
-
-_MESSAGE = b'\x00\x00\x00'
-
-_ASSERTION_MESSAGE = "Control flow should never reach here."
-
-# NOTE(gnossen): We use a global variable here so that the signal handler can be
-# installed before the RPC begins. If we do not do this, then we may receive the
-# SIGINT before the signal handler is installed. I'm not happy with per-process
-# global state, but the per-process global state that is signal handlers
-# somewhat forces my hand.
-per_process_rpc_future = None
-
-
-def handle_sigint(unused_signum, unused_frame):
- print(SIGTERM_MESSAGE)
- if per_process_rpc_future is not None:
- per_process_rpc_future.cancel()
- sys.stderr.flush()
- # This sys.exit(0) avoids an exception caused by the cancelled RPC.
- sys.exit(0)
-
-
-def main_unary(server_target):
- """Initiate a unary RPC to be interrupted by a SIGINT."""
- global per_process_rpc_future # pylint: disable=global-statement
- with grpc.insecure_channel(server_target) as channel:
- multicallable = channel.unary_unary(UNARY_UNARY)
- signal.signal(signal.SIGINT, handle_sigint)
+# Copyright 2019 the gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Client for testing responsiveness to signals."""
+
+from __future__ import print_function
+
+import argparse
+import functools
+import logging
+import signal
+import sys
+
+import grpc
+
+SIGTERM_MESSAGE = "Handling sigterm!"
+
+UNARY_UNARY = "/test/Unary"
+UNARY_STREAM = "/test/ServerStreaming"
+
+_MESSAGE = b'\x00\x00\x00'
+
+_ASSERTION_MESSAGE = "Control flow should never reach here."
+
+# NOTE(gnossen): We use a global variable here so that the signal handler can be
+# installed before the RPC begins. If we do not do this, then we may receive the
+# SIGINT before the signal handler is installed. I'm not happy with per-process
+# global state, but the per-process global state that is signal handlers
+# somewhat forces my hand.
+per_process_rpc_future = None
+
+
+def handle_sigint(unused_signum, unused_frame):
+ print(SIGTERM_MESSAGE)
+ if per_process_rpc_future is not None:
+ per_process_rpc_future.cancel()
+ sys.stderr.flush()
+ # This sys.exit(0) avoids an exception caused by the cancelled RPC.
+ sys.exit(0)
+
+
+def main_unary(server_target):
+ """Initiate a unary RPC to be interrupted by a SIGINT."""
+ global per_process_rpc_future # pylint: disable=global-statement
+ with grpc.insecure_channel(server_target) as channel:
+ multicallable = channel.unary_unary(UNARY_UNARY)
+ signal.signal(signal.SIGINT, handle_sigint)
per_process_rpc_future = multicallable.future(_MESSAGE,
wait_for_ready=True)
- result = per_process_rpc_future.result()
- assert False, _ASSERTION_MESSAGE
-
-
-def main_streaming(server_target):
- """Initiate a streaming RPC to be interrupted by a SIGINT."""
- global per_process_rpc_future # pylint: disable=global-statement
- with grpc.insecure_channel(server_target) as channel:
- signal.signal(signal.SIGINT, handle_sigint)
- per_process_rpc_future = channel.unary_stream(UNARY_STREAM)(
- _MESSAGE, wait_for_ready=True)
- for result in per_process_rpc_future:
- pass
- assert False, _ASSERTION_MESSAGE
-
-
-def main_unary_with_exception(server_target):
- """Initiate a unary RPC with a signal handler that will raise."""
- channel = grpc.insecure_channel(server_target)
- try:
- channel.unary_unary(UNARY_UNARY)(_MESSAGE, wait_for_ready=True)
- except KeyboardInterrupt:
- sys.stderr.write("Running signal handler.\n")
- sys.stderr.flush()
-
- # This call should not hang.
- channel.close()
-
-
-def main_streaming_with_exception(server_target):
- """Initiate a streaming RPC with a signal handler that will raise."""
- channel = grpc.insecure_channel(server_target)
- try:
+ result = per_process_rpc_future.result()
+ assert False, _ASSERTION_MESSAGE
+
+
+def main_streaming(server_target):
+ """Initiate a streaming RPC to be interrupted by a SIGINT."""
+ global per_process_rpc_future # pylint: disable=global-statement
+ with grpc.insecure_channel(server_target) as channel:
+ signal.signal(signal.SIGINT, handle_sigint)
+ per_process_rpc_future = channel.unary_stream(UNARY_STREAM)(
+ _MESSAGE, wait_for_ready=True)
+ for result in per_process_rpc_future:
+ pass
+ assert False, _ASSERTION_MESSAGE
+
+
+def main_unary_with_exception(server_target):
+ """Initiate a unary RPC with a signal handler that will raise."""
+ channel = grpc.insecure_channel(server_target)
+ try:
+ channel.unary_unary(UNARY_UNARY)(_MESSAGE, wait_for_ready=True)
+ except KeyboardInterrupt:
+ sys.stderr.write("Running signal handler.\n")
+ sys.stderr.flush()
+
+ # This call should not hang.
+ channel.close()
+
+
+def main_streaming_with_exception(server_target):
+ """Initiate a streaming RPC with a signal handler that will raise."""
+ channel = grpc.insecure_channel(server_target)
+ try:
for _ in channel.unary_stream(UNARY_STREAM)(_MESSAGE,
wait_for_ready=True):
- pass
- except KeyboardInterrupt:
- sys.stderr.write("Running signal handler.\n")
- sys.stderr.flush()
-
- # This call should not hang.
- channel.close()
-
-
-if __name__ == '__main__':
- parser = argparse.ArgumentParser(description='Signal test client.')
- parser.add_argument('server', help='Server target')
- parser.add_argument('arity', help='Arity', choices=('unary', 'streaming'))
+ pass
+ except KeyboardInterrupt:
+ sys.stderr.write("Running signal handler.\n")
+ sys.stderr.flush()
+
+ # This call should not hang.
+ channel.close()
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Signal test client.')
+ parser.add_argument('server', help='Server target')
+ parser.add_argument('arity', help='Arity', choices=('unary', 'streaming'))
parser.add_argument('--exception',
help='Whether the signal throws an exception',
action='store_true')
- args = parser.parse_args()
- if args.arity == 'unary' and not args.exception:
- main_unary(args.server)
- elif args.arity == 'streaming' and not args.exception:
- main_streaming(args.server)
- elif args.arity == 'unary' and args.exception:
- main_unary_with_exception(args.server)
- else:
- main_streaming_with_exception(args.server)
+ args = parser.parse_args()
+ if args.arity == 'unary' and not args.exception:
+ main_unary(args.server)
+ elif args.arity == 'streaming' and not args.exception:
+ main_streaming(args.server)
+ elif args.arity == 'unary' and args.exception:
+ main_unary_with_exception(args.server)
+ else:
+ main_streaming_with_exception(args.server)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py
index a05e42d5a3..9de3fe0505 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py
@@ -1,200 +1,200 @@
-# Copyright 2019 the gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of responsiveness to signals."""
-
-import logging
-import os
-import signal
-import subprocess
-import tempfile
-import threading
-import unittest
-import sys
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit import _signal_client
-
-_CLIENT_PATH = None
-if sys.executable is not None:
- _CLIENT_PATH = 'tests.unit._signal_client'
-else:
- # NOTE(rbellevi): For compatibility with internal testing.
- if len(sys.argv) != 2:
- raise RuntimeError("Must supply path to executable client.")
- client_name = sys.argv[1].split("/")[-1]
- del sys.argv[1] # For compatibility with test runner.
- _CLIENT_PATH = os.path.realpath(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), client_name))
-
-_HOST = 'localhost'
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self):
- self._connected_clients_lock = threading.RLock()
- self._connected_clients_event = threading.Event()
- self._connected_clients = 0
-
- self._unary_unary_handler = grpc.unary_unary_rpc_method_handler(
- self._handle_unary_unary)
- self._unary_stream_handler = grpc.unary_stream_rpc_method_handler(
- self._handle_unary_stream)
-
- def _on_client_connect(self):
- with self._connected_clients_lock:
- self._connected_clients += 1
- self._connected_clients_event.set()
-
- def _on_client_disconnect(self):
- with self._connected_clients_lock:
- self._connected_clients -= 1
- if self._connected_clients == 0:
- self._connected_clients_event.clear()
-
- def await_connected_client(self):
- """Blocks until a client connects to the server."""
- self._connected_clients_event.wait()
-
- def _handle_unary_unary(self, request, servicer_context):
- """Handles a unary RPC.
-
- Blocks until the client disconnects and then echoes.
- """
- stop_event = threading.Event()
-
- def on_rpc_end():
- self._on_client_disconnect()
- stop_event.set()
-
- servicer_context.add_callback(on_rpc_end)
- self._on_client_connect()
- stop_event.wait()
- return request
-
- def _handle_unary_stream(self, request, servicer_context):
- """Handles a server streaming RPC.
-
- Blocks until the client disconnects and then echoes.
- """
- stop_event = threading.Event()
-
- def on_rpc_end():
- self._on_client_disconnect()
- stop_event.set()
-
- servicer_context.add_callback(on_rpc_end)
- self._on_client_connect()
- stop_event.wait()
- yield request
-
- def service(self, handler_call_details):
- if handler_call_details.method == _signal_client.UNARY_UNARY:
- return self._unary_unary_handler
- elif handler_call_details.method == _signal_client.UNARY_STREAM:
- return self._unary_stream_handler
- else:
- return None
-
-
-def _read_stream(stream):
- stream.seek(0)
- return stream.read()
-
-
-def _start_client(args, stdout, stderr):
- invocation = None
- if sys.executable is not None:
- invocation = (sys.executable, '-m', _CLIENT_PATH) + tuple(args)
- else:
- invocation = (_CLIENT_PATH,) + tuple(args)
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- return subprocess.Popen(invocation, stdout=stdout, stderr=stderr, env=env)
-
-
-class SignalHandlingTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._port = self._server.add_insecure_port('{}:0'.format(_HOST))
- self._handler = _GenericHandler()
- self._server.add_generic_rpc_handlers((self._handler,))
- self._server.start()
-
- def tearDown(self):
- self._server.stop(None)
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testUnary(self):
- """Tests that the server unary code path does not stall signal handlers."""
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client((server_target, 'unary'), client_stdout,
- client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- self.assertFalse(client.wait(), msg=_read_stream(client_stderr))
- client_stdout.seek(0)
- self.assertIn(_signal_client.SIGTERM_MESSAGE,
- client_stdout.read())
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testStreaming(self):
- """Tests that the server streaming code path does not stall signal handlers."""
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client((server_target, 'streaming'),
- client_stdout, client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- self.assertFalse(client.wait(), msg=_read_stream(client_stderr))
- client_stdout.seek(0)
- self.assertIn(_signal_client.SIGTERM_MESSAGE,
- client_stdout.read())
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testUnaryWithException(self):
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client(('--exception', server_target, 'unary'),
- client_stdout, client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- client.wait()
- self.assertEqual(0, client.returncode)
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testStreamingHandlerWithException(self):
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client(
- ('--exception', server_target, 'streaming'), client_stdout,
- client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- client.wait()
- print(_read_stream(client_stderr))
- self.assertEqual(0, client.returncode)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2019 the gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Test of responsiveness to signals."""
+
+import logging
+import os
+import signal
+import subprocess
+import tempfile
+import threading
+import unittest
+import sys
+
+import grpc
+
+from tests.unit import test_common
+from tests.unit import _signal_client
+
+_CLIENT_PATH = None
+if sys.executable is not None:
+ _CLIENT_PATH = 'tests.unit._signal_client'
+else:
+ # NOTE(rbellevi): For compatibility with internal testing.
+ if len(sys.argv) != 2:
+ raise RuntimeError("Must supply path to executable client.")
+ client_name = sys.argv[1].split("/")[-1]
+ del sys.argv[1] # For compatibility with test runner.
+ _CLIENT_PATH = os.path.realpath(
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), client_name))
+
+_HOST = 'localhost'
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self):
+ self._connected_clients_lock = threading.RLock()
+ self._connected_clients_event = threading.Event()
+ self._connected_clients = 0
+
+ self._unary_unary_handler = grpc.unary_unary_rpc_method_handler(
+ self._handle_unary_unary)
+ self._unary_stream_handler = grpc.unary_stream_rpc_method_handler(
+ self._handle_unary_stream)
+
+ def _on_client_connect(self):
+ with self._connected_clients_lock:
+ self._connected_clients += 1
+ self._connected_clients_event.set()
+
+ def _on_client_disconnect(self):
+ with self._connected_clients_lock:
+ self._connected_clients -= 1
+ if self._connected_clients == 0:
+ self._connected_clients_event.clear()
+
+ def await_connected_client(self):
+ """Blocks until a client connects to the server."""
+ self._connected_clients_event.wait()
+
+ def _handle_unary_unary(self, request, servicer_context):
+ """Handles a unary RPC.
+
+ Blocks until the client disconnects and then echoes.
+ """
+ stop_event = threading.Event()
+
+ def on_rpc_end():
+ self._on_client_disconnect()
+ stop_event.set()
+
+ servicer_context.add_callback(on_rpc_end)
+ self._on_client_connect()
+ stop_event.wait()
+ return request
+
+ def _handle_unary_stream(self, request, servicer_context):
+ """Handles a server streaming RPC.
+
+ Blocks until the client disconnects and then echoes.
+ """
+ stop_event = threading.Event()
+
+ def on_rpc_end():
+ self._on_client_disconnect()
+ stop_event.set()
+
+ servicer_context.add_callback(on_rpc_end)
+ self._on_client_connect()
+ stop_event.wait()
+ yield request
+
+ def service(self, handler_call_details):
+ if handler_call_details.method == _signal_client.UNARY_UNARY:
+ return self._unary_unary_handler
+ elif handler_call_details.method == _signal_client.UNARY_STREAM:
+ return self._unary_stream_handler
+ else:
+ return None
+
+
+def _read_stream(stream):
+ stream.seek(0)
+ return stream.read()
+
+
+def _start_client(args, stdout, stderr):
+ invocation = None
+ if sys.executable is not None:
+ invocation = (sys.executable, '-m', _CLIENT_PATH) + tuple(args)
+ else:
+ invocation = (_CLIENT_PATH,) + tuple(args)
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ return subprocess.Popen(invocation, stdout=stdout, stderr=stderr, env=env)
+
+
+class SignalHandlingTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = test_common.test_server()
+ self._port = self._server.add_insecure_port('{}:0'.format(_HOST))
+ self._handler = _GenericHandler()
+ self._server.add_generic_rpc_handlers((self._handler,))
+ self._server.start()
+
+ def tearDown(self):
+ self._server.stop(None)
+
+ @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
+ def testUnary(self):
+ """Tests that the server unary code path does not stall signal handlers."""
+ server_target = '{}:{}'.format(_HOST, self._port)
+ with tempfile.TemporaryFile(mode='r') as client_stdout:
+ with tempfile.TemporaryFile(mode='r') as client_stderr:
+ client = _start_client((server_target, 'unary'), client_stdout,
+ client_stderr)
+ self._handler.await_connected_client()
+ client.send_signal(signal.SIGINT)
+ self.assertFalse(client.wait(), msg=_read_stream(client_stderr))
+ client_stdout.seek(0)
+ self.assertIn(_signal_client.SIGTERM_MESSAGE,
+ client_stdout.read())
+
+ @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
+ def testStreaming(self):
+ """Tests that the server streaming code path does not stall signal handlers."""
+ server_target = '{}:{}'.format(_HOST, self._port)
+ with tempfile.TemporaryFile(mode='r') as client_stdout:
+ with tempfile.TemporaryFile(mode='r') as client_stderr:
+ client = _start_client((server_target, 'streaming'),
+ client_stdout, client_stderr)
+ self._handler.await_connected_client()
+ client.send_signal(signal.SIGINT)
+ self.assertFalse(client.wait(), msg=_read_stream(client_stderr))
+ client_stdout.seek(0)
+ self.assertIn(_signal_client.SIGTERM_MESSAGE,
+ client_stdout.read())
+
+ @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
+ def testUnaryWithException(self):
+ server_target = '{}:{}'.format(_HOST, self._port)
+ with tempfile.TemporaryFile(mode='r') as client_stdout:
+ with tempfile.TemporaryFile(mode='r') as client_stderr:
+ client = _start_client(('--exception', server_target, 'unary'),
+ client_stdout, client_stderr)
+ self._handler.await_connected_client()
+ client.send_signal(signal.SIGINT)
+ client.wait()
+ self.assertEqual(0, client.returncode)
+
+ @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
+ def testStreamingHandlerWithException(self):
+ server_target = '{}:{}'.format(_HOST, self._port)
+ with tempfile.TemporaryFile(mode='r') as client_stdout:
+ with tempfile.TemporaryFile(mode='r') as client_stderr:
+ client = _start_client(
+ ('--exception', server_target, 'streaming'), client_stdout,
+ client_stderr)
+ self._handler.await_connected_client()
+ client.send_signal(signal.SIGINT)
+ client.wait()
+ print(_read_stream(client_stderr))
+ self.assertEqual(0, client.returncode)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py
index 84dc0e2d6c..9a620f7508 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py
@@ -1,141 +1,141 @@
-# Copyright 2019 the gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-""" Proxies a TCP connection between a single client-server pair.
-
-This proxy is not suitable for production, but should work well for cases in
-which a test needs to spy on the bytes put on the wire between a server and
-a client.
-"""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import datetime
-import select
-import socket
-import threading
-
-from tests.unit.framework.common import get_socket
-
-_TCP_PROXY_BUFFER_SIZE = 1024
-_TCP_PROXY_TIMEOUT = datetime.timedelta(milliseconds=500)
-
-
-def _init_proxy_socket(gateway_address, gateway_port):
- proxy_socket = socket.create_connection((gateway_address, gateway_port))
- return proxy_socket
-
-
-class TcpProxy(object):
- """Proxies a TCP connection between one client and one server."""
-
- def __init__(self, bind_address, gateway_address, gateway_port):
- self._bind_address = bind_address
- self._gateway_address = gateway_address
- self._gateway_port = gateway_port
-
- self._byte_count_lock = threading.RLock()
- self._sent_byte_count = 0
- self._received_byte_count = 0
-
- self._stop_event = threading.Event()
-
- self._port = None
- self._listen_socket = None
- self._proxy_socket = None
-
- # The following three attributes are owned by the serving thread.
- self._northbound_data = b""
- self._southbound_data = b""
- self._client_sockets = []
-
- self._thread = threading.Thread(target=self._run_proxy)
-
- def start(self):
- _, self._port, self._listen_socket = get_socket(
- bind_address=self._bind_address)
- self._proxy_socket = _init_proxy_socket(self._gateway_address,
- self._gateway_port)
- self._thread.start()
-
- def get_port(self):
- return self._port
-
- def _handle_reads(self, sockets_to_read):
- for socket_to_read in sockets_to_read:
- if socket_to_read is self._listen_socket:
- client_socket, client_address = socket_to_read.accept()
- self._client_sockets.append(client_socket)
- elif socket_to_read is self._proxy_socket:
- data = socket_to_read.recv(_TCP_PROXY_BUFFER_SIZE)
- with self._byte_count_lock:
- self._received_byte_count += len(data)
- self._northbound_data += data
- elif socket_to_read in self._client_sockets:
- data = socket_to_read.recv(_TCP_PROXY_BUFFER_SIZE)
- if data:
- with self._byte_count_lock:
- self._sent_byte_count += len(data)
- self._southbound_data += data
- else:
- self._client_sockets.remove(socket_to_read)
- else:
- raise RuntimeError('Unidentified socket appeared in read set.')
-
- def _handle_writes(self, sockets_to_write):
- for socket_to_write in sockets_to_write:
- if socket_to_write is self._proxy_socket:
- if self._southbound_data:
- self._proxy_socket.sendall(self._southbound_data)
- self._southbound_data = b""
- elif socket_to_write in self._client_sockets:
- if self._northbound_data:
- socket_to_write.sendall(self._northbound_data)
- self._northbound_data = b""
-
- def _run_proxy(self):
- while not self._stop_event.is_set():
- expected_reads = (self._listen_socket, self._proxy_socket) + tuple(
- self._client_sockets)
- expected_writes = expected_reads
- sockets_to_read, sockets_to_write, _ = select.select(
- expected_reads, expected_writes, (),
- _TCP_PROXY_TIMEOUT.total_seconds())
- self._handle_reads(sockets_to_read)
- self._handle_writes(sockets_to_write)
- for client_socket in self._client_sockets:
- client_socket.close()
-
- def stop(self):
- self._stop_event.set()
- self._thread.join()
- self._listen_socket.close()
- self._proxy_socket.close()
-
- def get_byte_count(self):
- with self._byte_count_lock:
- return self._sent_byte_count, self._received_byte_count
-
- def reset_byte_count(self):
- with self._byte_count_lock:
- self._byte_count = 0
- self._received_byte_count = 0
-
- def __enter__(self):
- self.start()
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- self.stop()
+# Copyright 2019 the gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+""" Proxies a TCP connection between a single client-server pair.
+
+This proxy is not suitable for production, but should work well for cases in
+which a test needs to spy on the bytes put on the wire between a server and
+a client.
+"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import datetime
+import select
+import socket
+import threading
+
+from tests.unit.framework.common import get_socket
+
+_TCP_PROXY_BUFFER_SIZE = 1024
+_TCP_PROXY_TIMEOUT = datetime.timedelta(milliseconds=500)
+
+
+def _init_proxy_socket(gateway_address, gateway_port):
+ proxy_socket = socket.create_connection((gateway_address, gateway_port))
+ return proxy_socket
+
+
+class TcpProxy(object):
+ """Proxies a TCP connection between one client and one server."""
+
+ def __init__(self, bind_address, gateway_address, gateway_port):
+ self._bind_address = bind_address
+ self._gateway_address = gateway_address
+ self._gateway_port = gateway_port
+
+ self._byte_count_lock = threading.RLock()
+ self._sent_byte_count = 0
+ self._received_byte_count = 0
+
+ self._stop_event = threading.Event()
+
+ self._port = None
+ self._listen_socket = None
+ self._proxy_socket = None
+
+ # The following three attributes are owned by the serving thread.
+ self._northbound_data = b""
+ self._southbound_data = b""
+ self._client_sockets = []
+
+ self._thread = threading.Thread(target=self._run_proxy)
+
+ def start(self):
+ _, self._port, self._listen_socket = get_socket(
+ bind_address=self._bind_address)
+ self._proxy_socket = _init_proxy_socket(self._gateway_address,
+ self._gateway_port)
+ self._thread.start()
+
+ def get_port(self):
+ return self._port
+
+ def _handle_reads(self, sockets_to_read):
+ for socket_to_read in sockets_to_read:
+ if socket_to_read is self._listen_socket:
+ client_socket, client_address = socket_to_read.accept()
+ self._client_sockets.append(client_socket)
+ elif socket_to_read is self._proxy_socket:
+ data = socket_to_read.recv(_TCP_PROXY_BUFFER_SIZE)
+ with self._byte_count_lock:
+ self._received_byte_count += len(data)
+ self._northbound_data += data
+ elif socket_to_read in self._client_sockets:
+ data = socket_to_read.recv(_TCP_PROXY_BUFFER_SIZE)
+ if data:
+ with self._byte_count_lock:
+ self._sent_byte_count += len(data)
+ self._southbound_data += data
+ else:
+ self._client_sockets.remove(socket_to_read)
+ else:
+ raise RuntimeError('Unidentified socket appeared in read set.')
+
+ def _handle_writes(self, sockets_to_write):
+ for socket_to_write in sockets_to_write:
+ if socket_to_write is self._proxy_socket:
+ if self._southbound_data:
+ self._proxy_socket.sendall(self._southbound_data)
+ self._southbound_data = b""
+ elif socket_to_write in self._client_sockets:
+ if self._northbound_data:
+ socket_to_write.sendall(self._northbound_data)
+ self._northbound_data = b""
+
+ def _run_proxy(self):
+ while not self._stop_event.is_set():
+ expected_reads = (self._listen_socket, self._proxy_socket) + tuple(
+ self._client_sockets)
+ expected_writes = expected_reads
+ sockets_to_read, sockets_to_write, _ = select.select(
+ expected_reads, expected_writes, (),
+ _TCP_PROXY_TIMEOUT.total_seconds())
+ self._handle_reads(sockets_to_read)
+ self._handle_writes(sockets_to_write)
+ for client_socket in self._client_sockets:
+ client_socket.close()
+
+ def stop(self):
+ self._stop_event.set()
+ self._thread.join()
+ self._listen_socket.close()
+ self._proxy_socket.close()
+
+ def get_byte_count(self):
+ with self._byte_count_lock:
+ return self._sent_byte_count, self._received_byte_count
+
+ def reset_byte_count(self):
+ with self._byte_count_lock:
+ self._byte_count = 0
+ self._received_byte_count = 0
+
+ def __enter__(self):
+ self.start()
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.stop()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py
index 3d37b319e5..699004330c 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py
@@ -1,30 +1,30 @@
-# Copyright 2018 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.
-"""Test for grpc.__version__"""
-
-import unittest
-import grpc
-import logging
-from grpc import _grpcio_metadata
-
-
-class VersionTest(unittest.TestCase):
-
- def test_get_version(self):
- self.assertEqual(grpc.__version__, _grpcio_metadata.__version__)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
+# Copyright 2018 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.
+"""Test for grpc.__version__"""
+
+import unittest
+import grpc
+import logging
+from grpc import _grpcio_metadata
+
+
+class VersionTest(unittest.TestCase):
+
+ def test_get_version(self):
+ self.assertEqual(grpc.__version__, _grpcio_metadata.__version__)
+
+
+if __name__ == '__main__':
+ logging.basicConfig()
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py
index 5fb4f3c3cf..dc985eebb4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 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.
+# Copyright 2015 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py
index a111d68764..6981322561 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py
@@ -1,354 +1,354 @@
-# Copyright 2015 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.
-"""Tests Face interface compliance of the gRPC Python Beta API."""
-
-import threading
-import unittest
-
-from grpc.beta import implementations
-from grpc.beta import interfaces
-from grpc.framework.common import cardinality
-from grpc.framework.interfaces.face import utilities
-from tests.unit import resources
-from tests.unit.beta import test_utilities
-from tests.unit.framework.common import test_constants
-
-_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
-
-_PER_RPC_CREDENTIALS_METADATA_KEY = b'my-call-credentials-metadata-key'
-_PER_RPC_CREDENTIALS_METADATA_VALUE = b'my-call-credentials-metadata-value'
-
-_GROUP = 'group'
-_UNARY_UNARY = 'unary-unary'
-_UNARY_STREAM = 'unary-stream'
-_STREAM_UNARY = 'stream-unary'
-_STREAM_STREAM = 'stream-stream'
-
-_REQUEST = b'abc'
-_RESPONSE = b'123'
-
-
-class _Servicer(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._peer = None
- self._serviced = False
-
- def unary_unary(self, request, context):
- with self._condition:
- self._request = request
- self._peer = context.protocol_context().peer()
- self._invocation_metadata = context.invocation_metadata()
- context.protocol_context().disable_next_response_compression()
- self._serviced = True
- self._condition.notify_all()
- return _RESPONSE
-
- def unary_stream(self, request, context):
- with self._condition:
- self._request = request
- self._peer = context.protocol_context().peer()
- self._invocation_metadata = context.invocation_metadata()
- context.protocol_context().disable_next_response_compression()
- self._serviced = True
- self._condition.notify_all()
- return
- yield # pylint: disable=unreachable
-
- def stream_unary(self, request_iterator, context):
- for request in request_iterator:
- self._request = request
- with self._condition:
- self._peer = context.protocol_context().peer()
- self._invocation_metadata = context.invocation_metadata()
- context.protocol_context().disable_next_response_compression()
- self._serviced = True
- self._condition.notify_all()
- return _RESPONSE
-
- def stream_stream(self, request_iterator, context):
- for request in request_iterator:
- with self._condition:
- self._peer = context.protocol_context().peer()
- context.protocol_context().disable_next_response_compression()
- yield _RESPONSE
- with self._condition:
- self._invocation_metadata = context.invocation_metadata()
- self._serviced = True
- self._condition.notify_all()
-
- def peer(self):
- with self._condition:
- return self._peer
-
- def block_until_serviced(self):
- with self._condition:
- while not self._serviced:
- self._condition.wait()
-
-
-class _BlockingIterator(object):
-
- def __init__(self, upstream):
- self._condition = threading.Condition()
- self._upstream = upstream
- self._allowed = []
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self.next()
-
- def next(self):
- with self._condition:
- while True:
- if self._allowed is None:
- raise StopIteration()
- elif self._allowed:
- return self._allowed.pop(0)
- else:
- self._condition.wait()
-
- def allow(self):
- with self._condition:
- try:
- self._allowed.append(next(self._upstream))
- except StopIteration:
- self._allowed = None
- self._condition.notify_all()
-
-
-def _metadata_plugin(context, callback):
+# Copyright 2015 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.
+"""Tests Face interface compliance of the gRPC Python Beta API."""
+
+import threading
+import unittest
+
+from grpc.beta import implementations
+from grpc.beta import interfaces
+from grpc.framework.common import cardinality
+from grpc.framework.interfaces.face import utilities
+from tests.unit import resources
+from tests.unit.beta import test_utilities
+from tests.unit.framework.common import test_constants
+
+_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
+
+_PER_RPC_CREDENTIALS_METADATA_KEY = b'my-call-credentials-metadata-key'
+_PER_RPC_CREDENTIALS_METADATA_VALUE = b'my-call-credentials-metadata-value'
+
+_GROUP = 'group'
+_UNARY_UNARY = 'unary-unary'
+_UNARY_STREAM = 'unary-stream'
+_STREAM_UNARY = 'stream-unary'
+_STREAM_STREAM = 'stream-stream'
+
+_REQUEST = b'abc'
+_RESPONSE = b'123'
+
+
+class _Servicer(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._peer = None
+ self._serviced = False
+
+ def unary_unary(self, request, context):
+ with self._condition:
+ self._request = request
+ self._peer = context.protocol_context().peer()
+ self._invocation_metadata = context.invocation_metadata()
+ context.protocol_context().disable_next_response_compression()
+ self._serviced = True
+ self._condition.notify_all()
+ return _RESPONSE
+
+ def unary_stream(self, request, context):
+ with self._condition:
+ self._request = request
+ self._peer = context.protocol_context().peer()
+ self._invocation_metadata = context.invocation_metadata()
+ context.protocol_context().disable_next_response_compression()
+ self._serviced = True
+ self._condition.notify_all()
+ return
+ yield # pylint: disable=unreachable
+
+ def stream_unary(self, request_iterator, context):
+ for request in request_iterator:
+ self._request = request
+ with self._condition:
+ self._peer = context.protocol_context().peer()
+ self._invocation_metadata = context.invocation_metadata()
+ context.protocol_context().disable_next_response_compression()
+ self._serviced = True
+ self._condition.notify_all()
+ return _RESPONSE
+
+ def stream_stream(self, request_iterator, context):
+ for request in request_iterator:
+ with self._condition:
+ self._peer = context.protocol_context().peer()
+ context.protocol_context().disable_next_response_compression()
+ yield _RESPONSE
+ with self._condition:
+ self._invocation_metadata = context.invocation_metadata()
+ self._serviced = True
+ self._condition.notify_all()
+
+ def peer(self):
+ with self._condition:
+ return self._peer
+
+ def block_until_serviced(self):
+ with self._condition:
+ while not self._serviced:
+ self._condition.wait()
+
+
+class _BlockingIterator(object):
+
+ def __init__(self, upstream):
+ self._condition = threading.Condition()
+ self._upstream = upstream
+ self._allowed = []
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return self.next()
+
+ def next(self):
+ with self._condition:
+ while True:
+ if self._allowed is None:
+ raise StopIteration()
+ elif self._allowed:
+ return self._allowed.pop(0)
+ else:
+ self._condition.wait()
+
+ def allow(self):
+ with self._condition:
+ try:
+ self._allowed.append(next(self._upstream))
+ except StopIteration:
+ self._allowed = None
+ self._condition.notify_all()
+
+
+def _metadata_plugin(context, callback):
callback([
(_PER_RPC_CREDENTIALS_METADATA_KEY, _PER_RPC_CREDENTIALS_METADATA_VALUE)
], None)
-
-
-class BetaFeaturesTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _Servicer()
- method_implementations = {
- (_GROUP, _UNARY_UNARY):
+
+
+class BetaFeaturesTest(unittest.TestCase):
+
+ def setUp(self):
+ self._servicer = _Servicer()
+ method_implementations = {
+ (_GROUP, _UNARY_UNARY):
utilities.unary_unary_inline(self._servicer.unary_unary),
- (_GROUP, _UNARY_STREAM):
+ (_GROUP, _UNARY_STREAM):
utilities.unary_stream_inline(self._servicer.unary_stream),
- (_GROUP, _STREAM_UNARY):
+ (_GROUP, _STREAM_UNARY):
utilities.stream_unary_inline(self._servicer.stream_unary),
- (_GROUP, _STREAM_STREAM):
+ (_GROUP, _STREAM_STREAM):
utilities.stream_stream_inline(self._servicer.stream_stream),
- }
-
- cardinalities = {
- _UNARY_UNARY: cardinality.Cardinality.UNARY_UNARY,
- _UNARY_STREAM: cardinality.Cardinality.UNARY_STREAM,
- _STREAM_UNARY: cardinality.Cardinality.STREAM_UNARY,
- _STREAM_STREAM: cardinality.Cardinality.STREAM_STREAM,
- }
-
- server_options = implementations.server_options(
- thread_pool_size=test_constants.POOL_SIZE)
+ }
+
+ cardinalities = {
+ _UNARY_UNARY: cardinality.Cardinality.UNARY_UNARY,
+ _UNARY_STREAM: cardinality.Cardinality.UNARY_STREAM,
+ _STREAM_UNARY: cardinality.Cardinality.STREAM_UNARY,
+ _STREAM_STREAM: cardinality.Cardinality.STREAM_STREAM,
+ }
+
+ server_options = implementations.server_options(
+ thread_pool_size=test_constants.POOL_SIZE)
self._server = implementations.server(method_implementations,
options=server_options)
- server_credentials = implementations.ssl_server_credentials([
- (
- resources.private_key(),
- resources.certificate_chain(),
- ),
- ])
- port = self._server.add_secure_port('[::]:0', server_credentials)
- self._server.start()
- self._channel_credentials = implementations.ssl_channel_credentials(
- resources.test_root_certificates())
- self._call_credentials = implementations.metadata_call_credentials(
- _metadata_plugin)
- channel = test_utilities.not_really_secure_channel(
- 'localhost', port, self._channel_credentials, _SERVER_HOST_OVERRIDE)
- stub_options = implementations.stub_options(
- thread_pool_size=test_constants.POOL_SIZE)
+ server_credentials = implementations.ssl_server_credentials([
+ (
+ resources.private_key(),
+ resources.certificate_chain(),
+ ),
+ ])
+ port = self._server.add_secure_port('[::]:0', server_credentials)
+ self._server.start()
+ self._channel_credentials = implementations.ssl_channel_credentials(
+ resources.test_root_certificates())
+ self._call_credentials = implementations.metadata_call_credentials(
+ _metadata_plugin)
+ channel = test_utilities.not_really_secure_channel(
+ 'localhost', port, self._channel_credentials, _SERVER_HOST_OVERRIDE)
+ stub_options = implementations.stub_options(
+ thread_pool_size=test_constants.POOL_SIZE)
self._dynamic_stub = implementations.dynamic_stub(channel,
_GROUP,
cardinalities,
options=stub_options)
-
- def tearDown(self):
- self._dynamic_stub = None
- self._server.stop(test_constants.SHORT_TIMEOUT).wait()
-
- def test_unary_unary(self):
- call_options = interfaces.grpc_call_options(
- disable_compression=True, credentials=self._call_credentials)
+
+ def tearDown(self):
+ self._dynamic_stub = None
+ self._server.stop(test_constants.SHORT_TIMEOUT).wait()
+
+ def test_unary_unary(self):
+ call_options = interfaces.grpc_call_options(
+ disable_compression=True, credentials=self._call_credentials)
response = getattr(self._dynamic_stub,
_UNARY_UNARY)(_REQUEST,
test_constants.LONG_TIMEOUT,
protocol_options=call_options)
- self.assertEqual(_RESPONSE, response)
- self.assertIsNotNone(self._servicer.peer())
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
- def test_unary_stream(self):
- call_options = interfaces.grpc_call_options(
- disable_compression=True, credentials=self._call_credentials)
- response_iterator = getattr(self._dynamic_stub, _UNARY_STREAM)(
- _REQUEST,
- test_constants.LONG_TIMEOUT,
- protocol_options=call_options)
- self._servicer.block_until_serviced()
- self.assertIsNotNone(self._servicer.peer())
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
- def test_stream_unary(self):
- call_options = interfaces.grpc_call_options(
- credentials=self._call_credentials)
- request_iterator = _BlockingIterator(iter((_REQUEST,)))
- response_future = getattr(self._dynamic_stub, _STREAM_UNARY).future(
- request_iterator,
- test_constants.LONG_TIMEOUT,
- protocol_options=call_options)
- response_future.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- response_future.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- self._servicer.block_until_serviced()
- self.assertIsNotNone(self._servicer.peer())
- self.assertEqual(_RESPONSE, response_future.result())
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
- def test_stream_stream(self):
- call_options = interfaces.grpc_call_options(
- credentials=self._call_credentials)
- request_iterator = _BlockingIterator(iter((_REQUEST,)))
- response_iterator = getattr(self._dynamic_stub, _STREAM_STREAM)(
- request_iterator,
- test_constants.SHORT_TIMEOUT,
- protocol_options=call_options)
- response_iterator.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- response = next(response_iterator)
- response_iterator.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- self._servicer.block_until_serviced()
- self.assertIsNotNone(self._servicer.peer())
- self.assertEqual(_RESPONSE, response)
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
-
-class ContextManagementAndLifecycleTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _Servicer()
- self._method_implementations = {
- (_GROUP, _UNARY_UNARY):
+ self.assertEqual(_RESPONSE, response)
+ self.assertIsNotNone(self._servicer.peer())
+ invocation_metadata = [
+ (metadatum.key, metadatum.value)
+ for metadatum in self._servicer._invocation_metadata
+ ]
+ self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
+ _PER_RPC_CREDENTIALS_METADATA_VALUE),
+ invocation_metadata)
+
+ def test_unary_stream(self):
+ call_options = interfaces.grpc_call_options(
+ disable_compression=True, credentials=self._call_credentials)
+ response_iterator = getattr(self._dynamic_stub, _UNARY_STREAM)(
+ _REQUEST,
+ test_constants.LONG_TIMEOUT,
+ protocol_options=call_options)
+ self._servicer.block_until_serviced()
+ self.assertIsNotNone(self._servicer.peer())
+ invocation_metadata = [
+ (metadatum.key, metadatum.value)
+ for metadatum in self._servicer._invocation_metadata
+ ]
+ self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
+ _PER_RPC_CREDENTIALS_METADATA_VALUE),
+ invocation_metadata)
+
+ def test_stream_unary(self):
+ call_options = interfaces.grpc_call_options(
+ credentials=self._call_credentials)
+ request_iterator = _BlockingIterator(iter((_REQUEST,)))
+ response_future = getattr(self._dynamic_stub, _STREAM_UNARY).future(
+ request_iterator,
+ test_constants.LONG_TIMEOUT,
+ protocol_options=call_options)
+ response_future.protocol_context().disable_next_request_compression()
+ request_iterator.allow()
+ response_future.protocol_context().disable_next_request_compression()
+ request_iterator.allow()
+ self._servicer.block_until_serviced()
+ self.assertIsNotNone(self._servicer.peer())
+ self.assertEqual(_RESPONSE, response_future.result())
+ invocation_metadata = [
+ (metadatum.key, metadatum.value)
+ for metadatum in self._servicer._invocation_metadata
+ ]
+ self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
+ _PER_RPC_CREDENTIALS_METADATA_VALUE),
+ invocation_metadata)
+
+ def test_stream_stream(self):
+ call_options = interfaces.grpc_call_options(
+ credentials=self._call_credentials)
+ request_iterator = _BlockingIterator(iter((_REQUEST,)))
+ response_iterator = getattr(self._dynamic_stub, _STREAM_STREAM)(
+ request_iterator,
+ test_constants.SHORT_TIMEOUT,
+ protocol_options=call_options)
+ response_iterator.protocol_context().disable_next_request_compression()
+ request_iterator.allow()
+ response = next(response_iterator)
+ response_iterator.protocol_context().disable_next_request_compression()
+ request_iterator.allow()
+ self._servicer.block_until_serviced()
+ self.assertIsNotNone(self._servicer.peer())
+ self.assertEqual(_RESPONSE, response)
+ invocation_metadata = [
+ (metadatum.key, metadatum.value)
+ for metadatum in self._servicer._invocation_metadata
+ ]
+ self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
+ _PER_RPC_CREDENTIALS_METADATA_VALUE),
+ invocation_metadata)
+
+
+class ContextManagementAndLifecycleTest(unittest.TestCase):
+
+ def setUp(self):
+ self._servicer = _Servicer()
+ self._method_implementations = {
+ (_GROUP, _UNARY_UNARY):
utilities.unary_unary_inline(self._servicer.unary_unary),
- (_GROUP, _UNARY_STREAM):
+ (_GROUP, _UNARY_STREAM):
utilities.unary_stream_inline(self._servicer.unary_stream),
- (_GROUP, _STREAM_UNARY):
+ (_GROUP, _STREAM_UNARY):
utilities.stream_unary_inline(self._servicer.stream_unary),
- (_GROUP, _STREAM_STREAM):
+ (_GROUP, _STREAM_STREAM):
utilities.stream_stream_inline(self._servicer.stream_stream),
- }
-
- self._cardinalities = {
- _UNARY_UNARY: cardinality.Cardinality.UNARY_UNARY,
- _UNARY_STREAM: cardinality.Cardinality.UNARY_STREAM,
- _STREAM_UNARY: cardinality.Cardinality.STREAM_UNARY,
- _STREAM_STREAM: cardinality.Cardinality.STREAM_STREAM,
- }
-
- self._server_options = implementations.server_options(
- thread_pool_size=test_constants.POOL_SIZE)
- self._server_credentials = implementations.ssl_server_credentials([
- (
- resources.private_key(),
- resources.certificate_chain(),
- ),
- ])
- self._channel_credentials = implementations.ssl_channel_credentials(
- resources.test_root_certificates())
- self._stub_options = implementations.stub_options(
- thread_pool_size=test_constants.POOL_SIZE)
-
- def test_stub_context(self):
+ }
+
+ self._cardinalities = {
+ _UNARY_UNARY: cardinality.Cardinality.UNARY_UNARY,
+ _UNARY_STREAM: cardinality.Cardinality.UNARY_STREAM,
+ _STREAM_UNARY: cardinality.Cardinality.STREAM_UNARY,
+ _STREAM_STREAM: cardinality.Cardinality.STREAM_STREAM,
+ }
+
+ self._server_options = implementations.server_options(
+ thread_pool_size=test_constants.POOL_SIZE)
+ self._server_credentials = implementations.ssl_server_credentials([
+ (
+ resources.private_key(),
+ resources.certificate_chain(),
+ ),
+ ])
+ self._channel_credentials = implementations.ssl_channel_credentials(
+ resources.test_root_certificates())
+ self._stub_options = implementations.stub_options(
+ thread_pool_size=test_constants.POOL_SIZE)
+
+ def test_stub_context(self):
server = implementations.server(self._method_implementations,
options=self._server_options)
- port = server.add_secure_port('[::]:0', self._server_credentials)
- server.start()
-
- channel = test_utilities.not_really_secure_channel(
- 'localhost', port, self._channel_credentials, _SERVER_HOST_OVERRIDE)
+ port = server.add_secure_port('[::]:0', self._server_credentials)
+ server.start()
+
+ channel = test_utilities.not_really_secure_channel(
+ 'localhost', port, self._channel_credentials, _SERVER_HOST_OVERRIDE)
dynamic_stub = implementations.dynamic_stub(channel,
_GROUP,
self._cardinalities,
options=self._stub_options)
- for _ in range(100):
- with dynamic_stub:
- pass
- for _ in range(10):
- with dynamic_stub:
- call_options = interfaces.grpc_call_options(
- disable_compression=True)
+ for _ in range(100):
+ with dynamic_stub:
+ pass
+ for _ in range(10):
+ with dynamic_stub:
+ call_options = interfaces.grpc_call_options(
+ disable_compression=True)
response = getattr(dynamic_stub,
_UNARY_UNARY)(_REQUEST,
test_constants.LONG_TIMEOUT,
protocol_options=call_options)
- self.assertEqual(_RESPONSE, response)
- self.assertIsNotNone(self._servicer.peer())
-
- server.stop(test_constants.SHORT_TIMEOUT).wait()
-
- def test_server_lifecycle(self):
- for _ in range(100):
+ self.assertEqual(_RESPONSE, response)
+ self.assertIsNotNone(self._servicer.peer())
+
+ server.stop(test_constants.SHORT_TIMEOUT).wait()
+
+ def test_server_lifecycle(self):
+ for _ in range(100):
server = implementations.server(self._method_implementations,
options=self._server_options)
- port = server.add_secure_port('[::]:0', self._server_credentials)
- server.start()
- server.stop(test_constants.SHORT_TIMEOUT).wait()
- for _ in range(100):
+ port = server.add_secure_port('[::]:0', self._server_credentials)
+ server.start()
+ server.stop(test_constants.SHORT_TIMEOUT).wait()
+ for _ in range(100):
server = implementations.server(self._method_implementations,
options=self._server_options)
- server.add_secure_port('[::]:0', self._server_credentials)
- server.add_insecure_port('[::]:0')
- with server:
- server.stop(test_constants.SHORT_TIMEOUT)
- server.stop(test_constants.SHORT_TIMEOUT)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ server.add_secure_port('[::]:0', self._server_credentials)
+ server.add_insecure_port('[::]:0')
+ with server:
+ server.stop(test_constants.SHORT_TIMEOUT)
+ server.stop(test_constants.SHORT_TIMEOUT)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py
index 1416902eab..4eb570f21b 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py
@@ -1,32 +1,32 @@
-# Copyright 2015 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.
-"""Tests of grpc.beta._connectivity_channel."""
-
-import unittest
-
-from grpc.beta import interfaces
-
-
-class ConnectivityStatesTest(unittest.TestCase):
-
- def testBetaConnectivityStates(self):
- self.assertIsNotNone(interfaces.ChannelConnectivity.IDLE)
- self.assertIsNotNone(interfaces.ChannelConnectivity.CONNECTING)
- self.assertIsNotNone(interfaces.ChannelConnectivity.READY)
- self.assertIsNotNone(interfaces.ChannelConnectivity.TRANSIENT_FAILURE)
- self.assertIsNotNone(interfaces.ChannelConnectivity.FATAL_FAILURE)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2015 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.
+"""Tests of grpc.beta._connectivity_channel."""
+
+import unittest
+
+from grpc.beta import interfaces
+
+
+class ConnectivityStatesTest(unittest.TestCase):
+
+ def testBetaConnectivityStates(self):
+ self.assertIsNotNone(interfaces.ChannelConnectivity.IDLE)
+ self.assertIsNotNone(interfaces.ChannelConnectivity.CONNECTING)
+ self.assertIsNotNone(interfaces.ChannelConnectivity.READY)
+ self.assertIsNotNone(interfaces.ChannelConnectivity.TRANSIENT_FAILURE)
+ self.assertIsNotNone(interfaces.ChannelConnectivity.FATAL_FAILURE)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_implementations_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_implementations_test.py
index 75a615eeff..ae60a0e4cd 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_implementations_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_implementations_test.py
@@ -1,55 +1,55 @@
-# Copyright 2016 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.
-"""Tests the implementations module of the gRPC Python Beta API."""
-
-import datetime
-import unittest
-
-from oauth2client import client as oauth2client_client
-
-from grpc.beta import implementations
-from tests.unit import resources
-
-
-class ChannelCredentialsTest(unittest.TestCase):
-
- def test_runtime_provided_root_certificates(self):
- channel_credentials = implementations.ssl_channel_credentials()
- self.assertIsInstance(channel_credentials,
- implementations.ChannelCredentials)
-
- def test_application_provided_root_certificates(self):
- channel_credentials = implementations.ssl_channel_credentials(
- resources.test_root_certificates())
- self.assertIsInstance(channel_credentials,
- implementations.ChannelCredentials)
-
-
-class CallCredentialsTest(unittest.TestCase):
-
- def test_google_call_credentials(self):
- creds = oauth2client_client.GoogleCredentials(
- 'token', 'client_id', 'secret', 'refresh_token',
+# Copyright 2016 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.
+"""Tests the implementations module of the gRPC Python Beta API."""
+
+import datetime
+import unittest
+
+from oauth2client import client as oauth2client_client
+
+from grpc.beta import implementations
+from tests.unit import resources
+
+
+class ChannelCredentialsTest(unittest.TestCase):
+
+ def test_runtime_provided_root_certificates(self):
+ channel_credentials = implementations.ssl_channel_credentials()
+ self.assertIsInstance(channel_credentials,
+ implementations.ChannelCredentials)
+
+ def test_application_provided_root_certificates(self):
+ channel_credentials = implementations.ssl_channel_credentials(
+ resources.test_root_certificates())
+ self.assertIsInstance(channel_credentials,
+ implementations.ChannelCredentials)
+
+
+class CallCredentialsTest(unittest.TestCase):
+
+ def test_google_call_credentials(self):
+ creds = oauth2client_client.GoogleCredentials(
+ 'token', 'client_id', 'secret', 'refresh_token',
datetime.datetime(2008, 6, 24), 'https://refresh.uri.com/',
'user_agent')
- call_creds = implementations.google_call_credentials(creds)
- self.assertIsInstance(call_creds, implementations.CallCredentials)
-
- def test_access_token_call_credentials(self):
- call_creds = implementations.access_token_call_credentials('token')
- self.assertIsInstance(call_creds, implementations.CallCredentials)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ call_creds = implementations.google_call_credentials(creds)
+ self.assertIsInstance(call_creds, implementations.CallCredentials)
+
+ def test_access_token_call_credentials(self):
+ call_creds = implementations.access_token_call_credentials('token')
+ self.assertIsInstance(call_creds, implementations.CallCredentials)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py
index 837d2bbebf..dbede08a38 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py
@@ -1,59 +1,59 @@
-# Copyright 2015 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.
-"""Tests of RPC-method-not-found behavior."""
-
-import unittest
-
-from grpc.beta import implementations
-from grpc.beta import interfaces
-from grpc.framework.interfaces.face import face
-from tests.unit.framework.common import test_constants
-
-
-class NotFoundTest(unittest.TestCase):
-
- def setUp(self):
- self._server = implementations.server({})
- port = self._server.add_insecure_port('[::]:0')
- channel = implementations.insecure_channel('localhost', port)
- self._generic_stub = implementations.generic_stub(channel)
- self._server.start()
-
- def tearDown(self):
- self._server.stop(0).wait()
- self._generic_stub = None
-
- def test_blocking_unary_unary_not_found(self):
- with self.assertRaises(face.LocalError) as exception_assertion_context:
+# Copyright 2015 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.
+"""Tests of RPC-method-not-found behavior."""
+
+import unittest
+
+from grpc.beta import implementations
+from grpc.beta import interfaces
+from grpc.framework.interfaces.face import face
+from tests.unit.framework.common import test_constants
+
+
+class NotFoundTest(unittest.TestCase):
+
+ def setUp(self):
+ self._server = implementations.server({})
+ port = self._server.add_insecure_port('[::]:0')
+ channel = implementations.insecure_channel('localhost', port)
+ self._generic_stub = implementations.generic_stub(channel)
+ self._server.start()
+
+ def tearDown(self):
+ self._server.stop(0).wait()
+ self._generic_stub = None
+
+ def test_blocking_unary_unary_not_found(self):
+ with self.assertRaises(face.LocalError) as exception_assertion_context:
self._generic_stub.blocking_unary_unary('groop',
'meffod',
b'abc',
test_constants.LONG_TIMEOUT,
with_call=True)
- self.assertIs(exception_assertion_context.exception.code,
- interfaces.StatusCode.UNIMPLEMENTED)
-
- def test_future_stream_unary_not_found(self):
- rpc_future = self._generic_stub.future_stream_unary(
- 'grupe', 'mevvod', iter([b'def']), test_constants.LONG_TIMEOUT)
- with self.assertRaises(face.LocalError) as exception_assertion_context:
- rpc_future.result()
- self.assertIs(exception_assertion_context.exception.code,
- interfaces.StatusCode.UNIMPLEMENTED)
- self.assertIs(rpc_future.exception().code,
- interfaces.StatusCode.UNIMPLEMENTED)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+ self.assertIs(exception_assertion_context.exception.code,
+ interfaces.StatusCode.UNIMPLEMENTED)
+
+ def test_future_stream_unary_not_found(self):
+ rpc_future = self._generic_stub.future_stream_unary(
+ 'grupe', 'mevvod', iter([b'def']), test_constants.LONG_TIMEOUT)
+ with self.assertRaises(face.LocalError) as exception_assertion_context:
+ rpc_future.result()
+ self.assertIs(exception_assertion_context.exception.code,
+ interfaces.StatusCode.UNIMPLEMENTED)
+ self.assertIs(rpc_future.exception().code,
+ interfaces.StatusCode.UNIMPLEMENTED)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py
index e042262796..2a59e7b2c8 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py
@@ -1,93 +1,93 @@
-# Copyright 2015 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.
-"""Tests of grpc.beta.utilities."""
-
-import threading
-import time
-import unittest
-
-from grpc.beta import implementations
-from grpc.beta import utilities
-from grpc.framework.foundation import future
-from tests.unit.framework.common import test_constants
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
-
- def accept_value(self, value):
- with self._condition:
- self._value = value
- self._condition.notify_all()
-
- def block_until_called(self):
- with self._condition:
- while self._value is None:
- self._condition.wait()
- return self._value
-
-
-@unittest.skip('https://github.com/grpc/grpc/issues/16134')
-class ChannelConnectivityTest(unittest.TestCase):
-
- def test_lonely_channel_connectivity(self):
- channel = implementations.insecure_channel('localhost', 12345)
- callback = _Callback()
-
- ready_future = utilities.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- with self.assertRaises(future.TimeoutError):
- ready_future.result(timeout=test_constants.SHORT_TIMEOUT)
- self.assertFalse(ready_future.cancelled())
- self.assertFalse(ready_future.done())
- self.assertTrue(ready_future.running())
- ready_future.cancel()
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertTrue(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
-
- def test_immediately_connectable_channel_connectivity(self):
- server = implementations.server({})
- port = server.add_insecure_port('[::]:0')
- server.start()
- channel = implementations.insecure_channel('localhost', port)
- callback = _Callback()
-
- try:
- ready_future = utilities.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- self.assertIsNone(
- ready_future.result(timeout=test_constants.LONG_TIMEOUT))
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- # Cancellation after maturity has no effect.
- ready_future.cancel()
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- finally:
- ready_future.cancel()
- server.stop(0)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2015 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.
+"""Tests of grpc.beta.utilities."""
+
+import threading
+import time
+import unittest
+
+from grpc.beta import implementations
+from grpc.beta import utilities
+from grpc.framework.foundation import future
+from tests.unit.framework.common import test_constants
+
+
+class _Callback(object):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._value = None
+
+ def accept_value(self, value):
+ with self._condition:
+ self._value = value
+ self._condition.notify_all()
+
+ def block_until_called(self):
+ with self._condition:
+ while self._value is None:
+ self._condition.wait()
+ return self._value
+
+
+@unittest.skip('https://github.com/grpc/grpc/issues/16134')
+class ChannelConnectivityTest(unittest.TestCase):
+
+ def test_lonely_channel_connectivity(self):
+ channel = implementations.insecure_channel('localhost', 12345)
+ callback = _Callback()
+
+ ready_future = utilities.channel_ready_future(channel)
+ ready_future.add_done_callback(callback.accept_value)
+ with self.assertRaises(future.TimeoutError):
+ ready_future.result(timeout=test_constants.SHORT_TIMEOUT)
+ self.assertFalse(ready_future.cancelled())
+ self.assertFalse(ready_future.done())
+ self.assertTrue(ready_future.running())
+ ready_future.cancel()
+ value_passed_to_callback = callback.block_until_called()
+ self.assertIs(ready_future, value_passed_to_callback)
+ self.assertTrue(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+
+ def test_immediately_connectable_channel_connectivity(self):
+ server = implementations.server({})
+ port = server.add_insecure_port('[::]:0')
+ server.start()
+ channel = implementations.insecure_channel('localhost', port)
+ callback = _Callback()
+
+ try:
+ ready_future = utilities.channel_ready_future(channel)
+ ready_future.add_done_callback(callback.accept_value)
+ self.assertIsNone(
+ ready_future.result(timeout=test_constants.LONG_TIMEOUT))
+ value_passed_to_callback = callback.block_until_called()
+ self.assertIs(ready_future, value_passed_to_callback)
+ self.assertFalse(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+ # Cancellation after maturity has no effect.
+ ready_future.cancel()
+ self.assertFalse(ready_future.cancelled())
+ self.assertTrue(ready_future.done())
+ self.assertFalse(ready_future.running())
+ finally:
+ ready_future.cancel()
+ server.stop(0)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py
index c8d920d35e..4a32205b89 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py
@@ -1,40 +1,40 @@
-# Copyright 2015 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.
-"""Test-appropriate entry points into the gRPC Python Beta API."""
-
-import grpc
-from grpc.beta import implementations
-
-
-def not_really_secure_channel(host, port, channel_credentials,
- server_host_override):
- """Creates an insecure Channel to a remote host.
-
- Args:
- host: The name of the remote host to which to connect.
- port: The port of the remote host to which to connect.
- channel_credentials: The implementations.ChannelCredentials with which to
- connect.
- server_host_override: The target name used for SSL host name checking.
-
- Returns:
- An implementations.Channel to the remote host through which RPCs may be
- conducted.
- """
- target = '%s:%d' % (host, port)
- channel = grpc.secure_channel(target, channel_credentials, ((
- 'grpc.ssl_target_name_override',
- server_host_override,
- ),))
- return implementations.Channel(channel)
+# Copyright 2015 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.
+"""Test-appropriate entry points into the gRPC Python Beta API."""
+
+import grpc
+from grpc.beta import implementations
+
+
+def not_really_secure_channel(host, port, channel_credentials,
+ server_host_override):
+ """Creates an insecure Channel to a remote host.
+
+ Args:
+ host: The name of the remote host to which to connect.
+ port: The port of the remote host to which to connect.
+ channel_credentials: The implementations.ChannelCredentials with which to
+ connect.
+ server_host_override: The target name used for SSL host name checking.
+
+ Returns:
+ An implementations.Channel to the remote host through which RPCs may be
+ conducted.
+ """
+ target = '%s:%d' % (host, port)
+ channel = grpc.secure_channel(target, channel_credentials, ((
+ 'grpc.ssl_target_name_override',
+ server_host_override,
+ ),))
+ return implementations.Channel(channel)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md
index 100b43c1aa..d25440d660 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md
@@ -1,15 +1,15 @@
-These are test keys *NOT* to be used in production.
-
-The `certificate_hierarchy_1` and `certificate_hierarchy_2` contain
-two disjoint but similarly organized certificate hierarchies. Each
-contains:
-
-* The respective root CA cert in `certs/ca.cert.pem`
-
-* The intermediate CA cert in
- `intermediate/certs/intermediate.cert.pem`, signed by the root CA
-
-* A client cert and a server cert--both signed by the intermediate
- CA--in `intermediate/certs/client.cert.pem` and
- `intermediate/certs/localhost-1.cert.pem`; the corresponding keys
- are in `intermediate/private`
+These are test keys *NOT* to be used in production.
+
+The `certificate_hierarchy_1` and `certificate_hierarchy_2` contain
+two disjoint but similarly organized certificate hierarchies. Each
+contains:
+
+* The respective root CA cert in `certs/ca.cert.pem`
+
+* The intermediate CA cert in
+ `intermediate/certs/intermediate.cert.pem`, signed by the root CA
+
+* A client cert and a server cert--both signed by the intermediate
+ CA--in `intermediate/certs/client.cert.pem` and
+ `intermediate/certs/localhost-1.cert.pem`; the corresponding keys
+ are in `intermediate/private`
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem
index 49d39cd8ed..5f62638013 100755
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem
@@ -1,4 +1,4 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIIDWjCCAkKgAwIBAgIUWrP0VvHcy+LP6UuYNtiL9gBhD5owDQYJKoZIhvcNAQEL
BQAwVjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEPMA0GA1UEAwwGdGVzdGNhMB4XDTIw
@@ -17,4 +17,4 @@ CVTtdJB4CYWpcNyXOdqefrbJW5QNljxgi6Fhvs7JJkBqdXIkWXtFk2eRgOIP2Eo9
/OHQHlYnwZFrk6sp4wPyR+A95S0toZBcyDVz7u+hOW0pGK3wviOe9lvRgj/H3Pwt
bewb0l+MhRig0/DVHamyVxrDRbqInU1/GTNCwcZkXKYFWSf92U+kIcTth24Q1gcw
eZiLl5FfrWokUNytFElXob0V0a5/kbhiLc3yWmvWqHTpqCALbVyF+rKJo2f5Kw==
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key
index 086462992c..25cdade2fb 100755
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key
@@ -1,4 +1,4 @@
------BEGIN PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDnE443EknxvxBq
6+hvn/t09hl8hx366EBYvZmVM/NC+7igXRAjiJiA/mIaCvL3MS0Iz5hBLxSGICU+
WproA3GCIFITIwcf/ETyWj/5xpgZ4AKrLrjQmmX8mhwUajfF3UvwMJrCOVqPp67t
@@ -25,4 +25,4 @@ FRuGldlSOW1z/nSh8ViizSYE5H5HX1qkXEippvFRE88CgYB3Bfu3YQY60ITWIShv
nNkdcbTT9eoP9suaRJjw92Ln+7ZpALYlQMKUZmJ/5uBmLs4RFwUTQruLOPL4yLTH
awADWUzs3IRr1fwn9E+zM8JVyKCnUEM3w4N5UZskGO2klashAd30hWO+knRv/y0r
uGIYs9Ek7YXlXIRVrzMwcsrt1w==
------END PRIVATE KEY-----
+-----END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem
index 88244f856c..d37efbaafa 100755
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem
@@ -1,4 +1,4 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIIDtDCCApygAwIBAgIUbJfTREJ6k6/+oInWhV1O1j3ZT0IwDQYJKoZIhvcNAQEL
BQAwVjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEPMA0GA1UEAwwGdGVzdGNhMB4XDTIw
@@ -19,4 +19,4 @@ Jl4RK0tSkGQ3YNY4NzXwQP/vmUgfkw8VBAZ4Y4GKxppdATjffIW+srbAmdDruIRM
wPeikgOoRrXf0LA1fi4TqxARzeRwenQpayNfGHTvVF9aJkl8HoaMunTAdG5pIVcr
9GKi/gEMpXUJbbVv3U5frX1Wo4CFo+rZWJ/LyCMeb0jciNLxSdMwj/E/ZuExlyeZ
gc9ctPjSMvgSyXEKv6Vwobleeg88V2ZgzenziORoWj4KszG/lbQZvg==
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py
index 5fb4f3c3cf..dc985eebb4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 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.
+# Copyright 2015 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py
index 8b58a0c46a..3006b859c4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py
@@ -1,64 +1,64 @@
-# Copyright 2019 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import contextlib
-import os
-import socket
+# Copyright 2019 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import contextlib
+import os
+import socket
import errno
-
+
_DEFAULT_SOCK_OPTIONS = (socket.SO_REUSEADDR,
socket.SO_REUSEPORT) if os.name != 'nt' else (
socket.SO_REUSEADDR,)
_UNRECOVERABLE_ERRNOS = (errno.EADDRINUSE, errno.ENOSR)
-
-
-def get_socket(bind_address='localhost',
+
+
+def get_socket(bind_address='localhost',
port=0,
- listen=True,
+ listen=True,
sock_options=_DEFAULT_SOCK_OPTIONS):
"""Opens a socket.
-
- Useful for reserving a port for a system-under-test.
-
- Args:
- bind_address: The host to which to bind.
+
+ Useful for reserving a port for a system-under-test.
+
+ Args:
+ bind_address: The host to which to bind.
port: The port to which to bind.
- listen: A boolean value indicating whether or not to listen on the socket.
- sock_options: A sequence of socket options to apply to the socket.
-
- Returns:
- A tuple containing:
- - the address to which the socket is bound
- - the port to which the socket is bound
- - the socket object itself
- """
- _sock_options = sock_options if sock_options else []
- if socket.has_ipv6:
- address_families = (socket.AF_INET6, socket.AF_INET)
- else:
- address_families = (socket.AF_INET)
- for address_family in address_families:
- try:
- sock = socket.socket(address_family, socket.SOCK_STREAM)
- for sock_option in _sock_options:
- sock.setsockopt(socket.SOL_SOCKET, sock_option, 1)
+ listen: A boolean value indicating whether or not to listen on the socket.
+ sock_options: A sequence of socket options to apply to the socket.
+
+ Returns:
+ A tuple containing:
+ - the address to which the socket is bound
+ - the port to which the socket is bound
+ - the socket object itself
+ """
+ _sock_options = sock_options if sock_options else []
+ if socket.has_ipv6:
+ address_families = (socket.AF_INET6, socket.AF_INET)
+ else:
+ address_families = (socket.AF_INET)
+ for address_family in address_families:
+ try:
+ sock = socket.socket(address_family, socket.SOCK_STREAM)
+ for sock_option in _sock_options:
+ sock.setsockopt(socket.SOL_SOCKET, sock_option, 1)
sock.bind((bind_address, port))
- if listen:
- sock.listen(1)
- return bind_address, sock.getsockname()[1], sock
+ if listen:
+ sock.listen(1)
+ return bind_address, sock.getsockname()[1], sock
except OSError as os_error:
- sock.close()
+ sock.close()
if os_error.errno in _UNRECOVERABLE_ERRNOS:
raise
else:
@@ -67,36 +67,36 @@ def get_socket(bind_address='localhost',
# pointing to OSError. We need this catch to make it 2/3 agnostic.
except socket.error: # pylint: disable=duplicate-except
sock.close()
- continue
- raise RuntimeError("Failed to bind to {} with sock_options {}".format(
- bind_address, sock_options))
-
-
-@contextlib.contextmanager
-def bound_socket(bind_address='localhost',
+ continue
+ raise RuntimeError("Failed to bind to {} with sock_options {}".format(
+ bind_address, sock_options))
+
+
+@contextlib.contextmanager
+def bound_socket(bind_address='localhost',
port=0,
- listen=True,
+ listen=True,
sock_options=_DEFAULT_SOCK_OPTIONS):
- """Opens a socket bound to an arbitrary port.
-
- Useful for reserving a port for a system-under-test.
-
- Args:
- bind_address: The host to which to bind.
+ """Opens a socket bound to an arbitrary port.
+
+ Useful for reserving a port for a system-under-test.
+
+ Args:
+ bind_address: The host to which to bind.
port: The port to which to bind.
- listen: A boolean value indicating whether or not to listen on the socket.
- sock_options: A sequence of socket options to apply to the socket.
-
- Yields:
- A tuple containing:
- - the address to which the socket is bound
- - the port to which the socket is bound
- """
+ listen: A boolean value indicating whether or not to listen on the socket.
+ sock_options: A sequence of socket options to apply to the socket.
+
+ Yields:
+ A tuple containing:
+ - the address to which the socket is bound
+ - the port to which the socket is bound
+ """
host, port, sock = get_socket(bind_address=bind_address,
port=port,
listen=listen,
sock_options=sock_options)
- try:
- yield host, port
- finally:
- sock.close()
+ try:
+ yield host, port
+ finally:
+ sock.close()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py
index 2b9eb2e35b..7e5a9d2c0f 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py
@@ -1,45 +1,45 @@
-# Copyright 2015 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.
-"""Constants shared among tests throughout RPC Framework."""
-
-# Value for maximum duration in seconds that a test is allowed for its actual
-# behavioral logic, excluding all time spent deliberately waiting in the test.
-TIME_ALLOWANCE = 10
-# Value for maximum duration in seconds of RPCs that may time out as part of a
-# test.
-SHORT_TIMEOUT = 4
-# Absurdly large value for maximum duration in seconds for should-not-time-out
-# RPCs made during tests.
-LONG_TIMEOUT = 3000
-# Values to supply on construction of an object that will service RPCs; these
-# should not be used as the actual timeout values of any RPCs made during tests.
-DEFAULT_TIMEOUT = 300
-MAXIMUM_TIMEOUT = 3600
-
-# The number of payloads to transmit in streaming tests.
-STREAM_LENGTH = 200
-
-# The size of payloads to transmit in tests.
-PAYLOAD_SIZE = 256 * 1024 + 17
-
-# The concurrency to use in tests of concurrent RPCs that will not create as
-# many threads as RPCs.
-RPC_CONCURRENCY = 200
-
-# The concurrency to use in tests of concurrent RPCs that will create as many
-# threads as RPCs.
-THREAD_CONCURRENCY = 25
-
-# The size of thread pools to use in tests.
-POOL_SIZE = 10
+# Copyright 2015 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.
+"""Constants shared among tests throughout RPC Framework."""
+
+# Value for maximum duration in seconds that a test is allowed for its actual
+# behavioral logic, excluding all time spent deliberately waiting in the test.
+TIME_ALLOWANCE = 10
+# Value for maximum duration in seconds of RPCs that may time out as part of a
+# test.
+SHORT_TIMEOUT = 4
+# Absurdly large value for maximum duration in seconds for should-not-time-out
+# RPCs made during tests.
+LONG_TIMEOUT = 3000
+# Values to supply on construction of an object that will service RPCs; these
+# should not be used as the actual timeout values of any RPCs made during tests.
+DEFAULT_TIMEOUT = 300
+MAXIMUM_TIMEOUT = 3600
+
+# The number of payloads to transmit in streaming tests.
+STREAM_LENGTH = 200
+
+# The size of payloads to transmit in tests.
+PAYLOAD_SIZE = 256 * 1024 + 17
+
+# The concurrency to use in tests of concurrent RPCs that will not create as
+# many threads as RPCs.
+RPC_CONCURRENCY = 200
+
+# The concurrency to use in tests of concurrent RPCs that will create as many
+# threads as RPCs.
+THREAD_CONCURRENCY = 25
+
+# The size of thread pools to use in tests.
+POOL_SIZE = 10
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py
index 6a422825cc..ea88372dc0 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py
@@ -1,97 +1,97 @@
-# Copyright 2015 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.
-"""Code for instructing systems under test to block or fail."""
-
-import abc
-import contextlib
-import threading
-
-import six
-
-
-class Defect(Exception):
- """Simulates a programming defect raised into in a system under test.
-
- Use of a standard exception type is too easily misconstrued as an actual
- defect in either the test infrastructure or the system under test.
- """
-
-
-class Control(six.with_metaclass(abc.ABCMeta)):
- """An object that accepts program control from a system under test.
-
- Systems under test passed a Control should call its control() method
- frequently during execution. The control() method may block, raise an
- exception, or do nothing, all according to the enclosing test's desire for
- the system under test to simulate hanging, failing, or functioning.
- """
-
- @abc.abstractmethod
- def control(self):
- """Potentially does anything."""
- raise NotImplementedError()
-
-
-class PauseFailControl(Control):
- """A Control that can be used to pause or fail code under control.
-
- This object is only safe for use from two threads: one of the system under
- test calling control and the other from the test system calling pause,
- block_until_paused, and fail.
- """
-
- def __init__(self):
- self._condition = threading.Condition()
- self._pause = False
- self._paused = False
- self._fail = False
-
- def control(self):
- with self._condition:
- if self._fail:
- raise Defect()
-
- while self._pause:
- self._paused = True
- self._condition.notify_all()
- self._condition.wait()
- self._paused = False
-
- @contextlib.contextmanager
- def pause(self):
- """Pauses code under control while controlling code is in context."""
- with self._condition:
- self._pause = True
- yield
- with self._condition:
- self._pause = False
- self._condition.notify_all()
-
- def block_until_paused(self):
- """Blocks controlling code until code under control is paused.
-
- May only be called within the context of a pause call.
- """
- with self._condition:
- while not self._paused:
- self._condition.wait()
-
- @contextlib.contextmanager
- def fail(self):
- """Fails code under control while controlling code is in context."""
- with self._condition:
- self._fail = True
- yield
- with self._condition:
- self._fail = False
+# Copyright 2015 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.
+"""Code for instructing systems under test to block or fail."""
+
+import abc
+import contextlib
+import threading
+
+import six
+
+
+class Defect(Exception):
+ """Simulates a programming defect raised into in a system under test.
+
+ Use of a standard exception type is too easily misconstrued as an actual
+ defect in either the test infrastructure or the system under test.
+ """
+
+
+class Control(six.with_metaclass(abc.ABCMeta)):
+ """An object that accepts program control from a system under test.
+
+ Systems under test passed a Control should call its control() method
+ frequently during execution. The control() method may block, raise an
+ exception, or do nothing, all according to the enclosing test's desire for
+ the system under test to simulate hanging, failing, or functioning.
+ """
+
+ @abc.abstractmethod
+ def control(self):
+ """Potentially does anything."""
+ raise NotImplementedError()
+
+
+class PauseFailControl(Control):
+ """A Control that can be used to pause or fail code under control.
+
+ This object is only safe for use from two threads: one of the system under
+ test calling control and the other from the test system calling pause,
+ block_until_paused, and fail.
+ """
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._pause = False
+ self._paused = False
+ self._fail = False
+
+ def control(self):
+ with self._condition:
+ if self._fail:
+ raise Defect()
+
+ while self._pause:
+ self._paused = True
+ self._condition.notify_all()
+ self._condition.wait()
+ self._paused = False
+
+ @contextlib.contextmanager
+ def pause(self):
+ """Pauses code under control while controlling code is in context."""
+ with self._condition:
+ self._pause = True
+ yield
+ with self._condition:
+ self._pause = False
+ self._condition.notify_all()
+
+ def block_until_paused(self):
+ """Blocks controlling code until code under control is paused.
+
+ May only be called within the context of a pause call.
+ """
+ with self._condition:
+ while not self._paused:
+ self._condition.wait()
+
+ @contextlib.contextmanager
+ def fail(self):
+ """Fails code under control while controlling code is in context."""
+ with self._condition:
+ self._fail = True
+ yield
+ with self._condition:
+ self._fail = False
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py
index f90a11963f..1652a7633c 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py
@@ -1,101 +1,101 @@
-# Copyright 2015 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.
-"""Governs coverage for tests of RPCs throughout RPC Framework."""
-
-import abc
-
-import six
-
-# This code is designed for use with the unittest module.
-# pylint: disable=invalid-name
-
-
-class Coverage(six.with_metaclass(abc.ABCMeta)):
- """Specification of test coverage."""
-
- @abc.abstractmethod
- def testSuccessfulUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSuccessfulUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSuccessfulStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSuccessfulStreamRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSequentialInvocations(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testParallelInvocations(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testWaitingForSomeButNotAllParallelInvocations(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledStreamRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredStreamRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedStreamRequestStreamResponse(self):
- raise NotImplementedError()
+# Copyright 2015 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.
+"""Governs coverage for tests of RPCs throughout RPC Framework."""
+
+import abc
+
+import six
+
+# This code is designed for use with the unittest module.
+# pylint: disable=invalid-name
+
+
+class Coverage(six.with_metaclass(abc.ABCMeta)):
+ """Specification of test coverage."""
+
+ @abc.abstractmethod
+ def testSuccessfulUnaryRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testSuccessfulUnaryRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testSuccessfulStreamRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testSuccessfulStreamRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testSequentialInvocations(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testParallelInvocations(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testWaitingForSomeButNotAllParallelInvocations(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testCancelledUnaryRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testCancelledUnaryRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testCancelledStreamRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testCancelledStreamRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testExpiredUnaryRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testExpiredUnaryRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testExpiredStreamRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testExpiredStreamRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testFailedUnaryRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testFailedUnaryRequestStreamResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testFailedStreamRequestUnaryResponse(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def testFailedStreamRequestStreamResponse(self):
+ raise NotImplementedError()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py
index 5fb4f3c3cf..dc985eebb4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 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.
+# Copyright 2015 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.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py
index c4ea03177c..2a4c20ffc4 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py
@@ -1,73 +1,73 @@
-# Copyright 2015 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.
-"""Tests for grpc.framework.foundation.logging_pool."""
-
-import threading
-import unittest
-
-from grpc.framework.foundation import logging_pool
-
-_POOL_SIZE = 16
-
-
-class _CallableObject(object):
-
- def __init__(self):
- self._lock = threading.Lock()
- self._passed_values = []
-
- def __call__(self, value):
- with self._lock:
- self._passed_values.append(value)
-
- def passed_values(self):
- with self._lock:
- return tuple(self._passed_values)
-
-
-class LoggingPoolTest(unittest.TestCase):
-
- def testUpAndDown(self):
- pool = logging_pool.pool(_POOL_SIZE)
- pool.shutdown(wait=True)
-
- with logging_pool.pool(_POOL_SIZE) as pool:
- self.assertIsNotNone(pool)
-
- def testTaskExecuted(self):
- test_list = []
-
- with logging_pool.pool(_POOL_SIZE) as pool:
- pool.submit(lambda: test_list.append(object())).result()
-
- self.assertTrue(test_list)
-
- def testException(self):
- with logging_pool.pool(_POOL_SIZE) as pool:
- raised_exception = pool.submit(lambda: 1 / 0).exception()
-
- self.assertIsNotNone(raised_exception)
-
- def testCallableObjectExecuted(self):
- callable_object = _CallableObject()
- passed_object = object()
- with logging_pool.pool(_POOL_SIZE) as pool:
- future = pool.submit(callable_object, passed_object)
- self.assertIsNone(future.result())
- self.assertSequenceEqual((passed_object,),
- callable_object.passed_values())
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2015 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.
+"""Tests for grpc.framework.foundation.logging_pool."""
+
+import threading
+import unittest
+
+from grpc.framework.foundation import logging_pool
+
+_POOL_SIZE = 16
+
+
+class _CallableObject(object):
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._passed_values = []
+
+ def __call__(self, value):
+ with self._lock:
+ self._passed_values.append(value)
+
+ def passed_values(self):
+ with self._lock:
+ return tuple(self._passed_values)
+
+
+class LoggingPoolTest(unittest.TestCase):
+
+ def testUpAndDown(self):
+ pool = logging_pool.pool(_POOL_SIZE)
+ pool.shutdown(wait=True)
+
+ with logging_pool.pool(_POOL_SIZE) as pool:
+ self.assertIsNotNone(pool)
+
+ def testTaskExecuted(self):
+ test_list = []
+
+ with logging_pool.pool(_POOL_SIZE) as pool:
+ pool.submit(lambda: test_list.append(object())).result()
+
+ self.assertTrue(test_list)
+
+ def testException(self):
+ with logging_pool.pool(_POOL_SIZE) as pool:
+ raised_exception = pool.submit(lambda: 1 / 0).exception()
+
+ self.assertIsNotNone(raised_exception)
+
+ def testCallableObjectExecuted(self):
+ callable_object = _CallableObject()
+ passed_object = object()
+ with logging_pool.pool(_POOL_SIZE) as pool:
+ future = pool.submit(callable_object, passed_object)
+ self.assertIsNone(future.result())
+ self.assertSequenceEqual((passed_object,),
+ callable_object.passed_values())
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py
index dd5c5b3b03..9c3b526b50 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py
@@ -1,57 +1,57 @@
-# Copyright 2015 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.
-"""Utilities for testing stream-related code."""
-
-from grpc.framework.foundation import stream
-
-
-class TestConsumer(stream.Consumer):
- """A stream.Consumer instrumented for testing.
-
- Attributes:
- calls: A sequence of value-termination pairs describing the history of calls
- made on this object.
- """
-
- def __init__(self):
- self.calls = []
-
- def consume(self, value):
- """See stream.Consumer.consume for specification."""
- self.calls.append((value, False))
-
- def terminate(self):
- """See stream.Consumer.terminate for specification."""
- self.calls.append((None, True))
-
- def consume_and_terminate(self, value):
- """See stream.Consumer.consume_and_terminate for specification."""
- self.calls.append((value, True))
-
- def is_legal(self):
- """Reports whether or not a legal sequence of calls has been made."""
- terminated = False
- for value, terminal in self.calls:
- if terminated:
- return False
- elif terminal:
- terminated = True
- elif value is None:
- return False
- else: # pylint: disable=useless-else-on-loop
- return True
-
- def values(self):
- """Returns the sequence of values that have been passed to this Consumer."""
- return [value for value, _ in self.calls if value]
+# Copyright 2015 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.
+"""Utilities for testing stream-related code."""
+
+from grpc.framework.foundation import stream
+
+
+class TestConsumer(stream.Consumer):
+ """A stream.Consumer instrumented for testing.
+
+ Attributes:
+ calls: A sequence of value-termination pairs describing the history of calls
+ made on this object.
+ """
+
+ def __init__(self):
+ self.calls = []
+
+ def consume(self, value):
+ """See stream.Consumer.consume for specification."""
+ self.calls.append((value, False))
+
+ def terminate(self):
+ """See stream.Consumer.terminate for specification."""
+ self.calls.append((None, True))
+
+ def consume_and_terminate(self, value):
+ """See stream.Consumer.consume_and_terminate for specification."""
+ self.calls.append((value, True))
+
+ def is_legal(self):
+ """Reports whether or not a legal sequence of calls has been made."""
+ terminated = False
+ for value, terminal in self.calls:
+ if terminated:
+ return False
+ elif terminal:
+ terminated = True
+ elif value is None:
+ return False
+ else: # pylint: disable=useless-else-on-loop
+ return True
+
+ def values(self):
+ """Returns the sequence of values that have been passed to this Consumer."""
+ return [value for value, _ in self.calls if value]
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py
index 6efd870fc8..1e6d40454a 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py
@@ -1,113 +1,113 @@
-# Copyright 2015 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.
-"""Constants and functions for data used in testing."""
-
-import os
-import pkgutil
-
-_ROOT_CERTIFICATES_RESOURCE_PATH = 'credentials/ca.pem'
-_PRIVATE_KEY_RESOURCE_PATH = 'credentials/server1.key'
-_CERTIFICATE_CHAIN_RESOURCE_PATH = 'credentials/server1.pem'
-
-
-def test_root_certificates():
- return pkgutil.get_data(__name__, _ROOT_CERTIFICATES_RESOURCE_PATH)
-
-
-def private_key():
- return pkgutil.get_data(__name__, _PRIVATE_KEY_RESOURCE_PATH)
-
-
-def certificate_chain():
- return pkgutil.get_data(__name__, _CERTIFICATE_CHAIN_RESOURCE_PATH)
-
-
-def cert_hier_1_root_ca_cert():
- return pkgutil.get_data(
- __name__, 'credentials/certificate_hierarchy_1/certs/ca.cert.pem')
-
-
-def cert_hier_1_intermediate_ca_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/certs/intermediate.cert.pem'
- )
-
-
-def cert_hier_1_client_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/private/client.key.pem'
- )
-
-
-def cert_hier_1_client_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem'
- )
-
-
-def cert_hier_1_server_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem'
- )
-
-
-def cert_hier_1_server_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/certs/localhost-1.cert.pem'
- )
-
-
-def cert_hier_2_root_ca_cert():
- return pkgutil.get_data(
- __name__, 'credentials/certificate_hierarchy_2/certs/ca.cert.pem')
-
-
-def cert_hier_2_intermediate_ca_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem'
- )
-
-
-def cert_hier_2_client_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/private/client.key.pem'
- )
-
-
-def cert_hier_2_client_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem'
- )
-
-
-def cert_hier_2_server_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem'
- )
-
-
-def cert_hier_2_server_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem'
- )
+# Copyright 2015 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.
+"""Constants and functions for data used in testing."""
+
+import os
+import pkgutil
+
+_ROOT_CERTIFICATES_RESOURCE_PATH = 'credentials/ca.pem'
+_PRIVATE_KEY_RESOURCE_PATH = 'credentials/server1.key'
+_CERTIFICATE_CHAIN_RESOURCE_PATH = 'credentials/server1.pem'
+
+
+def test_root_certificates():
+ return pkgutil.get_data(__name__, _ROOT_CERTIFICATES_RESOURCE_PATH)
+
+
+def private_key():
+ return pkgutil.get_data(__name__, _PRIVATE_KEY_RESOURCE_PATH)
+
+
+def certificate_chain():
+ return pkgutil.get_data(__name__, _CERTIFICATE_CHAIN_RESOURCE_PATH)
+
+
+def cert_hier_1_root_ca_cert():
+ return pkgutil.get_data(
+ __name__, 'credentials/certificate_hierarchy_1/certs/ca.cert.pem')
+
+
+def cert_hier_1_intermediate_ca_cert():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_1/intermediate/certs/intermediate.cert.pem'
+ )
+
+
+def cert_hier_1_client_1_key():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_1/intermediate/private/client.key.pem'
+ )
+
+
+def cert_hier_1_client_1_cert():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem'
+ )
+
+
+def cert_hier_1_server_1_key():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem'
+ )
+
+
+def cert_hier_1_server_1_cert():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_1/intermediate/certs/localhost-1.cert.pem'
+ )
+
+
+def cert_hier_2_root_ca_cert():
+ return pkgutil.get_data(
+ __name__, 'credentials/certificate_hierarchy_2/certs/ca.cert.pem')
+
+
+def cert_hier_2_intermediate_ca_cert():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem'
+ )
+
+
+def cert_hier_2_client_1_key():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_2/intermediate/private/client.key.pem'
+ )
+
+
+def cert_hier_2_client_1_cert():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem'
+ )
+
+
+def cert_hier_2_server_1_key():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem'
+ )
+
+
+def cert_hier_2_server_1_cert():
+ return pkgutil.get_data(
+ __name__,
+ 'credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem'
+ )
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py
index 59ded0752f..a916dac283 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py
@@ -1,134 +1,134 @@
-# Copyright 2015 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.
-"""Common code used throughout tests of gRPC."""
-
-import collections
-import threading
-
-from concurrent import futures
-import grpc
-import six
-
-INVOCATION_INITIAL_METADATA = (
- ('0', 'abc'),
- ('1', 'def'),
- ('2', 'ghi'),
-)
-SERVICE_INITIAL_METADATA = (
- ('3', 'jkl'),
- ('4', 'mno'),
- ('5', 'pqr'),
-)
-SERVICE_TERMINAL_METADATA = (
- ('6', 'stu'),
- ('7', 'vwx'),
- ('8', 'yza'),
-)
-DETAILS = 'test details'
-
-
-def metadata_transmitted(original_metadata, transmitted_metadata):
- """Judges whether or not metadata was acceptably transmitted.
-
- gRPC is allowed to insert key-value pairs into the metadata values given by
- applications and to reorder key-value pairs with different keys but it is not
- allowed to alter existing key-value pairs or to reorder key-value pairs with
- the same key.
-
- Args:
- original_metadata: A metadata value used in a test of gRPC. An iterable over
- iterables of length 2.
- transmitted_metadata: A metadata value corresponding to original_metadata
- after having been transmitted via gRPC. An iterable over iterables of
- length 2.
-
- Returns:
- A boolean indicating whether transmitted_metadata accurately reflects
- original_metadata after having been transmitted via gRPC.
- """
- original = collections.defaultdict(list)
- for key, value in original_metadata:
- original[key].append(value)
- transmitted = collections.defaultdict(list)
- for key, value in transmitted_metadata:
- transmitted[key].append(value)
-
- for key, values in six.iteritems(original):
- transmitted_values = transmitted[key]
- transmitted_iterator = iter(transmitted_values)
- try:
- for value in values:
- while True:
- transmitted_value = next(transmitted_iterator)
- if value == transmitted_value:
- break
- except StopIteration:
- return False
- else:
- return True
-
-
-def test_secure_channel(target, channel_credentials, server_host_override):
- """Creates an insecure Channel to a remote host.
-
- Args:
- host: The name of the remote host to which to connect.
- port: The port of the remote host to which to connect.
- channel_credentials: The implementations.ChannelCredentials with which to
- connect.
- server_host_override: The target name used for SSL host name checking.
-
- Returns:
- An implementations.Channel to the remote host through which RPCs may be
- conducted.
- """
- channel = grpc.secure_channel(target, channel_credentials, ((
- 'grpc.ssl_target_name_override',
- server_host_override,
- ),))
- return channel
-
-
-def test_server(max_workers=10, reuse_port=False):
- """Creates an insecure grpc server.
-
- These servers have SO_REUSEPORT disabled to prevent cross-talk.
- """
+# Copyright 2015 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.
+"""Common code used throughout tests of gRPC."""
+
+import collections
+import threading
+
+from concurrent import futures
+import grpc
+import six
+
+INVOCATION_INITIAL_METADATA = (
+ ('0', 'abc'),
+ ('1', 'def'),
+ ('2', 'ghi'),
+)
+SERVICE_INITIAL_METADATA = (
+ ('3', 'jkl'),
+ ('4', 'mno'),
+ ('5', 'pqr'),
+)
+SERVICE_TERMINAL_METADATA = (
+ ('6', 'stu'),
+ ('7', 'vwx'),
+ ('8', 'yza'),
+)
+DETAILS = 'test details'
+
+
+def metadata_transmitted(original_metadata, transmitted_metadata):
+ """Judges whether or not metadata was acceptably transmitted.
+
+ gRPC is allowed to insert key-value pairs into the metadata values given by
+ applications and to reorder key-value pairs with different keys but it is not
+ allowed to alter existing key-value pairs or to reorder key-value pairs with
+ the same key.
+
+ Args:
+ original_metadata: A metadata value used in a test of gRPC. An iterable over
+ iterables of length 2.
+ transmitted_metadata: A metadata value corresponding to original_metadata
+ after having been transmitted via gRPC. An iterable over iterables of
+ length 2.
+
+ Returns:
+ A boolean indicating whether transmitted_metadata accurately reflects
+ original_metadata after having been transmitted via gRPC.
+ """
+ original = collections.defaultdict(list)
+ for key, value in original_metadata:
+ original[key].append(value)
+ transmitted = collections.defaultdict(list)
+ for key, value in transmitted_metadata:
+ transmitted[key].append(value)
+
+ for key, values in six.iteritems(original):
+ transmitted_values = transmitted[key]
+ transmitted_iterator = iter(transmitted_values)
+ try:
+ for value in values:
+ while True:
+ transmitted_value = next(transmitted_iterator)
+ if value == transmitted_value:
+ break
+ except StopIteration:
+ return False
+ else:
+ return True
+
+
+def test_secure_channel(target, channel_credentials, server_host_override):
+ """Creates an insecure Channel to a remote host.
+
+ Args:
+ host: The name of the remote host to which to connect.
+ port: The port of the remote host to which to connect.
+ channel_credentials: The implementations.ChannelCredentials with which to
+ connect.
+ server_host_override: The target name used for SSL host name checking.
+
+ Returns:
+ An implementations.Channel to the remote host through which RPCs may be
+ conducted.
+ """
+ channel = grpc.secure_channel(target, channel_credentials, ((
+ 'grpc.ssl_target_name_override',
+ server_host_override,
+ ),))
+ return channel
+
+
+def test_server(max_workers=10, reuse_port=False):
+ """Creates an insecure grpc server.
+
+ These servers have SO_REUSEPORT disabled to prevent cross-talk.
+ """
return grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers),
options=(('grpc.so_reuseport', int(reuse_port)),))
-
-
-class WaitGroup(object):
-
- def __init__(self, n=0):
- self.count = n
- self.cv = threading.Condition()
-
- def add(self, n):
- self.cv.acquire()
- self.count += n
- self.cv.release()
-
- def done(self):
- self.cv.acquire()
- self.count -= 1
- if self.count == 0:
- self.cv.notify_all()
- self.cv.release()
-
- def wait(self):
- self.cv.acquire()
- while self.count > 0:
- self.cv.wait()
- self.cv.release()
+
+
+class WaitGroup(object):
+
+ def __init__(self, n=0):
+ self.count = n
+ self.cv = threading.Condition()
+
+ def add(self, n):
+ self.cv.acquire()
+ self.count += n
+ self.cv.release()
+
+ def done(self):
+ self.cv.acquire()
+ self.count -= 1
+ if self.count == 0:
+ self.cv.notify_all()
+ self.cv.release()
+
+ def wait(self):
+ self.cv.acquire()
+ while self.count > 0:
+ self.cv.wait()
+ self.cv.release()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py
index 094e203cd9..c2d05c9cb6 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py
@@ -1,34 +1,34 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import threading
-from concurrent import futures
-
-
-class RecordingThreadPool(futures.ThreadPoolExecutor):
- """A thread pool that records if used."""
-
- def __init__(self, max_workers):
- self._tp_executor = futures.ThreadPoolExecutor(max_workers=max_workers)
- self._lock = threading.Lock()
- self._was_used = False
-
- def submit(self, fn, *args, **kwargs): # pylint: disable=arguments-differ
- with self._lock:
- self._was_used = True
- self._tp_executor.submit(fn, *args, **kwargs)
-
- def was_used(self):
- with self._lock:
- return self._was_used
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import threading
+from concurrent import futures
+
+
+class RecordingThreadPool(futures.ThreadPoolExecutor):
+ """A thread pool that records if used."""
+
+ def __init__(self, max_workers):
+ self._tp_executor = futures.ThreadPoolExecutor(max_workers=max_workers)
+ self._lock = threading.Lock()
+ self._was_used = False
+
+ def submit(self, fn, *args, **kwargs): # pylint: disable=arguments-differ
+ with self._lock:
+ self._was_used = True
+ self._tp_executor.submit(fn, *args, **kwargs)
+
+ def was_used(self):
+ with self._lock:
+ return self._was_used
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/__init__.py
index 8ddd310696..b4533c806e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/__init__.py
@@ -1,21 +1,21 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from __future__ import absolute_import
-
-from tests import _loader
-from tests import _runner
-
-Loader = _loader.Loader
-Runner = _runner.Runner
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+
+from tests import _loader
+from tests import _runner
+
+Loader = _loader.Loader
+Runner = _runner.Runner
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/__init__.py
index f4b321fc5b..690315b5ad 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/_sanity_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/_sanity_test.py
index e74dec0739..d69c738f4d 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/_sanity_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/_sanity/_sanity_test.py
@@ -1,27 +1,27 @@
-# Copyright 2019 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import unittest
-
-from tests._sanity import _sanity_test
-
-
-class AioSanityTest(_sanity_test.SanityTest):
-
- TEST_PKG_MODULE_NAME = 'tests_aio'
- TEST_PKG_PATH = 'tests_aio'
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
+# Copyright 2019 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+
+from tests._sanity import _sanity_test
+
+
+class AioSanityTest(_sanity_test.SanityTest):
+
+ TEST_PKG_MODULE_NAME = 'tests_aio'
+ TEST_PKG_PATH = 'tests_aio'
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/benchmark/server.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/benchmark/server.py
index 561298a626..1d0ca1eb72 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/benchmark/server.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/benchmark/server.py
@@ -1,46 +1,46 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import asyncio
-import logging
-import unittest
-
-from grpc.experimental import aio
-
-from src.proto.grpc.testing import benchmark_service_pb2_grpc
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import asyncio
+import logging
+import unittest
+
+from grpc.experimental import aio
+
+from src.proto.grpc.testing import benchmark_service_pb2_grpc
from tests_aio.benchmark import benchmark_servicer
-
-
-async def _start_async_server():
- server = aio.server()
-
+
+
+async def _start_async_server():
+ server = aio.server()
+
port = server.add_insecure_port('localhost:%s' % 50051)
servicer = benchmark_servicer.BenchmarkServicer()
- benchmark_service_pb2_grpc.add_BenchmarkServiceServicer_to_server(
- servicer, server)
-
- await server.start()
+ benchmark_service_pb2_grpc.add_BenchmarkServiceServicer_to_server(
+ servicer, server)
+
+ await server.start()
logging.info('Benchmark server started at :%d' % port)
- await server.wait_for_termination()
-
-
-def main():
- loop = asyncio.get_event_loop()
- loop.create_task(_start_async_server())
- loop.run_forever()
-
-
-if __name__ == '__main__':
+ await server.wait_for_termination()
+
+
+def main():
+ loop = asyncio.get_event_loop()
+ loop.create_task(_start_async_server())
+ loop.run_forever()
+
+
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- main()
+ main()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/__init__.py
index f4b321fc5b..690315b5ad 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_base.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_base.py
index ec5f2112da..d74ee6cf90 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_base.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_base.py
@@ -1,26 +1,26 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import logging
import functools
-import asyncio
+import asyncio
from typing import Callable
-import unittest
-from grpc.experimental import aio
-
+import unittest
+from grpc.experimental import aio
+
__all__ = 'AioTestBase'
-
+
_COROUTINE_FUNCTION_ALLOWLIST = ['setUp', 'tearDown']
@@ -45,13 +45,13 @@ def _get_default_loop(debug=True):
# NOTE(gnossen) this test class can also be implemented with metaclass.
-class AioTestBase(unittest.TestCase):
+class AioTestBase(unittest.TestCase):
# NOTE(lidi) We need to pick a loop for entire testing phase, otherwise it
# will trigger create new loops in new threads, leads to deadlock.
_TEST_LOOP = _get_default_loop()
-
- @property
- def loop(self):
+
+ @property
+ def loop(self):
return self._TEST_LOOP
def __getattribute__(self, name):
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_server.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_server.py
index 5e5081a38d..f979f285d3 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_server.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/_test_server.py
@@ -1,27 +1,27 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
+# Copyright 2019 The gRPC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import asyncio
import datetime
-
+
import grpc
-from grpc.experimental import aio
+from grpc.experimental import aio
from tests.unit import resources
-
+
from src.proto.grpc.testing import empty_pb2, messages_pb2, test_pb2_grpc
from tests_aio.unit import _constants
-
+
_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
@@ -48,14 +48,14 @@ async def _maybe_echo_status(request: messages_pb2.SimpleRequest,
class TestServiceServicer(test_pb2_grpc.TestServiceServicer):
-
+
async def UnaryCall(self, request, context):
await _maybe_echo_metadata(context)
await _maybe_echo_status(request, context)
return messages_pb2.SimpleResponse(
payload=messages_pb2.Payload(type=messages_pb2.COMPRESSABLE,
body=b'\x00' * request.response_size))
-
+
async def EmptyCall(self, request, context):
return empty_pb2.Empty()
@@ -71,14 +71,14 @@ class TestServiceServicer(test_pb2_grpc.TestServiceServicer):
payload=messages_pb2.Payload(type=request.response_type,
body=b'\x00' *
response_parameters.size))
-
+
# Next methods are extra ones that are registred programatically
# when the sever is instantiated. They are not being provided by
# the proto file.
async def UnaryCallWithSleep(self, unused_request, unused_context):
await asyncio.sleep(_constants.UNARY_CALL_WITH_SLEEP_VALUE)
return messages_pb2.SimpleResponse()
-
+
async def StreamingInputCall(self, request_async_iterator, unused_context):
aggregate_size = 0
async for request in request_async_iterator:
@@ -137,7 +137,7 @@ async def start_test_server(port=0,
else:
port = server.add_insecure_port('[::]:%d' % port)
- await server.start()
+ await server.start()
- # NOTE(lidizheng) returning the server to prevent it from deallocation
- return 'localhost:%d' % port, server
+ # NOTE(lidizheng) returning the server to prevent it from deallocation
+ return 'localhost:%d' % port, server
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/call_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/call_test.py
index 1961226fa6..0fdbdb2a2d 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/call_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/call_test.py
@@ -1,31 +1,31 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Tests behavior of the Call classes."""
-import asyncio
-import logging
-import unittest
+import asyncio
+import logging
+import unittest
import datetime
-
-import grpc
+
+import grpc
from grpc.experimental import aio
-
+
from src.proto.grpc.testing import messages_pb2, test_pb2_grpc
from tests_aio.unit._test_base import AioTestBase
-from tests_aio.unit._test_server import start_test_server
+from tests_aio.unit._test_server import start_test_server
from tests_aio.unit._constants import UNREACHABLE_TARGET
-
+
_SHORT_TIMEOUT_S = datetime.timedelta(seconds=1).total_seconds()
_NUM_STREAM_RESPONSES = 5
@@ -34,22 +34,22 @@ _REQUEST_PAYLOAD_SIZE = 7
_LOCAL_CANCEL_DETAILS_EXPECTATION = 'Locally cancelled by application!'
_RESPONSE_INTERVAL_US = int(_SHORT_TIMEOUT_S * 1000 * 1000)
_INFINITE_INTERVAL_US = 2**31 - 1
-
-
+
+
class _MulticallableTestMixin():
-
+
async def setUp(self):
address, self._server = await start_test_server()
self._channel = aio.insecure_channel(address)
self._stub = test_pb2_grpc.TestServiceStub(self._channel)
-
+
async def tearDown(self):
await self._channel.close()
await self._server.stop(None)
-
-
+
+
class TestUnaryUnaryCall(_MulticallableTestMixin, AioTestBase):
-
+
async def test_call_to_string(self):
call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
@@ -63,47 +63,47 @@ class TestUnaryUnaryCall(_MulticallableTestMixin, AioTestBase):
async def test_call_ok(self):
call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
-
+
self.assertFalse(call.done())
-
+
response = await call
-
+
self.assertTrue(call.done())
self.assertIsInstance(response, messages_pb2.SimpleResponse)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
# Response is cached at call object level, reentrance
# returns again the same response
response_retry = await call
self.assertIs(response, response_retry)
-
+
async def test_call_rpc_error(self):
async with aio.insecure_channel(UNREACHABLE_TARGET) as channel:
stub = test_pb2_grpc.TestServiceStub(channel)
-
+
call = stub.UnaryCall(messages_pb2.SimpleRequest())
-
+
with self.assertRaises(aio.AioRpcError) as exception_context:
await call
-
+
self.assertEqual(grpc.StatusCode.UNAVAILABLE,
exception_context.exception.code())
-
+
self.assertTrue(call.done())
self.assertEqual(grpc.StatusCode.UNAVAILABLE, await call.code())
-
+
async def test_call_code_awaitable(self):
call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_call_details_awaitable(self):
call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
self.assertEqual('', await call.details())
-
+
async def test_call_initial_metadata_awaitable(self):
call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
self.assertEqual(aio.Metadata(), await call.initial_metadata())
-
+
async def test_call_trailing_metadata_awaitable(self):
call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
self.assertEqual(aio.Metadata(), await call.trailing_metadata())
@@ -450,56 +450,56 @@ class TestUnaryStreamCall(_MulticallableTestMixin, AioTestBase):
size=_RESPONSE_PAYLOAD_SIZE,
interval_us=_RESPONSE_INTERVAL_US,
))
-
+
call = self._stub.StreamingOutputCall(request,
timeout=_SHORT_TIMEOUT_S * 2)
-
+
response = await call.read()
self.assertEqual(_RESPONSE_PAYLOAD_SIZE, len(response.payload.body))
-
+
# Should be around the same as the timeout
remained_time = call.time_remaining()
self.assertGreater(remained_time, _SHORT_TIMEOUT_S * 3 / 2)
self.assertLess(remained_time, _SHORT_TIMEOUT_S * 5 / 2)
-
+
response = await call.read()
self.assertEqual(_RESPONSE_PAYLOAD_SIZE, len(response.payload.body))
-
+
# Should be around the timeout minus a unit of wait time
remained_time = call.time_remaining()
self.assertGreater(remained_time, _SHORT_TIMEOUT_S / 2)
self.assertLess(remained_time, _SHORT_TIMEOUT_S * 3 / 2)
-
+
self.assertEqual(grpc.StatusCode.OK, await call.code())
-
-
+
+
class TestStreamUnaryCall(_MulticallableTestMixin, AioTestBase):
-
+
async def test_cancel_stream_unary(self):
call = self._stub.StreamingInputCall()
-
+
# Prepares the request
payload = messages_pb2.Payload(body=b'\0' * _REQUEST_PAYLOAD_SIZE)
request = messages_pb2.StreamingInputCallRequest(payload=payload)
-
+
# Sends out requests
for _ in range(_NUM_STREAM_RESPONSES):
await call.write(request)
-
+
# Cancels the RPC
self.assertFalse(call.done())
self.assertFalse(call.cancelled())
self.assertTrue(call.cancel())
self.assertTrue(call.cancelled())
-
+
await call.done_writing()
-
+
with self.assertRaises(asyncio.CancelledError):
await call
-
+
async def test_early_cancel_stream_unary(self):
call = self._stub.StreamingInputCall()
-
+
# Cancels the RPC
self.assertFalse(call.done())
self.assertFalse(call.cancelled())
@@ -809,6 +809,6 @@ class TestStreamStreamCall(_MulticallableTestMixin, AioTestBase):
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-if __name__ == '__main__':
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/channel_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/channel_test.py
index 58cd555491..76027c433e 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/channel_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/channel_test.py
@@ -1,54 +1,54 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Tests behavior of the grpc.aio.Channel class."""
-import logging
+import logging
import os
-import unittest
-
-import grpc
+import unittest
+
+import grpc
from grpc.experimental import aio
-
+
from src.proto.grpc.testing import messages_pb2, test_pb2_grpc
-from tests.unit.framework.common import test_constants
+from tests.unit.framework.common import test_constants
from tests_aio.unit._constants import (UNARY_CALL_WITH_SLEEP_VALUE,
UNREACHABLE_TARGET)
from tests_aio.unit._test_base import AioTestBase
-from tests_aio.unit._test_server import start_test_server
-
-_UNARY_CALL_METHOD = '/grpc.testing.TestService/UnaryCall'
+from tests_aio.unit._test_server import start_test_server
+
+_UNARY_CALL_METHOD = '/grpc.testing.TestService/UnaryCall'
_UNARY_CALL_METHOD_WITH_SLEEP = '/grpc.testing.TestService/UnaryCallWithSleep'
_STREAMING_OUTPUT_CALL_METHOD = '/grpc.testing.TestService/StreamingOutputCall'
-
+
_INVOCATION_METADATA = (
('x-grpc-test-echo-initial', 'initial-md-value'),
('x-grpc-test-echo-trailing-bin', b'\x00\x02'),
)
-
+
_NUM_STREAM_RESPONSES = 5
_REQUEST_PAYLOAD_SIZE = 7
_RESPONSE_PAYLOAD_SIZE = 42
-
-
+
+
class TestChannel(AioTestBase):
-
+
async def setUp(self):
self._server_target, self._server = await start_test_server()
-
+
async def tearDown(self):
await self._server.stop(None)
-
+
async def test_async_context(self):
async with aio.insecure_channel(self._server_target) as channel:
hi = channel.unary_unary(
@@ -56,17 +56,17 @@ class TestChannel(AioTestBase):
request_serializer=messages_pb2.SimpleRequest.SerializeToString,
response_deserializer=messages_pb2.SimpleResponse.FromString)
await hi(messages_pb2.SimpleRequest())
-
+
async def test_unary_unary(self):
async with aio.insecure_channel(self._server_target) as channel:
- hi = channel.unary_unary(
- _UNARY_CALL_METHOD,
- request_serializer=messages_pb2.SimpleRequest.SerializeToString,
- response_deserializer=messages_pb2.SimpleResponse.FromString)
- response = await hi(messages_pb2.SimpleRequest())
-
+ hi = channel.unary_unary(
+ _UNARY_CALL_METHOD,
+ request_serializer=messages_pb2.SimpleRequest.SerializeToString,
+ response_deserializer=messages_pb2.SimpleResponse.FromString)
+ response = await hi(messages_pb2.SimpleRequest())
+
self.assertIsInstance(response, messages_pb2.SimpleResponse)
-
+
async def test_unary_call_times_out(self):
async with aio.insecure_channel(self._server_target) as channel:
hi = channel.unary_unary(
@@ -74,11 +74,11 @@ class TestChannel(AioTestBase):
request_serializer=messages_pb2.SimpleRequest.SerializeToString,
response_deserializer=messages_pb2.SimpleResponse.FromString,
)
-
+
with self.assertRaises(grpc.RpcError) as exception_context:
await hi(messages_pb2.SimpleRequest(),
timeout=UNARY_CALL_WITH_SLEEP_VALUE / 2)
-
+
_, details = grpc.StatusCode.DEADLINE_EXCEEDED.value # pylint: disable=unused-variable
self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED,
exception_context.exception.code())
@@ -87,7 +87,7 @@ class TestChannel(AioTestBase):
self.assertIsNotNone(exception_context.exception.initial_metadata())
self.assertIsNotNone(
exception_context.exception.trailing_metadata())
-
+
@unittest.skipIf(os.name == 'nt',
'TODO: https://github.com/grpc/grpc/issues/21658')
async def test_unary_call_does_not_times_out(self):
@@ -97,24 +97,24 @@ class TestChannel(AioTestBase):
request_serializer=messages_pb2.SimpleRequest.SerializeToString,
response_deserializer=messages_pb2.SimpleResponse.FromString,
)
-
+
call = hi(messages_pb2.SimpleRequest(),
timeout=UNARY_CALL_WITH_SLEEP_VALUE * 5)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_unary_stream(self):
channel = aio.insecure_channel(self._server_target)
stub = test_pb2_grpc.TestServiceStub(channel)
-
+
# Prepares the request
request = messages_pb2.StreamingOutputCallRequest()
for _ in range(_NUM_STREAM_RESPONSES):
request.response_parameters.append(
messages_pb2.ResponseParameters(size=_RESPONSE_PAYLOAD_SIZE))
-
+
# Invokes the actual RPC
call = stub.StreamingOutputCall(request)
-
+
# Validates the responses
response_cnt = 0
async for response in call:
@@ -122,22 +122,22 @@ class TestChannel(AioTestBase):
self.assertIs(type(response),
messages_pb2.StreamingOutputCallResponse)
self.assertEqual(_RESPONSE_PAYLOAD_SIZE, len(response.payload.body))
-
+
self.assertEqual(_NUM_STREAM_RESPONSES, response_cnt)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
await channel.close()
-
+
async def test_stream_unary_using_write(self):
channel = aio.insecure_channel(self._server_target)
stub = test_pb2_grpc.TestServiceStub(channel)
-
+
# Invokes the actual RPC
call = stub.StreamingInputCall()
-
+
# Prepares the request
payload = messages_pb2.Payload(body=b'\0' * _REQUEST_PAYLOAD_SIZE)
request = messages_pb2.StreamingInputCallRequest(payload=payload)
-
+
# Sends out requests
for _ in range(_NUM_STREAM_RESPONSES):
await call.write(request)
@@ -225,6 +225,6 @@ class TestChannel(AioTestBase):
await channel.close()
-if __name__ == '__main__':
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/init_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/init_test.py
index b9183a22c7..8d5eed6972 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/init_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/init_test.py
@@ -1,33 +1,33 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-import logging
-import unittest
-
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import logging
+import unittest
+
class TestInit(unittest.TestCase):
-
+
def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
-
+
def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
+
-
-if __name__ == '__main__':
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/server_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/server_test.py
index 61d1edd523..6e528faf37 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/server_test.py
+++ b/contrib/libs/grpc/src/python/grpcio_tests/tests_aio/unit/server_test.py
@@ -1,34 +1,34 @@
-# Copyright 2019 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import asyncio
+# Copyright 2019 The gRPC Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import asyncio
import gc
-import logging
+import logging
import socket
import time
-import unittest
-
-import grpc
-from grpc.experimental import aio
+import unittest
+
+import grpc
+from grpc.experimental import aio
from tests.unit import resources
from tests.unit.framework.common import test_constants
-from tests_aio.unit._test_base import AioTestBase
-
-_SIMPLE_UNARY_UNARY = '/test/SimpleUnaryUnary'
-_BLOCK_FOREVER = '/test/BlockForever'
-_BLOCK_BRIEFLY = '/test/BlockBriefly'
+from tests_aio.unit._test_base import AioTestBase
+
+_SIMPLE_UNARY_UNARY = '/test/SimpleUnaryUnary'
+_BLOCK_FOREVER = '/test/BlockForever'
+_BLOCK_BRIEFLY = '/test/BlockBriefly'
_UNARY_STREAM_ASYNC_GEN = '/test/UnaryStreamAsyncGen'
_UNARY_STREAM_READER_WRITER = '/test/UnaryStreamReaderWriter'
_UNARY_STREAM_EVILLY_MIXED = '/test/UnaryStreamEvillyMixed'
@@ -42,17 +42,17 @@ _UNIMPLEMENTED_METHOD = '/test/UnimplementedMethod'
_ERROR_IN_STREAM_STREAM = '/test/ErrorInStreamStream'
_ERROR_WITHOUT_RAISE_IN_UNARY_UNARY = '/test/ErrorWithoutRaiseInUnaryUnary'
_ERROR_WITHOUT_RAISE_IN_STREAM_STREAM = '/test/ErrorWithoutRaiseInStreamStream'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x01\x01\x01'
+
+_REQUEST = b'\x00\x00\x00'
+_RESPONSE = b'\x01\x01\x01'
_NUM_STREAM_REQUESTS = 3
_NUM_STREAM_RESPONSES = 5
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self):
- self._called = asyncio.get_event_loop().create_future()
+
+
+class _GenericHandler(grpc.GenericRpcHandler):
+
+ def __init__(self):
+ self._called = asyncio.get_event_loop().create_future()
self._routing_table = {
_SIMPLE_UNARY_UNARY:
grpc.unary_unary_rpc_method_handler(self._unary_unary),
@@ -97,18 +97,18 @@ class _GenericHandler(grpc.GenericRpcHandler):
grpc.stream_stream_rpc_method_handler(
self._error_without_raise_in_stream_stream),
}
-
- @staticmethod
- async def _unary_unary(unused_request, unused_context):
- return _RESPONSE
-
- async def _block_forever(self, unused_request, unused_context):
- await asyncio.get_event_loop().create_future()
-
+
+ @staticmethod
+ async def _unary_unary(unused_request, unused_context):
+ return _RESPONSE
+
+ async def _block_forever(self, unused_request, unused_context):
+ await asyncio.get_event_loop().create_future()
+
async def _block_briefly(self, unused_request, unused_context):
- await asyncio.sleep(test_constants.SHORT_TIMEOUT / 2)
- return _RESPONSE
-
+ await asyncio.sleep(test_constants.SHORT_TIMEOUT / 2)
+ return _RESPONSE
+
async def _unary_stream_async_gen(self, unused_request, unused_context):
for _ in range(_NUM_STREAM_RESPONSES):
yield _RESPONSE
@@ -188,164 +188,164 @@ class _GenericHandler(grpc.GenericRpcHandler):
assert _REQUEST == request
context.set_code(grpc.StatusCode.INTERNAL)
- def service(self, handler_details):
- self._called.set_result(None)
+ def service(self, handler_details):
+ self._called.set_result(None)
return self._routing_table.get(handler_details.method)
-
- async def wait_for_call(self):
- await self._called
-
-
-async def _start_test_server():
- server = aio.server()
- port = server.add_insecure_port('[::]:0')
- generic_handler = _GenericHandler()
- server.add_generic_rpc_handlers((generic_handler,))
- await server.start()
- return 'localhost:%d' % port, server, generic_handler
-
-
-class TestServer(AioTestBase):
-
+
+ async def wait_for_call(self):
+ await self._called
+
+
+async def _start_test_server():
+ server = aio.server()
+ port = server.add_insecure_port('[::]:0')
+ generic_handler = _GenericHandler()
+ server.add_generic_rpc_handlers((generic_handler,))
+ await server.start()
+ return 'localhost:%d' % port, server, generic_handler
+
+
+class TestServer(AioTestBase):
+
async def setUp(self):
addr, self._server, self._generic_handler = await _start_test_server()
self._channel = aio.insecure_channel(addr)
-
+
async def tearDown(self):
await self._channel.close()
await self._server.stop(None)
-
+
async def test_unary_unary(self):
unary_unary_call = self._channel.unary_unary(_SIMPLE_UNARY_UNARY)
response = await unary_unary_call(_REQUEST)
self.assertEqual(response, _RESPONSE)
-
+
async def test_unary_stream_async_generator(self):
unary_stream_call = self._channel.unary_stream(_UNARY_STREAM_ASYNC_GEN)
call = unary_stream_call(_REQUEST)
-
+
response_cnt = 0
async for response in call:
response_cnt += 1
self.assertEqual(_RESPONSE, response)
-
+
self.assertEqual(_NUM_STREAM_RESPONSES, response_cnt)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_unary_stream_reader_writer(self):
unary_stream_call = self._channel.unary_stream(
_UNARY_STREAM_READER_WRITER)
call = unary_stream_call(_REQUEST)
-
+
for _ in range(_NUM_STREAM_RESPONSES):
response = await call.read()
self.assertEqual(_RESPONSE, response)
-
+
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_unary_stream_evilly_mixed(self):
unary_stream_call = self._channel.unary_stream(
_UNARY_STREAM_EVILLY_MIXED)
call = unary_stream_call(_REQUEST)
-
+
# Uses reader API
self.assertEqual(_RESPONSE, await call.read())
-
+
# Uses async generator API, mixed!
with self.assertRaises(aio.UsageError):
async for response in call:
self.assertEqual(_RESPONSE, response)
-
+
async def test_stream_unary_async_generator(self):
stream_unary_call = self._channel.stream_unary(_STREAM_UNARY_ASYNC_GEN)
call = stream_unary_call()
-
+
for _ in range(_NUM_STREAM_REQUESTS):
await call.write(_REQUEST)
await call.done_writing()
-
+
response = await call
self.assertEqual(_RESPONSE, response)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_stream_unary_reader_writer(self):
stream_unary_call = self._channel.stream_unary(
_STREAM_UNARY_READER_WRITER)
call = stream_unary_call()
-
+
for _ in range(_NUM_STREAM_REQUESTS):
await call.write(_REQUEST)
await call.done_writing()
-
+
response = await call
self.assertEqual(_RESPONSE, response)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_stream_unary_evilly_mixed(self):
stream_unary_call = self._channel.stream_unary(
_STREAM_UNARY_EVILLY_MIXED)
call = stream_unary_call()
-
+
for _ in range(_NUM_STREAM_REQUESTS):
await call.write(_REQUEST)
await call.done_writing()
-
+
response = await call
self.assertEqual(_RESPONSE, response)
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_stream_stream_async_generator(self):
stream_stream_call = self._channel.stream_stream(
_STREAM_STREAM_ASYNC_GEN)
call = stream_stream_call()
-
+
for _ in range(_NUM_STREAM_REQUESTS):
await call.write(_REQUEST)
await call.done_writing()
-
+
for _ in range(_NUM_STREAM_RESPONSES):
response = await call.read()
self.assertEqual(_RESPONSE, response)
-
+
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_stream_stream_reader_writer(self):
stream_stream_call = self._channel.stream_stream(
_STREAM_STREAM_READER_WRITER)
call = stream_stream_call()
-
+
for _ in range(_NUM_STREAM_REQUESTS):
await call.write(_REQUEST)
await call.done_writing()
-
+
for _ in range(_NUM_STREAM_RESPONSES):
response = await call.read()
self.assertEqual(_RESPONSE, response)
-
+
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_stream_stream_evilly_mixed(self):
stream_stream_call = self._channel.stream_stream(
_STREAM_STREAM_EVILLY_MIXED)
call = stream_stream_call()
-
+
for _ in range(_NUM_STREAM_REQUESTS):
await call.write(_REQUEST)
await call.done_writing()
-
+
for _ in range(_NUM_STREAM_RESPONSES):
response = await call.read()
self.assertEqual(_RESPONSE, response)
-
+
self.assertEqual(await call.code(), grpc.StatusCode.OK)
-
+
async def test_shutdown(self):
await self._server.stop(None)
# Ensures no SIGSEGV triggered, and ends within timeout.
-
+
async def test_shutdown_after_call(self):
await self._channel.unary_unary(_SIMPLE_UNARY_UNARY)(_REQUEST)
-
+
await self._server.stop(None)
async def test_graceful_shutdown_success(self):
@@ -410,24 +410,24 @@ class TestServer(AioTestBase):
async def test_shutdown_before_call(self):
await self._server.stop(None)
-
+
# Ensures the server is cleaned up at this point.
# Some proper exception should be raised.
with self.assertRaises(aio.AioRpcError):
await self._channel.unary_unary(_SIMPLE_UNARY_UNARY)(_REQUEST)
-
+
async def test_unimplemented(self):
call = self._channel.unary_unary(_UNIMPLEMENTED_METHOD)
with self.assertRaises(aio.AioRpcError) as exception_context:
await call(_REQUEST)
rpc_error = exception_context.exception
self.assertEqual(grpc.StatusCode.UNIMPLEMENTED, rpc_error.code())
-
+
async def test_shutdown_during_stream_stream(self):
stream_stream_call = self._channel.stream_stream(
_STREAM_STREAM_ASYNC_GEN)
call = stream_stream_call()
-
+
# Don't half close the RPC yet, keep it alive.
await call.write(_REQUEST)
await self._server.stop(None)
@@ -481,6 +481,6 @@ class TestServer(AioTestBase):
server.add_secure_port(bind_address, server_credentials)
-if __name__ == '__main__':
+if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/ya.make b/contrib/libs/grpc/src/python/grpcio_tests/ya.make
index b0642eae34..f87a6aac0c 100644
--- a/contrib/libs/grpc/src/python/grpcio_tests/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio_tests/ya.make
@@ -1,141 +1,141 @@
-PY3TEST()
-
+PY3TEST()
+
LICENSE(Apache-2.0)
-
+
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
PEERDIR(
contrib/libs/grpc/python
)
-NO_LINT()
-
-PY_SRCS(
- TOP_LEVEL
- # tests/_sanity/__init__.py
- # tests/testing/proto/__init__.py
- # tests/testing/__init__.py
- # tests/testing/_application_common.py
- # tests/testing/_application_testing_common.py
- # tests/testing/_client_application.py
- # tests/testing/_client_test.py
- # tests/testing/_server_application.py
- # tests/testing/_server_test.py
- # tests/testing/_time_test.py
- tests/unit/__init__.py
- tests/unit/_cython/__init__.py
- tests/unit/_cython/_common.py
- tests/unit/_cython/test_utilities.py
- tests/unit/_exit_scenarios.py
- tests/unit/_from_grpc_import_star.py
+NO_LINT()
+
+PY_SRCS(
+ TOP_LEVEL
+ # tests/_sanity/__init__.py
+ # tests/testing/proto/__init__.py
+ # tests/testing/__init__.py
+ # tests/testing/_application_common.py
+ # tests/testing/_application_testing_common.py
+ # tests/testing/_client_application.py
+ # tests/testing/_client_test.py
+ # tests/testing/_server_application.py
+ # tests/testing/_server_test.py
+ # tests/testing/_time_test.py
+ tests/unit/__init__.py
+ tests/unit/_cython/__init__.py
+ tests/unit/_cython/_common.py
+ tests/unit/_cython/test_utilities.py
+ tests/unit/_exit_scenarios.py
+ tests/unit/_from_grpc_import_star.py
tests/unit/_rpc_test_helpers.py
- tests/unit/_server_shutdown_scenarios.py
- tests/unit/_signal_client.py
- tests/unit/_tcp_proxy.py
- tests/unit/beta/__init__.py
- tests/unit/beta/test_utilities.py
- tests/unit/framework/__init__.py
- tests/unit/framework/common/__init__.py
- tests/unit/framework/common/test_constants.py
- tests/unit/framework/common/test_control.py
- tests/unit/framework/common/test_coverage.py
- tests/unit/framework/foundation/__init__.py
- tests/unit/resources.py
- tests/unit/test_common.py
- tests/unit/thread_pool.py
- # protofiles
- # tests/interop/__init__.py
- # tests/interop/_intraop_test_case.py
- # tests/interop/client.py
- # tests/interop/methods.py
- # tests/interop/resources.py
- # tests/interop/server.py
- # tests/interop/service.py
- # protofiles
- # tests/fork/__init__.py
- # tests/fork/client.py
- # tests/fork/methods.py
- # protofiles
- # tests/__init__.py
- # tests/_loader.py
- # tests/_result.py
- # tests/_runner.py
-)
-
-TEST_SRCS(
- # coverage
- # tests/_sanity/_sanity_test.py
- tests/unit/_api_test.py
- tests/unit/_abort_test.py
- # CRASH
- # tests/unit/_auth_context_test.py
- tests/unit/_auth_test.py
- tests/unit/_channel_args_test.py
- tests/unit/_channel_close_test.py
- tests/unit/_channel_connectivity_test.py
- tests/unit/_channel_ready_future_test.py
- # FLAKY
- # tests/unit/_compression_test.py
+ tests/unit/_server_shutdown_scenarios.py
+ tests/unit/_signal_client.py
+ tests/unit/_tcp_proxy.py
+ tests/unit/beta/__init__.py
+ tests/unit/beta/test_utilities.py
+ tests/unit/framework/__init__.py
+ tests/unit/framework/common/__init__.py
+ tests/unit/framework/common/test_constants.py
+ tests/unit/framework/common/test_control.py
+ tests/unit/framework/common/test_coverage.py
+ tests/unit/framework/foundation/__init__.py
+ tests/unit/resources.py
+ tests/unit/test_common.py
+ tests/unit/thread_pool.py
+ # protofiles
+ # tests/interop/__init__.py
+ # tests/interop/_intraop_test_case.py
+ # tests/interop/client.py
+ # tests/interop/methods.py
+ # tests/interop/resources.py
+ # tests/interop/server.py
+ # tests/interop/service.py
+ # protofiles
+ # tests/fork/__init__.py
+ # tests/fork/client.py
+ # tests/fork/methods.py
+ # protofiles
+ # tests/__init__.py
+ # tests/_loader.py
+ # tests/_result.py
+ # tests/_runner.py
+)
+
+TEST_SRCS(
+ # coverage
+ # tests/_sanity/_sanity_test.py
+ tests/unit/_api_test.py
+ tests/unit/_abort_test.py
+ # CRASH
+ # tests/unit/_auth_context_test.py
+ tests/unit/_auth_test.py
+ tests/unit/_channel_args_test.py
+ tests/unit/_channel_close_test.py
+ tests/unit/_channel_connectivity_test.py
+ tests/unit/_channel_ready_future_test.py
+ # FLAKY
+ # tests/unit/_compression_test.py
tests/unit/_contextvars_propagation_test.py
- tests/unit/_credentials_test.py
- tests/unit/_cython/_cancel_many_calls_test.py
- tests/unit/_cython/_channel_test.py
- tests/unit/_cython/_fork_test.py
- tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
- tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
- tests/unit/_cython/_read_some_but_not_all_responses_test.py
- tests/unit/_cython/_server_test.py
- tests/unit/_cython/cygrpc_test.py
- tests/unit/_dns_resolver_test.py
+ tests/unit/_credentials_test.py
+ tests/unit/_cython/_cancel_many_calls_test.py
+ tests/unit/_cython/_channel_test.py
+ tests/unit/_cython/_fork_test.py
+ tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
+ tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
+ tests/unit/_cython/_read_some_but_not_all_responses_test.py
+ tests/unit/_cython/_server_test.py
+ tests/unit/_cython/cygrpc_test.py
+ tests/unit/_dns_resolver_test.py
tests/unit/_dynamic_stubs_test.py
- tests/unit/_empty_message_test.py
- tests/unit/_error_message_encoding_test.py
- tests/unit/_exit_test.py
- tests/unit/_grpc_shutdown_test.py
- tests/unit/_interceptor_test.py
- tests/unit/_invalid_metadata_test.py
- tests/unit/_invocation_defects_test.py
- tests/unit/_local_credentials_test.py
- tests/unit/_logging_test.py
- tests/unit/_metadata_code_details_test.py
- tests/unit/_metadata_flags_test.py
- tests/unit/_metadata_test.py
- tests/unit/_reconnect_test.py
- tests/unit/_resource_exhausted_test.py
+ tests/unit/_empty_message_test.py
+ tests/unit/_error_message_encoding_test.py
+ tests/unit/_exit_test.py
+ tests/unit/_grpc_shutdown_test.py
+ tests/unit/_interceptor_test.py
+ tests/unit/_invalid_metadata_test.py
+ tests/unit/_invocation_defects_test.py
+ tests/unit/_local_credentials_test.py
+ tests/unit/_logging_test.py
+ tests/unit/_metadata_code_details_test.py
+ tests/unit/_metadata_flags_test.py
+ tests/unit/_metadata_test.py
+ tests/unit/_reconnect_test.py
+ tests/unit/_resource_exhausted_test.py
tests/unit/_rpc_part_1_test.py
tests/unit/_rpc_part_2_test.py
- tests/unit/_server_shutdown_test.py
- # tests.testing
- # tests/unit/_server_ssl_cert_config_test.py
- tests/unit/_server_test.py
- tests/unit/_server_wait_for_termination_test.py
- # CRASH
- # tests/unit/_session_cache_test.py
- tests/unit/_signal_handling_test.py
- tests/unit/_version_test.py
- tests/unit/beta/_beta_features_test.py
- tests/unit/beta/_connectivity_channel_test.py
- # oauth2client
- # tests/unit/beta/_implementations_test.py
- tests/unit/beta/_not_found_test.py
- tests/unit/beta/_utilities_test.py
- tests/unit/framework/foundation/_logging_pool_test.py
- tests/unit/framework/foundation/stream_testing.py
- # protofiles
- # tests/interop/_insecure_intraop_test.py
- # tests/interop/_secure_intraop_test.py
- # tests/fork/_fork_interop_test.py
-)
-
-SIZE(MEDIUM)
-
-RESOURCE_FILES(
- PREFIX contrib/libs/grpc/src/python/grpcio_tests/
- tests/unit/credentials/ca.pem
- tests/unit/credentials/server1.key
- tests/unit/credentials/server1.pem
-)
-
-REQUIREMENTS(network:full)
-
-END()
+ tests/unit/_server_shutdown_test.py
+ # tests.testing
+ # tests/unit/_server_ssl_cert_config_test.py
+ tests/unit/_server_test.py
+ tests/unit/_server_wait_for_termination_test.py
+ # CRASH
+ # tests/unit/_session_cache_test.py
+ tests/unit/_signal_handling_test.py
+ tests/unit/_version_test.py
+ tests/unit/beta/_beta_features_test.py
+ tests/unit/beta/_connectivity_channel_test.py
+ # oauth2client
+ # tests/unit/beta/_implementations_test.py
+ tests/unit/beta/_not_found_test.py
+ tests/unit/beta/_utilities_test.py
+ tests/unit/framework/foundation/_logging_pool_test.py
+ tests/unit/framework/foundation/stream_testing.py
+ # protofiles
+ # tests/interop/_insecure_intraop_test.py
+ # tests/interop/_secure_intraop_test.py
+ # tests/fork/_fork_interop_test.py
+)
+
+SIZE(MEDIUM)
+
+RESOURCE_FILES(
+ PREFIX contrib/libs/grpc/src/python/grpcio_tests/
+ tests/unit/credentials/ca.pem
+ tests/unit/credentials/server1.key
+ tests/unit/credentials/server1.pem
+)
+
+REQUIREMENTS(network:full)
+
+END()
diff --git a/contrib/libs/grpc/test/core/util/cmdline.cc b/contrib/libs/grpc/test/core/util/cmdline.cc
index 62b47f927a..55d801ec7d 100644
--- a/contrib/libs/grpc/test/core/util/cmdline.cc
+++ b/contrib/libs/grpc/test/core/util/cmdline.cc
@@ -1,319 +1,319 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/cmdline.h"
-
-#include <limits.h>
-#include <stdio.h>
-#include <string.h>
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/cmdline.h"
+
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
#include <vector>
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include "src/core/lib/gpr/string.h"
-
-typedef enum { ARGTYPE_INT, ARGTYPE_BOOL, ARGTYPE_STRING } argtype;
-
-typedef struct arg {
- const char* name;
- const char* help;
- argtype type;
- void* value;
- struct arg* next;
-} arg;
-
-struct gpr_cmdline {
- const char* description;
- arg* args;
- const char* argv0;
-
- const char* extra_arg_name;
- const char* extra_arg_help;
- void (*extra_arg)(void* user_data, const char* arg);
- void* extra_arg_user_data;
-
- int (*state)(gpr_cmdline* cl, char* arg);
- arg* cur_arg;
-
- int survive_failure;
-};
-
-static int normal_state(gpr_cmdline* cl, char* arg);
-
-gpr_cmdline* gpr_cmdline_create(const char* description) {
- gpr_cmdline* cl = static_cast<gpr_cmdline*>(gpr_zalloc(sizeof(gpr_cmdline)));
-
- cl->description = description;
- cl->state = normal_state;
-
- return cl;
-}
-
-void gpr_cmdline_set_survive_failure(gpr_cmdline* cl) {
- cl->survive_failure = 1;
-}
-
-void gpr_cmdline_destroy(gpr_cmdline* cl) {
- while (cl->args) {
- arg* a = cl->args;
- cl->args = a->next;
- gpr_free(a);
- }
- gpr_free(cl);
-}
-
-static void add_arg(gpr_cmdline* cl, const char* name, const char* help,
- argtype type, void* value) {
- arg* a;
-
- for (a = cl->args; a; a = a->next) {
- GPR_ASSERT(0 != strcmp(a->name, name));
- }
-
- a = static_cast<arg*>(gpr_zalloc(sizeof(arg)));
- a->name = name;
- a->help = help;
- a->type = type;
- a->value = value;
- a->next = cl->args;
- cl->args = a;
-}
-
-void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help,
- int* value) {
- add_arg(cl, name, help, ARGTYPE_INT, value);
-}
-
-void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help,
- int* value) {
- add_arg(cl, name, help, ARGTYPE_BOOL, value);
-}
-
-void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help,
- const char** value) {
- add_arg(cl, name, help, ARGTYPE_STRING, value);
-}
-
-void gpr_cmdline_on_extra_arg(
- gpr_cmdline* cl, const char* name, const char* help,
- void (*on_extra_arg)(void* user_data, const char* arg), void* user_data) {
- GPR_ASSERT(!cl->extra_arg);
- GPR_ASSERT(on_extra_arg);
-
- cl->extra_arg = on_extra_arg;
- cl->extra_arg_user_data = user_data;
- cl->extra_arg_name = name;
- cl->extra_arg_help = help;
-}
-
-/* recursively descend argument list, adding the last element
- to s first - so that arguments are added in the order they were
- added to the list by api calls */
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/gpr/string.h"
+
+typedef enum { ARGTYPE_INT, ARGTYPE_BOOL, ARGTYPE_STRING } argtype;
+
+typedef struct arg {
+ const char* name;
+ const char* help;
+ argtype type;
+ void* value;
+ struct arg* next;
+} arg;
+
+struct gpr_cmdline {
+ const char* description;
+ arg* args;
+ const char* argv0;
+
+ const char* extra_arg_name;
+ const char* extra_arg_help;
+ void (*extra_arg)(void* user_data, const char* arg);
+ void* extra_arg_user_data;
+
+ int (*state)(gpr_cmdline* cl, char* arg);
+ arg* cur_arg;
+
+ int survive_failure;
+};
+
+static int normal_state(gpr_cmdline* cl, char* arg);
+
+gpr_cmdline* gpr_cmdline_create(const char* description) {
+ gpr_cmdline* cl = static_cast<gpr_cmdline*>(gpr_zalloc(sizeof(gpr_cmdline)));
+
+ cl->description = description;
+ cl->state = normal_state;
+
+ return cl;
+}
+
+void gpr_cmdline_set_survive_failure(gpr_cmdline* cl) {
+ cl->survive_failure = 1;
+}
+
+void gpr_cmdline_destroy(gpr_cmdline* cl) {
+ while (cl->args) {
+ arg* a = cl->args;
+ cl->args = a->next;
+ gpr_free(a);
+ }
+ gpr_free(cl);
+}
+
+static void add_arg(gpr_cmdline* cl, const char* name, const char* help,
+ argtype type, void* value) {
+ arg* a;
+
+ for (a = cl->args; a; a = a->next) {
+ GPR_ASSERT(0 != strcmp(a->name, name));
+ }
+
+ a = static_cast<arg*>(gpr_zalloc(sizeof(arg)));
+ a->name = name;
+ a->help = help;
+ a->type = type;
+ a->value = value;
+ a->next = cl->args;
+ cl->args = a;
+}
+
+void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help,
+ int* value) {
+ add_arg(cl, name, help, ARGTYPE_INT, value);
+}
+
+void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help,
+ int* value) {
+ add_arg(cl, name, help, ARGTYPE_BOOL, value);
+}
+
+void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help,
+ const char** value) {
+ add_arg(cl, name, help, ARGTYPE_STRING, value);
+}
+
+void gpr_cmdline_on_extra_arg(
+ gpr_cmdline* cl, const char* name, const char* help,
+ void (*on_extra_arg)(void* user_data, const char* arg), void* user_data) {
+ GPR_ASSERT(!cl->extra_arg);
+ GPR_ASSERT(on_extra_arg);
+
+ cl->extra_arg = on_extra_arg;
+ cl->extra_arg_user_data = user_data;
+ cl->extra_arg_name = name;
+ cl->extra_arg_help = help;
+}
+
+/* recursively descend argument list, adding the last element
+ to s first - so that arguments are added in the order they were
+ added to the list by api calls */
static void add_args_to_usage(arg* a, std::vector<TString>* s) {
if (a == nullptr) return;
add_args_to_usage(a->next, s);
- switch (a->type) {
- case ARGTYPE_BOOL:
+ switch (a->type) {
+ case ARGTYPE_BOOL:
s->push_back(y_absl::StrFormat(" [--%s|--no-%s]", a->name, a->name));
- break;
- case ARGTYPE_STRING:
+ break;
+ case ARGTYPE_STRING:
s->push_back(y_absl::StrFormat(" [--%s=string]", a->name));
- break;
- case ARGTYPE_INT:
+ break;
+ case ARGTYPE_INT:
s->push_back(y_absl::StrFormat(" [--%s=int]", a->name));
- break;
- }
-}
-
+ break;
+ }
+}
+
TString gpr_cmdline_usage_string(gpr_cmdline* cl, const char* argv0) {
- const char* name = strrchr(argv0, '/');
+ const char* name = strrchr(argv0, '/');
if (name != nullptr) {
- name++;
- } else {
- name = argv0;
- }
-
+ name++;
+ } else {
+ name = argv0;
+ }
+
std::vector<TString> s;
s.push_back(y_absl::StrCat("Usage: ", name));
add_args_to_usage(cl->args, &s);
- if (cl->extra_arg) {
+ if (cl->extra_arg) {
s.push_back(y_absl::StrFormat(" [%s...]", cl->extra_arg_name));
- }
+ }
s.push_back("\n");
return y_absl::StrJoin(s, "");
-}
-
-static int print_usage_and_die(gpr_cmdline* cl) {
+}
+
+static int print_usage_and_die(gpr_cmdline* cl) {
fprintf(stderr, "%s", gpr_cmdline_usage_string(cl, cl->argv0).c_str());
- if (!cl->survive_failure) {
- exit(1);
- }
- return 0;
-}
-
-static int extra_state(gpr_cmdline* cl, char* str) {
- if (!cl->extra_arg) {
- return print_usage_and_die(cl);
- }
- cl->extra_arg(cl->extra_arg_user_data, str);
- return 1;
-}
-
-static arg* find_arg(gpr_cmdline* cl, char* name) {
- arg* a;
-
- for (a = cl->args; a; a = a->next) {
- if (0 == strcmp(a->name, name)) {
- break;
- }
- }
-
- if (!a) {
- fprintf(stderr, "Unknown argument: %s\n", name);
- return nullptr;
- }
-
- return a;
-}
-
-static int value_state(gpr_cmdline* cl, char* str) {
- long intval;
- char* end;
-
- GPR_ASSERT(cl->cur_arg);
-
- switch (cl->cur_arg->type) {
- case ARGTYPE_INT:
- intval = strtol(str, &end, 0);
- if (*end || intval < INT_MIN || intval > INT_MAX) {
- fprintf(stderr, "expected integer, got '%s' for %s\n", str,
- cl->cur_arg->name);
- return print_usage_and_die(cl);
- }
- *static_cast<int*>(cl->cur_arg->value) = static_cast<int>(intval);
- break;
- case ARGTYPE_BOOL:
- if (0 == strcmp(str, "1") || 0 == strcmp(str, "true")) {
- *static_cast<int*>(cl->cur_arg->value) = 1;
- } else if (0 == strcmp(str, "0") || 0 == strcmp(str, "false")) {
- *static_cast<int*>(cl->cur_arg->value) = 0;
- } else {
- fprintf(stderr, "expected boolean, got '%s' for %s\n", str,
- cl->cur_arg->name);
- return print_usage_and_die(cl);
- }
- break;
- case ARGTYPE_STRING:
- *static_cast<char**>(cl->cur_arg->value) = str;
- break;
- }
-
- cl->state = normal_state;
- return 1;
-}
-
-static int normal_state(gpr_cmdline* cl, char* str) {
- char* eq = nullptr;
- char* tmp = nullptr;
- char* arg_name = nullptr;
- int r = 1;
-
- if (0 == strcmp(str, "-help") || 0 == strcmp(str, "--help") ||
- 0 == strcmp(str, "-h")) {
- return print_usage_and_die(cl);
- }
-
- cl->cur_arg = nullptr;
-
- if (str[0] == '-') {
- if (str[1] == '-') {
- if (str[2] == 0) {
- /* handle '--' to move to just extra args */
- cl->state = extra_state;
- return 1;
- }
- str += 2;
- } else {
- str += 1;
- }
- /* first byte of str is now past the leading '-' or '--' */
- if (str[0] == 'n' && str[1] == 'o' && str[2] == '-') {
- /* str is of the form '--no-foo' - it's a flag disable */
- str += 3;
- cl->cur_arg = find_arg(cl, str);
- if (cl->cur_arg == nullptr) {
- return print_usage_and_die(cl);
- }
- if (cl->cur_arg->type != ARGTYPE_BOOL) {
- fprintf(stderr, "%s is not a flag argument\n", str);
- return print_usage_and_die(cl);
- }
- *static_cast<int*>(cl->cur_arg->value) = 0;
- return 1; /* early out */
- }
- eq = strchr(str, '=');
- if (eq != nullptr) {
- /* copy the string into a temp buffer and extract the name */
- tmp = arg_name =
- static_cast<char*>(gpr_malloc(static_cast<size_t>(eq - str + 1)));
- memcpy(arg_name, str, static_cast<size_t>(eq - str));
- arg_name[eq - str] = 0;
- } else {
- arg_name = str;
- }
- cl->cur_arg = find_arg(cl, arg_name);
- if (cl->cur_arg == nullptr) {
- return print_usage_and_die(cl);
- }
- if (eq != nullptr) {
- /* str was of the type --foo=value, parse the value */
- r = value_state(cl, eq + 1);
- } else if (cl->cur_arg->type != ARGTYPE_BOOL) {
- /* flag types don't have a '--foo value' variant, other types do */
- cl->state = value_state;
- } else {
- /* flag parameter: just set the value */
- *static_cast<int*>(cl->cur_arg->value) = 1;
- }
- } else {
- r = extra_state(cl, str);
- }
-
- gpr_free(tmp);
- return r;
-}
-
-int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv) {
- int i;
-
- GPR_ASSERT(argc >= 1);
- cl->argv0 = argv[0];
-
- for (i = 1; i < argc; i++) {
- if (!cl->state(cl, argv[i])) {
- return 0;
- }
- }
- return 1;
-}
+ if (!cl->survive_failure) {
+ exit(1);
+ }
+ return 0;
+}
+
+static int extra_state(gpr_cmdline* cl, char* str) {
+ if (!cl->extra_arg) {
+ return print_usage_and_die(cl);
+ }
+ cl->extra_arg(cl->extra_arg_user_data, str);
+ return 1;
+}
+
+static arg* find_arg(gpr_cmdline* cl, char* name) {
+ arg* a;
+
+ for (a = cl->args; a; a = a->next) {
+ if (0 == strcmp(a->name, name)) {
+ break;
+ }
+ }
+
+ if (!a) {
+ fprintf(stderr, "Unknown argument: %s\n", name);
+ return nullptr;
+ }
+
+ return a;
+}
+
+static int value_state(gpr_cmdline* cl, char* str) {
+ long intval;
+ char* end;
+
+ GPR_ASSERT(cl->cur_arg);
+
+ switch (cl->cur_arg->type) {
+ case ARGTYPE_INT:
+ intval = strtol(str, &end, 0);
+ if (*end || intval < INT_MIN || intval > INT_MAX) {
+ fprintf(stderr, "expected integer, got '%s' for %s\n", str,
+ cl->cur_arg->name);
+ return print_usage_and_die(cl);
+ }
+ *static_cast<int*>(cl->cur_arg->value) = static_cast<int>(intval);
+ break;
+ case ARGTYPE_BOOL:
+ if (0 == strcmp(str, "1") || 0 == strcmp(str, "true")) {
+ *static_cast<int*>(cl->cur_arg->value) = 1;
+ } else if (0 == strcmp(str, "0") || 0 == strcmp(str, "false")) {
+ *static_cast<int*>(cl->cur_arg->value) = 0;
+ } else {
+ fprintf(stderr, "expected boolean, got '%s' for %s\n", str,
+ cl->cur_arg->name);
+ return print_usage_and_die(cl);
+ }
+ break;
+ case ARGTYPE_STRING:
+ *static_cast<char**>(cl->cur_arg->value) = str;
+ break;
+ }
+
+ cl->state = normal_state;
+ return 1;
+}
+
+static int normal_state(gpr_cmdline* cl, char* str) {
+ char* eq = nullptr;
+ char* tmp = nullptr;
+ char* arg_name = nullptr;
+ int r = 1;
+
+ if (0 == strcmp(str, "-help") || 0 == strcmp(str, "--help") ||
+ 0 == strcmp(str, "-h")) {
+ return print_usage_and_die(cl);
+ }
+
+ cl->cur_arg = nullptr;
+
+ if (str[0] == '-') {
+ if (str[1] == '-') {
+ if (str[2] == 0) {
+ /* handle '--' to move to just extra args */
+ cl->state = extra_state;
+ return 1;
+ }
+ str += 2;
+ } else {
+ str += 1;
+ }
+ /* first byte of str is now past the leading '-' or '--' */
+ if (str[0] == 'n' && str[1] == 'o' && str[2] == '-') {
+ /* str is of the form '--no-foo' - it's a flag disable */
+ str += 3;
+ cl->cur_arg = find_arg(cl, str);
+ if (cl->cur_arg == nullptr) {
+ return print_usage_and_die(cl);
+ }
+ if (cl->cur_arg->type != ARGTYPE_BOOL) {
+ fprintf(stderr, "%s is not a flag argument\n", str);
+ return print_usage_and_die(cl);
+ }
+ *static_cast<int*>(cl->cur_arg->value) = 0;
+ return 1; /* early out */
+ }
+ eq = strchr(str, '=');
+ if (eq != nullptr) {
+ /* copy the string into a temp buffer and extract the name */
+ tmp = arg_name =
+ static_cast<char*>(gpr_malloc(static_cast<size_t>(eq - str + 1)));
+ memcpy(arg_name, str, static_cast<size_t>(eq - str));
+ arg_name[eq - str] = 0;
+ } else {
+ arg_name = str;
+ }
+ cl->cur_arg = find_arg(cl, arg_name);
+ if (cl->cur_arg == nullptr) {
+ return print_usage_and_die(cl);
+ }
+ if (eq != nullptr) {
+ /* str was of the type --foo=value, parse the value */
+ r = value_state(cl, eq + 1);
+ } else if (cl->cur_arg->type != ARGTYPE_BOOL) {
+ /* flag types don't have a '--foo value' variant, other types do */
+ cl->state = value_state;
+ } else {
+ /* flag parameter: just set the value */
+ *static_cast<int*>(cl->cur_arg->value) = 1;
+ }
+ } else {
+ r = extra_state(cl, str);
+ }
+
+ gpr_free(tmp);
+ return r;
+}
+
+int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv) {
+ int i;
+
+ GPR_ASSERT(argc >= 1);
+ cl->argv0 = argv[0];
+
+ for (i = 1; i < argc; i++) {
+ if (!cl->state(cl, argv[i])) {
+ return 0;
+ }
+ }
+ return 1;
+}
diff --git a/contrib/libs/grpc/test/core/util/cmdline.h b/contrib/libs/grpc/test/core/util/cmdline.h
index cc75a8974e..6a06bbfe43 100644
--- a/contrib/libs/grpc/test/core/util/cmdline.h
+++ b/contrib/libs/grpc/test/core/util/cmdline.h
@@ -1,82 +1,82 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_CMDLINE_H
-#define GRPC_TEST_CORE_UTIL_CMDLINE_H
-
-#include <grpc/support/port_platform.h>
-
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_CMDLINE_H
+#define GRPC_TEST_CORE_UTIL_CMDLINE_H
+
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
-/** Simple command line parser.
-
- Supports flags that can be specified as -foo, --foo, --no-foo, -no-foo, etc
- And integers, strings that can be specified as -foo=4, -foo blah, etc
-
- No support for short command line options (but we may get that in the
- future.)
-
- Usage (for a program with a single flag argument 'foo'):
-
- int main(int argc, char **argv) {
- gpr_cmdline *cl;
- int verbose = 0;
-
- cl = gpr_cmdline_create("My cool tool");
- gpr_cmdline_add_int(cl, "verbose", "Produce verbose output?", &verbose);
- gpr_cmdline_parse(cl, argc, argv);
- gpr_cmdline_destroy(cl);
-
- if (verbose) {
- gpr_log(GPR_INFO, "Goodbye cruel world!");
- }
-
- return 0;
- } */
-
-typedef struct gpr_cmdline gpr_cmdline;
-
-/** Construct a command line parser: takes a short description of the tool
- doing the parsing */
-gpr_cmdline* gpr_cmdline_create(const char* description);
-/** Add an integer parameter, with a name (used on the command line) and some
- helpful text (used in the command usage) */
-void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help,
- int* value);
-/** The same, for a boolean flag */
-void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help,
- int* value);
-/** And for a string */
-void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help,
- const char** value);
-/** Set a callback for non-named arguments */
-void gpr_cmdline_on_extra_arg(
- gpr_cmdline* cl, const char* name, const char* help,
- void (*on_extra_arg)(void* user_data, const char* arg), void* user_data);
-/** Enable surviving failure: default behavior is to exit the process */
-void gpr_cmdline_set_survive_failure(gpr_cmdline* cl);
-/** Parse the command line; returns 1 on success, on failure either dies
- (by default) or returns 0 if gpr_cmdline_set_survive_failure() has been
- called */
-int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv);
-/** Destroy the parser */
-void gpr_cmdline_destroy(gpr_cmdline* cl);
-/** Get a string describing usage */
+/** Simple command line parser.
+
+ Supports flags that can be specified as -foo, --foo, --no-foo, -no-foo, etc
+ And integers, strings that can be specified as -foo=4, -foo blah, etc
+
+ No support for short command line options (but we may get that in the
+ future.)
+
+ Usage (for a program with a single flag argument 'foo'):
+
+ int main(int argc, char **argv) {
+ gpr_cmdline *cl;
+ int verbose = 0;
+
+ cl = gpr_cmdline_create("My cool tool");
+ gpr_cmdline_add_int(cl, "verbose", "Produce verbose output?", &verbose);
+ gpr_cmdline_parse(cl, argc, argv);
+ gpr_cmdline_destroy(cl);
+
+ if (verbose) {
+ gpr_log(GPR_INFO, "Goodbye cruel world!");
+ }
+
+ return 0;
+ } */
+
+typedef struct gpr_cmdline gpr_cmdline;
+
+/** Construct a command line parser: takes a short description of the tool
+ doing the parsing */
+gpr_cmdline* gpr_cmdline_create(const char* description);
+/** Add an integer parameter, with a name (used on the command line) and some
+ helpful text (used in the command usage) */
+void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help,
+ int* value);
+/** The same, for a boolean flag */
+void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help,
+ int* value);
+/** And for a string */
+void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help,
+ const char** value);
+/** Set a callback for non-named arguments */
+void gpr_cmdline_on_extra_arg(
+ gpr_cmdline* cl, const char* name, const char* help,
+ void (*on_extra_arg)(void* user_data, const char* arg), void* user_data);
+/** Enable surviving failure: default behavior is to exit the process */
+void gpr_cmdline_set_survive_failure(gpr_cmdline* cl);
+/** Parse the command line; returns 1 on success, on failure either dies
+ (by default) or returns 0 if gpr_cmdline_set_survive_failure() has been
+ called */
+int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv);
+/** Destroy the parser */
+void gpr_cmdline_destroy(gpr_cmdline* cl);
+/** Get a string describing usage */
TString gpr_cmdline_usage_string(gpr_cmdline* cl, const char* argv0);
-
-#endif /* GRPC_TEST_CORE_UTIL_CMDLINE_H */
+
+#endif /* GRPC_TEST_CORE_UTIL_CMDLINE_H */
diff --git a/contrib/libs/grpc/test/core/util/cmdline_test.cc b/contrib/libs/grpc/test/core/util/cmdline_test.cc
index b1b7da6b17..10628d18f0 100644
--- a/contrib/libs/grpc/test/core/util/cmdline_test.cc
+++ b/contrib/libs/grpc/test/core/util/cmdline_test.cc
@@ -1,488 +1,488 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "test/core/util/cmdline.h"
-#include "test/core/util/test_config.h"
-
-#define LOG_TEST() gpr_log(GPR_INFO, "test at %s:%d", __FILE__, __LINE__)
-
-static void test_simple_int(void) {
- int x = 1;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"),
- const_cast<char*>("3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_int(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 1);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 3);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_eq_int(void) {
- int x = 1;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_int(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 1);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 3);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_2dash_int(void) {
- int x = 1;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"),
- const_cast<char*>("3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_int(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 1);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 3);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_2dash_eq_int(void) {
- int x = 1;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_int(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 1);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 3);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_simple_string(void) {
- const char* x = nullptr;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"),
- const_cast<char*>("3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_string(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == nullptr);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(0 == strcmp(x, "3"));
- gpr_cmdline_destroy(cl);
-}
-
-static void test_eq_string(void) {
- const char* x = nullptr;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_string(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == nullptr);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(0 == strcmp(x, "3"));
- gpr_cmdline_destroy(cl);
-}
-
-static void test_2dash_string(void) {
- const char* x = nullptr;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"),
- const_cast<char*>("3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_string(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == nullptr);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(0 == strcmp(x, "3"));
- gpr_cmdline_destroy(cl);
-}
-
-static void test_2dash_eq_string(void) {
- const char* x = nullptr;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_string(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == nullptr);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(0 == strcmp(x, "3"));
- gpr_cmdline_destroy(cl);
-}
-
-static void test_flag_on(void) {
- int x = 2;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 2);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 1);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_flag_no(void) {
- int x = 2;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--no-foo")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 2);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 0);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_flag_val_1(void) {
- int x = 2;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=1")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 2);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 1);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_flag_val_0(void) {
- int x = 2;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=0")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 2);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 0);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_flag_val_true(void) {
- int x = 2;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=true")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 2);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 1);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_flag_val_false(void) {
- int x = 2;
- gpr_cmdline* cl;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=false")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
- GPR_ASSERT(x == 2);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 0);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_many(void) {
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
- gpr_cmdline* cl;
-
- char* args[] = {(char*)__FILE__, const_cast<char*>("--str"),
- const_cast<char*>("hello"), const_cast<char*>("-x=4"),
- const_cast<char*>("-no-flag")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(x == 4);
- GPR_ASSERT(0 == strcmp(str, "hello"));
- GPR_ASSERT(flag == 0);
- gpr_cmdline_destroy(cl);
-}
-
-static void extra_arg_cb(void* user_data, const char* arg) {
- int* count = static_cast<int*>(user_data);
- GPR_ASSERT(arg != nullptr);
- GPR_ASSERT(strlen(arg) == 1);
- GPR_ASSERT(arg[0] == 'a' + *count);
- ++*count;
-}
-
-static void test_extra(void) {
- gpr_cmdline* cl;
- int count = 0;
- char* args[] = {(char*)__FILE__, const_cast<char*>("a"),
- const_cast<char*>("b"), const_cast<char*>("c")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- &count);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(count == 3);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_extra_dashdash(void) {
- gpr_cmdline* cl;
- int count = 0;
- char* args[] = {(char*)__FILE__, const_cast<char*>("--"),
- const_cast<char*>("a"), const_cast<char*>("b"),
- const_cast<char*>("c")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- &count);
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
- GPR_ASSERT(count == 3);
- gpr_cmdline_destroy(cl);
-}
-
-static void test_usage(void) {
- gpr_cmdline* cl;
-
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- nullptr);
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "test/core/util/cmdline.h"
+#include "test/core/util/test_config.h"
+
+#define LOG_TEST() gpr_log(GPR_INFO, "test at %s:%d", __FILE__, __LINE__)
+
+static void test_simple_int(void) {
+ int x = 1;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"),
+ const_cast<char*>("3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_int(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 3);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_eq_int(void) {
+ int x = 1;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_int(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 3);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_2dash_int(void) {
+ int x = 1;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"),
+ const_cast<char*>("3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_int(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 3);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_2dash_eq_int(void) {
+ int x = 1;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_int(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 3);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_simple_string(void) {
+ const char* x = nullptr;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"),
+ const_cast<char*>("3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_string(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == nullptr);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(0 == strcmp(x, "3"));
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_eq_string(void) {
+ const char* x = nullptr;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_string(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == nullptr);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(0 == strcmp(x, "3"));
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_2dash_string(void) {
+ const char* x = nullptr;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"),
+ const_cast<char*>("3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_string(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == nullptr);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(0 == strcmp(x, "3"));
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_2dash_eq_string(void) {
+ const char* x = nullptr;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_string(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == nullptr);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(0 == strcmp(x, "3"));
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_flag_on(void) {
+ int x = 2;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 2);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_flag_no(void) {
+ int x = 2;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--no-foo")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 2);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 0);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_flag_val_1(void) {
+ int x = 2;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=1")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 2);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_flag_val_0(void) {
+ int x = 2;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=0")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 2);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 0);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_flag_val_true(void) {
+ int x = 2;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=true")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 2);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 1);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_flag_val_false(void) {
+ int x = 2;
+ gpr_cmdline* cl;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=false")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_flag(cl, "foo", nullptr, &x);
+ GPR_ASSERT(x == 2);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 0);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_many(void) {
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+ gpr_cmdline* cl;
+
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--str"),
+ const_cast<char*>("hello"), const_cast<char*>("-x=4"),
+ const_cast<char*>("-no-flag")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(x == 4);
+ GPR_ASSERT(0 == strcmp(str, "hello"));
+ GPR_ASSERT(flag == 0);
+ gpr_cmdline_destroy(cl);
+}
+
+static void extra_arg_cb(void* user_data, const char* arg) {
+ int* count = static_cast<int*>(user_data);
+ GPR_ASSERT(arg != nullptr);
+ GPR_ASSERT(strlen(arg) == 1);
+ GPR_ASSERT(arg[0] == 'a' + *count);
+ ++*count;
+}
+
+static void test_extra(void) {
+ gpr_cmdline* cl;
+ int count = 0;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("a"),
+ const_cast<char*>("b"), const_cast<char*>("c")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ &count);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(count == 3);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_extra_dashdash(void) {
+ gpr_cmdline* cl;
+ int count = 0;
+ char* args[] = {(char*)__FILE__, const_cast<char*>("--"),
+ const_cast<char*>("a"), const_cast<char*>("b"),
+ const_cast<char*>("c")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ &count);
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args);
+ GPR_ASSERT(count == 3);
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_usage(void) {
+ gpr_cmdline* cl;
+
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ nullptr);
+
TString usage = gpr_cmdline_usage_string(cl, "test");
GPR_ASSERT(usage ==
"Usage: test [--str=string] [--x=int] "
"[--flag|--no-flag] [file...]\n");
-
- usage = gpr_cmdline_usage_string(cl, "/foo/test");
+
+ usage = gpr_cmdline_usage_string(cl, "/foo/test");
GPR_ASSERT(usage ==
"Usage: test [--str=string] [--x=int] "
"[--flag|--no-flag] [file...]\n");
-
- gpr_cmdline_destroy(cl);
-}
-
-static void test_help(void) {
- gpr_cmdline* cl;
-
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
-
- char* help[] = {(char*)__FILE__, const_cast<char*>("-h")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_set_survive_failure(cl);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- nullptr);
-
- GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(help), help));
-
- gpr_cmdline_destroy(cl);
-}
-
-static void test_badargs1(void) {
- gpr_cmdline* cl;
-
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
-
- char* bad_arg_name[] = {(char*)__FILE__, const_cast<char*>("--y")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_set_survive_failure(cl);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- nullptr);
-
- GPR_ASSERT(0 ==
- gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_arg_name), bad_arg_name));
-
- gpr_cmdline_destroy(cl);
-}
-
-static void test_badargs2(void) {
- gpr_cmdline* cl;
-
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
-
- char* bad_int_value[] = {(char*)__FILE__, const_cast<char*>("--x"),
- const_cast<char*>("henry")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_set_survive_failure(cl);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- nullptr);
-
- GPR_ASSERT(
- 0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_int_value), bad_int_value));
-
- gpr_cmdline_destroy(cl);
-}
-
-static void test_badargs3(void) {
- gpr_cmdline* cl;
-
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
-
- char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--flag=henry")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_set_survive_failure(cl);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- nullptr);
-
- GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value),
- bad_bool_value));
-
- gpr_cmdline_destroy(cl);
-}
-
-static void test_badargs4(void) {
- gpr_cmdline* cl;
-
- const char* str = nullptr;
- int x = 0;
- int flag = 2;
-
- char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--no-str")};
-
- LOG_TEST();
-
- cl = gpr_cmdline_create(nullptr);
- gpr_cmdline_set_survive_failure(cl);
- gpr_cmdline_add_string(cl, "str", nullptr, &str);
- gpr_cmdline_add_int(cl, "x", nullptr, &x);
- gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
- gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
- nullptr);
-
- GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value),
- bad_bool_value));
-
- gpr_cmdline_destroy(cl);
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- test_simple_int();
- test_eq_int();
- test_2dash_int();
- test_2dash_eq_int();
- test_simple_string();
- test_eq_string();
- test_2dash_string();
- test_2dash_eq_string();
- test_flag_on();
- test_flag_no();
- test_flag_val_1();
- test_flag_val_0();
- test_flag_val_true();
- test_flag_val_false();
- test_many();
- test_extra();
- test_extra_dashdash();
- test_usage();
- test_help();
- test_badargs1();
- test_badargs2();
- test_badargs3();
- test_badargs4();
- return 0;
-}
+
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_help(void) {
+ gpr_cmdline* cl;
+
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+
+ char* help[] = {(char*)__FILE__, const_cast<char*>("-h")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_set_survive_failure(cl);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ nullptr);
+
+ GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(help), help));
+
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_badargs1(void) {
+ gpr_cmdline* cl;
+
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+
+ char* bad_arg_name[] = {(char*)__FILE__, const_cast<char*>("--y")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_set_survive_failure(cl);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ nullptr);
+
+ GPR_ASSERT(0 ==
+ gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_arg_name), bad_arg_name));
+
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_badargs2(void) {
+ gpr_cmdline* cl;
+
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+
+ char* bad_int_value[] = {(char*)__FILE__, const_cast<char*>("--x"),
+ const_cast<char*>("henry")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_set_survive_failure(cl);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ nullptr);
+
+ GPR_ASSERT(
+ 0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_int_value), bad_int_value));
+
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_badargs3(void) {
+ gpr_cmdline* cl;
+
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+
+ char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--flag=henry")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_set_survive_failure(cl);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ nullptr);
+
+ GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value),
+ bad_bool_value));
+
+ gpr_cmdline_destroy(cl);
+}
+
+static void test_badargs4(void) {
+ gpr_cmdline* cl;
+
+ const char* str = nullptr;
+ int x = 0;
+ int flag = 2;
+
+ char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--no-str")};
+
+ LOG_TEST();
+
+ cl = gpr_cmdline_create(nullptr);
+ gpr_cmdline_set_survive_failure(cl);
+ gpr_cmdline_add_string(cl, "str", nullptr, &str);
+ gpr_cmdline_add_int(cl, "x", nullptr, &x);
+ gpr_cmdline_add_flag(cl, "flag", nullptr, &flag);
+ gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb,
+ nullptr);
+
+ GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value),
+ bad_bool_value));
+
+ gpr_cmdline_destroy(cl);
+}
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ test_simple_int();
+ test_eq_int();
+ test_2dash_int();
+ test_2dash_eq_int();
+ test_simple_string();
+ test_eq_string();
+ test_2dash_string();
+ test_2dash_eq_string();
+ test_flag_on();
+ test_flag_no();
+ test_flag_val_1();
+ test_flag_val_0();
+ test_flag_val_true();
+ test_flag_val_false();
+ test_many();
+ test_extra();
+ test_extra_dashdash();
+ test_usage();
+ test_help();
+ test_badargs1();
+ test_badargs2();
+ test_badargs3();
+ test_badargs4();
+ return 0;
+}
diff --git a/contrib/libs/grpc/test/core/util/debugger_macros.cc b/contrib/libs/grpc/test/core/util/debugger_macros.cc
index fde68f3217..b866cfd647 100644
--- a/contrib/libs/grpc/test/core/util/debugger_macros.cc
+++ b/contrib/libs/grpc/test/core/util/debugger_macros.cc
@@ -1,57 +1,57 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-/*
- * A collection of 'macros' that help navigating the grpc object hierarchy
- * Not intended to be robust for main-line code, often cuts across abstraction
- * boundaries.
- */
-#include <stdio.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-#include "src/core/lib/channel/connected_channel.h"
-#include "src/core/lib/surface/call.h"
-
-grpc_stream* grpc_transport_stream_from_call(grpc_call* call) {
- grpc_call_stack* cs = grpc_call_get_call_stack(call);
- for (;;) {
- grpc_call_element* el = grpc_call_stack_element(cs, cs->count - 1);
- if (el->filter == &grpc_client_channel_filter) {
- grpc_core::RefCountedPtr<grpc_core::SubchannelCall> scc =
- grpc_client_channel_get_subchannel_call(el);
- if (scc == nullptr) {
- fprintf(stderr, "No subchannel-call");
- fflush(stderr);
- return nullptr;
- }
- cs = scc->GetCallStack();
- } else if (el->filter == &grpc_connected_filter) {
- return grpc_connected_channel_get_stream(el);
- } else {
- fprintf(stderr, "Unrecognized filter: %s", el->filter->name);
- fflush(stderr);
- return nullptr;
- }
- }
-}
-
-grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call) {
- return reinterpret_cast<grpc_chttp2_stream*>(
- grpc_transport_stream_from_call(call));
-}
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+/*
+ * A collection of 'macros' that help navigating the grpc object hierarchy
+ * Not intended to be robust for main-line code, often cuts across abstraction
+ * boundaries.
+ */
+#include <stdio.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+#include "src/core/lib/channel/connected_channel.h"
+#include "src/core/lib/surface/call.h"
+
+grpc_stream* grpc_transport_stream_from_call(grpc_call* call) {
+ grpc_call_stack* cs = grpc_call_get_call_stack(call);
+ for (;;) {
+ grpc_call_element* el = grpc_call_stack_element(cs, cs->count - 1);
+ if (el->filter == &grpc_client_channel_filter) {
+ grpc_core::RefCountedPtr<grpc_core::SubchannelCall> scc =
+ grpc_client_channel_get_subchannel_call(el);
+ if (scc == nullptr) {
+ fprintf(stderr, "No subchannel-call");
+ fflush(stderr);
+ return nullptr;
+ }
+ cs = scc->GetCallStack();
+ } else if (el->filter == &grpc_connected_filter) {
+ return grpc_connected_channel_get_stream(el);
+ } else {
+ fprintf(stderr, "Unrecognized filter: %s", el->filter->name);
+ fflush(stderr);
+ return nullptr;
+ }
+ }
+}
+
+grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call) {
+ return reinterpret_cast<grpc_chttp2_stream*>(
+ grpc_transport_stream_from_call(call));
+}
diff --git a/contrib/libs/grpc/test/core/util/debugger_macros.h b/contrib/libs/grpc/test/core/util/debugger_macros.h
index 71228c6e87..a5a603661b 100644
--- a/contrib/libs/grpc/test/core/util/debugger_macros.h
+++ b/contrib/libs/grpc/test/core/util/debugger_macros.h
@@ -1,27 +1,27 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H
-#define GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H
-
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-#include "src/core/lib/surface/call.h"
-
-grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call);
-
-#endif /* GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H */
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H
+#define GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H
+
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+#include "src/core/lib/surface/call.h"
+
+grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call);
+
+#endif /* GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H */
diff --git a/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc b/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc
index 99ab45120d..ad7bad6fe5 100644
--- a/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc
+++ b/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc
@@ -1,169 +1,169 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <stdbool.h>
-
-#include <dirent.h>
-#include <gflags/gflags.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <sys/types.h>
-
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <stdbool.h>
+
+#include <dirent.h>
+#include <gflags/gflags.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <gtest/gtest.h>
+#include <stdio.h>
+#include <sys/types.h>
+
#include <grpc/grpc.h>
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/iomgr/load_file.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/test_config.h"
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
-extern bool squelch;
-extern bool leak_check;
-
-// In some distros, gflags is in the namespace google, and in some others,
-// in gflags. This hack is enabling us to find both.
-namespace google {}
-namespace gflags {}
-using namespace google;
-using namespace gflags;
-
-DEFINE_string(file, "", "Use this file as test data");
-DEFINE_string(directory, "", "Use this directory as test data");
-
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/iomgr/load_file.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/test_config.h"
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
+extern bool squelch;
+extern bool leak_check;
+
+// In some distros, gflags is in the namespace google, and in some others,
+// in gflags. This hack is enabling us to find both.
+namespace google {}
+namespace gflags {}
+using namespace google;
+using namespace gflags;
+
+DEFINE_string(file, "", "Use this file as test data");
+DEFINE_string(directory, "", "Use this directory as test data");
+
class FuzzerCorpusTest : public ::testing::TestWithParam<TString> {};
-
-TEST_P(FuzzerCorpusTest, RunOneExample) {
+
+TEST_P(FuzzerCorpusTest, RunOneExample) {
// Need to call grpc_init() here to use a slice, but need to shut it
// down before calling LLVMFuzzerTestOneInput(), because most
// implementations of that function will initialize and shutdown gRPC
// internally.
grpc_init();
- gpr_log(GPR_DEBUG, "Example file: %s", GetParam().c_str());
- grpc_slice buffer;
- squelch = false;
- leak_check = false;
- GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
- grpc_load_file(GetParam().c_str(), 0, &buffer)));
+ gpr_log(GPR_DEBUG, "Example file: %s", GetParam().c_str());
+ grpc_slice buffer;
+ squelch = false;
+ leak_check = false;
+ GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
+ grpc_load_file(GetParam().c_str(), 0, &buffer)));
size_t length = GRPC_SLICE_LENGTH(buffer);
void* data = gpr_malloc(length);
memcpy(data, GPR_SLICE_START_PTR(buffer), length);
- grpc_slice_unref(buffer);
+ grpc_slice_unref(buffer);
grpc_shutdown_blocking();
LLVMFuzzerTestOneInput(static_cast<uint8_t*>(data), length);
gpr_free(data);
-}
-
-class ExampleGenerator
+}
+
+class ExampleGenerator
: public ::testing::internal::ParamGeneratorInterface<TString> {
- public:
+ public:
virtual ::testing::internal::ParamIteratorInterface<TString>* Begin()
- const;
+ const;
virtual ::testing::internal::ParamIteratorInterface<TString>* End() const;
-
- private:
- void Materialize() const {
- if (examples_.empty()) {
- if (!FLAGS_file.empty()) examples_.push_back(FLAGS_file);
- if (!FLAGS_directory.empty()) {
- char* test_srcdir = gpr_getenv("TEST_SRCDIR");
+
+ private:
+ void Materialize() const {
+ if (examples_.empty()) {
+ if (!FLAGS_file.empty()) examples_.push_back(FLAGS_file);
+ if (!FLAGS_directory.empty()) {
+ char* test_srcdir = gpr_getenv("TEST_SRCDIR");
gpr_log(GPR_DEBUG, "test_srcdir=\"%s\"", test_srcdir);
TString directory = FLAGS_directory;
- if (test_srcdir != nullptr) {
+ if (test_srcdir != nullptr) {
directory =
test_srcdir + TString("/com_github_grpc_grpc/") + directory;
- }
+ }
gpr_log(GPR_DEBUG, "Using corpus directory: %s", directory.c_str());
- DIR* dp;
- struct dirent* ep;
+ DIR* dp;
+ struct dirent* ep;
dp = opendir(directory.c_str());
-
- if (dp != nullptr) {
- while ((ep = readdir(dp)) != nullptr) {
+
+ if (dp != nullptr) {
+ while ((ep = readdir(dp)) != nullptr) {
if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0) {
examples_.push_back(directory + "/" + ep->d_name);
- }
- }
-
- (void)closedir(dp);
- } else {
- perror("Couldn't open the directory");
- abort();
- }
- gpr_free(test_srcdir);
- }
- }
+ }
+ }
+
+ (void)closedir(dp);
+ } else {
+ perror("Couldn't open the directory");
+ abort();
+ }
+ gpr_free(test_srcdir);
+ }
+ }
// Make sure we don't succeed without doing anything, which caused
// us to be blind to our fuzzers not running for 9 months.
GPR_ASSERT(!examples_.empty());
- }
-
+ }
+
mutable std::vector<TString> examples_;
-};
-
-class ExampleIterator
+};
+
+class ExampleIterator
: public ::testing::internal::ParamIteratorInterface<TString> {
- public:
- ExampleIterator(const ExampleGenerator& base_,
+ public:
+ ExampleIterator(const ExampleGenerator& base_,
std::vector<TString>::const_iterator begin)
- : base_(base_), begin_(begin), current_(begin) {}
-
- virtual const ExampleGenerator* BaseGenerator() const { return &base_; }
-
- virtual void Advance() { current_++; }
- virtual ExampleIterator* Clone() const { return new ExampleIterator(*this); }
+ : base_(base_), begin_(begin), current_(begin) {}
+
+ virtual const ExampleGenerator* BaseGenerator() const { return &base_; }
+
+ virtual void Advance() { current_++; }
+ virtual ExampleIterator* Clone() const { return new ExampleIterator(*this); }
virtual const TString* Current() const { return &*current_; }
-
+
virtual bool Equals(const ParamIteratorInterface<TString>& other) const {
- return &base_ == other.BaseGenerator() &&
- current_ == dynamic_cast<const ExampleIterator*>(&other)->current_;
- }
-
- private:
- ExampleIterator(const ExampleIterator& other)
- : base_(other.base_), begin_(other.begin_), current_(other.current_) {}
-
- const ExampleGenerator& base_;
+ return &base_ == other.BaseGenerator() &&
+ current_ == dynamic_cast<const ExampleIterator*>(&other)->current_;
+ }
+
+ private:
+ ExampleIterator(const ExampleIterator& other)
+ : base_(other.base_), begin_(other.begin_), current_(other.current_) {}
+
+ const ExampleGenerator& base_;
const std::vector<TString>::const_iterator begin_;
std::vector<TString>::const_iterator current_;
-};
-
+};
+
::testing::internal::ParamIteratorInterface<TString>*
-ExampleGenerator::Begin() const {
- Materialize();
- return new ExampleIterator(*this, examples_.begin());
-}
-
+ExampleGenerator::Begin() const {
+ Materialize();
+ return new ExampleIterator(*this, examples_.begin());
+}
+
::testing::internal::ParamIteratorInterface<TString>*
-ExampleGenerator::End() const {
- Materialize();
- return new ExampleIterator(*this, examples_.end());
-}
-
-INSTANTIATE_TEST_SUITE_P(
- CorpusExamples, FuzzerCorpusTest,
+ExampleGenerator::End() const {
+ Materialize();
+ return new ExampleIterator(*this, examples_.end());
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ CorpusExamples, FuzzerCorpusTest,
::testing::internal::ParamGenerator<TString>(new ExampleGenerator));
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
grpc::testing::InitTest(&argc, &argv, true);
- ::testing::InitGoogleTest(&argc, argv);
-
- return RUN_ALL_TESTS();
-}
+ ::testing::InitGoogleTest(&argc, argv);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh b/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh
index 7c471afcc2..7ffd96f006 100755
--- a/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh
+++ b/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh
@@ -1,18 +1,18 @@
-#!/bin/sh
-
-# Test runner for fuzzer tests from bazel
-
-# Copyright 2017 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.
-"$1" "$2"
+#!/bin/sh
+
+# Test runner for fuzzer tests from bazel
+
+# Copyright 2017 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.
+"$1" "$2"
diff --git a/contrib/libs/grpc/test/core/util/fuzzer_util.cc b/contrib/libs/grpc/test/core/util/fuzzer_util.cc
index 29c9b8875f..0601ae9356 100644
--- a/contrib/libs/grpc/test/core/util/fuzzer_util.cc
+++ b/contrib/libs/grpc/test/core/util/fuzzer_util.cc
@@ -1,82 +1,82 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include "test/core/util/fuzzer_util.h"
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-namespace grpc_core {
-namespace testing {
-
-uint8_t grpc_fuzzer_get_next_byte(input_stream* inp) {
- if (inp->cur == inp->end) {
- return 0;
- }
- return *inp->cur++;
-}
-
-char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special) {
- char* str = nullptr;
- size_t cap = 0;
- size_t sz = 0;
- char c;
- do {
- if (cap == sz) {
- cap = GPR_MAX(3 * cap / 2, cap + 8);
- str = static_cast<char*>(gpr_realloc(str, cap));
- }
- c = static_cast<char>(grpc_fuzzer_get_next_byte(inp));
- str[sz++] = c;
- } while (c != 0 && c != 1);
- if (special != nullptr) {
- *special = (c == 1);
- }
- if (c == 1) {
- str[sz - 1] = 0;
- }
- return str;
-}
-
-uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp) {
- uint8_t b = grpc_fuzzer_get_next_byte(inp);
- uint32_t x = b & 0x7f;
- if (b & 0x80) {
- x <<= 7;
- b = grpc_fuzzer_get_next_byte(inp);
- x |= b & 0x7f;
- if (b & 0x80) {
- x <<= 7;
- b = grpc_fuzzer_get_next_byte(inp);
- x |= b & 0x7f;
- if (b & 0x80) {
- x <<= 7;
- b = grpc_fuzzer_get_next_byte(inp);
- x |= b & 0x7f;
- if (b & 0x80) {
- x = (x << 4) | (grpc_fuzzer_get_next_byte(inp) & 0x0f);
- }
- }
- }
- }
- return x;
-}
-
-} // namespace testing
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include "test/core/util/fuzzer_util.h"
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+namespace grpc_core {
+namespace testing {
+
+uint8_t grpc_fuzzer_get_next_byte(input_stream* inp) {
+ if (inp->cur == inp->end) {
+ return 0;
+ }
+ return *inp->cur++;
+}
+
+char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special) {
+ char* str = nullptr;
+ size_t cap = 0;
+ size_t sz = 0;
+ char c;
+ do {
+ if (cap == sz) {
+ cap = GPR_MAX(3 * cap / 2, cap + 8);
+ str = static_cast<char*>(gpr_realloc(str, cap));
+ }
+ c = static_cast<char>(grpc_fuzzer_get_next_byte(inp));
+ str[sz++] = c;
+ } while (c != 0 && c != 1);
+ if (special != nullptr) {
+ *special = (c == 1);
+ }
+ if (c == 1) {
+ str[sz - 1] = 0;
+ }
+ return str;
+}
+
+uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp) {
+ uint8_t b = grpc_fuzzer_get_next_byte(inp);
+ uint32_t x = b & 0x7f;
+ if (b & 0x80) {
+ x <<= 7;
+ b = grpc_fuzzer_get_next_byte(inp);
+ x |= b & 0x7f;
+ if (b & 0x80) {
+ x <<= 7;
+ b = grpc_fuzzer_get_next_byte(inp);
+ x |= b & 0x7f;
+ if (b & 0x80) {
+ x <<= 7;
+ b = grpc_fuzzer_get_next_byte(inp);
+ x |= b & 0x7f;
+ if (b & 0x80) {
+ x = (x << 4) | (grpc_fuzzer_get_next_byte(inp) & 0x0f);
+ }
+ }
+ }
+ }
+ return x;
+}
+
+} // namespace testing
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/test/core/util/fuzzer_util.h b/contrib/libs/grpc/test/core/util/fuzzer_util.h
index 0e938399a1..7e2d74831c 100644
--- a/contrib/libs/grpc/test/core/util/fuzzer_util.h
+++ b/contrib/libs/grpc/test/core/util/fuzzer_util.h
@@ -1,49 +1,49 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H
-#define GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H
-
-#include <stdint.h>
-
-namespace grpc_core {
-
-namespace testing {
-
-// Main struct for input_stream. It allows easy access to input
-// bytes, and allows reading a little past the end(avoiding
-// needing to check everywhere).
-typedef struct {
- const uint8_t* cur;
- const uint8_t* end;
-} input_stream;
-
-// get a byte from an input stream.
-uint8_t grpc_fuzzer_get_next_byte(input_stream* inp);
-
-// get a string and boolean values (if special is not null) from an input
-// stream.
-char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special);
-
-// get a uint32 value from an input stream.
-uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp);
-
-} // namespace testing
-} // namespace grpc_core
-
-#endif /* GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H */
+/*
+ *
+ * Copyright 2018 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H
+#define GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H
+
+#include <stdint.h>
+
+namespace grpc_core {
+
+namespace testing {
+
+// Main struct for input_stream. It allows easy access to input
+// bytes, and allows reading a little past the end(avoiding
+// needing to check everywhere).
+typedef struct {
+ const uint8_t* cur;
+ const uint8_t* end;
+} input_stream;
+
+// get a byte from an input stream.
+uint8_t grpc_fuzzer_get_next_byte(input_stream* inp);
+
+// get a string and boolean values (if special is not null) from an input
+// stream.
+char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special);
+
+// get a uint32 value from an input stream.
+uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp);
+
+} // namespace testing
+} // namespace grpc_core
+
+#endif /* GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H */
diff --git a/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl b/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl
index 99594b29e1..e6d7053374 100644
--- a/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl
+++ b/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl
@@ -1,29 +1,29 @@
-# Copyright 2016 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.
-
-load("//bazel:grpc_build_system.bzl", "grpc_cc_test")
-
+# Copyright 2016 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.
+
+load("//bazel:grpc_build_system.bzl", "grpc_cc_test")
+
def grpc_fuzzer(name, corpus, srcs = [], deps = [], data = [], size = "large", **kwargs):
- grpc_cc_test(
- name = name,
- srcs = srcs,
- deps = deps + ["//test/core/util:fuzzer_corpus_test"],
+ grpc_cc_test(
+ name = name,
+ srcs = srcs,
+ deps = deps + ["//test/core/util:fuzzer_corpus_test"],
data = data + native.glob([corpus + "/**"]),
- external_deps = [
- "gtest",
- ],
- size = size,
- args = ["--directory=" + native.package_name() + "/" + corpus],
- **kwargs
- )
+ external_deps = [
+ "gtest",
+ ],
+ size = size,
+ args = ["--directory=" + native.package_name() + "/" + corpus],
+ **kwargs
+ )
diff --git a/contrib/libs/grpc/test/core/util/grpc_profiler.cc b/contrib/libs/grpc/test/core/util/grpc_profiler.cc
index 88f233598b..6ed0d14c9f 100644
--- a/contrib/libs/grpc/test/core/util/grpc_profiler.cc
+++ b/contrib/libs/grpc/test/core/util/grpc_profiler.cc
@@ -1,45 +1,45 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/grpc_profiler.h"
-
-#if GRPC_HAVE_PERFTOOLS
-#include <gperftools/profiler.h>
-
-void grpc_profiler_start(const char* filename) { ProfilerStart(filename); }
-
-void grpc_profiler_stop() { ProfilerStop(); }
-#else
-#include <grpc/support/log.h>
-
-void grpc_profiler_start(const char* filename) {
- static int printed_warning = 0;
- if (!printed_warning) {
- gpr_log(GPR_DEBUG,
- "You do not have google-perftools installed, profiling is disabled "
- "[for %s]",
- filename);
- gpr_log(GPR_DEBUG,
- "To install on ubuntu: sudo apt-get install google-perftools "
- "libgoogle-perftools-dev");
- printed_warning = 1;
- }
-}
-
-void grpc_profiler_stop(void) {}
-#endif
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/grpc_profiler.h"
+
+#if GRPC_HAVE_PERFTOOLS
+#include <gperftools/profiler.h>
+
+void grpc_profiler_start(const char* filename) { ProfilerStart(filename); }
+
+void grpc_profiler_stop() { ProfilerStop(); }
+#else
+#include <grpc/support/log.h>
+
+void grpc_profiler_start(const char* filename) {
+ static int printed_warning = 0;
+ if (!printed_warning) {
+ gpr_log(GPR_DEBUG,
+ "You do not have google-perftools installed, profiling is disabled "
+ "[for %s]",
+ filename);
+ gpr_log(GPR_DEBUG,
+ "To install on ubuntu: sudo apt-get install google-perftools "
+ "libgoogle-perftools-dev");
+ printed_warning = 1;
+ }
+}
+
+void grpc_profiler_stop(void) {}
+#endif
diff --git a/contrib/libs/grpc/test/core/util/grpc_profiler.h b/contrib/libs/grpc/test/core/util/grpc_profiler.h
index f9ddd2242e..ca715c22bc 100644
--- a/contrib/libs/grpc/test/core/util/grpc_profiler.h
+++ b/contrib/libs/grpc/test/core/util/grpc_profiler.h
@@ -1,25 +1,25 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H
-#define GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H
-
-void grpc_profiler_start(const char* filename);
-void grpc_profiler_stop();
-
-#endif /* GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H
+#define GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H
+
+void grpc_profiler_start(const char* filename);
+void grpc_profiler_stop();
+
+#endif /* GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H */
diff --git a/contrib/libs/grpc/test/core/util/histogram.cc b/contrib/libs/grpc/test/core/util/histogram.cc
index f028ac404e..3b17818873 100644
--- a/contrib/libs/grpc/test/core/util/histogram.cc
+++ b/contrib/libs/grpc/test/core/util/histogram.cc
@@ -1,230 +1,230 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/histogram.h"
-
-#include <math.h>
-#include <stddef.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-/* Histograms are stored with exponentially increasing bucket sizes.
- The first bucket is [0, m) where m = 1 + resolution
- Bucket n (n>=1) contains [m**n, m**(n+1))
- There are sufficient buckets to reach max_bucket_start */
-
-struct grpc_histogram {
- /* Sum of all values seen so far */
- double sum;
- /* Sum of squares of all values seen so far */
- double sum_of_squares;
- /* number of values seen so far */
- double count;
- /* m in the description */
- double multiplier;
- double one_on_log_multiplier;
- /* minimum value seen */
- double min_seen;
- /* maximum value seen */
- double max_seen;
- /* maximum representable value */
- double max_possible;
- /* number of buckets */
- size_t num_buckets;
- /* the buckets themselves */
- uint32_t* buckets;
-};
-
-/* determine a bucket index given a value - does no bounds checking */
-static size_t bucket_for_unchecked(grpc_histogram* h, double x) {
- return static_cast<size_t>(log(x) * h->one_on_log_multiplier);
-}
-
-/* bounds checked version of the above */
-static size_t bucket_for(grpc_histogram* h, double x) {
- size_t bucket = bucket_for_unchecked(h, GPR_CLAMP(x, 1.0, h->max_possible));
- GPR_ASSERT(bucket < h->num_buckets);
- return bucket;
-}
-
-/* at what value does a bucket start? */
-static double bucket_start(grpc_histogram* h, double x) {
- return pow(h->multiplier, x);
-}
-
-grpc_histogram* grpc_histogram_create(double resolution,
- double max_bucket_start) {
- grpc_histogram* h =
- static_cast<grpc_histogram*>(gpr_malloc(sizeof(grpc_histogram)));
- GPR_ASSERT(resolution > 0.0);
- GPR_ASSERT(max_bucket_start > resolution);
- h->sum = 0.0;
- h->sum_of_squares = 0.0;
- h->multiplier = 1.0 + resolution;
- h->one_on_log_multiplier = 1.0 / log(1.0 + resolution);
- h->max_possible = max_bucket_start;
- h->count = 0.0;
- h->min_seen = max_bucket_start;
- h->max_seen = 0.0;
- h->num_buckets = bucket_for_unchecked(h, max_bucket_start) + 1;
- GPR_ASSERT(h->num_buckets > 1);
- GPR_ASSERT(h->num_buckets < 100000000);
- h->buckets =
- static_cast<uint32_t*>(gpr_zalloc(sizeof(uint32_t) * h->num_buckets));
- return h;
-}
-
-void grpc_histogram_destroy(grpc_histogram* h) {
- gpr_free(h->buckets);
- gpr_free(h);
-}
-
-void grpc_histogram_add(grpc_histogram* h, double x) {
- h->sum += x;
- h->sum_of_squares += x * x;
- h->count++;
- if (x < h->min_seen) {
- h->min_seen = x;
- }
- if (x > h->max_seen) {
- h->max_seen = x;
- }
- h->buckets[bucket_for(h, x)]++;
-}
-
-int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src) {
- if ((dst->num_buckets != src->num_buckets) ||
- (dst->multiplier != src->multiplier)) {
- /* Fail because these histograms don't match */
- return 0;
- }
- grpc_histogram_merge_contents(dst, src->buckets, src->num_buckets,
- src->min_seen, src->max_seen, src->sum,
- src->sum_of_squares, src->count);
- return 1;
-}
-
-void grpc_histogram_merge_contents(grpc_histogram* dst, const uint32_t* data,
- size_t data_count, double min_seen,
- double max_seen, double sum,
- double sum_of_squares, double count) {
- size_t i;
- GPR_ASSERT(dst->num_buckets == data_count);
- dst->sum += sum;
- dst->sum_of_squares += sum_of_squares;
- dst->count += count;
- if (min_seen < dst->min_seen) {
- dst->min_seen = min_seen;
- }
- if (max_seen > dst->max_seen) {
- dst->max_seen = max_seen;
- }
- for (i = 0; i < dst->num_buckets; i++) {
- dst->buckets[i] += data[i];
- }
-}
-
-static double threshold_for_count_below(grpc_histogram* h, double count_below) {
- double count_so_far;
- double lower_bound;
- double upper_bound;
- size_t lower_idx;
- size_t upper_idx;
-
- if (h->count == 0) {
- return 0.0;
- }
-
- if (count_below <= 0) {
- return h->min_seen;
- }
- if (count_below >= h->count) {
- return h->max_seen;
- }
-
- /* find the lowest bucket that gets us above count_below */
- count_so_far = 0.0;
- for (lower_idx = 0; lower_idx < h->num_buckets; lower_idx++) {
- count_so_far += h->buckets[lower_idx];
- if (count_so_far >= count_below) {
- break;
- }
- }
- if (count_so_far == count_below) {
- /* this bucket hits the threshold exactly... we should be midway through
- any run of zero values following the bucket */
- for (upper_idx = lower_idx + 1; upper_idx < h->num_buckets; upper_idx++) {
- if (h->buckets[upper_idx]) {
- break;
- }
- }
- return (bucket_start(h, static_cast<double>(lower_idx)) +
- bucket_start(h, static_cast<double>(upper_idx))) /
- 2.0;
- } else {
- /* treat values as uniform throughout the bucket, and find where this value
- should lie */
- lower_bound = bucket_start(h, static_cast<double>(lower_idx));
- upper_bound = bucket_start(h, static_cast<double>(lower_idx + 1));
- return GPR_CLAMP(upper_bound - (upper_bound - lower_bound) *
- (count_so_far - count_below) /
- h->buckets[lower_idx],
- h->min_seen, h->max_seen);
- }
-}
-
-double grpc_histogram_percentile(grpc_histogram* h, double percentile) {
- return threshold_for_count_below(h, h->count * percentile / 100.0);
-}
-
-double grpc_histogram_mean(grpc_histogram* h) {
- GPR_ASSERT(h->count != 0);
- return h->sum / h->count;
-}
-
-double grpc_histogram_stddev(grpc_histogram* h) {
- return sqrt(grpc_histogram_variance(h));
-}
-
-double grpc_histogram_variance(grpc_histogram* h) {
- if (h->count == 0) return 0.0;
- return (h->sum_of_squares * h->count - h->sum * h->sum) /
- (h->count * h->count);
-}
-
-double grpc_histogram_maximum(grpc_histogram* h) { return h->max_seen; }
-
-double grpc_histogram_minimum(grpc_histogram* h) { return h->min_seen; }
-
-double grpc_histogram_count(grpc_histogram* h) { return h->count; }
-
-double grpc_histogram_sum(grpc_histogram* h) { return h->sum; }
-
-double grpc_histogram_sum_of_squares(grpc_histogram* h) {
- return h->sum_of_squares;
-}
-
-const uint32_t* grpc_histogram_get_contents(grpc_histogram* h, size_t* size) {
- *size = h->num_buckets;
- return h->buckets;
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/histogram.h"
+
+#include <math.h>
+#include <stddef.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+/* Histograms are stored with exponentially increasing bucket sizes.
+ The first bucket is [0, m) where m = 1 + resolution
+ Bucket n (n>=1) contains [m**n, m**(n+1))
+ There are sufficient buckets to reach max_bucket_start */
+
+struct grpc_histogram {
+ /* Sum of all values seen so far */
+ double sum;
+ /* Sum of squares of all values seen so far */
+ double sum_of_squares;
+ /* number of values seen so far */
+ double count;
+ /* m in the description */
+ double multiplier;
+ double one_on_log_multiplier;
+ /* minimum value seen */
+ double min_seen;
+ /* maximum value seen */
+ double max_seen;
+ /* maximum representable value */
+ double max_possible;
+ /* number of buckets */
+ size_t num_buckets;
+ /* the buckets themselves */
+ uint32_t* buckets;
+};
+
+/* determine a bucket index given a value - does no bounds checking */
+static size_t bucket_for_unchecked(grpc_histogram* h, double x) {
+ return static_cast<size_t>(log(x) * h->one_on_log_multiplier);
+}
+
+/* bounds checked version of the above */
+static size_t bucket_for(grpc_histogram* h, double x) {
+ size_t bucket = bucket_for_unchecked(h, GPR_CLAMP(x, 1.0, h->max_possible));
+ GPR_ASSERT(bucket < h->num_buckets);
+ return bucket;
+}
+
+/* at what value does a bucket start? */
+static double bucket_start(grpc_histogram* h, double x) {
+ return pow(h->multiplier, x);
+}
+
+grpc_histogram* grpc_histogram_create(double resolution,
+ double max_bucket_start) {
+ grpc_histogram* h =
+ static_cast<grpc_histogram*>(gpr_malloc(sizeof(grpc_histogram)));
+ GPR_ASSERT(resolution > 0.0);
+ GPR_ASSERT(max_bucket_start > resolution);
+ h->sum = 0.0;
+ h->sum_of_squares = 0.0;
+ h->multiplier = 1.0 + resolution;
+ h->one_on_log_multiplier = 1.0 / log(1.0 + resolution);
+ h->max_possible = max_bucket_start;
+ h->count = 0.0;
+ h->min_seen = max_bucket_start;
+ h->max_seen = 0.0;
+ h->num_buckets = bucket_for_unchecked(h, max_bucket_start) + 1;
+ GPR_ASSERT(h->num_buckets > 1);
+ GPR_ASSERT(h->num_buckets < 100000000);
+ h->buckets =
+ static_cast<uint32_t*>(gpr_zalloc(sizeof(uint32_t) * h->num_buckets));
+ return h;
+}
+
+void grpc_histogram_destroy(grpc_histogram* h) {
+ gpr_free(h->buckets);
+ gpr_free(h);
+}
+
+void grpc_histogram_add(grpc_histogram* h, double x) {
+ h->sum += x;
+ h->sum_of_squares += x * x;
+ h->count++;
+ if (x < h->min_seen) {
+ h->min_seen = x;
+ }
+ if (x > h->max_seen) {
+ h->max_seen = x;
+ }
+ h->buckets[bucket_for(h, x)]++;
+}
+
+int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src) {
+ if ((dst->num_buckets != src->num_buckets) ||
+ (dst->multiplier != src->multiplier)) {
+ /* Fail because these histograms don't match */
+ return 0;
+ }
+ grpc_histogram_merge_contents(dst, src->buckets, src->num_buckets,
+ src->min_seen, src->max_seen, src->sum,
+ src->sum_of_squares, src->count);
+ return 1;
+}
+
+void grpc_histogram_merge_contents(grpc_histogram* dst, const uint32_t* data,
+ size_t data_count, double min_seen,
+ double max_seen, double sum,
+ double sum_of_squares, double count) {
+ size_t i;
+ GPR_ASSERT(dst->num_buckets == data_count);
+ dst->sum += sum;
+ dst->sum_of_squares += sum_of_squares;
+ dst->count += count;
+ if (min_seen < dst->min_seen) {
+ dst->min_seen = min_seen;
+ }
+ if (max_seen > dst->max_seen) {
+ dst->max_seen = max_seen;
+ }
+ for (i = 0; i < dst->num_buckets; i++) {
+ dst->buckets[i] += data[i];
+ }
+}
+
+static double threshold_for_count_below(grpc_histogram* h, double count_below) {
+ double count_so_far;
+ double lower_bound;
+ double upper_bound;
+ size_t lower_idx;
+ size_t upper_idx;
+
+ if (h->count == 0) {
+ return 0.0;
+ }
+
+ if (count_below <= 0) {
+ return h->min_seen;
+ }
+ if (count_below >= h->count) {
+ return h->max_seen;
+ }
+
+ /* find the lowest bucket that gets us above count_below */
+ count_so_far = 0.0;
+ for (lower_idx = 0; lower_idx < h->num_buckets; lower_idx++) {
+ count_so_far += h->buckets[lower_idx];
+ if (count_so_far >= count_below) {
+ break;
+ }
+ }
+ if (count_so_far == count_below) {
+ /* this bucket hits the threshold exactly... we should be midway through
+ any run of zero values following the bucket */
+ for (upper_idx = lower_idx + 1; upper_idx < h->num_buckets; upper_idx++) {
+ if (h->buckets[upper_idx]) {
+ break;
+ }
+ }
+ return (bucket_start(h, static_cast<double>(lower_idx)) +
+ bucket_start(h, static_cast<double>(upper_idx))) /
+ 2.0;
+ } else {
+ /* treat values as uniform throughout the bucket, and find where this value
+ should lie */
+ lower_bound = bucket_start(h, static_cast<double>(lower_idx));
+ upper_bound = bucket_start(h, static_cast<double>(lower_idx + 1));
+ return GPR_CLAMP(upper_bound - (upper_bound - lower_bound) *
+ (count_so_far - count_below) /
+ h->buckets[lower_idx],
+ h->min_seen, h->max_seen);
+ }
+}
+
+double grpc_histogram_percentile(grpc_histogram* h, double percentile) {
+ return threshold_for_count_below(h, h->count * percentile / 100.0);
+}
+
+double grpc_histogram_mean(grpc_histogram* h) {
+ GPR_ASSERT(h->count != 0);
+ return h->sum / h->count;
+}
+
+double grpc_histogram_stddev(grpc_histogram* h) {
+ return sqrt(grpc_histogram_variance(h));
+}
+
+double grpc_histogram_variance(grpc_histogram* h) {
+ if (h->count == 0) return 0.0;
+ return (h->sum_of_squares * h->count - h->sum * h->sum) /
+ (h->count * h->count);
+}
+
+double grpc_histogram_maximum(grpc_histogram* h) { return h->max_seen; }
+
+double grpc_histogram_minimum(grpc_histogram* h) { return h->min_seen; }
+
+double grpc_histogram_count(grpc_histogram* h) { return h->count; }
+
+double grpc_histogram_sum(grpc_histogram* h) { return h->sum; }
+
+double grpc_histogram_sum_of_squares(grpc_histogram* h) {
+ return h->sum_of_squares;
+}
+
+const uint32_t* grpc_histogram_get_contents(grpc_histogram* h, size_t* size) {
+ *size = h->num_buckets;
+ return h->buckets;
+}
diff --git a/contrib/libs/grpc/test/core/util/histogram.h b/contrib/libs/grpc/test/core/util/histogram.h
index 9d4985e64f..eeeb06352c 100644
--- a/contrib/libs/grpc/test/core/util/histogram.h
+++ b/contrib/libs/grpc/test/core/util/histogram.h
@@ -1,62 +1,62 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_SUPPORT_HISTOGRAM_H
-#define GRPC_SUPPORT_HISTOGRAM_H
-
-#include <grpc/support/port_platform.h>
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct grpc_histogram grpc_histogram;
-
-grpc_histogram* grpc_histogram_create(double resolution,
- double max_bucket_start);
-void grpc_histogram_destroy(grpc_histogram* h);
-void grpc_histogram_add(grpc_histogram* h, double x);
-
-/** The following merges the second histogram into the first. It only works
- if they have the same buckets and resolution. Returns 0 on failure, 1
- on success */
-int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src);
-
-double grpc_histogram_percentile(grpc_histogram* histogram, double percentile);
-double grpc_histogram_mean(grpc_histogram* histogram);
-double grpc_histogram_stddev(grpc_histogram* histogram);
-double grpc_histogram_variance(grpc_histogram* histogram);
-double grpc_histogram_maximum(grpc_histogram* histogram);
-double grpc_histogram_minimum(grpc_histogram* histogram);
-double grpc_histogram_count(grpc_histogram* histogram);
-double grpc_histogram_sum(grpc_histogram* histogram);
-double grpc_histogram_sum_of_squares(grpc_histogram* histogram);
-
-const uint32_t* grpc_histogram_get_contents(grpc_histogram* histogram,
- size_t* count);
-void grpc_histogram_merge_contents(grpc_histogram* histogram,
- const uint32_t* data, size_t data_count,
- double min_seen, double max_seen, double sum,
- double sum_of_squares, double count);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* GRPC_SUPPORT_HISTOGRAM_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_SUPPORT_HISTOGRAM_H
+#define GRPC_SUPPORT_HISTOGRAM_H
+
+#include <grpc/support/port_platform.h>
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct grpc_histogram grpc_histogram;
+
+grpc_histogram* grpc_histogram_create(double resolution,
+ double max_bucket_start);
+void grpc_histogram_destroy(grpc_histogram* h);
+void grpc_histogram_add(grpc_histogram* h, double x);
+
+/** The following merges the second histogram into the first. It only works
+ if they have the same buckets and resolution. Returns 0 on failure, 1
+ on success */
+int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src);
+
+double grpc_histogram_percentile(grpc_histogram* histogram, double percentile);
+double grpc_histogram_mean(grpc_histogram* histogram);
+double grpc_histogram_stddev(grpc_histogram* histogram);
+double grpc_histogram_variance(grpc_histogram* histogram);
+double grpc_histogram_maximum(grpc_histogram* histogram);
+double grpc_histogram_minimum(grpc_histogram* histogram);
+double grpc_histogram_count(grpc_histogram* histogram);
+double grpc_histogram_sum(grpc_histogram* histogram);
+double grpc_histogram_sum_of_squares(grpc_histogram* histogram);
+
+const uint32_t* grpc_histogram_get_contents(grpc_histogram* histogram,
+ size_t* count);
+void grpc_histogram_merge_contents(grpc_histogram* histogram,
+ const uint32_t* data, size_t data_count,
+ double min_seen, double max_seen, double sum,
+ double sum_of_squares, double count);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_SUPPORT_HISTOGRAM_H */
diff --git a/contrib/libs/grpc/test/core/util/histogram_test.cc b/contrib/libs/grpc/test/core/util/histogram_test.cc
index b96ac7d841..44c0084185 100644
--- a/contrib/libs/grpc/test/core/util/histogram_test.cc
+++ b/contrib/libs/grpc/test/core/util/histogram_test.cc
@@ -1,163 +1,163 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/histogram.h"
-#include <grpc/support/log.h>
-
-#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", x);
-
-static void test_no_op(void) {
- grpc_histogram_destroy(grpc_histogram_create(0.01, 60e9));
-}
-
-static void expect_percentile(grpc_histogram* h, double percentile,
- double min_expect, double max_expect) {
- double got = grpc_histogram_percentile(h, percentile);
- gpr_log(GPR_INFO, "@%f%%, expect %f <= %f <= %f", percentile, min_expect, got,
- max_expect);
- GPR_ASSERT(min_expect <= got);
- GPR_ASSERT(got <= max_expect);
-}
-
-static void test_simple(void) {
- grpc_histogram* h;
-
- LOG_TEST("test_simple");
-
- h = grpc_histogram_create(0.01, 60e9);
- grpc_histogram_add(h, 10000);
- grpc_histogram_add(h, 10000);
- grpc_histogram_add(h, 11000);
- grpc_histogram_add(h, 11000);
-
- expect_percentile(h, 50, 10001, 10999);
- GPR_ASSERT(grpc_histogram_mean(h) == 10500);
-
- grpc_histogram_destroy(h);
-}
-
-static void test_percentile(void) {
- grpc_histogram* h;
- double last;
- double i;
- double cur;
-
- LOG_TEST("test_percentile");
-
- h = grpc_histogram_create(0.05, 1e9);
- grpc_histogram_add(h, 2.5);
- grpc_histogram_add(h, 2.5);
- grpc_histogram_add(h, 8);
- grpc_histogram_add(h, 4);
-
- GPR_ASSERT(grpc_histogram_count(h) == 4);
- GPR_ASSERT(grpc_histogram_minimum(h) == 2.5);
- GPR_ASSERT(grpc_histogram_maximum(h) == 8);
- GPR_ASSERT(grpc_histogram_sum(h) == 17);
- GPR_ASSERT(grpc_histogram_sum_of_squares(h) == 92.5);
- GPR_ASSERT(grpc_histogram_mean(h) == 4.25);
- GPR_ASSERT(grpc_histogram_variance(h) == 5.0625);
- GPR_ASSERT(grpc_histogram_stddev(h) == 2.25);
-
- expect_percentile(h, -10, 2.5, 2.5);
- expect_percentile(h, 0, 2.5, 2.5);
- expect_percentile(h, 12.5, 2.5, 2.5);
- expect_percentile(h, 25, 2.5, 2.5);
- expect_percentile(h, 37.5, 2.5, 2.8);
- expect_percentile(h, 50, 3.0, 3.5);
- expect_percentile(h, 62.5, 3.5, 4.5);
- expect_percentile(h, 75, 5, 7.9);
- expect_percentile(h, 100, 8, 8);
- expect_percentile(h, 110, 8, 8);
-
- /* test monotonicity */
- last = 0.0;
- for (i = 0; i < 100.0; i += 0.01) {
- cur = grpc_histogram_percentile(h, i);
- GPR_ASSERT(cur >= last);
- last = cur;
- }
-
- grpc_histogram_destroy(h);
-}
-
-static void test_merge(void) {
- grpc_histogram *h1, *h2;
- double last;
- double i;
- double cur;
-
- LOG_TEST("test_merge");
-
- h1 = grpc_histogram_create(0.05, 1e9);
- grpc_histogram_add(h1, 2.5);
- grpc_histogram_add(h1, 2.5);
- grpc_histogram_add(h1, 8);
- grpc_histogram_add(h1, 4);
-
- h2 = grpc_histogram_create(0.01, 1e9);
- GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0);
- grpc_histogram_destroy(h2);
-
- h2 = grpc_histogram_create(0.05, 1e10);
- GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0);
- grpc_histogram_destroy(h2);
-
- h2 = grpc_histogram_create(0.05, 1e9);
- GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1);
- GPR_ASSERT(grpc_histogram_count(h1) == 4);
- GPR_ASSERT(grpc_histogram_minimum(h1) == 2.5);
- GPR_ASSERT(grpc_histogram_maximum(h1) == 8);
- GPR_ASSERT(grpc_histogram_sum(h1) == 17);
- GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 92.5);
- GPR_ASSERT(grpc_histogram_mean(h1) == 4.25);
- GPR_ASSERT(grpc_histogram_variance(h1) == 5.0625);
- GPR_ASSERT(grpc_histogram_stddev(h1) == 2.25);
- grpc_histogram_destroy(h2);
-
- h2 = grpc_histogram_create(0.05, 1e9);
- grpc_histogram_add(h2, 7.0);
- grpc_histogram_add(h2, 17.0);
- grpc_histogram_add(h2, 1.0);
- GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1);
- GPR_ASSERT(grpc_histogram_count(h1) == 7);
- GPR_ASSERT(grpc_histogram_minimum(h1) == 1.0);
- GPR_ASSERT(grpc_histogram_maximum(h1) == 17.0);
- GPR_ASSERT(grpc_histogram_sum(h1) == 42.0);
- GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 431.5);
- GPR_ASSERT(grpc_histogram_mean(h1) == 6.0);
-
- /* test monotonicity */
- last = 0.0;
- for (i = 0; i < 100.0; i += 0.01) {
- cur = grpc_histogram_percentile(h1, i);
- GPR_ASSERT(cur >= last);
- last = cur;
- }
-
- grpc_histogram_destroy(h1);
- grpc_histogram_destroy(h2);
-}
-
-int main(void) {
- test_no_op();
- test_simple();
- test_percentile();
- test_merge();
- return 0;
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/histogram.h"
+#include <grpc/support/log.h>
+
+#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", x);
+
+static void test_no_op(void) {
+ grpc_histogram_destroy(grpc_histogram_create(0.01, 60e9));
+}
+
+static void expect_percentile(grpc_histogram* h, double percentile,
+ double min_expect, double max_expect) {
+ double got = grpc_histogram_percentile(h, percentile);
+ gpr_log(GPR_INFO, "@%f%%, expect %f <= %f <= %f", percentile, min_expect, got,
+ max_expect);
+ GPR_ASSERT(min_expect <= got);
+ GPR_ASSERT(got <= max_expect);
+}
+
+static void test_simple(void) {
+ grpc_histogram* h;
+
+ LOG_TEST("test_simple");
+
+ h = grpc_histogram_create(0.01, 60e9);
+ grpc_histogram_add(h, 10000);
+ grpc_histogram_add(h, 10000);
+ grpc_histogram_add(h, 11000);
+ grpc_histogram_add(h, 11000);
+
+ expect_percentile(h, 50, 10001, 10999);
+ GPR_ASSERT(grpc_histogram_mean(h) == 10500);
+
+ grpc_histogram_destroy(h);
+}
+
+static void test_percentile(void) {
+ grpc_histogram* h;
+ double last;
+ double i;
+ double cur;
+
+ LOG_TEST("test_percentile");
+
+ h = grpc_histogram_create(0.05, 1e9);
+ grpc_histogram_add(h, 2.5);
+ grpc_histogram_add(h, 2.5);
+ grpc_histogram_add(h, 8);
+ grpc_histogram_add(h, 4);
+
+ GPR_ASSERT(grpc_histogram_count(h) == 4);
+ GPR_ASSERT(grpc_histogram_minimum(h) == 2.5);
+ GPR_ASSERT(grpc_histogram_maximum(h) == 8);
+ GPR_ASSERT(grpc_histogram_sum(h) == 17);
+ GPR_ASSERT(grpc_histogram_sum_of_squares(h) == 92.5);
+ GPR_ASSERT(grpc_histogram_mean(h) == 4.25);
+ GPR_ASSERT(grpc_histogram_variance(h) == 5.0625);
+ GPR_ASSERT(grpc_histogram_stddev(h) == 2.25);
+
+ expect_percentile(h, -10, 2.5, 2.5);
+ expect_percentile(h, 0, 2.5, 2.5);
+ expect_percentile(h, 12.5, 2.5, 2.5);
+ expect_percentile(h, 25, 2.5, 2.5);
+ expect_percentile(h, 37.5, 2.5, 2.8);
+ expect_percentile(h, 50, 3.0, 3.5);
+ expect_percentile(h, 62.5, 3.5, 4.5);
+ expect_percentile(h, 75, 5, 7.9);
+ expect_percentile(h, 100, 8, 8);
+ expect_percentile(h, 110, 8, 8);
+
+ /* test monotonicity */
+ last = 0.0;
+ for (i = 0; i < 100.0; i += 0.01) {
+ cur = grpc_histogram_percentile(h, i);
+ GPR_ASSERT(cur >= last);
+ last = cur;
+ }
+
+ grpc_histogram_destroy(h);
+}
+
+static void test_merge(void) {
+ grpc_histogram *h1, *h2;
+ double last;
+ double i;
+ double cur;
+
+ LOG_TEST("test_merge");
+
+ h1 = grpc_histogram_create(0.05, 1e9);
+ grpc_histogram_add(h1, 2.5);
+ grpc_histogram_add(h1, 2.5);
+ grpc_histogram_add(h1, 8);
+ grpc_histogram_add(h1, 4);
+
+ h2 = grpc_histogram_create(0.01, 1e9);
+ GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0);
+ grpc_histogram_destroy(h2);
+
+ h2 = grpc_histogram_create(0.05, 1e10);
+ GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0);
+ grpc_histogram_destroy(h2);
+
+ h2 = grpc_histogram_create(0.05, 1e9);
+ GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1);
+ GPR_ASSERT(grpc_histogram_count(h1) == 4);
+ GPR_ASSERT(grpc_histogram_minimum(h1) == 2.5);
+ GPR_ASSERT(grpc_histogram_maximum(h1) == 8);
+ GPR_ASSERT(grpc_histogram_sum(h1) == 17);
+ GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 92.5);
+ GPR_ASSERT(grpc_histogram_mean(h1) == 4.25);
+ GPR_ASSERT(grpc_histogram_variance(h1) == 5.0625);
+ GPR_ASSERT(grpc_histogram_stddev(h1) == 2.25);
+ grpc_histogram_destroy(h2);
+
+ h2 = grpc_histogram_create(0.05, 1e9);
+ grpc_histogram_add(h2, 7.0);
+ grpc_histogram_add(h2, 17.0);
+ grpc_histogram_add(h2, 1.0);
+ GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1);
+ GPR_ASSERT(grpc_histogram_count(h1) == 7);
+ GPR_ASSERT(grpc_histogram_minimum(h1) == 1.0);
+ GPR_ASSERT(grpc_histogram_maximum(h1) == 17.0);
+ GPR_ASSERT(grpc_histogram_sum(h1) == 42.0);
+ GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 431.5);
+ GPR_ASSERT(grpc_histogram_mean(h1) == 6.0);
+
+ /* test monotonicity */
+ last = 0.0;
+ for (i = 0; i < 100.0; i += 0.01) {
+ cur = grpc_histogram_percentile(h1, i);
+ GPR_ASSERT(cur >= last);
+ last = cur;
+ }
+
+ grpc_histogram_destroy(h1);
+ grpc_histogram_destroy(h2);
+}
+
+int main(void) {
+ test_no_op();
+ test_simple();
+ test_percentile();
+ test_merge();
+ return 0;
+}
diff --git a/contrib/libs/grpc/test/core/util/lsan_suppressions.txt b/contrib/libs/grpc/test/core/util/lsan_suppressions.txt
index 204ddbef5e..4ab9d9978b 100644
--- a/contrib/libs/grpc/test/core/util/lsan_suppressions.txt
+++ b/contrib/libs/grpc/test/core/util/lsan_suppressions.txt
@@ -1,6 +1,6 @@
-# this is busted in BoringSSL
-leak:CRYPTO_set_thread_local
-leak:err_get_state
-leak:ERR_add_error_dataf
-leak:err_add_error_vdata
-leak:RAND_bytes_with_additional_data
+# this is busted in BoringSSL
+leak:CRYPTO_set_thread_local
+leak:err_get_state
+leak:ERR_add_error_dataf
+leak:err_add_error_vdata
+leak:RAND_bytes_with_additional_data
diff --git a/contrib/libs/grpc/test/core/util/memory_counters.cc b/contrib/libs/grpc/test/core/util/memory_counters.cc
index ddd8d2f283..62cfc9b4c3 100644
--- a/contrib/libs/grpc/test/core/util/memory_counters.cc
+++ b/contrib/libs/grpc/test/core/util/memory_counters.cc
@@ -1,169 +1,169 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/gpr/alloc.h"
-#include "src/core/lib/surface/init.h"
-#include "test/core/util/memory_counters.h"
-
-#include <stdio.h>
-
-static struct grpc_memory_counters g_memory_counters;
-static bool g_memory_counter_enabled;
-
-#ifdef GPR_LOW_LEVEL_COUNTERS
-/* hide these from the microbenchmark atomic stats */
-#define NO_BARRIER_FETCH_ADD(x, sz) \
- __atomic_fetch_add((x), (sz), __ATOMIC_RELAXED)
-#define NO_BARRIER_LOAD(x) __atomic_load_n((x), __ATOMIC_RELAXED)
-#else
-#define NO_BARRIER_FETCH_ADD(x, sz) gpr_atm_no_barrier_fetch_add(x, sz)
-#define NO_BARRIER_LOAD(x) gpr_atm_no_barrier_load(x)
-#endif
-
-// Memory counter uses --wrap=symbol feature from ld. To use this,
-// `GPR_WRAP_MEMORY_COUNTER` needs to be defined. following options should be
-// passed to the compiler.
-// -Wl,--wrap=malloc -Wl,--wrap=calloc -Wl,--wrap=realloc -Wl,--wrap=free
-// * Reference: https://linux.die.net/man/1/ld)
-#if GPR_WRAP_MEMORY_COUNTER
-
-extern "C" {
-void* __real_malloc(size_t size);
-void* __real_calloc(size_t size);
-void* __real_realloc(void* ptr, size_t size);
-void __real_free(void* ptr);
-
-void* __wrap_malloc(size_t size);
-void* __wrap_calloc(size_t size);
-void* __wrap_realloc(void* ptr, size_t size);
-void __wrap_free(void* ptr);
-}
-
-void* __wrap_malloc(size_t size) {
- if (!size) return nullptr;
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1);
- void* ptr =
- __real_malloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size);
- *static_cast<size_t*>(ptr) = size;
- return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
-}
-
-void* __wrap_calloc(size_t size) {
- if (!size) return nullptr;
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1);
- void* ptr =
- __real_calloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size);
- *static_cast<size_t*>(ptr) = size;
- return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
-}
-
-void* __wrap_realloc(void* ptr, size_t size) {
- if (ptr == nullptr) {
- return __wrap_malloc(size);
- }
- if (size == 0) {
- __wrap_free(ptr);
- return nullptr;
- }
- void* rptr =
- static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative,
- -*static_cast<gpr_atm*>(rptr));
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size);
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1);
- void* new_ptr =
- __real_realloc(rptr, GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size);
- *static_cast<size_t*>(new_ptr) = size;
- return static_cast<char*>(new_ptr) +
- GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
-}
-
-void __wrap_free(void* ptr) {
- if (ptr == nullptr) return;
- void* rptr =
- static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size_t));
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative,
- -*static_cast<gpr_atm*>(rptr));
- NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, -(gpr_atm)1);
- __real_free(rptr);
-}
-
-#endif // GPR_WRAP_MEMORY_COUNTER
-
-void grpc_memory_counters_init() {
- memset(&g_memory_counters, 0, sizeof(g_memory_counters));
- g_memory_counter_enabled = true;
-}
-
-void grpc_memory_counters_destroy() { g_memory_counter_enabled = false; }
-
-struct grpc_memory_counters grpc_memory_counters_snapshot() {
- struct grpc_memory_counters counters;
- counters.total_size_relative =
- NO_BARRIER_LOAD(&g_memory_counters.total_size_relative);
- counters.total_size_absolute =
- NO_BARRIER_LOAD(&g_memory_counters.total_size_absolute);
- counters.total_allocs_relative =
- NO_BARRIER_LOAD(&g_memory_counters.total_allocs_relative);
- counters.total_allocs_absolute =
- NO_BARRIER_LOAD(&g_memory_counters.total_allocs_absolute);
- return counters;
-}
-
-namespace grpc_core {
-namespace testing {
-
-LeakDetector::LeakDetector(bool enable) : enabled_(enable) {
- if (enabled_) {
- grpc_memory_counters_init();
- }
-}
-
-LeakDetector::~LeakDetector() {
- // Wait for grpc_shutdown() to finish its async work.
- grpc_maybe_wait_for_async_shutdown();
- if (enabled_) {
- struct grpc_memory_counters counters = grpc_memory_counters_snapshot();
- if (counters.total_size_relative != 0) {
- gpr_log(GPR_ERROR, "Leaking %" PRIuPTR " bytes",
- static_cast<uintptr_t>(counters.total_size_relative));
- GPR_ASSERT(0);
- }
- grpc_memory_counters_destroy();
- }
-}
-
-} // namespace testing
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <inttypes.h>
+#include <stdint.h>
+#include <string.h>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/gpr/alloc.h"
+#include "src/core/lib/surface/init.h"
+#include "test/core/util/memory_counters.h"
+
+#include <stdio.h>
+
+static struct grpc_memory_counters g_memory_counters;
+static bool g_memory_counter_enabled;
+
+#ifdef GPR_LOW_LEVEL_COUNTERS
+/* hide these from the microbenchmark atomic stats */
+#define NO_BARRIER_FETCH_ADD(x, sz) \
+ __atomic_fetch_add((x), (sz), __ATOMIC_RELAXED)
+#define NO_BARRIER_LOAD(x) __atomic_load_n((x), __ATOMIC_RELAXED)
+#else
+#define NO_BARRIER_FETCH_ADD(x, sz) gpr_atm_no_barrier_fetch_add(x, sz)
+#define NO_BARRIER_LOAD(x) gpr_atm_no_barrier_load(x)
+#endif
+
+// Memory counter uses --wrap=symbol feature from ld. To use this,
+// `GPR_WRAP_MEMORY_COUNTER` needs to be defined. following options should be
+// passed to the compiler.
+// -Wl,--wrap=malloc -Wl,--wrap=calloc -Wl,--wrap=realloc -Wl,--wrap=free
+// * Reference: https://linux.die.net/man/1/ld)
+#if GPR_WRAP_MEMORY_COUNTER
+
+extern "C" {
+void* __real_malloc(size_t size);
+void* __real_calloc(size_t size);
+void* __real_realloc(void* ptr, size_t size);
+void __real_free(void* ptr);
+
+void* __wrap_malloc(size_t size);
+void* __wrap_calloc(size_t size);
+void* __wrap_realloc(void* ptr, size_t size);
+void __wrap_free(void* ptr);
+}
+
+void* __wrap_malloc(size_t size) {
+ if (!size) return nullptr;
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1);
+ void* ptr =
+ __real_malloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size);
+ *static_cast<size_t*>(ptr) = size;
+ return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
+}
+
+void* __wrap_calloc(size_t size) {
+ if (!size) return nullptr;
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1);
+ void* ptr =
+ __real_calloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size);
+ *static_cast<size_t*>(ptr) = size;
+ return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
+}
+
+void* __wrap_realloc(void* ptr, size_t size) {
+ if (ptr == nullptr) {
+ return __wrap_malloc(size);
+ }
+ if (size == 0) {
+ __wrap_free(ptr);
+ return nullptr;
+ }
+ void* rptr =
+ static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative,
+ -*static_cast<gpr_atm*>(rptr));
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size);
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1);
+ void* new_ptr =
+ __real_realloc(rptr, GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size);
+ *static_cast<size_t*>(new_ptr) = size;
+ return static_cast<char*>(new_ptr) +
+ GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size));
+}
+
+void __wrap_free(void* ptr) {
+ if (ptr == nullptr) return;
+ void* rptr =
+ static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size_t));
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative,
+ -*static_cast<gpr_atm*>(rptr));
+ NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, -(gpr_atm)1);
+ __real_free(rptr);
+}
+
+#endif // GPR_WRAP_MEMORY_COUNTER
+
+void grpc_memory_counters_init() {
+ memset(&g_memory_counters, 0, sizeof(g_memory_counters));
+ g_memory_counter_enabled = true;
+}
+
+void grpc_memory_counters_destroy() { g_memory_counter_enabled = false; }
+
+struct grpc_memory_counters grpc_memory_counters_snapshot() {
+ struct grpc_memory_counters counters;
+ counters.total_size_relative =
+ NO_BARRIER_LOAD(&g_memory_counters.total_size_relative);
+ counters.total_size_absolute =
+ NO_BARRIER_LOAD(&g_memory_counters.total_size_absolute);
+ counters.total_allocs_relative =
+ NO_BARRIER_LOAD(&g_memory_counters.total_allocs_relative);
+ counters.total_allocs_absolute =
+ NO_BARRIER_LOAD(&g_memory_counters.total_allocs_absolute);
+ return counters;
+}
+
+namespace grpc_core {
+namespace testing {
+
+LeakDetector::LeakDetector(bool enable) : enabled_(enable) {
+ if (enabled_) {
+ grpc_memory_counters_init();
+ }
+}
+
+LeakDetector::~LeakDetector() {
+ // Wait for grpc_shutdown() to finish its async work.
+ grpc_maybe_wait_for_async_shutdown();
+ if (enabled_) {
+ struct grpc_memory_counters counters = grpc_memory_counters_snapshot();
+ if (counters.total_size_relative != 0) {
+ gpr_log(GPR_ERROR, "Leaking %" PRIuPTR " bytes",
+ static_cast<uintptr_t>(counters.total_size_relative));
+ GPR_ASSERT(0);
+ }
+ grpc_memory_counters_destroy();
+ }
+}
+
+} // namespace testing
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/test/core/util/memory_counters.h b/contrib/libs/grpc/test/core/util/memory_counters.h
index c92a001ff1..bb4100032d 100644
--- a/contrib/libs/grpc/test/core/util/memory_counters.h
+++ b/contrib/libs/grpc/test/core/util/memory_counters.h
@@ -1,53 +1,53 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H
-#define GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H
-
-#include <grpc/support/atm.h>
-
-struct grpc_memory_counters {
- gpr_atm total_size_relative;
- gpr_atm total_size_absolute;
- gpr_atm total_allocs_relative;
- gpr_atm total_allocs_absolute;
-};
-
-void grpc_memory_counters_init();
-void grpc_memory_counters_destroy();
-struct grpc_memory_counters grpc_memory_counters_snapshot();
-
-namespace grpc_core {
-namespace testing {
-
-// At destruction time, it will check there is no memory leak.
-// The object should be created before grpc_init() is called and destroyed after
-// grpc_shutdown() is returned.
-class LeakDetector {
- public:
- explicit LeakDetector(bool enable);
- ~LeakDetector();
-
- private:
- const bool enabled_;
-};
-
-} // namespace testing
-} // namespace grpc_core
-
-#endif
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H
+#define GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H
+
+#include <grpc/support/atm.h>
+
+struct grpc_memory_counters {
+ gpr_atm total_size_relative;
+ gpr_atm total_size_absolute;
+ gpr_atm total_allocs_relative;
+ gpr_atm total_allocs_absolute;
+};
+
+void grpc_memory_counters_init();
+void grpc_memory_counters_destroy();
+struct grpc_memory_counters grpc_memory_counters_snapshot();
+
+namespace grpc_core {
+namespace testing {
+
+// At destruction time, it will check there is no memory leak.
+// The object should be created before grpc_init() is called and destroyed after
+// grpc_shutdown() is returned.
+class LeakDetector {
+ public:
+ explicit LeakDetector(bool enable);
+ ~LeakDetector();
+
+ private:
+ const bool enabled_;
+};
+
+} // namespace testing
+} // namespace grpc_core
+
+#endif
diff --git a/contrib/libs/grpc/test/core/util/mock_endpoint.cc b/contrib/libs/grpc/test/core/util/mock_endpoint.cc
index 3c2d6a3f8b..6191adee89 100644
--- a/contrib/libs/grpc/test/core/util/mock_endpoint.cc
+++ b/contrib/libs/grpc/test/core/util/mock_endpoint.cc
@@ -1,155 +1,155 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when
- using that endpoint. Because of various transitive includes in uv.h,
- including windows.h on Windows, uv.h must be included before other system
- headers. Therefore, sockaddr.h must always be included first */
-#include "src/core/lib/iomgr/sockaddr.h"
-
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when
+ using that endpoint. Because of various transitive includes in uv.h,
+ including windows.h on Windows, uv.h must be included before other system
+ headers. Therefore, sockaddr.h must always be included first */
+#include "src/core/lib/iomgr/sockaddr.h"
+
#include <inttypes.h>
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-#include "test/core/util/mock_endpoint.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include "src/core/lib/iomgr/sockaddr.h"
-
-typedef struct mock_endpoint {
- grpc_endpoint base;
- gpr_mu mu;
- void (*on_write)(grpc_slice slice);
- grpc_slice_buffer read_buffer;
- grpc_slice_buffer* on_read_out;
- grpc_closure* on_read;
- grpc_resource_user* resource_user;
-} mock_endpoint;
-
-static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool /*urgent*/) {
- mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
- gpr_mu_lock(&m->mu);
- if (m->read_buffer.count > 0) {
- grpc_slice_buffer_swap(&m->read_buffer, slices);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
- } else {
- m->on_read = cb;
- m->on_read_out = slices;
- }
- gpr_mu_unlock(&m->mu);
-}
-
-static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, void* /*arg*/) {
- mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
- for (size_t i = 0; i < slices->count; i++) {
- m->on_write(slices->slices[i]);
- }
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
-}
-
-static void me_add_to_pollset(grpc_endpoint* /*ep*/,
- grpc_pollset* /*pollset*/) {}
-
-static void me_add_to_pollset_set(grpc_endpoint* /*ep*/,
- grpc_pollset_set* /*pollset*/) {}
-
-static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/,
- grpc_pollset_set* /*pollset*/) {}
-
-static void me_shutdown(grpc_endpoint* ep, grpc_error* why) {
- mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
- gpr_mu_lock(&m->mu);
- if (m->on_read) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Endpoint Shutdown", &why, 1));
- m->on_read = nullptr;
- }
- gpr_mu_unlock(&m->mu);
- grpc_resource_user_shutdown(m->resource_user);
- GRPC_ERROR_UNREF(why);
-}
-
-static void me_destroy(grpc_endpoint* ep) {
- mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
- grpc_slice_buffer_destroy(&m->read_buffer);
- grpc_resource_user_unref(m->resource_user);
- gpr_mu_destroy(&m->mu);
- gpr_free(m);
-}
-
+#include "test/core/util/mock_endpoint.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/iomgr/sockaddr.h"
+
+typedef struct mock_endpoint {
+ grpc_endpoint base;
+ gpr_mu mu;
+ void (*on_write)(grpc_slice slice);
+ grpc_slice_buffer read_buffer;
+ grpc_slice_buffer* on_read_out;
+ grpc_closure* on_read;
+ grpc_resource_user* resource_user;
+} mock_endpoint;
+
+static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
+ grpc_closure* cb, bool /*urgent*/) {
+ mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
+ gpr_mu_lock(&m->mu);
+ if (m->read_buffer.count > 0) {
+ grpc_slice_buffer_swap(&m->read_buffer, slices);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
+ } else {
+ m->on_read = cb;
+ m->on_read_out = slices;
+ }
+ gpr_mu_unlock(&m->mu);
+}
+
+static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
+ grpc_closure* cb, void* /*arg*/) {
+ mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
+ for (size_t i = 0; i < slices->count; i++) {
+ m->on_write(slices->slices[i]);
+ }
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
+}
+
+static void me_add_to_pollset(grpc_endpoint* /*ep*/,
+ grpc_pollset* /*pollset*/) {}
+
+static void me_add_to_pollset_set(grpc_endpoint* /*ep*/,
+ grpc_pollset_set* /*pollset*/) {}
+
+static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/,
+ grpc_pollset_set* /*pollset*/) {}
+
+static void me_shutdown(grpc_endpoint* ep, grpc_error* why) {
+ mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
+ gpr_mu_lock(&m->mu);
+ if (m->on_read) {
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Endpoint Shutdown", &why, 1));
+ m->on_read = nullptr;
+ }
+ gpr_mu_unlock(&m->mu);
+ grpc_resource_user_shutdown(m->resource_user);
+ GRPC_ERROR_UNREF(why);
+}
+
+static void me_destroy(grpc_endpoint* ep) {
+ mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
+ grpc_slice_buffer_destroy(&m->read_buffer);
+ grpc_resource_user_unref(m->resource_user);
+ gpr_mu_destroy(&m->mu);
+ gpr_free(m);
+}
+
static y_absl::string_view me_get_peer(grpc_endpoint* /*ep*/) {
return "fake:mock_endpoint";
-}
-
+}
+
static y_absl::string_view me_get_local_address(grpc_endpoint* /*ep*/) {
return "fake:mock_endpoint";
}
-static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) {
- mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
- return m->resource_user;
-}
-
-static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; }
-
-static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; }
-
-static const grpc_endpoint_vtable vtable = {me_read,
- me_write,
- me_add_to_pollset,
- me_add_to_pollset_set,
- me_delete_from_pollset_set,
- me_shutdown,
- me_destroy,
- me_get_resource_user,
- me_get_peer,
+static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) {
+ mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
+ return m->resource_user;
+}
+
+static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; }
+
+static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; }
+
+static const grpc_endpoint_vtable vtable = {me_read,
+ me_write,
+ me_add_to_pollset,
+ me_add_to_pollset_set,
+ me_delete_from_pollset_set,
+ me_shutdown,
+ me_destroy,
+ me_get_resource_user,
+ me_get_peer,
me_get_local_address,
- me_get_fd,
- me_can_track_err};
-
-grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice),
- grpc_resource_quota* resource_quota) {
- mock_endpoint* m = static_cast<mock_endpoint*>(gpr_malloc(sizeof(*m)));
- m->base.vtable = &vtable;
+ me_get_fd,
+ me_can_track_err};
+
+grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice),
+ grpc_resource_quota* resource_quota) {
+ mock_endpoint* m = static_cast<mock_endpoint*>(gpr_malloc(sizeof(*m)));
+ m->base.vtable = &vtable;
TString name = y_absl::StrFormat("mock_endpoint_%" PRIxPTR, (intptr_t)m);
m->resource_user = grpc_resource_user_create(resource_quota, name.c_str());
- grpc_slice_buffer_init(&m->read_buffer);
- gpr_mu_init(&m->mu);
- m->on_write = on_write;
- m->on_read = nullptr;
- return &m->base;
-}
-
-void grpc_mock_endpoint_put_read(grpc_endpoint* ep, grpc_slice slice) {
- mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
- gpr_mu_lock(&m->mu);
- if (m->on_read != nullptr) {
- grpc_slice_buffer_add(m->on_read_out, slice);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE);
- m->on_read = nullptr;
- } else {
- grpc_slice_buffer_add(&m->read_buffer, slice);
- }
- gpr_mu_unlock(&m->mu);
-}
+ grpc_slice_buffer_init(&m->read_buffer);
+ gpr_mu_init(&m->mu);
+ m->on_write = on_write;
+ m->on_read = nullptr;
+ return &m->base;
+}
+
+void grpc_mock_endpoint_put_read(grpc_endpoint* ep, grpc_slice slice) {
+ mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep);
+ gpr_mu_lock(&m->mu);
+ if (m->on_read != nullptr) {
+ grpc_slice_buffer_add(m->on_read_out, slice);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE);
+ m->on_read = nullptr;
+ } else {
+ grpc_slice_buffer_add(&m->read_buffer, slice);
+ }
+ gpr_mu_unlock(&m->mu);
+}
diff --git a/contrib/libs/grpc/test/core/util/mock_endpoint.h b/contrib/libs/grpc/test/core/util/mock_endpoint.h
index 6521d3e8e8..1d63c36256 100644
--- a/contrib/libs/grpc/test/core/util/mock_endpoint.h
+++ b/contrib/libs/grpc/test/core/util/mock_endpoint.h
@@ -1,29 +1,29 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef MOCK_ENDPOINT_H
-#define MOCK_ENDPOINT_H
-
-#include "src/core/lib/iomgr/endpoint.h"
-
-grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice),
- grpc_resource_quota* resource_quota);
-void grpc_mock_endpoint_put_read(grpc_endpoint* mock_endpoint,
- grpc_slice slice);
-
-#endif
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef MOCK_ENDPOINT_H
+#define MOCK_ENDPOINT_H
+
+#include "src/core/lib/iomgr/endpoint.h"
+
+grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice),
+ grpc_resource_quota* resource_quota);
+void grpc_mock_endpoint_put_read(grpc_endpoint* mock_endpoint,
+ grpc_slice slice);
+
+#endif
diff --git a/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc b/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc
index 2f376d6853..564dacad9a 100644
--- a/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc
+++ b/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc
@@ -1,48 +1,48 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <stdbool.h>
-
-#include <grpc/grpc.h>
-
-#include <grpc/support/log.h>
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/load_file.h"
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
-
-extern bool squelch;
-extern bool leak_check;
-
-int main(int argc, char** argv) {
- grpc_slice buffer;
- squelch = false;
- leak_check = false;
- /* TODO(yashkt) Calling grpc_init breaks tests. Fix the tests and replace
- * grpc_core::ExecCtx::GlobalInit with grpc_init and GlobalShutdown with
- * grpc_shutdown */
- GPR_ASSERT(argc > 1); /* Make sure that we have a filename argument */
- GPR_ASSERT(
- GRPC_LOG_IF_ERROR("load_file", grpc_load_file(argv[1], 0, &buffer)));
- LLVMFuzzerTestOneInput(GRPC_SLICE_START_PTR(buffer),
- GRPC_SLICE_LENGTH(buffer));
- grpc_core::ExecCtx::GlobalInit();
- grpc_slice_unref(buffer);
- grpc_core::ExecCtx::GlobalShutdown();
- return 0;
-}
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <stdbool.h>
+
+#include <grpc/grpc.h>
+
+#include <grpc/support/log.h>
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/load_file.h"
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
+
+extern bool squelch;
+extern bool leak_check;
+
+int main(int argc, char** argv) {
+ grpc_slice buffer;
+ squelch = false;
+ leak_check = false;
+ /* TODO(yashkt) Calling grpc_init breaks tests. Fix the tests and replace
+ * grpc_core::ExecCtx::GlobalInit with grpc_init and GlobalShutdown with
+ * grpc_shutdown */
+ GPR_ASSERT(argc > 1); /* Make sure that we have a filename argument */
+ GPR_ASSERT(
+ GRPC_LOG_IF_ERROR("load_file", grpc_load_file(argv[1], 0, &buffer)));
+ LLVMFuzzerTestOneInput(GRPC_SLICE_START_PTR(buffer),
+ GRPC_SLICE_LENGTH(buffer));
+ grpc_core::ExecCtx::GlobalInit();
+ grpc_slice_unref(buffer);
+ grpc_core::ExecCtx::GlobalShutdown();
+ return 0;
+}
diff --git a/contrib/libs/grpc/test/core/util/parse_hexstring.cc b/contrib/libs/grpc/test/core/util/parse_hexstring.cc
index cd64843bd3..a4830e87fc 100644
--- a/contrib/libs/grpc/test/core/util/parse_hexstring.cc
+++ b/contrib/libs/grpc/test/core/util/parse_hexstring.cc
@@ -1,56 +1,56 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/parse_hexstring.h"
-#include <grpc/support/log.h>
-
-grpc_slice parse_hexstring(const char* hexstring) {
- size_t nibbles = 0;
- const char* p = nullptr;
- uint8_t* out;
- uint8_t temp;
- grpc_slice slice;
-
- for (p = hexstring; *p; p++) {
- nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f');
- }
-
- GPR_ASSERT((nibbles & 1) == 0);
-
- slice = grpc_slice_malloc(nibbles / 2);
- out = GRPC_SLICE_START_PTR(slice);
-
- nibbles = 0;
- temp = 0;
- for (p = hexstring; *p; p++) {
- if (*p >= '0' && *p <= '9') {
- temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0');
- nibbles++;
- } else if (*p >= 'a' && *p <= 'f') {
- temp =
- static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10);
- nibbles++;
- }
- if (nibbles == 2) {
- *out++ = temp;
- nibbles = 0;
- }
- }
-
- return slice;
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/parse_hexstring.h"
+#include <grpc/support/log.h>
+
+grpc_slice parse_hexstring(const char* hexstring) {
+ size_t nibbles = 0;
+ const char* p = nullptr;
+ uint8_t* out;
+ uint8_t temp;
+ grpc_slice slice;
+
+ for (p = hexstring; *p; p++) {
+ nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f');
+ }
+
+ GPR_ASSERT((nibbles & 1) == 0);
+
+ slice = grpc_slice_malloc(nibbles / 2);
+ out = GRPC_SLICE_START_PTR(slice);
+
+ nibbles = 0;
+ temp = 0;
+ for (p = hexstring; *p; p++) {
+ if (*p >= '0' && *p <= '9') {
+ temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0');
+ nibbles++;
+ } else if (*p >= 'a' && *p <= 'f') {
+ temp =
+ static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10);
+ nibbles++;
+ }
+ if (nibbles == 2) {
+ *out++ = temp;
+ nibbles = 0;
+ }
+ }
+
+ return slice;
+}
diff --git a/contrib/libs/grpc/test/core/util/parse_hexstring.h b/contrib/libs/grpc/test/core/util/parse_hexstring.h
index b7d54c1711..0c0419461e 100644
--- a/contrib/libs/grpc/test/core/util/parse_hexstring.h
+++ b/contrib/libs/grpc/test/core/util/parse_hexstring.h
@@ -1,26 +1,26 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H
-#define GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H
-
-#include <grpc/slice.h>
-
-grpc_slice parse_hexstring(const char* hexstring);
-
-#endif /* GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H
+#define GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H
+
+#include <grpc/slice.h>
+
+grpc_slice parse_hexstring(const char* hexstring);
+
+#endif /* GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H */
diff --git a/contrib/libs/grpc/test/core/util/passthru_endpoint.cc b/contrib/libs/grpc/test/core/util/passthru_endpoint.cc
index a5baafad02..f2224260af 100644
--- a/contrib/libs/grpc/test/core/util/passthru_endpoint.cc
+++ b/contrib/libs/grpc/test/core/util/passthru_endpoint.cc
@@ -1,164 +1,164 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when
- using that endpoint. Because of various transitive includes in uv.h,
- including windows.h on Windows, uv.h must be included before other system
- headers. Therefore, sockaddr.h must always be included first */
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include "test/core/util/passthru_endpoint.h"
-
-#include <inttypes.h>
-#include <string.h>
-
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when
+ using that endpoint. Because of various transitive includes in uv.h,
+ including windows.h on Windows, uv.h must be included before other system
+ headers. Therefore, sockaddr.h must always be included first */
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include "test/core/util/passthru_endpoint.h"
+
+#include <inttypes.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include "src/core/lib/slice/slice_internal.h"
-
-typedef struct passthru_endpoint passthru_endpoint;
-
-typedef struct {
- grpc_endpoint base;
- passthru_endpoint* parent;
- grpc_slice_buffer read_buffer;
- grpc_slice_buffer* on_read_out;
- grpc_closure* on_read;
- grpc_resource_user* resource_user;
-} half;
-
-struct passthru_endpoint {
- gpr_mu mu;
- int halves;
- grpc_passthru_endpoint_stats* stats;
- bool shutdown;
- half client;
- half server;
-};
-
-static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool /*urgent*/) {
- half* m = reinterpret_cast<half*>(ep);
- gpr_mu_lock(&m->parent->mu);
- if (m->parent->shutdown) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, cb,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Already shutdown"));
- } else if (m->read_buffer.count > 0) {
- grpc_slice_buffer_swap(&m->read_buffer, slices);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
- } else {
- m->on_read = cb;
- m->on_read_out = slices;
- }
- gpr_mu_unlock(&m->parent->mu);
-}
-
-static half* other_half(half* h) {
- if (h == &h->parent->client) return &h->parent->server;
- return &h->parent->client;
-}
-
-static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, void* /*arg*/) {
- half* m = other_half(reinterpret_cast<half*>(ep));
- gpr_mu_lock(&m->parent->mu);
- grpc_error* error = GRPC_ERROR_NONE;
- gpr_atm_no_barrier_fetch_add(&m->parent->stats->num_writes, (gpr_atm)1);
- if (m->parent->shutdown) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown");
- } else if (m->on_read != nullptr) {
- for (size_t i = 0; i < slices->count; i++) {
- grpc_slice_buffer_add(m->on_read_out, grpc_slice_copy(slices->slices[i]));
- }
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE);
- m->on_read = nullptr;
- } else {
- for (size_t i = 0; i < slices->count; i++) {
- grpc_slice_buffer_add(&m->read_buffer,
- grpc_slice_copy(slices->slices[i]));
- }
- }
- gpr_mu_unlock(&m->parent->mu);
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
-}
-
-static void me_add_to_pollset(grpc_endpoint* /*ep*/,
- grpc_pollset* /*pollset*/) {}
-
-static void me_add_to_pollset_set(grpc_endpoint* /*ep*/,
- grpc_pollset_set* /*pollset*/) {}
-
-static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/,
- grpc_pollset_set* /*pollset*/) {}
-
-static void me_shutdown(grpc_endpoint* ep, grpc_error* why) {
- half* m = reinterpret_cast<half*>(ep);
- gpr_mu_lock(&m->parent->mu);
- m->parent->shutdown = true;
- if (m->on_read) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, m->on_read,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1));
- m->on_read = nullptr;
- }
- m = other_half(m);
- if (m->on_read) {
- grpc_core::ExecCtx::Run(
- DEBUG_LOCATION, m->on_read,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1));
- m->on_read = nullptr;
- }
- gpr_mu_unlock(&m->parent->mu);
- grpc_resource_user_shutdown(m->resource_user);
- GRPC_ERROR_UNREF(why);
-}
-
-static void me_destroy(grpc_endpoint* ep) {
- passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent;
- gpr_mu_lock(&p->mu);
- if (0 == --p->halves) {
- gpr_mu_unlock(&p->mu);
- gpr_mu_destroy(&p->mu);
- grpc_passthru_endpoint_stats_destroy(p->stats);
- grpc_slice_buffer_destroy_internal(&p->client.read_buffer);
- grpc_slice_buffer_destroy_internal(&p->server.read_buffer);
- grpc_resource_user_unref(p->client.resource_user);
- grpc_resource_user_unref(p->server.resource_user);
- gpr_free(p);
- } else {
- gpr_mu_unlock(&p->mu);
- }
-}
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include "src/core/lib/slice/slice_internal.h"
+
+typedef struct passthru_endpoint passthru_endpoint;
+
+typedef struct {
+ grpc_endpoint base;
+ passthru_endpoint* parent;
+ grpc_slice_buffer read_buffer;
+ grpc_slice_buffer* on_read_out;
+ grpc_closure* on_read;
+ grpc_resource_user* resource_user;
+} half;
+
+struct passthru_endpoint {
+ gpr_mu mu;
+ int halves;
+ grpc_passthru_endpoint_stats* stats;
+ bool shutdown;
+ half client;
+ half server;
+};
+
+static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
+ grpc_closure* cb, bool /*urgent*/) {
+ half* m = reinterpret_cast<half*>(ep);
+ gpr_mu_lock(&m->parent->mu);
+ if (m->parent->shutdown) {
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, cb,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Already shutdown"));
+ } else if (m->read_buffer.count > 0) {
+ grpc_slice_buffer_swap(&m->read_buffer, slices);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE);
+ } else {
+ m->on_read = cb;
+ m->on_read_out = slices;
+ }
+ gpr_mu_unlock(&m->parent->mu);
+}
+
+static half* other_half(half* h) {
+ if (h == &h->parent->client) return &h->parent->server;
+ return &h->parent->client;
+}
+
+static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
+ grpc_closure* cb, void* /*arg*/) {
+ half* m = other_half(reinterpret_cast<half*>(ep));
+ gpr_mu_lock(&m->parent->mu);
+ grpc_error* error = GRPC_ERROR_NONE;
+ gpr_atm_no_barrier_fetch_add(&m->parent->stats->num_writes, (gpr_atm)1);
+ if (m->parent->shutdown) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown");
+ } else if (m->on_read != nullptr) {
+ for (size_t i = 0; i < slices->count; i++) {
+ grpc_slice_buffer_add(m->on_read_out, grpc_slice_copy(slices->slices[i]));
+ }
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE);
+ m->on_read = nullptr;
+ } else {
+ for (size_t i = 0; i < slices->count; i++) {
+ grpc_slice_buffer_add(&m->read_buffer,
+ grpc_slice_copy(slices->slices[i]));
+ }
+ }
+ gpr_mu_unlock(&m->parent->mu);
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
+}
+
+static void me_add_to_pollset(grpc_endpoint* /*ep*/,
+ grpc_pollset* /*pollset*/) {}
+
+static void me_add_to_pollset_set(grpc_endpoint* /*ep*/,
+ grpc_pollset_set* /*pollset*/) {}
+
+static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/,
+ grpc_pollset_set* /*pollset*/) {}
+
+static void me_shutdown(grpc_endpoint* ep, grpc_error* why) {
+ half* m = reinterpret_cast<half*>(ep);
+ gpr_mu_lock(&m->parent->mu);
+ m->parent->shutdown = true;
+ if (m->on_read) {
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, m->on_read,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1));
+ m->on_read = nullptr;
+ }
+ m = other_half(m);
+ if (m->on_read) {
+ grpc_core::ExecCtx::Run(
+ DEBUG_LOCATION, m->on_read,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1));
+ m->on_read = nullptr;
+ }
+ gpr_mu_unlock(&m->parent->mu);
+ grpc_resource_user_shutdown(m->resource_user);
+ GRPC_ERROR_UNREF(why);
+}
+
+static void me_destroy(grpc_endpoint* ep) {
+ passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent;
+ gpr_mu_lock(&p->mu);
+ if (0 == --p->halves) {
+ gpr_mu_unlock(&p->mu);
+ gpr_mu_destroy(&p->mu);
+ grpc_passthru_endpoint_stats_destroy(p->stats);
+ grpc_slice_buffer_destroy_internal(&p->client.read_buffer);
+ grpc_slice_buffer_destroy_internal(&p->server.read_buffer);
+ grpc_resource_user_unref(p->client.resource_user);
+ grpc_resource_user_unref(p->server.resource_user);
+ gpr_free(p);
+ } else {
+ gpr_mu_unlock(&p->mu);
+ }
+}
+
static y_absl::string_view me_get_peer(grpc_endpoint* ep) {
- passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent;
- return (reinterpret_cast<half*>(ep)) == &p->client
+ passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent;
+ return (reinterpret_cast<half*>(ep)) == &p->client
? "fake:mock_client_endpoint"
: "fake:mock_server_endpoint";
-}
-
+}
+
static y_absl::string_view me_get_local_address(grpc_endpoint* ep) {
passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent;
return (reinterpret_cast<half*>(ep)) == &p->client
@@ -166,74 +166,74 @@ static y_absl::string_view me_get_local_address(grpc_endpoint* ep) {
: "fake:mock_server_endpoint";
}
-static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; }
-
-static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; }
-
-static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) {
- half* m = reinterpret_cast<half*>(ep);
- return m->resource_user;
-}
-
-static const grpc_endpoint_vtable vtable = {
- me_read,
- me_write,
- me_add_to_pollset,
- me_add_to_pollset_set,
- me_delete_from_pollset_set,
- me_shutdown,
- me_destroy,
- me_get_resource_user,
- me_get_peer,
+static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; }
+
+static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; }
+
+static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) {
+ half* m = reinterpret_cast<half*>(ep);
+ return m->resource_user;
+}
+
+static const grpc_endpoint_vtable vtable = {
+ me_read,
+ me_write,
+ me_add_to_pollset,
+ me_add_to_pollset_set,
+ me_delete_from_pollset_set,
+ me_shutdown,
+ me_destroy,
+ me_get_resource_user,
+ me_get_peer,
me_get_local_address,
- me_get_fd,
- me_can_track_err,
-};
-
-static void half_init(half* m, passthru_endpoint* parent,
- grpc_resource_quota* resource_quota,
- const char* half_name) {
- m->base.vtable = &vtable;
- m->parent = parent;
- grpc_slice_buffer_init(&m->read_buffer);
- m->on_read = nullptr;
+ me_get_fd,
+ me_can_track_err,
+};
+
+static void half_init(half* m, passthru_endpoint* parent,
+ grpc_resource_quota* resource_quota,
+ const char* half_name) {
+ m->base.vtable = &vtable;
+ m->parent = parent;
+ grpc_slice_buffer_init(&m->read_buffer);
+ m->on_read = nullptr;
TString name = y_absl::StrFormat("passthru_endpoint_%s_%" PRIxPTR,
half_name, (intptr_t)parent);
m->resource_user = grpc_resource_user_create(resource_quota, name.c_str());
-}
-
-void grpc_passthru_endpoint_create(grpc_endpoint** client,
- grpc_endpoint** server,
- grpc_resource_quota* resource_quota,
- grpc_passthru_endpoint_stats* stats) {
- passthru_endpoint* m =
- static_cast<passthru_endpoint*>(gpr_malloc(sizeof(*m)));
- m->halves = 2;
- m->shutdown = 0;
- if (stats == nullptr) {
- m->stats = grpc_passthru_endpoint_stats_create();
- } else {
- gpr_ref(&stats->refs);
- m->stats = stats;
- }
- half_init(&m->client, m, resource_quota, "client");
- half_init(&m->server, m, resource_quota, "server");
- gpr_mu_init(&m->mu);
- *client = &m->client.base;
- *server = &m->server.base;
-}
-
-grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create() {
- grpc_passthru_endpoint_stats* stats =
- static_cast<grpc_passthru_endpoint_stats*>(
- gpr_malloc(sizeof(grpc_passthru_endpoint_stats)));
- memset(stats, 0, sizeof(*stats));
- gpr_ref_init(&stats->refs, 1);
- return stats;
-}
-
-void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats) {
- if (gpr_unref(&stats->refs)) {
- gpr_free(stats);
- }
-}
+}
+
+void grpc_passthru_endpoint_create(grpc_endpoint** client,
+ grpc_endpoint** server,
+ grpc_resource_quota* resource_quota,
+ grpc_passthru_endpoint_stats* stats) {
+ passthru_endpoint* m =
+ static_cast<passthru_endpoint*>(gpr_malloc(sizeof(*m)));
+ m->halves = 2;
+ m->shutdown = 0;
+ if (stats == nullptr) {
+ m->stats = grpc_passthru_endpoint_stats_create();
+ } else {
+ gpr_ref(&stats->refs);
+ m->stats = stats;
+ }
+ half_init(&m->client, m, resource_quota, "client");
+ half_init(&m->server, m, resource_quota, "server");
+ gpr_mu_init(&m->mu);
+ *client = &m->client.base;
+ *server = &m->server.base;
+}
+
+grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create() {
+ grpc_passthru_endpoint_stats* stats =
+ static_cast<grpc_passthru_endpoint_stats*>(
+ gpr_malloc(sizeof(grpc_passthru_endpoint_stats)));
+ memset(stats, 0, sizeof(*stats));
+ gpr_ref_init(&stats->refs, 1);
+ return stats;
+}
+
+void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats) {
+ if (gpr_unref(&stats->refs)) {
+ gpr_free(stats);
+ }
+}
diff --git a/contrib/libs/grpc/test/core/util/passthru_endpoint.h b/contrib/libs/grpc/test/core/util/passthru_endpoint.h
index a46c775505..039e5e0aa1 100644
--- a/contrib/libs/grpc/test/core/util/passthru_endpoint.h
+++ b/contrib/libs/grpc/test/core/util/passthru_endpoint.h
@@ -1,43 +1,43 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef MOCK_ENDPOINT_H
-#define MOCK_ENDPOINT_H
-
-#include <grpc/support/atm.h>
-
-#include "src/core/lib/iomgr/endpoint.h"
-
-/* The struct is refcounted, always use grpc_passthru_endpoint_stats_create and
- * grpc_passthru_endpoint_stats_destroy, rather then embedding it in your
- * objects by value. */
-typedef struct {
- gpr_refcount refs;
- gpr_atm num_writes;
-} grpc_passthru_endpoint_stats;
-
-void grpc_passthru_endpoint_create(grpc_endpoint** client,
- grpc_endpoint** server,
- grpc_resource_quota* resource_quota,
- grpc_passthru_endpoint_stats* stats);
-
-grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create();
-
-void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats);
-
-#endif
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef MOCK_ENDPOINT_H
+#define MOCK_ENDPOINT_H
+
+#include <grpc/support/atm.h>
+
+#include "src/core/lib/iomgr/endpoint.h"
+
+/* The struct is refcounted, always use grpc_passthru_endpoint_stats_create and
+ * grpc_passthru_endpoint_stats_destroy, rather then embedding it in your
+ * objects by value. */
+typedef struct {
+ gpr_refcount refs;
+ gpr_atm num_writes;
+} grpc_passthru_endpoint_stats;
+
+void grpc_passthru_endpoint_create(grpc_endpoint** client,
+ grpc_endpoint** server,
+ grpc_resource_quota* resource_quota,
+ grpc_passthru_endpoint_stats* stats);
+
+grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create();
+
+void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats);
+
+#endif
diff --git a/contrib/libs/grpc/test/core/util/port.cc b/contrib/libs/grpc/test/core/util/port.cc
index 5a34b6026f..936929fd66 100644
--- a/contrib/libs/grpc/test/core/util/port.cc
+++ b/contrib/libs/grpc/test/core/util/port.cc
@@ -1,143 +1,143 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "src/core/lib/iomgr/port.h"
-#include "test/core/util/test_config.h"
-#if defined(GRPC_TEST_PICK_PORT)
-
-#include "test/core/util/port.h"
-
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/http/httpcli.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "test/core/util/port_server_client.h"
-
-static int* chosen_ports = nullptr;
-static size_t num_chosen_ports = 0;
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "src/core/lib/iomgr/port.h"
+#include "test/core/util/test_config.h"
+#if defined(GRPC_TEST_PICK_PORT)
+
+#include "test/core/util/port.h"
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/http/httpcli.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "test/core/util/port_server_client.h"
+
+static int* chosen_ports = nullptr;
+static size_t num_chosen_ports = 0;
static grpc_core::Mutex* g_default_port_picker_mu;
static gpr_once g_default_port_picker_init = GPR_ONCE_INIT;
-
+
static void init_default_port_picker() {
g_default_port_picker_mu = new grpc_core::Mutex();
}
static int free_chosen_port_locked(int port) {
- size_t i;
- int found = 0;
- size_t found_at = 0;
- /* Find the port and erase it from the list, then tell the server it can be
- freed. */
- for (i = 0; i < num_chosen_ports; i++) {
- if (chosen_ports[i] == port) {
- GPR_ASSERT(found == 0);
- found = 1;
- found_at = i;
- }
- }
- if (found) {
- chosen_ports[found_at] = chosen_ports[num_chosen_ports - 1];
- num_chosen_ports--;
- grpc_free_port_using_server(port);
- }
- return found;
-}
-
-static void free_chosen_ports(void) {
+ size_t i;
+ int found = 0;
+ size_t found_at = 0;
+ /* Find the port and erase it from the list, then tell the server it can be
+ freed. */
+ for (i = 0; i < num_chosen_ports; i++) {
+ if (chosen_ports[i] == port) {
+ GPR_ASSERT(found == 0);
+ found = 1;
+ found_at = i;
+ }
+ }
+ if (found) {
+ chosen_ports[found_at] = chosen_ports[num_chosen_ports - 1];
+ num_chosen_ports--;
+ grpc_free_port_using_server(port);
+ }
+ return found;
+}
+
+static void free_chosen_ports(void) {
grpc_core::MutexLock lock(g_default_port_picker_mu);
- size_t i;
- grpc_init();
- for (i = 0; i < num_chosen_ports; i++) {
- grpc_free_port_using_server(chosen_ports[i]);
- }
- grpc_shutdown_blocking();
- gpr_free(chosen_ports);
-}
-
+ size_t i;
+ grpc_init();
+ for (i = 0; i < num_chosen_ports; i++) {
+ grpc_free_port_using_server(chosen_ports[i]);
+ }
+ grpc_shutdown_blocking();
+ gpr_free(chosen_ports);
+}
+
static void chose_port_locked(int port) {
- if (chosen_ports == nullptr) {
- atexit(free_chosen_ports);
- }
- num_chosen_ports++;
- chosen_ports = static_cast<int*>(
- gpr_realloc(chosen_ports, sizeof(int) * num_chosen_ports));
- chosen_ports[num_chosen_ports - 1] = port;
-}
-
-static int grpc_pick_unused_port_impl(void) {
+ if (chosen_ports == nullptr) {
+ atexit(free_chosen_ports);
+ }
+ num_chosen_ports++;
+ chosen_ports = static_cast<int*>(
+ gpr_realloc(chosen_ports, sizeof(int) * num_chosen_ports));
+ chosen_ports[num_chosen_ports - 1] = port;
+}
+
+static int grpc_pick_unused_port_impl(void) {
gpr_once_init(&g_default_port_picker_init, init_default_port_picker);
grpc_core::MutexLock lock(g_default_port_picker_mu);
- int port = grpc_pick_port_using_server();
- if (port != 0) {
+ int port = grpc_pick_port_using_server();
+ if (port != 0) {
chose_port_locked(port);
- }
-
- return port;
-}
-
-static int grpc_pick_unused_port_or_die_impl(void) {
- int port = grpc_pick_unused_port();
- if (port == 0) {
- fprintf(stderr,
- "gRPC tests require a helper port server to allocate ports used \n"
- "during the test.\n\n"
- "This server is not currently running.\n\n"
- "To start it, run tools/run_tests/start_port_server.py\n\n");
- exit(1);
- }
- return port;
-}
-
-static void grpc_recycle_unused_port_impl(int port) {
+ }
+
+ return port;
+}
+
+static int grpc_pick_unused_port_or_die_impl(void) {
+ int port = grpc_pick_unused_port();
+ if (port == 0) {
+ fprintf(stderr,
+ "gRPC tests require a helper port server to allocate ports used \n"
+ "during the test.\n\n"
+ "This server is not currently running.\n\n"
+ "To start it, run tools/run_tests/start_port_server.py\n\n");
+ exit(1);
+ }
+ return port;
+}
+
+static void grpc_recycle_unused_port_impl(int port) {
gpr_once_init(&g_default_port_picker_init, init_default_port_picker);
grpc_core::MutexLock lock(g_default_port_picker_mu);
GPR_ASSERT(free_chosen_port_locked(port));
-}
-
-static grpc_pick_port_functions g_pick_port_functions = {
- grpc_pick_unused_port_impl, grpc_pick_unused_port_or_die_impl,
- grpc_recycle_unused_port_impl};
-
-int grpc_pick_unused_port(void) {
- return g_pick_port_functions.pick_unused_port_fn();
-}
-
-int grpc_pick_unused_port_or_die(void) {
- return g_pick_port_functions.pick_unused_port_or_die_fn();
-}
-
-void grpc_recycle_unused_port(int port) {
- g_pick_port_functions.recycle_unused_port_fn(port);
-}
-
-void grpc_set_pick_port_functions(grpc_pick_port_functions functions) {
- GPR_ASSERT(functions.pick_unused_port_fn != nullptr);
- GPR_ASSERT(functions.pick_unused_port_or_die_fn != nullptr);
- GPR_ASSERT(functions.recycle_unused_port_fn != nullptr);
- g_pick_port_functions = functions;
-}
-
-#endif /* GRPC_TEST_PICK_PORT */
+}
+
+static grpc_pick_port_functions g_pick_port_functions = {
+ grpc_pick_unused_port_impl, grpc_pick_unused_port_or_die_impl,
+ grpc_recycle_unused_port_impl};
+
+int grpc_pick_unused_port(void) {
+ return g_pick_port_functions.pick_unused_port_fn();
+}
+
+int grpc_pick_unused_port_or_die(void) {
+ return g_pick_port_functions.pick_unused_port_or_die_fn();
+}
+
+void grpc_recycle_unused_port(int port) {
+ g_pick_port_functions.recycle_unused_port_fn(port);
+}
+
+void grpc_set_pick_port_functions(grpc_pick_port_functions functions) {
+ GPR_ASSERT(functions.pick_unused_port_fn != nullptr);
+ GPR_ASSERT(functions.pick_unused_port_or_die_fn != nullptr);
+ GPR_ASSERT(functions.recycle_unused_port_fn != nullptr);
+ g_pick_port_functions = functions;
+}
+
+#endif /* GRPC_TEST_PICK_PORT */
diff --git a/contrib/libs/grpc/test/core/util/port.h b/contrib/libs/grpc/test/core/util/port.h
index 3a4cf4467a..cf79445537 100644
--- a/contrib/libs/grpc/test/core/util/port.h
+++ b/contrib/libs/grpc/test/core/util/port.h
@@ -1,44 +1,44 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_PORT_H
-#define GRPC_TEST_CORE_UTIL_PORT_H
-
-typedef struct grpc_pick_port_functions {
- int (*pick_unused_port_fn)(void);
- int (*pick_unused_port_or_die_fn)(void);
- void (*recycle_unused_port_fn)(int port);
-} grpc_pick_port_functions;
-
-/* pick a port number that is currently unused by either tcp or udp. return
- 0 on failure. */
-int grpc_pick_unused_port(void);
-/* pick a port number that is currently unused by either tcp or udp. abort
- on failure. */
-int grpc_pick_unused_port_or_die(void);
-
-/* Return a port which was previously returned by grpc_pick_unused_port().
- * Implementations of grpc_pick_unused_port() backed by a portserver may limit
- * the total number of ports available; this lets a binary return its allocated
- * ports back to the server if it is going to allocate a large number. */
-void grpc_recycle_unused_port(int port);
-
-/** Request the family of pick_port functions in \a functions be used. */
-void grpc_set_pick_port_functions(grpc_pick_port_functions functions);
-
-#endif /* GRPC_TEST_CORE_UTIL_PORT_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_PORT_H
+#define GRPC_TEST_CORE_UTIL_PORT_H
+
+typedef struct grpc_pick_port_functions {
+ int (*pick_unused_port_fn)(void);
+ int (*pick_unused_port_or_die_fn)(void);
+ void (*recycle_unused_port_fn)(int port);
+} grpc_pick_port_functions;
+
+/* pick a port number that is currently unused by either tcp or udp. return
+ 0 on failure. */
+int grpc_pick_unused_port(void);
+/* pick a port number that is currently unused by either tcp or udp. abort
+ on failure. */
+int grpc_pick_unused_port_or_die(void);
+
+/* Return a port which was previously returned by grpc_pick_unused_port().
+ * Implementations of grpc_pick_unused_port() backed by a portserver may limit
+ * the total number of ports available; this lets a binary return its allocated
+ * ports back to the server if it is going to allocate a large number. */
+void grpc_recycle_unused_port(int port);
+
+/** Request the family of pick_port functions in \a functions be used. */
+void grpc_set_pick_port_functions(grpc_pick_port_functions functions);
+
+#endif /* GRPC_TEST_CORE_UTIL_PORT_H */
diff --git a/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc b/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc
index 5e043e7f97..7d0598cd81 100644
--- a/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc
+++ b/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc
@@ -1,56 +1,56 @@
-/*
- *
- * Copyright 2017 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.
- *
- */
-
-/* When individual tests run in an isolated runtime environment (e.g. each test
- * runs in a separate container) the framework takes a round-robin pick of a
- * port within certain range. There is no need to recycle ports.
- */
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <stdlib.h>
-#include "src/core/lib/iomgr/port.h"
-#include "test/core/util/test_config.h"
-#if defined(GRPC_PORT_ISOLATED_RUNTIME)
-
-#include "test/core/util/port.h"
-
-#define MIN_PORT 1025
-#define MAX_PORT 32766
-
-static int get_random_port_offset() {
- srand(gpr_now(GPR_CLOCK_REALTIME).tv_nsec);
- double rnd = static_cast<double>(rand()) /
- (static_cast<double>(RAND_MAX) + 1.0); // values from [0,1)
- return static_cast<int>(rnd * (MAX_PORT - MIN_PORT + 1));
-}
-
-static int s_initial_offset = get_random_port_offset();
-static gpr_atm s_pick_counter = 0;
-
+/*
+ *
+ * Copyright 2017 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.
+ *
+ */
+
+/* When individual tests run in an isolated runtime environment (e.g. each test
+ * runs in a separate container) the framework takes a round-robin pick of a
+ * port within certain range. There is no need to recycle ports.
+ */
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <stdlib.h>
+#include "src/core/lib/iomgr/port.h"
+#include "test/core/util/test_config.h"
+#if defined(GRPC_PORT_ISOLATED_RUNTIME)
+
+#include "test/core/util/port.h"
+
+#define MIN_PORT 1025
+#define MAX_PORT 32766
+
+static int get_random_port_offset() {
+ srand(gpr_now(GPR_CLOCK_REALTIME).tv_nsec);
+ double rnd = static_cast<double>(rand()) /
+ (static_cast<double>(RAND_MAX) + 1.0); // values from [0,1)
+ return static_cast<int>(rnd * (MAX_PORT - MIN_PORT + 1));
+}
+
+static int s_initial_offset = get_random_port_offset();
+static gpr_atm s_pick_counter = 0;
+
static int grpc_pick_unused_port_or_die_impl(void) {
- int orig_counter_val =
- static_cast<int>(gpr_atm_full_fetch_add(&s_pick_counter, 1));
- GPR_ASSERT(orig_counter_val < (MAX_PORT - MIN_PORT + 1));
- return MIN_PORT +
- (s_initial_offset + orig_counter_val) % (MAX_PORT - MIN_PORT + 1);
-}
-
+ int orig_counter_val =
+ static_cast<int>(gpr_atm_full_fetch_add(&s_pick_counter, 1));
+ GPR_ASSERT(orig_counter_val < (MAX_PORT - MIN_PORT + 1));
+ return MIN_PORT +
+ (s_initial_offset + orig_counter_val) % (MAX_PORT - MIN_PORT + 1);
+}
+
int grpc_pick_unused_port_or_die(void) {
while (true) {
int port = grpc_pick_unused_port_or_die_impl();
@@ -64,6 +64,6 @@ int grpc_pick_unused_port_or_die(void) {
}
}
-void grpc_recycle_unused_port(int port) { (void)port; }
-
-#endif /* GRPC_PORT_ISOLATED_RUNTIME */
+void grpc_recycle_unused_port(int port) { (void)port; }
+
+#endif /* GRPC_PORT_ISOLATED_RUNTIME */
diff --git a/contrib/libs/grpc/test/core/util/port_server_client.cc b/contrib/libs/grpc/test/core/util/port_server_client.cc
index 973068dcda..3f27a1687d 100644
--- a/contrib/libs/grpc/test/core/util/port_server_client.cc
+++ b/contrib/libs/grpc/test/core/util/port_server_client.cc
@@ -1,89 +1,89 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-#include "test/core/util/test_config.h"
-
-#ifdef GRPC_TEST_PICK_PORT
-#include "test/core/util/port_server_client.h"
-
-#include <math.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/http/httpcli.h"
-
-typedef struct freereq {
- gpr_mu* mu = nullptr;
- grpc_polling_entity pops = {};
- int done = 0;
-} freereq;
-
-static void destroy_pops_and_shutdown(void* p, grpc_error* /*error*/) {
- grpc_pollset* pollset =
- grpc_polling_entity_pollset(static_cast<grpc_polling_entity*>(p));
- grpc_pollset_destroy(pollset);
- gpr_free(pollset);
-}
-
-static void freed_port_from_server(void* arg, grpc_error* /*error*/) {
- freereq* pr = static_cast<freereq*>(arg);
- gpr_mu_lock(pr->mu);
- pr->done = 1;
- GRPC_LOG_IF_ERROR(
- "pollset_kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
- gpr_mu_unlock(pr->mu);
-}
-
-void grpc_free_port_using_server(int port) {
- grpc_httpcli_context context;
- grpc_httpcli_request req;
- grpc_httpcli_response rsp;
- freereq pr;
- char* path;
- grpc_closure* shutdown_closure;
-
- grpc_init();
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+#include "test/core/util/test_config.h"
+
+#ifdef GRPC_TEST_PICK_PORT
+#include "test/core/util/port_server_client.h"
+
+#include <math.h>
+#include <string.h>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/http/httpcli.h"
+
+typedef struct freereq {
+ gpr_mu* mu = nullptr;
+ grpc_polling_entity pops = {};
+ int done = 0;
+} freereq;
+
+static void destroy_pops_and_shutdown(void* p, grpc_error* /*error*/) {
+ grpc_pollset* pollset =
+ grpc_polling_entity_pollset(static_cast<grpc_polling_entity*>(p));
+ grpc_pollset_destroy(pollset);
+ gpr_free(pollset);
+}
+
+static void freed_port_from_server(void* arg, grpc_error* /*error*/) {
+ freereq* pr = static_cast<freereq*>(arg);
+ gpr_mu_lock(pr->mu);
+ pr->done = 1;
+ GRPC_LOG_IF_ERROR(
+ "pollset_kick",
+ grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
+ gpr_mu_unlock(pr->mu);
+}
+
+void grpc_free_port_using_server(int port) {
+ grpc_httpcli_context context;
+ grpc_httpcli_request req;
+ grpc_httpcli_response rsp;
+ freereq pr;
+ char* path;
+ grpc_closure* shutdown_closure;
+
+ grpc_init();
{
grpc_core::ExecCtx exec_ctx;
-
+
pr = {};
memset(&req, 0, sizeof(req));
rsp = {};
-
+
grpc_pollset* pollset =
static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
grpc_pollset_init(pollset, &pr.mu);
pr.pops = grpc_polling_entity_create_from_pollset(pollset);
shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,
grpc_schedule_on_exec_ctx);
-
+
req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
gpr_asprintf(&path, "/drop/%d", port);
req.http.path = path;
-
+
grpc_httpcli_context_init(&context);
grpc_resource_quota* resource_quota =
grpc_resource_quota_create("port_server_client/free");
@@ -104,153 +104,153 @@ void grpc_free_port_using_server(int port) {
grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {
pr.done = 1;
}
- }
+ }
gpr_mu_unlock(pr.mu);
-
+
grpc_httpcli_context_destroy(&context);
grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),
shutdown_closure);
-
+
gpr_free(path);
grpc_http_response_destroy(&rsp);
}
- grpc_shutdown();
-}
-
-typedef struct portreq {
- gpr_mu* mu = nullptr;
- grpc_polling_entity pops = {};
- int port = 0;
- int retries = 0;
- char* server = nullptr;
- grpc_httpcli_context* ctx = nullptr;
- grpc_httpcli_response response = {};
-} portreq;
-
-static void got_port_from_server(void* arg, grpc_error* error) {
- size_t i;
- int port = 0;
- portreq* pr = static_cast<portreq*>(arg);
- int failed = 0;
- grpc_httpcli_response* response = &pr->response;
-
- if (error != GRPC_ERROR_NONE) {
- failed = 1;
- const char* msg = grpc_error_string(error);
- gpr_log(GPR_DEBUG, "failed port pick from server: retrying [%s]", msg);
-
- } else if (response->status != 200) {
- failed = 1;
- gpr_log(GPR_DEBUG, "failed port pick from server: status=%d",
- response->status);
- }
-
- if (failed) {
- grpc_httpcli_request req;
- memset(&req, 0, sizeof(req));
- if (pr->retries >= 5) {
- gpr_mu_lock(pr->mu);
- pr->port = 0;
- GRPC_LOG_IF_ERROR(
- "pollset_kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
- gpr_mu_unlock(pr->mu);
- return;
- }
- GPR_ASSERT(pr->retries < 10);
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(
- static_cast<int64_t>(
- 1000.0 * (1 + pow(1.3, pr->retries) * rand() / RAND_MAX)),
- GPR_TIMESPAN)));
- pr->retries++;
- req.host = pr->server;
- req.http.path = const_cast<char*>("/get");
- grpc_http_response_destroy(&pr->response);
- pr->response = {};
- grpc_resource_quota* resource_quota =
- grpc_resource_quota_create("port_server_client/pick_retry");
- grpc_httpcli_get(pr->ctx, &pr->pops, resource_quota, &req,
- grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
- GRPC_CLOSURE_CREATE(got_port_from_server, pr,
- grpc_schedule_on_exec_ctx),
- &pr->response);
- grpc_resource_quota_unref_internal(resource_quota);
- return;
- }
- GPR_ASSERT(response);
- GPR_ASSERT(response->status == 200);
- for (i = 0; i < response->body_length; i++) {
- GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9');
- port = port * 10 + response->body[i] - '0';
- }
- GPR_ASSERT(port > 1024);
- gpr_mu_lock(pr->mu);
- pr->port = port;
- GRPC_LOG_IF_ERROR(
- "pollset_kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
- gpr_mu_unlock(pr->mu);
-}
-
-int grpc_pick_port_using_server(void) {
- grpc_httpcli_context context;
- grpc_httpcli_request req;
- portreq pr;
- grpc_closure* shutdown_closure;
-
- grpc_init();
- {
- grpc_core::ExecCtx exec_ctx;
- pr = {};
- memset(&req, 0, sizeof(req));
- grpc_pollset* pollset =
- static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
- grpc_pollset_init(pollset, &pr.mu);
- pr.pops = grpc_polling_entity_create_from_pollset(pollset);
- shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,
- grpc_schedule_on_exec_ctx);
- pr.port = -1;
- pr.server = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
- pr.ctx = &context;
-
- req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
- req.http.path = const_cast<char*>("/get");
-
- grpc_httpcli_context_init(&context);
- grpc_resource_quota* resource_quota =
- grpc_resource_quota_create("port_server_client/pick");
- grpc_httpcli_get(&context, &pr.pops, resource_quota, &req,
- grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
- GRPC_CLOSURE_CREATE(got_port_from_server, &pr,
- grpc_schedule_on_exec_ctx),
- &pr.response);
- grpc_resource_quota_unref_internal(resource_quota);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(pr.mu);
- while (pr.port == -1) {
- grpc_pollset_worker* worker = nullptr;
- if (!GRPC_LOG_IF_ERROR(
- "pollset_work",
- grpc_pollset_work(
- grpc_polling_entity_pollset(&pr.pops), &worker,
- grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {
- pr.port = 0;
- }
- }
- gpr_mu_unlock(pr.mu);
-
- grpc_http_response_destroy(&pr.response);
- grpc_httpcli_context_destroy(&context);
- grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),
- shutdown_closure);
-
- grpc_core::ExecCtx::Get()->Flush();
- }
- grpc_shutdown();
-
- return pr.port;
-}
-
-#endif // GRPC_TEST_PICK_PORT
+ grpc_shutdown();
+}
+
+typedef struct portreq {
+ gpr_mu* mu = nullptr;
+ grpc_polling_entity pops = {};
+ int port = 0;
+ int retries = 0;
+ char* server = nullptr;
+ grpc_httpcli_context* ctx = nullptr;
+ grpc_httpcli_response response = {};
+} portreq;
+
+static void got_port_from_server(void* arg, grpc_error* error) {
+ size_t i;
+ int port = 0;
+ portreq* pr = static_cast<portreq*>(arg);
+ int failed = 0;
+ grpc_httpcli_response* response = &pr->response;
+
+ if (error != GRPC_ERROR_NONE) {
+ failed = 1;
+ const char* msg = grpc_error_string(error);
+ gpr_log(GPR_DEBUG, "failed port pick from server: retrying [%s]", msg);
+
+ } else if (response->status != 200) {
+ failed = 1;
+ gpr_log(GPR_DEBUG, "failed port pick from server: status=%d",
+ response->status);
+ }
+
+ if (failed) {
+ grpc_httpcli_request req;
+ memset(&req, 0, sizeof(req));
+ if (pr->retries >= 5) {
+ gpr_mu_lock(pr->mu);
+ pr->port = 0;
+ GRPC_LOG_IF_ERROR(
+ "pollset_kick",
+ grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
+ gpr_mu_unlock(pr->mu);
+ return;
+ }
+ GPR_ASSERT(pr->retries < 10);
+ gpr_sleep_until(gpr_time_add(
+ gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_millis(
+ static_cast<int64_t>(
+ 1000.0 * (1 + pow(1.3, pr->retries) * rand() / RAND_MAX)),
+ GPR_TIMESPAN)));
+ pr->retries++;
+ req.host = pr->server;
+ req.http.path = const_cast<char*>("/get");
+ grpc_http_response_destroy(&pr->response);
+ pr->response = {};
+ grpc_resource_quota* resource_quota =
+ grpc_resource_quota_create("port_server_client/pick_retry");
+ grpc_httpcli_get(pr->ctx, &pr->pops, resource_quota, &req,
+ grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
+ GRPC_CLOSURE_CREATE(got_port_from_server, pr,
+ grpc_schedule_on_exec_ctx),
+ &pr->response);
+ grpc_resource_quota_unref_internal(resource_quota);
+ return;
+ }
+ GPR_ASSERT(response);
+ GPR_ASSERT(response->status == 200);
+ for (i = 0; i < response->body_length; i++) {
+ GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9');
+ port = port * 10 + response->body[i] - '0';
+ }
+ GPR_ASSERT(port > 1024);
+ gpr_mu_lock(pr->mu);
+ pr->port = port;
+ GRPC_LOG_IF_ERROR(
+ "pollset_kick",
+ grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
+ gpr_mu_unlock(pr->mu);
+}
+
+int grpc_pick_port_using_server(void) {
+ grpc_httpcli_context context;
+ grpc_httpcli_request req;
+ portreq pr;
+ grpc_closure* shutdown_closure;
+
+ grpc_init();
+ {
+ grpc_core::ExecCtx exec_ctx;
+ pr = {};
+ memset(&req, 0, sizeof(req));
+ grpc_pollset* pollset =
+ static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
+ grpc_pollset_init(pollset, &pr.mu);
+ pr.pops = grpc_polling_entity_create_from_pollset(pollset);
+ shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,
+ grpc_schedule_on_exec_ctx);
+ pr.port = -1;
+ pr.server = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
+ pr.ctx = &context;
+
+ req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
+ req.http.path = const_cast<char*>("/get");
+
+ grpc_httpcli_context_init(&context);
+ grpc_resource_quota* resource_quota =
+ grpc_resource_quota_create("port_server_client/pick");
+ grpc_httpcli_get(&context, &pr.pops, resource_quota, &req,
+ grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
+ GRPC_CLOSURE_CREATE(got_port_from_server, &pr,
+ grpc_schedule_on_exec_ctx),
+ &pr.response);
+ grpc_resource_quota_unref_internal(resource_quota);
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(pr.mu);
+ while (pr.port == -1) {
+ grpc_pollset_worker* worker = nullptr;
+ if (!GRPC_LOG_IF_ERROR(
+ "pollset_work",
+ grpc_pollset_work(
+ grpc_polling_entity_pollset(&pr.pops), &worker,
+ grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {
+ pr.port = 0;
+ }
+ }
+ gpr_mu_unlock(pr.mu);
+
+ grpc_http_response_destroy(&pr.response);
+ grpc_httpcli_context_destroy(&context);
+ grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),
+ shutdown_closure);
+
+ grpc_core::ExecCtx::Get()->Flush();
+ }
+ grpc_shutdown();
+
+ return pr.port;
+}
+
+#endif // GRPC_TEST_PICK_PORT
diff --git a/contrib/libs/grpc/test/core/util/port_server_client.h b/contrib/libs/grpc/test/core/util/port_server_client.h
index 86dd7018ff..6eac403714 100644
--- a/contrib/libs/grpc/test/core/util/port_server_client.h
+++ b/contrib/libs/grpc/test/core/util/port_server_client.h
@@ -1,30 +1,30 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
-#define GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
-
-// C interface to port_server.py
-
-// must be synchronized with tools/run_tests/python_utils/start_port_server.py
-#define GRPC_PORT_SERVER_ADDRESS "localhost:32766"
-
-int grpc_pick_port_using_server(void);
-void grpc_free_port_using_server(int port);
-
-#endif // GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
+#define GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
+
+// C interface to port_server.py
+
+// must be synchronized with tools/run_tests/python_utils/start_port_server.py
+#define GRPC_PORT_SERVER_ADDRESS "localhost:32766"
+
+int grpc_pick_port_using_server(void);
+void grpc_free_port_using_server(int port);
+
+#endif // GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
diff --git a/contrib/libs/grpc/test/core/util/reconnect_server.cc b/contrib/libs/grpc/test/core/util/reconnect_server.cc
index 070ab3fa0a..951953a69c 100644
--- a/contrib/libs/grpc/test/core/util/reconnect_server.cc
+++ b/contrib/libs/grpc/test/core/util/reconnect_server.cc
@@ -1,75 +1,75 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/reconnect_server.h"
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/reconnect_server.h"
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-#include <string.h>
-
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include <string.h>
+
#include "y_absl/strings/string_view.h"
-#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_tcp_server.h"
-
-static void pretty_print_backoffs(reconnect_server* server) {
- gpr_timespec diff;
- int i = 1;
- double expected_backoff = 1000.0, backoff;
- timestamp_list* head = server->head;
- gpr_log(GPR_INFO, "reconnect server: new connection");
- for (head = server->head; head && head->next; head = head->next, i++) {
- diff = gpr_time_sub(head->next->timestamp, head->timestamp);
- backoff = gpr_time_to_millis(diff);
- gpr_log(GPR_INFO,
- "retry %2d:backoff %6.2fs,expected backoff %6.2fs, jitter %4.2f%%",
- i, backoff / 1000.0, expected_backoff / 1000.0,
- (backoff - expected_backoff) * 100.0 / expected_backoff);
- expected_backoff *= 1.6;
- int max_reconnect_backoff_ms = 120 * 1000;
- if (server->max_reconnect_backoff_ms > 0) {
- max_reconnect_backoff_ms = server->max_reconnect_backoff_ms;
- }
- if (expected_backoff > max_reconnect_backoff_ms) {
- expected_backoff = max_reconnect_backoff_ms;
- }
- }
-}
-
-static void on_connect(void* arg, grpc_endpoint* tcp,
- grpc_pollset* /*accepting_pollset*/,
- grpc_tcp_server_acceptor* acceptor) {
- gpr_free(acceptor);
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_tcp_server.h"
+
+static void pretty_print_backoffs(reconnect_server* server) {
+ gpr_timespec diff;
+ int i = 1;
+ double expected_backoff = 1000.0, backoff;
+ timestamp_list* head = server->head;
+ gpr_log(GPR_INFO, "reconnect server: new connection");
+ for (head = server->head; head && head->next; head = head->next, i++) {
+ diff = gpr_time_sub(head->next->timestamp, head->timestamp);
+ backoff = gpr_time_to_millis(diff);
+ gpr_log(GPR_INFO,
+ "retry %2d:backoff %6.2fs,expected backoff %6.2fs, jitter %4.2f%%",
+ i, backoff / 1000.0, expected_backoff / 1000.0,
+ (backoff - expected_backoff) * 100.0 / expected_backoff);
+ expected_backoff *= 1.6;
+ int max_reconnect_backoff_ms = 120 * 1000;
+ if (server->max_reconnect_backoff_ms > 0) {
+ max_reconnect_backoff_ms = server->max_reconnect_backoff_ms;
+ }
+ if (expected_backoff > max_reconnect_backoff_ms) {
+ expected_backoff = max_reconnect_backoff_ms;
+ }
+ }
+}
+
+static void on_connect(void* arg, grpc_endpoint* tcp,
+ grpc_pollset* /*accepting_pollset*/,
+ grpc_tcp_server_acceptor* acceptor) {
+ gpr_free(acceptor);
y_absl::string_view peer;
int last_colon;
- reconnect_server* server = static_cast<reconnect_server*>(arg);
- gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
- timestamp_list* new_tail;
- peer = grpc_endpoint_get_peer(tcp);
- grpc_endpoint_shutdown(tcp,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Connected"));
- grpc_endpoint_destroy(tcp);
+ reconnect_server* server = static_cast<reconnect_server*>(arg);
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ timestamp_list* new_tail;
+ peer = grpc_endpoint_get_peer(tcp);
+ grpc_endpoint_shutdown(tcp,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Connected"));
+ grpc_endpoint_destroy(tcp);
last_colon = peer.rfind(':');
if (server->peer == nullptr) {
server->peer = new TString(peer);
@@ -80,50 +80,50 @@ static void on_connect(void* arg, grpc_endpoint* tcp,
*server->peer) != 0) {
gpr_log(GPR_ERROR, "mismatched peer! %s vs %s", server->peer->c_str(),
TString(peer).c_str());
- }
- }
- new_tail = static_cast<timestamp_list*>(gpr_malloc(sizeof(timestamp_list)));
- new_tail->timestamp = now;
- new_tail->next = nullptr;
- if (server->tail == nullptr) {
- server->head = new_tail;
- server->tail = new_tail;
- } else {
- server->tail->next = new_tail;
- server->tail = new_tail;
- }
- pretty_print_backoffs(server);
-}
-
-void reconnect_server_init(reconnect_server* server) {
- test_tcp_server_init(&server->tcp_server, on_connect, server);
- server->head = nullptr;
- server->tail = nullptr;
- server->peer = nullptr;
- server->max_reconnect_backoff_ms = 0;
-}
-
-void reconnect_server_start(reconnect_server* server, int port) {
- test_tcp_server_start(&server->tcp_server, port);
-}
-
-void reconnect_server_poll(reconnect_server* server, int seconds) {
- test_tcp_server_poll(&server->tcp_server, 1000 * seconds);
-}
-
-void reconnect_server_clear_timestamps(reconnect_server* server) {
- timestamp_list* new_head = server->head;
- while (server->head) {
- new_head = server->head->next;
- gpr_free(server->head);
- server->head = new_head;
- }
- server->tail = nullptr;
+ }
+ }
+ new_tail = static_cast<timestamp_list*>(gpr_malloc(sizeof(timestamp_list)));
+ new_tail->timestamp = now;
+ new_tail->next = nullptr;
+ if (server->tail == nullptr) {
+ server->head = new_tail;
+ server->tail = new_tail;
+ } else {
+ server->tail->next = new_tail;
+ server->tail = new_tail;
+ }
+ pretty_print_backoffs(server);
+}
+
+void reconnect_server_init(reconnect_server* server) {
+ test_tcp_server_init(&server->tcp_server, on_connect, server);
+ server->head = nullptr;
+ server->tail = nullptr;
+ server->peer = nullptr;
+ server->max_reconnect_backoff_ms = 0;
+}
+
+void reconnect_server_start(reconnect_server* server, int port) {
+ test_tcp_server_start(&server->tcp_server, port);
+}
+
+void reconnect_server_poll(reconnect_server* server, int seconds) {
+ test_tcp_server_poll(&server->tcp_server, 1000 * seconds);
+}
+
+void reconnect_server_clear_timestamps(reconnect_server* server) {
+ timestamp_list* new_head = server->head;
+ while (server->head) {
+ new_head = server->head->next;
+ gpr_free(server->head);
+ server->head = new_head;
+ }
+ server->tail = nullptr;
delete server->peer;
- server->peer = nullptr;
-}
-
-void reconnect_server_destroy(reconnect_server* server) {
- reconnect_server_clear_timestamps(server);
- test_tcp_server_destroy(&server->tcp_server);
-}
+ server->peer = nullptr;
+}
+
+void reconnect_server_destroy(reconnect_server* server) {
+ reconnect_server_clear_timestamps(server);
+ test_tcp_server_destroy(&server->tcp_server);
+}
diff --git a/contrib/libs/grpc/test/core/util/reconnect_server.h b/contrib/libs/grpc/test/core/util/reconnect_server.h
index 5fd03821f7..56873630b9 100644
--- a/contrib/libs/grpc/test/core/util/reconnect_server.h
+++ b/contrib/libs/grpc/test/core/util/reconnect_server.h
@@ -1,45 +1,45 @@
-/*
- *
- * Copyright 2015-2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H
-#define GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H
-
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-#include "test/core/util/test_tcp_server.h"
-
-typedef struct timestamp_list {
- gpr_timespec timestamp;
- struct timestamp_list* next;
-} timestamp_list;
-
-typedef struct reconnect_server {
- test_tcp_server tcp_server;
- timestamp_list* head;
- timestamp_list* tail;
+/*
+ *
+ * Copyright 2015-2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H
+#define GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H
+
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include "test/core/util/test_tcp_server.h"
+
+typedef struct timestamp_list {
+ gpr_timespec timestamp;
+ struct timestamp_list* next;
+} timestamp_list;
+
+typedef struct reconnect_server {
+ test_tcp_server tcp_server;
+ timestamp_list* head;
+ timestamp_list* tail;
TString* peer;
- int max_reconnect_backoff_ms;
-} reconnect_server;
-
-void reconnect_server_init(reconnect_server* server);
-void reconnect_server_start(reconnect_server* server, int port);
-void reconnect_server_poll(reconnect_server* server, int seconds);
-void reconnect_server_destroy(reconnect_server* server);
-void reconnect_server_clear_timestamps(reconnect_server* server);
-
-#endif /* GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H */
+ int max_reconnect_backoff_ms;
+} reconnect_server;
+
+void reconnect_server_init(reconnect_server* server);
+void reconnect_server_start(reconnect_server* server, int port);
+void reconnect_server_poll(reconnect_server* server, int seconds);
+void reconnect_server_destroy(reconnect_server* server);
+void reconnect_server_clear_timestamps(reconnect_server* server);
+
+#endif /* GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H */
diff --git a/contrib/libs/grpc/test/core/util/run_with_poller.sh b/contrib/libs/grpc/test/core/util/run_with_poller.sh
index 382a63e8ae..ad68e34b46 100755
--- a/contrib/libs/grpc/test/core/util/run_with_poller.sh
+++ b/contrib/libs/grpc/test/core/util/run_with_poller.sh
@@ -1,19 +1,19 @@
-#!/bin/sh
-# Copyright 2017 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.
-
-set -ex
-export GRPC_POLL_STRATEGY=$1
-shift
-"$@"
+#!/bin/sh
+# Copyright 2017 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.
+
+set -ex
+export GRPC_POLL_STRATEGY=$1
+shift
+"$@"
diff --git a/contrib/libs/grpc/test/core/util/slice_splitter.cc b/contrib/libs/grpc/test/core/util/slice_splitter.cc
index 1f81d03d96..44e44c1e0b 100644
--- a/contrib/libs/grpc/test/core/util/slice_splitter.cc
+++ b/contrib/libs/grpc/test/core/util/slice_splitter.cc
@@ -1,126 +1,126 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/slice_splitter.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode) {
- switch (mode) {
- case GRPC_SLICE_SPLIT_IDENTITY:
- return "identity";
- case GRPC_SLICE_SPLIT_MERGE_ALL:
- return "merge_all";
- case GRPC_SLICE_SPLIT_ONE_BYTE:
- return "one_byte";
- }
- return "error";
-}
-
-void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices,
- size_t src_slice_count, grpc_slice** dst_slices,
- size_t* dst_slice_count) {
- size_t i, j;
- size_t length;
-
- switch (mode) {
- case GRPC_SLICE_SPLIT_IDENTITY:
- *dst_slice_count = src_slice_count;
- *dst_slices = static_cast<grpc_slice*>(
- gpr_malloc(sizeof(grpc_slice) * src_slice_count));
- for (i = 0; i < src_slice_count; i++) {
- (*dst_slices)[i] = src_slices[i];
- grpc_slice_ref((*dst_slices)[i]);
- }
- break;
- case GRPC_SLICE_SPLIT_MERGE_ALL:
- *dst_slice_count = 1;
- length = 0;
- for (i = 0; i < src_slice_count; i++) {
- length += GRPC_SLICE_LENGTH(src_slices[i]);
- }
- *dst_slices = static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice)));
- **dst_slices = grpc_slice_malloc(length);
- length = 0;
- for (i = 0; i < src_slice_count; i++) {
- memcpy(GRPC_SLICE_START_PTR(**dst_slices) + length,
- GRPC_SLICE_START_PTR(src_slices[i]),
- GRPC_SLICE_LENGTH(src_slices[i]));
- length += GRPC_SLICE_LENGTH(src_slices[i]);
- }
- break;
- case GRPC_SLICE_SPLIT_ONE_BYTE:
- length = 0;
- for (i = 0; i < src_slice_count; i++) {
- length += GRPC_SLICE_LENGTH(src_slices[i]);
- }
- *dst_slice_count = length;
- *dst_slices =
- static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice) * length));
- length = 0;
- for (i = 0; i < src_slice_count; i++) {
- for (j = 0; j < GRPC_SLICE_LENGTH(src_slices[i]); j++) {
- (*dst_slices)[length] = grpc_slice_sub(src_slices[i], j, j + 1);
- length++;
- }
- }
- break;
- }
-}
-
-void grpc_split_slices_to_buffer(grpc_slice_split_mode mode,
- grpc_slice* src_slices, size_t src_slice_count,
- grpc_slice_buffer* dst) {
- grpc_slice* slices;
- size_t nslices;
- size_t i;
- grpc_split_slices(mode, src_slices, src_slice_count, &slices, &nslices);
- for (i = 0; i < nslices; i++) {
- /* add indexed to avoid re-merging split slices */
- grpc_slice_buffer_add_indexed(dst, slices[i]);
- }
- gpr_free(slices);
-}
-
-void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src,
- grpc_slice_buffer* dst) {
- grpc_split_slices_to_buffer(mode, src->slices, src->count, dst);
-}
-
-grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices) {
- uint8_t* out = nullptr;
- size_t length = 0;
- size_t capacity = 0;
- size_t i;
-
- for (i = 0; i < nslices; i++) {
- if (GRPC_SLICE_LENGTH(slices[i]) + length > capacity) {
- capacity = GPR_MAX(capacity * 2, GRPC_SLICE_LENGTH(slices[i]) + length);
- out = static_cast<uint8_t*>(gpr_realloc(out, capacity));
- }
- memcpy(out + length, GRPC_SLICE_START_PTR(slices[i]),
- GRPC_SLICE_LENGTH(slices[i]));
- length += GRPC_SLICE_LENGTH(slices[i]);
- }
-
- return grpc_slice_new(out, length, gpr_free);
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/slice_splitter.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode) {
+ switch (mode) {
+ case GRPC_SLICE_SPLIT_IDENTITY:
+ return "identity";
+ case GRPC_SLICE_SPLIT_MERGE_ALL:
+ return "merge_all";
+ case GRPC_SLICE_SPLIT_ONE_BYTE:
+ return "one_byte";
+ }
+ return "error";
+}
+
+void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices,
+ size_t src_slice_count, grpc_slice** dst_slices,
+ size_t* dst_slice_count) {
+ size_t i, j;
+ size_t length;
+
+ switch (mode) {
+ case GRPC_SLICE_SPLIT_IDENTITY:
+ *dst_slice_count = src_slice_count;
+ *dst_slices = static_cast<grpc_slice*>(
+ gpr_malloc(sizeof(grpc_slice) * src_slice_count));
+ for (i = 0; i < src_slice_count; i++) {
+ (*dst_slices)[i] = src_slices[i];
+ grpc_slice_ref((*dst_slices)[i]);
+ }
+ break;
+ case GRPC_SLICE_SPLIT_MERGE_ALL:
+ *dst_slice_count = 1;
+ length = 0;
+ for (i = 0; i < src_slice_count; i++) {
+ length += GRPC_SLICE_LENGTH(src_slices[i]);
+ }
+ *dst_slices = static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice)));
+ **dst_slices = grpc_slice_malloc(length);
+ length = 0;
+ for (i = 0; i < src_slice_count; i++) {
+ memcpy(GRPC_SLICE_START_PTR(**dst_slices) + length,
+ GRPC_SLICE_START_PTR(src_slices[i]),
+ GRPC_SLICE_LENGTH(src_slices[i]));
+ length += GRPC_SLICE_LENGTH(src_slices[i]);
+ }
+ break;
+ case GRPC_SLICE_SPLIT_ONE_BYTE:
+ length = 0;
+ for (i = 0; i < src_slice_count; i++) {
+ length += GRPC_SLICE_LENGTH(src_slices[i]);
+ }
+ *dst_slice_count = length;
+ *dst_slices =
+ static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice) * length));
+ length = 0;
+ for (i = 0; i < src_slice_count; i++) {
+ for (j = 0; j < GRPC_SLICE_LENGTH(src_slices[i]); j++) {
+ (*dst_slices)[length] = grpc_slice_sub(src_slices[i], j, j + 1);
+ length++;
+ }
+ }
+ break;
+ }
+}
+
+void grpc_split_slices_to_buffer(grpc_slice_split_mode mode,
+ grpc_slice* src_slices, size_t src_slice_count,
+ grpc_slice_buffer* dst) {
+ grpc_slice* slices;
+ size_t nslices;
+ size_t i;
+ grpc_split_slices(mode, src_slices, src_slice_count, &slices, &nslices);
+ for (i = 0; i < nslices; i++) {
+ /* add indexed to avoid re-merging split slices */
+ grpc_slice_buffer_add_indexed(dst, slices[i]);
+ }
+ gpr_free(slices);
+}
+
+void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src,
+ grpc_slice_buffer* dst) {
+ grpc_split_slices_to_buffer(mode, src->slices, src->count, dst);
+}
+
+grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices) {
+ uint8_t* out = nullptr;
+ size_t length = 0;
+ size_t capacity = 0;
+ size_t i;
+
+ for (i = 0; i < nslices; i++) {
+ if (GRPC_SLICE_LENGTH(slices[i]) + length > capacity) {
+ capacity = GPR_MAX(capacity * 2, GRPC_SLICE_LENGTH(slices[i]) + length);
+ out = static_cast<uint8_t*>(gpr_realloc(out, capacity));
+ }
+ memcpy(out + length, GRPC_SLICE_START_PTR(slices[i]),
+ GRPC_SLICE_LENGTH(slices[i]));
+ length += GRPC_SLICE_LENGTH(slices[i]);
+ }
+
+ return grpc_slice_new(out, length, gpr_free);
+}
diff --git a/contrib/libs/grpc/test/core/util/slice_splitter.h b/contrib/libs/grpc/test/core/util/slice_splitter.h
index 65b9f6f7df..3e698dffae 100644
--- a/contrib/libs/grpc/test/core/util/slice_splitter.h
+++ b/contrib/libs/grpc/test/core/util/slice_splitter.h
@@ -1,53 +1,53 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H
-#define GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H
-
-/* utility function to split/merge slices together to help create test
- cases */
-
-#include <grpc/slice.h>
-#include <grpc/slice_buffer.h>
-
-typedef enum {
- /* merge all input slices into a single slice */
- GRPC_SLICE_SPLIT_MERGE_ALL,
- /* leave slices as is */
- GRPC_SLICE_SPLIT_IDENTITY,
- /* split slices into one byte chunks */
- GRPC_SLICE_SPLIT_ONE_BYTE
-} grpc_slice_split_mode;
-
-/* allocates *dst_slices; caller must unref all slices in dst_slices then free
- it */
-void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices,
- size_t src_slice_count, grpc_slice** dst_slices,
- size_t* dst_slice_count);
-
-void grpc_split_slices_to_buffer(grpc_slice_split_mode mode,
- grpc_slice* src_slices, size_t src_slice_count,
- grpc_slice_buffer* dst);
-void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src,
- grpc_slice_buffer* dst);
-
-grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices);
-
-const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode);
-
-#endif /* GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H
+#define GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H
+
+/* utility function to split/merge slices together to help create test
+ cases */
+
+#include <grpc/slice.h>
+#include <grpc/slice_buffer.h>
+
+typedef enum {
+ /* merge all input slices into a single slice */
+ GRPC_SLICE_SPLIT_MERGE_ALL,
+ /* leave slices as is */
+ GRPC_SLICE_SPLIT_IDENTITY,
+ /* split slices into one byte chunks */
+ GRPC_SLICE_SPLIT_ONE_BYTE
+} grpc_slice_split_mode;
+
+/* allocates *dst_slices; caller must unref all slices in dst_slices then free
+ it */
+void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices,
+ size_t src_slice_count, grpc_slice** dst_slices,
+ size_t* dst_slice_count);
+
+void grpc_split_slices_to_buffer(grpc_slice_split_mode mode,
+ grpc_slice* src_slices, size_t src_slice_count,
+ grpc_slice_buffer* dst);
+void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src,
+ grpc_slice_buffer* dst);
+
+grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices);
+
+const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode);
+
+#endif /* GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H */
diff --git a/contrib/libs/grpc/test/core/util/subprocess.h b/contrib/libs/grpc/test/core/util/subprocess.h
index c7fe9af435..3163086bba 100644
--- a/contrib/libs/grpc/test/core/util/subprocess.h
+++ b/contrib/libs/grpc/test/core/util/subprocess.h
@@ -1,36 +1,36 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_SUBPROCESS_H
-#define GRPC_TEST_CORE_UTIL_SUBPROCESS_H
-
-#include <grpc/support/port_platform.h>
-
-typedef struct gpr_subprocess gpr_subprocess;
-
-/** .exe on windows, empty on unices */
-const char* gpr_subprocess_binary_extension();
-
-gpr_subprocess* gpr_subprocess_create(int argc, const char** argv);
-/** if subprocess has not been joined, kill it */
-void gpr_subprocess_destroy(gpr_subprocess* p);
-/** returns exit status; can be called at most once */
-int gpr_subprocess_join(gpr_subprocess* p);
-void gpr_subprocess_interrupt(gpr_subprocess* p);
-
-#endif /* GRPC_TEST_CORE_UTIL_SUBPROCESS_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_SUBPROCESS_H
+#define GRPC_TEST_CORE_UTIL_SUBPROCESS_H
+
+#include <grpc/support/port_platform.h>
+
+typedef struct gpr_subprocess gpr_subprocess;
+
+/** .exe on windows, empty on unices */
+const char* gpr_subprocess_binary_extension();
+
+gpr_subprocess* gpr_subprocess_create(int argc, const char** argv);
+/** if subprocess has not been joined, kill it */
+void gpr_subprocess_destroy(gpr_subprocess* p);
+/** returns exit status; can be called at most once */
+int gpr_subprocess_join(gpr_subprocess* p);
+void gpr_subprocess_interrupt(gpr_subprocess* p);
+
+#endif /* GRPC_TEST_CORE_UTIL_SUBPROCESS_H */
diff --git a/contrib/libs/grpc/test/core/util/subprocess_posix.cc b/contrib/libs/grpc/test/core/util/subprocess_posix.cc
index ab288d777f..263de85fbb 100644
--- a/contrib/libs/grpc/test/core/util/subprocess_posix.cc
+++ b/contrib/libs/grpc/test/core/util/subprocess_posix.cc
@@ -1,100 +1,100 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_POSIX_SUBPROCESS
-
-#include <assert.h>
-#include <errno.h>
-#include <signal.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "test/core/util/subprocess.h"
-
-struct gpr_subprocess {
- int pid;
- bool joined;
-};
-
-const char* gpr_subprocess_binary_extension() { return ""; }
-
-gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) {
- gpr_subprocess* r;
- int pid;
- char** exec_args;
-
- pid = fork();
- if (pid == -1) {
- return nullptr;
- } else if (pid == 0) {
- exec_args = static_cast<char**>(
- gpr_malloc((static_cast<size_t>(argc) + 1) * sizeof(char*)));
- memcpy(exec_args, argv, static_cast<size_t>(argc) * sizeof(char*));
- exec_args[argc] = nullptr;
- execv(exec_args[0], exec_args);
- /* if we reach here, an error has occurred */
- gpr_log(GPR_ERROR, "execv '%s' failed: %s", exec_args[0], strerror(errno));
- _exit(1);
- return nullptr;
- } else {
- r = static_cast<gpr_subprocess*>(gpr_zalloc(sizeof(gpr_subprocess)));
- r->pid = pid;
- return r;
- }
-}
-
-void gpr_subprocess_destroy(gpr_subprocess* p) {
- if (!p->joined) {
- kill(p->pid, SIGKILL);
- gpr_subprocess_join(p);
- }
- gpr_free(p);
-}
-
-int gpr_subprocess_join(gpr_subprocess* p) {
- int status;
-retry:
- if (waitpid(p->pid, &status, 0) == -1) {
- if (errno == EINTR) {
- goto retry;
- }
- gpr_log(GPR_ERROR, "waitpid failed for pid %d: %s", p->pid,
- strerror(errno));
- return -1;
- }
- p->joined = true;
- return status;
-}
-
-void gpr_subprocess_interrupt(gpr_subprocess* p) {
- if (!p->joined) {
- kill(p->pid, SIGINT);
- }
-}
-
-#endif /* GPR_POSIX_SUBPROCESS */
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_SUBPROCESS
+
+#include <assert.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "test/core/util/subprocess.h"
+
+struct gpr_subprocess {
+ int pid;
+ bool joined;
+};
+
+const char* gpr_subprocess_binary_extension() { return ""; }
+
+gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) {
+ gpr_subprocess* r;
+ int pid;
+ char** exec_args;
+
+ pid = fork();
+ if (pid == -1) {
+ return nullptr;
+ } else if (pid == 0) {
+ exec_args = static_cast<char**>(
+ gpr_malloc((static_cast<size_t>(argc) + 1) * sizeof(char*)));
+ memcpy(exec_args, argv, static_cast<size_t>(argc) * sizeof(char*));
+ exec_args[argc] = nullptr;
+ execv(exec_args[0], exec_args);
+ /* if we reach here, an error has occurred */
+ gpr_log(GPR_ERROR, "execv '%s' failed: %s", exec_args[0], strerror(errno));
+ _exit(1);
+ return nullptr;
+ } else {
+ r = static_cast<gpr_subprocess*>(gpr_zalloc(sizeof(gpr_subprocess)));
+ r->pid = pid;
+ return r;
+ }
+}
+
+void gpr_subprocess_destroy(gpr_subprocess* p) {
+ if (!p->joined) {
+ kill(p->pid, SIGKILL);
+ gpr_subprocess_join(p);
+ }
+ gpr_free(p);
+}
+
+int gpr_subprocess_join(gpr_subprocess* p) {
+ int status;
+retry:
+ if (waitpid(p->pid, &status, 0) == -1) {
+ if (errno == EINTR) {
+ goto retry;
+ }
+ gpr_log(GPR_ERROR, "waitpid failed for pid %d: %s", p->pid,
+ strerror(errno));
+ return -1;
+ }
+ p->joined = true;
+ return status;
+}
+
+void gpr_subprocess_interrupt(gpr_subprocess* p) {
+ if (!p->joined) {
+ kill(p->pid, SIGINT);
+ }
+}
+
+#endif /* GPR_POSIX_SUBPROCESS */
diff --git a/contrib/libs/grpc/test/core/util/subprocess_windows.cc b/contrib/libs/grpc/test/core/util/subprocess_windows.cc
index d3295244ea..4ca8dc3507 100644
--- a/contrib/libs/grpc/test/core/util/subprocess_windows.cc
+++ b/contrib/libs/grpc/test/core/util/subprocess_windows.cc
@@ -1,126 +1,126 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS_SUBPROCESS
-
-#include <string.h>
-#include <tchar.h>
-#include <windows.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/string_windows.h"
-#include "test/core/util/subprocess.h"
-
-struct gpr_subprocess {
- PROCESS_INFORMATION pi;
- int joined;
- int interrupted;
-};
-
-const char* gpr_subprocess_binary_extension() { return ".exe"; }
-
-gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) {
- gpr_subprocess* r;
-
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
-
- char* args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL);
- TCHAR* args_tchar;
-
- args_tchar = gpr_char_to_tchar(args);
- gpr_free(args);
-
- memset(&si, 0, sizeof(si));
- si.cb = sizeof(si);
- memset(&pi, 0, sizeof(pi));
-
- if (!CreateProcess(NULL, args_tchar, NULL, NULL, FALSE,
- CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi)) {
- gpr_free(args_tchar);
- return NULL;
- }
- gpr_free(args_tchar);
-
- r = (gpr_subprocess*)gpr_malloc(sizeof(gpr_subprocess));
- memset(r, 0, sizeof(*r));
- r->pi = pi;
- return r;
-}
-
-void gpr_subprocess_destroy(gpr_subprocess* p) {
- if (p) {
- if (!p->joined) {
- gpr_subprocess_interrupt(p);
- gpr_subprocess_join(p);
- }
- if (p->pi.hProcess) {
- CloseHandle(p->pi.hProcess);
- }
- if (p->pi.hThread) {
- CloseHandle(p->pi.hThread);
- }
- gpr_free(p);
- }
-}
-
-int gpr_subprocess_join(gpr_subprocess* p) {
- DWORD dwExitCode;
- if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
- if (dwExitCode == STILL_ACTIVE) {
- if (WaitForSingleObject(p->pi.hProcess, INFINITE) == WAIT_OBJECT_0) {
- p->joined = 1;
- goto getExitCode;
- }
- return -1; // failed to join
- } else {
- goto getExitCode;
- }
- } else {
- return -1; // failed to get exit code
- }
-
-getExitCode:
- if (p->interrupted) {
- return 0;
- }
- if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
- return (int)dwExitCode;
- } else {
- return -1; // failed to get exit code
- }
-}
-
-void gpr_subprocess_interrupt(gpr_subprocess* p) {
- DWORD dwExitCode;
- if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
- if (dwExitCode == STILL_ACTIVE) {
- gpr_log(GPR_INFO, "sending ctrl-break");
- GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p->pi.dwProcessId);
- p->joined = 1;
- p->interrupted = 1;
- }
- }
- return;
-}
-
-#endif /* GPR_WINDOWS_SUBPROCESS */
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS_SUBPROCESS
+
+#include <string.h>
+#include <tchar.h>
+#include <windows.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/string_windows.h"
+#include "test/core/util/subprocess.h"
+
+struct gpr_subprocess {
+ PROCESS_INFORMATION pi;
+ int joined;
+ int interrupted;
+};
+
+const char* gpr_subprocess_binary_extension() { return ".exe"; }
+
+gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) {
+ gpr_subprocess* r;
+
+ STARTUPINFO si;
+ PROCESS_INFORMATION pi;
+
+ char* args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL);
+ TCHAR* args_tchar;
+
+ args_tchar = gpr_char_to_tchar(args);
+ gpr_free(args);
+
+ memset(&si, 0, sizeof(si));
+ si.cb = sizeof(si);
+ memset(&pi, 0, sizeof(pi));
+
+ if (!CreateProcess(NULL, args_tchar, NULL, NULL, FALSE,
+ CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi)) {
+ gpr_free(args_tchar);
+ return NULL;
+ }
+ gpr_free(args_tchar);
+
+ r = (gpr_subprocess*)gpr_malloc(sizeof(gpr_subprocess));
+ memset(r, 0, sizeof(*r));
+ r->pi = pi;
+ return r;
+}
+
+void gpr_subprocess_destroy(gpr_subprocess* p) {
+ if (p) {
+ if (!p->joined) {
+ gpr_subprocess_interrupt(p);
+ gpr_subprocess_join(p);
+ }
+ if (p->pi.hProcess) {
+ CloseHandle(p->pi.hProcess);
+ }
+ if (p->pi.hThread) {
+ CloseHandle(p->pi.hThread);
+ }
+ gpr_free(p);
+ }
+}
+
+int gpr_subprocess_join(gpr_subprocess* p) {
+ DWORD dwExitCode;
+ if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
+ if (dwExitCode == STILL_ACTIVE) {
+ if (WaitForSingleObject(p->pi.hProcess, INFINITE) == WAIT_OBJECT_0) {
+ p->joined = 1;
+ goto getExitCode;
+ }
+ return -1; // failed to join
+ } else {
+ goto getExitCode;
+ }
+ } else {
+ return -1; // failed to get exit code
+ }
+
+getExitCode:
+ if (p->interrupted) {
+ return 0;
+ }
+ if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
+ return (int)dwExitCode;
+ } else {
+ return -1; // failed to get exit code
+ }
+}
+
+void gpr_subprocess_interrupt(gpr_subprocess* p) {
+ DWORD dwExitCode;
+ if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
+ if (dwExitCode == STILL_ACTIVE) {
+ gpr_log(GPR_INFO, "sending ctrl-break");
+ GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p->pi.dwProcessId);
+ p->joined = 1;
+ p->interrupted = 1;
+ }
+ }
+ return;
+}
+
+#endif /* GPR_WINDOWS_SUBPROCESS */
diff --git a/contrib/libs/grpc/test/core/util/test_config.cc b/contrib/libs/grpc/test/core/util/test_config.cc
index 9e57a486b2..9f3e935a3a 100644
--- a/contrib/libs/grpc/test/core/util/test_config.cc
+++ b/contrib/libs/grpc/test/core/util/test_config.cc
@@ -1,111 +1,111 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/test_config.h"
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/test_config.h"
+
#include <grpc/impl/codegen/gpr_types.h>
-#include <inttypes.h>
-#include <signal.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
+#include <inttypes.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/surface/init.h"
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/surface/init.h"
+
#include "y_absl/debugging/failure_signal_handler.h"
#include "y_absl/debugging/symbolize.h"
-int64_t g_fixture_slowdown_factor = 1;
-int64_t g_poller_slowdown_factor = 1;
-
-#if GPR_GETPID_IN_UNISTD_H
-#include <unistd.h>
-static unsigned seed(void) { return static_cast<unsigned>(getpid()); }
-#endif
-
-#if GPR_GETPID_IN_PROCESS_H
-#include <process.h>
-static unsigned seed(void) { return (unsigned)_getpid(); }
-#endif
-
-#if GPR_WINDOWS_CRASH_HANDLER
-#include <windows.h>
-
-#include <tchar.h>
-
-// disable warning 4091 - dbghelp.h is broken for msvc2015
-#pragma warning(disable : 4091)
-#define DBGHELP_TRANSLATE_TCHAR
-#include <dbghelp.h>
-
-#ifdef _MSC_VER
-#pragma comment(lib, "dbghelp.lib")
-#endif
-
+int64_t g_fixture_slowdown_factor = 1;
+int64_t g_poller_slowdown_factor = 1;
+
+#if GPR_GETPID_IN_UNISTD_H
+#include <unistd.h>
+static unsigned seed(void) { return static_cast<unsigned>(getpid()); }
+#endif
+
+#if GPR_GETPID_IN_PROCESS_H
+#include <process.h>
+static unsigned seed(void) { return (unsigned)_getpid(); }
+#endif
+
+#if GPR_WINDOWS_CRASH_HANDLER
+#include <windows.h>
+
+#include <tchar.h>
+
+// disable warning 4091 - dbghelp.h is broken for msvc2015
+#pragma warning(disable : 4091)
+#define DBGHELP_TRANSLATE_TCHAR
+#include <dbghelp.h>
+
+#ifdef _MSC_VER
+#pragma comment(lib, "dbghelp.lib")
+#endif
+
static void print_stack_from_context(HANDLE thread, CONTEXT c) {
- STACKFRAME s; // in/out stackframe
- memset(&s, 0, sizeof(s));
- DWORD imageType;
-#ifdef _M_IX86
- // normally, call ImageNtHeader() and use machine info from PE header
- imageType = IMAGE_FILE_MACHINE_I386;
- s.AddrPC.Offset = c.Eip;
- s.AddrPC.Mode = AddrModeFlat;
- s.AddrFrame.Offset = c.Ebp;
- s.AddrFrame.Mode = AddrModeFlat;
- s.AddrStack.Offset = c.Esp;
- s.AddrStack.Mode = AddrModeFlat;
-#elif _M_X64
- imageType = IMAGE_FILE_MACHINE_AMD64;
- s.AddrPC.Offset = c.Rip;
- s.AddrPC.Mode = AddrModeFlat;
- s.AddrFrame.Offset = c.Rbp;
- s.AddrFrame.Mode = AddrModeFlat;
- s.AddrStack.Offset = c.Rsp;
- s.AddrStack.Mode = AddrModeFlat;
-#elif _M_IA64
- imageType = IMAGE_FILE_MACHINE_IA64;
- s.AddrPC.Offset = c.StIIP;
- s.AddrPC.Mode = AddrModeFlat;
- s.AddrFrame.Offset = c.IntSp;
- s.AddrFrame.Mode = AddrModeFlat;
- s.AddrBStore.Offset = c.RsBSP;
- s.AddrBStore.Mode = AddrModeFlat;
- s.AddrStack.Offset = c.IntSp;
- s.AddrStack.Mode = AddrModeFlat;
-#else
-#error "Platform not supported!"
-#endif
-
- HANDLE process = GetCurrentProcess();
-
- SYMBOL_INFOW* symbol =
- (SYMBOL_INFOW*)calloc(sizeof(SYMBOL_INFOW) + 256 * sizeof(wchar_t), 1);
- symbol->MaxNameLen = 255;
- symbol->SizeOfStruct = sizeof(SYMBOL_INFOW);
-
+ STACKFRAME s; // in/out stackframe
+ memset(&s, 0, sizeof(s));
+ DWORD imageType;
+#ifdef _M_IX86
+ // normally, call ImageNtHeader() and use machine info from PE header
+ imageType = IMAGE_FILE_MACHINE_I386;
+ s.AddrPC.Offset = c.Eip;
+ s.AddrPC.Mode = AddrModeFlat;
+ s.AddrFrame.Offset = c.Ebp;
+ s.AddrFrame.Mode = AddrModeFlat;
+ s.AddrStack.Offset = c.Esp;
+ s.AddrStack.Mode = AddrModeFlat;
+#elif _M_X64
+ imageType = IMAGE_FILE_MACHINE_AMD64;
+ s.AddrPC.Offset = c.Rip;
+ s.AddrPC.Mode = AddrModeFlat;
+ s.AddrFrame.Offset = c.Rbp;
+ s.AddrFrame.Mode = AddrModeFlat;
+ s.AddrStack.Offset = c.Rsp;
+ s.AddrStack.Mode = AddrModeFlat;
+#elif _M_IA64
+ imageType = IMAGE_FILE_MACHINE_IA64;
+ s.AddrPC.Offset = c.StIIP;
+ s.AddrPC.Mode = AddrModeFlat;
+ s.AddrFrame.Offset = c.IntSp;
+ s.AddrFrame.Mode = AddrModeFlat;
+ s.AddrBStore.Offset = c.RsBSP;
+ s.AddrBStore.Mode = AddrModeFlat;
+ s.AddrStack.Offset = c.IntSp;
+ s.AddrStack.Mode = AddrModeFlat;
+#else
+#error "Platform not supported!"
+#endif
+
+ HANDLE process = GetCurrentProcess();
+
+ SYMBOL_INFOW* symbol =
+ (SYMBOL_INFOW*)calloc(sizeof(SYMBOL_INFOW) + 256 * sizeof(wchar_t), 1);
+ symbol->MaxNameLen = 255;
+ symbol->SizeOfStruct = sizeof(SYMBOL_INFOW);
+
const unsigned short MAX_CALLERS_SHOWN =
8192; // avoid flooding the stderr if stacktrace is way too long
for (int frame = 0; frame < MAX_CALLERS_SHOWN &&
@@ -133,265 +133,265 @@ static void print_stack_from_context(HANDLE thread, CONTEXT c) {
fwprintf(stderr, L"*** %d: %016I64X %ls - %016I64X (%ls:%d)\n", frame,
(DWORD64)(s.AddrPC.Offset), symbol_name, symbol_address, file_name,
line_number);
- fflush(stderr);
- }
-
- free(symbol);
-}
-
+ fflush(stderr);
+ }
+
+ free(symbol);
+}
+
static void print_current_stack() {
CONTEXT context;
RtlCaptureContext(&context);
print_stack_from_context(GetCurrentThread(), context);
}
-static LONG crash_handler(struct _EXCEPTION_POINTERS* ex_info) {
- fprintf(stderr, "Exception handler called, dumping information\n");
- bool try_to_print_stack = true;
- PEXCEPTION_RECORD exrec = ex_info->ExceptionRecord;
- while (exrec) {
- DWORD code = exrec->ExceptionCode;
- DWORD flgs = exrec->ExceptionFlags;
- PVOID addr = exrec->ExceptionAddress;
- if (code == EXCEPTION_STACK_OVERFLOW) try_to_print_stack = false;
- fprintf(stderr, "code: %x - flags: %d - address: %p\n", code, flgs, addr);
- exrec = exrec->ExceptionRecord;
- }
- if (try_to_print_stack) {
+static LONG crash_handler(struct _EXCEPTION_POINTERS* ex_info) {
+ fprintf(stderr, "Exception handler called, dumping information\n");
+ bool try_to_print_stack = true;
+ PEXCEPTION_RECORD exrec = ex_info->ExceptionRecord;
+ while (exrec) {
+ DWORD code = exrec->ExceptionCode;
+ DWORD flgs = exrec->ExceptionFlags;
+ PVOID addr = exrec->ExceptionAddress;
+ if (code == EXCEPTION_STACK_OVERFLOW) try_to_print_stack = false;
+ fprintf(stderr, "code: %x - flags: %d - address: %p\n", code, flgs, addr);
+ exrec = exrec->ExceptionRecord;
+ }
+ if (try_to_print_stack) {
print_stack_from_context(GetCurrentThread(), *ex_info->ContextRecord);
- }
- if (IsDebuggerPresent()) {
- __debugbreak();
- } else {
- _exit(1);
- }
- return EXCEPTION_EXECUTE_HANDLER;
-}
-
-static void abort_handler(int sig) {
- fprintf(stderr, "Abort handler called.\n");
- print_current_stack();
- if (IsDebuggerPresent()) {
- __debugbreak();
- } else {
- _exit(1);
- }
-}
-
-static void install_crash_handler() {
- if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
- fprintf(stderr, "SymInitialize failed: %d\n", GetLastError());
- }
- SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)crash_handler);
- _set_abort_behavior(0, _WRITE_ABORT_MSG);
- _set_abort_behavior(0, _CALL_REPORTFAULT);
- signal(SIGABRT, abort_handler);
-}
-#elif GPR_POSIX_CRASH_HANDLER
-#include <errno.h>
-#include <execinfo.h>
-#include <stdio.h>
-#include <string.h>
-
-#define SIGNAL_NAMES_LENGTH 32
-
-static const char* const signal_names[] = {
- nullptr, "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",
- "SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV",
- "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD",
- "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG",
- "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO",
- "SIGPWR", "SIGSYS"};
-
-static char g_alt_stack[GPR_MAX(MINSIGSTKSZ, 65536)];
-
-#define MAX_FRAMES 32
-
-/* signal safe output */
-static void output_string(const char* string) {
- size_t len = strlen(string);
- ssize_t r;
-
- do {
- r = write(STDERR_FILENO, string, len);
- } while (r == -1 && errno == EINTR);
-}
-
-static void output_num(long num) {
- char buf[GPR_LTOA_MIN_BUFSIZE];
- gpr_ltoa(num, buf);
- output_string(buf);
-}
-
-static void crash_handler(int signum, siginfo_t* /*info*/, void* /*data*/) {
- void* addrlist[MAX_FRAMES + 1];
- int addrlen;
-
- output_string("\n\n\n*******************************\nCaught signal ");
- if (signum > 0 && signum < SIGNAL_NAMES_LENGTH) {
- output_string(signal_names[signum]);
- } else {
- output_num(signum);
- }
- output_string("\n");
-
- addrlen = backtrace(addrlist, GPR_ARRAY_SIZE(addrlist));
-
- if (addrlen == 0) {
- output_string(" no backtrace\n");
- } else {
- backtrace_symbols_fd(addrlist, addrlen, STDERR_FILENO);
- }
-
- /* try to get a core dump for SIGTERM */
- if (signum == SIGTERM) signum = SIGQUIT;
- raise(signum);
-}
-
-static void install_crash_handler() {
- stack_t ss;
- struct sigaction sa;
-
- memset(&ss, 0, sizeof(ss));
- memset(&sa, 0, sizeof(sa));
- ss.ss_size = sizeof(g_alt_stack);
- ss.ss_sp = g_alt_stack;
- GPR_ASSERT(sigaltstack(&ss, nullptr) == 0);
- sa.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_RESETHAND);
- sa.sa_sigaction = crash_handler;
- GPR_ASSERT(sigaction(SIGILL, &sa, nullptr) == 0);
- GPR_ASSERT(sigaction(SIGABRT, &sa, nullptr) == 0);
- GPR_ASSERT(sigaction(SIGBUS, &sa, nullptr) == 0);
- GPR_ASSERT(sigaction(SIGSEGV, &sa, nullptr) == 0);
- GPR_ASSERT(sigaction(SIGTERM, &sa, nullptr) == 0);
- GPR_ASSERT(sigaction(SIGQUIT, &sa, nullptr) == 0);
-}
-#else
-static void install_crash_handler() {}
-#endif
-
-bool BuiltUnderValgrind() {
-#ifdef RUNNING_ON_VALGRIND
- return true;
-#else
- return false;
-#endif
-}
-
-bool BuiltUnderTsan() {
-#if defined(__has_feature)
-#if __has_feature(thread_sanitizer)
- return true;
-#else
- return false;
-#endif
-#else
-#ifdef THREAD_SANITIZER
- return true;
-#else
- return false;
-#endif
-#endif
-}
-
-bool BuiltUnderAsan() {
-#if defined(__has_feature)
-#if __has_feature(address_sanitizer)
- return true;
-#else
- return false;
-#endif
-#else
-#ifdef ADDRESS_SANITIZER
- return true;
-#else
- return false;
-#endif
-#endif
-}
-
-bool BuiltUnderMsan() {
-#if defined(__has_feature)
-#if __has_feature(memory_sanitizer)
- return true;
-#else
- return false;
-#endif
-#else
-#ifdef MEMORY_SANITIZER
- return true;
-#else
- return false;
-#endif
-#endif
-}
-
-bool BuiltUnderUbsan() {
-#ifdef GRPC_UBSAN
- return true;
-#else
- return false;
-#endif
-}
-
-int64_t grpc_test_sanitizer_slowdown_factor() {
- int64_t sanitizer_multiplier = 1;
- if (BuiltUnderValgrind()) {
- sanitizer_multiplier = 20;
- } else if (BuiltUnderTsan()) {
- sanitizer_multiplier = 5;
- } else if (BuiltUnderAsan()) {
- sanitizer_multiplier = 3;
- } else if (BuiltUnderMsan()) {
- sanitizer_multiplier = 4;
- } else if (BuiltUnderUbsan()) {
- sanitizer_multiplier = 5;
- }
- return sanitizer_multiplier;
-}
-
-int64_t grpc_test_slowdown_factor() {
- return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor *
- g_poller_slowdown_factor;
-}
-
-gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) {
- return gpr_time_add(
- gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(
- grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s,
- GPR_TIMESPAN));
-}
-
-gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) {
- return gpr_time_add(
- gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(
- grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms,
- GPR_TIMESPAN));
-}
-
+ }
+ if (IsDebuggerPresent()) {
+ __debugbreak();
+ } else {
+ _exit(1);
+ }
+ return EXCEPTION_EXECUTE_HANDLER;
+}
+
+static void abort_handler(int sig) {
+ fprintf(stderr, "Abort handler called.\n");
+ print_current_stack();
+ if (IsDebuggerPresent()) {
+ __debugbreak();
+ } else {
+ _exit(1);
+ }
+}
+
+static void install_crash_handler() {
+ if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
+ fprintf(stderr, "SymInitialize failed: %d\n", GetLastError());
+ }
+ SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)crash_handler);
+ _set_abort_behavior(0, _WRITE_ABORT_MSG);
+ _set_abort_behavior(0, _CALL_REPORTFAULT);
+ signal(SIGABRT, abort_handler);
+}
+#elif GPR_POSIX_CRASH_HANDLER
+#include <errno.h>
+#include <execinfo.h>
+#include <stdio.h>
+#include <string.h>
+
+#define SIGNAL_NAMES_LENGTH 32
+
+static const char* const signal_names[] = {
+ nullptr, "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",
+ "SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV",
+ "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD",
+ "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG",
+ "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO",
+ "SIGPWR", "SIGSYS"};
+
+static char g_alt_stack[GPR_MAX(MINSIGSTKSZ, 65536)];
+
+#define MAX_FRAMES 32
+
+/* signal safe output */
+static void output_string(const char* string) {
+ size_t len = strlen(string);
+ ssize_t r;
+
+ do {
+ r = write(STDERR_FILENO, string, len);
+ } while (r == -1 && errno == EINTR);
+}
+
+static void output_num(long num) {
+ char buf[GPR_LTOA_MIN_BUFSIZE];
+ gpr_ltoa(num, buf);
+ output_string(buf);
+}
+
+static void crash_handler(int signum, siginfo_t* /*info*/, void* /*data*/) {
+ void* addrlist[MAX_FRAMES + 1];
+ int addrlen;
+
+ output_string("\n\n\n*******************************\nCaught signal ");
+ if (signum > 0 && signum < SIGNAL_NAMES_LENGTH) {
+ output_string(signal_names[signum]);
+ } else {
+ output_num(signum);
+ }
+ output_string("\n");
+
+ addrlen = backtrace(addrlist, GPR_ARRAY_SIZE(addrlist));
+
+ if (addrlen == 0) {
+ output_string(" no backtrace\n");
+ } else {
+ backtrace_symbols_fd(addrlist, addrlen, STDERR_FILENO);
+ }
+
+ /* try to get a core dump for SIGTERM */
+ if (signum == SIGTERM) signum = SIGQUIT;
+ raise(signum);
+}
+
+static void install_crash_handler() {
+ stack_t ss;
+ struct sigaction sa;
+
+ memset(&ss, 0, sizeof(ss));
+ memset(&sa, 0, sizeof(sa));
+ ss.ss_size = sizeof(g_alt_stack);
+ ss.ss_sp = g_alt_stack;
+ GPR_ASSERT(sigaltstack(&ss, nullptr) == 0);
+ sa.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_RESETHAND);
+ sa.sa_sigaction = crash_handler;
+ GPR_ASSERT(sigaction(SIGILL, &sa, nullptr) == 0);
+ GPR_ASSERT(sigaction(SIGABRT, &sa, nullptr) == 0);
+ GPR_ASSERT(sigaction(SIGBUS, &sa, nullptr) == 0);
+ GPR_ASSERT(sigaction(SIGSEGV, &sa, nullptr) == 0);
+ GPR_ASSERT(sigaction(SIGTERM, &sa, nullptr) == 0);
+ GPR_ASSERT(sigaction(SIGQUIT, &sa, nullptr) == 0);
+}
+#else
+static void install_crash_handler() {}
+#endif
+
+bool BuiltUnderValgrind() {
+#ifdef RUNNING_ON_VALGRIND
+ return true;
+#else
+ return false;
+#endif
+}
+
+bool BuiltUnderTsan() {
+#if defined(__has_feature)
+#if __has_feature(thread_sanitizer)
+ return true;
+#else
+ return false;
+#endif
+#else
+#ifdef THREAD_SANITIZER
+ return true;
+#else
+ return false;
+#endif
+#endif
+}
+
+bool BuiltUnderAsan() {
+#if defined(__has_feature)
+#if __has_feature(address_sanitizer)
+ return true;
+#else
+ return false;
+#endif
+#else
+#ifdef ADDRESS_SANITIZER
+ return true;
+#else
+ return false;
+#endif
+#endif
+}
+
+bool BuiltUnderMsan() {
+#if defined(__has_feature)
+#if __has_feature(memory_sanitizer)
+ return true;
+#else
+ return false;
+#endif
+#else
+#ifdef MEMORY_SANITIZER
+ return true;
+#else
+ return false;
+#endif
+#endif
+}
+
+bool BuiltUnderUbsan() {
+#ifdef GRPC_UBSAN
+ return true;
+#else
+ return false;
+#endif
+}
+
+int64_t grpc_test_sanitizer_slowdown_factor() {
+ int64_t sanitizer_multiplier = 1;
+ if (BuiltUnderValgrind()) {
+ sanitizer_multiplier = 20;
+ } else if (BuiltUnderTsan()) {
+ sanitizer_multiplier = 5;
+ } else if (BuiltUnderAsan()) {
+ sanitizer_multiplier = 3;
+ } else if (BuiltUnderMsan()) {
+ sanitizer_multiplier = 4;
+ } else if (BuiltUnderUbsan()) {
+ sanitizer_multiplier = 5;
+ }
+ return sanitizer_multiplier;
+}
+
+int64_t grpc_test_slowdown_factor() {
+ return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor *
+ g_poller_slowdown_factor;
+}
+
+gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) {
+ return gpr_time_add(
+ gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_millis(
+ grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s,
+ GPR_TIMESPAN));
+}
+
+gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) {
+ return gpr_time_add(
+ gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_micros(
+ grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms,
+ GPR_TIMESPAN));
+}
+
void grpc_test_init(int argc, char** argv) {
#if GPR_WINDOWS
// Windows cannot use y_absl::InitializeSymbolizer until it fixes mysterious
// SymInitialize failure using Bazel RBE on Windows
// https://github.com/grpc/grpc/issues/24178
- install_crash_handler();
+ install_crash_handler();
#else
y_absl::InitializeSymbolizer(argv[0]);
y_absl::FailureSignalHandlerOptions options;
y_absl::InstallFailureSignalHandler(options);
#endif
- gpr_log(GPR_DEBUG,
- "test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64
- ", poller=%" PRId64 ", total=%" PRId64,
- grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor,
- g_poller_slowdown_factor, grpc_test_slowdown_factor());
- /* seed rng with pid, so we don't end up with the same random numbers as a
- concurrently running test binary */
- srand(seed());
-}
-
+ gpr_log(GPR_DEBUG,
+ "test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64
+ ", poller=%" PRId64 ", total=%" PRId64,
+ grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor,
+ g_poller_slowdown_factor, grpc_test_slowdown_factor());
+ /* seed rng with pid, so we don't end up with the same random numbers as a
+ concurrently running test binary */
+ srand(seed());
+}
+
bool grpc_wait_until_shutdown(int64_t time_s) {
gpr_timespec deadline = grpc_timeout_seconds_to_deadline(time_s);
while (grpc_is_initialized()) {
@@ -405,13 +405,13 @@ bool grpc_wait_until_shutdown(int64_t time_s) {
return true;
}
-namespace grpc {
-namespace testing {
-
-TestEnvironment::TestEnvironment(int argc, char** argv) {
- grpc_test_init(argc, argv);
-}
-
+namespace grpc {
+namespace testing {
+
+TestEnvironment::TestEnvironment(int argc, char** argv) {
+ grpc_test_init(argc, argv);
+}
+
TestEnvironment::~TestEnvironment() {
// This will wait until gRPC shutdown has actually happened to make sure
// no gRPC resources (such as thread) are active. (timeout = 10s)
@@ -429,7 +429,7 @@ TestEnvironment::~TestEnvironment() {
}
gpr_log(GPR_INFO, "TestEnvironment ends");
}
-
+
TestGrpcScope::TestGrpcScope() { grpc_init(); }
TestGrpcScope::~TestGrpcScope() {
@@ -439,5 +439,5 @@ TestGrpcScope::~TestGrpcScope() {
}
}
-} // namespace testing
-} // namespace grpc
+} // namespace testing
+} // namespace grpc
diff --git a/contrib/libs/grpc/test/core/util/test_config.h b/contrib/libs/grpc/test/core/util/test_config.h
index 6ac43de266..63ad2a51ba 100644
--- a/contrib/libs/grpc/test/core/util/test_config.h
+++ b/contrib/libs/grpc/test/core/util/test_config.h
@@ -1,42 +1,42 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_TEST_CONFIG_H
-#define GRPC_TEST_CORE_UTIL_TEST_CONFIG_H
-
-#include <grpc/support/time.h>
-
-extern int64_t g_fixture_slowdown_factor;
-extern int64_t g_poller_slowdown_factor;
-
-/* Returns an appropriate scaling factor for timeouts. */
-int64_t grpc_test_slowdown_factor();
-
-/* Converts a given timeout (in seconds) to a deadline. */
-gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s);
-
-/* Converts a given timeout (in milliseconds) to a deadline. */
-gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms);
-
-#if !defined(GRPC_TEST_CUSTOM_PICK_PORT) && !defined(GRPC_PORT_ISOLATED_RUNTIME)
-#define GRPC_TEST_PICK_PORT
-#endif
-
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_TEST_CONFIG_H
+#define GRPC_TEST_CORE_UTIL_TEST_CONFIG_H
+
+#include <grpc/support/time.h>
+
+extern int64_t g_fixture_slowdown_factor;
+extern int64_t g_poller_slowdown_factor;
+
+/* Returns an appropriate scaling factor for timeouts. */
+int64_t grpc_test_slowdown_factor();
+
+/* Converts a given timeout (in seconds) to a deadline. */
+gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s);
+
+/* Converts a given timeout (in milliseconds) to a deadline. */
+gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms);
+
+#if !defined(GRPC_TEST_CUSTOM_PICK_PORT) && !defined(GRPC_PORT_ISOLATED_RUNTIME)
+#define GRPC_TEST_PICK_PORT
+#endif
+
// Returns whether this is built under ThreadSanitizer
bool BuiltUnderTsan();
@@ -49,24 +49,24 @@ bool BuiltUnderMsan();
// Returns whether this is built under UndefinedBehaviorSanitizer
bool BuiltUnderUbsan();
-// Prefer TestEnvironment below.
-void grpc_test_init(int argc, char** argv);
-
+// Prefer TestEnvironment below.
+void grpc_test_init(int argc, char** argv);
+
// Wait until gRPC is fully shut down.
// Returns if grpc is shutdown
bool grpc_wait_until_shutdown(int64_t time_s);
-namespace grpc {
-namespace testing {
-
-// A TestEnvironment object should be alive in the main function of a test. It
-// provides test init and shutdown inside.
-class TestEnvironment {
- public:
- TestEnvironment(int argc, char** argv);
- ~TestEnvironment();
-};
-
+namespace grpc {
+namespace testing {
+
+// A TestEnvironment object should be alive in the main function of a test. It
+// provides test init and shutdown inside.
+class TestEnvironment {
+ public:
+ TestEnvironment(int argc, char** argv);
+ ~TestEnvironment();
+};
+
// A TestGrpcScope makes sure that
// - when it's created, gRPC will be initialized
// - when it's destroyed, gRPC will shutdown and it waits until shutdown
@@ -76,7 +76,7 @@ class TestGrpcScope {
~TestGrpcScope();
};
-} // namespace testing
-} // namespace grpc
-
-#endif /* GRPC_TEST_CORE_UTIL_TEST_CONFIG_H */
+} // namespace testing
+} // namespace grpc
+
+#endif /* GRPC_TEST_CORE_UTIL_TEST_CONFIG_H */
diff --git a/contrib/libs/grpc/test/core/util/test_lb_policies.cc b/contrib/libs/grpc/test/core/util/test_lb_policies.cc
index c1c1e9c56a..e163d7b9cb 100644
--- a/contrib/libs/grpc/test/core/util/test_lb_policies.cc
+++ b/contrib/libs/grpc/test/core/util/test_lb_policies.cc
@@ -1,84 +1,84 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include "test/core/util/test_lb_policies.h"
-
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include "test/core/util/test_lb_policies.h"
+
#include <util/generic/string.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/combiner.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/pollset_set.h"
-#include "src/core/lib/json/json.h"
-#include "src/core/lib/transport/connectivity_state.h"
-
-namespace grpc_core {
-
-namespace {
-
-//
-// ForwardingLoadBalancingPolicy
-//
-
-// A minimal forwarding class to avoid implementing a standalone test LB.
-class ForwardingLoadBalancingPolicy : public LoadBalancingPolicy {
- public:
- ForwardingLoadBalancingPolicy(
- std::unique_ptr<ChannelControlHelper> delegating_helper, Args args,
+
+#include <grpc/support/log.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy.h"
+#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/channelz.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/combiner.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/pollset_set.h"
+#include "src/core/lib/json/json.h"
+#include "src/core/lib/transport/connectivity_state.h"
+
+namespace grpc_core {
+
+namespace {
+
+//
+// ForwardingLoadBalancingPolicy
+//
+
+// A minimal forwarding class to avoid implementing a standalone test LB.
+class ForwardingLoadBalancingPolicy : public LoadBalancingPolicy {
+ public:
+ ForwardingLoadBalancingPolicy(
+ std::unique_ptr<ChannelControlHelper> delegating_helper, Args args,
const TString& delegate_policy_name, intptr_t initial_refcount = 1)
- : LoadBalancingPolicy(std::move(args), initial_refcount) {
- Args delegate_args;
+ : LoadBalancingPolicy(std::move(args), initial_refcount) {
+ Args delegate_args;
delegate_args.work_serializer = work_serializer();
- delegate_args.channel_control_helper = std::move(delegating_helper);
- delegate_args.args = args.args;
- delegate_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
- delegate_policy_name.c_str(), std::move(delegate_args));
- grpc_pollset_set_add_pollset_set(delegate_->interested_parties(),
- interested_parties());
- }
-
- ~ForwardingLoadBalancingPolicy() override = default;
-
- void UpdateLocked(UpdateArgs args) override {
- delegate_->UpdateLocked(std::move(args));
- }
-
- void ExitIdleLocked() override { delegate_->ExitIdleLocked(); }
-
- void ResetBackoffLocked() override { delegate_->ResetBackoffLocked(); }
-
- private:
- void ShutdownLocked() override { delegate_.reset(); }
-
- OrphanablePtr<LoadBalancingPolicy> delegate_;
-};
-
-//
+ delegate_args.channel_control_helper = std::move(delegating_helper);
+ delegate_args.args = args.args;
+ delegate_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
+ delegate_policy_name.c_str(), std::move(delegate_args));
+ grpc_pollset_set_add_pollset_set(delegate_->interested_parties(),
+ interested_parties());
+ }
+
+ ~ForwardingLoadBalancingPolicy() override = default;
+
+ void UpdateLocked(UpdateArgs args) override {
+ delegate_->UpdateLocked(std::move(args));
+ }
+
+ void ExitIdleLocked() override { delegate_->ExitIdleLocked(); }
+
+ void ResetBackoffLocked() override { delegate_->ResetBackoffLocked(); }
+
+ private:
+ void ShutdownLocked() override { delegate_.reset(); }
+
+ OrphanablePtr<LoadBalancingPolicy> delegate_;
+};
+
+//
// CopyMetadataToVector()
//
@@ -191,117 +191,117 @@ class TestPickArgsLbFactory : public LoadBalancingPolicyFactory {
};
//
-// InterceptRecvTrailingMetadataLoadBalancingPolicy
-//
-
-constexpr char kInterceptRecvTrailingMetadataLbPolicyName[] =
- "intercept_trailing_metadata_lb";
-
-class InterceptRecvTrailingMetadataLoadBalancingPolicy
- : public ForwardingLoadBalancingPolicy {
- public:
- InterceptRecvTrailingMetadataLoadBalancingPolicy(
+// InterceptRecvTrailingMetadataLoadBalancingPolicy
+//
+
+constexpr char kInterceptRecvTrailingMetadataLbPolicyName[] =
+ "intercept_trailing_metadata_lb";
+
+class InterceptRecvTrailingMetadataLoadBalancingPolicy
+ : public ForwardingLoadBalancingPolicy {
+ public:
+ InterceptRecvTrailingMetadataLoadBalancingPolicy(
Args args, InterceptRecvTrailingMetadataCallback cb)
- : ForwardingLoadBalancingPolicy(
+ : ForwardingLoadBalancingPolicy(
y_absl::make_unique<Helper>(
- RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy>(
- this),
+ RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy>(
+ this),
std::move(cb)),
- std::move(args),
- /*delegate_lb_policy_name=*/"pick_first",
- /*initial_refcount=*/2) {}
-
- ~InterceptRecvTrailingMetadataLoadBalancingPolicy() override = default;
-
- const char* name() const override {
- return kInterceptRecvTrailingMetadataLbPolicyName;
- }
-
- private:
- class Picker : public SubchannelPicker {
- public:
+ std::move(args),
+ /*delegate_lb_policy_name=*/"pick_first",
+ /*initial_refcount=*/2) {}
+
+ ~InterceptRecvTrailingMetadataLoadBalancingPolicy() override = default;
+
+ const char* name() const override {
+ return kInterceptRecvTrailingMetadataLbPolicyName;
+ }
+
+ private:
+ class Picker : public SubchannelPicker {
+ public:
Picker(std::unique_ptr<SubchannelPicker> delegate_picker,
InterceptRecvTrailingMetadataCallback cb)
: delegate_picker_(std::move(delegate_picker)), cb_(std::move(cb)) {}
-
- PickResult Pick(PickArgs args) override {
- // Do pick.
- PickResult result = delegate_picker_->Pick(args);
- // Intercept trailing metadata.
- if (result.type == PickResult::PICK_COMPLETE &&
- result.subchannel != nullptr) {
- new (args.call_state->Alloc(sizeof(TrailingMetadataHandler)))
+
+ PickResult Pick(PickArgs args) override {
+ // Do pick.
+ PickResult result = delegate_picker_->Pick(args);
+ // Intercept trailing metadata.
+ if (result.type == PickResult::PICK_COMPLETE &&
+ result.subchannel != nullptr) {
+ new (args.call_state->Alloc(sizeof(TrailingMetadataHandler)))
TrailingMetadataHandler(&result, cb_);
- }
- return result;
- }
-
- private:
- std::unique_ptr<SubchannelPicker> delegate_picker_;
- InterceptRecvTrailingMetadataCallback cb_;
- };
-
- class Helper : public ChannelControlHelper {
- public:
- Helper(
- RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent,
+ }
+ return result;
+ }
+
+ private:
+ std::unique_ptr<SubchannelPicker> delegate_picker_;
+ InterceptRecvTrailingMetadataCallback cb_;
+ };
+
+ class Helper : public ChannelControlHelper {
+ public:
+ Helper(
+ RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent,
InterceptRecvTrailingMetadataCallback cb)
: parent_(std::move(parent)), cb_(std::move(cb)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
+
+ RefCountedPtr<SubchannelInterface> CreateSubchannel(
ServerAddress address, const grpc_channel_args& args) override {
return parent_->channel_control_helper()->CreateSubchannel(
std::move(address), args);
- }
-
+ }
+
void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override {
- parent_->channel_control_helper()->UpdateState(
+ std::unique_ptr<SubchannelPicker> picker) override {
+ parent_->channel_control_helper()->UpdateState(
state, status, y_absl::make_unique<Picker>(std::move(picker), cb_));
- }
-
- void RequestReresolution() override {
- parent_->channel_control_helper()->RequestReresolution();
- }
-
+ }
+
+ void RequestReresolution() override {
+ parent_->channel_control_helper()->RequestReresolution();
+ }
+
void AddTraceEvent(TraceSeverity severity,
y_absl::string_view message) override {
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
- }
-
- private:
- RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent_;
- InterceptRecvTrailingMetadataCallback cb_;
- };
-
- class TrailingMetadataHandler {
- public:
- TrailingMetadataHandler(PickResult* result,
+ parent_->channel_control_helper()->AddTraceEvent(severity, message);
+ }
+
+ private:
+ RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent_;
+ InterceptRecvTrailingMetadataCallback cb_;
+ };
+
+ class TrailingMetadataHandler {
+ public:
+ TrailingMetadataHandler(PickResult* result,
InterceptRecvTrailingMetadataCallback cb)
: cb_(std::move(cb)) {
- result->recv_trailing_metadata_ready = [this](grpc_error* error,
- MetadataInterface* metadata,
- CallState* call_state) {
- RecordRecvTrailingMetadata(error, metadata, call_state);
- };
- }
-
- private:
- void RecordRecvTrailingMetadata(grpc_error* /*error*/,
- MetadataInterface* recv_trailing_metadata,
- CallState* call_state) {
+ result->recv_trailing_metadata_ready = [this](grpc_error* error,
+ MetadataInterface* metadata,
+ CallState* call_state) {
+ RecordRecvTrailingMetadata(error, metadata, call_state);
+ };
+ }
+
+ private:
+ void RecordRecvTrailingMetadata(grpc_error* /*error*/,
+ MetadataInterface* recv_trailing_metadata,
+ CallState* call_state) {
TrailingMetadataArgsSeen args_seen;
args_seen.backend_metric_data = call_state->GetBackendMetricData();
- GPR_ASSERT(recv_trailing_metadata != nullptr);
+ GPR_ASSERT(recv_trailing_metadata != nullptr);
args_seen.metadata = CopyMetadataToVector(recv_trailing_metadata);
cb_(args_seen);
- this->~TrailingMetadataHandler();
- }
-
- InterceptRecvTrailingMetadataCallback cb_;
- };
-};
-
+ this->~TrailingMetadataHandler();
+ }
+
+ InterceptRecvTrailingMetadataCallback cb_;
+ };
+};
+
class InterceptTrailingConfig : public LoadBalancingPolicy::Config {
public:
const char* name() const override {
@@ -309,30 +309,30 @@ class InterceptTrailingConfig : public LoadBalancingPolicy::Config {
}
};
-class InterceptTrailingFactory : public LoadBalancingPolicyFactory {
- public:
+class InterceptTrailingFactory : public LoadBalancingPolicyFactory {
+ public:
explicit InterceptTrailingFactory(InterceptRecvTrailingMetadataCallback cb)
: cb_(std::move(cb)) {}
-
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<InterceptRecvTrailingMetadataLoadBalancingPolicy>(
+
+ OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+ LoadBalancingPolicy::Args args) const override {
+ return MakeOrphanable<InterceptRecvTrailingMetadataLoadBalancingPolicy>(
std::move(args), cb_);
- }
-
- const char* name() const override {
- return kInterceptRecvTrailingMetadataLbPolicyName;
- }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
+ }
+
+ const char* name() const override {
+ return kInterceptRecvTrailingMetadataLbPolicyName;
+ }
+
+ RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& /*json*/, grpc_error** /*error*/) const override {
return MakeRefCounted<InterceptTrailingConfig>();
- }
-
- private:
- InterceptRecvTrailingMetadataCallback cb_;
-};
-
+ }
+
+ private:
+ InterceptRecvTrailingMetadataCallback cb_;
+};
+
//
// AddressTestLoadBalancingPolicy
//
@@ -414,22 +414,22 @@ class AddressTestFactory : public LoadBalancingPolicyFactory {
AddressTestCallback cb_;
};
-} // namespace
-
+} // namespace
+
void RegisterTestPickArgsLoadBalancingPolicy(TestPickArgsCallback cb) {
LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<TestPickArgsLbFactory>(std::move(cb)));
}
-void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
+void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
InterceptRecvTrailingMetadataCallback cb) {
- LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
+ LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<InterceptTrailingFactory>(std::move(cb)));
-}
-
+}
+
void RegisterAddressTestLoadBalancingPolicy(AddressTestCallback cb) {
LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<AddressTestFactory>(std::move(cb)));
}
-} // namespace grpc_core
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/test/core/util/test_lb_policies.h b/contrib/libs/grpc/test/core/util/test_lb_policies.h
index 9e14c707a3..a5c02283b6 100644
--- a/contrib/libs/grpc/test/core/util/test_lb_policies.h
+++ b/contrib/libs/grpc/test/core/util/test_lb_policies.h
@@ -1,30 +1,30 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
-#define GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
-
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-
-namespace grpc_core {
-
+/*
+ *
+ * Copyright 2018 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
+#define GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
+
+#include "src/core/ext/filters/client_channel/lb_policy.h"
+
+namespace grpc_core {
+
using MetadataVector = std::vector<std::pair<TString, TString>>;
-
+
struct PickArgsSeen {
TString path;
MetadataVector metadata;
@@ -44,17 +44,17 @@ struct TrailingMetadataArgsSeen {
using InterceptRecvTrailingMetadataCallback =
std::function<void(const TrailingMetadataArgsSeen&)>;
-// Registers an LB policy called "intercept_trailing_metadata_lb" that
+// Registers an LB policy called "intercept_trailing_metadata_lb" that
// invokes cb when trailing metadata is received for each call.
-void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
+void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
InterceptRecvTrailingMetadataCallback cb);
-
+
using AddressTestCallback = std::function<void(const ServerAddress&)>;
// Registers an LB policy called "address_test_lb" that invokes cb for each
// address used to create a subchannel.
void RegisterAddressTestLoadBalancingPolicy(AddressTestCallback cb);
-} // namespace grpc_core
-
-#endif // GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
+} // namespace grpc_core
+
+#endif // GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
diff --git a/contrib/libs/grpc/test/core/util/test_tcp_server.cc b/contrib/libs/grpc/test/core/util/test_tcp_server.cc
index 9dd1e2af36..9550ef6b08 100644
--- a/contrib/libs/grpc/test/core/util/test_tcp_server.cc
+++ b/contrib/libs/grpc/test/core/util/test_tcp_server.cc
@@ -1,116 +1,116 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/socket_utils.h"
-
-#include "test/core/util/test_tcp_server.h"
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-#include <string.h>
-
-#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-
-static void on_server_destroyed(void* data, grpc_error* /*error*/) {
- test_tcp_server* server = static_cast<test_tcp_server*>(data);
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/socket_utils.h"
+
+#include "test/core/util/test_tcp_server.h"
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include <string.h>
+
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+
+static void on_server_destroyed(void* data, grpc_error* /*error*/) {
+ test_tcp_server* server = static_cast<test_tcp_server*>(data);
server->shutdown = true;
-}
-
-void test_tcp_server_init(test_tcp_server* server,
- grpc_tcp_server_cb on_connect, void* user_data) {
- grpc_init();
- GRPC_CLOSURE_INIT(&server->shutdown_complete, on_server_destroyed, server,
- grpc_schedule_on_exec_ctx);
+}
+
+void test_tcp_server_init(test_tcp_server* server,
+ grpc_tcp_server_cb on_connect, void* user_data) {
+ grpc_init();
+ GRPC_CLOSURE_INIT(&server->shutdown_complete, on_server_destroyed, server,
+ grpc_schedule_on_exec_ctx);
grpc_pollset* pollset =
static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
grpc_pollset_init(pollset, &server->mu);
server->pollset.push_back(pollset);
- server->on_connect = on_connect;
- server->cb_data = user_data;
-}
-
-void test_tcp_server_start(test_tcp_server* server, int port) {
- grpc_resolved_address resolved_addr;
- grpc_sockaddr_in* addr =
- reinterpret_cast<grpc_sockaddr_in*>(resolved_addr.addr);
- int port_added;
- grpc_core::ExecCtx exec_ctx;
-
- addr->sin_family = GRPC_AF_INET;
- addr->sin_port = grpc_htons(static_cast<uint16_t>(port));
- memset(&addr->sin_addr, 0, sizeof(addr->sin_addr));
-
- grpc_error* error = grpc_tcp_server_create(&server->shutdown_complete,
- nullptr, &server->tcp_server);
- GPR_ASSERT(error == GRPC_ERROR_NONE);
- error =
- grpc_tcp_server_add_port(server->tcp_server, &resolved_addr, &port_added);
- GPR_ASSERT(error == GRPC_ERROR_NONE);
- GPR_ASSERT(port_added == port);
-
+ server->on_connect = on_connect;
+ server->cb_data = user_data;
+}
+
+void test_tcp_server_start(test_tcp_server* server, int port) {
+ grpc_resolved_address resolved_addr;
+ grpc_sockaddr_in* addr =
+ reinterpret_cast<grpc_sockaddr_in*>(resolved_addr.addr);
+ int port_added;
+ grpc_core::ExecCtx exec_ctx;
+
+ addr->sin_family = GRPC_AF_INET;
+ addr->sin_port = grpc_htons(static_cast<uint16_t>(port));
+ memset(&addr->sin_addr, 0, sizeof(addr->sin_addr));
+
+ grpc_error* error = grpc_tcp_server_create(&server->shutdown_complete,
+ nullptr, &server->tcp_server);
+ GPR_ASSERT(error == GRPC_ERROR_NONE);
+ error =
+ grpc_tcp_server_add_port(server->tcp_server, &resolved_addr, &port_added);
+ GPR_ASSERT(error == GRPC_ERROR_NONE);
+ GPR_ASSERT(port_added == port);
+
grpc_tcp_server_start(server->tcp_server, &server->pollset,
- server->on_connect, server->cb_data);
- gpr_log(GPR_INFO, "test tcp server listening on 0.0.0.0:%d", port);
-}
-
-void test_tcp_server_poll(test_tcp_server* server, int milliseconds) {
- grpc_pollset_worker* worker = nullptr;
- grpc_core::ExecCtx exec_ctx;
- grpc_millis deadline = grpc_timespec_to_millis_round_up(
- grpc_timeout_milliseconds_to_deadline(milliseconds));
- gpr_mu_lock(server->mu);
- GRPC_LOG_IF_ERROR("pollset_work",
+ server->on_connect, server->cb_data);
+ gpr_log(GPR_INFO, "test tcp server listening on 0.0.0.0:%d", port);
+}
+
+void test_tcp_server_poll(test_tcp_server* server, int milliseconds) {
+ grpc_pollset_worker* worker = nullptr;
+ grpc_core::ExecCtx exec_ctx;
+ grpc_millis deadline = grpc_timespec_to_millis_round_up(
+ grpc_timeout_milliseconds_to_deadline(milliseconds));
+ gpr_mu_lock(server->mu);
+ GRPC_LOG_IF_ERROR("pollset_work",
grpc_pollset_work(server->pollset[0], &worker, deadline));
- gpr_mu_unlock(server->mu);
-}
-
-static void do_nothing(void* /*arg*/, grpc_error* /*error*/) {}
-static void finish_pollset(void* arg, grpc_error* /*error*/) {
- grpc_pollset_destroy(static_cast<grpc_pollset*>(arg));
-}
-
-void test_tcp_server_destroy(test_tcp_server* server) {
- grpc_core::ExecCtx exec_ctx;
- gpr_timespec shutdown_deadline;
- grpc_closure do_nothing_cb;
- grpc_tcp_server_unref(server->tcp_server);
- GRPC_CLOSURE_INIT(&do_nothing_cb, do_nothing, nullptr,
- grpc_schedule_on_exec_ctx);
- shutdown_deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_seconds(5, GPR_TIMESPAN));
- grpc_core::ExecCtx::Get()->Flush();
- while (!server->shutdown &&
- gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), shutdown_deadline) < 0) {
- test_tcp_server_poll(server, 1000);
- }
+ gpr_mu_unlock(server->mu);
+}
+
+static void do_nothing(void* /*arg*/, grpc_error* /*error*/) {}
+static void finish_pollset(void* arg, grpc_error* /*error*/) {
+ grpc_pollset_destroy(static_cast<grpc_pollset*>(arg));
+}
+
+void test_tcp_server_destroy(test_tcp_server* server) {
+ grpc_core::ExecCtx exec_ctx;
+ gpr_timespec shutdown_deadline;
+ grpc_closure do_nothing_cb;
+ grpc_tcp_server_unref(server->tcp_server);
+ GRPC_CLOSURE_INIT(&do_nothing_cb, do_nothing, nullptr,
+ grpc_schedule_on_exec_ctx);
+ shutdown_deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_seconds(5, GPR_TIMESPAN));
+ grpc_core::ExecCtx::Get()->Flush();
+ while (!server->shutdown &&
+ gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), shutdown_deadline) < 0) {
+ test_tcp_server_poll(server, 1000);
+ }
grpc_pollset_shutdown(server->pollset[0],
GRPC_CLOSURE_CREATE(finish_pollset, server->pollset[0],
- grpc_schedule_on_exec_ctx));
- grpc_core::ExecCtx::Get()->Flush();
+ grpc_schedule_on_exec_ctx));
+ grpc_core::ExecCtx::Get()->Flush();
gpr_free(server->pollset[0]);
- grpc_shutdown();
-}
+ grpc_shutdown();
+}
diff --git a/contrib/libs/grpc/test/core/util/test_tcp_server.h b/contrib/libs/grpc/test/core/util/test_tcp_server.h
index 8765ea9a22..8b40f3a1be 100644
--- a/contrib/libs/grpc/test/core/util/test_tcp_server.h
+++ b/contrib/libs/grpc/test/core/util/test_tcp_server.h
@@ -1,47 +1,47 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H
-#define GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H
-
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H
+#define GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H
+
#include <vector>
-#include <grpc/support/sync.h>
-#include "src/core/lib/iomgr/tcp_server.h"
-
+#include <grpc/support/sync.h>
+#include "src/core/lib/iomgr/tcp_server.h"
+
// test_tcp_server should be stack-allocated or new'ed, never gpr_malloc'ed
// since it contains C++ objects.
struct test_tcp_server {
grpc_tcp_server* tcp_server = nullptr;
- grpc_closure shutdown_complete;
+ grpc_closure shutdown_complete;
bool shutdown = false;
// mu is filled in by grpc_pollset_init and controls the pollset.
// TODO: Switch this to a Mutex once pollset_init can provide a Mutex
- gpr_mu* mu;
+ gpr_mu* mu;
std::vector<grpc_pollset*> pollset;
- grpc_tcp_server_cb on_connect;
- void* cb_data;
+ grpc_tcp_server_cb on_connect;
+ void* cb_data;
};
-
-void test_tcp_server_init(test_tcp_server* server,
- grpc_tcp_server_cb on_connect, void* user_data);
-void test_tcp_server_start(test_tcp_server* server, int port);
-void test_tcp_server_poll(test_tcp_server* server, int milliseconds);
-void test_tcp_server_destroy(test_tcp_server* server);
-
-#endif /* GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H */
+
+void test_tcp_server_init(test_tcp_server* server,
+ grpc_tcp_server_cb on_connect, void* user_data);
+void test_tcp_server_start(test_tcp_server* server, int port);
+void test_tcp_server_poll(test_tcp_server* server, int milliseconds);
+void test_tcp_server_destroy(test_tcp_server* server);
+
+#endif /* GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H */
diff --git a/contrib/libs/grpc/test/core/util/tracer_util.cc b/contrib/libs/grpc/test/core/util/tracer_util.cc
index 34a132daa7..6b4dfbdccd 100644
--- a/contrib/libs/grpc/test/core/util/tracer_util.cc
+++ b/contrib/libs/grpc/test/core/util/tracer_util.cc
@@ -1,31 +1,31 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include "test/core/util/test_config.h"
-
-#include "src/core/lib/debug/trace.h"
-
-namespace grpc_core {
-namespace testing {
-
-void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag) {
- flag->set_enabled(1);
-}
-
-} // namespace testing
-} // namespace grpc_core
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include "test/core/util/test_config.h"
+
+#include "src/core/lib/debug/trace.h"
+
+namespace grpc_core {
+namespace testing {
+
+void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag) {
+ flag->set_enabled(1);
+}
+
+} // namespace testing
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/test/core/util/tracer_util.h b/contrib/libs/grpc/test/core/util/tracer_util.h
index 0b432ffa46..a4ad95ab5c 100644
--- a/contrib/libs/grpc/test/core/util/tracer_util.h
+++ b/contrib/libs/grpc/test/core/util/tracer_util.h
@@ -1,32 +1,32 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_TRACER_UTIL_H
-#define GRPC_TEST_CORE_UTIL_TRACER_UTIL_H
-
-namespace grpc_core {
-class TraceFlag;
-
-namespace testing {
-// enables the TraceFlag passed to it. Used for testing purposes.
-void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag);
-
-} // namespace testing
-} // namespace grpc_core
-
-#endif /* GRPC_TEST_CORE_UTIL_TRACER_UTIL_H */
+/*
+ *
+ * Copyright 2015 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CORE_UTIL_TRACER_UTIL_H
+#define GRPC_TEST_CORE_UTIL_TRACER_UTIL_H
+
+namespace grpc_core {
+class TraceFlag;
+
+namespace testing {
+// enables the TraceFlag passed to it. Used for testing purposes.
+void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag);
+
+} // namespace testing
+} // namespace grpc_core
+
+#endif /* GRPC_TEST_CORE_UTIL_TRACER_UTIL_H */
diff --git a/contrib/libs/grpc/test/core/util/trickle_endpoint.cc b/contrib/libs/grpc/test/core/util/trickle_endpoint.cc
index 28ffb0e3e7..496e2586ab 100644
--- a/contrib/libs/grpc/test/core/util/trickle_endpoint.cc
+++ b/contrib/libs/grpc/test/core/util/trickle_endpoint.cc
@@ -1,215 +1,215 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include "test/core/util/passthru_endpoint.h"
-
-#include <inttypes.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-#define WRITE_BUFFER_SIZE (2 * 1024 * 1024)
-
-typedef struct {
- grpc_endpoint base;
- double bytes_per_second;
- grpc_endpoint* wrapped;
- gpr_timespec last_write;
-
- gpr_mu mu;
- grpc_slice_buffer write_buffer;
- grpc_slice_buffer writing_buffer;
- grpc_error* error;
- bool writing;
- grpc_closure* write_cb;
-} trickle_endpoint;
-
-static void te_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, bool urgent) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- grpc_endpoint_read(te->wrapped, slices, cb, urgent);
-}
-
-static void maybe_call_write_cb_locked(trickle_endpoint* te) {
- if (te->write_cb != nullptr &&
- (te->error != GRPC_ERROR_NONE ||
- te->write_buffer.length <= WRITE_BUFFER_SIZE)) {
- grpc_core::ExecCtx::Run(DEBUG_LOCATION, te->write_cb,
- GRPC_ERROR_REF(te->error));
- te->write_cb = nullptr;
- }
-}
-
-static void te_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
- grpc_closure* cb, void* /*arg*/) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- gpr_mu_lock(&te->mu);
- GPR_ASSERT(te->write_cb == nullptr);
- if (te->write_buffer.length == 0) {
- te->last_write = gpr_now(GPR_CLOCK_MONOTONIC);
- }
- for (size_t i = 0; i < slices->count; i++) {
- grpc_slice_buffer_add(&te->write_buffer,
- grpc_slice_copy(slices->slices[i]));
- }
- te->write_cb = cb;
- maybe_call_write_cb_locked(te);
- gpr_mu_unlock(&te->mu);
-}
-
-static void te_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- grpc_endpoint_add_to_pollset(te->wrapped, pollset);
-}
-
-static void te_add_to_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- grpc_endpoint_add_to_pollset_set(te->wrapped, pollset_set);
-}
-
-static void te_delete_from_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- grpc_endpoint_delete_from_pollset_set(te->wrapped, pollset_set);
-}
-
-static void te_shutdown(grpc_endpoint* ep, grpc_error* why) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- gpr_mu_lock(&te->mu);
- if (te->error == GRPC_ERROR_NONE) {
- te->error = GRPC_ERROR_REF(why);
- }
- maybe_call_write_cb_locked(te);
- gpr_mu_unlock(&te->mu);
- grpc_endpoint_shutdown(te->wrapped, why);
-}
-
-static void te_destroy(grpc_endpoint* ep) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- grpc_endpoint_destroy(te->wrapped);
- gpr_mu_destroy(&te->mu);
- grpc_slice_buffer_destroy_internal(&te->write_buffer);
- grpc_slice_buffer_destroy_internal(&te->writing_buffer);
- GRPC_ERROR_UNREF(te->error);
- gpr_free(te);
-}
-
-static grpc_resource_user* te_get_resource_user(grpc_endpoint* ep) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- return grpc_endpoint_get_resource_user(te->wrapped);
-}
-
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include "test/core/util/passthru_endpoint.h"
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+#define WRITE_BUFFER_SIZE (2 * 1024 * 1024)
+
+typedef struct {
+ grpc_endpoint base;
+ double bytes_per_second;
+ grpc_endpoint* wrapped;
+ gpr_timespec last_write;
+
+ gpr_mu mu;
+ grpc_slice_buffer write_buffer;
+ grpc_slice_buffer writing_buffer;
+ grpc_error* error;
+ bool writing;
+ grpc_closure* write_cb;
+} trickle_endpoint;
+
+static void te_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
+ grpc_closure* cb, bool urgent) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ grpc_endpoint_read(te->wrapped, slices, cb, urgent);
+}
+
+static void maybe_call_write_cb_locked(trickle_endpoint* te) {
+ if (te->write_cb != nullptr &&
+ (te->error != GRPC_ERROR_NONE ||
+ te->write_buffer.length <= WRITE_BUFFER_SIZE)) {
+ grpc_core::ExecCtx::Run(DEBUG_LOCATION, te->write_cb,
+ GRPC_ERROR_REF(te->error));
+ te->write_cb = nullptr;
+ }
+}
+
+static void te_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
+ grpc_closure* cb, void* /*arg*/) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ gpr_mu_lock(&te->mu);
+ GPR_ASSERT(te->write_cb == nullptr);
+ if (te->write_buffer.length == 0) {
+ te->last_write = gpr_now(GPR_CLOCK_MONOTONIC);
+ }
+ for (size_t i = 0; i < slices->count; i++) {
+ grpc_slice_buffer_add(&te->write_buffer,
+ grpc_slice_copy(slices->slices[i]));
+ }
+ te->write_cb = cb;
+ maybe_call_write_cb_locked(te);
+ gpr_mu_unlock(&te->mu);
+}
+
+static void te_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ grpc_endpoint_add_to_pollset(te->wrapped, pollset);
+}
+
+static void te_add_to_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ grpc_endpoint_add_to_pollset_set(te->wrapped, pollset_set);
+}
+
+static void te_delete_from_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ grpc_endpoint_delete_from_pollset_set(te->wrapped, pollset_set);
+}
+
+static void te_shutdown(grpc_endpoint* ep, grpc_error* why) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ gpr_mu_lock(&te->mu);
+ if (te->error == GRPC_ERROR_NONE) {
+ te->error = GRPC_ERROR_REF(why);
+ }
+ maybe_call_write_cb_locked(te);
+ gpr_mu_unlock(&te->mu);
+ grpc_endpoint_shutdown(te->wrapped, why);
+}
+
+static void te_destroy(grpc_endpoint* ep) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ grpc_endpoint_destroy(te->wrapped);
+ gpr_mu_destroy(&te->mu);
+ grpc_slice_buffer_destroy_internal(&te->write_buffer);
+ grpc_slice_buffer_destroy_internal(&te->writing_buffer);
+ GRPC_ERROR_UNREF(te->error);
+ gpr_free(te);
+}
+
+static grpc_resource_user* te_get_resource_user(grpc_endpoint* ep) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ return grpc_endpoint_get_resource_user(te->wrapped);
+}
+
static y_absl::string_view te_get_peer(grpc_endpoint* ep) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- return grpc_endpoint_get_peer(te->wrapped);
-}
-
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ return grpc_endpoint_get_peer(te->wrapped);
+}
+
static y_absl::string_view te_get_local_address(grpc_endpoint* ep) {
trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
return grpc_endpoint_get_local_address(te->wrapped);
}
-static int te_get_fd(grpc_endpoint* ep) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- return grpc_endpoint_get_fd(te->wrapped);
-}
-
-static bool te_can_track_err(grpc_endpoint* /*ep*/) { return false; }
-
-static void te_finish_write(void* arg, grpc_error* /*error*/) {
- trickle_endpoint* te = static_cast<trickle_endpoint*>(arg);
- gpr_mu_lock(&te->mu);
- te->writing = false;
- grpc_slice_buffer_reset_and_unref(&te->writing_buffer);
- gpr_mu_unlock(&te->mu);
-}
-
-static const grpc_endpoint_vtable vtable = {te_read,
- te_write,
- te_add_to_pollset,
- te_add_to_pollset_set,
- te_delete_from_pollset_set,
- te_shutdown,
- te_destroy,
- te_get_resource_user,
- te_get_peer,
+static int te_get_fd(grpc_endpoint* ep) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ return grpc_endpoint_get_fd(te->wrapped);
+}
+
+static bool te_can_track_err(grpc_endpoint* /*ep*/) { return false; }
+
+static void te_finish_write(void* arg, grpc_error* /*error*/) {
+ trickle_endpoint* te = static_cast<trickle_endpoint*>(arg);
+ gpr_mu_lock(&te->mu);
+ te->writing = false;
+ grpc_slice_buffer_reset_and_unref(&te->writing_buffer);
+ gpr_mu_unlock(&te->mu);
+}
+
+static const grpc_endpoint_vtable vtable = {te_read,
+ te_write,
+ te_add_to_pollset,
+ te_add_to_pollset_set,
+ te_delete_from_pollset_set,
+ te_shutdown,
+ te_destroy,
+ te_get_resource_user,
+ te_get_peer,
te_get_local_address,
- te_get_fd,
- te_can_track_err};
-
-grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap,
- double bytes_per_second) {
- trickle_endpoint* te =
- static_cast<trickle_endpoint*>(gpr_malloc(sizeof(*te)));
- te->base.vtable = &vtable;
- te->wrapped = wrap;
- te->bytes_per_second = bytes_per_second;
- te->write_cb = nullptr;
- gpr_mu_init(&te->mu);
- grpc_slice_buffer_init(&te->write_buffer);
- grpc_slice_buffer_init(&te->writing_buffer);
- te->error = GRPC_ERROR_NONE;
- te->writing = false;
- return &te->base;
-}
-
-static double ts2dbl(gpr_timespec s) {
- return static_cast<double>(s.tv_sec) + 1e-9 * static_cast<double>(s.tv_nsec);
-}
-
-size_t grpc_trickle_endpoint_trickle(grpc_endpoint* ep) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- gpr_mu_lock(&te->mu);
- if (!te->writing && te->write_buffer.length > 0) {
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- double elapsed = ts2dbl(gpr_time_sub(now, te->last_write));
- size_t bytes = static_cast<size_t>(te->bytes_per_second * elapsed);
- // gpr_log(GPR_DEBUG, "%lf elapsed --> %" PRIdPTR " bytes", elapsed, bytes);
- if (bytes > 0) {
- grpc_slice_buffer_move_first(&te->write_buffer,
- GPR_MIN(bytes, te->write_buffer.length),
- &te->writing_buffer);
- te->writing = true;
- te->last_write = now;
- grpc_endpoint_write(
- te->wrapped, &te->writing_buffer,
- GRPC_CLOSURE_CREATE(te_finish_write, te, grpc_schedule_on_exec_ctx),
- nullptr);
- maybe_call_write_cb_locked(te);
- }
- }
- size_t backlog = te->write_buffer.length;
- gpr_mu_unlock(&te->mu);
- return backlog;
-}
-
-size_t grpc_trickle_get_backlog(grpc_endpoint* ep) {
- trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
- gpr_mu_lock(&te->mu);
- size_t backlog = te->write_buffer.length;
- gpr_mu_unlock(&te->mu);
- return backlog;
-}
+ te_get_fd,
+ te_can_track_err};
+
+grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap,
+ double bytes_per_second) {
+ trickle_endpoint* te =
+ static_cast<trickle_endpoint*>(gpr_malloc(sizeof(*te)));
+ te->base.vtable = &vtable;
+ te->wrapped = wrap;
+ te->bytes_per_second = bytes_per_second;
+ te->write_cb = nullptr;
+ gpr_mu_init(&te->mu);
+ grpc_slice_buffer_init(&te->write_buffer);
+ grpc_slice_buffer_init(&te->writing_buffer);
+ te->error = GRPC_ERROR_NONE;
+ te->writing = false;
+ return &te->base;
+}
+
+static double ts2dbl(gpr_timespec s) {
+ return static_cast<double>(s.tv_sec) + 1e-9 * static_cast<double>(s.tv_nsec);
+}
+
+size_t grpc_trickle_endpoint_trickle(grpc_endpoint* ep) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ gpr_mu_lock(&te->mu);
+ if (!te->writing && te->write_buffer.length > 0) {
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ double elapsed = ts2dbl(gpr_time_sub(now, te->last_write));
+ size_t bytes = static_cast<size_t>(te->bytes_per_second * elapsed);
+ // gpr_log(GPR_DEBUG, "%lf elapsed --> %" PRIdPTR " bytes", elapsed, bytes);
+ if (bytes > 0) {
+ grpc_slice_buffer_move_first(&te->write_buffer,
+ GPR_MIN(bytes, te->write_buffer.length),
+ &te->writing_buffer);
+ te->writing = true;
+ te->last_write = now;
+ grpc_endpoint_write(
+ te->wrapped, &te->writing_buffer,
+ GRPC_CLOSURE_CREATE(te_finish_write, te, grpc_schedule_on_exec_ctx),
+ nullptr);
+ maybe_call_write_cb_locked(te);
+ }
+ }
+ size_t backlog = te->write_buffer.length;
+ gpr_mu_unlock(&te->mu);
+ return backlog;
+}
+
+size_t grpc_trickle_get_backlog(grpc_endpoint* ep) {
+ trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep);
+ gpr_mu_lock(&te->mu);
+ size_t backlog = te->write_buffer.length;
+ gpr_mu_unlock(&te->mu);
+ return backlog;
+}
diff --git a/contrib/libs/grpc/test/core/util/trickle_endpoint.h b/contrib/libs/grpc/test/core/util/trickle_endpoint.h
index cd07de905a..4912747d2a 100644
--- a/contrib/libs/grpc/test/core/util/trickle_endpoint.h
+++ b/contrib/libs/grpc/test/core/util/trickle_endpoint.h
@@ -1,32 +1,32 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef TRICKLE_ENDPOINT_H
-#define TRICKLE_ENDPOINT_H
-
-#include "src/core/lib/iomgr/endpoint.h"
-
-grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap,
- double bytes_per_second);
-
-/* Allow up to \a bytes through the endpoint. Returns the new backlog. */
-size_t grpc_trickle_endpoint_trickle(grpc_endpoint* endpoint);
-
-size_t grpc_trickle_get_backlog(grpc_endpoint* endpoint);
-
-#endif
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef TRICKLE_ENDPOINT_H
+#define TRICKLE_ENDPOINT_H
+
+#include "src/core/lib/iomgr/endpoint.h"
+
+grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap,
+ double bytes_per_second);
+
+/* Allow up to \a bytes through the endpoint. Returns the new backlog. */
+size_t grpc_trickle_endpoint_trickle(grpc_endpoint* endpoint);
+
+size_t grpc_trickle_get_backlog(grpc_endpoint* endpoint);
+
+#endif
diff --git a/contrib/libs/grpc/test/core/util/tsan_suppressions.txt b/contrib/libs/grpc/test/core/util/tsan_suppressions.txt
index e0c7907228..8db4f52d4a 100644
--- a/contrib/libs/grpc/test/core/util/tsan_suppressions.txt
+++ b/contrib/libs/grpc/test/core/util/tsan_suppressions.txt
@@ -1,13 +1,13 @@
-# OPENSSL_cleanse does racy access to a global
-race:OPENSSL_cleanse
-race:cleanse_ctr
-# these are legitimate races in OpenSSL, and it appears those folks are looking at it
-# https://www.mail-archive.com/openssl-dev@openssl.org/msg09019.html
-race:ssleay_rand_add
-race:ssleay_rand_bytes
-race:__sleep_for
-# protobuf has an idempotent write race in ByteSize/GetCachedSize
-# https://github.com/google/protobuf/issues/2169
-race:ByteSize
-race:ByteSizeLong
-race:GetCachedSize
+# OPENSSL_cleanse does racy access to a global
+race:OPENSSL_cleanse
+race:cleanse_ctr
+# these are legitimate races in OpenSSL, and it appears those folks are looking at it
+# https://www.mail-archive.com/openssl-dev@openssl.org/msg09019.html
+race:ssleay_rand_add
+race:ssleay_rand_bytes
+race:__sleep_for
+# protobuf has an idempotent write race in ByteSize/GetCachedSize
+# https://github.com/google/protobuf/issues/2169
+race:ByteSize
+race:ByteSizeLong
+race:GetCachedSize
diff --git a/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt b/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt
index ca233b8a28..f4fdce3d5c 100644
--- a/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt
+++ b/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt
@@ -1,27 +1,27 @@
-# Protobuf stuff
-nonnull-attribute:google::protobuf::*
-alignment:google::protobuf::*
-nonnull-attribute:_tr_stored_block
-# The following 5 suppressors should be removed as part of C++ cleanup
-enum:client_fuzzer_one_entry
-enum:message_compress_test
-enum:transport_security_test
-enum:algorithm_test
-alignment:transport_security_test
-# TODO(jtattermusch): address issues and remove the supressions
-nonnull-attribute:gsec_aes_gcm_aead_crypter_decrypt_iovec
-nonnull-attribute:gsec_test_random_encrypt_decrypt
-nonnull-attribute:gsec_test_multiple_random_encrypt_decrypt
-nonnull-attribute:gsec_test_copy
-nonnull-attribute:gsec_test_encrypt_decrypt_test_vector
+# Protobuf stuff
+nonnull-attribute:google::protobuf::*
+alignment:google::protobuf::*
+nonnull-attribute:_tr_stored_block
+# The following 5 suppressors should be removed as part of C++ cleanup
+enum:client_fuzzer_one_entry
+enum:message_compress_test
+enum:transport_security_test
+enum:algorithm_test
+alignment:transport_security_test
+# TODO(jtattermusch): address issues and remove the supressions
+nonnull-attribute:gsec_aes_gcm_aead_crypter_decrypt_iovec
+nonnull-attribute:gsec_test_random_encrypt_decrypt
+nonnull-attribute:gsec_test_multiple_random_encrypt_decrypt
+nonnull-attribute:gsec_test_copy
+nonnull-attribute:gsec_test_encrypt_decrypt_test_vector
alignment:y_absl::little_endian::Store64
alignment:y_absl::little_endian::Load64
-float-divide-by-zero:grpc::testing::postprocess_scenario_result
-enum:grpc_op_string
-signed-integer-overflow:chrono
-enum:grpc_http2_error_to_grpc_status
-enum:grpc_chttp2_cancel_stream
-# TODO(juanlishen): Remove this supression after
-# https://github.com/GoogleCloudPlatform/layer-definitions/issues/531 is
-# addressed.
-alignment:grpc_core::XdsPriorityListUpdate::*
+float-divide-by-zero:grpc::testing::postprocess_scenario_result
+enum:grpc_op_string
+signed-integer-overflow:chrono
+enum:grpc_http2_error_to_grpc_status
+enum:grpc_chttp2_cancel_stream
+# TODO(juanlishen): Remove this supression after
+# https://github.com/GoogleCloudPlatform/layer-definitions/issues/531 is
+# addressed.
+alignment:grpc_core::XdsPriorityListUpdate::*
diff --git a/contrib/libs/grpc/test/core/util/ya.make b/contrib/libs/grpc/test/core/util/ya.make
index fbaad80cad..51d10abb13 100644
--- a/contrib/libs/grpc/test/core/util/ya.make
+++ b/contrib/libs/grpc/test/core/util/ya.make
@@ -1,53 +1,53 @@
-LIBRARY()
-
+LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
+
OWNER(dvshkurko)
-PEERDIR(
- contrib/libs/grpc
+PEERDIR(
+ contrib/libs/grpc
contrib/restricted/abseil-cpp-tstring/y_absl/debugging/failure_signal_handler
-)
-
+)
+
ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
contrib/libs/grpc
)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- # cmdline.cc
- # cmdline_test.cc
- # debugger_macros.cc
- # fuzzer_corpus_test.cc
- # fuzzer_one_entry_runner.sh*
- # fuzzer_util.cc
- # grpc_fuzzer.bzl
- # grpc_profiler.cc
- # histogram.cc
- # histogram_test.cc
- # lsan_suppressions.txt
- # memory_counters.cc
- # mock_endpoint.cc
- # one_corpus_entry_fuzzer.cc
- # parse_hexstring.cc
- # passthru_endpoint.cc
- port.cc
- # port_isolated_runtime_environment.cc
- port_server_client.cc
- # reconnect_server.cc
- # run_with_poller.sh*
- # slice_splitter.cc
- # subprocess_posix.cc
- # subprocess_windows.cc
- test_config.cc
- test_lb_policies.cc
- # test_tcp_server.cc
- # tracer_util.cc
- # trickle_endpoint.cc
-)
-
-END()
+
+NO_COMPILER_WARNINGS()
+
+SRCS(
+ # cmdline.cc
+ # cmdline_test.cc
+ # debugger_macros.cc
+ # fuzzer_corpus_test.cc
+ # fuzzer_one_entry_runner.sh*
+ # fuzzer_util.cc
+ # grpc_fuzzer.bzl
+ # grpc_profiler.cc
+ # histogram.cc
+ # histogram_test.cc
+ # lsan_suppressions.txt
+ # memory_counters.cc
+ # mock_endpoint.cc
+ # one_corpus_entry_fuzzer.cc
+ # parse_hexstring.cc
+ # passthru_endpoint.cc
+ port.cc
+ # port_isolated_runtime_environment.cc
+ port_server_client.cc
+ # reconnect_server.cc
+ # run_with_poller.sh*
+ # slice_splitter.cc
+ # subprocess_posix.cc
+ # subprocess_windows.cc
+ test_config.cc
+ test_lb_policies.cc
+ # test_tcp_server.cc
+ # tracer_util.cc
+ # trickle_endpoint.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/test/cpp/README-iOS.md b/contrib/libs/grpc/test/cpp/README-iOS.md
index 898931085b..faef8aaf5f 100644
--- a/contrib/libs/grpc/test/cpp/README-iOS.md
+++ b/contrib/libs/grpc/test/cpp/README-iOS.md
@@ -1,52 +1,52 @@
-## C++ tests on iOS
-
-[GTMGoogleTestRunner](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm) is used to convert googletest cases to XCTest that can be run on iOS. GTMGoogleTestRunner doesn't execute the `main` function, so we can't have any test logic in `main`.
-However, it's ok to call `::testing::InitGoogleTest` in `main`, as `GTMGoogleTestRunner` [calls InitGoogleTest](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L151).
-`grpc::testing::TestEnvironment` can also be called from `main`, as it does some test initialization (install crash handler, seed RNG) that's not strictly required to run testcases on iOS.
-
-
-## Porting exising C++ tests to run on iOS
-
-Please follow these guidelines when porting tests to run on iOS:
-
-- Tests need to use the googletest framework
-- Any setup/teardown code in `main` needs to be moved to `SetUpTestCase`/`TearDownTestCase`, and `TEST` needs to be changed to `TEST_F`.
-- [Death tests](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests) are not supported on iOS, so use the `*_IF_SUPPORTED()` macros to ensure that your code compiles on iOS.
-
-For example, the following test
-```c++
-TEST(MyTest, TestOne) {
- ASSERT_DEATH(ThisShouldDie(), "");
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- grpc_init();
- return RUN_ALL_TESTS();
- grpc_shutdown();
-}
-```
-
-should be changed to
-```c++
-class MyTest : public ::testing::Test {
- protected:
- static void SetUpTestCase() { grpc_init(); }
- static void TearDownTestCase() { grpc_shutdown(); }
-};
-
-TEST_F(MyTest, TestOne) {
- ASSERT_DEATH_IF_SUPPORTED(ThisShouldDie(), "");
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-```
-
-## Limitations
-
-Due to a [limitation](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L48-L56) in GTMGoogleTestRunner, `SetUpTestCase`/`TeardownTestCase` will be called before/after *every* individual test case, similar to `SetUp`/`TearDown`.
+## C++ tests on iOS
+
+[GTMGoogleTestRunner](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm) is used to convert googletest cases to XCTest that can be run on iOS. GTMGoogleTestRunner doesn't execute the `main` function, so we can't have any test logic in `main`.
+However, it's ok to call `::testing::InitGoogleTest` in `main`, as `GTMGoogleTestRunner` [calls InitGoogleTest](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L151).
+`grpc::testing::TestEnvironment` can also be called from `main`, as it does some test initialization (install crash handler, seed RNG) that's not strictly required to run testcases on iOS.
+
+
+## Porting exising C++ tests to run on iOS
+
+Please follow these guidelines when porting tests to run on iOS:
+
+- Tests need to use the googletest framework
+- Any setup/teardown code in `main` needs to be moved to `SetUpTestCase`/`TearDownTestCase`, and `TEST` needs to be changed to `TEST_F`.
+- [Death tests](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests) are not supported on iOS, so use the `*_IF_SUPPORTED()` macros to ensure that your code compiles on iOS.
+
+For example, the following test
+```c++
+TEST(MyTest, TestOne) {
+ ASSERT_DEATH(ThisShouldDie(), "");
+}
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ grpc_init();
+ return RUN_ALL_TESTS();
+ grpc_shutdown();
+}
+```
+
+should be changed to
+```c++
+class MyTest : public ::testing::Test {
+ protected:
+ static void SetUpTestCase() { grpc_init(); }
+ static void TearDownTestCase() { grpc_shutdown(); }
+};
+
+TEST_F(MyTest, TestOne) {
+ ASSERT_DEATH_IF_SUPPORTED(ThisShouldDie(), "");
+}
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
+```
+
+## Limitations
+
+Due to a [limitation](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L48-L56) in GTMGoogleTestRunner, `SetUpTestCase`/`TeardownTestCase` will be called before/after *every* individual test case, similar to `SetUp`/`TearDown`.
diff --git a/contrib/libs/grpc/test/cpp/end2end/async_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/async_end2end_test.cc
index 45df8718f9..85d8db87dc 100644
--- a/contrib/libs/grpc/test/cpp/end2end/async_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/async_end2end_test.cc
@@ -1,360 +1,360 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <cinttypes>
-#include <memory>
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/ext/health_check_service_server_builder_option.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/ext/filters/client_channel/backup_poller.h"
-#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/iomgr/port.h"
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/string_ref_helper.h"
-#include "test/cpp/util/test_credentials_provider.h"
-
-#ifdef GRPC_POSIX_SOCKET_EV
-#include "src/core/lib/iomgr/ev_posix.h"
-#endif // GRPC_POSIX_SOCKET_EV
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using grpc::testing::kTlsCredentialsType;
-using std::chrono::system_clock;
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
-int detag(void* p) { return static_cast<int>(reinterpret_cast<intptr_t>(p)); }
-
-class Verifier {
- public:
- Verifier() : lambda_run_(false) {}
- // Expect sets the expected ok value for a specific tag
- Verifier& Expect(int i, bool expect_ok) {
- return ExpectUnless(i, expect_ok, false);
- }
- // ExpectUnless sets the expected ok value for a specific tag
- // unless the tag was already marked seen (as a result of ExpectMaybe)
- Verifier& ExpectUnless(int i, bool expect_ok, bool seen) {
- if (!seen) {
- expectations_[tag(i)] = expect_ok;
- }
- return *this;
- }
- // ExpectMaybe sets the expected ok value for a specific tag, but does not
- // require it to appear
- // If it does, sets *seen to true
- Verifier& ExpectMaybe(int i, bool expect_ok, bool* seen) {
- if (!*seen) {
- maybe_expectations_[tag(i)] = MaybeExpect{expect_ok, seen};
- }
- return *this;
- }
-
- // Next waits for 1 async tag to complete, checks its
- // expectations, and returns the tag
- int Next(CompletionQueue* cq, bool ignore_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- GotTag(got_tag, ok, ignore_ok);
- return detag(got_tag);
- }
-
- template <typename T>
- CompletionQueue::NextStatus DoOnceThenAsyncNext(
- CompletionQueue* cq, void** got_tag, bool* ok, T deadline,
- std::function<void(void)> lambda) {
- if (lambda_run_) {
- return cq->AsyncNext(got_tag, ok, deadline);
- } else {
- lambda_run_ = true;
- return cq->DoThenAsyncNext(lambda, got_tag, ok, deadline);
- }
- }
-
- // Verify keeps calling Next until all currently set
- // expected tags are complete
- void Verify(CompletionQueue* cq) { Verify(cq, false); }
-
- // This version of Verify allows optionally ignoring the
- // outcome of the expectation
- void Verify(CompletionQueue* cq, bool ignore_ok) {
- GPR_ASSERT(!expectations_.empty() || !maybe_expectations_.empty());
- while (!expectations_.empty()) {
- Next(cq, ignore_ok);
- }
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <cinttypes>
+#include <memory>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/ext/health_check_service_server_builder_option.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/ext/filters/client_channel/backup_poller.h"
+#include "src/core/lib/gpr/tls.h"
+#include "src/core/lib/iomgr/port.h"
+#include "src/proto/grpc/health/v1/health.grpc.pb.h"
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/string_ref_helper.h"
+#include "test/cpp/util/test_credentials_provider.h"
+
+#ifdef GRPC_POSIX_SOCKET_EV
+#include "src/core/lib/iomgr/ev_posix.h"
+#endif // GRPC_POSIX_SOCKET_EV
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using grpc::testing::kTlsCredentialsType;
+using std::chrono::system_clock;
+
+namespace grpc {
+namespace testing {
+
+namespace {
+
+void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
+int detag(void* p) { return static_cast<int>(reinterpret_cast<intptr_t>(p)); }
+
+class Verifier {
+ public:
+ Verifier() : lambda_run_(false) {}
+ // Expect sets the expected ok value for a specific tag
+ Verifier& Expect(int i, bool expect_ok) {
+ return ExpectUnless(i, expect_ok, false);
+ }
+ // ExpectUnless sets the expected ok value for a specific tag
+ // unless the tag was already marked seen (as a result of ExpectMaybe)
+ Verifier& ExpectUnless(int i, bool expect_ok, bool seen) {
+ if (!seen) {
+ expectations_[tag(i)] = expect_ok;
+ }
+ return *this;
+ }
+ // ExpectMaybe sets the expected ok value for a specific tag, but does not
+ // require it to appear
+ // If it does, sets *seen to true
+ Verifier& ExpectMaybe(int i, bool expect_ok, bool* seen) {
+ if (!*seen) {
+ maybe_expectations_[tag(i)] = MaybeExpect{expect_ok, seen};
+ }
+ return *this;
+ }
+
+ // Next waits for 1 async tag to complete, checks its
+ // expectations, and returns the tag
+ int Next(CompletionQueue* cq, bool ignore_ok) {
+ bool ok;
+ void* got_tag;
+ EXPECT_TRUE(cq->Next(&got_tag, &ok));
+ GotTag(got_tag, ok, ignore_ok);
+ return detag(got_tag);
+ }
+
+ template <typename T>
+ CompletionQueue::NextStatus DoOnceThenAsyncNext(
+ CompletionQueue* cq, void** got_tag, bool* ok, T deadline,
+ std::function<void(void)> lambda) {
+ if (lambda_run_) {
+ return cq->AsyncNext(got_tag, ok, deadline);
+ } else {
+ lambda_run_ = true;
+ return cq->DoThenAsyncNext(lambda, got_tag, ok, deadline);
+ }
+ }
+
+ // Verify keeps calling Next until all currently set
+ // expected tags are complete
+ void Verify(CompletionQueue* cq) { Verify(cq, false); }
+
+ // This version of Verify allows optionally ignoring the
+ // outcome of the expectation
+ void Verify(CompletionQueue* cq, bool ignore_ok) {
+ GPR_ASSERT(!expectations_.empty() || !maybe_expectations_.empty());
+ while (!expectations_.empty()) {
+ Next(cq, ignore_ok);
+ }
maybe_expectations_.clear();
- }
-
- // This version of Verify stops after a certain deadline
- void Verify(CompletionQueue* cq,
- std::chrono::system_clock::time_point deadline) {
- if (expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(cq->AsyncNext(&got_tag, &ok, deadline),
- CompletionQueue::TIMEOUT);
- } else {
- while (!expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(cq->AsyncNext(&got_tag, &ok, deadline),
- CompletionQueue::GOT_EVENT);
- GotTag(got_tag, ok, false);
- }
- }
+ }
+
+ // This version of Verify stops after a certain deadline
+ void Verify(CompletionQueue* cq,
+ std::chrono::system_clock::time_point deadline) {
+ if (expectations_.empty()) {
+ bool ok;
+ void* got_tag;
+ EXPECT_EQ(cq->AsyncNext(&got_tag, &ok, deadline),
+ CompletionQueue::TIMEOUT);
+ } else {
+ while (!expectations_.empty()) {
+ bool ok;
+ void* got_tag;
+ EXPECT_EQ(cq->AsyncNext(&got_tag, &ok, deadline),
+ CompletionQueue::GOT_EVENT);
+ GotTag(got_tag, ok, false);
+ }
+ }
maybe_expectations_.clear();
- }
-
- // This version of Verify stops after a certain deadline, and uses the
- // DoThenAsyncNext API
- // to call the lambda
- void Verify(CompletionQueue* cq,
- std::chrono::system_clock::time_point deadline,
- const std::function<void(void)>& lambda) {
- if (expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::TIMEOUT);
- } else {
- while (!expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::GOT_EVENT);
- GotTag(got_tag, ok, false);
- }
- }
+ }
+
+ // This version of Verify stops after a certain deadline, and uses the
+ // DoThenAsyncNext API
+ // to call the lambda
+ void Verify(CompletionQueue* cq,
+ std::chrono::system_clock::time_point deadline,
+ const std::function<void(void)>& lambda) {
+ if (expectations_.empty()) {
+ bool ok;
+ void* got_tag;
+ EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
+ CompletionQueue::TIMEOUT);
+ } else {
+ while (!expectations_.empty()) {
+ bool ok;
+ void* got_tag;
+ EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
+ CompletionQueue::GOT_EVENT);
+ GotTag(got_tag, ok, false);
+ }
+ }
maybe_expectations_.clear();
- }
-
- private:
- void GotTag(void* got_tag, bool ok, bool ignore_ok) {
- auto it = expectations_.find(got_tag);
- if (it != expectations_.end()) {
- if (!ignore_ok) {
- EXPECT_EQ(it->second, ok);
- }
- expectations_.erase(it);
- } else {
- auto it2 = maybe_expectations_.find(got_tag);
- if (it2 != maybe_expectations_.end()) {
- if (it2->second.seen != nullptr) {
- EXPECT_FALSE(*it2->second.seen);
- *it2->second.seen = true;
- }
- if (!ignore_ok) {
- EXPECT_EQ(it2->second.ok, ok);
- }
+ }
+
+ private:
+ void GotTag(void* got_tag, bool ok, bool ignore_ok) {
+ auto it = expectations_.find(got_tag);
+ if (it != expectations_.end()) {
+ if (!ignore_ok) {
+ EXPECT_EQ(it->second, ok);
+ }
+ expectations_.erase(it);
+ } else {
+ auto it2 = maybe_expectations_.find(got_tag);
+ if (it2 != maybe_expectations_.end()) {
+ if (it2->second.seen != nullptr) {
+ EXPECT_FALSE(*it2->second.seen);
+ *it2->second.seen = true;
+ }
+ if (!ignore_ok) {
+ EXPECT_EQ(it2->second.ok, ok);
+ }
maybe_expectations_.erase(it2);
- } else {
- gpr_log(GPR_ERROR, "Unexpected tag: %p", got_tag);
- abort();
- }
- }
- }
-
- struct MaybeExpect {
- bool ok;
- bool* seen;
- };
-
- std::map<void*, bool> expectations_;
- std::map<void*, MaybeExpect> maybe_expectations_;
- bool lambda_run_;
-};
-
-bool plugin_has_sync_methods(std::unique_ptr<ServerBuilderPlugin>& plugin) {
- return plugin->has_sync_methods();
-}
-
-// This class disables the server builder plugins that may add sync services to
-// the server. If there are sync services, UnimplementedRpc test will triger
-// the sync unknown rpc routine on the server side, rather than the async one
-// that needs to be tested here.
-class ServerBuilderSyncPluginDisabler : public ::grpc::ServerBuilderOption {
- public:
- void UpdateArguments(ChannelArguments* /*arg*/) override {}
-
- void UpdatePlugins(
- std::vector<std::unique_ptr<ServerBuilderPlugin>>* plugins) override {
- plugins->erase(std::remove_if(plugins->begin(), plugins->end(),
- plugin_has_sync_methods),
- plugins->end());
- }
-};
-
-class TestScenario {
- public:
+ } else {
+ gpr_log(GPR_ERROR, "Unexpected tag: %p", got_tag);
+ abort();
+ }
+ }
+ }
+
+ struct MaybeExpect {
+ bool ok;
+ bool* seen;
+ };
+
+ std::map<void*, bool> expectations_;
+ std::map<void*, MaybeExpect> maybe_expectations_;
+ bool lambda_run_;
+};
+
+bool plugin_has_sync_methods(std::unique_ptr<ServerBuilderPlugin>& plugin) {
+ return plugin->has_sync_methods();
+}
+
+// This class disables the server builder plugins that may add sync services to
+// the server. If there are sync services, UnimplementedRpc test will triger
+// the sync unknown rpc routine on the server side, rather than the async one
+// that needs to be tested here.
+class ServerBuilderSyncPluginDisabler : public ::grpc::ServerBuilderOption {
+ public:
+ void UpdateArguments(ChannelArguments* /*arg*/) override {}
+
+ void UpdatePlugins(
+ std::vector<std::unique_ptr<ServerBuilderPlugin>>* plugins) override {
+ plugins->erase(std::remove_if(plugins->begin(), plugins->end(),
+ plugin_has_sync_methods),
+ plugins->end());
+ }
+};
+
+class TestScenario {
+ public:
TestScenario(bool inproc_stub, const TString& creds_type, bool hcs,
const TString& content)
- : inproc(inproc_stub),
- health_check_service(hcs),
- credentials_type(creds_type),
- message_content(content) {}
- void Log() const;
- bool inproc;
- bool health_check_service;
+ : inproc(inproc_stub),
+ health_check_service(hcs),
+ credentials_type(creds_type),
+ message_content(content) {}
+ void Log() const;
+ bool inproc;
+ bool health_check_service;
const TString credentials_type;
const TString message_content;
-};
-
-static std::ostream& operator<<(std::ostream& out,
- const TestScenario& scenario) {
- return out << "TestScenario{inproc=" << (scenario.inproc ? "true" : "false")
- << ", credentials='" << scenario.credentials_type
- << ", health_check_service="
- << (scenario.health_check_service ? "true" : "false")
- << "', message_size=" << scenario.message_content.size() << "}";
-}
-
-void TestScenario::Log() const {
- std::ostringstream out;
- out << *this;
- gpr_log(GPR_DEBUG, "%s", out.str().c_str());
-}
-
-class HealthCheck : public health::v1::Health::Service {};
-
-class AsyncEnd2endTest : public ::testing::TestWithParam<TestScenario> {
- protected:
- AsyncEnd2endTest() { GetParam().Log(); }
-
- void SetUp() override {
- port_ = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port_;
-
- // Setup server
- BuildAndStartServer();
- }
-
- void TearDown() override {
- server_->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- cq_->Shutdown();
- while (cq_->Next(&ignored_tag, &ignored_ok))
- ;
- stub_.reset();
- grpc_recycle_unused_port(port_);
- }
-
- void BuildAndStartServer() {
- ServerBuilder builder;
- auto server_creds = GetCredentialsProvider()->GetServerCredentials(
- GetParam().credentials_type);
- builder.AddListeningPort(server_address_.str(), server_creds);
- service_.reset(new grpc::testing::EchoTestService::AsyncService());
- builder.RegisterService(service_.get());
- if (GetParam().health_check_service) {
- builder.RegisterService(&health_check_);
- }
- cq_ = builder.AddCompletionQueue();
-
- // TODO(zyc): make a test option to choose wheather sync plugins should be
- // deleted
- std::unique_ptr<ServerBuilderOption> sync_plugin_disabler(
- new ServerBuilderSyncPluginDisabler());
- builder.SetOption(move(sync_plugin_disabler));
- server_ = builder.BuildAndStart();
- }
-
- void ResetStub() {
- ChannelArguments args;
- auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
- GetParam().credentials_type, &args);
- std::shared_ptr<Channel> channel =
- !(GetParam().inproc) ? ::grpc::CreateCustomChannel(
- server_address_.str(), channel_creds, args)
- : server_->InProcessChannel(args);
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- void SendRpc(int num_rpcs) {
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer,
- cq_.get(), cq_.get(), tag(2));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
- }
-
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::unique_ptr<grpc::testing::EchoTestService::AsyncService> service_;
- HealthCheck health_check_;
- std::ostringstream server_address_;
- int port_;
-};
-
-TEST_P(AsyncEnd2endTest, SimpleRpc) {
- ResetStub();
- SendRpc(1);
-}
-
+};
+
+static std::ostream& operator<<(std::ostream& out,
+ const TestScenario& scenario) {
+ return out << "TestScenario{inproc=" << (scenario.inproc ? "true" : "false")
+ << ", credentials='" << scenario.credentials_type
+ << ", health_check_service="
+ << (scenario.health_check_service ? "true" : "false")
+ << "', message_size=" << scenario.message_content.size() << "}";
+}
+
+void TestScenario::Log() const {
+ std::ostringstream out;
+ out << *this;
+ gpr_log(GPR_DEBUG, "%s", out.str().c_str());
+}
+
+class HealthCheck : public health::v1::Health::Service {};
+
+class AsyncEnd2endTest : public ::testing::TestWithParam<TestScenario> {
+ protected:
+ AsyncEnd2endTest() { GetParam().Log(); }
+
+ void SetUp() override {
+ port_ = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port_;
+
+ // Setup server
+ BuildAndStartServer();
+ }
+
+ void TearDown() override {
+ server_->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ cq_->Shutdown();
+ while (cq_->Next(&ignored_tag, &ignored_ok))
+ ;
+ stub_.reset();
+ grpc_recycle_unused_port(port_);
+ }
+
+ void BuildAndStartServer() {
+ ServerBuilder builder;
+ auto server_creds = GetCredentialsProvider()->GetServerCredentials(
+ GetParam().credentials_type);
+ builder.AddListeningPort(server_address_.str(), server_creds);
+ service_.reset(new grpc::testing::EchoTestService::AsyncService());
+ builder.RegisterService(service_.get());
+ if (GetParam().health_check_service) {
+ builder.RegisterService(&health_check_);
+ }
+ cq_ = builder.AddCompletionQueue();
+
+ // TODO(zyc): make a test option to choose wheather sync plugins should be
+ // deleted
+ std::unique_ptr<ServerBuilderOption> sync_plugin_disabler(
+ new ServerBuilderSyncPluginDisabler());
+ builder.SetOption(move(sync_plugin_disabler));
+ server_ = builder.BuildAndStart();
+ }
+
+ void ResetStub() {
+ ChannelArguments args;
+ auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
+ GetParam().credentials_type, &args);
+ std::shared_ptr<Channel> channel =
+ !(GetParam().inproc) ? ::grpc::CreateCustomChannel(
+ server_address_.str(), channel_creds, args)
+ : server_->InProcessChannel(args);
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ void SendRpc(int num_rpcs) {
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer,
+ cq_.get(), cq_.get(), tag(2));
+
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+ }
+
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::unique_ptr<grpc::testing::EchoTestService::AsyncService> service_;
+ HealthCheck health_check_;
+ std::ostringstream server_address_;
+ int port_;
+};
+
+TEST_P(AsyncEnd2endTest, SimpleRpc) {
+ ResetStub();
+ SendRpc(1);
+}
+
TEST_P(AsyncEnd2endTest, SimpleRpcWithExpectedError) {
ResetStub();
@@ -401,1509 +401,1509 @@ TEST_P(AsyncEnd2endTest, SimpleRpcWithExpectedError) {
EXPECT_FALSE(srv_ctx.IsCancelled());
}
-TEST_P(AsyncEnd2endTest, SequentialRpcs) {
- ResetStub();
- SendRpc(10);
-}
-
-TEST_P(AsyncEnd2endTest, ReconnectChannel) {
- // GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS is set to 100ms in main()
- if (GetParam().inproc) {
- return;
- }
- int poller_slowdown_factor = 1;
-#ifdef GRPC_POSIX_SOCKET_EV
- // It needs 2 pollset_works to reconnect the channel with polling engine
- // "poll"
- grpc_core::UniquePtr<char> poller = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
- if (0 == strcmp(poller.get(), "poll")) {
- poller_slowdown_factor = 2;
- }
-#endif // GRPC_POSIX_SOCKET_EV
- ResetStub();
- SendRpc(1);
- server_->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- cq_->Shutdown();
- while (cq_->Next(&ignored_tag, &ignored_ok))
- ;
- BuildAndStartServer();
- // It needs more than GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS time to
- // reconnect the channel.
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(
- 300 * poller_slowdown_factor * grpc_test_slowdown_factor(),
- GPR_TIMESPAN)));
- SendRpc(1);
-}
-
-// We do not need to protect notify because the use is synchronized.
-void ServerWait(Server* server, int* notify) {
- server->Wait();
- *notify = 1;
-}
-TEST_P(AsyncEnd2endTest, WaitAndShutdownTest) {
- int notify = 0;
- std::thread wait_thread(&ServerWait, server_.get(), &notify);
- ResetStub();
- SendRpc(1);
- EXPECT_EQ(0, notify);
- server_->Shutdown();
- wait_thread.join();
- EXPECT_EQ(1, notify);
-}
-
-TEST_P(AsyncEnd2endTest, ShutdownThenWait) {
- ResetStub();
- SendRpc(1);
- std::thread t([this]() { server_->Shutdown(); });
- server_->Wait();
- t.join();
-}
-
-// Test a simple RPC using the async version of Next
-TEST_P(AsyncEnd2endTest, AsyncNextRpc) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
-
- std::chrono::system_clock::time_point time_now(
- std::chrono::system_clock::now());
- std::chrono::system_clock::time_point time_limit(
- std::chrono::system_clock::now() + std::chrono::seconds(10));
- Verifier().Verify(cq_.get(), time_now);
- Verifier().Verify(cq_.get(), time_now);
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- Verifier().Expect(2, true).Verify(cq_.get(), time_limit);
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(
- cq_.get(), std::chrono::system_clock::time_point::max());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-// Test a simple RPC using the async version of Next
-TEST_P(AsyncEnd2endTest, DoThenAsyncNextRpc) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
-
- std::chrono::system_clock::time_point time_now(
- std::chrono::system_clock::now());
- std::chrono::system_clock::time_point time_limit(
- std::chrono::system_clock::now() + std::chrono::seconds(10));
- Verifier().Verify(cq_.get(), time_now);
- Verifier().Verify(cq_.get(), time_now);
-
- auto resp_writer_ptr = &response_writer;
- auto lambda_2 = [&, this, resp_writer_ptr]() {
- service_->RequestEcho(&srv_ctx, &recv_request, resp_writer_ptr, cq_.get(),
- cq_.get(), tag(2));
- };
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- Verifier().Expect(2, true).Verify(cq_.get(), time_limit, lambda_2);
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- auto lambda_3 = [resp_writer_ptr, send_response]() {
- resp_writer_ptr->Finish(send_response, Status::OK, tag(3));
- };
- Verifier().Expect(3, true).Expect(4, true).Verify(
- cq_.get(), std::chrono::system_clock::time_point::max(), lambda_3);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-// Two pings and a final pong.
-TEST_P(AsyncEnd2endTest, SimpleClientStreaming) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
- stub_->AsyncRequestStream(&cli_ctx, &recv_response, cq_.get(), tag(1)));
-
- service_->RequestRequestStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- Verifier().Expect(2, true).Expect(1, true).Verify(cq_.get());
-
- cli_stream->Write(send_request, tag(3));
- srv_stream.Read(&recv_request, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- cli_stream->Write(send_request, tag(5));
- srv_stream.Read(&recv_request, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
-
- EXPECT_EQ(send_request.message(), recv_request.message());
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- send_response.set_message(recv_request.message());
- srv_stream.Finish(send_response, Status::OK, tag(9));
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-// Two pings and a final pong.
-TEST_P(AsyncEnd2endTest, SimpleClientStreamingWithCoalescingApi) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- cli_ctx.set_initial_metadata_corked(true);
- // tag:1 never comes up since no op is performed
- std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
- stub_->AsyncRequestStream(&cli_ctx, &recv_response, cq_.get(), tag(1)));
-
- service_->RequestRequestStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- cli_stream->Write(send_request, tag(3));
-
- bool seen3 = false;
-
- Verifier().Expect(2, true).ExpectMaybe(3, true, &seen3).Verify(cq_.get());
-
- srv_stream.Read(&recv_request, tag(4));
-
- Verifier().ExpectUnless(3, true, seen3).Expect(4, true).Verify(cq_.get());
-
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- cli_stream->WriteLast(send_request, WriteOptions(), tag(5));
- srv_stream.Read(&recv_request, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- srv_stream.Read(&recv_request, tag(7));
- Verifier().Expect(7, false).Verify(cq_.get());
-
- send_response.set_message(recv_request.message());
- srv_stream.Finish(send_response, Status::OK, tag(8));
- cli_stream->Finish(&recv_status, tag(9));
- Verifier().Expect(8, true).Expect(9, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-// One ping, two pongs.
-TEST_P(AsyncEnd2endTest, SimpleServerStreaming) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
-
- service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(3));
- cli_stream->Read(&recv_response, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- srv_stream.Finish(Status::OK, tag(7));
- cli_stream->Read(&recv_response, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status, tag(9));
- Verifier().Expect(9, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// One ping, two pongs. Using WriteAndFinish API
-TEST_P(AsyncEnd2endTest, SimpleServerStreamingWithCoalescingApiWAF) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
-
- service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(3));
- cli_stream->Read(&recv_response, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- srv_stream.WriteAndFinish(send_response, WriteOptions(), Status::OK, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->Read(&recv_response, tag(7));
- Verifier().Expect(7, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status, tag(8));
- Verifier().Expect(8, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// One ping, two pongs. Using WriteLast API
-TEST_P(AsyncEnd2endTest, SimpleServerStreamingWithCoalescingApiWL) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
-
- service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(3));
- cli_stream->Read(&recv_response, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- srv_stream.WriteLast(send_response, WriteOptions(), tag(5));
- cli_stream->Read(&recv_response, tag(6));
- srv_stream.Finish(Status::OK, tag(7));
- Verifier().Expect(5, true).Expect(6, true).Expect(7, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->Read(&recv_response, tag(8));
- Verifier().Expect(8, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status, tag(9));
- Verifier().Expect(9, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// One ping, one pong.
-TEST_P(AsyncEnd2endTest, SimpleBidiStreaming) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
-
- service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
-
- cli_stream->Write(send_request, tag(3));
- srv_stream.Read(&recv_request, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- srv_stream.Finish(Status::OK, tag(9));
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// One ping, one pong. Using server:WriteAndFinish api
-TEST_P(AsyncEnd2endTest, SimpleBidiStreamingWithCoalescingApiWAF) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- cli_ctx.set_initial_metadata_corked(true);
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
-
- service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- cli_stream->WriteLast(send_request, WriteOptions(), tag(3));
-
- bool seen3 = false;
-
- Verifier().Expect(2, true).ExpectMaybe(3, true, &seen3).Verify(cq_.get());
-
- srv_stream.Read(&recv_request, tag(4));
-
- Verifier().ExpectUnless(3, true, seen3).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- srv_stream.Read(&recv_request, tag(5));
- Verifier().Expect(5, false).Verify(cq_.get());
-
- send_response.set_message(recv_request.message());
- srv_stream.WriteAndFinish(send_response, WriteOptions(), Status::OK, tag(6));
- cli_stream->Read(&recv_response, tag(7));
- Verifier().Expect(6, true).Expect(7, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->Finish(&recv_status, tag(8));
- Verifier().Expect(8, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// One ping, one pong. Using server:WriteLast api
-TEST_P(AsyncEnd2endTest, SimpleBidiStreamingWithCoalescingApiWL) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- cli_ctx.set_initial_metadata_corked(true);
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
-
- service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- cli_stream->WriteLast(send_request, WriteOptions(), tag(3));
-
- bool seen3 = false;
-
- Verifier().Expect(2, true).ExpectMaybe(3, true, &seen3).Verify(cq_.get());
-
- srv_stream.Read(&recv_request, tag(4));
-
- Verifier().ExpectUnless(3, true, seen3).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- srv_stream.Read(&recv_request, tag(5));
- Verifier().Expect(5, false).Verify(cq_.get());
-
- send_response.set_message(recv_request.message());
- srv_stream.WriteLast(send_response, WriteOptions(), tag(6));
- srv_stream.Finish(Status::OK, tag(7));
- cli_stream->Read(&recv_response, tag(8));
- Verifier().Expect(6, true).Expect(7, true).Expect(8, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->Finish(&recv_status, tag(9));
- Verifier().Expect(9, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// Metadata tests
-TEST_P(AsyncEnd2endTest, ClientInitialMetadataRpc) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
+TEST_P(AsyncEnd2endTest, SequentialRpcs) {
+ ResetStub();
+ SendRpc(10);
+}
+
+TEST_P(AsyncEnd2endTest, ReconnectChannel) {
+ // GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS is set to 100ms in main()
+ if (GetParam().inproc) {
+ return;
+ }
+ int poller_slowdown_factor = 1;
+#ifdef GRPC_POSIX_SOCKET_EV
+ // It needs 2 pollset_works to reconnect the channel with polling engine
+ // "poll"
+ grpc_core::UniquePtr<char> poller = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
+ if (0 == strcmp(poller.get(), "poll")) {
+ poller_slowdown_factor = 2;
+ }
+#endif // GRPC_POSIX_SOCKET_EV
+ ResetStub();
+ SendRpc(1);
+ server_->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ cq_->Shutdown();
+ while (cq_->Next(&ignored_tag, &ignored_ok))
+ ;
+ BuildAndStartServer();
+ // It needs more than GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS time to
+ // reconnect the channel.
+ gpr_sleep_until(gpr_time_add(
+ gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_millis(
+ 300 * poller_slowdown_factor * grpc_test_slowdown_factor(),
+ GPR_TIMESPAN)));
+ SendRpc(1);
+}
+
+// We do not need to protect notify because the use is synchronized.
+void ServerWait(Server* server, int* notify) {
+ server->Wait();
+ *notify = 1;
+}
+TEST_P(AsyncEnd2endTest, WaitAndShutdownTest) {
+ int notify = 0;
+ std::thread wait_thread(&ServerWait, server_.get(), &notify);
+ ResetStub();
+ SendRpc(1);
+ EXPECT_EQ(0, notify);
+ server_->Shutdown();
+ wait_thread.join();
+ EXPECT_EQ(1, notify);
+}
+
+TEST_P(AsyncEnd2endTest, ShutdownThenWait) {
+ ResetStub();
+ SendRpc(1);
+ std::thread t([this]() { server_->Shutdown(); });
+ server_->Wait();
+ t.join();
+}
+
+// Test a simple RPC using the async version of Next
+TEST_P(AsyncEnd2endTest, AsyncNextRpc) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+
+ std::chrono::system_clock::time_point time_now(
+ std::chrono::system_clock::now());
+ std::chrono::system_clock::time_point time_limit(
+ std::chrono::system_clock::now() + std::chrono::seconds(10));
+ Verifier().Verify(cq_.get(), time_now);
+ Verifier().Verify(cq_.get(), time_now);
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ Verifier().Expect(2, true).Verify(cq_.get(), time_limit);
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(
+ cq_.get(), std::chrono::system_clock::time_point::max());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// Test a simple RPC using the async version of Next
+TEST_P(AsyncEnd2endTest, DoThenAsyncNextRpc) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+
+ std::chrono::system_clock::time_point time_now(
+ std::chrono::system_clock::now());
+ std::chrono::system_clock::time_point time_limit(
+ std::chrono::system_clock::now() + std::chrono::seconds(10));
+ Verifier().Verify(cq_.get(), time_now);
+ Verifier().Verify(cq_.get(), time_now);
+
+ auto resp_writer_ptr = &response_writer;
+ auto lambda_2 = [&, this, resp_writer_ptr]() {
+ service_->RequestEcho(&srv_ctx, &recv_request, resp_writer_ptr, cq_.get(),
+ cq_.get(), tag(2));
+ };
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ Verifier().Expect(2, true).Verify(cq_.get(), time_limit, lambda_2);
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ auto lambda_3 = [resp_writer_ptr, send_response]() {
+ resp_writer_ptr->Finish(send_response, Status::OK, tag(3));
+ };
+ Verifier().Expect(3, true).Expect(4, true).Verify(
+ cq_.get(), std::chrono::system_clock::time_point::max(), lambda_3);
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// Two pings and a final pong.
+TEST_P(AsyncEnd2endTest, SimpleClientStreaming) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
+ stub_->AsyncRequestStream(&cli_ctx, &recv_response, cq_.get(), tag(1)));
+
+ service_->RequestRequestStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ Verifier().Expect(2, true).Expect(1, true).Verify(cq_.get());
+
+ cli_stream->Write(send_request, tag(3));
+ srv_stream.Read(&recv_request, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ cli_stream->Write(send_request, tag(5));
+ srv_stream.Read(&recv_request, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_request.message(), recv_request.message());
+ cli_stream->WritesDone(tag(7));
+ srv_stream.Read(&recv_request, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Finish(send_response, Status::OK, tag(9));
+ cli_stream->Finish(&recv_status, tag(10));
+ Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// Two pings and a final pong.
+TEST_P(AsyncEnd2endTest, SimpleClientStreamingWithCoalescingApi) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ cli_ctx.set_initial_metadata_corked(true);
+ // tag:1 never comes up since no op is performed
+ std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
+ stub_->AsyncRequestStream(&cli_ctx, &recv_response, cq_.get(), tag(1)));
+
+ service_->RequestRequestStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ cli_stream->Write(send_request, tag(3));
+
+ bool seen3 = false;
+
+ Verifier().Expect(2, true).ExpectMaybe(3, true, &seen3).Verify(cq_.get());
+
+ srv_stream.Read(&recv_request, tag(4));
+
+ Verifier().ExpectUnless(3, true, seen3).Expect(4, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ cli_stream->WriteLast(send_request, WriteOptions(), tag(5));
+ srv_stream.Read(&recv_request, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ srv_stream.Read(&recv_request, tag(7));
+ Verifier().Expect(7, false).Verify(cq_.get());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Finish(send_response, Status::OK, tag(8));
+ cli_stream->Finish(&recv_status, tag(9));
+ Verifier().Expect(8, true).Expect(9, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// One ping, two pongs.
+TEST_P(AsyncEnd2endTest, SimpleServerStreaming) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
+
+ service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Write(send_response, tag(3));
+ cli_stream->Read(&recv_response, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ srv_stream.Write(send_response, tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ srv_stream.Finish(Status::OK, tag(7));
+ cli_stream->Read(&recv_response, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status, tag(9));
+ Verifier().Expect(9, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// One ping, two pongs. Using WriteAndFinish API
+TEST_P(AsyncEnd2endTest, SimpleServerStreamingWithCoalescingApiWAF) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
+
+ service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Write(send_response, tag(3));
+ cli_stream->Read(&recv_response, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ srv_stream.WriteAndFinish(send_response, WriteOptions(), Status::OK, tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->Read(&recv_response, tag(7));
+ Verifier().Expect(7, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status, tag(8));
+ Verifier().Expect(8, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// One ping, two pongs. Using WriteLast API
+TEST_P(AsyncEnd2endTest, SimpleServerStreamingWithCoalescingApiWL) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
+
+ service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Write(send_response, tag(3));
+ cli_stream->Read(&recv_response, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ srv_stream.WriteLast(send_response, WriteOptions(), tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ srv_stream.Finish(Status::OK, tag(7));
+ Verifier().Expect(5, true).Expect(6, true).Expect(7, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->Read(&recv_response, tag(8));
+ Verifier().Expect(8, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status, tag(9));
+ Verifier().Expect(9, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// One ping, one pong.
+TEST_P(AsyncEnd2endTest, SimpleBidiStreaming) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
+ cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
+
+ service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+
+ cli_stream->Write(send_request, tag(3));
+ srv_stream.Read(&recv_request, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Write(send_response, tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->WritesDone(tag(7));
+ srv_stream.Read(&recv_request, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ srv_stream.Finish(Status::OK, tag(9));
+ cli_stream->Finish(&recv_status, tag(10));
+ Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// One ping, one pong. Using server:WriteAndFinish api
+TEST_P(AsyncEnd2endTest, SimpleBidiStreamingWithCoalescingApiWAF) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ cli_ctx.set_initial_metadata_corked(true);
+ std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
+ cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
+
+ service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ cli_stream->WriteLast(send_request, WriteOptions(), tag(3));
+
+ bool seen3 = false;
+
+ Verifier().Expect(2, true).ExpectMaybe(3, true, &seen3).Verify(cq_.get());
+
+ srv_stream.Read(&recv_request, tag(4));
+
+ Verifier().ExpectUnless(3, true, seen3).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ srv_stream.Read(&recv_request, tag(5));
+ Verifier().Expect(5, false).Verify(cq_.get());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.WriteAndFinish(send_response, WriteOptions(), Status::OK, tag(6));
+ cli_stream->Read(&recv_response, tag(7));
+ Verifier().Expect(6, true).Expect(7, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->Finish(&recv_status, tag(8));
+ Verifier().Expect(8, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// One ping, one pong. Using server:WriteLast api
+TEST_P(AsyncEnd2endTest, SimpleBidiStreamingWithCoalescingApiWL) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ cli_ctx.set_initial_metadata_corked(true);
+ std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
+ cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
+
+ service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ cli_stream->WriteLast(send_request, WriteOptions(), tag(3));
+
+ bool seen3 = false;
+
+ Verifier().Expect(2, true).ExpectMaybe(3, true, &seen3).Verify(cq_.get());
+
+ srv_stream.Read(&recv_request, tag(4));
+
+ Verifier().ExpectUnless(3, true, seen3).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ srv_stream.Read(&recv_request, tag(5));
+ Verifier().Expect(5, false).Verify(cq_.get());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.WriteLast(send_response, WriteOptions(), tag(6));
+ srv_stream.Finish(Status::OK, tag(7));
+ cli_stream->Read(&recv_response, tag(8));
+ Verifier().Expect(6, true).Expect(7, true).Expect(8, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->Finish(&recv_status, tag(9));
+ Verifier().Expect(9, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// Metadata tests
+TEST_P(AsyncEnd2endTest, ClientInitialMetadataRpc) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
std::pair<TString, TString> meta1("key1", "val1");
std::pair<TString, TString> meta2("key2", "val2");
std::pair<TString, TString> meta3("g.r.d-bin", "xyz");
- cli_ctx.AddMetadata(meta1.first, meta1.second);
- cli_ctx.AddMetadata(meta2.first, meta2.second);
- cli_ctx.AddMetadata(meta3.first, meta3.second);
-
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
- const auto& client_initial_metadata = srv_ctx.client_metadata();
- EXPECT_EQ(meta1.second,
- ToString(client_initial_metadata.find(meta1.first)->second));
- EXPECT_EQ(meta2.second,
- ToString(client_initial_metadata.find(meta2.first)->second));
- EXPECT_EQ(meta3.second,
- ToString(client_initial_metadata.find(meta3.first)->second));
- EXPECT_GE(client_initial_metadata.size(), static_cast<size_t>(2));
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-TEST_P(AsyncEnd2endTest, ServerInitialMetadataRpc) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
+ cli_ctx.AddMetadata(meta1.first, meta1.second);
+ cli_ctx.AddMetadata(meta2.first, meta2.second);
+ cli_ctx.AddMetadata(meta3.first, meta3.second);
+
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+ const auto& client_initial_metadata = srv_ctx.client_metadata();
+ EXPECT_EQ(meta1.second,
+ ToString(client_initial_metadata.find(meta1.first)->second));
+ EXPECT_EQ(meta2.second,
+ ToString(client_initial_metadata.find(meta2.first)->second));
+ EXPECT_EQ(meta3.second,
+ ToString(client_initial_metadata.find(meta3.first)->second));
+ EXPECT_GE(client_initial_metadata.size(), static_cast<size_t>(2));
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+TEST_P(AsyncEnd2endTest, ServerInitialMetadataRpc) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
std::pair<TString, TString> meta1("key1", "val1");
std::pair<TString, TString> meta2("key2", "val2");
-
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
- response_reader->ReadInitialMetadata(tag(4));
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
- srv_ctx.AddInitialMetadata(meta1.first, meta1.second);
- srv_ctx.AddInitialMetadata(meta2.first, meta2.second);
- response_writer.SendInitialMetadata(tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- const auto& server_initial_metadata = cli_ctx.GetServerInitialMetadata();
- EXPECT_EQ(meta1.second,
- ToString(server_initial_metadata.find(meta1.first)->second));
- EXPECT_EQ(meta2.second,
- ToString(server_initial_metadata.find(meta2.first)->second));
- EXPECT_EQ(static_cast<size_t>(2), server_initial_metadata.size());
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(5));
- response_reader->Finish(&recv_response, &recv_status, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-// 1 ping, 2 pongs.
-TEST_P(AsyncEnd2endTest, ServerInitialMetadataServerStreaming) {
- ResetStub();
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
-
+
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+ response_reader->ReadInitialMetadata(tag(4));
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+ srv_ctx.AddInitialMetadata(meta1.first, meta1.second);
+ srv_ctx.AddInitialMetadata(meta2.first, meta2.second);
+ response_writer.SendInitialMetadata(tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ const auto& server_initial_metadata = cli_ctx.GetServerInitialMetadata();
+ EXPECT_EQ(meta1.second,
+ ToString(server_initial_metadata.find(meta1.first)->second));
+ EXPECT_EQ(meta2.second,
+ ToString(server_initial_metadata.find(meta2.first)->second));
+ EXPECT_EQ(static_cast<size_t>(2), server_initial_metadata.size());
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(5));
+ response_reader->Finish(&recv_response, &recv_status, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// 1 ping, 2 pongs.
+TEST_P(AsyncEnd2endTest, ServerInitialMetadataServerStreaming) {
+ ResetStub();
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+
std::pair<::TString, ::TString> meta1("key1", "val1");
std::pair<::TString, ::TString> meta2("key2", "val2");
-
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
- cli_stream->ReadInitialMetadata(tag(11));
- service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
-
- srv_ctx.AddInitialMetadata(meta1.first, meta1.second);
- srv_ctx.AddInitialMetadata(meta2.first, meta2.second);
- srv_stream.SendInitialMetadata(tag(10));
- Verifier().Expect(10, true).Expect(11, true).Verify(cq_.get());
- auto server_initial_metadata = cli_ctx.GetServerInitialMetadata();
- EXPECT_EQ(meta1.second,
- ToString(server_initial_metadata.find(meta1.first)->second));
- EXPECT_EQ(meta2.second,
- ToString(server_initial_metadata.find(meta2.first)->second));
- EXPECT_EQ(static_cast<size_t>(2), server_initial_metadata.size());
-
- srv_stream.Write(send_response, tag(3));
-
- cli_stream->Read(&recv_response, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
-
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
-
- srv_stream.Finish(Status::OK, tag(7));
- cli_stream->Read(&recv_response, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status, tag(9));
- Verifier().Expect(9, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-// 1 ping, 2 pongs.
-// Test for server initial metadata being sent implicitly
-TEST_P(AsyncEnd2endTest, ServerInitialMetadataServerStreamingImplicit) {
- ResetStub();
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
+
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
+ cli_stream->ReadInitialMetadata(tag(11));
+ service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+
+ srv_ctx.AddInitialMetadata(meta1.first, meta1.second);
+ srv_ctx.AddInitialMetadata(meta2.first, meta2.second);
+ srv_stream.SendInitialMetadata(tag(10));
+ Verifier().Expect(10, true).Expect(11, true).Verify(cq_.get());
+ auto server_initial_metadata = cli_ctx.GetServerInitialMetadata();
+ EXPECT_EQ(meta1.second,
+ ToString(server_initial_metadata.find(meta1.first)->second));
+ EXPECT_EQ(meta2.second,
+ ToString(server_initial_metadata.find(meta2.first)->second));
+ EXPECT_EQ(static_cast<size_t>(2), server_initial_metadata.size());
+
+ srv_stream.Write(send_response, tag(3));
+
+ cli_stream->Read(&recv_response, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+
+ srv_stream.Write(send_response, tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+
+ srv_stream.Finish(Status::OK, tag(7));
+ cli_stream->Read(&recv_response, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status, tag(9));
+ Verifier().Expect(9, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+// 1 ping, 2 pongs.
+// Test for server initial metadata being sent implicitly
+TEST_P(AsyncEnd2endTest, ServerInitialMetadataServerStreamingImplicit) {
+ ResetStub();
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
std::pair<::TString, ::TString> meta1("key1", "val1");
std::pair<::TString, ::TString> meta2("key2", "val2");
-
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
- service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- srv_ctx.AddInitialMetadata(meta1.first, meta1.second);
- srv_ctx.AddInitialMetadata(meta2.first, meta2.second);
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(3));
-
- cli_stream->Read(&recv_response, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- auto server_initial_metadata = cli_ctx.GetServerInitialMetadata();
- EXPECT_EQ(meta1.second,
- ToString(server_initial_metadata.find(meta1.first)->second));
- EXPECT_EQ(meta2.second,
- ToString(server_initial_metadata.find(meta2.first)->second));
- EXPECT_EQ(static_cast<size_t>(2), server_initial_metadata.size());
-
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
-
- srv_stream.Finish(Status::OK, tag(7));
- cli_stream->Read(&recv_response, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status, tag(9));
- Verifier().Expect(9, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status.ok());
-}
-
-TEST_P(AsyncEnd2endTest, ServerTrailingMetadataRpc) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
+
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx, send_request, cq_.get(), tag(1)));
+ service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ srv_ctx.AddInitialMetadata(meta1.first, meta1.second);
+ srv_ctx.AddInitialMetadata(meta2.first, meta2.second);
+ send_response.set_message(recv_request.message());
+ srv_stream.Write(send_response, tag(3));
+
+ cli_stream->Read(&recv_response, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ auto server_initial_metadata = cli_ctx.GetServerInitialMetadata();
+ EXPECT_EQ(meta1.second,
+ ToString(server_initial_metadata.find(meta1.first)->second));
+ EXPECT_EQ(meta2.second,
+ ToString(server_initial_metadata.find(meta2.first)->second));
+ EXPECT_EQ(static_cast<size_t>(2), server_initial_metadata.size());
+
+ srv_stream.Write(send_response, tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+
+ srv_stream.Finish(Status::OK, tag(7));
+ cli_stream->Read(&recv_response, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status, tag(9));
+ Verifier().Expect(9, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status.ok());
+}
+
+TEST_P(AsyncEnd2endTest, ServerTrailingMetadataRpc) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
std::pair<TString, TString> meta1("key1", "val1");
std::pair<TString, TString> meta2("key2", "val2");
-
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
- response_reader->Finish(&recv_response, &recv_status, tag(5));
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
- response_writer.SendInitialMetadata(tag(3));
- Verifier().Expect(3, true).Verify(cq_.get());
-
- send_response.set_message(recv_request.message());
- srv_ctx.AddTrailingMetadata(meta1.first, meta1.second);
- srv_ctx.AddTrailingMetadata(meta2.first, meta2.second);
- response_writer.Finish(send_response, Status::OK, tag(4));
-
- Verifier().Expect(4, true).Expect(5, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- const auto& server_trailing_metadata = cli_ctx.GetServerTrailingMetadata();
- EXPECT_EQ(meta1.second,
- ToString(server_trailing_metadata.find(meta1.first)->second));
- EXPECT_EQ(meta2.second,
- ToString(server_trailing_metadata.find(meta2.first)->second));
- EXPECT_EQ(static_cast<size_t>(2), server_trailing_metadata.size());
-}
-
-TEST_P(AsyncEnd2endTest, MetadataRpc) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
+
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+ response_reader->Finish(&recv_response, &recv_status, tag(5));
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+ response_writer.SendInitialMetadata(tag(3));
+ Verifier().Expect(3, true).Verify(cq_.get());
+
+ send_response.set_message(recv_request.message());
+ srv_ctx.AddTrailingMetadata(meta1.first, meta1.second);
+ srv_ctx.AddTrailingMetadata(meta2.first, meta2.second);
+ response_writer.Finish(send_response, Status::OK, tag(4));
+
+ Verifier().Expect(4, true).Expect(5, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ const auto& server_trailing_metadata = cli_ctx.GetServerTrailingMetadata();
+ EXPECT_EQ(meta1.second,
+ ToString(server_trailing_metadata.find(meta1.first)->second));
+ EXPECT_EQ(meta2.second,
+ ToString(server_trailing_metadata.find(meta2.first)->second));
+ EXPECT_EQ(static_cast<size_t>(2), server_trailing_metadata.size());
+}
+
+TEST_P(AsyncEnd2endTest, MetadataRpc) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
std::pair<TString, TString> meta1("key1", "val1");
std::pair<TString, TString> meta2(
- "key2-bin",
+ "key2-bin",
TString("\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc", 13));
std::pair<TString, TString> meta3("key3", "val3");
std::pair<TString, TString> meta6(
- "key4-bin",
+ "key4-bin",
TString("\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d",
14));
std::pair<TString, TString> meta5("key5", "val5");
std::pair<TString, TString> meta4(
- "key6-bin",
+ "key6-bin",
TString(
- "\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee", 15));
-
- cli_ctx.AddMetadata(meta1.first, meta1.second);
- cli_ctx.AddMetadata(meta2.first, meta2.second);
-
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
- response_reader->ReadInitialMetadata(tag(4));
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
- const auto& client_initial_metadata = srv_ctx.client_metadata();
- EXPECT_EQ(meta1.second,
- ToString(client_initial_metadata.find(meta1.first)->second));
- EXPECT_EQ(meta2.second,
- ToString(client_initial_metadata.find(meta2.first)->second));
- EXPECT_GE(client_initial_metadata.size(), static_cast<size_t>(2));
-
- srv_ctx.AddInitialMetadata(meta3.first, meta3.second);
- srv_ctx.AddInitialMetadata(meta4.first, meta4.second);
- response_writer.SendInitialMetadata(tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- const auto& server_initial_metadata = cli_ctx.GetServerInitialMetadata();
- EXPECT_EQ(meta3.second,
- ToString(server_initial_metadata.find(meta3.first)->second));
- EXPECT_EQ(meta4.second,
- ToString(server_initial_metadata.find(meta4.first)->second));
- EXPECT_GE(server_initial_metadata.size(), static_cast<size_t>(2));
-
- send_response.set_message(recv_request.message());
- srv_ctx.AddTrailingMetadata(meta5.first, meta5.second);
- srv_ctx.AddTrailingMetadata(meta6.first, meta6.second);
- response_writer.Finish(send_response, Status::OK, tag(5));
- response_reader->Finish(&recv_response, &recv_status, tag(6));
-
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- const auto& server_trailing_metadata = cli_ctx.GetServerTrailingMetadata();
- EXPECT_EQ(meta5.second,
- ToString(server_trailing_metadata.find(meta5.first)->second));
- EXPECT_EQ(meta6.second,
- ToString(server_trailing_metadata.find(meta6.first)->second));
- EXPECT_GE(server_trailing_metadata.size(), static_cast<size_t>(2));
-}
-
-// Server uses AsyncNotifyWhenDone API to check for cancellation
-TEST_P(AsyncEnd2endTest, ServerCheckCancellation) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- srv_ctx.AsyncNotifyWhenDone(tag(5));
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
-
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- cli_ctx.TryCancel();
- Verifier().Expect(5, true).Expect(4, true).Verify(cq_.get());
- EXPECT_TRUE(srv_ctx.IsCancelled());
-
- EXPECT_EQ(StatusCode::CANCELLED, recv_status.error_code());
-}
-
-// Server uses AsyncNotifyWhenDone API to check for normal finish
-TEST_P(AsyncEnd2endTest, ServerCheckDone) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- srv_ctx.AsyncNotifyWhenDone(tag(5));
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
- cq_.get(), tag(2));
-
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Expect(5, true).Verify(cq_.get());
- EXPECT_FALSE(srv_ctx.IsCancelled());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-TEST_P(AsyncEnd2endTest, UnimplementedRpc) {
- ChannelArguments args;
- const auto& channel_creds = GetCredentialsProvider()->GetChannelCredentials(
- GetParam().credentials_type, &args);
- std::shared_ptr<Channel> channel =
- !(GetParam().inproc) ? ::grpc::CreateCustomChannel(server_address_.str(),
- channel_creds, args)
- : server_->InProcessChannel(args);
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- send_request.set_message(GetParam().message_content);
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncUnimplemented(&cli_ctx, send_request, cq_.get()));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
- Verifier().Expect(4, true).Verify(cq_.get());
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-}
-
-// This class is for testing scenarios where RPCs are cancelled on the server
-// by calling ServerContext::TryCancel(). Server uses AsyncNotifyWhenDone
-// API to check for cancellation
-class AsyncEnd2endServerTryCancelTest : public AsyncEnd2endTest {
- protected:
- typedef enum {
- DO_NOT_CANCEL = 0,
- CANCEL_BEFORE_PROCESSING,
- CANCEL_DURING_PROCESSING,
- CANCEL_AFTER_PROCESSING
- } ServerTryCancelRequestPhase;
-
- // Helper for testing client-streaming RPCs which are cancelled on the server.
- // Depending on the value of server_try_cancel parameter, this will test one
- // of the following three scenarios:
- // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading
- // any messages from the client
- //
- // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
- // messages from the client
- //
- // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
- // messages from the client (but before sending any status back to the
- // client)
- void TestClientStreamingServerCancel(
- ServerTryCancelRequestPhase server_try_cancel) {
- ResetStub();
-
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- // Initiate the 'RequestStream' call on client
- CompletionQueue cli_cq;
-
- std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
- stub_->AsyncRequestStream(&cli_ctx, &recv_response, &cli_cq, tag(1)));
-
- // On the server, request to be notified of 'RequestStream' calls
- // and receive the 'RequestStream' call just made by the client
- srv_ctx.AsyncNotifyWhenDone(tag(11));
- service_->RequestRequestStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
- std::thread t1([&cli_cq] { Verifier().Expect(1, true).Verify(&cli_cq); });
- Verifier().Expect(2, true).Verify(cq_.get());
- t1.join();
-
- bool expected_server_cq_result = true;
- bool expected_client_cq_result = true;
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- srv_ctx.TryCancel();
- Verifier().Expect(11, true).Verify(cq_.get());
- EXPECT_TRUE(srv_ctx.IsCancelled());
-
- // Since cancellation is done before server reads any results, we know
- // for sure that all server cq results will return false from this
- // point forward
- expected_server_cq_result = false;
- expected_client_cq_result = false;
- }
-
- bool ignore_client_cq_result =
- (server_try_cancel == CANCEL_DURING_PROCESSING) ||
- (server_try_cancel == CANCEL_BEFORE_PROCESSING);
-
- std::thread cli_thread([&cli_cq, &cli_stream, &expected_client_cq_result,
- &ignore_client_cq_result] {
- EchoRequest send_request;
- // Client sends 3 messages (tags 3, 4 and 5)
- for (int tag_idx = 3; tag_idx <= 5; tag_idx++) {
+ "\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee", 15));
+
+ cli_ctx.AddMetadata(meta1.first, meta1.second);
+ cli_ctx.AddMetadata(meta2.first, meta2.second);
+
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+ response_reader->ReadInitialMetadata(tag(4));
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+ const auto& client_initial_metadata = srv_ctx.client_metadata();
+ EXPECT_EQ(meta1.second,
+ ToString(client_initial_metadata.find(meta1.first)->second));
+ EXPECT_EQ(meta2.second,
+ ToString(client_initial_metadata.find(meta2.first)->second));
+ EXPECT_GE(client_initial_metadata.size(), static_cast<size_t>(2));
+
+ srv_ctx.AddInitialMetadata(meta3.first, meta3.second);
+ srv_ctx.AddInitialMetadata(meta4.first, meta4.second);
+ response_writer.SendInitialMetadata(tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ const auto& server_initial_metadata = cli_ctx.GetServerInitialMetadata();
+ EXPECT_EQ(meta3.second,
+ ToString(server_initial_metadata.find(meta3.first)->second));
+ EXPECT_EQ(meta4.second,
+ ToString(server_initial_metadata.find(meta4.first)->second));
+ EXPECT_GE(server_initial_metadata.size(), static_cast<size_t>(2));
+
+ send_response.set_message(recv_request.message());
+ srv_ctx.AddTrailingMetadata(meta5.first, meta5.second);
+ srv_ctx.AddTrailingMetadata(meta6.first, meta6.second);
+ response_writer.Finish(send_response, Status::OK, tag(5));
+ response_reader->Finish(&recv_response, &recv_status, tag(6));
+
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ const auto& server_trailing_metadata = cli_ctx.GetServerTrailingMetadata();
+ EXPECT_EQ(meta5.second,
+ ToString(server_trailing_metadata.find(meta5.first)->second));
+ EXPECT_EQ(meta6.second,
+ ToString(server_trailing_metadata.find(meta6.first)->second));
+ EXPECT_GE(server_trailing_metadata.size(), static_cast<size_t>(2));
+}
+
+// Server uses AsyncNotifyWhenDone API to check for cancellation
+TEST_P(AsyncEnd2endTest, ServerCheckCancellation) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ srv_ctx.AsyncNotifyWhenDone(tag(5));
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ cli_ctx.TryCancel();
+ Verifier().Expect(5, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+
+ EXPECT_EQ(StatusCode::CANCELLED, recv_status.error_code());
+}
+
+// Server uses AsyncNotifyWhenDone API to check for normal finish
+TEST_P(AsyncEnd2endTest, ServerCheckDone) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx, send_request, cq_.get()));
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ srv_ctx.AsyncNotifyWhenDone(tag(5));
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Expect(5, true).Verify(cq_.get());
+ EXPECT_FALSE(srv_ctx.IsCancelled());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+TEST_P(AsyncEnd2endTest, UnimplementedRpc) {
+ ChannelArguments args;
+ const auto& channel_creds = GetCredentialsProvider()->GetChannelCredentials(
+ GetParam().credentials_type, &args);
+ std::shared_ptr<Channel> channel =
+ !(GetParam().inproc) ? ::grpc::CreateCustomChannel(server_address_.str(),
+ channel_creds, args)
+ : server_->InProcessChannel(args);
+ std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
+ stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
+ EchoRequest send_request;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ send_request.set_message(GetParam().message_content);
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub->AsyncUnimplemented(&cli_ctx, send_request, cq_.get()));
+
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+ Verifier().Expect(4, true).Verify(cq_.get());
+
+ EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
+ EXPECT_EQ("", recv_status.error_message());
+}
+
+// This class is for testing scenarios where RPCs are cancelled on the server
+// by calling ServerContext::TryCancel(). Server uses AsyncNotifyWhenDone
+// API to check for cancellation
+class AsyncEnd2endServerTryCancelTest : public AsyncEnd2endTest {
+ protected:
+ typedef enum {
+ DO_NOT_CANCEL = 0,
+ CANCEL_BEFORE_PROCESSING,
+ CANCEL_DURING_PROCESSING,
+ CANCEL_AFTER_PROCESSING
+ } ServerTryCancelRequestPhase;
+
+ // Helper for testing client-streaming RPCs which are cancelled on the server.
+ // Depending on the value of server_try_cancel parameter, this will test one
+ // of the following three scenarios:
+ // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading
+ // any messages from the client
+ //
+ // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
+ // messages from the client
+ //
+ // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
+ // messages from the client (but before sending any status back to the
+ // client)
+ void TestClientStreamingServerCancel(
+ ServerTryCancelRequestPhase server_try_cancel) {
+ ResetStub();
+
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ // Initiate the 'RequestStream' call on client
+ CompletionQueue cli_cq;
+
+ std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
+ stub_->AsyncRequestStream(&cli_ctx, &recv_response, &cli_cq, tag(1)));
+
+ // On the server, request to be notified of 'RequestStream' calls
+ // and receive the 'RequestStream' call just made by the client
+ srv_ctx.AsyncNotifyWhenDone(tag(11));
+ service_->RequestRequestStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+ std::thread t1([&cli_cq] { Verifier().Expect(1, true).Verify(&cli_cq); });
+ Verifier().Expect(2, true).Verify(cq_.get());
+ t1.join();
+
+ bool expected_server_cq_result = true;
+ bool expected_client_cq_result = true;
+
+ if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
+ srv_ctx.TryCancel();
+ Verifier().Expect(11, true).Verify(cq_.get());
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+
+ // Since cancellation is done before server reads any results, we know
+ // for sure that all server cq results will return false from this
+ // point forward
+ expected_server_cq_result = false;
+ expected_client_cq_result = false;
+ }
+
+ bool ignore_client_cq_result =
+ (server_try_cancel == CANCEL_DURING_PROCESSING) ||
+ (server_try_cancel == CANCEL_BEFORE_PROCESSING);
+
+ std::thread cli_thread([&cli_cq, &cli_stream, &expected_client_cq_result,
+ &ignore_client_cq_result] {
+ EchoRequest send_request;
+ // Client sends 3 messages (tags 3, 4 and 5)
+ for (int tag_idx = 3; tag_idx <= 5; tag_idx++) {
send_request.set_message("Ping " + ToString(tag_idx));
- cli_stream->Write(send_request, tag(tag_idx));
- Verifier()
- .Expect(tag_idx, expected_client_cq_result)
- .Verify(&cli_cq, ignore_client_cq_result);
- }
- cli_stream->WritesDone(tag(6));
- // Ignore ok on WritesDone since cancel can affect it
- Verifier()
- .Expect(6, expected_client_cq_result)
- .Verify(&cli_cq, ignore_client_cq_result);
- });
-
- bool ignore_cq_result = false;
- bool want_done_tag = false;
- std::thread* server_try_cancel_thd = nullptr;
-
- auto verif = Verifier();
-
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([&srv_ctx] { srv_ctx.TryCancel(); });
- // Server will cancel the RPC in a parallel thread while reading the
- // requests from the client. Since the cancellation can happen at anytime,
- // some of the cq results (i.e those until cancellation) might be true but
- // its non deterministic. So better to ignore the cq results
- ignore_cq_result = true;
- // Expect that we might possibly see the done tag that
- // indicates cancellation completion in this case
- want_done_tag = true;
- verif.Expect(11, true);
- }
-
- // Server reads 3 messages (tags 6, 7 and 8)
- // But if want_done_tag is true, we might also see tag 11
- for (int tag_idx = 6; tag_idx <= 8; tag_idx++) {
- srv_stream.Read(&recv_request, tag(tag_idx));
- // Note that we'll add something to the verifier and verify that
- // something was seen, but it might be tag 11 and not what we
- // just added
- int got_tag = verif.Expect(tag_idx, expected_server_cq_result)
- .Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == tag_idx) || (got_tag == 11 && want_done_tag));
- if (got_tag == 11) {
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- // Now get the other entry that we were waiting on
- EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_result), tag_idx);
- }
- }
-
- cli_thread.join();
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- srv_ctx.TryCancel();
- want_done_tag = true;
- verif.Expect(11, true);
- }
-
- if (want_done_tag) {
- verif.Verify(cq_.get());
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- }
-
- // The RPC has been cancelled at this point for sure (i.e irrespective of
- // the value of `server_try_cancel` is). So, from this point forward, we
- // know that cq results are supposed to return false on server.
-
- // Server sends the final message and cancelled status (but the RPC is
- // already cancelled at this point. So we expect the operation to fail)
- srv_stream.Finish(send_response, Status::CANCELLED, tag(9));
- Verifier().Expect(9, false).Verify(cq_.get());
-
- // Client will see the cancellation
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(10, true).Verify(&cli_cq);
- EXPECT_FALSE(recv_status.ok());
- EXPECT_EQ(::grpc::StatusCode::CANCELLED, recv_status.error_code());
-
- cli_cq.Shutdown();
- void* dummy_tag;
- bool dummy_ok;
- while (cli_cq.Next(&dummy_tag, &dummy_ok)) {
- }
- }
-
- // Helper for testing server-streaming RPCs which are cancelled on the server.
- // Depending on the value of server_try_cancel parameter, this will test one
- // of the following three scenarios:
- // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before sending
- // any messages to the client
- //
- // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while sending
- // messages to the client
- //
- // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after sending all
- // messages to the client (but before sending any status back to the
- // client)
- void TestServerStreamingServerCancel(
- ServerTryCancelRequestPhase server_try_cancel) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
-
- send_request.set_message("Ping");
- // Initiate the 'ResponseStream' call on the client
- CompletionQueue cli_cq;
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx, send_request, &cli_cq, tag(1)));
- // On the server, request to be notified of 'ResponseStream' calls and
- // receive the call just made by the client
- srv_ctx.AsyncNotifyWhenDone(tag(11));
- service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- std::thread t1([&cli_cq] { Verifier().Expect(1, true).Verify(&cli_cq); });
- Verifier().Expect(2, true).Verify(cq_.get());
- t1.join();
-
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- bool expected_cq_result = true;
- bool ignore_cq_result = false;
- bool want_done_tag = false;
- bool expected_client_cq_result = true;
- bool ignore_client_cq_result =
- (server_try_cancel != CANCEL_BEFORE_PROCESSING);
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- srv_ctx.TryCancel();
- Verifier().Expect(11, true).Verify(cq_.get());
- EXPECT_TRUE(srv_ctx.IsCancelled());
-
- // We know for sure that all cq results will be false from this point
- // since the server cancelled the RPC
- expected_cq_result = false;
- expected_client_cq_result = false;
- }
-
- std::thread cli_thread([&cli_cq, &cli_stream, &expected_client_cq_result,
- &ignore_client_cq_result] {
- // Client attempts to read the three messages from the server
- for (int tag_idx = 6; tag_idx <= 8; tag_idx++) {
- EchoResponse recv_response;
- cli_stream->Read(&recv_response, tag(tag_idx));
- Verifier()
- .Expect(tag_idx, expected_client_cq_result)
- .Verify(&cli_cq, ignore_client_cq_result);
- }
- });
-
- std::thread* server_try_cancel_thd = nullptr;
-
- auto verif = Verifier();
-
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([&srv_ctx] { srv_ctx.TryCancel(); });
-
- // Server will cancel the RPC in a parallel thread while writing responses
- // to the client. Since the cancellation can happen at anytime, some of
- // the cq results (i.e those until cancellation) might be true but it is
- // non deterministic. So better to ignore the cq results
- ignore_cq_result = true;
- // Expect that we might possibly see the done tag that
- // indicates cancellation completion in this case
- want_done_tag = true;
- verif.Expect(11, true);
- }
-
- // Server sends three messages (tags 3, 4 and 5)
- // But if want_done tag is true, we might also see tag 11
- for (int tag_idx = 3; tag_idx <= 5; tag_idx++) {
+ cli_stream->Write(send_request, tag(tag_idx));
+ Verifier()
+ .Expect(tag_idx, expected_client_cq_result)
+ .Verify(&cli_cq, ignore_client_cq_result);
+ }
+ cli_stream->WritesDone(tag(6));
+ // Ignore ok on WritesDone since cancel can affect it
+ Verifier()
+ .Expect(6, expected_client_cq_result)
+ .Verify(&cli_cq, ignore_client_cq_result);
+ });
+
+ bool ignore_cq_result = false;
+ bool want_done_tag = false;
+ std::thread* server_try_cancel_thd = nullptr;
+
+ auto verif = Verifier();
+
+ if (server_try_cancel == CANCEL_DURING_PROCESSING) {
+ server_try_cancel_thd =
+ new std::thread([&srv_ctx] { srv_ctx.TryCancel(); });
+ // Server will cancel the RPC in a parallel thread while reading the
+ // requests from the client. Since the cancellation can happen at anytime,
+ // some of the cq results (i.e those until cancellation) might be true but
+ // its non deterministic. So better to ignore the cq results
+ ignore_cq_result = true;
+ // Expect that we might possibly see the done tag that
+ // indicates cancellation completion in this case
+ want_done_tag = true;
+ verif.Expect(11, true);
+ }
+
+ // Server reads 3 messages (tags 6, 7 and 8)
+ // But if want_done_tag is true, we might also see tag 11
+ for (int tag_idx = 6; tag_idx <= 8; tag_idx++) {
+ srv_stream.Read(&recv_request, tag(tag_idx));
+ // Note that we'll add something to the verifier and verify that
+ // something was seen, but it might be tag 11 and not what we
+ // just added
+ int got_tag = verif.Expect(tag_idx, expected_server_cq_result)
+ .Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == tag_idx) || (got_tag == 11 && want_done_tag));
+ if (got_tag == 11) {
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ // Now get the other entry that we were waiting on
+ EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_result), tag_idx);
+ }
+ }
+
+ cli_thread.join();
+
+ if (server_try_cancel_thd != nullptr) {
+ server_try_cancel_thd->join();
+ delete server_try_cancel_thd;
+ }
+
+ if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
+ srv_ctx.TryCancel();
+ want_done_tag = true;
+ verif.Expect(11, true);
+ }
+
+ if (want_done_tag) {
+ verif.Verify(cq_.get());
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ }
+
+ // The RPC has been cancelled at this point for sure (i.e irrespective of
+ // the value of `server_try_cancel` is). So, from this point forward, we
+ // know that cq results are supposed to return false on server.
+
+ // Server sends the final message and cancelled status (but the RPC is
+ // already cancelled at this point. So we expect the operation to fail)
+ srv_stream.Finish(send_response, Status::CANCELLED, tag(9));
+ Verifier().Expect(9, false).Verify(cq_.get());
+
+ // Client will see the cancellation
+ cli_stream->Finish(&recv_status, tag(10));
+ Verifier().Expect(10, true).Verify(&cli_cq);
+ EXPECT_FALSE(recv_status.ok());
+ EXPECT_EQ(::grpc::StatusCode::CANCELLED, recv_status.error_code());
+
+ cli_cq.Shutdown();
+ void* dummy_tag;
+ bool dummy_ok;
+ while (cli_cq.Next(&dummy_tag, &dummy_ok)) {
+ }
+ }
+
+ // Helper for testing server-streaming RPCs which are cancelled on the server.
+ // Depending on the value of server_try_cancel parameter, this will test one
+ // of the following three scenarios:
+ // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before sending
+ // any messages to the client
+ //
+ // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while sending
+ // messages to the client
+ //
+ // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after sending all
+ // messages to the client (but before sending any status back to the
+ // client)
+ void TestServerStreamingServerCancel(
+ ServerTryCancelRequestPhase server_try_cancel) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+
+ send_request.set_message("Ping");
+ // Initiate the 'ResponseStream' call on the client
+ CompletionQueue cli_cq;
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx, send_request, &cli_cq, tag(1)));
+ // On the server, request to be notified of 'ResponseStream' calls and
+ // receive the call just made by the client
+ srv_ctx.AsyncNotifyWhenDone(tag(11));
+ service_->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ std::thread t1([&cli_cq] { Verifier().Expect(1, true).Verify(&cli_cq); });
+ Verifier().Expect(2, true).Verify(cq_.get());
+ t1.join();
+
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ bool expected_cq_result = true;
+ bool ignore_cq_result = false;
+ bool want_done_tag = false;
+ bool expected_client_cq_result = true;
+ bool ignore_client_cq_result =
+ (server_try_cancel != CANCEL_BEFORE_PROCESSING);
+
+ if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
+ srv_ctx.TryCancel();
+ Verifier().Expect(11, true).Verify(cq_.get());
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+
+ // We know for sure that all cq results will be false from this point
+ // since the server cancelled the RPC
+ expected_cq_result = false;
+ expected_client_cq_result = false;
+ }
+
+ std::thread cli_thread([&cli_cq, &cli_stream, &expected_client_cq_result,
+ &ignore_client_cq_result] {
+ // Client attempts to read the three messages from the server
+ for (int tag_idx = 6; tag_idx <= 8; tag_idx++) {
+ EchoResponse recv_response;
+ cli_stream->Read(&recv_response, tag(tag_idx));
+ Verifier()
+ .Expect(tag_idx, expected_client_cq_result)
+ .Verify(&cli_cq, ignore_client_cq_result);
+ }
+ });
+
+ std::thread* server_try_cancel_thd = nullptr;
+
+ auto verif = Verifier();
+
+ if (server_try_cancel == CANCEL_DURING_PROCESSING) {
+ server_try_cancel_thd =
+ new std::thread([&srv_ctx] { srv_ctx.TryCancel(); });
+
+ // Server will cancel the RPC in a parallel thread while writing responses
+ // to the client. Since the cancellation can happen at anytime, some of
+ // the cq results (i.e those until cancellation) might be true but it is
+ // non deterministic. So better to ignore the cq results
+ ignore_cq_result = true;
+ // Expect that we might possibly see the done tag that
+ // indicates cancellation completion in this case
+ want_done_tag = true;
+ verif.Expect(11, true);
+ }
+
+ // Server sends three messages (tags 3, 4 and 5)
+ // But if want_done tag is true, we might also see tag 11
+ for (int tag_idx = 3; tag_idx <= 5; tag_idx++) {
send_response.set_message("Pong " + ToString(tag_idx));
- srv_stream.Write(send_response, tag(tag_idx));
- // Note that we'll add something to the verifier and verify that
- // something was seen, but it might be tag 11 and not what we
- // just added
- int got_tag = verif.Expect(tag_idx, expected_cq_result)
- .Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == tag_idx) || (got_tag == 11 && want_done_tag));
- if (got_tag == 11) {
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- // Now get the other entry that we were waiting on
- EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_result), tag_idx);
- }
- }
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- srv_ctx.TryCancel();
- want_done_tag = true;
- verif.Expect(11, true);
- }
-
- if (want_done_tag) {
- verif.Verify(cq_.get());
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- }
-
- cli_thread.join();
-
- // The RPC has been cancelled at this point for sure (i.e irrespective of
- // the value of `server_try_cancel` is). So, from this point forward, we
- // know that cq results are supposed to return false on server.
-
- // Server finishes the stream (but the RPC is already cancelled)
- srv_stream.Finish(Status::CANCELLED, tag(9));
- Verifier().Expect(9, false).Verify(cq_.get());
-
- // Client will see the cancellation
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(10, true).Verify(&cli_cq);
- EXPECT_FALSE(recv_status.ok());
- EXPECT_EQ(::grpc::StatusCode::CANCELLED, recv_status.error_code());
-
- cli_cq.Shutdown();
- void* dummy_tag;
- bool dummy_ok;
- while (cli_cq.Next(&dummy_tag, &dummy_ok)) {
- }
- }
-
- // Helper for testing bidirectinal-streaming RPCs which are cancelled on the
- // server.
- //
- // Depending on the value of server_try_cancel parameter, this will
- // test one of the following three scenarios:
- // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading/
- // writing any messages from/to the client
- //
- // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
- // messages from the client
- //
- // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
- // messages from the client (but before sending any status back to the
- // client)
- void TestBidiStreamingServerCancel(
- ServerTryCancelRequestPhase server_try_cancel) {
- ResetStub();
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- // Initiate the call from the client side
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
-
- // On the server, request to be notified of the 'BidiStream' call and
- // receive the call just made by the client
- srv_ctx.AsyncNotifyWhenDone(tag(11));
- service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
-
- auto verif = Verifier();
-
- // Client sends the first and the only message
- send_request.set_message("Ping");
- cli_stream->Write(send_request, tag(3));
- verif.Expect(3, true);
-
- bool expected_cq_result = true;
- bool ignore_cq_result = false;
- bool want_done_tag = false;
-
- int got_tag, got_tag2;
- bool tag_3_done = false;
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- srv_ctx.TryCancel();
- verif.Expect(11, true);
- // We know for sure that all server cq results will be false from
- // this point since the server cancelled the RPC. However, we can't
- // say for sure about the client
- expected_cq_result = false;
- ignore_cq_result = true;
-
- do {
- got_tag = verif.Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT(((got_tag == 3) && !tag_3_done) || (got_tag == 11));
- if (got_tag == 3) {
- tag_3_done = true;
- }
- } while (got_tag != 11);
- EXPECT_TRUE(srv_ctx.IsCancelled());
- }
-
- std::thread* server_try_cancel_thd = nullptr;
-
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([&srv_ctx] { srv_ctx.TryCancel(); });
-
- // Since server is going to cancel the RPC in a parallel thread, some of
- // the cq results (i.e those until the cancellation) might be true. Since
- // that number is non-deterministic, it is better to ignore the cq results
- ignore_cq_result = true;
- // Expect that we might possibly see the done tag that
- // indicates cancellation completion in this case
- want_done_tag = true;
- verif.Expect(11, true);
- }
-
- srv_stream.Read(&recv_request, tag(4));
- verif.Expect(4, expected_cq_result);
- got_tag = tag_3_done ? 3 : verif.Next(cq_.get(), ignore_cq_result);
- got_tag2 = verif.Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == 3) || (got_tag == 4) ||
- (got_tag == 11 && want_done_tag));
- GPR_ASSERT((got_tag2 == 3) || (got_tag2 == 4) ||
- (got_tag2 == 11 && want_done_tag));
- // If we get 3 and 4, we don't need to wait for 11, but if
- // we get 11, we should also clear 3 and 4
- if (got_tag + got_tag2 != 7) {
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- got_tag = verif.Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == 3) || (got_tag == 4));
- }
-
- send_response.set_message("Pong");
- srv_stream.Write(send_response, tag(5));
- verif.Expect(5, expected_cq_result);
-
- cli_stream->Read(&recv_response, tag(6));
- verif.Expect(6, expected_cq_result);
- got_tag = verif.Next(cq_.get(), ignore_cq_result);
- got_tag2 = verif.Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == 5) || (got_tag == 6) ||
- (got_tag == 11 && want_done_tag));
- GPR_ASSERT((got_tag2 == 5) || (got_tag2 == 6) ||
- (got_tag2 == 11 && want_done_tag));
- // If we get 5 and 6, we don't need to wait for 11, but if
- // we get 11, we should also clear 5 and 6
- if (got_tag + got_tag2 != 11) {
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- got_tag = verif.Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == 5) || (got_tag == 6));
- }
-
- // This is expected to succeed in all cases
- cli_stream->WritesDone(tag(7));
- verif.Expect(7, true);
- // TODO(vjpai): Consider whether the following is too flexible
- // or whether it should just be reset to ignore_cq_result
- bool ignore_cq_wd_result =
- ignore_cq_result || (server_try_cancel == CANCEL_BEFORE_PROCESSING);
- got_tag = verif.Next(cq_.get(), ignore_cq_wd_result);
- GPR_ASSERT((got_tag == 7) || (got_tag == 11 && want_done_tag));
- if (got_tag == 11) {
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- // Now get the other entry that we were waiting on
- EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_wd_result), 7);
- }
-
- // This is expected to fail in all cases i.e for all values of
- // server_try_cancel. This is because at this point, either there are no
- // more msgs from the client (because client called WritesDone) or the RPC
- // is cancelled on the server
- srv_stream.Read(&recv_request, tag(8));
- verif.Expect(8, false);
- got_tag = verif.Next(cq_.get(), ignore_cq_result);
- GPR_ASSERT((got_tag == 8) || (got_tag == 11 && want_done_tag));
- if (got_tag == 11) {
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- // Now get the other entry that we were waiting on
- EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_result), 8);
- }
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- srv_ctx.TryCancel();
- want_done_tag = true;
- verif.Expect(11, true);
- }
-
- if (want_done_tag) {
- verif.Verify(cq_.get());
- EXPECT_TRUE(srv_ctx.IsCancelled());
- want_done_tag = false;
- }
-
- // The RPC has been cancelled at this point for sure (i.e irrespective of
- // the value of `server_try_cancel` is). So, from this point forward, we
- // know that cq results are supposed to return false on server.
-
- srv_stream.Finish(Status::CANCELLED, tag(9));
- Verifier().Expect(9, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(10, true).Verify(cq_.get());
- EXPECT_FALSE(recv_status.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, recv_status.error_code());
- }
-};
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ClientStreamingServerTryCancelBefore) {
- TestClientStreamingServerCancel(CANCEL_BEFORE_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ClientStreamingServerTryCancelDuring) {
- TestClientStreamingServerCancel(CANCEL_DURING_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ClientStreamingServerTryCancelAfter) {
- TestClientStreamingServerCancel(CANCEL_AFTER_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ServerStreamingServerTryCancelBefore) {
- TestServerStreamingServerCancel(CANCEL_BEFORE_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ServerStreamingServerTryCancelDuring) {
- TestServerStreamingServerCancel(CANCEL_DURING_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ServerStreamingServerTryCancelAfter) {
- TestServerStreamingServerCancel(CANCEL_AFTER_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ServerBidiStreamingTryCancelBefore) {
- TestBidiStreamingServerCancel(CANCEL_BEFORE_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ServerBidiStreamingTryCancelDuring) {
- TestBidiStreamingServerCancel(CANCEL_DURING_PROCESSING);
-}
-
-TEST_P(AsyncEnd2endServerTryCancelTest, ServerBidiStreamingTryCancelAfter) {
- TestBidiStreamingServerCancel(CANCEL_AFTER_PROCESSING);
-}
-
-std::vector<TestScenario> CreateTestScenarios(bool /*test_secure*/,
- bool test_message_size_limit) {
- std::vector<TestScenario> scenarios;
+ srv_stream.Write(send_response, tag(tag_idx));
+ // Note that we'll add something to the verifier and verify that
+ // something was seen, but it might be tag 11 and not what we
+ // just added
+ int got_tag = verif.Expect(tag_idx, expected_cq_result)
+ .Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == tag_idx) || (got_tag == 11 && want_done_tag));
+ if (got_tag == 11) {
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ // Now get the other entry that we were waiting on
+ EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_result), tag_idx);
+ }
+ }
+
+ if (server_try_cancel_thd != nullptr) {
+ server_try_cancel_thd->join();
+ delete server_try_cancel_thd;
+ }
+
+ if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
+ srv_ctx.TryCancel();
+ want_done_tag = true;
+ verif.Expect(11, true);
+ }
+
+ if (want_done_tag) {
+ verif.Verify(cq_.get());
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ }
+
+ cli_thread.join();
+
+ // The RPC has been cancelled at this point for sure (i.e irrespective of
+ // the value of `server_try_cancel` is). So, from this point forward, we
+ // know that cq results are supposed to return false on server.
+
+ // Server finishes the stream (but the RPC is already cancelled)
+ srv_stream.Finish(Status::CANCELLED, tag(9));
+ Verifier().Expect(9, false).Verify(cq_.get());
+
+ // Client will see the cancellation
+ cli_stream->Finish(&recv_status, tag(10));
+ Verifier().Expect(10, true).Verify(&cli_cq);
+ EXPECT_FALSE(recv_status.ok());
+ EXPECT_EQ(::grpc::StatusCode::CANCELLED, recv_status.error_code());
+
+ cli_cq.Shutdown();
+ void* dummy_tag;
+ bool dummy_ok;
+ while (cli_cq.Next(&dummy_tag, &dummy_ok)) {
+ }
+ }
+
+ // Helper for testing bidirectinal-streaming RPCs which are cancelled on the
+ // server.
+ //
+ // Depending on the value of server_try_cancel parameter, this will
+ // test one of the following three scenarios:
+ // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading/
+ // writing any messages from/to the client
+ //
+ // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
+ // messages from the client
+ //
+ // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
+ // messages from the client (but before sending any status back to the
+ // client)
+ void TestBidiStreamingServerCancel(
+ ServerTryCancelRequestPhase server_try_cancel) {
+ ResetStub();
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ // Initiate the call from the client side
+ std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
+ cli_stream(stub_->AsyncBidiStream(&cli_ctx, cq_.get(), tag(1)));
+
+ // On the server, request to be notified of the 'BidiStream' call and
+ // receive the call just made by the client
+ srv_ctx.AsyncNotifyWhenDone(tag(11));
+ service_->RequestBidiStream(&srv_ctx, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+
+ auto verif = Verifier();
+
+ // Client sends the first and the only message
+ send_request.set_message("Ping");
+ cli_stream->Write(send_request, tag(3));
+ verif.Expect(3, true);
+
+ bool expected_cq_result = true;
+ bool ignore_cq_result = false;
+ bool want_done_tag = false;
+
+ int got_tag, got_tag2;
+ bool tag_3_done = false;
+
+ if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
+ srv_ctx.TryCancel();
+ verif.Expect(11, true);
+ // We know for sure that all server cq results will be false from
+ // this point since the server cancelled the RPC. However, we can't
+ // say for sure about the client
+ expected_cq_result = false;
+ ignore_cq_result = true;
+
+ do {
+ got_tag = verif.Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT(((got_tag == 3) && !tag_3_done) || (got_tag == 11));
+ if (got_tag == 3) {
+ tag_3_done = true;
+ }
+ } while (got_tag != 11);
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ }
+
+ std::thread* server_try_cancel_thd = nullptr;
+
+ if (server_try_cancel == CANCEL_DURING_PROCESSING) {
+ server_try_cancel_thd =
+ new std::thread([&srv_ctx] { srv_ctx.TryCancel(); });
+
+ // Since server is going to cancel the RPC in a parallel thread, some of
+ // the cq results (i.e those until the cancellation) might be true. Since
+ // that number is non-deterministic, it is better to ignore the cq results
+ ignore_cq_result = true;
+ // Expect that we might possibly see the done tag that
+ // indicates cancellation completion in this case
+ want_done_tag = true;
+ verif.Expect(11, true);
+ }
+
+ srv_stream.Read(&recv_request, tag(4));
+ verif.Expect(4, expected_cq_result);
+ got_tag = tag_3_done ? 3 : verif.Next(cq_.get(), ignore_cq_result);
+ got_tag2 = verif.Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == 3) || (got_tag == 4) ||
+ (got_tag == 11 && want_done_tag));
+ GPR_ASSERT((got_tag2 == 3) || (got_tag2 == 4) ||
+ (got_tag2 == 11 && want_done_tag));
+ // If we get 3 and 4, we don't need to wait for 11, but if
+ // we get 11, we should also clear 3 and 4
+ if (got_tag + got_tag2 != 7) {
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ got_tag = verif.Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == 3) || (got_tag == 4));
+ }
+
+ send_response.set_message("Pong");
+ srv_stream.Write(send_response, tag(5));
+ verif.Expect(5, expected_cq_result);
+
+ cli_stream->Read(&recv_response, tag(6));
+ verif.Expect(6, expected_cq_result);
+ got_tag = verif.Next(cq_.get(), ignore_cq_result);
+ got_tag2 = verif.Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == 5) || (got_tag == 6) ||
+ (got_tag == 11 && want_done_tag));
+ GPR_ASSERT((got_tag2 == 5) || (got_tag2 == 6) ||
+ (got_tag2 == 11 && want_done_tag));
+ // If we get 5 and 6, we don't need to wait for 11, but if
+ // we get 11, we should also clear 5 and 6
+ if (got_tag + got_tag2 != 11) {
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ got_tag = verif.Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == 5) || (got_tag == 6));
+ }
+
+ // This is expected to succeed in all cases
+ cli_stream->WritesDone(tag(7));
+ verif.Expect(7, true);
+ // TODO(vjpai): Consider whether the following is too flexible
+ // or whether it should just be reset to ignore_cq_result
+ bool ignore_cq_wd_result =
+ ignore_cq_result || (server_try_cancel == CANCEL_BEFORE_PROCESSING);
+ got_tag = verif.Next(cq_.get(), ignore_cq_wd_result);
+ GPR_ASSERT((got_tag == 7) || (got_tag == 11 && want_done_tag));
+ if (got_tag == 11) {
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ // Now get the other entry that we were waiting on
+ EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_wd_result), 7);
+ }
+
+ // This is expected to fail in all cases i.e for all values of
+ // server_try_cancel. This is because at this point, either there are no
+ // more msgs from the client (because client called WritesDone) or the RPC
+ // is cancelled on the server
+ srv_stream.Read(&recv_request, tag(8));
+ verif.Expect(8, false);
+ got_tag = verif.Next(cq_.get(), ignore_cq_result);
+ GPR_ASSERT((got_tag == 8) || (got_tag == 11 && want_done_tag));
+ if (got_tag == 11) {
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ // Now get the other entry that we were waiting on
+ EXPECT_EQ(verif.Next(cq_.get(), ignore_cq_result), 8);
+ }
+
+ if (server_try_cancel_thd != nullptr) {
+ server_try_cancel_thd->join();
+ delete server_try_cancel_thd;
+ }
+
+ if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
+ srv_ctx.TryCancel();
+ want_done_tag = true;
+ verif.Expect(11, true);
+ }
+
+ if (want_done_tag) {
+ verif.Verify(cq_.get());
+ EXPECT_TRUE(srv_ctx.IsCancelled());
+ want_done_tag = false;
+ }
+
+ // The RPC has been cancelled at this point for sure (i.e irrespective of
+ // the value of `server_try_cancel` is). So, from this point forward, we
+ // know that cq results are supposed to return false on server.
+
+ srv_stream.Finish(Status::CANCELLED, tag(9));
+ Verifier().Expect(9, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status, tag(10));
+ Verifier().Expect(10, true).Verify(cq_.get());
+ EXPECT_FALSE(recv_status.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, recv_status.error_code());
+ }
+};
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ClientStreamingServerTryCancelBefore) {
+ TestClientStreamingServerCancel(CANCEL_BEFORE_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ClientStreamingServerTryCancelDuring) {
+ TestClientStreamingServerCancel(CANCEL_DURING_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ClientStreamingServerTryCancelAfter) {
+ TestClientStreamingServerCancel(CANCEL_AFTER_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ServerStreamingServerTryCancelBefore) {
+ TestServerStreamingServerCancel(CANCEL_BEFORE_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ServerStreamingServerTryCancelDuring) {
+ TestServerStreamingServerCancel(CANCEL_DURING_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ServerStreamingServerTryCancelAfter) {
+ TestServerStreamingServerCancel(CANCEL_AFTER_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ServerBidiStreamingTryCancelBefore) {
+ TestBidiStreamingServerCancel(CANCEL_BEFORE_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ServerBidiStreamingTryCancelDuring) {
+ TestBidiStreamingServerCancel(CANCEL_DURING_PROCESSING);
+}
+
+TEST_P(AsyncEnd2endServerTryCancelTest, ServerBidiStreamingTryCancelAfter) {
+ TestBidiStreamingServerCancel(CANCEL_AFTER_PROCESSING);
+}
+
+std::vector<TestScenario> CreateTestScenarios(bool /*test_secure*/,
+ bool test_message_size_limit) {
+ std::vector<TestScenario> scenarios;
std::vector<TString> credentials_types;
std::vector<TString> messages;
-
- auto insec_ok = [] {
- // Only allow insecure credentials type when it is registered with the
- // provider. User may create providers that do not have insecure.
- return GetCredentialsProvider()->GetChannelCredentials(
- kInsecureCredentialsType, nullptr) != nullptr;
- };
-
- if (insec_ok()) {
- credentials_types.push_back(kInsecureCredentialsType);
- }
- auto sec_list = GetCredentialsProvider()->GetSecureCredentialsTypeList();
- for (auto sec = sec_list.begin(); sec != sec_list.end(); sec++) {
- credentials_types.push_back(*sec);
- }
- GPR_ASSERT(!credentials_types.empty());
-
- messages.push_back("Hello");
- if (test_message_size_limit) {
- for (size_t k = 1; k < GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH / 1024;
- k *= 32) {
+
+ auto insec_ok = [] {
+ // Only allow insecure credentials type when it is registered with the
+ // provider. User may create providers that do not have insecure.
+ return GetCredentialsProvider()->GetChannelCredentials(
+ kInsecureCredentialsType, nullptr) != nullptr;
+ };
+
+ if (insec_ok()) {
+ credentials_types.push_back(kInsecureCredentialsType);
+ }
+ auto sec_list = GetCredentialsProvider()->GetSecureCredentialsTypeList();
+ for (auto sec = sec_list.begin(); sec != sec_list.end(); sec++) {
+ credentials_types.push_back(*sec);
+ }
+ GPR_ASSERT(!credentials_types.empty());
+
+ messages.push_back("Hello");
+ if (test_message_size_limit) {
+ for (size_t k = 1; k < GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH / 1024;
+ k *= 32) {
TString big_msg;
- for (size_t i = 0; i < k * 1024; ++i) {
- char c = 'a' + (i % 26);
- big_msg += c;
- }
- messages.push_back(big_msg);
- }
+ for (size_t i = 0; i < k * 1024; ++i) {
+ char c = 'a' + (i % 26);
+ big_msg += c;
+ }
+ messages.push_back(big_msg);
+ }
if (!BuiltUnderMsan()) {
// 4MB message processing with SSL is very slow under msan
// (causes timeouts) and doesn't really increase the signal from tests.
@@ -1911,42 +1911,42 @@ std::vector<TestScenario> CreateTestScenarios(bool /*test_secure*/,
messages.push_back(
TString(GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH - 100, 'a'));
}
- }
-
- // TODO (sreek) Renable tests with health check service after the issue
- // https://github.com/grpc/grpc/issues/11223 is resolved
- for (auto health_check_service : {false}) {
- for (auto msg = messages.begin(); msg != messages.end(); msg++) {
- for (auto cred = credentials_types.begin();
- cred != credentials_types.end(); ++cred) {
- scenarios.emplace_back(false, *cred, health_check_service, *msg);
- }
- if (insec_ok()) {
- scenarios.emplace_back(true, kInsecureCredentialsType,
- health_check_service, *msg);
- }
- }
- }
- return scenarios;
-}
-
-INSTANTIATE_TEST_SUITE_P(AsyncEnd2end, AsyncEnd2endTest,
- ::testing::ValuesIn(CreateTestScenarios(true, true)));
-INSTANTIATE_TEST_SUITE_P(AsyncEnd2endServerTryCancel,
- AsyncEnd2endServerTryCancelTest,
- ::testing::ValuesIn(CreateTestScenarios(false,
- false)));
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- // Change the backup poll interval from 5s to 100ms to speed up the
- // ReconnectChannel test
- GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 100);
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- int ret = RUN_ALL_TESTS();
- return ret;
-}
+ }
+
+ // TODO (sreek) Renable tests with health check service after the issue
+ // https://github.com/grpc/grpc/issues/11223 is resolved
+ for (auto health_check_service : {false}) {
+ for (auto msg = messages.begin(); msg != messages.end(); msg++) {
+ for (auto cred = credentials_types.begin();
+ cred != credentials_types.end(); ++cred) {
+ scenarios.emplace_back(false, *cred, health_check_service, *msg);
+ }
+ if (insec_ok()) {
+ scenarios.emplace_back(true, kInsecureCredentialsType,
+ health_check_service, *msg);
+ }
+ }
+ }
+ return scenarios;
+}
+
+INSTANTIATE_TEST_SUITE_P(AsyncEnd2end, AsyncEnd2endTest,
+ ::testing::ValuesIn(CreateTestScenarios(true, true)));
+INSTANTIATE_TEST_SUITE_P(AsyncEnd2endServerTryCancel,
+ AsyncEnd2endServerTryCancelTest,
+ ::testing::ValuesIn(CreateTestScenarios(false,
+ false)));
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ // Change the backup poll interval from 5s to 100ms to speed up the
+ // ReconnectChannel test
+ GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 100);
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ int ret = RUN_ALL_TESTS();
+ return ret;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/channelz_service_test.cc b/contrib/libs/grpc/test/cpp/end2end/channelz_service_test.cc
index 9c723bebb6..2f9c840a0f 100644
--- a/contrib/libs/grpc/test/cpp/end2end/channelz_service_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/channelz_service_test.cc
@@ -1,767 +1,767 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include <grpcpp/ext/channelz_service_plugin.h>
-#include "src/core/lib/gpr/env.h"
-#include "src/proto/grpc/channelz/channelz.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <gtest/gtest.h>
-
-using grpc::channelz::v1::GetChannelRequest;
-using grpc::channelz::v1::GetChannelResponse;
-using grpc::channelz::v1::GetServerRequest;
-using grpc::channelz::v1::GetServerResponse;
-using grpc::channelz::v1::GetServerSocketsRequest;
-using grpc::channelz::v1::GetServerSocketsResponse;
-using grpc::channelz::v1::GetServersRequest;
-using grpc::channelz::v1::GetServersResponse;
-using grpc::channelz::v1::GetSocketRequest;
-using grpc::channelz::v1::GetSocketResponse;
-using grpc::channelz::v1::GetSubchannelRequest;
-using grpc::channelz::v1::GetSubchannelResponse;
-using grpc::channelz::v1::GetTopChannelsRequest;
-using grpc::channelz::v1::GetTopChannelsResponse;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-// Proxy service supports N backends. Sends RPC to backend dictated by
-// request->backend_channel_idx().
-class Proxy : public ::grpc::testing::EchoTestService::Service {
- public:
- Proxy() {}
-
- void AddChannelToBackend(const std::shared_ptr<Channel>& channel) {
- stubs_.push_back(grpc::testing::EchoTestService::NewStub(channel));
- }
-
- Status Echo(ServerContext* server_context, const EchoRequest* request,
- EchoResponse* response) override {
- std::unique_ptr<ClientContext> client_context =
- ClientContext::FromServerContext(*server_context);
- size_t idx = request->param().backend_channel_idx();
- GPR_ASSERT(idx < stubs_.size());
- return stubs_[idx]->Echo(client_context.get(), *request, response);
- }
-
- Status BidiStream(ServerContext* server_context,
- ServerReaderWriter<EchoResponse, EchoRequest>*
- stream_from_client) override {
- EchoRequest request;
- EchoResponse response;
- std::unique_ptr<ClientContext> client_context =
- ClientContext::FromServerContext(*server_context);
-
- // always use the first proxy for streaming
- auto stream_to_backend = stubs_[0]->BidiStream(client_context.get());
- while (stream_from_client->Read(&request)) {
- stream_to_backend->Write(request);
- stream_to_backend->Read(&response);
- stream_from_client->Write(response);
- }
-
- stream_to_backend->WritesDone();
- return stream_to_backend->Finish();
- }
-
- private:
- std::vector<std::unique_ptr<::grpc::testing::EchoTestService::Stub>> stubs_;
-};
-
-} // namespace
-
-class ChannelzServerTest : public ::testing::Test {
- public:
- ChannelzServerTest() {}
- static void SetUpTestCase() {
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
- }
- void SetUp() override {
- // ensure channel server is brought up on all severs we build.
- ::grpc::channelz::experimental::InitChannelzService();
-
- // We set up a proxy server with channelz enabled.
- proxy_port_ = grpc_pick_unused_port_or_die();
- ServerBuilder proxy_builder;
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include <grpcpp/ext/channelz_service_plugin.h>
+#include "src/core/lib/gpr/env.h"
+#include "src/proto/grpc/channelz/channelz.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_service_impl.h"
+
+#include <gtest/gtest.h>
+
+using grpc::channelz::v1::GetChannelRequest;
+using grpc::channelz::v1::GetChannelResponse;
+using grpc::channelz::v1::GetServerRequest;
+using grpc::channelz::v1::GetServerResponse;
+using grpc::channelz::v1::GetServerSocketsRequest;
+using grpc::channelz::v1::GetServerSocketsResponse;
+using grpc::channelz::v1::GetServersRequest;
+using grpc::channelz::v1::GetServersResponse;
+using grpc::channelz::v1::GetSocketRequest;
+using grpc::channelz::v1::GetSocketResponse;
+using grpc::channelz::v1::GetSubchannelRequest;
+using grpc::channelz::v1::GetSubchannelResponse;
+using grpc::channelz::v1::GetTopChannelsRequest;
+using grpc::channelz::v1::GetTopChannelsResponse;
+
+namespace grpc {
+namespace testing {
+namespace {
+
+// Proxy service supports N backends. Sends RPC to backend dictated by
+// request->backend_channel_idx().
+class Proxy : public ::grpc::testing::EchoTestService::Service {
+ public:
+ Proxy() {}
+
+ void AddChannelToBackend(const std::shared_ptr<Channel>& channel) {
+ stubs_.push_back(grpc::testing::EchoTestService::NewStub(channel));
+ }
+
+ Status Echo(ServerContext* server_context, const EchoRequest* request,
+ EchoResponse* response) override {
+ std::unique_ptr<ClientContext> client_context =
+ ClientContext::FromServerContext(*server_context);
+ size_t idx = request->param().backend_channel_idx();
+ GPR_ASSERT(idx < stubs_.size());
+ return stubs_[idx]->Echo(client_context.get(), *request, response);
+ }
+
+ Status BidiStream(ServerContext* server_context,
+ ServerReaderWriter<EchoResponse, EchoRequest>*
+ stream_from_client) override {
+ EchoRequest request;
+ EchoResponse response;
+ std::unique_ptr<ClientContext> client_context =
+ ClientContext::FromServerContext(*server_context);
+
+ // always use the first proxy for streaming
+ auto stream_to_backend = stubs_[0]->BidiStream(client_context.get());
+ while (stream_from_client->Read(&request)) {
+ stream_to_backend->Write(request);
+ stream_to_backend->Read(&response);
+ stream_from_client->Write(response);
+ }
+
+ stream_to_backend->WritesDone();
+ return stream_to_backend->Finish();
+ }
+
+ private:
+ std::vector<std::unique_ptr<::grpc::testing::EchoTestService::Stub>> stubs_;
+};
+
+} // namespace
+
+class ChannelzServerTest : public ::testing::Test {
+ public:
+ ChannelzServerTest() {}
+ static void SetUpTestCase() {
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+ }
+ void SetUp() override {
+ // ensure channel server is brought up on all severs we build.
+ ::grpc::channelz::experimental::InitChannelzService();
+
+ // We set up a proxy server with channelz enabled.
+ proxy_port_ = grpc_pick_unused_port_or_die();
+ ServerBuilder proxy_builder;
TString proxy_server_address = "localhost:" + to_string(proxy_port_);
- proxy_builder.AddListeningPort(proxy_server_address,
- InsecureServerCredentials());
- // forces channelz and channel tracing to be enabled.
- proxy_builder.AddChannelArgument(GRPC_ARG_ENABLE_CHANNELZ, 1);
- proxy_builder.AddChannelArgument(
- GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE, 1024);
- proxy_builder.RegisterService(&proxy_service_);
- proxy_server_ = proxy_builder.BuildAndStart();
- }
-
- // Sets the proxy up to have an arbitrary number of backends.
- void ConfigureProxy(size_t num_backends) {
- backends_.resize(num_backends);
- for (size_t i = 0; i < num_backends; ++i) {
- // create a new backend.
- backends_[i].port = grpc_pick_unused_port_or_die();
- ServerBuilder backend_builder;
+ proxy_builder.AddListeningPort(proxy_server_address,
+ InsecureServerCredentials());
+ // forces channelz and channel tracing to be enabled.
+ proxy_builder.AddChannelArgument(GRPC_ARG_ENABLE_CHANNELZ, 1);
+ proxy_builder.AddChannelArgument(
+ GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE, 1024);
+ proxy_builder.RegisterService(&proxy_service_);
+ proxy_server_ = proxy_builder.BuildAndStart();
+ }
+
+ // Sets the proxy up to have an arbitrary number of backends.
+ void ConfigureProxy(size_t num_backends) {
+ backends_.resize(num_backends);
+ for (size_t i = 0; i < num_backends; ++i) {
+ // create a new backend.
+ backends_[i].port = grpc_pick_unused_port_or_die();
+ ServerBuilder backend_builder;
TString backend_server_address =
- "localhost:" + to_string(backends_[i].port);
- backend_builder.AddListeningPort(backend_server_address,
- InsecureServerCredentials());
- backends_[i].service.reset(new TestServiceImpl);
- // ensure that the backend itself has channelz disabled.
- backend_builder.AddChannelArgument(GRPC_ARG_ENABLE_CHANNELZ, 0);
- backend_builder.RegisterService(backends_[i].service.get());
- backends_[i].server = backend_builder.BuildAndStart();
- // set up a channel to the backend. We ensure that this channel has
- // channelz enabled since these channels (proxy outbound to backends)
- // are the ones that our test will actually be validating.
- ChannelArguments args;
- args.SetInt(GRPC_ARG_ENABLE_CHANNELZ, 1);
- args.SetInt(GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE, 1024);
- std::shared_ptr<Channel> channel_to_backend = ::grpc::CreateCustomChannel(
- backend_server_address, InsecureChannelCredentials(), args);
- proxy_service_.AddChannelToBackend(channel_to_backend);
- }
- }
-
- void ResetStubs() {
- string target = "dns:localhost:" + to_string(proxy_port_);
- ChannelArguments args;
- // disable channelz. We only want to focus on proxy to backend outbound.
- args.SetInt(GRPC_ARG_ENABLE_CHANNELZ, 0);
- std::shared_ptr<Channel> channel =
- ::grpc::CreateCustomChannel(target, InsecureChannelCredentials(), args);
- channelz_stub_ = grpc::channelz::v1::Channelz::NewStub(channel);
- echo_stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- std::unique_ptr<grpc::testing::EchoTestService::Stub> NewEchoStub() {
- string target = "dns:localhost:" + to_string(proxy_port_);
- ChannelArguments args;
- // disable channelz. We only want to focus on proxy to backend outbound.
- args.SetInt(GRPC_ARG_ENABLE_CHANNELZ, 0);
- // This ensures that gRPC will not do connection sharing.
- args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, true);
- std::shared_ptr<Channel> channel =
- ::grpc::CreateCustomChannel(target, InsecureChannelCredentials(), args);
- return grpc::testing::EchoTestService::NewStub(channel);
- }
-
- void SendSuccessfulEcho(int channel_idx) {
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello channelz");
- request.mutable_param()->set_backend_channel_idx(channel_idx);
- ClientContext context;
- Status s = echo_stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- }
-
- void SendSuccessfulStream(int num_messages) {
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello channelz");
- ClientContext context;
- auto stream_to_proxy = echo_stub_->BidiStream(&context);
- for (int i = 0; i < num_messages; ++i) {
- EXPECT_TRUE(stream_to_proxy->Write(request));
- EXPECT_TRUE(stream_to_proxy->Read(&response));
- }
- stream_to_proxy->WritesDone();
- Status s = stream_to_proxy->Finish();
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- }
-
- void SendFailedEcho(int channel_idx) {
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello channelz");
- request.mutable_param()->set_backend_channel_idx(channel_idx);
- auto* error = request.mutable_param()->mutable_expected_error();
- error->set_code(13); // INTERNAL
- error->set_error_message("error");
- ClientContext context;
- Status s = echo_stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- }
-
- // Uses GetTopChannels to return the channel_id of a particular channel,
- // so that the unit tests may test GetChannel call.
- intptr_t GetChannelId(int channel_idx) {
- GetTopChannelsRequest request;
- GetTopChannelsResponse response;
- request.set_start_channel_id(0);
- ClientContext context;
- Status s = channelz_stub_->GetTopChannels(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_GT(response.channel_size(), channel_idx);
- return response.channel(channel_idx).ref().channel_id();
- }
-
- static string to_string(const int number) {
- std::stringstream strs;
- strs << number;
- return strs.str();
- }
-
- protected:
- // package of data needed for each backend server.
- struct BackendData {
- std::unique_ptr<Server> server;
- int port;
- std::unique_ptr<TestServiceImpl> service;
- };
-
- std::unique_ptr<grpc::channelz::v1::Channelz::Stub> channelz_stub_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> echo_stub_;
-
- // proxy server to ping with channelz requests.
- std::unique_ptr<Server> proxy_server_;
- int proxy_port_;
- Proxy proxy_service_;
-
- // backends. All implement the echo service.
- std::vector<BackendData> backends_;
-};
-
-TEST_F(ChannelzServerTest, BasicTest) {
- ResetStubs();
- ConfigureProxy(1);
- GetTopChannelsRequest request;
- GetTopChannelsResponse response;
- request.set_start_channel_id(0);
- ClientContext context;
- Status s = channelz_stub_->GetTopChannels(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel_size(), 1);
-}
-
-TEST_F(ChannelzServerTest, HighStartId) {
- ResetStubs();
- ConfigureProxy(1);
- GetTopChannelsRequest request;
- GetTopChannelsResponse response;
- request.set_start_channel_id(10000);
- ClientContext context;
- Status s = channelz_stub_->GetTopChannels(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel_size(), 0);
-}
-
-TEST_F(ChannelzServerTest, SuccessfulRequestTest) {
- ResetStubs();
- ConfigureProxy(1);
- SendSuccessfulEcho(0);
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(0));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(), 1);
- EXPECT_EQ(response.channel().data().calls_succeeded(), 1);
- EXPECT_EQ(response.channel().data().calls_failed(), 0);
-}
-
-TEST_F(ChannelzServerTest, FailedRequestTest) {
- ResetStubs();
- ConfigureProxy(1);
- SendFailedEcho(0);
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(0));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(), 1);
- EXPECT_EQ(response.channel().data().calls_succeeded(), 0);
- EXPECT_EQ(response.channel().data().calls_failed(), 1);
-}
-
-TEST_F(ChannelzServerTest, ManyRequestsTest) {
- ResetStubs();
- ConfigureProxy(1);
- // send some RPCs
- const int kNumSuccess = 10;
- const int kNumFailed = 11;
- for (int i = 0; i < kNumSuccess; ++i) {
- SendSuccessfulEcho(0);
- }
- for (int i = 0; i < kNumFailed; ++i) {
- SendFailedEcho(0);
- }
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(0));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(),
- kNumSuccess + kNumFailed);
- EXPECT_EQ(response.channel().data().calls_succeeded(), kNumSuccess);
- EXPECT_EQ(response.channel().data().calls_failed(), kNumFailed);
-}
-
-TEST_F(ChannelzServerTest, ManyChannels) {
- ResetStubs();
- const int kNumChannels = 4;
- ConfigureProxy(kNumChannels);
- GetTopChannelsRequest request;
- GetTopChannelsResponse response;
- request.set_start_channel_id(0);
- ClientContext context;
- Status s = channelz_stub_->GetTopChannels(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel_size(), kNumChannels);
-}
-
-TEST_F(ChannelzServerTest, ManyRequestsManyChannels) {
- ResetStubs();
- const int kNumChannels = 4;
- ConfigureProxy(kNumChannels);
- const int kNumSuccess = 10;
- const int kNumFailed = 11;
- for (int i = 0; i < kNumSuccess; ++i) {
- SendSuccessfulEcho(0);
- SendSuccessfulEcho(2);
- }
- for (int i = 0; i < kNumFailed; ++i) {
- SendFailedEcho(1);
- SendFailedEcho(2);
- }
-
- // the first channel saw only successes
- {
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(0));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(), kNumSuccess);
- EXPECT_EQ(response.channel().data().calls_succeeded(), kNumSuccess);
- EXPECT_EQ(response.channel().data().calls_failed(), 0);
- }
-
- // the second channel saw only failures
- {
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(1));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(), kNumFailed);
- EXPECT_EQ(response.channel().data().calls_succeeded(), 0);
- EXPECT_EQ(response.channel().data().calls_failed(), kNumFailed);
- }
-
- // the third channel saw both
- {
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(2));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(),
- kNumSuccess + kNumFailed);
- EXPECT_EQ(response.channel().data().calls_succeeded(), kNumSuccess);
- EXPECT_EQ(response.channel().data().calls_failed(), kNumFailed);
- }
-
- // the fourth channel saw nothing
- {
- GetChannelRequest request;
- GetChannelResponse response;
- request.set_channel_id(GetChannelId(3));
- ClientContext context;
- Status s = channelz_stub_->GetChannel(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.channel().data().calls_started(), 0);
- EXPECT_EQ(response.channel().data().calls_succeeded(), 0);
- EXPECT_EQ(response.channel().data().calls_failed(), 0);
- }
-}
-
-TEST_F(ChannelzServerTest, ManySubchannels) {
- ResetStubs();
- const int kNumChannels = 4;
- ConfigureProxy(kNumChannels);
- const int kNumSuccess = 10;
- const int kNumFailed = 11;
- for (int i = 0; i < kNumSuccess; ++i) {
- SendSuccessfulEcho(0);
- SendSuccessfulEcho(2);
- }
- for (int i = 0; i < kNumFailed; ++i) {
- SendFailedEcho(1);
- SendFailedEcho(2);
- }
- GetTopChannelsRequest gtc_request;
- GetTopChannelsResponse gtc_response;
- gtc_request.set_start_channel_id(0);
- ClientContext context;
- Status s =
- channelz_stub_->GetTopChannels(&context, gtc_request, &gtc_response);
- EXPECT_TRUE(s.ok()) << s.error_message();
- EXPECT_EQ(gtc_response.channel_size(), kNumChannels);
- for (int i = 0; i < gtc_response.channel_size(); ++i) {
- // if the channel sent no RPCs, then expect no subchannels to have been
- // created.
- if (gtc_response.channel(i).data().calls_started() == 0) {
- EXPECT_EQ(gtc_response.channel(i).subchannel_ref_size(), 0);
- continue;
- }
- // The resolver must return at least one address.
- ASSERT_GT(gtc_response.channel(i).subchannel_ref_size(), 0);
- GetSubchannelRequest gsc_request;
- GetSubchannelResponse gsc_response;
- gsc_request.set_subchannel_id(
- gtc_response.channel(i).subchannel_ref(0).subchannel_id());
- ClientContext context;
- Status s =
- channelz_stub_->GetSubchannel(&context, gsc_request, &gsc_response);
- EXPECT_TRUE(s.ok()) << s.error_message();
- EXPECT_EQ(gtc_response.channel(i).data().calls_started(),
- gsc_response.subchannel().data().calls_started());
- EXPECT_EQ(gtc_response.channel(i).data().calls_succeeded(),
- gsc_response.subchannel().data().calls_succeeded());
- EXPECT_EQ(gtc_response.channel(i).data().calls_failed(),
- gsc_response.subchannel().data().calls_failed());
- }
-}
-
-TEST_F(ChannelzServerTest, BasicServerTest) {
- ResetStubs();
- ConfigureProxy(1);
- GetServersRequest request;
- GetServersResponse response;
- request.set_start_server_id(0);
- ClientContext context;
- Status s = channelz_stub_->GetServers(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.server_size(), 1);
-}
-
-TEST_F(ChannelzServerTest, BasicGetServerTest) {
- ResetStubs();
- ConfigureProxy(1);
- GetServersRequest get_servers_request;
- GetServersResponse get_servers_response;
- get_servers_request.set_start_server_id(0);
- ClientContext get_servers_context;
- Status s = channelz_stub_->GetServers(
- &get_servers_context, get_servers_request, &get_servers_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_servers_response.server_size(), 1);
- GetServerRequest get_server_request;
- GetServerResponse get_server_response;
- get_server_request.set_server_id(
- get_servers_response.server(0).ref().server_id());
- ClientContext get_server_context;
- s = channelz_stub_->GetServer(&get_server_context, get_server_request,
- &get_server_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_servers_response.server(0).ref().server_id(),
- get_server_response.server().ref().server_id());
-}
-
-TEST_F(ChannelzServerTest, ServerCallTest) {
- ResetStubs();
- ConfigureProxy(1);
- const int kNumSuccess = 10;
- const int kNumFailed = 11;
- for (int i = 0; i < kNumSuccess; ++i) {
- SendSuccessfulEcho(0);
- }
- for (int i = 0; i < kNumFailed; ++i) {
- SendFailedEcho(0);
- }
- GetServersRequest request;
- GetServersResponse response;
- request.set_start_server_id(0);
- ClientContext context;
- Status s = channelz_stub_->GetServers(&context, request, &response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(response.server_size(), 1);
- EXPECT_EQ(response.server(0).data().calls_succeeded(), kNumSuccess);
- EXPECT_EQ(response.server(0).data().calls_failed(), kNumFailed);
- // This is success+failure+1 because the call that retrieved this information
- // will be counted as started. It will not track success/failure until after
- // it has returned, so that is not included in the response.
- EXPECT_EQ(response.server(0).data().calls_started(),
- kNumSuccess + kNumFailed + 1);
-}
-
-TEST_F(ChannelzServerTest, ManySubchannelsAndSockets) {
- ResetStubs();
- const int kNumChannels = 4;
- ConfigureProxy(kNumChannels);
- const int kNumSuccess = 10;
- const int kNumFailed = 11;
- for (int i = 0; i < kNumSuccess; ++i) {
- SendSuccessfulEcho(0);
- SendSuccessfulEcho(2);
- }
- for (int i = 0; i < kNumFailed; ++i) {
- SendFailedEcho(1);
- SendFailedEcho(2);
- }
- GetTopChannelsRequest gtc_request;
- GetTopChannelsResponse gtc_response;
- gtc_request.set_start_channel_id(0);
- ClientContext context;
- Status s =
- channelz_stub_->GetTopChannels(&context, gtc_request, &gtc_response);
- EXPECT_TRUE(s.ok()) << s.error_message();
- EXPECT_EQ(gtc_response.channel_size(), kNumChannels);
- for (int i = 0; i < gtc_response.channel_size(); ++i) {
- // if the channel sent no RPCs, then expect no subchannels to have been
- // created.
- if (gtc_response.channel(i).data().calls_started() == 0) {
- EXPECT_EQ(gtc_response.channel(i).subchannel_ref_size(), 0);
- continue;
- }
- // The resolver must return at least one address.
- ASSERT_GT(gtc_response.channel(i).subchannel_ref_size(), 0);
- // First grab the subchannel
- GetSubchannelRequest get_subchannel_req;
- GetSubchannelResponse get_subchannel_resp;
- get_subchannel_req.set_subchannel_id(
- gtc_response.channel(i).subchannel_ref(0).subchannel_id());
- ClientContext get_subchannel_ctx;
- Status s = channelz_stub_->GetSubchannel(
- &get_subchannel_ctx, get_subchannel_req, &get_subchannel_resp);
- EXPECT_TRUE(s.ok()) << s.error_message();
- EXPECT_EQ(get_subchannel_resp.subchannel().socket_ref_size(), 1);
- // Now grab the socket.
- GetSocketRequest get_socket_req;
- GetSocketResponse get_socket_resp;
- ClientContext get_socket_ctx;
- get_socket_req.set_socket_id(
- get_subchannel_resp.subchannel().socket_ref(0).socket_id());
- s = channelz_stub_->GetSocket(&get_socket_ctx, get_socket_req,
- &get_socket_resp);
- EXPECT_TRUE(
- get_subchannel_resp.subchannel().socket_ref(0).name().find("http"));
- EXPECT_TRUE(s.ok()) << s.error_message();
- // calls started == streams started AND stream succeeded. Since none of
- // these RPCs were canceled, all of the streams will succeeded even though
- // the RPCs they represent might have failed.
- EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_started(),
- get_socket_resp.socket().data().streams_started());
- EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_started(),
- get_socket_resp.socket().data().streams_succeeded());
- // All of the calls were unary, so calls started == messages sent.
- EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_started(),
- get_socket_resp.socket().data().messages_sent());
- // We only get responses when the RPC was successful, so
- // calls succeeded == messages received.
- EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_succeeded(),
- get_socket_resp.socket().data().messages_received());
- }
-}
-
-TEST_F(ChannelzServerTest, StreamingRPC) {
- ResetStubs();
- ConfigureProxy(1);
- const int kNumMessages = 5;
- SendSuccessfulStream(kNumMessages);
- // Get the channel
- GetChannelRequest get_channel_request;
- GetChannelResponse get_channel_response;
- get_channel_request.set_channel_id(GetChannelId(0));
- ClientContext get_channel_context;
- Status s = channelz_stub_->GetChannel(
- &get_channel_context, get_channel_request, &get_channel_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_channel_response.channel().data().calls_started(), 1);
- EXPECT_EQ(get_channel_response.channel().data().calls_succeeded(), 1);
- EXPECT_EQ(get_channel_response.channel().data().calls_failed(), 0);
- // Get the subchannel
- ASSERT_GT(get_channel_response.channel().subchannel_ref_size(), 0);
- GetSubchannelRequest get_subchannel_request;
- GetSubchannelResponse get_subchannel_response;
- ClientContext get_subchannel_context;
- get_subchannel_request.set_subchannel_id(
- get_channel_response.channel().subchannel_ref(0).subchannel_id());
- s = channelz_stub_->GetSubchannel(&get_subchannel_context,
- get_subchannel_request,
- &get_subchannel_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_subchannel_response.subchannel().data().calls_started(), 1);
- EXPECT_EQ(get_subchannel_response.subchannel().data().calls_succeeded(), 1);
- EXPECT_EQ(get_subchannel_response.subchannel().data().calls_failed(), 0);
- // Get the socket
- ASSERT_GT(get_subchannel_response.subchannel().socket_ref_size(), 0);
- GetSocketRequest get_socket_request;
- GetSocketResponse get_socket_response;
- ClientContext get_socket_context;
- get_socket_request.set_socket_id(
- get_subchannel_response.subchannel().socket_ref(0).socket_id());
- EXPECT_TRUE(
- get_subchannel_response.subchannel().socket_ref(0).name().find("http"));
- s = channelz_stub_->GetSocket(&get_socket_context, get_socket_request,
- &get_socket_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_socket_response.socket().data().streams_started(), 1);
- EXPECT_EQ(get_socket_response.socket().data().streams_succeeded(), 1);
- EXPECT_EQ(get_socket_response.socket().data().streams_failed(), 0);
- EXPECT_EQ(get_socket_response.socket().data().messages_sent(), kNumMessages);
- EXPECT_EQ(get_socket_response.socket().data().messages_received(),
- kNumMessages);
-}
-
-TEST_F(ChannelzServerTest, GetServerSocketsTest) {
- ResetStubs();
- ConfigureProxy(1);
- GetServersRequest get_server_request;
- GetServersResponse get_server_response;
- get_server_request.set_start_server_id(0);
- ClientContext get_server_context;
- Status s = channelz_stub_->GetServers(&get_server_context, get_server_request,
- &get_server_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_server_response.server_size(), 1);
- GetServerSocketsRequest get_server_sockets_request;
- GetServerSocketsResponse get_server_sockets_response;
- get_server_sockets_request.set_server_id(
- get_server_response.server(0).ref().server_id());
- get_server_sockets_request.set_start_socket_id(0);
- ClientContext get_server_sockets_context;
- s = channelz_stub_->GetServerSockets(&get_server_sockets_context,
- get_server_sockets_request,
- &get_server_sockets_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_server_sockets_response.socket_ref_size(), 1);
- EXPECT_TRUE(get_server_sockets_response.socket_ref(0).name().find("http"));
-}
-
-TEST_F(ChannelzServerTest, GetServerSocketsPaginationTest) {
- ResetStubs();
- ConfigureProxy(1);
- std::vector<std::unique_ptr<grpc::testing::EchoTestService::Stub>> stubs;
- const int kNumServerSocketsCreated = 20;
- for (int i = 0; i < kNumServerSocketsCreated; ++i) {
- stubs.push_back(NewEchoStub());
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello channelz");
- request.mutable_param()->set_backend_channel_idx(0);
- ClientContext context;
- Status s = stubs.back()->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- }
- GetServersRequest get_server_request;
- GetServersResponse get_server_response;
- get_server_request.set_start_server_id(0);
- ClientContext get_server_context;
- Status s = channelz_stub_->GetServers(&get_server_context, get_server_request,
- &get_server_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_server_response.server_size(), 1);
- // Make a request that gets all of the serversockets
- {
- GetServerSocketsRequest get_server_sockets_request;
- GetServerSocketsResponse get_server_sockets_response;
- get_server_sockets_request.set_server_id(
- get_server_response.server(0).ref().server_id());
- get_server_sockets_request.set_start_socket_id(0);
- ClientContext get_server_sockets_context;
- s = channelz_stub_->GetServerSockets(&get_server_sockets_context,
- get_server_sockets_request,
- &get_server_sockets_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- // We add one to account the channelz stub that will end up creating
- // a serversocket.
- EXPECT_EQ(get_server_sockets_response.socket_ref_size(),
- kNumServerSocketsCreated + 1);
- EXPECT_TRUE(get_server_sockets_response.end());
- }
- // Now we make a request that exercises pagination.
- {
- GetServerSocketsRequest get_server_sockets_request;
- GetServerSocketsResponse get_server_sockets_response;
- get_server_sockets_request.set_server_id(
- get_server_response.server(0).ref().server_id());
- get_server_sockets_request.set_start_socket_id(0);
- const int kMaxResults = 10;
- get_server_sockets_request.set_max_results(kMaxResults);
- ClientContext get_server_sockets_context;
- s = channelz_stub_->GetServerSockets(&get_server_sockets_context,
- get_server_sockets_request,
- &get_server_sockets_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_server_sockets_response.socket_ref_size(), kMaxResults);
- EXPECT_FALSE(get_server_sockets_response.end());
- }
-}
-
-TEST_F(ChannelzServerTest, GetServerListenSocketsTest) {
- ResetStubs();
- ConfigureProxy(1);
- GetServersRequest get_server_request;
- GetServersResponse get_server_response;
- get_server_request.set_start_server_id(0);
- ClientContext get_server_context;
- Status s = channelz_stub_->GetServers(&get_server_context, get_server_request,
- &get_server_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
- EXPECT_EQ(get_server_response.server_size(), 1);
- EXPECT_EQ(get_server_response.server(0).listen_socket_size(), 1);
- GetSocketRequest get_socket_request;
- GetSocketResponse get_socket_response;
- get_socket_request.set_socket_id(
- get_server_response.server(0).listen_socket(0).socket_id());
- EXPECT_TRUE(
- get_server_response.server(0).listen_socket(0).name().find("http"));
- ClientContext get_socket_context;
- s = channelz_stub_->GetSocket(&get_socket_context, get_socket_request,
- &get_socket_response);
- EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
-}
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ "localhost:" + to_string(backends_[i].port);
+ backend_builder.AddListeningPort(backend_server_address,
+ InsecureServerCredentials());
+ backends_[i].service.reset(new TestServiceImpl);
+ // ensure that the backend itself has channelz disabled.
+ backend_builder.AddChannelArgument(GRPC_ARG_ENABLE_CHANNELZ, 0);
+ backend_builder.RegisterService(backends_[i].service.get());
+ backends_[i].server = backend_builder.BuildAndStart();
+ // set up a channel to the backend. We ensure that this channel has
+ // channelz enabled since these channels (proxy outbound to backends)
+ // are the ones that our test will actually be validating.
+ ChannelArguments args;
+ args.SetInt(GRPC_ARG_ENABLE_CHANNELZ, 1);
+ args.SetInt(GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE, 1024);
+ std::shared_ptr<Channel> channel_to_backend = ::grpc::CreateCustomChannel(
+ backend_server_address, InsecureChannelCredentials(), args);
+ proxy_service_.AddChannelToBackend(channel_to_backend);
+ }
+ }
+
+ void ResetStubs() {
+ string target = "dns:localhost:" + to_string(proxy_port_);
+ ChannelArguments args;
+ // disable channelz. We only want to focus on proxy to backend outbound.
+ args.SetInt(GRPC_ARG_ENABLE_CHANNELZ, 0);
+ std::shared_ptr<Channel> channel =
+ ::grpc::CreateCustomChannel(target, InsecureChannelCredentials(), args);
+ channelz_stub_ = grpc::channelz::v1::Channelz::NewStub(channel);
+ echo_stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> NewEchoStub() {
+ string target = "dns:localhost:" + to_string(proxy_port_);
+ ChannelArguments args;
+ // disable channelz. We only want to focus on proxy to backend outbound.
+ args.SetInt(GRPC_ARG_ENABLE_CHANNELZ, 0);
+ // This ensures that gRPC will not do connection sharing.
+ args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, true);
+ std::shared_ptr<Channel> channel =
+ ::grpc::CreateCustomChannel(target, InsecureChannelCredentials(), args);
+ return grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ void SendSuccessfulEcho(int channel_idx) {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello channelz");
+ request.mutable_param()->set_backend_channel_idx(channel_idx);
+ ClientContext context;
+ Status s = echo_stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ }
+
+ void SendSuccessfulStream(int num_messages) {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello channelz");
+ ClientContext context;
+ auto stream_to_proxy = echo_stub_->BidiStream(&context);
+ for (int i = 0; i < num_messages; ++i) {
+ EXPECT_TRUE(stream_to_proxy->Write(request));
+ EXPECT_TRUE(stream_to_proxy->Read(&response));
+ }
+ stream_to_proxy->WritesDone();
+ Status s = stream_to_proxy->Finish();
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ }
+
+ void SendFailedEcho(int channel_idx) {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello channelz");
+ request.mutable_param()->set_backend_channel_idx(channel_idx);
+ auto* error = request.mutable_param()->mutable_expected_error();
+ error->set_code(13); // INTERNAL
+ error->set_error_message("error");
+ ClientContext context;
+ Status s = echo_stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ }
+
+ // Uses GetTopChannels to return the channel_id of a particular channel,
+ // so that the unit tests may test GetChannel call.
+ intptr_t GetChannelId(int channel_idx) {
+ GetTopChannelsRequest request;
+ GetTopChannelsResponse response;
+ request.set_start_channel_id(0);
+ ClientContext context;
+ Status s = channelz_stub_->GetTopChannels(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_GT(response.channel_size(), channel_idx);
+ return response.channel(channel_idx).ref().channel_id();
+ }
+
+ static string to_string(const int number) {
+ std::stringstream strs;
+ strs << number;
+ return strs.str();
+ }
+
+ protected:
+ // package of data needed for each backend server.
+ struct BackendData {
+ std::unique_ptr<Server> server;
+ int port;
+ std::unique_ptr<TestServiceImpl> service;
+ };
+
+ std::unique_ptr<grpc::channelz::v1::Channelz::Stub> channelz_stub_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> echo_stub_;
+
+ // proxy server to ping with channelz requests.
+ std::unique_ptr<Server> proxy_server_;
+ int proxy_port_;
+ Proxy proxy_service_;
+
+ // backends. All implement the echo service.
+ std::vector<BackendData> backends_;
+};
+
+TEST_F(ChannelzServerTest, BasicTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ GetTopChannelsRequest request;
+ GetTopChannelsResponse response;
+ request.set_start_channel_id(0);
+ ClientContext context;
+ Status s = channelz_stub_->GetTopChannels(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel_size(), 1);
+}
+
+TEST_F(ChannelzServerTest, HighStartId) {
+ ResetStubs();
+ ConfigureProxy(1);
+ GetTopChannelsRequest request;
+ GetTopChannelsResponse response;
+ request.set_start_channel_id(10000);
+ ClientContext context;
+ Status s = channelz_stub_->GetTopChannels(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel_size(), 0);
+}
+
+TEST_F(ChannelzServerTest, SuccessfulRequestTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ SendSuccessfulEcho(0);
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(0));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(), 1);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), 1);
+ EXPECT_EQ(response.channel().data().calls_failed(), 0);
+}
+
+TEST_F(ChannelzServerTest, FailedRequestTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ SendFailedEcho(0);
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(0));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(), 1);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), 0);
+ EXPECT_EQ(response.channel().data().calls_failed(), 1);
+}
+
+TEST_F(ChannelzServerTest, ManyRequestsTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ // send some RPCs
+ const int kNumSuccess = 10;
+ const int kNumFailed = 11;
+ for (int i = 0; i < kNumSuccess; ++i) {
+ SendSuccessfulEcho(0);
+ }
+ for (int i = 0; i < kNumFailed; ++i) {
+ SendFailedEcho(0);
+ }
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(0));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(),
+ kNumSuccess + kNumFailed);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), kNumSuccess);
+ EXPECT_EQ(response.channel().data().calls_failed(), kNumFailed);
+}
+
+TEST_F(ChannelzServerTest, ManyChannels) {
+ ResetStubs();
+ const int kNumChannels = 4;
+ ConfigureProxy(kNumChannels);
+ GetTopChannelsRequest request;
+ GetTopChannelsResponse response;
+ request.set_start_channel_id(0);
+ ClientContext context;
+ Status s = channelz_stub_->GetTopChannels(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel_size(), kNumChannels);
+}
+
+TEST_F(ChannelzServerTest, ManyRequestsManyChannels) {
+ ResetStubs();
+ const int kNumChannels = 4;
+ ConfigureProxy(kNumChannels);
+ const int kNumSuccess = 10;
+ const int kNumFailed = 11;
+ for (int i = 0; i < kNumSuccess; ++i) {
+ SendSuccessfulEcho(0);
+ SendSuccessfulEcho(2);
+ }
+ for (int i = 0; i < kNumFailed; ++i) {
+ SendFailedEcho(1);
+ SendFailedEcho(2);
+ }
+
+ // the first channel saw only successes
+ {
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(0));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(), kNumSuccess);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), kNumSuccess);
+ EXPECT_EQ(response.channel().data().calls_failed(), 0);
+ }
+
+ // the second channel saw only failures
+ {
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(1));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(), kNumFailed);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), 0);
+ EXPECT_EQ(response.channel().data().calls_failed(), kNumFailed);
+ }
+
+ // the third channel saw both
+ {
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(2));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(),
+ kNumSuccess + kNumFailed);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), kNumSuccess);
+ EXPECT_EQ(response.channel().data().calls_failed(), kNumFailed);
+ }
+
+ // the fourth channel saw nothing
+ {
+ GetChannelRequest request;
+ GetChannelResponse response;
+ request.set_channel_id(GetChannelId(3));
+ ClientContext context;
+ Status s = channelz_stub_->GetChannel(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.channel().data().calls_started(), 0);
+ EXPECT_EQ(response.channel().data().calls_succeeded(), 0);
+ EXPECT_EQ(response.channel().data().calls_failed(), 0);
+ }
+}
+
+TEST_F(ChannelzServerTest, ManySubchannels) {
+ ResetStubs();
+ const int kNumChannels = 4;
+ ConfigureProxy(kNumChannels);
+ const int kNumSuccess = 10;
+ const int kNumFailed = 11;
+ for (int i = 0; i < kNumSuccess; ++i) {
+ SendSuccessfulEcho(0);
+ SendSuccessfulEcho(2);
+ }
+ for (int i = 0; i < kNumFailed; ++i) {
+ SendFailedEcho(1);
+ SendFailedEcho(2);
+ }
+ GetTopChannelsRequest gtc_request;
+ GetTopChannelsResponse gtc_response;
+ gtc_request.set_start_channel_id(0);
+ ClientContext context;
+ Status s =
+ channelz_stub_->GetTopChannels(&context, gtc_request, &gtc_response);
+ EXPECT_TRUE(s.ok()) << s.error_message();
+ EXPECT_EQ(gtc_response.channel_size(), kNumChannels);
+ for (int i = 0; i < gtc_response.channel_size(); ++i) {
+ // if the channel sent no RPCs, then expect no subchannels to have been
+ // created.
+ if (gtc_response.channel(i).data().calls_started() == 0) {
+ EXPECT_EQ(gtc_response.channel(i).subchannel_ref_size(), 0);
+ continue;
+ }
+ // The resolver must return at least one address.
+ ASSERT_GT(gtc_response.channel(i).subchannel_ref_size(), 0);
+ GetSubchannelRequest gsc_request;
+ GetSubchannelResponse gsc_response;
+ gsc_request.set_subchannel_id(
+ gtc_response.channel(i).subchannel_ref(0).subchannel_id());
+ ClientContext context;
+ Status s =
+ channelz_stub_->GetSubchannel(&context, gsc_request, &gsc_response);
+ EXPECT_TRUE(s.ok()) << s.error_message();
+ EXPECT_EQ(gtc_response.channel(i).data().calls_started(),
+ gsc_response.subchannel().data().calls_started());
+ EXPECT_EQ(gtc_response.channel(i).data().calls_succeeded(),
+ gsc_response.subchannel().data().calls_succeeded());
+ EXPECT_EQ(gtc_response.channel(i).data().calls_failed(),
+ gsc_response.subchannel().data().calls_failed());
+ }
+}
+
+TEST_F(ChannelzServerTest, BasicServerTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ GetServersRequest request;
+ GetServersResponse response;
+ request.set_start_server_id(0);
+ ClientContext context;
+ Status s = channelz_stub_->GetServers(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.server_size(), 1);
+}
+
+TEST_F(ChannelzServerTest, BasicGetServerTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ GetServersRequest get_servers_request;
+ GetServersResponse get_servers_response;
+ get_servers_request.set_start_server_id(0);
+ ClientContext get_servers_context;
+ Status s = channelz_stub_->GetServers(
+ &get_servers_context, get_servers_request, &get_servers_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_servers_response.server_size(), 1);
+ GetServerRequest get_server_request;
+ GetServerResponse get_server_response;
+ get_server_request.set_server_id(
+ get_servers_response.server(0).ref().server_id());
+ ClientContext get_server_context;
+ s = channelz_stub_->GetServer(&get_server_context, get_server_request,
+ &get_server_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_servers_response.server(0).ref().server_id(),
+ get_server_response.server().ref().server_id());
+}
+
+TEST_F(ChannelzServerTest, ServerCallTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ const int kNumSuccess = 10;
+ const int kNumFailed = 11;
+ for (int i = 0; i < kNumSuccess; ++i) {
+ SendSuccessfulEcho(0);
+ }
+ for (int i = 0; i < kNumFailed; ++i) {
+ SendFailedEcho(0);
+ }
+ GetServersRequest request;
+ GetServersResponse response;
+ request.set_start_server_id(0);
+ ClientContext context;
+ Status s = channelz_stub_->GetServers(&context, request, &response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(response.server_size(), 1);
+ EXPECT_EQ(response.server(0).data().calls_succeeded(), kNumSuccess);
+ EXPECT_EQ(response.server(0).data().calls_failed(), kNumFailed);
+ // This is success+failure+1 because the call that retrieved this information
+ // will be counted as started. It will not track success/failure until after
+ // it has returned, so that is not included in the response.
+ EXPECT_EQ(response.server(0).data().calls_started(),
+ kNumSuccess + kNumFailed + 1);
+}
+
+TEST_F(ChannelzServerTest, ManySubchannelsAndSockets) {
+ ResetStubs();
+ const int kNumChannels = 4;
+ ConfigureProxy(kNumChannels);
+ const int kNumSuccess = 10;
+ const int kNumFailed = 11;
+ for (int i = 0; i < kNumSuccess; ++i) {
+ SendSuccessfulEcho(0);
+ SendSuccessfulEcho(2);
+ }
+ for (int i = 0; i < kNumFailed; ++i) {
+ SendFailedEcho(1);
+ SendFailedEcho(2);
+ }
+ GetTopChannelsRequest gtc_request;
+ GetTopChannelsResponse gtc_response;
+ gtc_request.set_start_channel_id(0);
+ ClientContext context;
+ Status s =
+ channelz_stub_->GetTopChannels(&context, gtc_request, &gtc_response);
+ EXPECT_TRUE(s.ok()) << s.error_message();
+ EXPECT_EQ(gtc_response.channel_size(), kNumChannels);
+ for (int i = 0; i < gtc_response.channel_size(); ++i) {
+ // if the channel sent no RPCs, then expect no subchannels to have been
+ // created.
+ if (gtc_response.channel(i).data().calls_started() == 0) {
+ EXPECT_EQ(gtc_response.channel(i).subchannel_ref_size(), 0);
+ continue;
+ }
+ // The resolver must return at least one address.
+ ASSERT_GT(gtc_response.channel(i).subchannel_ref_size(), 0);
+ // First grab the subchannel
+ GetSubchannelRequest get_subchannel_req;
+ GetSubchannelResponse get_subchannel_resp;
+ get_subchannel_req.set_subchannel_id(
+ gtc_response.channel(i).subchannel_ref(0).subchannel_id());
+ ClientContext get_subchannel_ctx;
+ Status s = channelz_stub_->GetSubchannel(
+ &get_subchannel_ctx, get_subchannel_req, &get_subchannel_resp);
+ EXPECT_TRUE(s.ok()) << s.error_message();
+ EXPECT_EQ(get_subchannel_resp.subchannel().socket_ref_size(), 1);
+ // Now grab the socket.
+ GetSocketRequest get_socket_req;
+ GetSocketResponse get_socket_resp;
+ ClientContext get_socket_ctx;
+ get_socket_req.set_socket_id(
+ get_subchannel_resp.subchannel().socket_ref(0).socket_id());
+ s = channelz_stub_->GetSocket(&get_socket_ctx, get_socket_req,
+ &get_socket_resp);
+ EXPECT_TRUE(
+ get_subchannel_resp.subchannel().socket_ref(0).name().find("http"));
+ EXPECT_TRUE(s.ok()) << s.error_message();
+ // calls started == streams started AND stream succeeded. Since none of
+ // these RPCs were canceled, all of the streams will succeeded even though
+ // the RPCs they represent might have failed.
+ EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_started(),
+ get_socket_resp.socket().data().streams_started());
+ EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_started(),
+ get_socket_resp.socket().data().streams_succeeded());
+ // All of the calls were unary, so calls started == messages sent.
+ EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_started(),
+ get_socket_resp.socket().data().messages_sent());
+ // We only get responses when the RPC was successful, so
+ // calls succeeded == messages received.
+ EXPECT_EQ(get_subchannel_resp.subchannel().data().calls_succeeded(),
+ get_socket_resp.socket().data().messages_received());
+ }
+}
+
+TEST_F(ChannelzServerTest, StreamingRPC) {
+ ResetStubs();
+ ConfigureProxy(1);
+ const int kNumMessages = 5;
+ SendSuccessfulStream(kNumMessages);
+ // Get the channel
+ GetChannelRequest get_channel_request;
+ GetChannelResponse get_channel_response;
+ get_channel_request.set_channel_id(GetChannelId(0));
+ ClientContext get_channel_context;
+ Status s = channelz_stub_->GetChannel(
+ &get_channel_context, get_channel_request, &get_channel_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_channel_response.channel().data().calls_started(), 1);
+ EXPECT_EQ(get_channel_response.channel().data().calls_succeeded(), 1);
+ EXPECT_EQ(get_channel_response.channel().data().calls_failed(), 0);
+ // Get the subchannel
+ ASSERT_GT(get_channel_response.channel().subchannel_ref_size(), 0);
+ GetSubchannelRequest get_subchannel_request;
+ GetSubchannelResponse get_subchannel_response;
+ ClientContext get_subchannel_context;
+ get_subchannel_request.set_subchannel_id(
+ get_channel_response.channel().subchannel_ref(0).subchannel_id());
+ s = channelz_stub_->GetSubchannel(&get_subchannel_context,
+ get_subchannel_request,
+ &get_subchannel_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_subchannel_response.subchannel().data().calls_started(), 1);
+ EXPECT_EQ(get_subchannel_response.subchannel().data().calls_succeeded(), 1);
+ EXPECT_EQ(get_subchannel_response.subchannel().data().calls_failed(), 0);
+ // Get the socket
+ ASSERT_GT(get_subchannel_response.subchannel().socket_ref_size(), 0);
+ GetSocketRequest get_socket_request;
+ GetSocketResponse get_socket_response;
+ ClientContext get_socket_context;
+ get_socket_request.set_socket_id(
+ get_subchannel_response.subchannel().socket_ref(0).socket_id());
+ EXPECT_TRUE(
+ get_subchannel_response.subchannel().socket_ref(0).name().find("http"));
+ s = channelz_stub_->GetSocket(&get_socket_context, get_socket_request,
+ &get_socket_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_socket_response.socket().data().streams_started(), 1);
+ EXPECT_EQ(get_socket_response.socket().data().streams_succeeded(), 1);
+ EXPECT_EQ(get_socket_response.socket().data().streams_failed(), 0);
+ EXPECT_EQ(get_socket_response.socket().data().messages_sent(), kNumMessages);
+ EXPECT_EQ(get_socket_response.socket().data().messages_received(),
+ kNumMessages);
+}
+
+TEST_F(ChannelzServerTest, GetServerSocketsTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ GetServersRequest get_server_request;
+ GetServersResponse get_server_response;
+ get_server_request.set_start_server_id(0);
+ ClientContext get_server_context;
+ Status s = channelz_stub_->GetServers(&get_server_context, get_server_request,
+ &get_server_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_server_response.server_size(), 1);
+ GetServerSocketsRequest get_server_sockets_request;
+ GetServerSocketsResponse get_server_sockets_response;
+ get_server_sockets_request.set_server_id(
+ get_server_response.server(0).ref().server_id());
+ get_server_sockets_request.set_start_socket_id(0);
+ ClientContext get_server_sockets_context;
+ s = channelz_stub_->GetServerSockets(&get_server_sockets_context,
+ get_server_sockets_request,
+ &get_server_sockets_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_server_sockets_response.socket_ref_size(), 1);
+ EXPECT_TRUE(get_server_sockets_response.socket_ref(0).name().find("http"));
+}
+
+TEST_F(ChannelzServerTest, GetServerSocketsPaginationTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ std::vector<std::unique_ptr<grpc::testing::EchoTestService::Stub>> stubs;
+ const int kNumServerSocketsCreated = 20;
+ for (int i = 0; i < kNumServerSocketsCreated; ++i) {
+ stubs.push_back(NewEchoStub());
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello channelz");
+ request.mutable_param()->set_backend_channel_idx(0);
+ ClientContext context;
+ Status s = stubs.back()->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ }
+ GetServersRequest get_server_request;
+ GetServersResponse get_server_response;
+ get_server_request.set_start_server_id(0);
+ ClientContext get_server_context;
+ Status s = channelz_stub_->GetServers(&get_server_context, get_server_request,
+ &get_server_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_server_response.server_size(), 1);
+ // Make a request that gets all of the serversockets
+ {
+ GetServerSocketsRequest get_server_sockets_request;
+ GetServerSocketsResponse get_server_sockets_response;
+ get_server_sockets_request.set_server_id(
+ get_server_response.server(0).ref().server_id());
+ get_server_sockets_request.set_start_socket_id(0);
+ ClientContext get_server_sockets_context;
+ s = channelz_stub_->GetServerSockets(&get_server_sockets_context,
+ get_server_sockets_request,
+ &get_server_sockets_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ // We add one to account the channelz stub that will end up creating
+ // a serversocket.
+ EXPECT_EQ(get_server_sockets_response.socket_ref_size(),
+ kNumServerSocketsCreated + 1);
+ EXPECT_TRUE(get_server_sockets_response.end());
+ }
+ // Now we make a request that exercises pagination.
+ {
+ GetServerSocketsRequest get_server_sockets_request;
+ GetServerSocketsResponse get_server_sockets_response;
+ get_server_sockets_request.set_server_id(
+ get_server_response.server(0).ref().server_id());
+ get_server_sockets_request.set_start_socket_id(0);
+ const int kMaxResults = 10;
+ get_server_sockets_request.set_max_results(kMaxResults);
+ ClientContext get_server_sockets_context;
+ s = channelz_stub_->GetServerSockets(&get_server_sockets_context,
+ get_server_sockets_request,
+ &get_server_sockets_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_server_sockets_response.socket_ref_size(), kMaxResults);
+ EXPECT_FALSE(get_server_sockets_response.end());
+ }
+}
+
+TEST_F(ChannelzServerTest, GetServerListenSocketsTest) {
+ ResetStubs();
+ ConfigureProxy(1);
+ GetServersRequest get_server_request;
+ GetServersResponse get_server_response;
+ get_server_request.set_start_server_id(0);
+ ClientContext get_server_context;
+ Status s = channelz_stub_->GetServers(&get_server_context, get_server_request,
+ &get_server_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+ EXPECT_EQ(get_server_response.server_size(), 1);
+ EXPECT_EQ(get_server_response.server(0).listen_socket_size(), 1);
+ GetSocketRequest get_socket_request;
+ GetSocketResponse get_socket_response;
+ get_socket_request.set_socket_id(
+ get_server_response.server(0).listen_socket(0).socket_id());
+ EXPECT_TRUE(
+ get_server_response.server(0).listen_socket(0).name().find("http"));
+ ClientContext get_socket_context;
+ s = channelz_stub_->GetSocket(&get_socket_context, get_socket_request,
+ &get_socket_response);
+ EXPECT_TRUE(s.ok()) << "s.error_message() = " << s.error_message();
+}
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/client_callback_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/client_callback_end2end_test.cc
index 12cb40a953..53efd793d4 100644
--- a/contrib/libs/grpc/test/cpp/end2end/client_callback_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/client_callback_end2end_test.cc
@@ -1,32 +1,32 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/client_callback.h>
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/generic/generic_stub.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/client_callback.h>
#include <gtest/gtest.h>
-
+
#include <algorithm>
#include <condition_variable>
#include <functional>
@@ -34,330 +34,330 @@
#include <sstream>
#include <thread>
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/interceptors_util.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-#include "test/cpp/util/string_ref_helper.h"
-#include "test/cpp/util/test_credentials_provider.h"
-
-// MAYBE_SKIP_TEST is a macro to determine if this particular test configuration
-// should be skipped based on a decision made at SetUp time. In particular, any
-// callback tests can only be run if the iomgr can run in the background or if
-// the transport is in-process.
-#define MAYBE_SKIP_TEST \
- do { \
- if (do_not_test_) { \
- return; \
- } \
- } while (0)
-
-namespace grpc {
-namespace testing {
-namespace {
-
-enum class Protocol { INPROC, TCP };
-
-class TestScenario {
- public:
- TestScenario(bool serve_callback, Protocol protocol, bool intercept,
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/interceptors_util.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+#include "test/cpp/util/string_ref_helper.h"
+#include "test/cpp/util/test_credentials_provider.h"
+
+// MAYBE_SKIP_TEST is a macro to determine if this particular test configuration
+// should be skipped based on a decision made at SetUp time. In particular, any
+// callback tests can only be run if the iomgr can run in the background or if
+// the transport is in-process.
+#define MAYBE_SKIP_TEST \
+ do { \
+ if (do_not_test_) { \
+ return; \
+ } \
+ } while (0)
+
+namespace grpc {
+namespace testing {
+namespace {
+
+enum class Protocol { INPROC, TCP };
+
+class TestScenario {
+ public:
+ TestScenario(bool serve_callback, Protocol protocol, bool intercept,
const TString& creds_type)
- : callback_server(serve_callback),
- protocol(protocol),
- use_interceptors(intercept),
- credentials_type(creds_type) {}
- void Log() const;
- bool callback_server;
- Protocol protocol;
- bool use_interceptors;
+ : callback_server(serve_callback),
+ protocol(protocol),
+ use_interceptors(intercept),
+ credentials_type(creds_type) {}
+ void Log() const;
+ bool callback_server;
+ Protocol protocol;
+ bool use_interceptors;
const TString credentials_type;
-};
-
-static std::ostream& operator<<(std::ostream& out,
- const TestScenario& scenario) {
- return out << "TestScenario{callback_server="
- << (scenario.callback_server ? "true" : "false") << ",protocol="
- << (scenario.protocol == Protocol::INPROC ? "INPROC" : "TCP")
- << ",intercept=" << (scenario.use_interceptors ? "true" : "false")
- << ",creds=" << scenario.credentials_type << "}";
-}
-
-void TestScenario::Log() const {
- std::ostringstream out;
- out << *this;
- gpr_log(GPR_DEBUG, "%s", out.str().c_str());
-}
-
-class ClientCallbackEnd2endTest
- : public ::testing::TestWithParam<TestScenario> {
- protected:
- ClientCallbackEnd2endTest() { GetParam().Log(); }
-
- void SetUp() override {
- ServerBuilder builder;
-
- auto server_creds = GetCredentialsProvider()->GetServerCredentials(
- GetParam().credentials_type);
- // TODO(vjpai): Support testing of AuthMetadataProcessor
-
- if (GetParam().protocol == Protocol::TCP) {
- picked_port_ = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << picked_port_;
- builder.AddListeningPort(server_address_.str(), server_creds);
- }
- if (!GetParam().callback_server) {
- builder.RegisterService(&service_);
- } else {
- builder.RegisterService(&callback_service_);
- }
-
- if (GetParam().use_interceptors) {
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy server interceptors
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- }
-
- server_ = builder.BuildAndStart();
- is_server_started_ = true;
- if (GetParam().protocol == Protocol::TCP &&
- !grpc_iomgr_run_in_background()) {
- do_not_test_ = true;
- }
- }
-
- void ResetStub() {
- ChannelArguments args;
- auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
- GetParam().credentials_type, &args);
- switch (GetParam().protocol) {
- case Protocol::TCP:
- if (!GetParam().use_interceptors) {
- channel_ = ::grpc::CreateCustomChannel(server_address_.str(),
- channel_creds, args);
- } else {
- channel_ = CreateCustomChannelWithInterceptors(
- server_address_.str(), channel_creds, args,
- CreateDummyClientInterceptors());
- }
- break;
- case Protocol::INPROC:
- if (!GetParam().use_interceptors) {
- channel_ = server_->InProcessChannel(args);
- } else {
- channel_ = server_->experimental().InProcessChannelWithInterceptors(
- args, CreateDummyClientInterceptors());
- }
- break;
- default:
- assert(false);
- }
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- generic_stub_.reset(new GenericStub(channel_));
- DummyInterceptor::Reset();
- }
-
- void TearDown() override {
- if (is_server_started_) {
- // Although we would normally do an explicit shutdown, the server
- // should also work correctly with just a destructor call. The regular
- // end2end test uses explicit shutdown, so let this one just do reset.
- server_.reset();
- }
- if (picked_port_ > 0) {
- grpc_recycle_unused_port(picked_port_);
- }
- }
-
- void SendRpcs(int num_rpcs, bool with_binary_metadata) {
+};
+
+static std::ostream& operator<<(std::ostream& out,
+ const TestScenario& scenario) {
+ return out << "TestScenario{callback_server="
+ << (scenario.callback_server ? "true" : "false") << ",protocol="
+ << (scenario.protocol == Protocol::INPROC ? "INPROC" : "TCP")
+ << ",intercept=" << (scenario.use_interceptors ? "true" : "false")
+ << ",creds=" << scenario.credentials_type << "}";
+}
+
+void TestScenario::Log() const {
+ std::ostringstream out;
+ out << *this;
+ gpr_log(GPR_DEBUG, "%s", out.str().c_str());
+}
+
+class ClientCallbackEnd2endTest
+ : public ::testing::TestWithParam<TestScenario> {
+ protected:
+ ClientCallbackEnd2endTest() { GetParam().Log(); }
+
+ void SetUp() override {
+ ServerBuilder builder;
+
+ auto server_creds = GetCredentialsProvider()->GetServerCredentials(
+ GetParam().credentials_type);
+ // TODO(vjpai): Support testing of AuthMetadataProcessor
+
+ if (GetParam().protocol == Protocol::TCP) {
+ picked_port_ = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << picked_port_;
+ builder.AddListeningPort(server_address_.str(), server_creds);
+ }
+ if (!GetParam().callback_server) {
+ builder.RegisterService(&service_);
+ } else {
+ builder.RegisterService(&callback_service_);
+ }
+
+ if (GetParam().use_interceptors) {
+ std::vector<
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy server interceptors
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ }
+
+ server_ = builder.BuildAndStart();
+ is_server_started_ = true;
+ if (GetParam().protocol == Protocol::TCP &&
+ !grpc_iomgr_run_in_background()) {
+ do_not_test_ = true;
+ }
+ }
+
+ void ResetStub() {
+ ChannelArguments args;
+ auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
+ GetParam().credentials_type, &args);
+ switch (GetParam().protocol) {
+ case Protocol::TCP:
+ if (!GetParam().use_interceptors) {
+ channel_ = ::grpc::CreateCustomChannel(server_address_.str(),
+ channel_creds, args);
+ } else {
+ channel_ = CreateCustomChannelWithInterceptors(
+ server_address_.str(), channel_creds, args,
+ CreateDummyClientInterceptors());
+ }
+ break;
+ case Protocol::INPROC:
+ if (!GetParam().use_interceptors) {
+ channel_ = server_->InProcessChannel(args);
+ } else {
+ channel_ = server_->experimental().InProcessChannelWithInterceptors(
+ args, CreateDummyClientInterceptors());
+ }
+ break;
+ default:
+ assert(false);
+ }
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ generic_stub_.reset(new GenericStub(channel_));
+ DummyInterceptor::Reset();
+ }
+
+ void TearDown() override {
+ if (is_server_started_) {
+ // Although we would normally do an explicit shutdown, the server
+ // should also work correctly with just a destructor call. The regular
+ // end2end test uses explicit shutdown, so let this one just do reset.
+ server_.reset();
+ }
+ if (picked_port_ > 0) {
+ grpc_recycle_unused_port(picked_port_);
+ }
+ }
+
+ void SendRpcs(int num_rpcs, bool with_binary_metadata) {
TString test_string("");
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest request;
- EchoResponse response;
- ClientContext cli_ctx;
-
- test_string += "Hello world. ";
- request.set_message(test_string);
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext cli_ctx;
+
+ test_string += "Hello world. ";
+ request.set_message(test_string);
TString val;
- if (with_binary_metadata) {
- request.mutable_param()->set_echo_metadata(true);
- char bytes[8] = {'\0', '\1', '\2', '\3',
- '\4', '\5', '\6', static_cast<char>(i)};
+ if (with_binary_metadata) {
+ request.mutable_param()->set_echo_metadata(true);
+ char bytes[8] = {'\0', '\1', '\2', '\3',
+ '\4', '\5', '\6', static_cast<char>(i)};
val = TString(bytes, 8);
- cli_ctx.AddMetadata("custom-bin", val);
- }
-
- cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
-
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- stub_->experimental_async()->Echo(
- &cli_ctx, &request, &response,
- [&cli_ctx, &request, &response, &done, &mu, &cv, val,
- with_binary_metadata](Status s) {
- GPR_ASSERT(s.ok());
-
- EXPECT_EQ(request.message(), response.message());
- if (with_binary_metadata) {
- EXPECT_EQ(
- 1u, cli_ctx.GetServerTrailingMetadata().count("custom-bin"));
- EXPECT_EQ(val, ToString(cli_ctx.GetServerTrailingMetadata()
- .find("custom-bin")
- ->second));
- }
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
- }
- }
-
- void SendRpcsGeneric(int num_rpcs, bool maybe_except) {
+ cli_ctx.AddMetadata("custom-bin", val);
+ }
+
+ cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
+
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ stub_->experimental_async()->Echo(
+ &cli_ctx, &request, &response,
+ [&cli_ctx, &request, &response, &done, &mu, &cv, val,
+ with_binary_metadata](Status s) {
+ GPR_ASSERT(s.ok());
+
+ EXPECT_EQ(request.message(), response.message());
+ if (with_binary_metadata) {
+ EXPECT_EQ(
+ 1u, cli_ctx.GetServerTrailingMetadata().count("custom-bin"));
+ EXPECT_EQ(val, ToString(cli_ctx.GetServerTrailingMetadata()
+ .find("custom-bin")
+ ->second));
+ }
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+ }
+ }
+
+ void SendRpcsGeneric(int num_rpcs, bool maybe_except) {
const TString kMethodName("/grpc.testing.EchoTestService/Echo");
TString test_string("");
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest request;
- std::unique_ptr<ByteBuffer> send_buf;
- ByteBuffer recv_buf;
- ClientContext cli_ctx;
-
- test_string += "Hello world. ";
- request.set_message(test_string);
- send_buf = SerializeToByteBuffer(&request);
-
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- generic_stub_->experimental().UnaryCall(
- &cli_ctx, kMethodName, send_buf.get(), &recv_buf,
- [&request, &recv_buf, &done, &mu, &cv, maybe_except](Status s) {
- GPR_ASSERT(s.ok());
-
- EchoResponse response;
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buf, &response));
- EXPECT_EQ(request.message(), response.message());
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
-#if GRPC_ALLOW_EXCEPTIONS
- if (maybe_except) {
- throw - 1;
- }
-#else
- GPR_ASSERT(!maybe_except);
-#endif
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
- }
- }
-
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest request;
+ std::unique_ptr<ByteBuffer> send_buf;
+ ByteBuffer recv_buf;
+ ClientContext cli_ctx;
+
+ test_string += "Hello world. ";
+ request.set_message(test_string);
+ send_buf = SerializeToByteBuffer(&request);
+
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ generic_stub_->experimental().UnaryCall(
+ &cli_ctx, kMethodName, send_buf.get(), &recv_buf,
+ [&request, &recv_buf, &done, &mu, &cv, maybe_except](Status s) {
+ GPR_ASSERT(s.ok());
+
+ EchoResponse response;
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buf, &response));
+ EXPECT_EQ(request.message(), response.message());
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+#if GRPC_ALLOW_EXCEPTIONS
+ if (maybe_except) {
+ throw - 1;
+ }
+#else
+ GPR_ASSERT(!maybe_except);
+#endif
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+ }
+ }
+
void SendGenericEchoAsBidi(int num_rpcs, int reuses, bool do_writes_done) {
const TString kMethodName("/grpc.testing.EchoTestService/Echo");
TString test_string("");
- for (int i = 0; i < num_rpcs; i++) {
- test_string += "Hello world. ";
- class Client : public grpc::experimental::ClientBidiReactor<ByteBuffer,
- ByteBuffer> {
- public:
+ for (int i = 0; i < num_rpcs; i++) {
+ test_string += "Hello world. ";
+ class Client : public grpc::experimental::ClientBidiReactor<ByteBuffer,
+ ByteBuffer> {
+ public:
Client(ClientCallbackEnd2endTest* test, const TString& method_name,
const TString& test_str, int reuses, bool do_writes_done)
: reuses_remaining_(reuses), do_writes_done_(do_writes_done) {
- activate_ = [this, test, method_name, test_str] {
- if (reuses_remaining_ > 0) {
- cli_ctx_.reset(new ClientContext);
- reuses_remaining_--;
- test->generic_stub_->experimental().PrepareBidiStreamingCall(
- cli_ctx_.get(), method_name, this);
- request_.set_message(test_str);
- send_buf_ = SerializeToByteBuffer(&request_);
- StartWrite(send_buf_.get());
- StartRead(&recv_buf_);
- StartCall();
- } else {
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- cv_.notify_one();
- }
- };
- activate_();
- }
+ activate_ = [this, test, method_name, test_str] {
+ if (reuses_remaining_ > 0) {
+ cli_ctx_.reset(new ClientContext);
+ reuses_remaining_--;
+ test->generic_stub_->experimental().PrepareBidiStreamingCall(
+ cli_ctx_.get(), method_name, this);
+ request_.set_message(test_str);
+ send_buf_ = SerializeToByteBuffer(&request_);
+ StartWrite(send_buf_.get());
+ StartRead(&recv_buf_);
+ StartCall();
+ } else {
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ cv_.notify_one();
+ }
+ };
+ activate_();
+ }
void OnWriteDone(bool /*ok*/) override {
if (do_writes_done_) {
StartWritesDone();
}
}
- void OnReadDone(bool /*ok*/) override {
- EchoResponse response;
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buf_, &response));
- EXPECT_EQ(request_.message(), response.message());
- };
- void OnDone(const Status& s) override {
- EXPECT_TRUE(s.ok());
- activate_();
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- cv_.wait(l);
- }
- }
-
- EchoRequest request_;
- std::unique_ptr<ByteBuffer> send_buf_;
- ByteBuffer recv_buf_;
- std::unique_ptr<ClientContext> cli_ctx_;
- int reuses_remaining_;
- std::function<void()> activate_;
- std::mutex mu_;
- std::condition_variable cv_;
- bool done_ = false;
+ void OnReadDone(bool /*ok*/) override {
+ EchoResponse response;
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buf_, &response));
+ EXPECT_EQ(request_.message(), response.message());
+ };
+ void OnDone(const Status& s) override {
+ EXPECT_TRUE(s.ok());
+ activate_();
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ cv_.wait(l);
+ }
+ }
+
+ EchoRequest request_;
+ std::unique_ptr<ByteBuffer> send_buf_;
+ ByteBuffer recv_buf_;
+ std::unique_ptr<ClientContext> cli_ctx_;
+ int reuses_remaining_;
+ std::function<void()> activate_;
+ std::mutex mu_;
+ std::condition_variable cv_;
+ bool done_ = false;
const bool do_writes_done_;
};
-
+
Client rpc(this, kMethodName, test_string, reuses, do_writes_done);
- rpc.Await();
- }
- }
- bool do_not_test_{false};
- bool is_server_started_{false};
- int picked_port_{0};
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<grpc::GenericStub> generic_stub_;
- TestServiceImpl service_;
- CallbackTestServiceImpl callback_service_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
-};
-
-TEST_P(ClientCallbackEnd2endTest, SimpleRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpcs(1, false);
-}
-
+ rpc.Await();
+ }
+ }
+ bool do_not_test_{false};
+ bool is_server_started_{false};
+ int picked_port_{0};
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<grpc::GenericStub> generic_stub_;
+ TestServiceImpl service_;
+ CallbackTestServiceImpl callback_service_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+};
+
+TEST_P(ClientCallbackEnd2endTest, SimpleRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpcs(1, false);
+}
+
TEST_P(ClientCallbackEnd2endTest, SimpleRpcExpectedError) {
- MAYBE_SKIP_TEST;
- ResetStub();
+ MAYBE_SKIP_TEST;
+ ResetStub();
EchoRequest request;
EchoResponse response;
@@ -370,9 +370,9 @@ TEST_P(ClientCallbackEnd2endTest, SimpleRpcExpectedError) {
*request.mutable_param()->mutable_expected_error() = error_status;
std::mutex mu;
- std::condition_variable cv;
- bool done = false;
-
+ std::condition_variable cv;
+ bool done = false;
+
stub_->experimental_async()->Echo(
&cli_ctx, &request, &response,
[&response, &done, &mu, &cv, &error_status](Status s) {
@@ -385,11 +385,11 @@ TEST_P(ClientCallbackEnd2endTest, SimpleRpcExpectedError) {
});
std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
+ while (!done) {
+ cv.wait(l);
+ }
+}
+
TEST_P(ClientCallbackEnd2endTest, SimpleRpcUnderLockNested) {
MAYBE_SKIP_TEST;
ResetStub();
@@ -451,415 +451,415 @@ TEST_P(ClientCallbackEnd2endTest, SimpleRpcUnderLockNested) {
}
}
-TEST_P(ClientCallbackEnd2endTest, SimpleRpcUnderLock) {
- MAYBE_SKIP_TEST;
- ResetStub();
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- EchoRequest request;
- request.set_message("Hello locked world.");
- EchoResponse response;
- ClientContext cli_ctx;
- {
- std::lock_guard<std::mutex> l(mu);
- stub_->experimental_async()->Echo(
- &cli_ctx, &request, &response,
- [&mu, &cv, &done, &request, &response](Status s) {
- std::lock_guard<std::mutex> l(mu);
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(request.message(), response.message());
- done = true;
- cv.notify_one();
- });
- }
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, SequentialRpcs) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpcs(10, false);
-}
-
-TEST_P(ClientCallbackEnd2endTest, SendClientInitialMetadata) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SimpleRequest request;
- SimpleResponse response;
- ClientContext cli_ctx;
-
- cli_ctx.AddMetadata(kCheckClientInitialMetadataKey,
- kCheckClientInitialMetadataVal);
-
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- stub_->experimental_async()->CheckClientInitialMetadata(
- &cli_ctx, &request, &response, [&done, &mu, &cv](Status s) {
- GPR_ASSERT(s.ok());
-
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, SimpleRpcWithBinaryMetadata) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpcs(1, true);
-}
-
-TEST_P(ClientCallbackEnd2endTest, SequentialRpcsWithVariedBinaryMetadataValue) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpcs(10, true);
-}
-
-TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcs) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpcsGeneric(10, false);
-}
-
-TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidi) {
- MAYBE_SKIP_TEST;
- ResetStub();
+TEST_P(ClientCallbackEnd2endTest, SimpleRpcUnderLock) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ EchoRequest request;
+ request.set_message("Hello locked world.");
+ EchoResponse response;
+ ClientContext cli_ctx;
+ {
+ std::lock_guard<std::mutex> l(mu);
+ stub_->experimental_async()->Echo(
+ &cli_ctx, &request, &response,
+ [&mu, &cv, &done, &request, &response](Status s) {
+ std::lock_guard<std::mutex> l(mu);
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(request.message(), response.message());
+ done = true;
+ cv.notify_one();
+ });
+ }
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, SequentialRpcs) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpcs(10, false);
+}
+
+TEST_P(ClientCallbackEnd2endTest, SendClientInitialMetadata) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SimpleRequest request;
+ SimpleResponse response;
+ ClientContext cli_ctx;
+
+ cli_ctx.AddMetadata(kCheckClientInitialMetadataKey,
+ kCheckClientInitialMetadataVal);
+
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ stub_->experimental_async()->CheckClientInitialMetadata(
+ &cli_ctx, &request, &response, [&done, &mu, &cv](Status s) {
+ GPR_ASSERT(s.ok());
+
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, SimpleRpcWithBinaryMetadata) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpcs(1, true);
+}
+
+TEST_P(ClientCallbackEnd2endTest, SequentialRpcsWithVariedBinaryMetadataValue) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpcs(10, true);
+}
+
+TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcs) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpcsGeneric(10, false);
+}
+
+TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidi) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
SendGenericEchoAsBidi(10, 1, /*do_writes_done=*/true);
-}
-
-TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidiWithReactorReuse) {
- MAYBE_SKIP_TEST;
- ResetStub();
+}
+
+TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidiWithReactorReuse) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
SendGenericEchoAsBidi(10, 10, /*do_writes_done=*/true);
-}
-
+}
+
TEST_P(ClientCallbackEnd2endTest, GenericRpcNoWritesDone) {
MAYBE_SKIP_TEST;
ResetStub();
SendGenericEchoAsBidi(1, 1, /*do_writes_done=*/false);
}
-#if GRPC_ALLOW_EXCEPTIONS
-TEST_P(ClientCallbackEnd2endTest, ExceptingRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpcsGeneric(10, true);
-}
-#endif
-
-TEST_P(ClientCallbackEnd2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
- MAYBE_SKIP_TEST;
- ResetStub();
- std::vector<std::thread> threads;
- threads.reserve(10);
- for (int i = 0; i < 10; ++i) {
- threads.emplace_back([this] { SendRpcs(10, true); });
- }
- for (int i = 0; i < 10; ++i) {
- threads[i].join();
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, MultipleRpcs) {
- MAYBE_SKIP_TEST;
- ResetStub();
- std::vector<std::thread> threads;
- threads.reserve(10);
- for (int i = 0; i < 10; ++i) {
- threads.emplace_back([this] { SendRpcs(10, false); });
- }
- for (int i = 0; i < 10; ++i) {
- threads[i].join();
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, CancelRpcBeforeStart) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
- context.TryCancel();
-
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- stub_->experimental_async()->Echo(
- &context, &request, &response, [&response, &done, &mu, &cv](Status s) {
- EXPECT_EQ("", response.message());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, RequestEchoServerCancel) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
- context.AddMetadata(kServerTryCancelRequest,
+#if GRPC_ALLOW_EXCEPTIONS
+TEST_P(ClientCallbackEnd2endTest, ExceptingRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpcsGeneric(10, true);
+}
+#endif
+
+TEST_P(ClientCallbackEnd2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ std::vector<std::thread> threads;
+ threads.reserve(10);
+ for (int i = 0; i < 10; ++i) {
+ threads.emplace_back([this] { SendRpcs(10, true); });
+ }
+ for (int i = 0; i < 10; ++i) {
+ threads[i].join();
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, MultipleRpcs) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ std::vector<std::thread> threads;
+ threads.reserve(10);
+ for (int i = 0; i < 10; ++i) {
+ threads.emplace_back([this] { SendRpcs(10, false); });
+ }
+ for (int i = 0; i < 10; ++i) {
+ threads[i].join();
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, CancelRpcBeforeStart) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+ context.TryCancel();
+
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ stub_->experimental_async()->Echo(
+ &context, &request, &response, [&response, &done, &mu, &cv](Status s) {
+ EXPECT_EQ("", response.message());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, RequestEchoServerCancel) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+ context.AddMetadata(kServerTryCancelRequest,
ToString(CANCEL_BEFORE_PROCESSING));
-
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- stub_->experimental_async()->Echo(
- &context, &request, &response, [&done, &mu, &cv](Status s) {
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-struct ClientCancelInfo {
- bool cancel{false};
- int ops_before_cancel;
-
- ClientCancelInfo() : cancel{false} {}
- explicit ClientCancelInfo(int ops) : cancel{true}, ops_before_cancel{ops} {}
-};
-
-class WriteClient : public grpc::experimental::ClientWriteReactor<EchoRequest> {
- public:
- WriteClient(grpc::testing::EchoTestService::Stub* stub,
- ServerTryCancelRequestPhase server_try_cancel,
- int num_msgs_to_send, ClientCancelInfo client_cancel = {})
- : server_try_cancel_(server_try_cancel),
- num_msgs_to_send_(num_msgs_to_send),
- client_cancel_{client_cancel} {
+
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ stub_->experimental_async()->Echo(
+ &context, &request, &response, [&done, &mu, &cv](Status s) {
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+}
+
+struct ClientCancelInfo {
+ bool cancel{false};
+ int ops_before_cancel;
+
+ ClientCancelInfo() : cancel{false} {}
+ explicit ClientCancelInfo(int ops) : cancel{true}, ops_before_cancel{ops} {}
+};
+
+class WriteClient : public grpc::experimental::ClientWriteReactor<EchoRequest> {
+ public:
+ WriteClient(grpc::testing::EchoTestService::Stub* stub,
+ ServerTryCancelRequestPhase server_try_cancel,
+ int num_msgs_to_send, ClientCancelInfo client_cancel = {})
+ : server_try_cancel_(server_try_cancel),
+ num_msgs_to_send_(num_msgs_to_send),
+ client_cancel_{client_cancel} {
TString msg{"Hello server."};
- for (int i = 0; i < num_msgs_to_send; i++) {
- desired_ += msg;
- }
- if (server_try_cancel != DO_NOT_CANCEL) {
- // Send server_try_cancel value in the client metadata
- context_.AddMetadata(kServerTryCancelRequest,
+ for (int i = 0; i < num_msgs_to_send; i++) {
+ desired_ += msg;
+ }
+ if (server_try_cancel != DO_NOT_CANCEL) {
+ // Send server_try_cancel value in the client metadata
+ context_.AddMetadata(kServerTryCancelRequest,
ToString(server_try_cancel));
- }
- context_.set_initial_metadata_corked(true);
- stub->experimental_async()->RequestStream(&context_, &response_, this);
- StartCall();
- request_.set_message(msg);
- MaybeWrite();
- }
- void OnWriteDone(bool ok) override {
- if (ok) {
- num_msgs_sent_++;
- MaybeWrite();
- }
- }
- void OnDone(const Status& s) override {
- gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent_);
- int num_to_send =
- (client_cancel_.cancel)
- ? std::min(num_msgs_to_send_, client_cancel_.ops_before_cancel)
- : num_msgs_to_send_;
- switch (server_try_cancel_) {
- case CANCEL_BEFORE_PROCESSING:
- case CANCEL_DURING_PROCESSING:
- // If the RPC is canceled by server before / during messages from the
- // client, it means that the client most likely did not get a chance to
- // send all the messages it wanted to send. i.e num_msgs_sent <=
- // num_msgs_to_send
- EXPECT_LE(num_msgs_sent_, num_to_send);
- break;
- case DO_NOT_CANCEL:
- case CANCEL_AFTER_PROCESSING:
- // If the RPC was not canceled or canceled after all messages were read
- // by the server, the client did get a chance to send all its messages
- EXPECT_EQ(num_msgs_sent_, num_to_send);
- break;
- default:
- assert(false);
- break;
- }
- if ((server_try_cancel_ == DO_NOT_CANCEL) && !client_cancel_.cancel) {
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(response_.message(), desired_);
- } else {
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- }
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- cv_.notify_one();
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- cv_.wait(l);
- }
- }
-
- private:
- void MaybeWrite() {
- if (client_cancel_.cancel &&
- num_msgs_sent_ == client_cancel_.ops_before_cancel) {
- context_.TryCancel();
- } else if (num_msgs_to_send_ > num_msgs_sent_ + 1) {
- StartWrite(&request_);
- } else if (num_msgs_to_send_ == num_msgs_sent_ + 1) {
- StartWriteLast(&request_, WriteOptions());
- }
- }
- EchoRequest request_;
- EchoResponse response_;
- ClientContext context_;
- const ServerTryCancelRequestPhase server_try_cancel_;
- int num_msgs_sent_{0};
- const int num_msgs_to_send_;
+ }
+ context_.set_initial_metadata_corked(true);
+ stub->experimental_async()->RequestStream(&context_, &response_, this);
+ StartCall();
+ request_.set_message(msg);
+ MaybeWrite();
+ }
+ void OnWriteDone(bool ok) override {
+ if (ok) {
+ num_msgs_sent_++;
+ MaybeWrite();
+ }
+ }
+ void OnDone(const Status& s) override {
+ gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent_);
+ int num_to_send =
+ (client_cancel_.cancel)
+ ? std::min(num_msgs_to_send_, client_cancel_.ops_before_cancel)
+ : num_msgs_to_send_;
+ switch (server_try_cancel_) {
+ case CANCEL_BEFORE_PROCESSING:
+ case CANCEL_DURING_PROCESSING:
+ // If the RPC is canceled by server before / during messages from the
+ // client, it means that the client most likely did not get a chance to
+ // send all the messages it wanted to send. i.e num_msgs_sent <=
+ // num_msgs_to_send
+ EXPECT_LE(num_msgs_sent_, num_to_send);
+ break;
+ case DO_NOT_CANCEL:
+ case CANCEL_AFTER_PROCESSING:
+ // If the RPC was not canceled or canceled after all messages were read
+ // by the server, the client did get a chance to send all its messages
+ EXPECT_EQ(num_msgs_sent_, num_to_send);
+ break;
+ default:
+ assert(false);
+ break;
+ }
+ if ((server_try_cancel_ == DO_NOT_CANCEL) && !client_cancel_.cancel) {
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(response_.message(), desired_);
+ } else {
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ }
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ cv_.notify_one();
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ cv_.wait(l);
+ }
+ }
+
+ private:
+ void MaybeWrite() {
+ if (client_cancel_.cancel &&
+ num_msgs_sent_ == client_cancel_.ops_before_cancel) {
+ context_.TryCancel();
+ } else if (num_msgs_to_send_ > num_msgs_sent_ + 1) {
+ StartWrite(&request_);
+ } else if (num_msgs_to_send_ == num_msgs_sent_ + 1) {
+ StartWriteLast(&request_, WriteOptions());
+ }
+ }
+ EchoRequest request_;
+ EchoResponse response_;
+ ClientContext context_;
+ const ServerTryCancelRequestPhase server_try_cancel_;
+ int num_msgs_sent_{0};
+ const int num_msgs_to_send_;
TString desired_;
- const ClientCancelInfo client_cancel_;
- std::mutex mu_;
- std::condition_variable cv_;
- bool done_ = false;
-};
-
-TEST_P(ClientCallbackEnd2endTest, RequestStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- WriteClient test{stub_.get(), DO_NOT_CANCEL, 3};
- test.Await();
- // Make sure that the server interceptors were not notified to cancel
- if (GetParam().use_interceptors) {
- EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, ClientCancelsRequestStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- WriteClient test{stub_.get(), DO_NOT_CANCEL, 3, ClientCancelInfo{2}};
- test.Await();
- // Make sure that the server interceptors got the cancel
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel before doing reading the request
-TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelBeforeReads) {
- MAYBE_SKIP_TEST;
- ResetStub();
- WriteClient test{stub_.get(), CANCEL_BEFORE_PROCESSING, 1};
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel while reading a request from the stream in parallel
-TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelDuringRead) {
- MAYBE_SKIP_TEST;
- ResetStub();
- WriteClient test{stub_.get(), CANCEL_DURING_PROCESSING, 10};
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel after reading all the requests but before returning to the
-// client
-TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelAfterReads) {
- MAYBE_SKIP_TEST;
- ResetStub();
- WriteClient test{stub_.get(), CANCEL_AFTER_PROCESSING, 4};
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, UnaryReactor) {
- MAYBE_SKIP_TEST;
- ResetStub();
- class UnaryClient : public grpc::experimental::ClientUnaryReactor {
- public:
- UnaryClient(grpc::testing::EchoTestService::Stub* stub) {
- cli_ctx_.AddMetadata("key1", "val1");
- cli_ctx_.AddMetadata("key2", "val2");
- request_.mutable_param()->set_echo_metadata_initially(true);
- request_.set_message("Hello metadata");
- stub->experimental_async()->Echo(&cli_ctx_, &request_, &response_, this);
- StartCall();
- }
- void OnReadInitialMetadataDone(bool ok) override {
- EXPECT_TRUE(ok);
- EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key1"));
- EXPECT_EQ(
- "val1",
- ToString(cli_ctx_.GetServerInitialMetadata().find("key1")->second));
- EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key2"));
- EXPECT_EQ(
- "val2",
- ToString(cli_ctx_.GetServerInitialMetadata().find("key2")->second));
- initial_metadata_done_ = true;
- }
- void OnDone(const Status& s) override {
- EXPECT_TRUE(initial_metadata_done_);
- EXPECT_EQ(0u, cli_ctx_.GetServerTrailingMetadata().size());
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(request_.message(), response_.message());
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- cv_.notify_one();
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- cv_.wait(l);
- }
- }
-
- private:
- EchoRequest request_;
- EchoResponse response_;
- ClientContext cli_ctx_;
- std::mutex mu_;
- std::condition_variable cv_;
- bool done_{false};
- bool initial_metadata_done_{false};
- };
-
- UnaryClient test{stub_.get()};
- test.Await();
- // Make sure that the server interceptors were not notified of a cancel
- if (GetParam().use_interceptors) {
- EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
+ const ClientCancelInfo client_cancel_;
+ std::mutex mu_;
+ std::condition_variable cv_;
+ bool done_ = false;
+};
+
+TEST_P(ClientCallbackEnd2endTest, RequestStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ WriteClient test{stub_.get(), DO_NOT_CANCEL, 3};
+ test.Await();
+ // Make sure that the server interceptors were not notified to cancel
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, ClientCancelsRequestStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ WriteClient test{stub_.get(), DO_NOT_CANCEL, 3, ClientCancelInfo{2}};
+ test.Await();
+ // Make sure that the server interceptors got the cancel
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel before doing reading the request
+TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelBeforeReads) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ WriteClient test{stub_.get(), CANCEL_BEFORE_PROCESSING, 1};
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel while reading a request from the stream in parallel
+TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelDuringRead) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ WriteClient test{stub_.get(), CANCEL_DURING_PROCESSING, 10};
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel after reading all the requests but before returning to the
+// client
+TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelAfterReads) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ WriteClient test{stub_.get(), CANCEL_AFTER_PROCESSING, 4};
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, UnaryReactor) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ class UnaryClient : public grpc::experimental::ClientUnaryReactor {
+ public:
+ UnaryClient(grpc::testing::EchoTestService::Stub* stub) {
+ cli_ctx_.AddMetadata("key1", "val1");
+ cli_ctx_.AddMetadata("key2", "val2");
+ request_.mutable_param()->set_echo_metadata_initially(true);
+ request_.set_message("Hello metadata");
+ stub->experimental_async()->Echo(&cli_ctx_, &request_, &response_, this);
+ StartCall();
+ }
+ void OnReadInitialMetadataDone(bool ok) override {
+ EXPECT_TRUE(ok);
+ EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key1"));
+ EXPECT_EQ(
+ "val1",
+ ToString(cli_ctx_.GetServerInitialMetadata().find("key1")->second));
+ EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key2"));
+ EXPECT_EQ(
+ "val2",
+ ToString(cli_ctx_.GetServerInitialMetadata().find("key2")->second));
+ initial_metadata_done_ = true;
+ }
+ void OnDone(const Status& s) override {
+ EXPECT_TRUE(initial_metadata_done_);
+ EXPECT_EQ(0u, cli_ctx_.GetServerTrailingMetadata().size());
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(request_.message(), response_.message());
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ cv_.notify_one();
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ cv_.wait(l);
+ }
+ }
+
+ private:
+ EchoRequest request_;
+ EchoResponse response_;
+ ClientContext cli_ctx_;
+ std::mutex mu_;
+ std::condition_variable cv_;
+ bool done_{false};
+ bool initial_metadata_done_{false};
+ };
+
+ UnaryClient test{stub_.get()};
+ test.Await();
+ // Make sure that the server interceptors were not notified of a cancel
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
TEST_P(ClientCallbackEnd2endTest, GenericUnaryReactor) {
MAYBE_SKIP_TEST;
ResetStub();
@@ -926,270 +926,270 @@ TEST_P(ClientCallbackEnd2endTest, GenericUnaryReactor) {
}
}
-class ReadClient : public grpc::experimental::ClientReadReactor<EchoResponse> {
- public:
- ReadClient(grpc::testing::EchoTestService::Stub* stub,
- ServerTryCancelRequestPhase server_try_cancel,
- ClientCancelInfo client_cancel = {})
- : server_try_cancel_(server_try_cancel), client_cancel_{client_cancel} {
- if (server_try_cancel_ != DO_NOT_CANCEL) {
- // Send server_try_cancel value in the client metadata
- context_.AddMetadata(kServerTryCancelRequest,
+class ReadClient : public grpc::experimental::ClientReadReactor<EchoResponse> {
+ public:
+ ReadClient(grpc::testing::EchoTestService::Stub* stub,
+ ServerTryCancelRequestPhase server_try_cancel,
+ ClientCancelInfo client_cancel = {})
+ : server_try_cancel_(server_try_cancel), client_cancel_{client_cancel} {
+ if (server_try_cancel_ != DO_NOT_CANCEL) {
+ // Send server_try_cancel value in the client metadata
+ context_.AddMetadata(kServerTryCancelRequest,
ToString(server_try_cancel));
- }
- request_.set_message("Hello client ");
- stub->experimental_async()->ResponseStream(&context_, &request_, this);
- if (client_cancel_.cancel &&
- reads_complete_ == client_cancel_.ops_before_cancel) {
- context_.TryCancel();
- }
- // Even if we cancel, read until failure because there might be responses
- // pending
- StartRead(&response_);
- StartCall();
- }
- void OnReadDone(bool ok) override {
- if (!ok) {
- if (server_try_cancel_ == DO_NOT_CANCEL && !client_cancel_.cancel) {
- EXPECT_EQ(reads_complete_, kServerDefaultResponseStreamsToSend);
- }
- } else {
- EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
- EXPECT_EQ(response_.message(),
+ }
+ request_.set_message("Hello client ");
+ stub->experimental_async()->ResponseStream(&context_, &request_, this);
+ if (client_cancel_.cancel &&
+ reads_complete_ == client_cancel_.ops_before_cancel) {
+ context_.TryCancel();
+ }
+ // Even if we cancel, read until failure because there might be responses
+ // pending
+ StartRead(&response_);
+ StartCall();
+ }
+ void OnReadDone(bool ok) override {
+ if (!ok) {
+ if (server_try_cancel_ == DO_NOT_CANCEL && !client_cancel_.cancel) {
+ EXPECT_EQ(reads_complete_, kServerDefaultResponseStreamsToSend);
+ }
+ } else {
+ EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
+ EXPECT_EQ(response_.message(),
request_.message() + ToString(reads_complete_));
- reads_complete_++;
- if (client_cancel_.cancel &&
- reads_complete_ == client_cancel_.ops_before_cancel) {
- context_.TryCancel();
- }
- // Even if we cancel, read until failure because there might be responses
- // pending
- StartRead(&response_);
- }
- }
- void OnDone(const Status& s) override {
- gpr_log(GPR_INFO, "Read %d messages", reads_complete_);
- switch (server_try_cancel_) {
- case DO_NOT_CANCEL:
- if (!client_cancel_.cancel || client_cancel_.ops_before_cancel >
- kServerDefaultResponseStreamsToSend) {
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(reads_complete_, kServerDefaultResponseStreamsToSend);
- } else {
- EXPECT_GE(reads_complete_, client_cancel_.ops_before_cancel);
- EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
- // Status might be ok or cancelled depending on whether server
- // sent status before client cancel went through
- if (!s.ok()) {
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- }
- }
- break;
- case CANCEL_BEFORE_PROCESSING:
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- EXPECT_EQ(reads_complete_, 0);
- break;
- case CANCEL_DURING_PROCESSING:
- case CANCEL_AFTER_PROCESSING:
- // If server canceled while writing messages, client must have read
- // less than or equal to the expected number of messages. Even if the
- // server canceled after writing all messages, the RPC may be canceled
- // before the Client got a chance to read all the messages.
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
- break;
- default:
- assert(false);
- }
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- cv_.notify_one();
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- cv_.wait(l);
- }
- }
-
- private:
- EchoRequest request_;
- EchoResponse response_;
- ClientContext context_;
- const ServerTryCancelRequestPhase server_try_cancel_;
- int reads_complete_{0};
- const ClientCancelInfo client_cancel_;
- std::mutex mu_;
- std::condition_variable cv_;
- bool done_ = false;
-};
-
-TEST_P(ClientCallbackEnd2endTest, ResponseStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- ReadClient test{stub_.get(), DO_NOT_CANCEL};
- test.Await();
- // Make sure that the server interceptors were not notified of a cancel
- if (GetParam().use_interceptors) {
- EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, ClientCancelsResponseStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- ReadClient test{stub_.get(), DO_NOT_CANCEL, ClientCancelInfo{2}};
- test.Await();
- // Because cancel in this case races with server finish, we can't be sure that
- // server interceptors even see cancellation
-}
-
-// Server to cancel before sending any response messages
-TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelBefore) {
- MAYBE_SKIP_TEST;
- ResetStub();
- ReadClient test{stub_.get(), CANCEL_BEFORE_PROCESSING};
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel while writing a response to the stream in parallel
-TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelDuring) {
- MAYBE_SKIP_TEST;
- ResetStub();
- ReadClient test{stub_.get(), CANCEL_DURING_PROCESSING};
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel after writing all the respones to the stream but before
-// returning to the client
-TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelAfter) {
- MAYBE_SKIP_TEST;
- ResetStub();
- ReadClient test{stub_.get(), CANCEL_AFTER_PROCESSING};
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-class BidiClient
- : public grpc::experimental::ClientBidiReactor<EchoRequest, EchoResponse> {
- public:
- BidiClient(grpc::testing::EchoTestService::Stub* stub,
- ServerTryCancelRequestPhase server_try_cancel,
+ reads_complete_++;
+ if (client_cancel_.cancel &&
+ reads_complete_ == client_cancel_.ops_before_cancel) {
+ context_.TryCancel();
+ }
+ // Even if we cancel, read until failure because there might be responses
+ // pending
+ StartRead(&response_);
+ }
+ }
+ void OnDone(const Status& s) override {
+ gpr_log(GPR_INFO, "Read %d messages", reads_complete_);
+ switch (server_try_cancel_) {
+ case DO_NOT_CANCEL:
+ if (!client_cancel_.cancel || client_cancel_.ops_before_cancel >
+ kServerDefaultResponseStreamsToSend) {
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(reads_complete_, kServerDefaultResponseStreamsToSend);
+ } else {
+ EXPECT_GE(reads_complete_, client_cancel_.ops_before_cancel);
+ EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
+ // Status might be ok or cancelled depending on whether server
+ // sent status before client cancel went through
+ if (!s.ok()) {
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ }
+ }
+ break;
+ case CANCEL_BEFORE_PROCESSING:
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ EXPECT_EQ(reads_complete_, 0);
+ break;
+ case CANCEL_DURING_PROCESSING:
+ case CANCEL_AFTER_PROCESSING:
+ // If server canceled while writing messages, client must have read
+ // less than or equal to the expected number of messages. Even if the
+ // server canceled after writing all messages, the RPC may be canceled
+ // before the Client got a chance to read all the messages.
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
+ break;
+ default:
+ assert(false);
+ }
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ cv_.notify_one();
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ cv_.wait(l);
+ }
+ }
+
+ private:
+ EchoRequest request_;
+ EchoResponse response_;
+ ClientContext context_;
+ const ServerTryCancelRequestPhase server_try_cancel_;
+ int reads_complete_{0};
+ const ClientCancelInfo client_cancel_;
+ std::mutex mu_;
+ std::condition_variable cv_;
+ bool done_ = false;
+};
+
+TEST_P(ClientCallbackEnd2endTest, ResponseStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ ReadClient test{stub_.get(), DO_NOT_CANCEL};
+ test.Await();
+ // Make sure that the server interceptors were not notified of a cancel
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, ClientCancelsResponseStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ ReadClient test{stub_.get(), DO_NOT_CANCEL, ClientCancelInfo{2}};
+ test.Await();
+ // Because cancel in this case races with server finish, we can't be sure that
+ // server interceptors even see cancellation
+}
+
+// Server to cancel before sending any response messages
+TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelBefore) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ ReadClient test{stub_.get(), CANCEL_BEFORE_PROCESSING};
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel while writing a response to the stream in parallel
+TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelDuring) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ ReadClient test{stub_.get(), CANCEL_DURING_PROCESSING};
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel after writing all the respones to the stream but before
+// returning to the client
+TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelAfter) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ ReadClient test{stub_.get(), CANCEL_AFTER_PROCESSING};
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+class BidiClient
+ : public grpc::experimental::ClientBidiReactor<EchoRequest, EchoResponse> {
+ public:
+ BidiClient(grpc::testing::EchoTestService::Stub* stub,
+ ServerTryCancelRequestPhase server_try_cancel,
int num_msgs_to_send, bool cork_metadata, bool first_write_async,
ClientCancelInfo client_cancel = {})
- : server_try_cancel_(server_try_cancel),
- msgs_to_send_{num_msgs_to_send},
- client_cancel_{client_cancel} {
- if (server_try_cancel_ != DO_NOT_CANCEL) {
- // Send server_try_cancel value in the client metadata
- context_.AddMetadata(kServerTryCancelRequest,
+ : server_try_cancel_(server_try_cancel),
+ msgs_to_send_{num_msgs_to_send},
+ client_cancel_{client_cancel} {
+ if (server_try_cancel_ != DO_NOT_CANCEL) {
+ // Send server_try_cancel value in the client metadata
+ context_.AddMetadata(kServerTryCancelRequest,
ToString(server_try_cancel));
- }
- request_.set_message("Hello fren ");
+ }
+ request_.set_message("Hello fren ");
context_.set_initial_metadata_corked(cork_metadata);
- stub->experimental_async()->BidiStream(&context_, this);
+ stub->experimental_async()->BidiStream(&context_, this);
MaybeAsyncWrite(first_write_async);
- StartRead(&response_);
- StartCall();
- }
- void OnReadDone(bool ok) override {
- if (!ok) {
- if (server_try_cancel_ == DO_NOT_CANCEL) {
- if (!client_cancel_.cancel) {
- EXPECT_EQ(reads_complete_, msgs_to_send_);
- } else {
- EXPECT_LE(reads_complete_, writes_complete_);
- }
- }
- } else {
- EXPECT_LE(reads_complete_, msgs_to_send_);
- EXPECT_EQ(response_.message(), request_.message());
- reads_complete_++;
- StartRead(&response_);
- }
- }
- void OnWriteDone(bool ok) override {
+ StartRead(&response_);
+ StartCall();
+ }
+ void OnReadDone(bool ok) override {
+ if (!ok) {
+ if (server_try_cancel_ == DO_NOT_CANCEL) {
+ if (!client_cancel_.cancel) {
+ EXPECT_EQ(reads_complete_, msgs_to_send_);
+ } else {
+ EXPECT_LE(reads_complete_, writes_complete_);
+ }
+ }
+ } else {
+ EXPECT_LE(reads_complete_, msgs_to_send_);
+ EXPECT_EQ(response_.message(), request_.message());
+ reads_complete_++;
+ StartRead(&response_);
+ }
+ }
+ void OnWriteDone(bool ok) override {
if (async_write_thread_.joinable()) {
async_write_thread_.join();
RemoveHold();
}
- if (server_try_cancel_ == DO_NOT_CANCEL) {
- EXPECT_TRUE(ok);
- } else if (!ok) {
- return;
- }
- writes_complete_++;
- MaybeWrite();
- }
- void OnDone(const Status& s) override {
- gpr_log(GPR_INFO, "Sent %d messages", writes_complete_);
- gpr_log(GPR_INFO, "Read %d messages", reads_complete_);
- switch (server_try_cancel_) {
- case DO_NOT_CANCEL:
- if (!client_cancel_.cancel ||
- client_cancel_.ops_before_cancel > msgs_to_send_) {
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(writes_complete_, msgs_to_send_);
- EXPECT_EQ(reads_complete_, writes_complete_);
- } else {
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- EXPECT_EQ(writes_complete_, client_cancel_.ops_before_cancel);
- EXPECT_LE(reads_complete_, writes_complete_);
- }
- break;
- case CANCEL_BEFORE_PROCESSING:
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- // The RPC is canceled before the server did any work or returned any
- // reads, but it's possible that some writes took place first from the
- // client
- EXPECT_LE(writes_complete_, msgs_to_send_);
- EXPECT_EQ(reads_complete_, 0);
- break;
- case CANCEL_DURING_PROCESSING:
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- EXPECT_LE(writes_complete_, msgs_to_send_);
- EXPECT_LE(reads_complete_, writes_complete_);
- break;
- case CANCEL_AFTER_PROCESSING:
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- EXPECT_EQ(writes_complete_, msgs_to_send_);
- // The Server canceled after reading the last message and after writing
- // the message to the client. However, the RPC cancellation might have
- // taken effect before the client actually read the response.
- EXPECT_LE(reads_complete_, writes_complete_);
- break;
- default:
- assert(false);
- }
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- cv_.notify_one();
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- cv_.wait(l);
- }
- }
-
- private:
+ if (server_try_cancel_ == DO_NOT_CANCEL) {
+ EXPECT_TRUE(ok);
+ } else if (!ok) {
+ return;
+ }
+ writes_complete_++;
+ MaybeWrite();
+ }
+ void OnDone(const Status& s) override {
+ gpr_log(GPR_INFO, "Sent %d messages", writes_complete_);
+ gpr_log(GPR_INFO, "Read %d messages", reads_complete_);
+ switch (server_try_cancel_) {
+ case DO_NOT_CANCEL:
+ if (!client_cancel_.cancel ||
+ client_cancel_.ops_before_cancel > msgs_to_send_) {
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(writes_complete_, msgs_to_send_);
+ EXPECT_EQ(reads_complete_, writes_complete_);
+ } else {
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ EXPECT_EQ(writes_complete_, client_cancel_.ops_before_cancel);
+ EXPECT_LE(reads_complete_, writes_complete_);
+ }
+ break;
+ case CANCEL_BEFORE_PROCESSING:
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ // The RPC is canceled before the server did any work or returned any
+ // reads, but it's possible that some writes took place first from the
+ // client
+ EXPECT_LE(writes_complete_, msgs_to_send_);
+ EXPECT_EQ(reads_complete_, 0);
+ break;
+ case CANCEL_DURING_PROCESSING:
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ EXPECT_LE(writes_complete_, msgs_to_send_);
+ EXPECT_LE(reads_complete_, writes_complete_);
+ break;
+ case CANCEL_AFTER_PROCESSING:
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ EXPECT_EQ(writes_complete_, msgs_to_send_);
+ // The Server canceled after reading the last message and after writing
+ // the message to the client. However, the RPC cancellation might have
+ // taken effect before the client actually read the response.
+ EXPECT_LE(reads_complete_, writes_complete_);
+ break;
+ default:
+ assert(false);
+ }
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ cv_.notify_one();
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ cv_.wait(l);
+ }
+ }
+
+ private:
void MaybeAsyncWrite(bool first_write_async) {
if (first_write_async) {
// Make sure that we have a write to issue.
@@ -1210,46 +1210,46 @@ class BidiClient
}
MaybeWrite();
}
- void MaybeWrite() {
- if (client_cancel_.cancel &&
- writes_complete_ == client_cancel_.ops_before_cancel) {
- context_.TryCancel();
- } else if (writes_complete_ == msgs_to_send_) {
- StartWritesDone();
- } else {
- StartWrite(&request_);
- }
- }
- EchoRequest request_;
- EchoResponse response_;
- ClientContext context_;
- const ServerTryCancelRequestPhase server_try_cancel_;
- int reads_complete_{0};
- int writes_complete_{0};
- const int msgs_to_send_;
- const ClientCancelInfo client_cancel_;
- std::mutex mu_;
- std::condition_variable cv_;
- bool done_ = false;
+ void MaybeWrite() {
+ if (client_cancel_.cancel &&
+ writes_complete_ == client_cancel_.ops_before_cancel) {
+ context_.TryCancel();
+ } else if (writes_complete_ == msgs_to_send_) {
+ StartWritesDone();
+ } else {
+ StartWrite(&request_);
+ }
+ }
+ EchoRequest request_;
+ EchoResponse response_;
+ ClientContext context_;
+ const ServerTryCancelRequestPhase server_try_cancel_;
+ int reads_complete_{0};
+ int writes_complete_{0};
+ const int msgs_to_send_;
+ const ClientCancelInfo client_cancel_;
+ std::mutex mu_;
+ std::condition_variable cv_;
+ bool done_ = false;
std::thread async_write_thread_;
bool async_write_thread_start_ = false;
std::mutex async_write_thread_mu_;
std::condition_variable async_write_thread_cv_;
-};
-
-TEST_P(ClientCallbackEnd2endTest, BidiStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
+};
+
+TEST_P(ClientCallbackEnd2endTest, BidiStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
BidiClient test(stub_.get(), DO_NOT_CANCEL,
kServerDefaultResponseStreamsToSend,
/*cork_metadata=*/false, /*first_write_async=*/false);
- test.Await();
- // Make sure that the server interceptors were not notified of a cancel
- if (GetParam().use_interceptors) {
- EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
+ test.Await();
+ // Make sure that the server interceptors were not notified of a cancel
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(0, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
TEST_P(ClientCallbackEnd2endTest, BidiStreamFirstWriteAsync) {
MAYBE_SKIP_TEST;
ResetStub();
@@ -1289,277 +1289,277 @@ TEST_P(ClientCallbackEnd2endTest, BidiStreamCorkedFirstWriteAsync) {
}
}
-TEST_P(ClientCallbackEnd2endTest, ClientCancelsBidiStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
+TEST_P(ClientCallbackEnd2endTest, ClientCancelsBidiStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
BidiClient test(stub_.get(), DO_NOT_CANCEL,
kServerDefaultResponseStreamsToSend,
/*cork_metadata=*/false, /*first_write_async=*/false,
ClientCancelInfo(2));
- test.Await();
- // Make sure that the server interceptors were notified of a cancel
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel before reading/writing any requests/responses on the stream
-TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelBefore) {
- MAYBE_SKIP_TEST;
- ResetStub();
+ test.Await();
+ // Make sure that the server interceptors were notified of a cancel
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel before reading/writing any requests/responses on the stream
+TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelBefore) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
BidiClient test(stub_.get(), CANCEL_BEFORE_PROCESSING, /*num_msgs_to_send=*/2,
/*cork_metadata=*/false, /*first_write_async=*/false);
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel while reading/writing requests/responses on the stream in
-// parallel
-TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelDuring) {
- MAYBE_SKIP_TEST;
- ResetStub();
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel while reading/writing requests/responses on the stream in
+// parallel
+TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelDuring) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
BidiClient test(stub_.get(), CANCEL_DURING_PROCESSING,
/*num_msgs_to_send=*/10, /*cork_metadata=*/false,
/*first_write_async=*/false);
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Server to cancel after reading/writing all requests/responses on the stream
-// but before returning to the client
-TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelAfter) {
- MAYBE_SKIP_TEST;
- ResetStub();
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Server to cancel after reading/writing all requests/responses on the stream
+// but before returning to the client
+TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelAfter) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
BidiClient test(stub_.get(), CANCEL_AFTER_PROCESSING, /*num_msgs_to_send=*/5,
/*cork_metadata=*/false, /*first_write_async=*/false);
- test.Await();
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest, SimultaneousReadAndWritesDone) {
- MAYBE_SKIP_TEST;
- ResetStub();
- class Client : public grpc::experimental::ClientBidiReactor<EchoRequest,
- EchoResponse> {
- public:
- Client(grpc::testing::EchoTestService::Stub* stub) {
- request_.set_message("Hello bidi ");
- stub->experimental_async()->BidiStream(&context_, this);
- StartWrite(&request_);
- StartCall();
- }
- void OnReadDone(bool ok) override {
- EXPECT_TRUE(ok);
- EXPECT_EQ(response_.message(), request_.message());
- }
- void OnWriteDone(bool ok) override {
- EXPECT_TRUE(ok);
- // Now send out the simultaneous Read and WritesDone
- StartWritesDone();
- StartRead(&response_);
- }
- void OnDone(const Status& s) override {
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(response_.message(), request_.message());
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- cv_.notify_one();
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- cv_.wait(l);
- }
- }
-
- private:
- EchoRequest request_;
- EchoResponse response_;
- ClientContext context_;
- std::mutex mu_;
- std::condition_variable cv_;
- bool done_ = false;
- } test{stub_.get()};
-
- test.Await();
-}
-
-TEST_P(ClientCallbackEnd2endTest, UnimplementedRpc) {
- MAYBE_SKIP_TEST;
- ChannelArguments args;
- const auto& channel_creds = GetCredentialsProvider()->GetChannelCredentials(
- GetParam().credentials_type, &args);
- std::shared_ptr<Channel> channel =
- (GetParam().protocol == Protocol::TCP)
- ? ::grpc::CreateCustomChannel(server_address_.str(), channel_creds,
- args)
- : server_->InProcessChannel(args);
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest request;
- EchoResponse response;
- ClientContext cli_ctx;
- request.set_message("Hello world.");
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- stub->experimental_async()->Unimplemented(
- &cli_ctx, &request, &response, [&done, &mu, &cv](Status s) {
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
- EXPECT_EQ("", s.error_message());
-
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-TEST_P(ClientCallbackEnd2endTest,
- ResponseStreamExtraReactionFlowReadsUntilDone) {
- MAYBE_SKIP_TEST;
- ResetStub();
- class ReadAllIncomingDataClient
- : public grpc::experimental::ClientReadReactor<EchoResponse> {
- public:
- ReadAllIncomingDataClient(grpc::testing::EchoTestService::Stub* stub) {
- request_.set_message("Hello client ");
- stub->experimental_async()->ResponseStream(&context_, &request_, this);
- }
- bool WaitForReadDone() {
- std::unique_lock<std::mutex> l(mu_);
- while (!read_done_) {
- read_cv_.wait(l);
- }
- read_done_ = false;
- return read_ok_;
- }
- void Await() {
- std::unique_lock<std::mutex> l(mu_);
- while (!done_) {
- done_cv_.wait(l);
- }
- }
+ test.Await();
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest, SimultaneousReadAndWritesDone) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ class Client : public grpc::experimental::ClientBidiReactor<EchoRequest,
+ EchoResponse> {
+ public:
+ Client(grpc::testing::EchoTestService::Stub* stub) {
+ request_.set_message("Hello bidi ");
+ stub->experimental_async()->BidiStream(&context_, this);
+ StartWrite(&request_);
+ StartCall();
+ }
+ void OnReadDone(bool ok) override {
+ EXPECT_TRUE(ok);
+ EXPECT_EQ(response_.message(), request_.message());
+ }
+ void OnWriteDone(bool ok) override {
+ EXPECT_TRUE(ok);
+ // Now send out the simultaneous Read and WritesDone
+ StartWritesDone();
+ StartRead(&response_);
+ }
+ void OnDone(const Status& s) override {
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(response_.message(), request_.message());
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ cv_.notify_one();
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ cv_.wait(l);
+ }
+ }
+
+ private:
+ EchoRequest request_;
+ EchoResponse response_;
+ ClientContext context_;
+ std::mutex mu_;
+ std::condition_variable cv_;
+ bool done_ = false;
+ } test{stub_.get()};
+
+ test.Await();
+}
+
+TEST_P(ClientCallbackEnd2endTest, UnimplementedRpc) {
+ MAYBE_SKIP_TEST;
+ ChannelArguments args;
+ const auto& channel_creds = GetCredentialsProvider()->GetChannelCredentials(
+ GetParam().credentials_type, &args);
+ std::shared_ptr<Channel> channel =
+ (GetParam().protocol == Protocol::TCP)
+ ? ::grpc::CreateCustomChannel(server_address_.str(), channel_creds,
+ args)
+ : server_->InProcessChannel(args);
+ std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
+ stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext cli_ctx;
+ request.set_message("Hello world.");
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ stub->experimental_async()->Unimplemented(
+ &cli_ctx, &request, &response, [&done, &mu, &cv](Status s) {
+ EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
+ EXPECT_EQ("", s.error_message());
+
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+}
+
+TEST_P(ClientCallbackEnd2endTest,
+ ResponseStreamExtraReactionFlowReadsUntilDone) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ class ReadAllIncomingDataClient
+ : public grpc::experimental::ClientReadReactor<EchoResponse> {
+ public:
+ ReadAllIncomingDataClient(grpc::testing::EchoTestService::Stub* stub) {
+ request_.set_message("Hello client ");
+ stub->experimental_async()->ResponseStream(&context_, &request_, this);
+ }
+ bool WaitForReadDone() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!read_done_) {
+ read_cv_.wait(l);
+ }
+ read_done_ = false;
+ return read_ok_;
+ }
+ void Await() {
+ std::unique_lock<std::mutex> l(mu_);
+ while (!done_) {
+ done_cv_.wait(l);
+ }
+ }
// RemoveHold under the same lock used for OnDone to make sure that we don't
// call OnDone directly or indirectly from the RemoveHold function.
void RemoveHoldUnderLock() {
std::unique_lock<std::mutex> l(mu_);
RemoveHold();
}
- const Status& status() {
- std::unique_lock<std::mutex> l(mu_);
- return status_;
- }
-
- private:
- void OnReadDone(bool ok) override {
- std::unique_lock<std::mutex> l(mu_);
- read_ok_ = ok;
- read_done_ = true;
- read_cv_.notify_one();
- }
- void OnDone(const Status& s) override {
- std::unique_lock<std::mutex> l(mu_);
- done_ = true;
- status_ = s;
- done_cv_.notify_one();
- }
-
- EchoRequest request_;
- EchoResponse response_;
- ClientContext context_;
- bool read_ok_ = false;
- bool read_done_ = false;
- std::mutex mu_;
- std::condition_variable read_cv_;
- std::condition_variable done_cv_;
- bool done_ = false;
- Status status_;
- } client{stub_.get()};
-
- int reads_complete = 0;
- client.AddHold();
- client.StartCall();
-
- EchoResponse response;
- bool read_ok = true;
- while (read_ok) {
- client.StartRead(&response);
- read_ok = client.WaitForReadDone();
- if (read_ok) {
- ++reads_complete;
- }
- }
+ const Status& status() {
+ std::unique_lock<std::mutex> l(mu_);
+ return status_;
+ }
+
+ private:
+ void OnReadDone(bool ok) override {
+ std::unique_lock<std::mutex> l(mu_);
+ read_ok_ = ok;
+ read_done_ = true;
+ read_cv_.notify_one();
+ }
+ void OnDone(const Status& s) override {
+ std::unique_lock<std::mutex> l(mu_);
+ done_ = true;
+ status_ = s;
+ done_cv_.notify_one();
+ }
+
+ EchoRequest request_;
+ EchoResponse response_;
+ ClientContext context_;
+ bool read_ok_ = false;
+ bool read_done_ = false;
+ std::mutex mu_;
+ std::condition_variable read_cv_;
+ std::condition_variable done_cv_;
+ bool done_ = false;
+ Status status_;
+ } client{stub_.get()};
+
+ int reads_complete = 0;
+ client.AddHold();
+ client.StartCall();
+
+ EchoResponse response;
+ bool read_ok = true;
+ while (read_ok) {
+ client.StartRead(&response);
+ read_ok = client.WaitForReadDone();
+ if (read_ok) {
+ ++reads_complete;
+ }
+ }
client.RemoveHoldUnderLock();
- client.Await();
-
- EXPECT_EQ(kServerDefaultResponseStreamsToSend, reads_complete);
- EXPECT_EQ(client.status().error_code(), grpc::StatusCode::OK);
-}
-
-std::vector<TestScenario> CreateTestScenarios(bool test_insecure) {
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
-
- std::vector<TestScenario> scenarios;
+ client.Await();
+
+ EXPECT_EQ(kServerDefaultResponseStreamsToSend, reads_complete);
+ EXPECT_EQ(client.status().error_code(), grpc::StatusCode::OK);
+}
+
+std::vector<TestScenario> CreateTestScenarios(bool test_insecure) {
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+
+ std::vector<TestScenario> scenarios;
std::vector<TString> credentials_types{
- GetCredentialsProvider()->GetSecureCredentialsTypeList()};
- auto insec_ok = [] {
- // Only allow insecure credentials type when it is registered with the
- // provider. User may create providers that do not have insecure.
- return GetCredentialsProvider()->GetChannelCredentials(
- kInsecureCredentialsType, nullptr) != nullptr;
- };
- if (test_insecure && insec_ok()) {
- credentials_types.push_back(kInsecureCredentialsType);
- }
- GPR_ASSERT(!credentials_types.empty());
-
- bool barr[]{false, true};
- Protocol parr[]{Protocol::INPROC, Protocol::TCP};
- for (Protocol p : parr) {
- for (const auto& cred : credentials_types) {
- // TODO(vjpai): Test inproc with secure credentials when feasible
- if (p == Protocol::INPROC &&
- (cred != kInsecureCredentialsType || !insec_ok())) {
- continue;
- }
- for (bool callback_server : barr) {
- for (bool use_interceptors : barr) {
- scenarios.emplace_back(callback_server, p, use_interceptors, cred);
- }
- }
- }
- }
- return scenarios;
-}
-
-INSTANTIATE_TEST_SUITE_P(ClientCallbackEnd2endTest, ClientCallbackEnd2endTest,
- ::testing::ValuesIn(CreateTestScenarios(true)));
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
+ GetCredentialsProvider()->GetSecureCredentialsTypeList()};
+ auto insec_ok = [] {
+ // Only allow insecure credentials type when it is registered with the
+ // provider. User may create providers that do not have insecure.
+ return GetCredentialsProvider()->GetChannelCredentials(
+ kInsecureCredentialsType, nullptr) != nullptr;
+ };
+ if (test_insecure && insec_ok()) {
+ credentials_types.push_back(kInsecureCredentialsType);
+ }
+ GPR_ASSERT(!credentials_types.empty());
+
+ bool barr[]{false, true};
+ Protocol parr[]{Protocol::INPROC, Protocol::TCP};
+ for (Protocol p : parr) {
+ for (const auto& cred : credentials_types) {
+ // TODO(vjpai): Test inproc with secure credentials when feasible
+ if (p == Protocol::INPROC &&
+ (cred != kInsecureCredentialsType || !insec_ok())) {
+ continue;
+ }
+ for (bool callback_server : barr) {
+ for (bool use_interceptors : barr) {
+ scenarios.emplace_back(callback_server, p, use_interceptors, cred);
+ }
+ }
+ }
+ }
+ return scenarios;
+}
+
+INSTANTIATE_TEST_SUITE_P(ClientCallbackEnd2endTest, ClientCallbackEnd2endTest,
+ ::testing::ValuesIn(CreateTestScenarios(true)));
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
grpc::testing::TestEnvironment env(argc, argv);
- grpc_init();
- int ret = RUN_ALL_TESTS();
- grpc_shutdown();
- return ret;
-}
+ grpc_init();
+ int ret = RUN_ALL_TESTS();
+ grpc_shutdown();
+ return ret;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/client_crash_test.cc b/contrib/libs/grpc/test/cpp/end2end/client_crash_test.cc
index 80e1869396..93131f8104 100644
--- a/contrib/libs/grpc/test/cpp/end2end/client_crash_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/client_crash_test.cc
@@ -1,147 +1,147 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/subprocess.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/subprocess.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
static TString g_root;
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-class CrashTest : public ::testing::Test {
- protected:
- CrashTest() {}
-
- std::unique_ptr<grpc::testing::EchoTestService::Stub> CreateServerAndStub() {
- auto port = grpc_pick_unused_port_or_die();
- std::ostringstream addr_stream;
- addr_stream << "localhost:" << port;
- auto addr = addr_stream.str();
- server_.reset(new SubProcess({
- g_root + "/client_crash_test_server",
- "--address=" + addr,
- }));
- GPR_ASSERT(server_);
- return grpc::testing::EchoTestService::NewStub(
- grpc::CreateChannel(addr, InsecureChannelCredentials()));
- }
-
- void KillServer() { server_.reset(); }
-
- private:
- std::unique_ptr<SubProcess> server_;
-};
-
-TEST_F(CrashTest, KillBeforeWrite) {
- auto stub = CreateServerAndStub();
-
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_wait_for_ready(true);
-
- auto stream = stub->BidiStream(&context);
-
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- KillServer();
-
- request.set_message("You should be dead");
- // This may succeed or fail depending on the state of the TCP connection
- stream->Write(request);
- // But the read will definitely fail
- EXPECT_FALSE(stream->Read(&response));
-
- EXPECT_FALSE(stream->Finish().ok());
-}
-
-TEST_F(CrashTest, KillAfterWrite) {
- auto stub = CreateServerAndStub();
-
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_wait_for_ready(true);
-
- auto stream = stub->BidiStream(&context);
-
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message("I'm going to kill you");
- EXPECT_TRUE(stream->Write(request));
-
- KillServer();
-
- // This may succeed or fail depending on how quick the server was
- stream->Read(&response);
-
- EXPECT_FALSE(stream->Finish().ok());
-}
-
-} // namespace
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
+
+namespace grpc {
+namespace testing {
+
+namespace {
+
+class CrashTest : public ::testing::Test {
+ protected:
+ CrashTest() {}
+
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> CreateServerAndStub() {
+ auto port = grpc_pick_unused_port_or_die();
+ std::ostringstream addr_stream;
+ addr_stream << "localhost:" << port;
+ auto addr = addr_stream.str();
+ server_.reset(new SubProcess({
+ g_root + "/client_crash_test_server",
+ "--address=" + addr,
+ }));
+ GPR_ASSERT(server_);
+ return grpc::testing::EchoTestService::NewStub(
+ grpc::CreateChannel(addr, InsecureChannelCredentials()));
+ }
+
+ void KillServer() { server_.reset(); }
+
+ private:
+ std::unique_ptr<SubProcess> server_;
+};
+
+TEST_F(CrashTest, KillBeforeWrite) {
+ auto stub = CreateServerAndStub();
+
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_wait_for_ready(true);
+
+ auto stream = stub->BidiStream(&context);
+
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ KillServer();
+
+ request.set_message("You should be dead");
+ // This may succeed or fail depending on the state of the TCP connection
+ stream->Write(request);
+ // But the read will definitely fail
+ EXPECT_FALSE(stream->Read(&response));
+
+ EXPECT_FALSE(stream->Finish().ok());
+}
+
+TEST_F(CrashTest, KillAfterWrite) {
+ auto stub = CreateServerAndStub();
+
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_wait_for_ready(true);
+
+ auto stream = stub->BidiStream(&context);
+
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message("I'm going to kill you");
+ EXPECT_TRUE(stream->Write(request));
+
+ KillServer();
+
+ // This may succeed or fail depending on how quick the server was
+ stream->Read(&response);
+
+ EXPECT_FALSE(stream->Finish().ok());
+}
+
+} // namespace
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
TString me = argv[0];
- auto lslash = me.rfind('/');
+ auto lslash = me.rfind('/');
if (lslash != TString::npos) {
- g_root = me.substr(0, lslash);
- } else {
- g_root = ".";
- }
-
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- // Order seems to matter on these tests: run three times to eliminate that
- for (int i = 0; i < 3; i++) {
- if (RUN_ALL_TESTS() != 0) {
- return 1;
- }
- }
- return 0;
-}
+ g_root = me.substr(0, lslash);
+ } else {
+ g_root = ".";
+ }
+
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ // Order seems to matter on these tests: run three times to eliminate that
+ for (int i = 0; i < 3; i++) {
+ if (RUN_ALL_TESTS() != 0) {
+ return 1;
+ }
+ }
+ return 0;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/client_crash_test_server.cc b/contrib/libs/grpc/test/cpp/end2end/client_crash_test_server.cc
index 2d5be420f2..a7e0dc3aa0 100644
--- a/contrib/libs/grpc/test/cpp/end2end/client_crash_test_server.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/client_crash_test_server.cc
@@ -1,80 +1,80 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <gflags/gflags.h>
-#include <iostream>
-#include <memory>
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <gflags/gflags.h>
+#include <iostream>
+#include <memory>
#include <util/generic/string.h>
-
-#include <grpc/support/log.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/test_config.h"
-
-DEFINE_string(address, "", "Address to bind to");
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-
-// In some distros, gflags is in the namespace google, and in some others,
-// in gflags. This hack is enabling us to find both.
-namespace google {}
-namespace gflags {}
-using namespace google;
-using namespace gflags;
-
-namespace grpc {
-namespace testing {
-
-class ServiceImpl final : public ::grpc::testing::EchoTestService::Service {
- Status BidiStream(
- ServerContext* /*context*/,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- EchoRequest request;
- EchoResponse response;
- while (stream->Read(&request)) {
- gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
- response.set_message(request.message());
- stream->Write(response);
- }
- return Status::OK;
- }
-};
-
-void RunServer() {
- ServiceImpl service;
-
- ServerBuilder builder;
- builder.AddListeningPort(FLAGS_address, grpc::InsecureServerCredentials());
- builder.RegisterService(&service);
- std::unique_ptr<Server> server(builder.BuildAndStart());
- std::cout << "Server listening on " << FLAGS_address << std::endl;
- server->Wait();
-}
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::InitTest(&argc, &argv, true);
- grpc::testing::RunServer();
-
- return 0;
-}
+
+#include <grpc/support/log.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/cpp/util/test_config.h"
+
+DEFINE_string(address, "", "Address to bind to");
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+
+// In some distros, gflags is in the namespace google, and in some others,
+// in gflags. This hack is enabling us to find both.
+namespace google {}
+namespace gflags {}
+using namespace google;
+using namespace gflags;
+
+namespace grpc {
+namespace testing {
+
+class ServiceImpl final : public ::grpc::testing::EchoTestService::Service {
+ Status BidiStream(
+ ServerContext* /*context*/,
+ ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
+ EchoRequest request;
+ EchoResponse response;
+ while (stream->Read(&request)) {
+ gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
+ response.set_message(request.message());
+ stream->Write(response);
+ }
+ return Status::OK;
+ }
+};
+
+void RunServer() {
+ ServiceImpl service;
+
+ ServerBuilder builder;
+ builder.AddListeningPort(FLAGS_address, grpc::InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::unique_ptr<Server> server(builder.BuildAndStart());
+ std::cout << "Server listening on " << FLAGS_address << std::endl;
+ server->Wait();
+}
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::InitTest(&argc, &argv, true);
+ grpc::testing::RunServer();
+
+ return 0;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/client_interceptors_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/client_interceptors_end2end_test.cc
index 956876d9f6..18a9e98b71 100644
--- a/contrib/libs/grpc/test/cpp/end2end/client_interceptors_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/client_interceptors_end2end_test.cc
@@ -1,48 +1,48 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <memory>
-#include <vector>
-
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/client_interceptor.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/interceptors_util.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <memory>
+#include <vector>
+
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/generic/generic_stub.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/client_interceptor.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/interceptors_util.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+#include "test/cpp/util/string_ref_helper.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+namespace {
+
enum class RPCType {
kSyncUnary,
kSyncClientStreaming,
@@ -54,495 +54,495 @@ enum class RPCType {
kAsyncCQBidiStreaming,
};
-/* Hijacks Echo RPC and fills in the expected values */
-class HijackingInterceptor : public experimental::Interceptor {
- public:
- HijackingInterceptor(experimental::ClientRpcInfo* info) {
- info_ = info;
- // Make sure it is the right method
- EXPECT_EQ(strcmp("/grpc.testing.EchoTestService/Echo", info->method()), 0);
- EXPECT_EQ(info->type(), experimental::ClientRpcInfo::Type::UNARY);
- }
-
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- bool hijack = false;
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Check that we can see the test metadata
- ASSERT_EQ(map->size(), static_cast<unsigned>(1));
- auto iterator = map->begin();
- EXPECT_EQ("testkey", iterator->first);
- EXPECT_EQ("testvalue", iterator->second);
- hijack = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_EQ(req.message(), "Hello");
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
- // Got nothing to do here for now
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- // Got nothing better to do here for now
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- // Check that we got the hijacked message, and re-insert the expected
- // message
- EXPECT_EQ(resp->message(), "Hello1");
- resp->set_message("Hello");
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.starts_with("testkey") &&
- pair.second.starts_with("testvalue");
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto* status = methods->GetRecvStatus();
- EXPECT_EQ(status->ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- // Got nothing better to do here at the moment
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
- // Insert a different message than expected
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- resp->set_message("Hello1");
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- // insert the metadata that we want
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- map->insert(std::make_pair("testkey", "testvalue"));
- auto* status = methods->GetRecvStatus();
- *status = Status(StatusCode::OK, "");
- }
- if (hijack) {
- methods->Hijack();
- } else {
- methods->Proceed();
- }
- }
-
- private:
- experimental::ClientRpcInfo* info_;
-};
-
-class HijackingInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new HijackingInterceptor(info);
- }
-};
-
-class HijackingInterceptorMakesAnotherCall : public experimental::Interceptor {
- public:
- HijackingInterceptorMakesAnotherCall(experimental::ClientRpcInfo* info) {
- info_ = info;
- // Make sure it is the right method
- EXPECT_EQ(strcmp("/grpc.testing.EchoTestService/Echo", info->method()), 0);
- }
-
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Check that we can see the test metadata
- ASSERT_EQ(map->size(), static_cast<unsigned>(1));
- auto iterator = map->begin();
- EXPECT_EQ("testkey", iterator->first);
- EXPECT_EQ("testvalue", iterator->second);
- // Make a copy of the map
- metadata_map_ = *map;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_EQ(req.message(), "Hello");
- req_ = req;
- stub_ = grpc::testing::EchoTestService::NewStub(
- methods->GetInterceptedChannel());
- ctx_.AddMetadata(metadata_map_.begin()->first,
- metadata_map_.begin()->second);
- stub_->experimental_async()->Echo(&ctx_, &req_, &resp_,
- [this, methods](Status s) {
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp_.message(), "Hello");
- methods->Hijack();
- });
- // This is a Unary RPC and we have got nothing interesting to do in the
- // PRE_SEND_CLOSE interception hook point for this interceptor, so let's
- // return here. (We do not want to call methods->Proceed(). When the new
- // RPC returns, we will call methods->Hijack() instead.)
- return;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
- // Got nothing to do here for now
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- // Got nothing better to do here for now
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- // Check that we got the hijacked message, and re-insert the expected
- // message
- EXPECT_EQ(resp->message(), "Hello");
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.starts_with("testkey") &&
- pair.second.starts_with("testvalue");
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto* status = methods->GetRecvStatus();
- EXPECT_EQ(status->ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- // Got nothing better to do here at the moment
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
- // Insert a different message than expected
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- resp->set_message(resp_.message());
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- // insert the metadata that we want
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- map->insert(std::make_pair("testkey", "testvalue"));
- auto* status = methods->GetRecvStatus();
- *status = Status(StatusCode::OK, "");
- }
-
- methods->Proceed();
- }
-
- private:
- experimental::ClientRpcInfo* info_;
+/* Hijacks Echo RPC and fills in the expected values */
+class HijackingInterceptor : public experimental::Interceptor {
+ public:
+ HijackingInterceptor(experimental::ClientRpcInfo* info) {
+ info_ = info;
+ // Make sure it is the right method
+ EXPECT_EQ(strcmp("/grpc.testing.EchoTestService/Echo", info->method()), 0);
+ EXPECT_EQ(info->type(), experimental::ClientRpcInfo::Type::UNARY);
+ }
+
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ bool hijack = false;
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ auto* map = methods->GetSendInitialMetadata();
+ // Check that we can see the test metadata
+ ASSERT_EQ(map->size(), static_cast<unsigned>(1));
+ auto iterator = map->begin();
+ EXPECT_EQ("testkey", iterator->first);
+ EXPECT_EQ("testvalue", iterator->second);
+ hijack = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ EchoRequest req;
+ auto* buffer = methods->GetSerializedSendMessage();
+ auto copied_buffer = *buffer;
+ EXPECT_TRUE(
+ SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
+ .ok());
+ EXPECT_EQ(req.message(), "Hello");
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
+ // Got nothing to do here for now
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
+ auto* map = methods->GetRecvInitialMetadata();
+ // Got nothing better to do here for now
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ // Check that we got the hijacked message, and re-insert the expected
+ // message
+ EXPECT_EQ(resp->message(), "Hello1");
+ resp->set_message("Hello");
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ bool found = false;
+ // Check that we received the metadata as an echo
+ for (const auto& pair : *map) {
+ found = pair.first.starts_with("testkey") &&
+ pair.second.starts_with("testvalue");
+ if (found) break;
+ }
+ EXPECT_EQ(found, true);
+ auto* status = methods->GetRecvStatus();
+ EXPECT_EQ(status->ok(), true);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA)) {
+ auto* map = methods->GetRecvInitialMetadata();
+ // Got nothing better to do here at the moment
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
+ // Insert a different message than expected
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ resp->set_message("Hello1");
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ // insert the metadata that we want
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ map->insert(std::make_pair("testkey", "testvalue"));
+ auto* status = methods->GetRecvStatus();
+ *status = Status(StatusCode::OK, "");
+ }
+ if (hijack) {
+ methods->Hijack();
+ } else {
+ methods->Proceed();
+ }
+ }
+
+ private:
+ experimental::ClientRpcInfo* info_;
+};
+
+class HijackingInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) override {
+ return new HijackingInterceptor(info);
+ }
+};
+
+class HijackingInterceptorMakesAnotherCall : public experimental::Interceptor {
+ public:
+ HijackingInterceptorMakesAnotherCall(experimental::ClientRpcInfo* info) {
+ info_ = info;
+ // Make sure it is the right method
+ EXPECT_EQ(strcmp("/grpc.testing.EchoTestService/Echo", info->method()), 0);
+ }
+
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ auto* map = methods->GetSendInitialMetadata();
+ // Check that we can see the test metadata
+ ASSERT_EQ(map->size(), static_cast<unsigned>(1));
+ auto iterator = map->begin();
+ EXPECT_EQ("testkey", iterator->first);
+ EXPECT_EQ("testvalue", iterator->second);
+ // Make a copy of the map
+ metadata_map_ = *map;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ EchoRequest req;
+ auto* buffer = methods->GetSerializedSendMessage();
+ auto copied_buffer = *buffer;
+ EXPECT_TRUE(
+ SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
+ .ok());
+ EXPECT_EQ(req.message(), "Hello");
+ req_ = req;
+ stub_ = grpc::testing::EchoTestService::NewStub(
+ methods->GetInterceptedChannel());
+ ctx_.AddMetadata(metadata_map_.begin()->first,
+ metadata_map_.begin()->second);
+ stub_->experimental_async()->Echo(&ctx_, &req_, &resp_,
+ [this, methods](Status s) {
+ EXPECT_EQ(s.ok(), true);
+ EXPECT_EQ(resp_.message(), "Hello");
+ methods->Hijack();
+ });
+ // This is a Unary RPC and we have got nothing interesting to do in the
+ // PRE_SEND_CLOSE interception hook point for this interceptor, so let's
+ // return here. (We do not want to call methods->Proceed(). When the new
+ // RPC returns, we will call methods->Hijack() instead.)
+ return;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
+ // Got nothing to do here for now
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
+ auto* map = methods->GetRecvInitialMetadata();
+ // Got nothing better to do here for now
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ // Check that we got the hijacked message, and re-insert the expected
+ // message
+ EXPECT_EQ(resp->message(), "Hello");
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ bool found = false;
+ // Check that we received the metadata as an echo
+ for (const auto& pair : *map) {
+ found = pair.first.starts_with("testkey") &&
+ pair.second.starts_with("testvalue");
+ if (found) break;
+ }
+ EXPECT_EQ(found, true);
+ auto* status = methods->GetRecvStatus();
+ EXPECT_EQ(status->ok(), true);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA)) {
+ auto* map = methods->GetRecvInitialMetadata();
+ // Got nothing better to do here at the moment
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
+ // Insert a different message than expected
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ resp->set_message(resp_.message());
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ // insert the metadata that we want
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ map->insert(std::make_pair("testkey", "testvalue"));
+ auto* status = methods->GetRecvStatus();
+ *status = Status(StatusCode::OK, "");
+ }
+
+ methods->Proceed();
+ }
+
+ private:
+ experimental::ClientRpcInfo* info_;
std::multimap<TString, TString> metadata_map_;
- ClientContext ctx_;
- EchoRequest req_;
- EchoResponse resp_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
-};
-
-class HijackingInterceptorMakesAnotherCallFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new HijackingInterceptorMakesAnotherCall(info);
- }
-};
-
-class BidiStreamingRpcHijackingInterceptor : public experimental::Interceptor {
- public:
- BidiStreamingRpcHijackingInterceptor(experimental::ClientRpcInfo* info) {
- info_ = info;
- }
-
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- bool hijack = false;
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- CheckMetadata(*methods->GetSendInitialMetadata(), "testkey", "testvalue");
- hijack = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_EQ(req.message().find("Hello"), 0u);
- msg = req.message();
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
- // Got nothing to do here for now
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
- CheckMetadata(*methods->GetRecvTrailingMetadata(), "testkey",
- "testvalue");
- auto* status = methods->GetRecvStatus();
- EXPECT_EQ(status->ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- resp->set_message(msg);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EXPECT_EQ(static_cast<EchoResponse*>(methods->GetRecvMessage())
- ->message()
- .find("Hello"),
- 0u);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- // insert the metadata that we want
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- map->insert(std::make_pair("testkey", "testvalue"));
- auto* status = methods->GetRecvStatus();
- *status = Status(StatusCode::OK, "");
- }
- if (hijack) {
- methods->Hijack();
- } else {
- methods->Proceed();
- }
- }
-
- private:
- experimental::ClientRpcInfo* info_;
+ ClientContext ctx_;
+ EchoRequest req_;
+ EchoResponse resp_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+};
+
+class HijackingInterceptorMakesAnotherCallFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) override {
+ return new HijackingInterceptorMakesAnotherCall(info);
+ }
+};
+
+class BidiStreamingRpcHijackingInterceptor : public experimental::Interceptor {
+ public:
+ BidiStreamingRpcHijackingInterceptor(experimental::ClientRpcInfo* info) {
+ info_ = info;
+ }
+
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ bool hijack = false;
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ CheckMetadata(*methods->GetSendInitialMetadata(), "testkey", "testvalue");
+ hijack = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ EchoRequest req;
+ auto* buffer = methods->GetSerializedSendMessage();
+ auto copied_buffer = *buffer;
+ EXPECT_TRUE(
+ SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
+ .ok());
+ EXPECT_EQ(req.message().find("Hello"), 0u);
+ msg = req.message();
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
+ // Got nothing to do here for now
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
+ CheckMetadata(*methods->GetRecvTrailingMetadata(), "testkey",
+ "testvalue");
+ auto* status = methods->GetRecvStatus();
+ EXPECT_EQ(status->ok(), true);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ resp->set_message(msg);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
+ EXPECT_EQ(static_cast<EchoResponse*>(methods->GetRecvMessage())
+ ->message()
+ .find("Hello"),
+ 0u);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ // insert the metadata that we want
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ map->insert(std::make_pair("testkey", "testvalue"));
+ auto* status = methods->GetRecvStatus();
+ *status = Status(StatusCode::OK, "");
+ }
+ if (hijack) {
+ methods->Hijack();
+ } else {
+ methods->Proceed();
+ }
+ }
+
+ private:
+ experimental::ClientRpcInfo* info_;
TString msg;
-};
-
-class ClientStreamingRpcHijackingInterceptor
- : public experimental::Interceptor {
- public:
- ClientStreamingRpcHijackingInterceptor(experimental::ClientRpcInfo* info) {
- info_ = info;
- }
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- bool hijack = false;
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- hijack = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- if (++count_ > 10) {
- methods->FailHijackedSendMessage();
- }
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_SEND_MESSAGE)) {
- EXPECT_FALSE(got_failed_send_);
- got_failed_send_ = !methods->GetSendMessageStatus();
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
- auto* status = methods->GetRecvStatus();
- *status = Status(StatusCode::UNAVAILABLE, "Done sending 10 messages");
- }
- if (hijack) {
- methods->Hijack();
- } else {
- methods->Proceed();
- }
- }
-
- static bool GotFailedSend() { return got_failed_send_; }
-
- private:
- experimental::ClientRpcInfo* info_;
- int count_ = 0;
- static bool got_failed_send_;
-};
-
-bool ClientStreamingRpcHijackingInterceptor::got_failed_send_ = false;
-
-class ClientStreamingRpcHijackingInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new ClientStreamingRpcHijackingInterceptor(info);
- }
-};
-
-class ServerStreamingRpcHijackingInterceptor
- : public experimental::Interceptor {
- public:
- ServerStreamingRpcHijackingInterceptor(experimental::ClientRpcInfo* info) {
- info_ = info;
+};
+
+class ClientStreamingRpcHijackingInterceptor
+ : public experimental::Interceptor {
+ public:
+ ClientStreamingRpcHijackingInterceptor(experimental::ClientRpcInfo* info) {
+ info_ = info;
+ }
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ bool hijack = false;
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ hijack = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ if (++count_ > 10) {
+ methods->FailHijackedSendMessage();
+ }
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_SEND_MESSAGE)) {
+ EXPECT_FALSE(got_failed_send_);
+ got_failed_send_ = !methods->GetSendMessageStatus();
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
+ auto* status = methods->GetRecvStatus();
+ *status = Status(StatusCode::UNAVAILABLE, "Done sending 10 messages");
+ }
+ if (hijack) {
+ methods->Hijack();
+ } else {
+ methods->Proceed();
+ }
+ }
+
+ static bool GotFailedSend() { return got_failed_send_; }
+
+ private:
+ experimental::ClientRpcInfo* info_;
+ int count_ = 0;
+ static bool got_failed_send_;
+};
+
+bool ClientStreamingRpcHijackingInterceptor::got_failed_send_ = false;
+
+class ClientStreamingRpcHijackingInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) override {
+ return new ClientStreamingRpcHijackingInterceptor(info);
+ }
+};
+
+class ServerStreamingRpcHijackingInterceptor
+ : public experimental::Interceptor {
+ public:
+ ServerStreamingRpcHijackingInterceptor(experimental::ClientRpcInfo* info) {
+ info_ = info;
got_failed_message_ = false;
- }
-
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- bool hijack = false;
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Check that we can see the test metadata
- ASSERT_EQ(map->size(), static_cast<unsigned>(1));
- auto iterator = map->begin();
- EXPECT_EQ("testkey", iterator->first);
- EXPECT_EQ("testvalue", iterator->second);
- hijack = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_EQ(req.message(), "Hello");
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
- // Got nothing to do here for now
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.starts_with("testkey") &&
- pair.second.starts_with("testvalue");
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto* status = methods->GetRecvStatus();
- EXPECT_EQ(status->ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
- if (++count_ > 10) {
- methods->FailHijackedRecvMessage();
- }
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- resp->set_message("Hello");
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- // Only the last message will be a failure
- EXPECT_FALSE(got_failed_message_);
- got_failed_message_ = methods->GetRecvMessage() == nullptr;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- // insert the metadata that we want
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- map->insert(std::make_pair("testkey", "testvalue"));
- auto* status = methods->GetRecvStatus();
- *status = Status(StatusCode::OK, "");
- }
- if (hijack) {
- methods->Hijack();
- } else {
- methods->Proceed();
- }
- }
-
- static bool GotFailedMessage() { return got_failed_message_; }
-
- private:
- experimental::ClientRpcInfo* info_;
- static bool got_failed_message_;
- int count_ = 0;
-};
-
-bool ServerStreamingRpcHijackingInterceptor::got_failed_message_ = false;
-
-class ServerStreamingRpcHijackingInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new ServerStreamingRpcHijackingInterceptor(info);
- }
-};
-
-class BidiStreamingRpcHijackingInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new BidiStreamingRpcHijackingInterceptor(info);
- }
-};
-
-// The logging interceptor is for testing purposes only. It is used to verify
-// that all the appropriate hook points are invoked for an RPC. The counts are
-// reset each time a new object of LoggingInterceptor is created, so only a
-// single RPC should be made on the channel before calling the Verify methods.
-class LoggingInterceptor : public experimental::Interceptor {
- public:
- LoggingInterceptor(experimental::ClientRpcInfo* /*info*/) {
- pre_send_initial_metadata_ = false;
- pre_send_message_count_ = 0;
- pre_send_close_ = false;
- post_recv_initial_metadata_ = false;
- post_recv_message_count_ = 0;
- post_recv_status_ = false;
- }
-
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Check that we can see the test metadata
- ASSERT_EQ(map->size(), static_cast<unsigned>(1));
- auto iterator = map->begin();
- EXPECT_EQ("testkey", iterator->first);
- EXPECT_EQ("testvalue", iterator->second);
- ASSERT_FALSE(pre_send_initial_metadata_);
- pre_send_initial_metadata_ = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
+ }
+
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ bool hijack = false;
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ auto* map = methods->GetSendInitialMetadata();
+ // Check that we can see the test metadata
+ ASSERT_EQ(map->size(), static_cast<unsigned>(1));
+ auto iterator = map->begin();
+ EXPECT_EQ("testkey", iterator->first);
+ EXPECT_EQ("testvalue", iterator->second);
+ hijack = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ EchoRequest req;
+ auto* buffer = methods->GetSerializedSendMessage();
+ auto copied_buffer = *buffer;
+ EXPECT_TRUE(
+ SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
+ .ok());
+ EXPECT_EQ(req.message(), "Hello");
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
+ // Got nothing to do here for now
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ bool found = false;
+ // Check that we received the metadata as an echo
+ for (const auto& pair : *map) {
+ found = pair.first.starts_with("testkey") &&
+ pair.second.starts_with("testvalue");
+ if (found) break;
+ }
+ EXPECT_EQ(found, true);
+ auto* status = methods->GetRecvStatus();
+ EXPECT_EQ(status->ok(), true);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)) {
+ if (++count_ > 10) {
+ methods->FailHijackedRecvMessage();
+ }
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ resp->set_message("Hello");
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
+ // Only the last message will be a failure
+ EXPECT_FALSE(got_failed_message_);
+ got_failed_message_ = methods->GetRecvMessage() == nullptr;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ // insert the metadata that we want
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ map->insert(std::make_pair("testkey", "testvalue"));
+ auto* status = methods->GetRecvStatus();
+ *status = Status(StatusCode::OK, "");
+ }
+ if (hijack) {
+ methods->Hijack();
+ } else {
+ methods->Proceed();
+ }
+ }
+
+ static bool GotFailedMessage() { return got_failed_message_; }
+
+ private:
+ experimental::ClientRpcInfo* info_;
+ static bool got_failed_message_;
+ int count_ = 0;
+};
+
+bool ServerStreamingRpcHijackingInterceptor::got_failed_message_ = false;
+
+class ServerStreamingRpcHijackingInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) override {
+ return new ServerStreamingRpcHijackingInterceptor(info);
+ }
+};
+
+class BidiStreamingRpcHijackingInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) override {
+ return new BidiStreamingRpcHijackingInterceptor(info);
+ }
+};
+
+// The logging interceptor is for testing purposes only. It is used to verify
+// that all the appropriate hook points are invoked for an RPC. The counts are
+// reset each time a new object of LoggingInterceptor is created, so only a
+// single RPC should be made on the channel before calling the Verify methods.
+class LoggingInterceptor : public experimental::Interceptor {
+ public:
+ LoggingInterceptor(experimental::ClientRpcInfo* /*info*/) {
+ pre_send_initial_metadata_ = false;
+ pre_send_message_count_ = 0;
+ pre_send_close_ = false;
+ post_recv_initial_metadata_ = false;
+ post_recv_message_count_ = 0;
+ post_recv_status_ = false;
+ }
+
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ auto* map = methods->GetSendInitialMetadata();
+ // Check that we can see the test metadata
+ ASSERT_EQ(map->size(), static_cast<unsigned>(1));
+ auto iterator = map->begin();
+ EXPECT_EQ("testkey", iterator->first);
+ EXPECT_EQ("testvalue", iterator->second);
+ ASSERT_FALSE(pre_send_initial_metadata_);
+ pre_send_initial_metadata_ = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ EchoRequest req;
auto* send_msg = methods->GetSendMessage();
if (send_msg == nullptr) {
// We did not get the non-serialized form of the message. Get the
@@ -559,53 +559,53 @@ class LoggingInterceptor : public experimental::Interceptor {
static_cast<const EchoRequest*>(send_msg)->message().find("Hello"),
0u);
}
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_TRUE(req.message().find("Hello") == 0u);
- pre_send_message_count_++;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
- // Got nothing to do here for now
- pre_send_close_ = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- // Got nothing better to do here for now
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- post_recv_initial_metadata_ = true;
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- if (resp != nullptr) {
- EXPECT_TRUE(resp->message().find("Hello") == 0u);
- post_recv_message_count_++;
- }
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
- auto* map = methods->GetRecvTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.starts_with("testkey") &&
- pair.second.starts_with("testvalue");
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto* status = methods->GetRecvStatus();
- EXPECT_EQ(status->ok(), true);
- post_recv_status_ = true;
- }
- methods->Proceed();
- }
-
+ auto* buffer = methods->GetSerializedSendMessage();
+ auto copied_buffer = *buffer;
+ EXPECT_TRUE(
+ SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
+ .ok());
+ EXPECT_TRUE(req.message().find("Hello") == 0u);
+ pre_send_message_count_++;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_CLOSE)) {
+ // Got nothing to do here for now
+ pre_send_close_ = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
+ auto* map = methods->GetRecvInitialMetadata();
+ // Got nothing better to do here for now
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ post_recv_initial_metadata_ = true;
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ if (resp != nullptr) {
+ EXPECT_TRUE(resp->message().find("Hello") == 0u);
+ post_recv_message_count_++;
+ }
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_STATUS)) {
+ auto* map = methods->GetRecvTrailingMetadata();
+ bool found = false;
+ // Check that we received the metadata as an echo
+ for (const auto& pair : *map) {
+ found = pair.first.starts_with("testkey") &&
+ pair.second.starts_with("testvalue");
+ if (found) break;
+ }
+ EXPECT_EQ(found, true);
+ auto* status = methods->GetRecvStatus();
+ EXPECT_EQ(status->ok(), true);
+ post_recv_status_ = true;
+ }
+ methods->Proceed();
+ }
+
static void VerifyCall(RPCType type) {
switch (type) {
case RPCType::kSyncUnary:
@@ -627,62 +627,62 @@ class LoggingInterceptor : public experimental::Interceptor {
}
}
- static void VerifyCallCommon() {
- EXPECT_TRUE(pre_send_initial_metadata_);
- EXPECT_TRUE(pre_send_close_);
- EXPECT_TRUE(post_recv_initial_metadata_);
- EXPECT_TRUE(post_recv_status_);
- }
-
- static void VerifyUnaryCall() {
- VerifyCallCommon();
- EXPECT_EQ(pre_send_message_count_, 1);
- EXPECT_EQ(post_recv_message_count_, 1);
- }
-
- static void VerifyClientStreamingCall() {
- VerifyCallCommon();
- EXPECT_EQ(pre_send_message_count_, kNumStreamingMessages);
- EXPECT_EQ(post_recv_message_count_, 1);
- }
-
- static void VerifyServerStreamingCall() {
- VerifyCallCommon();
- EXPECT_EQ(pre_send_message_count_, 1);
- EXPECT_EQ(post_recv_message_count_, kNumStreamingMessages);
- }
-
- static void VerifyBidiStreamingCall() {
- VerifyCallCommon();
- EXPECT_EQ(pre_send_message_count_, kNumStreamingMessages);
- EXPECT_EQ(post_recv_message_count_, kNumStreamingMessages);
- }
-
- private:
- static bool pre_send_initial_metadata_;
- static int pre_send_message_count_;
- static bool pre_send_close_;
- static bool post_recv_initial_metadata_;
- static int post_recv_message_count_;
- static bool post_recv_status_;
-};
-
-bool LoggingInterceptor::pre_send_initial_metadata_;
-int LoggingInterceptor::pre_send_message_count_;
-bool LoggingInterceptor::pre_send_close_;
-bool LoggingInterceptor::post_recv_initial_metadata_;
-int LoggingInterceptor::post_recv_message_count_;
-bool LoggingInterceptor::post_recv_status_;
-
-class LoggingInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new LoggingInterceptor(info);
- }
-};
-
+ static void VerifyCallCommon() {
+ EXPECT_TRUE(pre_send_initial_metadata_);
+ EXPECT_TRUE(pre_send_close_);
+ EXPECT_TRUE(post_recv_initial_metadata_);
+ EXPECT_TRUE(post_recv_status_);
+ }
+
+ static void VerifyUnaryCall() {
+ VerifyCallCommon();
+ EXPECT_EQ(pre_send_message_count_, 1);
+ EXPECT_EQ(post_recv_message_count_, 1);
+ }
+
+ static void VerifyClientStreamingCall() {
+ VerifyCallCommon();
+ EXPECT_EQ(pre_send_message_count_, kNumStreamingMessages);
+ EXPECT_EQ(post_recv_message_count_, 1);
+ }
+
+ static void VerifyServerStreamingCall() {
+ VerifyCallCommon();
+ EXPECT_EQ(pre_send_message_count_, 1);
+ EXPECT_EQ(post_recv_message_count_, kNumStreamingMessages);
+ }
+
+ static void VerifyBidiStreamingCall() {
+ VerifyCallCommon();
+ EXPECT_EQ(pre_send_message_count_, kNumStreamingMessages);
+ EXPECT_EQ(post_recv_message_count_, kNumStreamingMessages);
+ }
+
+ private:
+ static bool pre_send_initial_metadata_;
+ static int pre_send_message_count_;
+ static bool pre_send_close_;
+ static bool post_recv_initial_metadata_;
+ static int post_recv_message_count_;
+ static bool post_recv_status_;
+};
+
+bool LoggingInterceptor::pre_send_initial_metadata_;
+int LoggingInterceptor::pre_send_message_count_;
+bool LoggingInterceptor::pre_send_close_;
+bool LoggingInterceptor::post_recv_initial_metadata_;
+int LoggingInterceptor::post_recv_message_count_;
+bool LoggingInterceptor::post_recv_status_;
+
+class LoggingInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) override {
+ return new LoggingInterceptor(info);
+ }
+};
+
class TestScenario {
public:
explicit TestScenario(const RPCType& type) : type_(type) {}
@@ -706,19 +706,19 @@ std::vector<TestScenario> CreateTestScenarios() {
class ParameterizedClientInterceptorsEnd2endTest
: public ::testing::TestWithParam<TestScenario> {
- protected:
+ protected:
ParameterizedClientInterceptorsEnd2endTest() {
- int port = grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
+ int port = grpc_pick_unused_port_or_die();
+
+ ServerBuilder builder;
server_address_ = "localhost:" + ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- }
-
+ builder.AddListeningPort(server_address_, InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ }
+
~ParameterizedClientInterceptorsEnd2endTest() { server_->Shutdown(); }
-
+
void SendRPC(const std::shared_ptr<Channel>& channel) {
switch (GetParam().type()) {
case RPCType::kSyncUnary:
@@ -750,30 +750,30 @@ class ParameterizedClientInterceptorsEnd2endTest
TString server_address_;
EchoTestServiceStreamingImpl service_;
- std::unique_ptr<Server> server_;
-};
-
+ std::unique_ptr<Server> server_;
+};
+
TEST_P(ParameterizedClientInterceptorsEnd2endTest,
ClientInterceptorLoggingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptors
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptors
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
SendRPC(channel);
LoggingInterceptor::VerifyCall(GetParam().type());
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
INSTANTIATE_TEST_SUITE_P(ParameterizedClientInterceptorsEnd2end,
ParameterizedClientInterceptorsEnd2endTest,
::testing::ValuesIn(CreateTestScenarios()));
@@ -798,86 +798,86 @@ class ClientInterceptorsEnd2endTest
std::unique_ptr<Server> server_;
};
-TEST_F(ClientInterceptorsEnd2endTest,
- LameChannelClientInterceptorHijackingTest) {
- ChannelArguments args;
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<HijackingInterceptorFactory>(
- new HijackingInterceptorFactory()));
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, nullptr, args, std::move(creators));
- MakeCall(channel);
-}
-
-TEST_F(ClientInterceptorsEnd2endTest, ClientInterceptorHijackingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy interceptors before hijacking interceptor
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- creators.push_back(std::unique_ptr<HijackingInterceptorFactory>(
- new HijackingInterceptorFactory()));
- // Add 20 dummy interceptors after hijacking interceptor
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeCall(channel);
- // Make sure only 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ClientInterceptorsEnd2endTest, ClientInterceptorLogThenHijackTest) {
- ChannelArguments args;
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- creators.push_back(std::unique_ptr<HijackingInterceptorFactory>(
- new HijackingInterceptorFactory()));
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeCall(channel);
- LoggingInterceptor::VerifyUnaryCall();
-}
-
-TEST_F(ClientInterceptorsEnd2endTest,
- ClientInterceptorHijackingMakesAnotherCallTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 5 dummy interceptors before hijacking interceptor
- creators.reserve(5);
- for (auto i = 0; i < 5; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- creators.push_back(
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>(
- new HijackingInterceptorMakesAnotherCallFactory()));
- // Add 7 dummy interceptors after hijacking interceptor
- for (auto i = 0; i < 7; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = server_->experimental().InProcessChannelWithInterceptors(
- args, std::move(creators));
-
- MakeCall(channel);
- // Make sure all interceptors were run once, since the hijacking interceptor
- // makes an RPC on the intercepted channel
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 12);
-}
-
+TEST_F(ClientInterceptorsEnd2endTest,
+ LameChannelClientInterceptorHijackingTest) {
+ ChannelArguments args;
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<HijackingInterceptorFactory>(
+ new HijackingInterceptorFactory()));
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, nullptr, args, std::move(creators));
+ MakeCall(channel);
+}
+
+TEST_F(ClientInterceptorsEnd2endTest, ClientInterceptorHijackingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy interceptors before hijacking interceptor
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ creators.push_back(std::unique_ptr<HijackingInterceptorFactory>(
+ new HijackingInterceptorFactory()));
+ // Add 20 dummy interceptors after hijacking interceptor
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeCall(channel);
+ // Make sure only 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+TEST_F(ClientInterceptorsEnd2endTest, ClientInterceptorLogThenHijackTest) {
+ ChannelArguments args;
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ creators.push_back(std::unique_ptr<HijackingInterceptorFactory>(
+ new HijackingInterceptorFactory()));
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeCall(channel);
+ LoggingInterceptor::VerifyUnaryCall();
+}
+
+TEST_F(ClientInterceptorsEnd2endTest,
+ ClientInterceptorHijackingMakesAnotherCallTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ // Add 5 dummy interceptors before hijacking interceptor
+ creators.reserve(5);
+ for (auto i = 0; i < 5; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ creators.push_back(
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>(
+ new HijackingInterceptorMakesAnotherCallFactory()));
+ // Add 7 dummy interceptors after hijacking interceptor
+ for (auto i = 0; i < 7; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = server_->experimental().InProcessChannelWithInterceptors(
+ args, std::move(creators));
+
+ MakeCall(channel);
+ // Make sure all interceptors were run once, since the hijacking interceptor
+ // makes an RPC on the intercepted channel
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 12);
+}
+
class ClientInterceptorsCallbackEnd2endTest : public ::testing::Test {
protected:
ClientInterceptorsCallbackEnd2endTest() {
@@ -898,151 +898,151 @@ class ClientInterceptorsCallbackEnd2endTest : public ::testing::Test {
};
TEST_F(ClientInterceptorsCallbackEnd2endTest,
- ClientInterceptorLoggingTestWithCallback) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptors
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = server_->experimental().InProcessChannelWithInterceptors(
- args, std::move(creators));
- MakeCallbackCall(channel);
- LoggingInterceptor::VerifyUnaryCall();
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
+ ClientInterceptorLoggingTestWithCallback) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptors
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = server_->experimental().InProcessChannelWithInterceptors(
+ args, std::move(creators));
+ MakeCallbackCall(channel);
+ LoggingInterceptor::VerifyUnaryCall();
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
TEST_F(ClientInterceptorsCallbackEnd2endTest,
- ClientInterceptorFactoryAllowsNullptrReturn) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptors and 20 null interceptors
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- creators.push_back(
- std::unique_ptr<NullInterceptorFactory>(new NullInterceptorFactory()));
- }
- auto channel = server_->experimental().InProcessChannelWithInterceptors(
- args, std::move(creators));
- MakeCallbackCall(channel);
- LoggingInterceptor::VerifyUnaryCall();
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ClientInterceptorsStreamingEnd2endTest : public ::testing::Test {
- protected:
- ClientInterceptorsStreamingEnd2endTest() {
- int port = grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
+ ClientInterceptorFactoryAllowsNullptrReturn) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptors and 20 null interceptors
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ creators.push_back(
+ std::unique_ptr<NullInterceptorFactory>(new NullInterceptorFactory()));
+ }
+ auto channel = server_->experimental().InProcessChannelWithInterceptors(
+ args, std::move(creators));
+ MakeCallbackCall(channel);
+ LoggingInterceptor::VerifyUnaryCall();
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+class ClientInterceptorsStreamingEnd2endTest : public ::testing::Test {
+ protected:
+ ClientInterceptorsStreamingEnd2endTest() {
+ int port = grpc_pick_unused_port_or_die();
+
+ ServerBuilder builder;
server_address_ = "localhost:" + ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- }
-
- ~ClientInterceptorsStreamingEnd2endTest() { server_->Shutdown(); }
-
+ builder.AddListeningPort(server_address_, InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ }
+
+ ~ClientInterceptorsStreamingEnd2endTest() { server_->Shutdown(); }
+
TString server_address_;
- EchoTestServiceStreamingImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ClientInterceptorsStreamingEnd2endTest, ClientStreamingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptors
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeClientStreamingCall(channel);
- LoggingInterceptor::VerifyClientStreamingCall();
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ClientInterceptorsStreamingEnd2endTest, ServerStreamingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptors
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeServerStreamingCall(channel);
- LoggingInterceptor::VerifyServerStreamingCall();
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ClientInterceptorsStreamingEnd2endTest, ClientStreamingHijackingTest) {
- ChannelArguments args;
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<ClientStreamingRpcHijackingInterceptorFactory>(
- new ClientStreamingRpcHijackingInterceptorFactory()));
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
-
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- req.mutable_param()->set_echo_metadata(true);
- req.set_message("Hello");
- string expected_resp = "";
- auto writer = stub->RequestStream(&ctx, &resp);
- for (int i = 0; i < 10; i++) {
- EXPECT_TRUE(writer->Write(req));
- expected_resp += "Hello";
- }
- // The interceptor will reject the 11th message
- writer->Write(req);
- Status s = writer->Finish();
- EXPECT_EQ(s.ok(), false);
- EXPECT_TRUE(ClientStreamingRpcHijackingInterceptor::GotFailedSend());
-}
-
-TEST_F(ClientInterceptorsStreamingEnd2endTest, ServerStreamingHijackingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<ServerStreamingRpcHijackingInterceptorFactory>(
- new ServerStreamingRpcHijackingInterceptorFactory()));
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeServerStreamingCall(channel);
- EXPECT_TRUE(ServerStreamingRpcHijackingInterceptor::GotFailedMessage());
-}
-
+ EchoTestServiceStreamingImpl service_;
+ std::unique_ptr<Server> server_;
+};
+
+TEST_F(ClientInterceptorsStreamingEnd2endTest, ClientStreamingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptors
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeClientStreamingCall(channel);
+ LoggingInterceptor::VerifyClientStreamingCall();
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+TEST_F(ClientInterceptorsStreamingEnd2endTest, ServerStreamingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptors
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeServerStreamingCall(channel);
+ LoggingInterceptor::VerifyServerStreamingCall();
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+TEST_F(ClientInterceptorsStreamingEnd2endTest, ClientStreamingHijackingTest) {
+ ChannelArguments args;
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<ClientStreamingRpcHijackingInterceptorFactory>(
+ new ClientStreamingRpcHijackingInterceptorFactory()));
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ EchoResponse resp;
+ req.mutable_param()->set_echo_metadata(true);
+ req.set_message("Hello");
+ string expected_resp = "";
+ auto writer = stub->RequestStream(&ctx, &resp);
+ for (int i = 0; i < 10; i++) {
+ EXPECT_TRUE(writer->Write(req));
+ expected_resp += "Hello";
+ }
+ // The interceptor will reject the 11th message
+ writer->Write(req);
+ Status s = writer->Finish();
+ EXPECT_EQ(s.ok(), false);
+ EXPECT_TRUE(ClientStreamingRpcHijackingInterceptor::GotFailedSend());
+}
+
+TEST_F(ClientInterceptorsStreamingEnd2endTest, ServerStreamingHijackingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<ServerStreamingRpcHijackingInterceptorFactory>(
+ new ServerStreamingRpcHijackingInterceptorFactory()));
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeServerStreamingCall(channel);
+ EXPECT_TRUE(ServerStreamingRpcHijackingInterceptor::GotFailedMessage());
+}
+
TEST_F(ClientInterceptorsStreamingEnd2endTest,
AsyncCQServerStreamingHijackingTest) {
ChannelArguments args;
@@ -1058,137 +1058,137 @@ TEST_F(ClientInterceptorsStreamingEnd2endTest,
EXPECT_TRUE(ServerStreamingRpcHijackingInterceptor::GotFailedMessage());
}
-TEST_F(ClientInterceptorsStreamingEnd2endTest, BidiStreamingHijackingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<BidiStreamingRpcHijackingInterceptorFactory>(
- new BidiStreamingRpcHijackingInterceptorFactory()));
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeBidiStreamingCall(channel);
-}
-
-TEST_F(ClientInterceptorsStreamingEnd2endTest, BidiStreamingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptors
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeBidiStreamingCall(channel);
- LoggingInterceptor::VerifyBidiStreamingCall();
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ClientGlobalInterceptorEnd2endTest : public ::testing::Test {
- protected:
- ClientGlobalInterceptorEnd2endTest() {
- int port = grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
+TEST_F(ClientInterceptorsStreamingEnd2endTest, BidiStreamingHijackingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<BidiStreamingRpcHijackingInterceptorFactory>(
+ new BidiStreamingRpcHijackingInterceptorFactory()));
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeBidiStreamingCall(channel);
+}
+
+TEST_F(ClientInterceptorsStreamingEnd2endTest, BidiStreamingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(std::unique_ptr<LoggingInterceptorFactory>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptors
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeBidiStreamingCall(channel);
+ LoggingInterceptor::VerifyBidiStreamingCall();
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+class ClientGlobalInterceptorEnd2endTest : public ::testing::Test {
+ protected:
+ ClientGlobalInterceptorEnd2endTest() {
+ int port = grpc_pick_unused_port_or_die();
+
+ ServerBuilder builder;
server_address_ = "localhost:" + ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- }
-
- ~ClientGlobalInterceptorEnd2endTest() { server_->Shutdown(); }
-
+ builder.AddListeningPort(server_address_, InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ }
+
+ ~ClientGlobalInterceptorEnd2endTest() { server_->Shutdown(); }
+
TString server_address_;
- TestServiceImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ClientGlobalInterceptorEnd2endTest, DummyGlobalInterceptor) {
- // We should ideally be registering a global interceptor only once per
- // process, but for the purposes of testing, it should be fine to modify the
- // registered global interceptor when there are no ongoing gRPC operations
- DummyInterceptorFactory global_factory;
- experimental::RegisterGlobalClientInterceptorFactory(&global_factory);
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy interceptors
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeCall(channel);
- // Make sure all 20 dummy interceptors were run with the global interceptor
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 21);
- experimental::TestOnlyResetGlobalClientInterceptorFactory();
-}
-
-TEST_F(ClientGlobalInterceptorEnd2endTest, LoggingGlobalInterceptor) {
- // We should ideally be registering a global interceptor only once per
- // process, but for the purposes of testing, it should be fine to modify the
- // registered global interceptor when there are no ongoing gRPC operations
- LoggingInterceptorFactory global_factory;
- experimental::RegisterGlobalClientInterceptorFactory(&global_factory);
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy interceptors
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeCall(channel);
- LoggingInterceptor::VerifyUnaryCall();
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
- experimental::TestOnlyResetGlobalClientInterceptorFactory();
-}
-
-TEST_F(ClientGlobalInterceptorEnd2endTest, HijackingGlobalInterceptor) {
- // We should ideally be registering a global interceptor only once per
- // process, but for the purposes of testing, it should be fine to modify the
- // registered global interceptor when there are no ongoing gRPC operations
- HijackingInterceptorFactory global_factory;
- experimental::RegisterGlobalClientInterceptorFactory(&global_factory);
- ChannelArguments args;
- DummyInterceptor::Reset();
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy interceptors
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- auto channel = experimental::CreateCustomChannelWithInterceptors(
- server_address_, InsecureChannelCredentials(), args, std::move(creators));
- MakeCall(channel);
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
- experimental::TestOnlyResetGlobalClientInterceptorFactory();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ TestServiceImpl service_;
+ std::unique_ptr<Server> server_;
+};
+
+TEST_F(ClientGlobalInterceptorEnd2endTest, DummyGlobalInterceptor) {
+ // We should ideally be registering a global interceptor only once per
+ // process, but for the purposes of testing, it should be fine to modify the
+ // registered global interceptor when there are no ongoing gRPC operations
+ DummyInterceptorFactory global_factory;
+ experimental::RegisterGlobalClientInterceptorFactory(&global_factory);
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy interceptors
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeCall(channel);
+ // Make sure all 20 dummy interceptors were run with the global interceptor
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 21);
+ experimental::TestOnlyResetGlobalClientInterceptorFactory();
+}
+
+TEST_F(ClientGlobalInterceptorEnd2endTest, LoggingGlobalInterceptor) {
+ // We should ideally be registering a global interceptor only once per
+ // process, but for the purposes of testing, it should be fine to modify the
+ // registered global interceptor when there are no ongoing gRPC operations
+ LoggingInterceptorFactory global_factory;
+ experimental::RegisterGlobalClientInterceptorFactory(&global_factory);
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy interceptors
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeCall(channel);
+ LoggingInterceptor::VerifyUnaryCall();
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+ experimental::TestOnlyResetGlobalClientInterceptorFactory();
+}
+
+TEST_F(ClientGlobalInterceptorEnd2endTest, HijackingGlobalInterceptor) {
+ // We should ideally be registering a global interceptor only once per
+ // process, but for the purposes of testing, it should be fine to modify the
+ // registered global interceptor when there are no ongoing gRPC operations
+ HijackingInterceptorFactory global_factory;
+ experimental::RegisterGlobalClientInterceptorFactory(&global_factory);
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy interceptors
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ auto channel = experimental::CreateCustomChannelWithInterceptors(
+ server_address_, InsecureChannelCredentials(), args, std::move(creators));
+ MakeCall(channel);
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+ experimental::TestOnlyResetGlobalClientInterceptorFactory();
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/client_lb_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/client_lb_end2end_test.cc
index fd08dd163d..30cfb444a1 100644
--- a/contrib/libs/grpc/test/cpp/end2end/client_lb_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/client_lb_end2end_test.cc
@@ -1,1655 +1,1655 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <algorithm>
-#include <memory>
-#include <mutex>
-#include <random>
-#include <set>
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <algorithm>
+#include <memory>
+#include <mutex>
+#include <random>
+#include <set>
#include <util/generic/string.h>
-#include <thread>
-
+#include <thread>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/health_check_service_interface.h>
-#include <grpcpp/impl/codegen/sync.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-
-#include "src/core/ext/filters/client_channel/backup_poller.h"
-#include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
-#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
-#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
-#include "src/core/lib/backoff/backoff.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/gprpp/debug_location.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/health_check_service_interface.h>
+#include <grpcpp/impl/codegen/sync.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+
+#include "src/core/ext/filters/client_channel/backup_poller.h"
+#include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
+#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
+#include "src/core/ext/filters/client_channel/server_address.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/lib/backoff/backoff.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/parse_address.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/security/credentials/fake/fake_credentials.h"
-#include "src/cpp/client/secure_credentials.h"
-#include "src/cpp/server/secure_server_credentials.h"
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "src/proto/grpc/testing/xds/orca_load_report_for_test.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/core/util/test_lb_policies.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
-// defined in tcp_client.cc
-extern grpc_tcp_client_vtable* grpc_tcp_client_impl;
-
-static grpc_tcp_client_vtable* default_client_impl;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-gpr_atm g_connection_delay_ms;
-
-void tcp_client_connect_with_delay(grpc_closure* closure, grpc_endpoint** ep,
- grpc_pollset_set* interested_parties,
- const grpc_channel_args* channel_args,
- const grpc_resolved_address* addr,
- grpc_millis deadline) {
- const int delay_ms = gpr_atm_acq_load(&g_connection_delay_ms);
- if (delay_ms > 0) {
- gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
- }
- default_client_impl->connect(closure, ep, interested_parties, channel_args,
- addr, deadline + delay_ms);
-}
-
-grpc_tcp_client_vtable delayed_connect = {tcp_client_connect_with_delay};
-
-// Subclass of TestServiceImpl that increments a request counter for
-// every call to the Echo RPC.
-class MyTestServiceImpl : public TestServiceImpl {
- public:
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) override {
- const udpa::data::orca::v1::OrcaLoadReport* load_report = nullptr;
- {
- grpc::internal::MutexLock lock(&mu_);
- ++request_count_;
- load_report = load_report_;
- }
- AddClient(context->peer().c_str());
- if (load_report != nullptr) {
- // TODO(roth): Once we provide a more standard server-side API for
- // populating this data, use that API here.
- context->AddTrailingMetadata("x-endpoint-load-metrics-bin",
- load_report->SerializeAsString());
- }
- return TestServiceImpl::Echo(context, request, response);
- }
-
- int request_count() {
- grpc::internal::MutexLock lock(&mu_);
- return request_count_;
- }
-
- void ResetCounters() {
- grpc::internal::MutexLock lock(&mu_);
- request_count_ = 0;
- }
-
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/security/credentials/fake/fake_credentials.h"
+#include "src/cpp/client/secure_credentials.h"
+#include "src/cpp/server/secure_server_credentials.h"
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "src/proto/grpc/testing/xds/orca_load_report_for_test.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/core/util/test_lb_policies.h"
+#include "test/cpp/end2end/test_service_impl.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
+// defined in tcp_client.cc
+extern grpc_tcp_client_vtable* grpc_tcp_client_impl;
+
+static grpc_tcp_client_vtable* default_client_impl;
+
+namespace grpc {
+namespace testing {
+namespace {
+
+gpr_atm g_connection_delay_ms;
+
+void tcp_client_connect_with_delay(grpc_closure* closure, grpc_endpoint** ep,
+ grpc_pollset_set* interested_parties,
+ const grpc_channel_args* channel_args,
+ const grpc_resolved_address* addr,
+ grpc_millis deadline) {
+ const int delay_ms = gpr_atm_acq_load(&g_connection_delay_ms);
+ if (delay_ms > 0) {
+ gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
+ }
+ default_client_impl->connect(closure, ep, interested_parties, channel_args,
+ addr, deadline + delay_ms);
+}
+
+grpc_tcp_client_vtable delayed_connect = {tcp_client_connect_with_delay};
+
+// Subclass of TestServiceImpl that increments a request counter for
+// every call to the Echo RPC.
+class MyTestServiceImpl : public TestServiceImpl {
+ public:
+ Status Echo(ServerContext* context, const EchoRequest* request,
+ EchoResponse* response) override {
+ const udpa::data::orca::v1::OrcaLoadReport* load_report = nullptr;
+ {
+ grpc::internal::MutexLock lock(&mu_);
+ ++request_count_;
+ load_report = load_report_;
+ }
+ AddClient(context->peer().c_str());
+ if (load_report != nullptr) {
+ // TODO(roth): Once we provide a more standard server-side API for
+ // populating this data, use that API here.
+ context->AddTrailingMetadata("x-endpoint-load-metrics-bin",
+ load_report->SerializeAsString());
+ }
+ return TestServiceImpl::Echo(context, request, response);
+ }
+
+ int request_count() {
+ grpc::internal::MutexLock lock(&mu_);
+ return request_count_;
+ }
+
+ void ResetCounters() {
+ grpc::internal::MutexLock lock(&mu_);
+ request_count_ = 0;
+ }
+
std::set<TString> clients() {
- grpc::internal::MutexLock lock(&clients_mu_);
- return clients_;
- }
-
- void set_load_report(udpa::data::orca::v1::OrcaLoadReport* load_report) {
- grpc::internal::MutexLock lock(&mu_);
- load_report_ = load_report;
- }
-
- private:
+ grpc::internal::MutexLock lock(&clients_mu_);
+ return clients_;
+ }
+
+ void set_load_report(udpa::data::orca::v1::OrcaLoadReport* load_report) {
+ grpc::internal::MutexLock lock(&mu_);
+ load_report_ = load_report;
+ }
+
+ private:
void AddClient(const TString& client) {
- grpc::internal::MutexLock lock(&clients_mu_);
- clients_.insert(client);
- }
-
- grpc::internal::Mutex mu_;
- int request_count_ = 0;
- const udpa::data::orca::v1::OrcaLoadReport* load_report_ = nullptr;
- grpc::internal::Mutex clients_mu_;
+ grpc::internal::MutexLock lock(&clients_mu_);
+ clients_.insert(client);
+ }
+
+ grpc::internal::Mutex mu_;
+ int request_count_ = 0;
+ const udpa::data::orca::v1::OrcaLoadReport* load_report_ = nullptr;
+ grpc::internal::Mutex clients_mu_;
std::set<TString> clients_;
-};
-
-class FakeResolverResponseGeneratorWrapper {
- public:
- FakeResolverResponseGeneratorWrapper()
- : response_generator_(grpc_core::MakeRefCounted<
- grpc_core::FakeResolverResponseGenerator>()) {}
-
- FakeResolverResponseGeneratorWrapper(
+};
+
+class FakeResolverResponseGeneratorWrapper {
+ public:
+ FakeResolverResponseGeneratorWrapper()
+ : response_generator_(grpc_core::MakeRefCounted<
+ grpc_core::FakeResolverResponseGenerator>()) {}
+
+ FakeResolverResponseGeneratorWrapper(
FakeResolverResponseGeneratorWrapper&& other) noexcept {
- response_generator_ = std::move(other.response_generator_);
- }
-
+ response_generator_ = std::move(other.response_generator_);
+ }
+
void SetNextResolution(
const std::vector<int>& ports, const char* service_config_json = nullptr,
const char* attribute_key = nullptr,
std::unique_ptr<grpc_core::ServerAddress::AttributeInterface> attribute =
nullptr) {
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
response_generator_->SetResponse(BuildFakeResults(
ports, service_config_json, attribute_key, std::move(attribute)));
- }
-
- void SetNextResolutionUponError(const std::vector<int>& ports) {
- grpc_core::ExecCtx exec_ctx;
- response_generator_->SetReresolutionResponse(BuildFakeResults(ports));
- }
-
- void SetFailureOnReresolution() {
- grpc_core::ExecCtx exec_ctx;
- response_generator_->SetFailureOnReresolution();
- }
-
- grpc_core::FakeResolverResponseGenerator* Get() const {
- return response_generator_.get();
- }
-
- private:
- static grpc_core::Resolver::Result BuildFakeResults(
+ }
+
+ void SetNextResolutionUponError(const std::vector<int>& ports) {
+ grpc_core::ExecCtx exec_ctx;
+ response_generator_->SetReresolutionResponse(BuildFakeResults(ports));
+ }
+
+ void SetFailureOnReresolution() {
+ grpc_core::ExecCtx exec_ctx;
+ response_generator_->SetFailureOnReresolution();
+ }
+
+ grpc_core::FakeResolverResponseGenerator* Get() const {
+ return response_generator_.get();
+ }
+
+ private:
+ static grpc_core::Resolver::Result BuildFakeResults(
const std::vector<int>& ports, const char* service_config_json = nullptr,
const char* attribute_key = nullptr,
std::unique_ptr<grpc_core::ServerAddress::AttributeInterface> attribute =
nullptr) {
- grpc_core::Resolver::Result result;
- for (const int& port : ports) {
+ grpc_core::Resolver::Result result;
+ for (const int& port : ports) {
TString lb_uri_str = y_absl::StrCat("ipv4:127.0.0.1:", port);
grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str.c_str(), true);
- GPR_ASSERT(lb_uri != nullptr);
- grpc_resolved_address address;
- GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
+ GPR_ASSERT(lb_uri != nullptr);
+ grpc_resolved_address address;
+ GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
std::map<const char*,
std::unique_ptr<grpc_core::ServerAddress::AttributeInterface>>
attributes;
if (attribute != nullptr) {
attributes[attribute_key] = attribute->Copy();
}
- result.addresses.emplace_back(address.addr, address.len,
+ result.addresses.emplace_back(address.addr, address.len,
nullptr /* args */, std::move(attributes));
- grpc_uri_destroy(lb_uri);
- }
- if (service_config_json != nullptr) {
- result.service_config = grpc_core::ServiceConfig::Create(
+ grpc_uri_destroy(lb_uri);
+ }
+ if (service_config_json != nullptr) {
+ result.service_config = grpc_core::ServiceConfig::Create(
nullptr, service_config_json, &result.service_config_error);
- GPR_ASSERT(result.service_config != nullptr);
- }
- return result;
- }
-
- grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
- response_generator_;
-};
-
-class ClientLbEnd2endTest : public ::testing::Test {
- protected:
- ClientLbEnd2endTest()
- : server_host_("localhost"),
- kRequestMessage_("Live long and prosper."),
- creds_(new SecureChannelCredentials(
- grpc_fake_transport_security_credentials_create())) {}
-
- static void SetUpTestCase() {
- // Make the backup poller poll very frequently in order to pick up
- // updates from all the subchannels's FDs.
- GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
- }
-
- void SetUp() override { grpc_init(); }
-
- void TearDown() override {
- for (size_t i = 0; i < servers_.size(); ++i) {
- servers_[i]->Shutdown();
- }
- servers_.clear();
- creds_.reset();
- grpc_shutdown_blocking();
- }
-
- void CreateServers(size_t num_servers,
- std::vector<int> ports = std::vector<int>()) {
- servers_.clear();
- for (size_t i = 0; i < num_servers; ++i) {
- int port = 0;
- if (ports.size() == num_servers) port = ports[i];
- servers_.emplace_back(new ServerData(port));
- }
- }
-
- void StartServer(size_t index) { servers_[index]->Start(server_host_); }
-
- void StartServers(size_t num_servers,
- std::vector<int> ports = std::vector<int>()) {
- CreateServers(num_servers, std::move(ports));
- for (size_t i = 0; i < num_servers; ++i) {
- StartServer(i);
- }
- }
-
- std::vector<int> GetServersPorts(size_t start_index = 0) {
- std::vector<int> ports;
- for (size_t i = start_index; i < servers_.size(); ++i) {
- ports.push_back(servers_[i]->port_);
- }
- return ports;
- }
-
- FakeResolverResponseGeneratorWrapper BuildResolverResponseGenerator() {
- return FakeResolverResponseGeneratorWrapper();
- }
-
- std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
- const std::shared_ptr<Channel>& channel) {
- return grpc::testing::EchoTestService::NewStub(channel);
- }
-
- std::shared_ptr<Channel> BuildChannel(
+ GPR_ASSERT(result.service_config != nullptr);
+ }
+ return result;
+ }
+
+ grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
+ response_generator_;
+};
+
+class ClientLbEnd2endTest : public ::testing::Test {
+ protected:
+ ClientLbEnd2endTest()
+ : server_host_("localhost"),
+ kRequestMessage_("Live long and prosper."),
+ creds_(new SecureChannelCredentials(
+ grpc_fake_transport_security_credentials_create())) {}
+
+ static void SetUpTestCase() {
+ // Make the backup poller poll very frequently in order to pick up
+ // updates from all the subchannels's FDs.
+ GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+ }
+
+ void SetUp() override { grpc_init(); }
+
+ void TearDown() override {
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ servers_[i]->Shutdown();
+ }
+ servers_.clear();
+ creds_.reset();
+ grpc_shutdown_blocking();
+ }
+
+ void CreateServers(size_t num_servers,
+ std::vector<int> ports = std::vector<int>()) {
+ servers_.clear();
+ for (size_t i = 0; i < num_servers; ++i) {
+ int port = 0;
+ if (ports.size() == num_servers) port = ports[i];
+ servers_.emplace_back(new ServerData(port));
+ }
+ }
+
+ void StartServer(size_t index) { servers_[index]->Start(server_host_); }
+
+ void StartServers(size_t num_servers,
+ std::vector<int> ports = std::vector<int>()) {
+ CreateServers(num_servers, std::move(ports));
+ for (size_t i = 0; i < num_servers; ++i) {
+ StartServer(i);
+ }
+ }
+
+ std::vector<int> GetServersPorts(size_t start_index = 0) {
+ std::vector<int> ports;
+ for (size_t i = start_index; i < servers_.size(); ++i) {
+ ports.push_back(servers_[i]->port_);
+ }
+ return ports;
+ }
+
+ FakeResolverResponseGeneratorWrapper BuildResolverResponseGenerator() {
+ return FakeResolverResponseGeneratorWrapper();
+ }
+
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
+ const std::shared_ptr<Channel>& channel) {
+ return grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ std::shared_ptr<Channel> BuildChannel(
const TString& lb_policy_name,
- const FakeResolverResponseGeneratorWrapper& response_generator,
- ChannelArguments args = ChannelArguments()) {
- if (lb_policy_name.size() > 0) {
- args.SetLoadBalancingPolicyName(lb_policy_name);
- } // else, default to pick first
- args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
- response_generator.Get());
- return ::grpc::CreateCustomChannel("fake:///", creds_, args);
- }
-
- bool SendRpc(
- const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
- EchoResponse* response = nullptr, int timeout_ms = 1000,
- Status* result = nullptr, bool wait_for_ready = false) {
- const bool local_response = (response == nullptr);
- if (local_response) response = new EchoResponse;
- EchoRequest request;
- request.set_message(kRequestMessage_);
+ const FakeResolverResponseGeneratorWrapper& response_generator,
+ ChannelArguments args = ChannelArguments()) {
+ if (lb_policy_name.size() > 0) {
+ args.SetLoadBalancingPolicyName(lb_policy_name);
+ } // else, default to pick first
+ args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
+ response_generator.Get());
+ return ::grpc::CreateCustomChannel("fake:///", creds_, args);
+ }
+
+ bool SendRpc(
+ const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
+ EchoResponse* response = nullptr, int timeout_ms = 1000,
+ Status* result = nullptr, bool wait_for_ready = false) {
+ const bool local_response = (response == nullptr);
+ if (local_response) response = new EchoResponse;
+ EchoRequest request;
+ request.set_message(kRequestMessage_);
request.mutable_param()->set_echo_metadata(true);
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
- if (wait_for_ready) context.set_wait_for_ready(true);
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
+ if (wait_for_ready) context.set_wait_for_ready(true);
context.AddMetadata("foo", "1");
context.AddMetadata("bar", "2");
context.AddMetadata("baz", "3");
- Status status = stub->Echo(&context, request, response);
- if (result != nullptr) *result = status;
- if (local_response) delete response;
- return status.ok();
- }
-
- void CheckRpcSendOk(
- const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
- const grpc_core::DebugLocation& location, bool wait_for_ready = false) {
- EchoResponse response;
- Status status;
- const bool success =
- SendRpc(stub, &response, 2000, &status, wait_for_ready);
- ASSERT_TRUE(success) << "From " << location.file() << ":" << location.line()
- << "\n"
- << "Error: " << status.error_message() << " "
- << status.error_details();
- ASSERT_EQ(response.message(), kRequestMessage_)
- << "From " << location.file() << ":" << location.line();
- if (!success) abort();
- }
-
- void CheckRpcSendFailure(
- const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub) {
- const bool success = SendRpc(stub);
- EXPECT_FALSE(success);
- }
-
- struct ServerData {
- int port_;
- std::unique_ptr<Server> server_;
- MyTestServiceImpl service_;
- std::unique_ptr<std::thread> thread_;
- bool server_ready_ = false;
- bool started_ = false;
-
- explicit ServerData(int port = 0) {
- port_ = port > 0 ? port : 5100; // grpc_pick_unused_port_or_die();
- }
-
+ Status status = stub->Echo(&context, request, response);
+ if (result != nullptr) *result = status;
+ if (local_response) delete response;
+ return status.ok();
+ }
+
+ void CheckRpcSendOk(
+ const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
+ const grpc_core::DebugLocation& location, bool wait_for_ready = false) {
+ EchoResponse response;
+ Status status;
+ const bool success =
+ SendRpc(stub, &response, 2000, &status, wait_for_ready);
+ ASSERT_TRUE(success) << "From " << location.file() << ":" << location.line()
+ << "\n"
+ << "Error: " << status.error_message() << " "
+ << status.error_details();
+ ASSERT_EQ(response.message(), kRequestMessage_)
+ << "From " << location.file() << ":" << location.line();
+ if (!success) abort();
+ }
+
+ void CheckRpcSendFailure(
+ const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub) {
+ const bool success = SendRpc(stub);
+ EXPECT_FALSE(success);
+ }
+
+ struct ServerData {
+ int port_;
+ std::unique_ptr<Server> server_;
+ MyTestServiceImpl service_;
+ std::unique_ptr<std::thread> thread_;
+ bool server_ready_ = false;
+ bool started_ = false;
+
+ explicit ServerData(int port = 0) {
+ port_ = port > 0 ? port : 5100; // grpc_pick_unused_port_or_die();
+ }
+
void Start(const TString& server_host) {
- gpr_log(GPR_INFO, "starting server on port %d", port_);
- started_ = true;
- grpc::internal::Mutex mu;
- grpc::internal::MutexLock lock(&mu);
- grpc::internal::CondVar cond;
- thread_.reset(new std::thread(
- std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
- cond.WaitUntil(&mu, [this] { return server_ready_; });
- server_ready_ = false;
- gpr_log(GPR_INFO, "server startup complete");
- }
-
+ gpr_log(GPR_INFO, "starting server on port %d", port_);
+ started_ = true;
+ grpc::internal::Mutex mu;
+ grpc::internal::MutexLock lock(&mu);
+ grpc::internal::CondVar cond;
+ thread_.reset(new std::thread(
+ std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
+ cond.WaitUntil(&mu, [this] { return server_ready_; });
+ server_ready_ = false;
+ gpr_log(GPR_INFO, "server startup complete");
+ }
+
void Serve(const TString& server_host, grpc::internal::Mutex* mu,
- grpc::internal::CondVar* cond) {
- std::ostringstream server_address;
- server_address << server_host << ":" << port_;
- ServerBuilder builder;
- std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
- grpc_fake_transport_security_server_credentials_create()));
- builder.AddListeningPort(server_address.str(), std::move(creds));
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- grpc::internal::MutexLock lock(mu);
- server_ready_ = true;
- cond->Signal();
- }
-
- void Shutdown() {
- if (!started_) return;
- server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
- thread_->join();
- started_ = false;
- }
-
+ grpc::internal::CondVar* cond) {
+ std::ostringstream server_address;
+ server_address << server_host << ":" << port_;
+ ServerBuilder builder;
+ std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
+ grpc_fake_transport_security_server_credentials_create()));
+ builder.AddListeningPort(server_address.str(), std::move(creds));
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ grpc::internal::MutexLock lock(mu);
+ server_ready_ = true;
+ cond->Signal();
+ }
+
+ void Shutdown() {
+ if (!started_) return;
+ server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
+ thread_->join();
+ started_ = false;
+ }
+
void SetServingStatus(const TString& service, bool serving) {
- server_->GetHealthCheckService()->SetServingStatus(service, serving);
- }
- };
-
- void ResetCounters() {
- for (const auto& server : servers_) server->service_.ResetCounters();
- }
-
- void WaitForServer(
- const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
- size_t server_idx, const grpc_core::DebugLocation& location,
- bool ignore_failure = false) {
- do {
- if (ignore_failure) {
- SendRpc(stub);
- } else {
- CheckRpcSendOk(stub, location, true);
- }
- } while (servers_[server_idx]->service_.request_count() == 0);
- ResetCounters();
- }
-
- bool WaitForChannelState(
- Channel* channel, std::function<bool(grpc_connectivity_state)> predicate,
- bool try_to_connect = false, int timeout_seconds = 5) {
- const gpr_timespec deadline =
- grpc_timeout_seconds_to_deadline(timeout_seconds);
- while (true) {
- grpc_connectivity_state state = channel->GetState(try_to_connect);
- if (predicate(state)) break;
- if (!channel->WaitForStateChange(state, deadline)) return false;
- }
- return true;
- }
-
- bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
- auto predicate = [](grpc_connectivity_state state) {
- return state != GRPC_CHANNEL_READY;
- };
- return WaitForChannelState(channel, predicate, false, timeout_seconds);
- }
-
- bool WaitForChannelReady(Channel* channel, int timeout_seconds = 5) {
- auto predicate = [](grpc_connectivity_state state) {
- return state == GRPC_CHANNEL_READY;
- };
- return WaitForChannelState(channel, predicate, true, timeout_seconds);
- }
-
- bool SeenAllServers() {
- for (const auto& server : servers_) {
- if (server->service_.request_count() == 0) return false;
- }
- return true;
- }
-
- // Updates \a connection_order by appending to it the index of the newly
- // connected server. Must be called after every single RPC.
- void UpdateConnectionOrder(
- const std::vector<std::unique_ptr<ServerData>>& servers,
- std::vector<int>* connection_order) {
- for (size_t i = 0; i < servers.size(); ++i) {
- if (servers[i]->service_.request_count() == 1) {
- // Was the server index known? If not, update connection_order.
- const auto it =
- std::find(connection_order->begin(), connection_order->end(), i);
- if (it == connection_order->end()) {
- connection_order->push_back(i);
- return;
- }
- }
- }
- }
-
+ server_->GetHealthCheckService()->SetServingStatus(service, serving);
+ }
+ };
+
+ void ResetCounters() {
+ for (const auto& server : servers_) server->service_.ResetCounters();
+ }
+
+ void WaitForServer(
+ const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
+ size_t server_idx, const grpc_core::DebugLocation& location,
+ bool ignore_failure = false) {
+ do {
+ if (ignore_failure) {
+ SendRpc(stub);
+ } else {
+ CheckRpcSendOk(stub, location, true);
+ }
+ } while (servers_[server_idx]->service_.request_count() == 0);
+ ResetCounters();
+ }
+
+ bool WaitForChannelState(
+ Channel* channel, std::function<bool(grpc_connectivity_state)> predicate,
+ bool try_to_connect = false, int timeout_seconds = 5) {
+ const gpr_timespec deadline =
+ grpc_timeout_seconds_to_deadline(timeout_seconds);
+ while (true) {
+ grpc_connectivity_state state = channel->GetState(try_to_connect);
+ if (predicate(state)) break;
+ if (!channel->WaitForStateChange(state, deadline)) return false;
+ }
+ return true;
+ }
+
+ bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
+ auto predicate = [](grpc_connectivity_state state) {
+ return state != GRPC_CHANNEL_READY;
+ };
+ return WaitForChannelState(channel, predicate, false, timeout_seconds);
+ }
+
+ bool WaitForChannelReady(Channel* channel, int timeout_seconds = 5) {
+ auto predicate = [](grpc_connectivity_state state) {
+ return state == GRPC_CHANNEL_READY;
+ };
+ return WaitForChannelState(channel, predicate, true, timeout_seconds);
+ }
+
+ bool SeenAllServers() {
+ for (const auto& server : servers_) {
+ if (server->service_.request_count() == 0) return false;
+ }
+ return true;
+ }
+
+ // Updates \a connection_order by appending to it the index of the newly
+ // connected server. Must be called after every single RPC.
+ void UpdateConnectionOrder(
+ const std::vector<std::unique_ptr<ServerData>>& servers,
+ std::vector<int>* connection_order) {
+ for (size_t i = 0; i < servers.size(); ++i) {
+ if (servers[i]->service_.request_count() == 1) {
+ // Was the server index known? If not, update connection_order.
+ const auto it =
+ std::find(connection_order->begin(), connection_order->end(), i);
+ if (it == connection_order->end()) {
+ connection_order->push_back(i);
+ return;
+ }
+ }
+ }
+ }
+
const TString server_host_;
- std::vector<std::unique_ptr<ServerData>> servers_;
+ std::vector<std::unique_ptr<ServerData>> servers_;
const TString kRequestMessage_;
- std::shared_ptr<ChannelCredentials> creds_;
-};
-
-TEST_F(ClientLbEnd2endTest, ChannelStateConnectingWhenResolving) {
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("", response_generator);
- auto stub = BuildStub(channel);
- // Initial state should be IDLE.
- EXPECT_EQ(channel->GetState(false /* try_to_connect */), GRPC_CHANNEL_IDLE);
- // Tell the channel to try to connect.
- // Note that this call also returns IDLE, since the state change has
- // not yet occurred; it just gets triggered by this call.
- EXPECT_EQ(channel->GetState(true /* try_to_connect */), GRPC_CHANNEL_IDLE);
- // Now that the channel is trying to connect, we should be in state
- // CONNECTING.
- EXPECT_EQ(channel->GetState(false /* try_to_connect */),
- GRPC_CHANNEL_CONNECTING);
- // Return a resolver result, which allows the connection attempt to proceed.
- response_generator.SetNextResolution(GetServersPorts());
- // We should eventually transition into state READY.
- EXPECT_TRUE(WaitForChannelReady(channel.get()));
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirst) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel(
- "", response_generator); // test that pick first is the default.
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- for (size_t i = 0; i < servers_.size(); ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- // All requests should have gone to a single server.
- bool found = false;
- for (size_t i = 0; i < servers_.size(); ++i) {
- const int request_count = servers_[i]->service_.request_count();
- if (request_count == kNumServers) {
- found = true;
- } else {
- EXPECT_EQ(0, request_count);
- }
- }
- EXPECT_TRUE(found);
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstProcessPending) {
- StartServers(1); // Single server
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel(
- "", response_generator); // test that pick first is the default.
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution({servers_[0]->port_});
- WaitForServer(stub, 0, DEBUG_LOCATION);
- // Create a new channel and its corresponding PF LB policy, which will pick
- // the subchannels in READY state from the previous RPC against the same
- // target (even if it happened over a different channel, because subchannels
- // are globally reused). Progress should happen without any transition from
- // this READY state.
- auto second_response_generator = BuildResolverResponseGenerator();
- auto second_channel = BuildChannel("", second_response_generator);
- auto second_stub = BuildStub(second_channel);
- second_response_generator.SetNextResolution({servers_[0]->port_});
- CheckRpcSendOk(second_stub, DEBUG_LOCATION);
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstSelectsReadyAtStartup) {
- ChannelArguments args;
- constexpr int kInitialBackOffMs = 5000;
- args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
- // Create 2 servers, but start only the second one.
- std::vector<int> ports = { 5101, // grpc_pick_unused_port_or_die(),
- 5102}; // grpc_pick_unused_port_or_die()};
- CreateServers(2, ports);
- StartServer(1);
- auto response_generator1 = BuildResolverResponseGenerator();
- auto channel1 = BuildChannel("pick_first", response_generator1, args);
- auto stub1 = BuildStub(channel1);
- response_generator1.SetNextResolution(ports);
- // Wait for second server to be ready.
- WaitForServer(stub1, 1, DEBUG_LOCATION);
- // Create a second channel with the same addresses. Its PF instance
- // should immediately pick the second subchannel, since it's already
- // in READY state.
- auto response_generator2 = BuildResolverResponseGenerator();
- auto channel2 = BuildChannel("pick_first", response_generator2, args);
- response_generator2.SetNextResolution(ports);
- // Check that the channel reports READY without waiting for the
- // initial backoff.
- EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1 /* timeout_seconds */));
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstBackOffInitialReconnect) {
- ChannelArguments args;
- constexpr int kInitialBackOffMs = 100;
- args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
- const std::vector<int> ports = {5103}; // {grpc_pick_unused_port_or_die()};
- const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- // The channel won't become connected (there's no server).
- ASSERT_FALSE(channel->WaitForConnected(
- grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
- // Bring up a server on the chosen port.
- StartServers(1, ports);
- // Now it will.
- ASSERT_TRUE(channel->WaitForConnected(
- grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
- const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
- const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
- gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
- // We should have waited at least kInitialBackOffMs. We substract one to
- // account for test and precision accuracy drift.
- EXPECT_GE(waited_ms, kInitialBackOffMs - 1);
- // But not much more.
- EXPECT_GT(
- gpr_time_cmp(
- grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 1.10), t1),
- 0);
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstBackOffMinReconnect) {
- ChannelArguments args;
- constexpr int kMinReconnectBackOffMs = 1000;
- args.SetInt(GRPC_ARG_MIN_RECONNECT_BACKOFF_MS, kMinReconnectBackOffMs);
- const std::vector<int> ports = {5104}; // {grpc_pick_unused_port_or_die()};
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- // Make connection delay a 10% longer than it's willing to in order to make
- // sure we are hitting the codepath that waits for the min reconnect backoff.
- gpr_atm_rel_store(&g_connection_delay_ms, kMinReconnectBackOffMs * 1.10);
- default_client_impl = grpc_tcp_client_impl;
- grpc_set_tcp_client_impl(&delayed_connect);
- const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
- channel->WaitForConnected(
- grpc_timeout_milliseconds_to_deadline(kMinReconnectBackOffMs * 2));
- const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
- const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
- gpr_log(GPR_DEBUG, "Waited %" PRId64 " ms", waited_ms);
- // We should have waited at least kMinReconnectBackOffMs. We substract one to
- // account for test and precision accuracy drift.
- EXPECT_GE(waited_ms, kMinReconnectBackOffMs - 1);
- gpr_atm_rel_store(&g_connection_delay_ms, 0);
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstResetConnectionBackoff) {
- ChannelArguments args;
- constexpr int kInitialBackOffMs = 1000;
- args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
- const std::vector<int> ports = {5105}; // {grpc_pick_unused_port_or_die()};
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- // The channel won't become connected (there's no server).
- EXPECT_FALSE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
- // Bring up a server on the chosen port.
- StartServers(1, ports);
- const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
- // Wait for connect, but not long enough. This proves that we're
- // being throttled by initial backoff.
- EXPECT_FALSE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
- // Reset connection backoff.
- experimental::ChannelResetConnectionBackoff(channel.get());
+ std::shared_ptr<ChannelCredentials> creds_;
+};
+
+TEST_F(ClientLbEnd2endTest, ChannelStateConnectingWhenResolving) {
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("", response_generator);
+ auto stub = BuildStub(channel);
+ // Initial state should be IDLE.
+ EXPECT_EQ(channel->GetState(false /* try_to_connect */), GRPC_CHANNEL_IDLE);
+ // Tell the channel to try to connect.
+ // Note that this call also returns IDLE, since the state change has
+ // not yet occurred; it just gets triggered by this call.
+ EXPECT_EQ(channel->GetState(true /* try_to_connect */), GRPC_CHANNEL_IDLE);
+ // Now that the channel is trying to connect, we should be in state
+ // CONNECTING.
+ EXPECT_EQ(channel->GetState(false /* try_to_connect */),
+ GRPC_CHANNEL_CONNECTING);
+ // Return a resolver result, which allows the connection attempt to proceed.
+ response_generator.SetNextResolution(GetServersPorts());
+ // We should eventually transition into state READY.
+ EXPECT_TRUE(WaitForChannelReady(channel.get()));
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirst) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel(
+ "", response_generator); // test that pick first is the default.
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ // All requests should have gone to a single server.
+ bool found = false;
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ const int request_count = servers_[i]->service_.request_count();
+ if (request_count == kNumServers) {
+ found = true;
+ } else {
+ EXPECT_EQ(0, request_count);
+ }
+ }
+ EXPECT_TRUE(found);
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstProcessPending) {
+ StartServers(1); // Single server
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel(
+ "", response_generator); // test that pick first is the default.
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution({servers_[0]->port_});
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ // Create a new channel and its corresponding PF LB policy, which will pick
+ // the subchannels in READY state from the previous RPC against the same
+ // target (even if it happened over a different channel, because subchannels
+ // are globally reused). Progress should happen without any transition from
+ // this READY state.
+ auto second_response_generator = BuildResolverResponseGenerator();
+ auto second_channel = BuildChannel("", second_response_generator);
+ auto second_stub = BuildStub(second_channel);
+ second_response_generator.SetNextResolution({servers_[0]->port_});
+ CheckRpcSendOk(second_stub, DEBUG_LOCATION);
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstSelectsReadyAtStartup) {
+ ChannelArguments args;
+ constexpr int kInitialBackOffMs = 5000;
+ args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
+ // Create 2 servers, but start only the second one.
+ std::vector<int> ports = { 5101, // grpc_pick_unused_port_or_die(),
+ 5102}; // grpc_pick_unused_port_or_die()};
+ CreateServers(2, ports);
+ StartServer(1);
+ auto response_generator1 = BuildResolverResponseGenerator();
+ auto channel1 = BuildChannel("pick_first", response_generator1, args);
+ auto stub1 = BuildStub(channel1);
+ response_generator1.SetNextResolution(ports);
+ // Wait for second server to be ready.
+ WaitForServer(stub1, 1, DEBUG_LOCATION);
+ // Create a second channel with the same addresses. Its PF instance
+ // should immediately pick the second subchannel, since it's already
+ // in READY state.
+ auto response_generator2 = BuildResolverResponseGenerator();
+ auto channel2 = BuildChannel("pick_first", response_generator2, args);
+ response_generator2.SetNextResolution(ports);
+ // Check that the channel reports READY without waiting for the
+ // initial backoff.
+ EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1 /* timeout_seconds */));
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstBackOffInitialReconnect) {
+ ChannelArguments args;
+ constexpr int kInitialBackOffMs = 100;
+ args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
+ const std::vector<int> ports = {5103}; // {grpc_pick_unused_port_or_die()};
+ const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ // The channel won't become connected (there's no server).
+ ASSERT_FALSE(channel->WaitForConnected(
+ grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
+ // Bring up a server on the chosen port.
+ StartServers(1, ports);
+ // Now it will.
+ ASSERT_TRUE(channel->WaitForConnected(
+ grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
+ const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
+ const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
+ gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
+ // We should have waited at least kInitialBackOffMs. We substract one to
+ // account for test and precision accuracy drift.
+ EXPECT_GE(waited_ms, kInitialBackOffMs - 1);
+ // But not much more.
+ EXPECT_GT(
+ gpr_time_cmp(
+ grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 1.10), t1),
+ 0);
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstBackOffMinReconnect) {
+ ChannelArguments args;
+ constexpr int kMinReconnectBackOffMs = 1000;
+ args.SetInt(GRPC_ARG_MIN_RECONNECT_BACKOFF_MS, kMinReconnectBackOffMs);
+ const std::vector<int> ports = {5104}; // {grpc_pick_unused_port_or_die()};
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ // Make connection delay a 10% longer than it's willing to in order to make
+ // sure we are hitting the codepath that waits for the min reconnect backoff.
+ gpr_atm_rel_store(&g_connection_delay_ms, kMinReconnectBackOffMs * 1.10);
+ default_client_impl = grpc_tcp_client_impl;
+ grpc_set_tcp_client_impl(&delayed_connect);
+ const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
+ channel->WaitForConnected(
+ grpc_timeout_milliseconds_to_deadline(kMinReconnectBackOffMs * 2));
+ const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
+ const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
+ gpr_log(GPR_DEBUG, "Waited %" PRId64 " ms", waited_ms);
+ // We should have waited at least kMinReconnectBackOffMs. We substract one to
+ // account for test and precision accuracy drift.
+ EXPECT_GE(waited_ms, kMinReconnectBackOffMs - 1);
+ gpr_atm_rel_store(&g_connection_delay_ms, 0);
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstResetConnectionBackoff) {
+ ChannelArguments args;
+ constexpr int kInitialBackOffMs = 1000;
+ args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
+ const std::vector<int> ports = {5105}; // {grpc_pick_unused_port_or_die()};
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ // The channel won't become connected (there's no server).
+ EXPECT_FALSE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
+ // Bring up a server on the chosen port.
+ StartServers(1, ports);
+ const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
+ // Wait for connect, but not long enough. This proves that we're
+ // being throttled by initial backoff.
+ EXPECT_FALSE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
+ // Reset connection backoff.
+ experimental::ChannelResetConnectionBackoff(channel.get());
// Wait for connect. Should happen as soon as the client connects to
// the newly started server, which should be before the initial
// backoff timeout elapses.
- EXPECT_TRUE(
+ EXPECT_TRUE(
channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(20)));
- const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
- const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
- gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
- // We should have waited less than kInitialBackOffMs.
- EXPECT_LT(waited_ms, kInitialBackOffMs);
-}
-
-TEST_F(ClientLbEnd2endTest,
- PickFirstResetConnectionBackoffNextAttemptStartsImmediately) {
- ChannelArguments args;
- constexpr int kInitialBackOffMs = 1000;
- args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
- const std::vector<int> ports = {5106}; // {grpc_pick_unused_port_or_die()};
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- // Wait for connect, which should fail ~immediately, because the server
- // is not up.
- gpr_log(GPR_INFO, "=== INITIAL CONNECTION ATTEMPT");
- EXPECT_FALSE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
- // Reset connection backoff.
- // Note that the time at which the third attempt will be started is
- // actually computed at this point, so we record the start time here.
- gpr_log(GPR_INFO, "=== RESETTING BACKOFF");
- const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
- experimental::ChannelResetConnectionBackoff(channel.get());
- // Trigger a second connection attempt. This should also fail
- // ~immediately, but the retry should be scheduled for
- // kInitialBackOffMs instead of applying the multiplier.
- gpr_log(GPR_INFO, "=== POLLING FOR SECOND CONNECTION ATTEMPT");
- EXPECT_FALSE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
- // Bring up a server on the chosen port.
- gpr_log(GPR_INFO, "=== STARTING BACKEND");
- StartServers(1, ports);
- // Wait for connect. Should happen within kInitialBackOffMs.
- // Give an extra 100ms to account for the time spent in the second and
- // third connection attempts themselves (since what we really want to
- // measure is the time between the two). As long as this is less than
- // the 1.6x increase we would see if the backoff state was not reset
- // properly, the test is still proving that the backoff was reset.
- constexpr int kWaitMs = kInitialBackOffMs + 100;
- gpr_log(GPR_INFO, "=== POLLING FOR THIRD CONNECTION ATTEMPT");
- EXPECT_TRUE(channel->WaitForConnected(
- grpc_timeout_milliseconds_to_deadline(kWaitMs)));
- const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
- const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
- gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
- EXPECT_LT(waited_ms, kWaitMs);
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstUpdates) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator);
- auto stub = BuildStub(channel);
-
- std::vector<int> ports;
-
- // Perform one RPC against the first server.
- ports.emplace_back(servers_[0]->port_);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** SET [0] *******");
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(servers_[0]->service_.request_count(), 1);
-
- // An empty update will result in the channel going into TRANSIENT_FAILURE.
- ports.clear();
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** SET none *******");
- grpc_connectivity_state channel_state;
- do {
- channel_state = channel->GetState(true /* try to connect */);
- } while (channel_state == GRPC_CHANNEL_READY);
- ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
- servers_[0]->service_.ResetCounters();
-
- // Next update introduces servers_[1], making the channel recover.
- ports.clear();
- ports.emplace_back(servers_[1]->port_);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** SET [1] *******");
- WaitForServer(stub, 1, DEBUG_LOCATION);
- EXPECT_EQ(servers_[0]->service_.request_count(), 0);
-
- // And again for servers_[2]
- ports.clear();
- ports.emplace_back(servers_[2]->port_);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** SET [2] *******");
- WaitForServer(stub, 2, DEBUG_LOCATION);
- EXPECT_EQ(servers_[0]->service_.request_count(), 0);
- EXPECT_EQ(servers_[1]->service_.request_count(), 0);
-
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstUpdateSuperset) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator);
- auto stub = BuildStub(channel);
-
- std::vector<int> ports;
-
- // Perform one RPC against the first server.
- ports.emplace_back(servers_[0]->port_);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** SET [0] *******");
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(servers_[0]->service_.request_count(), 1);
- servers_[0]->service_.ResetCounters();
-
- // Send and superset update
- ports.clear();
- ports.emplace_back(servers_[1]->port_);
- ports.emplace_back(servers_[0]->port_);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** SET superset *******");
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- // We stick to the previously connected server.
- WaitForServer(stub, 0, DEBUG_LOCATION);
- EXPECT_EQ(0, servers_[1]->service_.request_count());
-
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstGlobalSubchannelPool) {
- // Start one server.
- const int kNumServers = 1;
- StartServers(kNumServers);
- std::vector<int> ports = GetServersPorts();
- // Create two channels that (by default) use the global subchannel pool.
- auto response_generator1 = BuildResolverResponseGenerator();
- auto channel1 = BuildChannel("pick_first", response_generator1);
- auto stub1 = BuildStub(channel1);
- response_generator1.SetNextResolution(ports);
- auto response_generator2 = BuildResolverResponseGenerator();
- auto channel2 = BuildChannel("pick_first", response_generator2);
- auto stub2 = BuildStub(channel2);
- response_generator2.SetNextResolution(ports);
- WaitForServer(stub1, 0, DEBUG_LOCATION);
- // Send one RPC on each channel.
- CheckRpcSendOk(stub1, DEBUG_LOCATION);
- CheckRpcSendOk(stub2, DEBUG_LOCATION);
- // The server receives two requests.
- EXPECT_EQ(2, servers_[0]->service_.request_count());
- // The two requests are from the same client port, because the two channels
- // share subchannels via the global subchannel pool.
- EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstLocalSubchannelPool) {
- // Start one server.
- const int kNumServers = 1;
- StartServers(kNumServers);
- std::vector<int> ports = GetServersPorts();
- // Create two channels that use local subchannel pool.
- ChannelArguments args;
- args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
- auto response_generator1 = BuildResolverResponseGenerator();
- auto channel1 = BuildChannel("pick_first", response_generator1, args);
- auto stub1 = BuildStub(channel1);
- response_generator1.SetNextResolution(ports);
- auto response_generator2 = BuildResolverResponseGenerator();
- auto channel2 = BuildChannel("pick_first", response_generator2, args);
- auto stub2 = BuildStub(channel2);
- response_generator2.SetNextResolution(ports);
- WaitForServer(stub1, 0, DEBUG_LOCATION);
- // Send one RPC on each channel.
- CheckRpcSendOk(stub1, DEBUG_LOCATION);
- CheckRpcSendOk(stub2, DEBUG_LOCATION);
- // The server receives two requests.
- EXPECT_EQ(2, servers_[0]->service_.request_count());
- // The two requests are from two client ports, because the two channels didn't
- // share subchannels with each other.
- EXPECT_EQ(2UL, servers_[0]->service_.clients().size());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstManyUpdates) {
- const int kNumUpdates = 1000;
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator);
- auto stub = BuildStub(channel);
- std::vector<int> ports = GetServersPorts();
- for (size_t i = 0; i < kNumUpdates; ++i) {
- std::shuffle(ports.begin(), ports.end(),
- std::mt19937(std::random_device()()));
- response_generator.SetNextResolution(ports);
- // We should re-enter core at the end of the loop to give the resolution
- // setting closure a chance to run.
- if ((i + 1) % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstReresolutionNoSelected) {
- // Prepare the ports for up servers and down servers.
- const int kNumServers = 3;
- const int kNumAliveServers = 1;
- StartServers(kNumAliveServers);
- std::vector<int> alive_ports, dead_ports;
- for (size_t i = 0; i < kNumServers; ++i) {
- if (i < kNumAliveServers) {
- alive_ports.emplace_back(servers_[i]->port_);
- } else {
- dead_ports.emplace_back(5107 + i);
- // dead_ports.emplace_back(grpc_pick_unused_port_or_die());
- }
- }
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator);
- auto stub = BuildStub(channel);
- // The initial resolution only contains dead ports. There won't be any
- // selected subchannel. Re-resolution will return the same result.
- response_generator.SetNextResolution(dead_ports);
- gpr_log(GPR_INFO, "****** INITIAL RESOLUTION SET *******");
- for (size_t i = 0; i < 10; ++i) CheckRpcSendFailure(stub);
- // Set a re-resolution result that contains reachable ports, so that the
- // pick_first LB policy can recover soon.
- response_generator.SetNextResolutionUponError(alive_ports);
- gpr_log(GPR_INFO, "****** RE-RESOLUTION SET *******");
- WaitForServer(stub, 0, DEBUG_LOCATION, true /* ignore_failure */);
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(servers_[0]->service_.request_count(), 1);
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstReconnectWithoutNewResolverResult) {
- std::vector<int> ports = {5110}; // {grpc_pick_unused_port_or_die()};
- StartServers(1, ports);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
- WaitForServer(stub, 0, DEBUG_LOCATION);
- gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
- servers_[0]->Shutdown();
- EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
- gpr_log(GPR_INFO, "****** RESTARTING SERVER ******");
- StartServers(1, ports);
- WaitForServer(stub, 0, DEBUG_LOCATION);
-}
-
-TEST_F(ClientLbEnd2endTest,
- PickFirstReconnectWithoutNewResolverResultStartsFromTopOfList) {
- std::vector<int> ports = {5111, // grpc_pick_unused_port_or_die(),
- 5112}; // grpc_pick_unused_port_or_die()};
- CreateServers(2, ports);
- StartServer(1);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("pick_first", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
- WaitForServer(stub, 1, DEBUG_LOCATION);
- gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
- servers_[1]->Shutdown();
- EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
- gpr_log(GPR_INFO, "****** STARTING BOTH SERVERS ******");
- StartServers(2, ports);
- WaitForServer(stub, 0, DEBUG_LOCATION);
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstCheckStateBeforeStartWatch) {
- std::vector<int> ports = {5113}; // {grpc_pick_unused_port_or_die()};
- StartServers(1, ports);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel_1 = BuildChannel("pick_first", response_generator);
- auto stub_1 = BuildStub(channel_1);
- response_generator.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 1 *******");
- WaitForServer(stub_1, 0, DEBUG_LOCATION);
- gpr_log(GPR_INFO, "****** CHANNEL 1 CONNECTED *******");
- servers_[0]->Shutdown();
- // Channel 1 will receive a re-resolution containing the same server. It will
- // create a new subchannel and hold a ref to it.
- StartServers(1, ports);
- gpr_log(GPR_INFO, "****** SERVER RESTARTED *******");
- auto response_generator_2 = BuildResolverResponseGenerator();
- auto channel_2 = BuildChannel("pick_first", response_generator_2);
- auto stub_2 = BuildStub(channel_2);
- response_generator_2.SetNextResolution(ports);
- gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 2 *******");
- WaitForServer(stub_2, 0, DEBUG_LOCATION, true);
- gpr_log(GPR_INFO, "****** CHANNEL 2 CONNECTED *******");
- servers_[0]->Shutdown();
- // Wait until the disconnection has triggered the connectivity notification.
- // Otherwise, the subchannel may be picked for next call but will fail soon.
- EXPECT_TRUE(WaitForChannelNotReady(channel_2.get()));
- // Channel 2 will also receive a re-resolution containing the same server.
- // Both channels will ref the same subchannel that failed.
- StartServers(1, ports);
- gpr_log(GPR_INFO, "****** SERVER RESTARTED AGAIN *******");
- gpr_log(GPR_INFO, "****** CHANNEL 2 STARTING A CALL *******");
- // The first call after the server restart will succeed.
- CheckRpcSendOk(stub_2, DEBUG_LOCATION);
- gpr_log(GPR_INFO, "****** CHANNEL 2 FINISHED A CALL *******");
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel_1->GetLoadBalancingPolicyName());
- // Check LB policy name for the channel.
- EXPECT_EQ("pick_first", channel_2->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstIdleOnDisconnect) {
- // Start server, send RPC, and make sure channel is READY.
- const int kNumServers = 1;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel =
- BuildChannel("", response_generator); // pick_first is the default.
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
- // Stop server. Channel should go into state IDLE.
- response_generator.SetFailureOnReresolution();
- servers_[0]->Shutdown();
- EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
- servers_.clear();
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstPendingUpdateAndSelectedSubchannelFails) {
- auto response_generator = BuildResolverResponseGenerator();
- auto channel =
- BuildChannel("", response_generator); // pick_first is the default.
- auto stub = BuildStub(channel);
- // Create a number of servers, but only start 1 of them.
- CreateServers(10);
- StartServer(0);
- // Initially resolve to first server and make sure it connects.
- gpr_log(GPR_INFO, "Phase 1: Connect to first server.");
- response_generator.SetNextResolution({servers_[0]->port_});
- CheckRpcSendOk(stub, DEBUG_LOCATION, true /* wait_for_ready */);
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
- // Send a resolution update with the remaining servers, none of which are
- // running yet, so the update will stay pending. Note that it's important
- // to have multiple servers here, or else the test will be flaky; with only
- // one server, the pending subchannel list has already gone into
- // TRANSIENT_FAILURE due to hitting the end of the list by the time we
- // check the state.
- gpr_log(GPR_INFO,
- "Phase 2: Resolver update pointing to remaining "
- "(not started) servers.");
- response_generator.SetNextResolution(GetServersPorts(1 /* start_index */));
- // RPCs will continue to be sent to the first server.
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- // Now stop the first server, so that the current subchannel list
- // fails. This should cause us to immediately swap over to the
- // pending list, even though it's not yet connected. The state should
- // be set to CONNECTING, since that's what the pending subchannel list
- // was doing when we swapped over.
- gpr_log(GPR_INFO, "Phase 3: Stopping first server.");
- servers_[0]->Shutdown();
- WaitForChannelNotReady(channel.get());
- // TODO(roth): This should always return CONNECTING, but it's flaky
- // between that and TRANSIENT_FAILURE. I suspect that this problem
- // will go away once we move the backoff code out of the subchannel
- // and into the LB policies.
- EXPECT_THAT(channel->GetState(false),
- ::testing::AnyOf(GRPC_CHANNEL_CONNECTING,
- GRPC_CHANNEL_TRANSIENT_FAILURE));
- // Now start the second server.
- gpr_log(GPR_INFO, "Phase 4: Starting second server.");
- StartServer(1);
- // The channel should go to READY state and RPCs should go to the
- // second server.
- WaitForChannelReady(channel.get());
- WaitForServer(stub, 1, DEBUG_LOCATION, true /* ignore_failure */);
-}
-
-TEST_F(ClientLbEnd2endTest, PickFirstStaysIdleUponEmptyUpdate) {
- // Start server, send RPC, and make sure channel is READY.
- const int kNumServers = 1;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel =
- BuildChannel("", response_generator); // pick_first is the default.
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
- // Stop server. Channel should go into state IDLE.
- servers_[0]->Shutdown();
- EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
- // Now send resolver update that includes no addresses. Channel
- // should stay in state IDLE.
- response_generator.SetNextResolution({});
- EXPECT_FALSE(channel->WaitForStateChange(
- GRPC_CHANNEL_IDLE, grpc_timeout_seconds_to_deadline(3)));
- // Now bring the backend back up and send a non-empty resolver update,
- // and then try to send an RPC. Channel should go back into state READY.
- StartServer(0);
- response_generator.SetNextResolution(GetServersPorts());
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobin) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- // Wait until all backends are ready.
- do {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- } while (!SeenAllServers());
- ResetCounters();
- // "Sync" to the end of the list. Next sequence of picks will start at the
- // first server (index 0).
- WaitForServer(stub, servers_.size() - 1, DEBUG_LOCATION);
- std::vector<int> connection_order;
- for (size_t i = 0; i < servers_.size(); ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- UpdateConnectionOrder(servers_, &connection_order);
- }
- // Backends should be iterated over in the order in which the addresses were
- // given.
- const auto expected = std::vector<int>{0, 1, 2};
- EXPECT_EQ(expected, connection_order);
- // Check LB policy name for the channel.
- EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinProcessPending) {
- StartServers(1); // Single server
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution({servers_[0]->port_});
- WaitForServer(stub, 0, DEBUG_LOCATION);
- // Create a new channel and its corresponding RR LB policy, which will pick
- // the subchannels in READY state from the previous RPC against the same
- // target (even if it happened over a different channel, because subchannels
- // are globally reused). Progress should happen without any transition from
- // this READY state.
- auto second_response_generator = BuildResolverResponseGenerator();
- auto second_channel = BuildChannel("round_robin", second_response_generator);
- auto second_stub = BuildStub(second_channel);
- second_response_generator.SetNextResolution({servers_[0]->port_});
- CheckRpcSendOk(second_stub, DEBUG_LOCATION);
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinUpdates) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- std::vector<int> ports;
- // Start with a single server.
- gpr_log(GPR_INFO, "*** FIRST BACKEND ***");
- ports.emplace_back(servers_[0]->port_);
- response_generator.SetNextResolution(ports);
- WaitForServer(stub, 0, DEBUG_LOCATION);
- // Send RPCs. They should all go servers_[0]
- for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(10, servers_[0]->service_.request_count());
- EXPECT_EQ(0, servers_[1]->service_.request_count());
- EXPECT_EQ(0, servers_[2]->service_.request_count());
- servers_[0]->service_.ResetCounters();
- // And now for the second server.
- gpr_log(GPR_INFO, "*** SECOND BACKEND ***");
- ports.clear();
- ports.emplace_back(servers_[1]->port_);
- response_generator.SetNextResolution(ports);
- // Wait until update has been processed, as signaled by the second backend
- // receiving a request.
- EXPECT_EQ(0, servers_[1]->service_.request_count());
- WaitForServer(stub, 1, DEBUG_LOCATION);
- for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(0, servers_[0]->service_.request_count());
- EXPECT_EQ(10, servers_[1]->service_.request_count());
- EXPECT_EQ(0, servers_[2]->service_.request_count());
- servers_[1]->service_.ResetCounters();
- // ... and for the last server.
- gpr_log(GPR_INFO, "*** THIRD BACKEND ***");
- ports.clear();
- ports.emplace_back(servers_[2]->port_);
- response_generator.SetNextResolution(ports);
- WaitForServer(stub, 2, DEBUG_LOCATION);
- for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(0, servers_[0]->service_.request_count());
- EXPECT_EQ(0, servers_[1]->service_.request_count());
- EXPECT_EQ(10, servers_[2]->service_.request_count());
- servers_[2]->service_.ResetCounters();
- // Back to all servers.
- gpr_log(GPR_INFO, "*** ALL BACKENDS ***");
- ports.clear();
- ports.emplace_back(servers_[0]->port_);
- ports.emplace_back(servers_[1]->port_);
- ports.emplace_back(servers_[2]->port_);
- response_generator.SetNextResolution(ports);
- WaitForServer(stub, 0, DEBUG_LOCATION);
- WaitForServer(stub, 1, DEBUG_LOCATION);
- WaitForServer(stub, 2, DEBUG_LOCATION);
- // Send three RPCs, one per server.
- for (size_t i = 0; i < 3; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(1, servers_[0]->service_.request_count());
- EXPECT_EQ(1, servers_[1]->service_.request_count());
- EXPECT_EQ(1, servers_[2]->service_.request_count());
- // An empty update will result in the channel going into TRANSIENT_FAILURE.
- gpr_log(GPR_INFO, "*** NO BACKENDS ***");
- ports.clear();
- response_generator.SetNextResolution(ports);
- grpc_connectivity_state channel_state;
- do {
- channel_state = channel->GetState(true /* try to connect */);
- } while (channel_state == GRPC_CHANNEL_READY);
- ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
- servers_[0]->service_.ResetCounters();
- // Next update introduces servers_[1], making the channel recover.
- gpr_log(GPR_INFO, "*** BACK TO SECOND BACKEND ***");
- ports.clear();
- ports.emplace_back(servers_[1]->port_);
- response_generator.SetNextResolution(ports);
- WaitForServer(stub, 1, DEBUG_LOCATION);
- channel_state = channel->GetState(false /* try to connect */);
- ASSERT_EQ(channel_state, GRPC_CHANNEL_READY);
- // Check LB policy name for the channel.
- EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinUpdateInError) {
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- std::vector<int> ports;
- // Start with a single server.
- ports.emplace_back(servers_[0]->port_);
- response_generator.SetNextResolution(ports);
- WaitForServer(stub, 0, DEBUG_LOCATION);
- // Send RPCs. They should all go to servers_[0]
- for (size_t i = 0; i < 10; ++i) SendRpc(stub);
- EXPECT_EQ(10, servers_[0]->service_.request_count());
- EXPECT_EQ(0, servers_[1]->service_.request_count());
- EXPECT_EQ(0, servers_[2]->service_.request_count());
- servers_[0]->service_.ResetCounters();
- // Shutdown one of the servers to be sent in the update.
- servers_[1]->Shutdown();
- ports.emplace_back(servers_[1]->port_);
- ports.emplace_back(servers_[2]->port_);
- response_generator.SetNextResolution(ports);
- WaitForServer(stub, 0, DEBUG_LOCATION);
- WaitForServer(stub, 2, DEBUG_LOCATION);
- // Send three RPCs, one per server.
- for (size_t i = 0; i < kNumServers; ++i) SendRpc(stub);
- // The server in shutdown shouldn't receive any.
- EXPECT_EQ(0, servers_[1]->service_.request_count());
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinManyUpdates) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- std::vector<int> ports = GetServersPorts();
- for (size_t i = 0; i < 1000; ++i) {
- std::shuffle(ports.begin(), ports.end(),
- std::mt19937(std::random_device()()));
- response_generator.SetNextResolution(ports);
- if (i % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- // Check LB policy name for the channel.
- EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinConcurrentUpdates) {
- // TODO(dgq): replicate the way internal testing exercises the concurrent
- // update provisions of RR.
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinReresolve) {
- // Start servers and send one RPC per server.
- const int kNumServers = 3;
- std::vector<int> first_ports;
- std::vector<int> second_ports;
- first_ports.reserve(kNumServers);
- for (int i = 0; i < kNumServers; ++i) {
- // first_ports.push_back(grpc_pick_unused_port_or_die());
- first_ports.push_back(5114 + i);
- }
- second_ports.reserve(kNumServers);
- for (int i = 0; i < kNumServers; ++i) {
- // second_ports.push_back(grpc_pick_unused_port_or_die());
- second_ports.push_back(5117 + i);
- }
- StartServers(kNumServers, first_ports);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(first_ports);
- // Send a number of RPCs, which succeed.
- for (size_t i = 0; i < 100; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- // Kill all servers
- gpr_log(GPR_INFO, "****** ABOUT TO KILL SERVERS *******");
- for (size_t i = 0; i < servers_.size(); ++i) {
- servers_[i]->Shutdown();
- }
- gpr_log(GPR_INFO, "****** SERVERS KILLED *******");
- gpr_log(GPR_INFO, "****** SENDING DOOMED REQUESTS *******");
- // Client requests should fail. Send enough to tickle all subchannels.
- for (size_t i = 0; i < servers_.size(); ++i) CheckRpcSendFailure(stub);
- gpr_log(GPR_INFO, "****** DOOMED REQUESTS SENT *******");
- // Bring servers back up on a different set of ports. We need to do this to be
- // sure that the eventual success is *not* due to subchannel reconnection
- // attempts and that an actual re-resolution has happened as a result of the
- // RR policy going into transient failure when all its subchannels become
- // unavailable (in transient failure as well).
- gpr_log(GPR_INFO, "****** RESTARTING SERVERS *******");
- StartServers(kNumServers, second_ports);
- // Don't notify of the update. Wait for the LB policy's re-resolution to
- // "pull" the new ports.
- response_generator.SetNextResolutionUponError(second_ports);
- gpr_log(GPR_INFO, "****** SERVERS RESTARTED *******");
- gpr_log(GPR_INFO, "****** SENDING REQUEST TO SUCCEED *******");
- // Client request should eventually (but still fairly soon) succeed.
- const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- while (gpr_time_cmp(deadline, now) > 0) {
- if (SendRpc(stub)) break;
- now = gpr_now(GPR_CLOCK_MONOTONIC);
- }
- ASSERT_GT(gpr_time_cmp(deadline, now), 0);
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinTransientFailure) {
- // Start servers and create channel. Channel should go to READY state.
- const int kNumServers = 3;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- EXPECT_TRUE(WaitForChannelReady(channel.get()));
- // Now kill the servers. The channel should transition to TRANSIENT_FAILURE.
- // TODO(roth): This test should ideally check that even when the
- // subchannels are in state CONNECTING for an extended period of time,
- // we will still report TRANSIENT_FAILURE. Unfortunately, we don't
- // currently have a good way to get a subchannel to report CONNECTING
- // for a long period of time, since the servers in this test framework
- // are on the loopback interface, which will immediately return a
- // "Connection refused" error, so the subchannels will only be in
- // CONNECTING state very briefly. When we have time, see if we can
- // find a way to fix this.
- for (size_t i = 0; i < servers_.size(); ++i) {
- servers_[i]->Shutdown();
- }
- auto predicate = [](grpc_connectivity_state state) {
- return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
- };
- EXPECT_TRUE(WaitForChannelState(channel.get(), predicate));
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinTransientFailureAtStartup) {
- // Create channel and return servers that don't exist. Channel should
- // quickly transition into TRANSIENT_FAILURE.
- // TODO(roth): This test should ideally check that even when the
- // subchannels are in state CONNECTING for an extended period of time,
- // we will still report TRANSIENT_FAILURE. Unfortunately, we don't
- // currently have a good way to get a subchannel to report CONNECTING
- // for a long period of time, since the servers in this test framework
- // are on the loopback interface, which will immediately return a
- // "Connection refused" error, so the subchannels will only be in
- // CONNECTING state very briefly. When we have time, see if we can
- // find a way to fix this.
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution({
- grpc_pick_unused_port_or_die(),
- grpc_pick_unused_port_or_die(),
- grpc_pick_unused_port_or_die(),
- });
- for (size_t i = 0; i < servers_.size(); ++i) {
- servers_[i]->Shutdown();
- }
- auto predicate = [](grpc_connectivity_state state) {
- return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
- };
- EXPECT_TRUE(WaitForChannelState(channel.get(), predicate, true));
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinSingleReconnect) {
- const int kNumServers = 3;
- StartServers(kNumServers);
- const auto ports = GetServersPorts();
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(ports);
- for (size_t i = 0; i < kNumServers; ++i) {
- WaitForServer(stub, i, DEBUG_LOCATION);
- }
- for (size_t i = 0; i < servers_.size(); ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(1, servers_[i]->service_.request_count()) << "for backend #" << i;
- }
- // One request should have gone to each server.
- for (size_t i = 0; i < servers_.size(); ++i) {
- EXPECT_EQ(1, servers_[i]->service_.request_count());
- }
- const auto pre_death = servers_[0]->service_.request_count();
- // Kill the first server.
- servers_[0]->Shutdown();
- // Client request still succeed. May need retrying if RR had returned a pick
- // before noticing the change in the server's connectivity.
- while (!SendRpc(stub)) {
- } // Retry until success.
- // Send a bunch of RPCs that should succeed.
- for (int i = 0; i < 10 * kNumServers; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- const auto post_death = servers_[0]->service_.request_count();
- // No requests have gone to the deceased server.
- EXPECT_EQ(pre_death, post_death);
- // Bring the first server back up.
- StartServer(0);
- // Requests should start arriving at the first server either right away (if
- // the server managed to start before the RR policy retried the subchannel) or
- // after the subchannel retry delay otherwise (RR's subchannel retried before
- // the server was fully back up).
- WaitForServer(stub, 0, DEBUG_LOCATION);
-}
-
-// If health checking is required by client but health checking service
-// is not running on the server, the channel should be treated as healthy.
-TEST_F(ClientLbEnd2endTest,
- RoundRobinServersHealthCheckingUnimplementedTreatedAsHealthy) {
- StartServers(1); // Single server
- ChannelArguments args;
- args.SetServiceConfigJSON(
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name\"}}");
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution({servers_[0]->port_});
- EXPECT_TRUE(WaitForChannelReady(channel.get()));
- CheckRpcSendOk(stub, DEBUG_LOCATION);
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthChecking) {
- EnableDefaultHealthCheckService(true);
- // Start servers.
- const int kNumServers = 3;
- StartServers(kNumServers);
- ChannelArguments args;
- args.SetServiceConfigJSON(
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name\"}}");
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- // Channel should not become READY, because health checks should be failing.
- gpr_log(GPR_INFO,
- "*** initial state: unknown health check service name for "
- "all servers");
- EXPECT_FALSE(WaitForChannelReady(channel.get(), 1));
- // Now set one of the servers to be healthy.
- // The channel should become healthy and all requests should go to
- // the healthy server.
- gpr_log(GPR_INFO, "*** server 0 healthy");
- servers_[0]->SetServingStatus("health_check_service_name", true);
- EXPECT_TRUE(WaitForChannelReady(channel.get()));
- for (int i = 0; i < 10; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- EXPECT_EQ(10, servers_[0]->service_.request_count());
- EXPECT_EQ(0, servers_[1]->service_.request_count());
- EXPECT_EQ(0, servers_[2]->service_.request_count());
- // Now set a second server to be healthy.
- gpr_log(GPR_INFO, "*** server 2 healthy");
- servers_[2]->SetServingStatus("health_check_service_name", true);
- WaitForServer(stub, 2, DEBUG_LOCATION);
- for (int i = 0; i < 10; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- EXPECT_EQ(5, servers_[0]->service_.request_count());
- EXPECT_EQ(0, servers_[1]->service_.request_count());
- EXPECT_EQ(5, servers_[2]->service_.request_count());
- // Now set the remaining server to be healthy.
- gpr_log(GPR_INFO, "*** server 1 healthy");
- servers_[1]->SetServingStatus("health_check_service_name", true);
- WaitForServer(stub, 1, DEBUG_LOCATION);
- for (int i = 0; i < 9; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- EXPECT_EQ(3, servers_[0]->service_.request_count());
- EXPECT_EQ(3, servers_[1]->service_.request_count());
- EXPECT_EQ(3, servers_[2]->service_.request_count());
- // Now set one server to be unhealthy again. Then wait until the
- // unhealthiness has hit the client. We know that the client will see
- // this when we send kNumServers requests and one of the remaining servers
- // sees two of the requests.
- gpr_log(GPR_INFO, "*** server 0 unhealthy");
- servers_[0]->SetServingStatus("health_check_service_name", false);
- do {
- ResetCounters();
- for (int i = 0; i < kNumServers; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- } while (servers_[1]->service_.request_count() != 2 &&
- servers_[2]->service_.request_count() != 2);
- // Now set the remaining two servers to be unhealthy. Make sure the
- // channel leaves READY state and that RPCs fail.
- gpr_log(GPR_INFO, "*** all servers unhealthy");
- servers_[1]->SetServingStatus("health_check_service_name", false);
- servers_[2]->SetServingStatus("health_check_service_name", false);
- EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
- CheckRpcSendFailure(stub);
- // Clean up.
- EnableDefaultHealthCheckService(false);
-}
-
-TEST_F(ClientLbEnd2endTest,
- RoundRobinWithHealthCheckingHandlesSubchannelFailure) {
- EnableDefaultHealthCheckService(true);
- // Start servers.
- const int kNumServers = 3;
- StartServers(kNumServers);
- servers_[0]->SetServingStatus("health_check_service_name", true);
- servers_[1]->SetServingStatus("health_check_service_name", true);
- servers_[2]->SetServingStatus("health_check_service_name", true);
- ChannelArguments args;
- args.SetServiceConfigJSON(
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name\"}}");
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- WaitForServer(stub, 0, DEBUG_LOCATION);
- // Stop server 0 and send a new resolver result to ensure that RR
- // checks each subchannel's state.
- servers_[0]->Shutdown();
- response_generator.SetNextResolution(GetServersPorts());
- // Send a bunch more RPCs.
- for (size_t i = 0; i < 100; i++) {
- SendRpc(stub);
- }
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingInhibitPerChannel) {
- EnableDefaultHealthCheckService(true);
- // Start server.
- const int kNumServers = 1;
- StartServers(kNumServers);
- // Create a channel with health-checking enabled.
- ChannelArguments args;
- args.SetServiceConfigJSON(
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name\"}}");
- auto response_generator1 = BuildResolverResponseGenerator();
- auto channel1 = BuildChannel("round_robin", response_generator1, args);
- auto stub1 = BuildStub(channel1);
- std::vector<int> ports = GetServersPorts();
- response_generator1.SetNextResolution(ports);
- // Create a channel with health checking enabled but inhibited.
- args.SetInt(GRPC_ARG_INHIBIT_HEALTH_CHECKING, 1);
- auto response_generator2 = BuildResolverResponseGenerator();
- auto channel2 = BuildChannel("round_robin", response_generator2, args);
- auto stub2 = BuildStub(channel2);
- response_generator2.SetNextResolution(ports);
- // First channel should not become READY, because health checks should be
- // failing.
- EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
- CheckRpcSendFailure(stub1);
- // Second channel should be READY.
- EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
- CheckRpcSendOk(stub2, DEBUG_LOCATION);
- // Enable health checks on the backend and wait for channel 1 to succeed.
- servers_[0]->SetServingStatus("health_check_service_name", true);
- CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
- // Check that we created only one subchannel to the backend.
- EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
- // Clean up.
- EnableDefaultHealthCheckService(false);
-}
-
-TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingServiceNamePerChannel) {
- EnableDefaultHealthCheckService(true);
- // Start server.
- const int kNumServers = 1;
- StartServers(kNumServers);
- // Create a channel with health-checking enabled.
- ChannelArguments args;
- args.SetServiceConfigJSON(
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name\"}}");
- auto response_generator1 = BuildResolverResponseGenerator();
- auto channel1 = BuildChannel("round_robin", response_generator1, args);
- auto stub1 = BuildStub(channel1);
- std::vector<int> ports = GetServersPorts();
- response_generator1.SetNextResolution(ports);
- // Create a channel with health-checking enabled with a different
- // service name.
- ChannelArguments args2;
- args2.SetServiceConfigJSON(
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name2\"}}");
- auto response_generator2 = BuildResolverResponseGenerator();
- auto channel2 = BuildChannel("round_robin", response_generator2, args2);
- auto stub2 = BuildStub(channel2);
- response_generator2.SetNextResolution(ports);
- // Allow health checks from channel 2 to succeed.
- servers_[0]->SetServingStatus("health_check_service_name2", true);
- // First channel should not become READY, because health checks should be
- // failing.
- EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
- CheckRpcSendFailure(stub1);
- // Second channel should be READY.
- EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
- CheckRpcSendOk(stub2, DEBUG_LOCATION);
- // Enable health checks for channel 1 and wait for it to succeed.
- servers_[0]->SetServingStatus("health_check_service_name", true);
- CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
- // Check that we created only one subchannel to the backend.
- EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
- // Clean up.
- EnableDefaultHealthCheckService(false);
-}
-
-TEST_F(ClientLbEnd2endTest,
- RoundRobinWithHealthCheckingServiceNameChangesAfterSubchannelsCreated) {
- EnableDefaultHealthCheckService(true);
- // Start server.
- const int kNumServers = 1;
- StartServers(kNumServers);
- // Create a channel with health-checking enabled.
- const char* kServiceConfigJson =
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name\"}}";
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("round_robin", response_generator);
- auto stub = BuildStub(channel);
- std::vector<int> ports = GetServersPorts();
- response_generator.SetNextResolution(ports, kServiceConfigJson);
- servers_[0]->SetServingStatus("health_check_service_name", true);
- EXPECT_TRUE(WaitForChannelReady(channel.get(), 1 /* timeout_seconds */));
- // Send an update on the channel to change it to use a health checking
- // service name that is not being reported as healthy.
- const char* kServiceConfigJson2 =
- "{\"healthCheckConfig\": "
- "{\"serviceName\": \"health_check_service_name2\"}}";
- response_generator.SetNextResolution(ports, kServiceConfigJson2);
- EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
- // Clean up.
- EnableDefaultHealthCheckService(false);
-}
-
-TEST_F(ClientLbEnd2endTest, ChannelIdleness) {
- // Start server.
- const int kNumServers = 1;
- StartServers(kNumServers);
- // Set max idle time and build the channel.
- ChannelArguments args;
- args.SetInt(GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS, 1000);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel = BuildChannel("", response_generator, args);
- auto stub = BuildStub(channel);
- // The initial channel state should be IDLE.
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
- // After sending RPC, channel state should be READY.
- response_generator.SetNextResolution(GetServersPorts());
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
- // After a period time not using the channel, the channel state should switch
- // to IDLE.
- gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(1200));
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
- // Sending a new RPC should awake the IDLE channel.
- response_generator.SetNextResolution(GetServersPorts());
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
-}
-
+ const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
+ const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
+ gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
+ // We should have waited less than kInitialBackOffMs.
+ EXPECT_LT(waited_ms, kInitialBackOffMs);
+}
+
+TEST_F(ClientLbEnd2endTest,
+ PickFirstResetConnectionBackoffNextAttemptStartsImmediately) {
+ ChannelArguments args;
+ constexpr int kInitialBackOffMs = 1000;
+ args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
+ const std::vector<int> ports = {5106}; // {grpc_pick_unused_port_or_die()};
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ // Wait for connect, which should fail ~immediately, because the server
+ // is not up.
+ gpr_log(GPR_INFO, "=== INITIAL CONNECTION ATTEMPT");
+ EXPECT_FALSE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
+ // Reset connection backoff.
+ // Note that the time at which the third attempt will be started is
+ // actually computed at this point, so we record the start time here.
+ gpr_log(GPR_INFO, "=== RESETTING BACKOFF");
+ const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
+ experimental::ChannelResetConnectionBackoff(channel.get());
+ // Trigger a second connection attempt. This should also fail
+ // ~immediately, but the retry should be scheduled for
+ // kInitialBackOffMs instead of applying the multiplier.
+ gpr_log(GPR_INFO, "=== POLLING FOR SECOND CONNECTION ATTEMPT");
+ EXPECT_FALSE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
+ // Bring up a server on the chosen port.
+ gpr_log(GPR_INFO, "=== STARTING BACKEND");
+ StartServers(1, ports);
+ // Wait for connect. Should happen within kInitialBackOffMs.
+ // Give an extra 100ms to account for the time spent in the second and
+ // third connection attempts themselves (since what we really want to
+ // measure is the time between the two). As long as this is less than
+ // the 1.6x increase we would see if the backoff state was not reset
+ // properly, the test is still proving that the backoff was reset.
+ constexpr int kWaitMs = kInitialBackOffMs + 100;
+ gpr_log(GPR_INFO, "=== POLLING FOR THIRD CONNECTION ATTEMPT");
+ EXPECT_TRUE(channel->WaitForConnected(
+ grpc_timeout_milliseconds_to_deadline(kWaitMs)));
+ const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
+ const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
+ gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
+ EXPECT_LT(waited_ms, kWaitMs);
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstUpdates) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator);
+ auto stub = BuildStub(channel);
+
+ std::vector<int> ports;
+
+ // Perform one RPC against the first server.
+ ports.emplace_back(servers_[0]->port_);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** SET [0] *******");
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(servers_[0]->service_.request_count(), 1);
+
+ // An empty update will result in the channel going into TRANSIENT_FAILURE.
+ ports.clear();
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** SET none *******");
+ grpc_connectivity_state channel_state;
+ do {
+ channel_state = channel->GetState(true /* try to connect */);
+ } while (channel_state == GRPC_CHANNEL_READY);
+ ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
+ servers_[0]->service_.ResetCounters();
+
+ // Next update introduces servers_[1], making the channel recover.
+ ports.clear();
+ ports.emplace_back(servers_[1]->port_);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** SET [1] *******");
+ WaitForServer(stub, 1, DEBUG_LOCATION);
+ EXPECT_EQ(servers_[0]->service_.request_count(), 0);
+
+ // And again for servers_[2]
+ ports.clear();
+ ports.emplace_back(servers_[2]->port_);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** SET [2] *******");
+ WaitForServer(stub, 2, DEBUG_LOCATION);
+ EXPECT_EQ(servers_[0]->service_.request_count(), 0);
+ EXPECT_EQ(servers_[1]->service_.request_count(), 0);
+
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstUpdateSuperset) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator);
+ auto stub = BuildStub(channel);
+
+ std::vector<int> ports;
+
+ // Perform one RPC against the first server.
+ ports.emplace_back(servers_[0]->port_);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** SET [0] *******");
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(servers_[0]->service_.request_count(), 1);
+ servers_[0]->service_.ResetCounters();
+
+ // Send and superset update
+ ports.clear();
+ ports.emplace_back(servers_[1]->port_);
+ ports.emplace_back(servers_[0]->port_);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** SET superset *******");
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ // We stick to the previously connected server.
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstGlobalSubchannelPool) {
+ // Start one server.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ std::vector<int> ports = GetServersPorts();
+ // Create two channels that (by default) use the global subchannel pool.
+ auto response_generator1 = BuildResolverResponseGenerator();
+ auto channel1 = BuildChannel("pick_first", response_generator1);
+ auto stub1 = BuildStub(channel1);
+ response_generator1.SetNextResolution(ports);
+ auto response_generator2 = BuildResolverResponseGenerator();
+ auto channel2 = BuildChannel("pick_first", response_generator2);
+ auto stub2 = BuildStub(channel2);
+ response_generator2.SetNextResolution(ports);
+ WaitForServer(stub1, 0, DEBUG_LOCATION);
+ // Send one RPC on each channel.
+ CheckRpcSendOk(stub1, DEBUG_LOCATION);
+ CheckRpcSendOk(stub2, DEBUG_LOCATION);
+ // The server receives two requests.
+ EXPECT_EQ(2, servers_[0]->service_.request_count());
+ // The two requests are from the same client port, because the two channels
+ // share subchannels via the global subchannel pool.
+ EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstLocalSubchannelPool) {
+ // Start one server.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ std::vector<int> ports = GetServersPorts();
+ // Create two channels that use local subchannel pool.
+ ChannelArguments args;
+ args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
+ auto response_generator1 = BuildResolverResponseGenerator();
+ auto channel1 = BuildChannel("pick_first", response_generator1, args);
+ auto stub1 = BuildStub(channel1);
+ response_generator1.SetNextResolution(ports);
+ auto response_generator2 = BuildResolverResponseGenerator();
+ auto channel2 = BuildChannel("pick_first", response_generator2, args);
+ auto stub2 = BuildStub(channel2);
+ response_generator2.SetNextResolution(ports);
+ WaitForServer(stub1, 0, DEBUG_LOCATION);
+ // Send one RPC on each channel.
+ CheckRpcSendOk(stub1, DEBUG_LOCATION);
+ CheckRpcSendOk(stub2, DEBUG_LOCATION);
+ // The server receives two requests.
+ EXPECT_EQ(2, servers_[0]->service_.request_count());
+ // The two requests are from two client ports, because the two channels didn't
+ // share subchannels with each other.
+ EXPECT_EQ(2UL, servers_[0]->service_.clients().size());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstManyUpdates) {
+ const int kNumUpdates = 1000;
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator);
+ auto stub = BuildStub(channel);
+ std::vector<int> ports = GetServersPorts();
+ for (size_t i = 0; i < kNumUpdates; ++i) {
+ std::shuffle(ports.begin(), ports.end(),
+ std::mt19937(std::random_device()()));
+ response_generator.SetNextResolution(ports);
+ // We should re-enter core at the end of the loop to give the resolution
+ // setting closure a chance to run.
+ if ((i + 1) % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstReresolutionNoSelected) {
+ // Prepare the ports for up servers and down servers.
+ const int kNumServers = 3;
+ const int kNumAliveServers = 1;
+ StartServers(kNumAliveServers);
+ std::vector<int> alive_ports, dead_ports;
+ for (size_t i = 0; i < kNumServers; ++i) {
+ if (i < kNumAliveServers) {
+ alive_ports.emplace_back(servers_[i]->port_);
+ } else {
+ dead_ports.emplace_back(5107 + i);
+ // dead_ports.emplace_back(grpc_pick_unused_port_or_die());
+ }
+ }
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator);
+ auto stub = BuildStub(channel);
+ // The initial resolution only contains dead ports. There won't be any
+ // selected subchannel. Re-resolution will return the same result.
+ response_generator.SetNextResolution(dead_ports);
+ gpr_log(GPR_INFO, "****** INITIAL RESOLUTION SET *******");
+ for (size_t i = 0; i < 10; ++i) CheckRpcSendFailure(stub);
+ // Set a re-resolution result that contains reachable ports, so that the
+ // pick_first LB policy can recover soon.
+ response_generator.SetNextResolutionUponError(alive_ports);
+ gpr_log(GPR_INFO, "****** RE-RESOLUTION SET *******");
+ WaitForServer(stub, 0, DEBUG_LOCATION, true /* ignore_failure */);
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(servers_[0]->service_.request_count(), 1);
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstReconnectWithoutNewResolverResult) {
+ std::vector<int> ports = {5110}; // {grpc_pick_unused_port_or_die()};
+ StartServers(1, ports);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
+ servers_[0]->Shutdown();
+ EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
+ gpr_log(GPR_INFO, "****** RESTARTING SERVER ******");
+ StartServers(1, ports);
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+}
+
+TEST_F(ClientLbEnd2endTest,
+ PickFirstReconnectWithoutNewResolverResultStartsFromTopOfList) {
+ std::vector<int> ports = {5111, // grpc_pick_unused_port_or_die(),
+ 5112}; // grpc_pick_unused_port_or_die()};
+ CreateServers(2, ports);
+ StartServer(1);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("pick_first", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
+ WaitForServer(stub, 1, DEBUG_LOCATION);
+ gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
+ servers_[1]->Shutdown();
+ EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
+ gpr_log(GPR_INFO, "****** STARTING BOTH SERVERS ******");
+ StartServers(2, ports);
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstCheckStateBeforeStartWatch) {
+ std::vector<int> ports = {5113}; // {grpc_pick_unused_port_or_die()};
+ StartServers(1, ports);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel_1 = BuildChannel("pick_first", response_generator);
+ auto stub_1 = BuildStub(channel_1);
+ response_generator.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 1 *******");
+ WaitForServer(stub_1, 0, DEBUG_LOCATION);
+ gpr_log(GPR_INFO, "****** CHANNEL 1 CONNECTED *******");
+ servers_[0]->Shutdown();
+ // Channel 1 will receive a re-resolution containing the same server. It will
+ // create a new subchannel and hold a ref to it.
+ StartServers(1, ports);
+ gpr_log(GPR_INFO, "****** SERVER RESTARTED *******");
+ auto response_generator_2 = BuildResolverResponseGenerator();
+ auto channel_2 = BuildChannel("pick_first", response_generator_2);
+ auto stub_2 = BuildStub(channel_2);
+ response_generator_2.SetNextResolution(ports);
+ gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 2 *******");
+ WaitForServer(stub_2, 0, DEBUG_LOCATION, true);
+ gpr_log(GPR_INFO, "****** CHANNEL 2 CONNECTED *******");
+ servers_[0]->Shutdown();
+ // Wait until the disconnection has triggered the connectivity notification.
+ // Otherwise, the subchannel may be picked for next call but will fail soon.
+ EXPECT_TRUE(WaitForChannelNotReady(channel_2.get()));
+ // Channel 2 will also receive a re-resolution containing the same server.
+ // Both channels will ref the same subchannel that failed.
+ StartServers(1, ports);
+ gpr_log(GPR_INFO, "****** SERVER RESTARTED AGAIN *******");
+ gpr_log(GPR_INFO, "****** CHANNEL 2 STARTING A CALL *******");
+ // The first call after the server restart will succeed.
+ CheckRpcSendOk(stub_2, DEBUG_LOCATION);
+ gpr_log(GPR_INFO, "****** CHANNEL 2 FINISHED A CALL *******");
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel_1->GetLoadBalancingPolicyName());
+ // Check LB policy name for the channel.
+ EXPECT_EQ("pick_first", channel_2->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstIdleOnDisconnect) {
+ // Start server, send RPC, and make sure channel is READY.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel =
+ BuildChannel("", response_generator); // pick_first is the default.
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
+ // Stop server. Channel should go into state IDLE.
+ response_generator.SetFailureOnReresolution();
+ servers_[0]->Shutdown();
+ EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
+ servers_.clear();
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstPendingUpdateAndSelectedSubchannelFails) {
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel =
+ BuildChannel("", response_generator); // pick_first is the default.
+ auto stub = BuildStub(channel);
+ // Create a number of servers, but only start 1 of them.
+ CreateServers(10);
+ StartServer(0);
+ // Initially resolve to first server and make sure it connects.
+ gpr_log(GPR_INFO, "Phase 1: Connect to first server.");
+ response_generator.SetNextResolution({servers_[0]->port_});
+ CheckRpcSendOk(stub, DEBUG_LOCATION, true /* wait_for_ready */);
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
+ // Send a resolution update with the remaining servers, none of which are
+ // running yet, so the update will stay pending. Note that it's important
+ // to have multiple servers here, or else the test will be flaky; with only
+ // one server, the pending subchannel list has already gone into
+ // TRANSIENT_FAILURE due to hitting the end of the list by the time we
+ // check the state.
+ gpr_log(GPR_INFO,
+ "Phase 2: Resolver update pointing to remaining "
+ "(not started) servers.");
+ response_generator.SetNextResolution(GetServersPorts(1 /* start_index */));
+ // RPCs will continue to be sent to the first server.
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ // Now stop the first server, so that the current subchannel list
+ // fails. This should cause us to immediately swap over to the
+ // pending list, even though it's not yet connected. The state should
+ // be set to CONNECTING, since that's what the pending subchannel list
+ // was doing when we swapped over.
+ gpr_log(GPR_INFO, "Phase 3: Stopping first server.");
+ servers_[0]->Shutdown();
+ WaitForChannelNotReady(channel.get());
+ // TODO(roth): This should always return CONNECTING, but it's flaky
+ // between that and TRANSIENT_FAILURE. I suspect that this problem
+ // will go away once we move the backoff code out of the subchannel
+ // and into the LB policies.
+ EXPECT_THAT(channel->GetState(false),
+ ::testing::AnyOf(GRPC_CHANNEL_CONNECTING,
+ GRPC_CHANNEL_TRANSIENT_FAILURE));
+ // Now start the second server.
+ gpr_log(GPR_INFO, "Phase 4: Starting second server.");
+ StartServer(1);
+ // The channel should go to READY state and RPCs should go to the
+ // second server.
+ WaitForChannelReady(channel.get());
+ WaitForServer(stub, 1, DEBUG_LOCATION, true /* ignore_failure */);
+}
+
+TEST_F(ClientLbEnd2endTest, PickFirstStaysIdleUponEmptyUpdate) {
+ // Start server, send RPC, and make sure channel is READY.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel =
+ BuildChannel("", response_generator); // pick_first is the default.
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
+ // Stop server. Channel should go into state IDLE.
+ servers_[0]->Shutdown();
+ EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
+ // Now send resolver update that includes no addresses. Channel
+ // should stay in state IDLE.
+ response_generator.SetNextResolution({});
+ EXPECT_FALSE(channel->WaitForStateChange(
+ GRPC_CHANNEL_IDLE, grpc_timeout_seconds_to_deadline(3)));
+ // Now bring the backend back up and send a non-empty resolver update,
+ // and then try to send an RPC. Channel should go back into state READY.
+ StartServer(0);
+ response_generator.SetNextResolution(GetServersPorts());
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobin) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ // Wait until all backends are ready.
+ do {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ } while (!SeenAllServers());
+ ResetCounters();
+ // "Sync" to the end of the list. Next sequence of picks will start at the
+ // first server (index 0).
+ WaitForServer(stub, servers_.size() - 1, DEBUG_LOCATION);
+ std::vector<int> connection_order;
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ UpdateConnectionOrder(servers_, &connection_order);
+ }
+ // Backends should be iterated over in the order in which the addresses were
+ // given.
+ const auto expected = std::vector<int>{0, 1, 2};
+ EXPECT_EQ(expected, connection_order);
+ // Check LB policy name for the channel.
+ EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinProcessPending) {
+ StartServers(1); // Single server
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution({servers_[0]->port_});
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ // Create a new channel and its corresponding RR LB policy, which will pick
+ // the subchannels in READY state from the previous RPC against the same
+ // target (even if it happened over a different channel, because subchannels
+ // are globally reused). Progress should happen without any transition from
+ // this READY state.
+ auto second_response_generator = BuildResolverResponseGenerator();
+ auto second_channel = BuildChannel("round_robin", second_response_generator);
+ auto second_stub = BuildStub(second_channel);
+ second_response_generator.SetNextResolution({servers_[0]->port_});
+ CheckRpcSendOk(second_stub, DEBUG_LOCATION);
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinUpdates) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ std::vector<int> ports;
+ // Start with a single server.
+ gpr_log(GPR_INFO, "*** FIRST BACKEND ***");
+ ports.emplace_back(servers_[0]->port_);
+ response_generator.SetNextResolution(ports);
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ // Send RPCs. They should all go servers_[0]
+ for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(10, servers_[0]->service_.request_count());
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+ EXPECT_EQ(0, servers_[2]->service_.request_count());
+ servers_[0]->service_.ResetCounters();
+ // And now for the second server.
+ gpr_log(GPR_INFO, "*** SECOND BACKEND ***");
+ ports.clear();
+ ports.emplace_back(servers_[1]->port_);
+ response_generator.SetNextResolution(ports);
+ // Wait until update has been processed, as signaled by the second backend
+ // receiving a request.
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+ WaitForServer(stub, 1, DEBUG_LOCATION);
+ for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(0, servers_[0]->service_.request_count());
+ EXPECT_EQ(10, servers_[1]->service_.request_count());
+ EXPECT_EQ(0, servers_[2]->service_.request_count());
+ servers_[1]->service_.ResetCounters();
+ // ... and for the last server.
+ gpr_log(GPR_INFO, "*** THIRD BACKEND ***");
+ ports.clear();
+ ports.emplace_back(servers_[2]->port_);
+ response_generator.SetNextResolution(ports);
+ WaitForServer(stub, 2, DEBUG_LOCATION);
+ for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(0, servers_[0]->service_.request_count());
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+ EXPECT_EQ(10, servers_[2]->service_.request_count());
+ servers_[2]->service_.ResetCounters();
+ // Back to all servers.
+ gpr_log(GPR_INFO, "*** ALL BACKENDS ***");
+ ports.clear();
+ ports.emplace_back(servers_[0]->port_);
+ ports.emplace_back(servers_[1]->port_);
+ ports.emplace_back(servers_[2]->port_);
+ response_generator.SetNextResolution(ports);
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ WaitForServer(stub, 1, DEBUG_LOCATION);
+ WaitForServer(stub, 2, DEBUG_LOCATION);
+ // Send three RPCs, one per server.
+ for (size_t i = 0; i < 3; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(1, servers_[0]->service_.request_count());
+ EXPECT_EQ(1, servers_[1]->service_.request_count());
+ EXPECT_EQ(1, servers_[2]->service_.request_count());
+ // An empty update will result in the channel going into TRANSIENT_FAILURE.
+ gpr_log(GPR_INFO, "*** NO BACKENDS ***");
+ ports.clear();
+ response_generator.SetNextResolution(ports);
+ grpc_connectivity_state channel_state;
+ do {
+ channel_state = channel->GetState(true /* try to connect */);
+ } while (channel_state == GRPC_CHANNEL_READY);
+ ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
+ servers_[0]->service_.ResetCounters();
+ // Next update introduces servers_[1], making the channel recover.
+ gpr_log(GPR_INFO, "*** BACK TO SECOND BACKEND ***");
+ ports.clear();
+ ports.emplace_back(servers_[1]->port_);
+ response_generator.SetNextResolution(ports);
+ WaitForServer(stub, 1, DEBUG_LOCATION);
+ channel_state = channel->GetState(false /* try to connect */);
+ ASSERT_EQ(channel_state, GRPC_CHANNEL_READY);
+ // Check LB policy name for the channel.
+ EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinUpdateInError) {
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ std::vector<int> ports;
+ // Start with a single server.
+ ports.emplace_back(servers_[0]->port_);
+ response_generator.SetNextResolution(ports);
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ // Send RPCs. They should all go to servers_[0]
+ for (size_t i = 0; i < 10; ++i) SendRpc(stub);
+ EXPECT_EQ(10, servers_[0]->service_.request_count());
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+ EXPECT_EQ(0, servers_[2]->service_.request_count());
+ servers_[0]->service_.ResetCounters();
+ // Shutdown one of the servers to be sent in the update.
+ servers_[1]->Shutdown();
+ ports.emplace_back(servers_[1]->port_);
+ ports.emplace_back(servers_[2]->port_);
+ response_generator.SetNextResolution(ports);
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ WaitForServer(stub, 2, DEBUG_LOCATION);
+ // Send three RPCs, one per server.
+ for (size_t i = 0; i < kNumServers; ++i) SendRpc(stub);
+ // The server in shutdown shouldn't receive any.
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinManyUpdates) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ std::vector<int> ports = GetServersPorts();
+ for (size_t i = 0; i < 1000; ++i) {
+ std::shuffle(ports.begin(), ports.end(),
+ std::mt19937(std::random_device()()));
+ response_generator.SetNextResolution(ports);
+ if (i % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ // Check LB policy name for the channel.
+ EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinConcurrentUpdates) {
+ // TODO(dgq): replicate the way internal testing exercises the concurrent
+ // update provisions of RR.
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinReresolve) {
+ // Start servers and send one RPC per server.
+ const int kNumServers = 3;
+ std::vector<int> first_ports;
+ std::vector<int> second_ports;
+ first_ports.reserve(kNumServers);
+ for (int i = 0; i < kNumServers; ++i) {
+ // first_ports.push_back(grpc_pick_unused_port_or_die());
+ first_ports.push_back(5114 + i);
+ }
+ second_ports.reserve(kNumServers);
+ for (int i = 0; i < kNumServers; ++i) {
+ // second_ports.push_back(grpc_pick_unused_port_or_die());
+ second_ports.push_back(5117 + i);
+ }
+ StartServers(kNumServers, first_ports);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(first_ports);
+ // Send a number of RPCs, which succeed.
+ for (size_t i = 0; i < 100; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ // Kill all servers
+ gpr_log(GPR_INFO, "****** ABOUT TO KILL SERVERS *******");
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ servers_[i]->Shutdown();
+ }
+ gpr_log(GPR_INFO, "****** SERVERS KILLED *******");
+ gpr_log(GPR_INFO, "****** SENDING DOOMED REQUESTS *******");
+ // Client requests should fail. Send enough to tickle all subchannels.
+ for (size_t i = 0; i < servers_.size(); ++i) CheckRpcSendFailure(stub);
+ gpr_log(GPR_INFO, "****** DOOMED REQUESTS SENT *******");
+ // Bring servers back up on a different set of ports. We need to do this to be
+ // sure that the eventual success is *not* due to subchannel reconnection
+ // attempts and that an actual re-resolution has happened as a result of the
+ // RR policy going into transient failure when all its subchannels become
+ // unavailable (in transient failure as well).
+ gpr_log(GPR_INFO, "****** RESTARTING SERVERS *******");
+ StartServers(kNumServers, second_ports);
+ // Don't notify of the update. Wait for the LB policy's re-resolution to
+ // "pull" the new ports.
+ response_generator.SetNextResolutionUponError(second_ports);
+ gpr_log(GPR_INFO, "****** SERVERS RESTARTED *******");
+ gpr_log(GPR_INFO, "****** SENDING REQUEST TO SUCCEED *******");
+ // Client request should eventually (but still fairly soon) succeed.
+ const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ while (gpr_time_cmp(deadline, now) > 0) {
+ if (SendRpc(stub)) break;
+ now = gpr_now(GPR_CLOCK_MONOTONIC);
+ }
+ ASSERT_GT(gpr_time_cmp(deadline, now), 0);
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinTransientFailure) {
+ // Start servers and create channel. Channel should go to READY state.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ EXPECT_TRUE(WaitForChannelReady(channel.get()));
+ // Now kill the servers. The channel should transition to TRANSIENT_FAILURE.
+ // TODO(roth): This test should ideally check that even when the
+ // subchannels are in state CONNECTING for an extended period of time,
+ // we will still report TRANSIENT_FAILURE. Unfortunately, we don't
+ // currently have a good way to get a subchannel to report CONNECTING
+ // for a long period of time, since the servers in this test framework
+ // are on the loopback interface, which will immediately return a
+ // "Connection refused" error, so the subchannels will only be in
+ // CONNECTING state very briefly. When we have time, see if we can
+ // find a way to fix this.
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ servers_[i]->Shutdown();
+ }
+ auto predicate = [](grpc_connectivity_state state) {
+ return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
+ };
+ EXPECT_TRUE(WaitForChannelState(channel.get(), predicate));
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinTransientFailureAtStartup) {
+ // Create channel and return servers that don't exist. Channel should
+ // quickly transition into TRANSIENT_FAILURE.
+ // TODO(roth): This test should ideally check that even when the
+ // subchannels are in state CONNECTING for an extended period of time,
+ // we will still report TRANSIENT_FAILURE. Unfortunately, we don't
+ // currently have a good way to get a subchannel to report CONNECTING
+ // for a long period of time, since the servers in this test framework
+ // are on the loopback interface, which will immediately return a
+ // "Connection refused" error, so the subchannels will only be in
+ // CONNECTING state very briefly. When we have time, see if we can
+ // find a way to fix this.
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution({
+ grpc_pick_unused_port_or_die(),
+ grpc_pick_unused_port_or_die(),
+ grpc_pick_unused_port_or_die(),
+ });
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ servers_[i]->Shutdown();
+ }
+ auto predicate = [](grpc_connectivity_state state) {
+ return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
+ };
+ EXPECT_TRUE(WaitForChannelState(channel.get(), predicate, true));
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinSingleReconnect) {
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ const auto ports = GetServersPorts();
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(ports);
+ for (size_t i = 0; i < kNumServers; ++i) {
+ WaitForServer(stub, i, DEBUG_LOCATION);
+ }
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(1, servers_[i]->service_.request_count()) << "for backend #" << i;
+ }
+ // One request should have gone to each server.
+ for (size_t i = 0; i < servers_.size(); ++i) {
+ EXPECT_EQ(1, servers_[i]->service_.request_count());
+ }
+ const auto pre_death = servers_[0]->service_.request_count();
+ // Kill the first server.
+ servers_[0]->Shutdown();
+ // Client request still succeed. May need retrying if RR had returned a pick
+ // before noticing the change in the server's connectivity.
+ while (!SendRpc(stub)) {
+ } // Retry until success.
+ // Send a bunch of RPCs that should succeed.
+ for (int i = 0; i < 10 * kNumServers; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ const auto post_death = servers_[0]->service_.request_count();
+ // No requests have gone to the deceased server.
+ EXPECT_EQ(pre_death, post_death);
+ // Bring the first server back up.
+ StartServer(0);
+ // Requests should start arriving at the first server either right away (if
+ // the server managed to start before the RR policy retried the subchannel) or
+ // after the subchannel retry delay otherwise (RR's subchannel retried before
+ // the server was fully back up).
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+}
+
+// If health checking is required by client but health checking service
+// is not running on the server, the channel should be treated as healthy.
+TEST_F(ClientLbEnd2endTest,
+ RoundRobinServersHealthCheckingUnimplementedTreatedAsHealthy) {
+ StartServers(1); // Single server
+ ChannelArguments args;
+ args.SetServiceConfigJSON(
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name\"}}");
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution({servers_[0]->port_});
+ EXPECT_TRUE(WaitForChannelReady(channel.get()));
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthChecking) {
+ EnableDefaultHealthCheckService(true);
+ // Start servers.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ ChannelArguments args;
+ args.SetServiceConfigJSON(
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name\"}}");
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ // Channel should not become READY, because health checks should be failing.
+ gpr_log(GPR_INFO,
+ "*** initial state: unknown health check service name for "
+ "all servers");
+ EXPECT_FALSE(WaitForChannelReady(channel.get(), 1));
+ // Now set one of the servers to be healthy.
+ // The channel should become healthy and all requests should go to
+ // the healthy server.
+ gpr_log(GPR_INFO, "*** server 0 healthy");
+ servers_[0]->SetServingStatus("health_check_service_name", true);
+ EXPECT_TRUE(WaitForChannelReady(channel.get()));
+ for (int i = 0; i < 10; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ EXPECT_EQ(10, servers_[0]->service_.request_count());
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+ EXPECT_EQ(0, servers_[2]->service_.request_count());
+ // Now set a second server to be healthy.
+ gpr_log(GPR_INFO, "*** server 2 healthy");
+ servers_[2]->SetServingStatus("health_check_service_name", true);
+ WaitForServer(stub, 2, DEBUG_LOCATION);
+ for (int i = 0; i < 10; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ EXPECT_EQ(5, servers_[0]->service_.request_count());
+ EXPECT_EQ(0, servers_[1]->service_.request_count());
+ EXPECT_EQ(5, servers_[2]->service_.request_count());
+ // Now set the remaining server to be healthy.
+ gpr_log(GPR_INFO, "*** server 1 healthy");
+ servers_[1]->SetServingStatus("health_check_service_name", true);
+ WaitForServer(stub, 1, DEBUG_LOCATION);
+ for (int i = 0; i < 9; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ EXPECT_EQ(3, servers_[0]->service_.request_count());
+ EXPECT_EQ(3, servers_[1]->service_.request_count());
+ EXPECT_EQ(3, servers_[2]->service_.request_count());
+ // Now set one server to be unhealthy again. Then wait until the
+ // unhealthiness has hit the client. We know that the client will see
+ // this when we send kNumServers requests and one of the remaining servers
+ // sees two of the requests.
+ gpr_log(GPR_INFO, "*** server 0 unhealthy");
+ servers_[0]->SetServingStatus("health_check_service_name", false);
+ do {
+ ResetCounters();
+ for (int i = 0; i < kNumServers; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ } while (servers_[1]->service_.request_count() != 2 &&
+ servers_[2]->service_.request_count() != 2);
+ // Now set the remaining two servers to be unhealthy. Make sure the
+ // channel leaves READY state and that RPCs fail.
+ gpr_log(GPR_INFO, "*** all servers unhealthy");
+ servers_[1]->SetServingStatus("health_check_service_name", false);
+ servers_[2]->SetServingStatus("health_check_service_name", false);
+ EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
+ CheckRpcSendFailure(stub);
+ // Clean up.
+ EnableDefaultHealthCheckService(false);
+}
+
+TEST_F(ClientLbEnd2endTest,
+ RoundRobinWithHealthCheckingHandlesSubchannelFailure) {
+ EnableDefaultHealthCheckService(true);
+ // Start servers.
+ const int kNumServers = 3;
+ StartServers(kNumServers);
+ servers_[0]->SetServingStatus("health_check_service_name", true);
+ servers_[1]->SetServingStatus("health_check_service_name", true);
+ servers_[2]->SetServingStatus("health_check_service_name", true);
+ ChannelArguments args;
+ args.SetServiceConfigJSON(
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name\"}}");
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ WaitForServer(stub, 0, DEBUG_LOCATION);
+ // Stop server 0 and send a new resolver result to ensure that RR
+ // checks each subchannel's state.
+ servers_[0]->Shutdown();
+ response_generator.SetNextResolution(GetServersPorts());
+ // Send a bunch more RPCs.
+ for (size_t i = 0; i < 100; i++) {
+ SendRpc(stub);
+ }
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingInhibitPerChannel) {
+ EnableDefaultHealthCheckService(true);
+ // Start server.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ // Create a channel with health-checking enabled.
+ ChannelArguments args;
+ args.SetServiceConfigJSON(
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name\"}}");
+ auto response_generator1 = BuildResolverResponseGenerator();
+ auto channel1 = BuildChannel("round_robin", response_generator1, args);
+ auto stub1 = BuildStub(channel1);
+ std::vector<int> ports = GetServersPorts();
+ response_generator1.SetNextResolution(ports);
+ // Create a channel with health checking enabled but inhibited.
+ args.SetInt(GRPC_ARG_INHIBIT_HEALTH_CHECKING, 1);
+ auto response_generator2 = BuildResolverResponseGenerator();
+ auto channel2 = BuildChannel("round_robin", response_generator2, args);
+ auto stub2 = BuildStub(channel2);
+ response_generator2.SetNextResolution(ports);
+ // First channel should not become READY, because health checks should be
+ // failing.
+ EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
+ CheckRpcSendFailure(stub1);
+ // Second channel should be READY.
+ EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
+ CheckRpcSendOk(stub2, DEBUG_LOCATION);
+ // Enable health checks on the backend and wait for channel 1 to succeed.
+ servers_[0]->SetServingStatus("health_check_service_name", true);
+ CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
+ // Check that we created only one subchannel to the backend.
+ EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
+ // Clean up.
+ EnableDefaultHealthCheckService(false);
+}
+
+TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingServiceNamePerChannel) {
+ EnableDefaultHealthCheckService(true);
+ // Start server.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ // Create a channel with health-checking enabled.
+ ChannelArguments args;
+ args.SetServiceConfigJSON(
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name\"}}");
+ auto response_generator1 = BuildResolverResponseGenerator();
+ auto channel1 = BuildChannel("round_robin", response_generator1, args);
+ auto stub1 = BuildStub(channel1);
+ std::vector<int> ports = GetServersPorts();
+ response_generator1.SetNextResolution(ports);
+ // Create a channel with health-checking enabled with a different
+ // service name.
+ ChannelArguments args2;
+ args2.SetServiceConfigJSON(
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name2\"}}");
+ auto response_generator2 = BuildResolverResponseGenerator();
+ auto channel2 = BuildChannel("round_robin", response_generator2, args2);
+ auto stub2 = BuildStub(channel2);
+ response_generator2.SetNextResolution(ports);
+ // Allow health checks from channel 2 to succeed.
+ servers_[0]->SetServingStatus("health_check_service_name2", true);
+ // First channel should not become READY, because health checks should be
+ // failing.
+ EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
+ CheckRpcSendFailure(stub1);
+ // Second channel should be READY.
+ EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
+ CheckRpcSendOk(stub2, DEBUG_LOCATION);
+ // Enable health checks for channel 1 and wait for it to succeed.
+ servers_[0]->SetServingStatus("health_check_service_name", true);
+ CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
+ // Check that we created only one subchannel to the backend.
+ EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
+ // Clean up.
+ EnableDefaultHealthCheckService(false);
+}
+
+TEST_F(ClientLbEnd2endTest,
+ RoundRobinWithHealthCheckingServiceNameChangesAfterSubchannelsCreated) {
+ EnableDefaultHealthCheckService(true);
+ // Start server.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ // Create a channel with health-checking enabled.
+ const char* kServiceConfigJson =
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name\"}}";
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("round_robin", response_generator);
+ auto stub = BuildStub(channel);
+ std::vector<int> ports = GetServersPorts();
+ response_generator.SetNextResolution(ports, kServiceConfigJson);
+ servers_[0]->SetServingStatus("health_check_service_name", true);
+ EXPECT_TRUE(WaitForChannelReady(channel.get(), 1 /* timeout_seconds */));
+ // Send an update on the channel to change it to use a health checking
+ // service name that is not being reported as healthy.
+ const char* kServiceConfigJson2 =
+ "{\"healthCheckConfig\": "
+ "{\"serviceName\": \"health_check_service_name2\"}}";
+ response_generator.SetNextResolution(ports, kServiceConfigJson2);
+ EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
+ // Clean up.
+ EnableDefaultHealthCheckService(false);
+}
+
+TEST_F(ClientLbEnd2endTest, ChannelIdleness) {
+ // Start server.
+ const int kNumServers = 1;
+ StartServers(kNumServers);
+ // Set max idle time and build the channel.
+ ChannelArguments args;
+ args.SetInt(GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS, 1000);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel = BuildChannel("", response_generator, args);
+ auto stub = BuildStub(channel);
+ // The initial channel state should be IDLE.
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
+ // After sending RPC, channel state should be READY.
+ response_generator.SetNextResolution(GetServersPorts());
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
+ // After a period time not using the channel, the channel state should switch
+ // to IDLE.
+ gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(1200));
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
+ // Sending a new RPC should awake the IDLE channel.
+ response_generator.SetNextResolution(GetServersPorts());
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
+}
+
class ClientLbPickArgsTest : public ClientLbEnd2endTest {
protected:
void SetUp() override {
@@ -1715,13 +1715,13 @@ TEST_F(ClientLbPickArgsTest, Basic) {
::testing::Pair("baz", "3"))))));
}
-class ClientLbInterceptTrailingMetadataTest : public ClientLbEnd2endTest {
- protected:
- void SetUp() override {
- ClientLbEnd2endTest::SetUp();
+class ClientLbInterceptTrailingMetadataTest : public ClientLbEnd2endTest {
+ protected:
+ void SetUp() override {
+ ClientLbEnd2endTest::SetUp();
current_test_instance_ = this;
- }
-
+ }
+
static void SetUpTestCase() {
grpc_init();
grpc_core::RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
@@ -1730,75 +1730,75 @@ class ClientLbInterceptTrailingMetadataTest : public ClientLbEnd2endTest {
static void TearDownTestCase() { grpc_shutdown_blocking(); }
- int trailers_intercepted() {
- grpc::internal::MutexLock lock(&mu_);
- return trailers_intercepted_;
- }
-
+ int trailers_intercepted() {
+ grpc::internal::MutexLock lock(&mu_);
+ return trailers_intercepted_;
+ }
+
const grpc_core::MetadataVector& trailing_metadata() {
grpc::internal::MutexLock lock(&mu_);
return trailing_metadata_;
}
- const udpa::data::orca::v1::OrcaLoadReport* backend_load_report() {
- grpc::internal::MutexLock lock(&mu_);
- return load_report_.get();
- }
-
- private:
- static void ReportTrailerIntercepted(
+ const udpa::data::orca::v1::OrcaLoadReport* backend_load_report() {
+ grpc::internal::MutexLock lock(&mu_);
+ return load_report_.get();
+ }
+
+ private:
+ static void ReportTrailerIntercepted(
const grpc_core::TrailingMetadataArgsSeen& args_seen) {
const auto* backend_metric_data = args_seen.backend_metric_data;
ClientLbInterceptTrailingMetadataTest* self = current_test_instance_;
- grpc::internal::MutexLock lock(&self->mu_);
- self->trailers_intercepted_++;
+ grpc::internal::MutexLock lock(&self->mu_);
+ self->trailers_intercepted_++;
self->trailing_metadata_ = args_seen.metadata;
- if (backend_metric_data != nullptr) {
- self->load_report_.reset(new udpa::data::orca::v1::OrcaLoadReport);
- self->load_report_->set_cpu_utilization(
- backend_metric_data->cpu_utilization);
- self->load_report_->set_mem_utilization(
- backend_metric_data->mem_utilization);
- self->load_report_->set_rps(backend_metric_data->requests_per_second);
- for (const auto& p : backend_metric_data->request_cost) {
+ if (backend_metric_data != nullptr) {
+ self->load_report_.reset(new udpa::data::orca::v1::OrcaLoadReport);
+ self->load_report_->set_cpu_utilization(
+ backend_metric_data->cpu_utilization);
+ self->load_report_->set_mem_utilization(
+ backend_metric_data->mem_utilization);
+ self->load_report_->set_rps(backend_metric_data->requests_per_second);
+ for (const auto& p : backend_metric_data->request_cost) {
TString name = TString(p.first);
(*self->load_report_->mutable_request_cost())[std::move(name)] =
p.second;
- }
- for (const auto& p : backend_metric_data->utilization) {
+ }
+ for (const auto& p : backend_metric_data->utilization) {
TString name = TString(p.first);
(*self->load_report_->mutable_utilization())[std::move(name)] =
p.second;
- }
- }
- }
-
+ }
+ }
+ }
+
static ClientLbInterceptTrailingMetadataTest* current_test_instance_;
- grpc::internal::Mutex mu_;
- int trailers_intercepted_ = 0;
+ grpc::internal::Mutex mu_;
+ int trailers_intercepted_ = 0;
grpc_core::MetadataVector trailing_metadata_;
- std::unique_ptr<udpa::data::orca::v1::OrcaLoadReport> load_report_;
-};
-
+ std::unique_ptr<udpa::data::orca::v1::OrcaLoadReport> load_report_;
+};
+
ClientLbInterceptTrailingMetadataTest*
ClientLbInterceptTrailingMetadataTest::current_test_instance_ = nullptr;
-TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesDisabled) {
- const int kNumServers = 1;
- const int kNumRpcs = 10;
- StartServers(kNumServers);
- auto response_generator = BuildResolverResponseGenerator();
- auto channel =
- BuildChannel("intercept_trailing_metadata_lb", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- for (size_t i = 0; i < kNumRpcs; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- // Check LB policy name for the channel.
- EXPECT_EQ("intercept_trailing_metadata_lb",
- channel->GetLoadBalancingPolicyName());
- EXPECT_EQ(kNumRpcs, trailers_intercepted());
+TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesDisabled) {
+ const int kNumServers = 1;
+ const int kNumRpcs = 10;
+ StartServers(kNumServers);
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel =
+ BuildChannel("intercept_trailing_metadata_lb", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ for (size_t i = 0; i < kNumRpcs; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ // Check LB policy name for the channel.
+ EXPECT_EQ("intercept_trailing_metadata_lb",
+ channel->GetLoadBalancingPolicyName());
+ EXPECT_EQ(kNumRpcs, trailers_intercepted());
EXPECT_THAT(trailing_metadata(),
::testing::UnorderedElementsAre(
// TODO(roth): Should grpc-status be visible here?
@@ -1806,41 +1806,41 @@ TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesDisabled) {
::testing::Pair("user-agent", ::testing::_),
::testing::Pair("foo", "1"), ::testing::Pair("bar", "2"),
::testing::Pair("baz", "3")));
- EXPECT_EQ(nullptr, backend_load_report());
-}
-
-TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesEnabled) {
- const int kNumServers = 1;
- const int kNumRpcs = 10;
- StartServers(kNumServers);
- ChannelArguments args;
- args.SetServiceConfigJSON(
- "{\n"
- " \"methodConfig\": [ {\n"
- " \"name\": [\n"
- " { \"service\": \"grpc.testing.EchoTestService\" }\n"
- " ],\n"
- " \"retryPolicy\": {\n"
- " \"maxAttempts\": 3,\n"
- " \"initialBackoff\": \"1s\",\n"
- " \"maxBackoff\": \"120s\",\n"
- " \"backoffMultiplier\": 1.6,\n"
- " \"retryableStatusCodes\": [ \"ABORTED\" ]\n"
- " }\n"
- " } ]\n"
- "}");
- auto response_generator = BuildResolverResponseGenerator();
- auto channel =
- BuildChannel("intercept_trailing_metadata_lb", response_generator, args);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- for (size_t i = 0; i < kNumRpcs; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- }
- // Check LB policy name for the channel.
- EXPECT_EQ("intercept_trailing_metadata_lb",
- channel->GetLoadBalancingPolicyName());
- EXPECT_EQ(kNumRpcs, trailers_intercepted());
+ EXPECT_EQ(nullptr, backend_load_report());
+}
+
+TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesEnabled) {
+ const int kNumServers = 1;
+ const int kNumRpcs = 10;
+ StartServers(kNumServers);
+ ChannelArguments args;
+ args.SetServiceConfigJSON(
+ "{\n"
+ " \"methodConfig\": [ {\n"
+ " \"name\": [\n"
+ " { \"service\": \"grpc.testing.EchoTestService\" }\n"
+ " ],\n"
+ " \"retryPolicy\": {\n"
+ " \"maxAttempts\": 3,\n"
+ " \"initialBackoff\": \"1s\",\n"
+ " \"maxBackoff\": \"120s\",\n"
+ " \"backoffMultiplier\": 1.6,\n"
+ " \"retryableStatusCodes\": [ \"ABORTED\" ]\n"
+ " }\n"
+ " } ]\n"
+ "}");
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel =
+ BuildChannel("intercept_trailing_metadata_lb", response_generator, args);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ for (size_t i = 0; i < kNumRpcs; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ }
+ // Check LB policy name for the channel.
+ EXPECT_EQ("intercept_trailing_metadata_lb",
+ channel->GetLoadBalancingPolicyName());
+ EXPECT_EQ(kNumRpcs, trailers_intercepted());
EXPECT_THAT(trailing_metadata(),
::testing::UnorderedElementsAre(
// TODO(roth): Should grpc-status be visible here?
@@ -1848,59 +1848,59 @@ TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesEnabled) {
::testing::Pair("user-agent", ::testing::_),
::testing::Pair("foo", "1"), ::testing::Pair("bar", "2"),
::testing::Pair("baz", "3")));
- EXPECT_EQ(nullptr, backend_load_report());
-}
-
-TEST_F(ClientLbInterceptTrailingMetadataTest, BackendMetricData) {
- const int kNumServers = 1;
- const int kNumRpcs = 10;
- StartServers(kNumServers);
- udpa::data::orca::v1::OrcaLoadReport load_report;
- load_report.set_cpu_utilization(0.5);
- load_report.set_mem_utilization(0.75);
- load_report.set_rps(25);
- auto* request_cost = load_report.mutable_request_cost();
- (*request_cost)["foo"] = 0.8;
- (*request_cost)["bar"] = 1.4;
- auto* utilization = load_report.mutable_utilization();
- (*utilization)["baz"] = 1.1;
- (*utilization)["quux"] = 0.9;
- for (const auto& server : servers_) {
- server->service_.set_load_report(&load_report);
- }
- auto response_generator = BuildResolverResponseGenerator();
- auto channel =
- BuildChannel("intercept_trailing_metadata_lb", response_generator);
- auto stub = BuildStub(channel);
- response_generator.SetNextResolution(GetServersPorts());
- for (size_t i = 0; i < kNumRpcs; ++i) {
- CheckRpcSendOk(stub, DEBUG_LOCATION);
- auto* actual = backend_load_report();
- ASSERT_NE(actual, nullptr);
- // TODO(roth): Change this to use EqualsProto() once that becomes
- // available in OSS.
- EXPECT_EQ(actual->cpu_utilization(), load_report.cpu_utilization());
- EXPECT_EQ(actual->mem_utilization(), load_report.mem_utilization());
- EXPECT_EQ(actual->rps(), load_report.rps());
- EXPECT_EQ(actual->request_cost().size(), load_report.request_cost().size());
- for (const auto& p : actual->request_cost()) {
- auto it = load_report.request_cost().find(p.first);
- ASSERT_NE(it, load_report.request_cost().end());
- EXPECT_EQ(it->second, p.second);
- }
- EXPECT_EQ(actual->utilization().size(), load_report.utilization().size());
- for (const auto& p : actual->utilization()) {
- auto it = load_report.utilization().find(p.first);
- ASSERT_NE(it, load_report.utilization().end());
- EXPECT_EQ(it->second, p.second);
- }
- }
- // Check LB policy name for the channel.
- EXPECT_EQ("intercept_trailing_metadata_lb",
- channel->GetLoadBalancingPolicyName());
- EXPECT_EQ(kNumRpcs, trailers_intercepted());
-}
-
+ EXPECT_EQ(nullptr, backend_load_report());
+}
+
+TEST_F(ClientLbInterceptTrailingMetadataTest, BackendMetricData) {
+ const int kNumServers = 1;
+ const int kNumRpcs = 10;
+ StartServers(kNumServers);
+ udpa::data::orca::v1::OrcaLoadReport load_report;
+ load_report.set_cpu_utilization(0.5);
+ load_report.set_mem_utilization(0.75);
+ load_report.set_rps(25);
+ auto* request_cost = load_report.mutable_request_cost();
+ (*request_cost)["foo"] = 0.8;
+ (*request_cost)["bar"] = 1.4;
+ auto* utilization = load_report.mutable_utilization();
+ (*utilization)["baz"] = 1.1;
+ (*utilization)["quux"] = 0.9;
+ for (const auto& server : servers_) {
+ server->service_.set_load_report(&load_report);
+ }
+ auto response_generator = BuildResolverResponseGenerator();
+ auto channel =
+ BuildChannel("intercept_trailing_metadata_lb", response_generator);
+ auto stub = BuildStub(channel);
+ response_generator.SetNextResolution(GetServersPorts());
+ for (size_t i = 0; i < kNumRpcs; ++i) {
+ CheckRpcSendOk(stub, DEBUG_LOCATION);
+ auto* actual = backend_load_report();
+ ASSERT_NE(actual, nullptr);
+ // TODO(roth): Change this to use EqualsProto() once that becomes
+ // available in OSS.
+ EXPECT_EQ(actual->cpu_utilization(), load_report.cpu_utilization());
+ EXPECT_EQ(actual->mem_utilization(), load_report.mem_utilization());
+ EXPECT_EQ(actual->rps(), load_report.rps());
+ EXPECT_EQ(actual->request_cost().size(), load_report.request_cost().size());
+ for (const auto& p : actual->request_cost()) {
+ auto it = load_report.request_cost().find(p.first);
+ ASSERT_NE(it, load_report.request_cost().end());
+ EXPECT_EQ(it->second, p.second);
+ }
+ EXPECT_EQ(actual->utilization().size(), load_report.utilization().size());
+ for (const auto& p : actual->utilization()) {
+ auto it = load_report.utilization().find(p.first);
+ ASSERT_NE(it, load_report.utilization().end());
+ EXPECT_EQ(it->second, p.second);
+ }
+ }
+ // Check LB policy name for the channel.
+ EXPECT_EQ("intercept_trailing_metadata_lb",
+ channel->GetLoadBalancingPolicyName());
+ EXPECT_EQ(kNumRpcs, trailers_intercepted());
+}
+
class ClientLbAddressTest : public ClientLbEnd2endTest {
protected:
static const char* kAttributeKey;
@@ -1978,13 +1978,13 @@ TEST_F(ClientLbAddressTest, Basic) {
EXPECT_EQ(addresses_seen(), expected);
}
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- grpc::testing::TestEnvironment env(argc, argv);
- const auto result = RUN_ALL_TESTS();
- return result;
-}
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ grpc::testing::TestEnvironment env(argc, argv);
+ const auto result = RUN_ALL_TESTS();
+ return result;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/end2end_test.cc
index ad2ddb7e84..9e1ae49b8d 100644
--- a/contrib/libs/grpc/test/cpp/end2end/end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/end2end_test.cc
@@ -1,95 +1,95 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/impl/codegen/status_code_enum.h>
-#include <grpcpp/resource_quota.h>
-#include <grpcpp/security/auth_metadata_processor.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/impl/codegen/status_code_enum.h>
+#include <grpcpp/resource_quota.h>
+#include <grpcpp/security/auth_metadata_processor.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
#include <grpcpp/support/string_ref.h>
#include <grpcpp/test/channel_test_peer.h>
-
-#include <mutex>
-#include <thread>
-
+
+#include <mutex>
+#include <thread>
+
#include "y_absl/strings/str_format.h"
-#include "src/core/ext/filters/client_channel/backup_poller.h"
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/security/credentials/credentials.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/interceptors_util.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/string_ref_helper.h"
-#include "test/cpp/util/test_credentials_provider.h"
-
-#ifdef GRPC_POSIX_SOCKET_EV
-#include "src/core/lib/iomgr/ev_posix.h"
-#endif // GRPC_POSIX_SOCKET_EV
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using grpc::testing::kTlsCredentialsType;
-using std::chrono::system_clock;
-
-// MAYBE_SKIP_TEST is a macro to determine if this particular test configuration
-// should be skipped based on a decision made at SetUp time. In particular,
-// tests that use the callback server can only be run if the iomgr can run in
-// the background or if the transport is in-process.
-#define MAYBE_SKIP_TEST \
- do { \
- if (do_not_test_) { \
- return; \
- } \
- } while (0)
-
-namespace grpc {
-namespace testing {
-namespace {
-
+#include "src/core/ext/filters/client_channel/backup_poller.h"
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/interceptors_util.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/string_ref_helper.h"
+#include "test/cpp/util/test_credentials_provider.h"
+
+#ifdef GRPC_POSIX_SOCKET_EV
+#include "src/core/lib/iomgr/ev_posix.h"
+#endif // GRPC_POSIX_SOCKET_EV
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using grpc::testing::kTlsCredentialsType;
+using std::chrono::system_clock;
+
+// MAYBE_SKIP_TEST is a macro to determine if this particular test configuration
+// should be skipped based on a decision made at SetUp time. In particular,
+// tests that use the callback server can only be run if the iomgr can run in
+// the background or if the transport is in-process.
+#define MAYBE_SKIP_TEST \
+ do { \
+ if (do_not_test_) { \
+ return; \
+ } \
+ } while (0)
+
+namespace grpc {
+namespace testing {
+namespace {
+
bool CheckIsLocalhost(const TString& addr) {
const TString kIpv6("ipv6:[::1]:");
const TString kIpv4MappedIpv6("ipv6:[::ffff:127.0.0.1]:");
const TString kIpv4("ipv4:127.0.0.1:");
- return addr.substr(0, kIpv4.size()) == kIpv4 ||
- addr.substr(0, kIpv4MappedIpv6.size()) == kIpv4MappedIpv6 ||
- addr.substr(0, kIpv6.size()) == kIpv6;
-}
-
+ return addr.substr(0, kIpv4.size()) == kIpv4 ||
+ addr.substr(0, kIpv4MappedIpv6.size()) == kIpv4MappedIpv6 ||
+ addr.substr(0, kIpv6.size()) == kIpv6;
+}
+
const int kClientChannelBackupPollIntervalMs = 200;
-const char kTestCredsPluginErrorMsg[] = "Could not find plugin metadata.";
-
+const char kTestCredsPluginErrorMsg[] = "Could not find plugin metadata.";
+
const char kFakeToken[] = "fake_token";
const char kFakeSelector[] = "fake_selector";
const char kExpectedFakeCredsDebugString[] =
@@ -142,738 +142,738 @@ const char kExpectedCompositeCallCredsDebugString[] =
"key:call-creds-key1,value:call-creds-val1},TestMetadataCredentials{key:"
"call-creds-key2,value:call-creds-val2}}}";
-class TestMetadataCredentialsPlugin : public MetadataCredentialsPlugin {
- public:
- static const char kGoodMetadataKey[];
- static const char kBadMetadataKey[];
-
- TestMetadataCredentialsPlugin(const grpc::string_ref& metadata_key,
- const grpc::string_ref& metadata_value,
- bool is_blocking, bool is_successful,
- int delay_ms)
- : metadata_key_(metadata_key.data(), metadata_key.length()),
- metadata_value_(metadata_value.data(), metadata_value.length()),
- is_blocking_(is_blocking),
- is_successful_(is_successful),
- delay_ms_(delay_ms) {}
-
- bool IsBlocking() const override { return is_blocking_; }
-
- Status GetMetadata(
- grpc::string_ref service_url, grpc::string_ref method_name,
- const grpc::AuthContext& channel_auth_context,
+class TestMetadataCredentialsPlugin : public MetadataCredentialsPlugin {
+ public:
+ static const char kGoodMetadataKey[];
+ static const char kBadMetadataKey[];
+
+ TestMetadataCredentialsPlugin(const grpc::string_ref& metadata_key,
+ const grpc::string_ref& metadata_value,
+ bool is_blocking, bool is_successful,
+ int delay_ms)
+ : metadata_key_(metadata_key.data(), metadata_key.length()),
+ metadata_value_(metadata_value.data(), metadata_value.length()),
+ is_blocking_(is_blocking),
+ is_successful_(is_successful),
+ delay_ms_(delay_ms) {}
+
+ bool IsBlocking() const override { return is_blocking_; }
+
+ Status GetMetadata(
+ grpc::string_ref service_url, grpc::string_ref method_name,
+ const grpc::AuthContext& channel_auth_context,
std::multimap<TString, TString>* metadata) override {
- if (delay_ms_ != 0) {
- gpr_sleep_until(
- gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(delay_ms_, GPR_TIMESPAN)));
- }
- EXPECT_GT(service_url.length(), 0UL);
- EXPECT_GT(method_name.length(), 0UL);
- EXPECT_TRUE(channel_auth_context.IsPeerAuthenticated());
- EXPECT_TRUE(metadata != nullptr);
- if (is_successful_) {
- metadata->insert(std::make_pair(metadata_key_, metadata_value_));
- return Status::OK;
- } else {
- return Status(StatusCode::NOT_FOUND, kTestCredsPluginErrorMsg);
- }
- }
-
+ if (delay_ms_ != 0) {
+ gpr_sleep_until(
+ gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_millis(delay_ms_, GPR_TIMESPAN)));
+ }
+ EXPECT_GT(service_url.length(), 0UL);
+ EXPECT_GT(method_name.length(), 0UL);
+ EXPECT_TRUE(channel_auth_context.IsPeerAuthenticated());
+ EXPECT_TRUE(metadata != nullptr);
+ if (is_successful_) {
+ metadata->insert(std::make_pair(metadata_key_, metadata_value_));
+ return Status::OK;
+ } else {
+ return Status(StatusCode::NOT_FOUND, kTestCredsPluginErrorMsg);
+ }
+ }
+
TString DebugString() override {
return y_absl::StrFormat("TestMetadataCredentials{key:%s,value:%s}",
metadata_key_.c_str(), metadata_value_.c_str());
}
- private:
+ private:
TString metadata_key_;
TString metadata_value_;
- bool is_blocking_;
- bool is_successful_;
- int delay_ms_;
-};
-
-const char TestMetadataCredentialsPlugin::kBadMetadataKey[] =
- "TestPluginMetadata";
-const char TestMetadataCredentialsPlugin::kGoodMetadataKey[] =
- "test-plugin-metadata";
-
-class TestAuthMetadataProcessor : public AuthMetadataProcessor {
- public:
- static const char kGoodGuy[];
-
- TestAuthMetadataProcessor(bool is_blocking) : is_blocking_(is_blocking) {}
-
- std::shared_ptr<CallCredentials> GetCompatibleClientCreds() {
- return grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(
- TestMetadataCredentialsPlugin::kGoodMetadataKey, kGoodGuy,
- is_blocking_, true, 0)));
- }
-
- std::shared_ptr<CallCredentials> GetIncompatibleClientCreds() {
- return grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(
- TestMetadataCredentialsPlugin::kGoodMetadataKey, "Mr Hyde",
- is_blocking_, true, 0)));
- }
-
- // Interface implementation
- bool IsBlocking() const override { return is_blocking_; }
-
- Status Process(const InputMetadata& auth_metadata, AuthContext* context,
- OutputMetadata* consumed_auth_metadata,
- OutputMetadata* response_metadata) override {
- EXPECT_TRUE(consumed_auth_metadata != nullptr);
- EXPECT_TRUE(context != nullptr);
- EXPECT_TRUE(response_metadata != nullptr);
- auto auth_md =
- auth_metadata.find(TestMetadataCredentialsPlugin::kGoodMetadataKey);
- EXPECT_NE(auth_md, auth_metadata.end());
- string_ref auth_md_value = auth_md->second;
- if (auth_md_value == kGoodGuy) {
- context->AddProperty(kIdentityPropName, kGoodGuy);
- context->SetPeerIdentityPropertyName(kIdentityPropName);
- consumed_auth_metadata->insert(std::make_pair(
- string(auth_md->first.data(), auth_md->first.length()),
- string(auth_md->second.data(), auth_md->second.length())));
- return Status::OK;
- } else {
- return Status(StatusCode::UNAUTHENTICATED,
- string("Invalid principal: ") +
- string(auth_md_value.data(), auth_md_value.length()));
- }
- }
-
- private:
- static const char kIdentityPropName[];
- bool is_blocking_;
-};
-
-const char TestAuthMetadataProcessor::kGoodGuy[] = "Dr Jekyll";
-const char TestAuthMetadataProcessor::kIdentityPropName[] = "novel identity";
-
-class Proxy : public ::grpc::testing::EchoTestService::Service {
- public:
- Proxy(const std::shared_ptr<Channel>& channel)
- : stub_(grpc::testing::EchoTestService::NewStub(channel)) {}
-
- Status Echo(ServerContext* server_context, const EchoRequest* request,
- EchoResponse* response) override {
- std::unique_ptr<ClientContext> client_context =
- ClientContext::FromServerContext(*server_context);
- return stub_->Echo(client_context.get(), *request, response);
- }
-
- private:
- std::unique_ptr<::grpc::testing::EchoTestService::Stub> stub_;
-};
-
-class TestServiceImplDupPkg
- : public ::grpc::testing::duplicate::EchoTestService::Service {
- public:
- Status Echo(ServerContext* /*context*/, const EchoRequest* /*request*/,
- EchoResponse* response) override {
- response->set_message("no package");
- return Status::OK;
- }
-};
-
-class TestScenario {
- public:
- TestScenario(bool interceptors, bool proxy, bool inproc_stub,
+ bool is_blocking_;
+ bool is_successful_;
+ int delay_ms_;
+};
+
+const char TestMetadataCredentialsPlugin::kBadMetadataKey[] =
+ "TestPluginMetadata";
+const char TestMetadataCredentialsPlugin::kGoodMetadataKey[] =
+ "test-plugin-metadata";
+
+class TestAuthMetadataProcessor : public AuthMetadataProcessor {
+ public:
+ static const char kGoodGuy[];
+
+ TestAuthMetadataProcessor(bool is_blocking) : is_blocking_(is_blocking) {}
+
+ std::shared_ptr<CallCredentials> GetCompatibleClientCreds() {
+ return grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(
+ TestMetadataCredentialsPlugin::kGoodMetadataKey, kGoodGuy,
+ is_blocking_, true, 0)));
+ }
+
+ std::shared_ptr<CallCredentials> GetIncompatibleClientCreds() {
+ return grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(
+ TestMetadataCredentialsPlugin::kGoodMetadataKey, "Mr Hyde",
+ is_blocking_, true, 0)));
+ }
+
+ // Interface implementation
+ bool IsBlocking() const override { return is_blocking_; }
+
+ Status Process(const InputMetadata& auth_metadata, AuthContext* context,
+ OutputMetadata* consumed_auth_metadata,
+ OutputMetadata* response_metadata) override {
+ EXPECT_TRUE(consumed_auth_metadata != nullptr);
+ EXPECT_TRUE(context != nullptr);
+ EXPECT_TRUE(response_metadata != nullptr);
+ auto auth_md =
+ auth_metadata.find(TestMetadataCredentialsPlugin::kGoodMetadataKey);
+ EXPECT_NE(auth_md, auth_metadata.end());
+ string_ref auth_md_value = auth_md->second;
+ if (auth_md_value == kGoodGuy) {
+ context->AddProperty(kIdentityPropName, kGoodGuy);
+ context->SetPeerIdentityPropertyName(kIdentityPropName);
+ consumed_auth_metadata->insert(std::make_pair(
+ string(auth_md->first.data(), auth_md->first.length()),
+ string(auth_md->second.data(), auth_md->second.length())));
+ return Status::OK;
+ } else {
+ return Status(StatusCode::UNAUTHENTICATED,
+ string("Invalid principal: ") +
+ string(auth_md_value.data(), auth_md_value.length()));
+ }
+ }
+
+ private:
+ static const char kIdentityPropName[];
+ bool is_blocking_;
+};
+
+const char TestAuthMetadataProcessor::kGoodGuy[] = "Dr Jekyll";
+const char TestAuthMetadataProcessor::kIdentityPropName[] = "novel identity";
+
+class Proxy : public ::grpc::testing::EchoTestService::Service {
+ public:
+ Proxy(const std::shared_ptr<Channel>& channel)
+ : stub_(grpc::testing::EchoTestService::NewStub(channel)) {}
+
+ Status Echo(ServerContext* server_context, const EchoRequest* request,
+ EchoResponse* response) override {
+ std::unique_ptr<ClientContext> client_context =
+ ClientContext::FromServerContext(*server_context);
+ return stub_->Echo(client_context.get(), *request, response);
+ }
+
+ private:
+ std::unique_ptr<::grpc::testing::EchoTestService::Stub> stub_;
+};
+
+class TestServiceImplDupPkg
+ : public ::grpc::testing::duplicate::EchoTestService::Service {
+ public:
+ Status Echo(ServerContext* /*context*/, const EchoRequest* /*request*/,
+ EchoResponse* response) override {
+ response->set_message("no package");
+ return Status::OK;
+ }
+};
+
+class TestScenario {
+ public:
+ TestScenario(bool interceptors, bool proxy, bool inproc_stub,
const TString& creds_type, bool use_callback_server)
- : use_interceptors(interceptors),
- use_proxy(proxy),
- inproc(inproc_stub),
- credentials_type(creds_type),
- callback_server(use_callback_server) {}
- void Log() const;
- bool use_interceptors;
- bool use_proxy;
- bool inproc;
+ : use_interceptors(interceptors),
+ use_proxy(proxy),
+ inproc(inproc_stub),
+ credentials_type(creds_type),
+ callback_server(use_callback_server) {}
+ void Log() const;
+ bool use_interceptors;
+ bool use_proxy;
+ bool inproc;
const TString credentials_type;
- bool callback_server;
-};
-
-static std::ostream& operator<<(std::ostream& out,
- const TestScenario& scenario) {
- return out << "TestScenario{use_interceptors="
- << (scenario.use_interceptors ? "true" : "false")
- << ", use_proxy=" << (scenario.use_proxy ? "true" : "false")
- << ", inproc=" << (scenario.inproc ? "true" : "false")
- << ", server_type="
- << (scenario.callback_server ? "callback" : "sync")
- << ", credentials='" << scenario.credentials_type << "'}";
-}
-
-void TestScenario::Log() const {
- std::ostringstream out;
- out << *this;
- gpr_log(GPR_DEBUG, "%s", out.str().c_str());
-}
-
-class End2endTest : public ::testing::TestWithParam<TestScenario> {
- protected:
- static void SetUpTestCase() { grpc_init(); }
- static void TearDownTestCase() { grpc_shutdown(); }
- End2endTest()
- : is_server_started_(false),
- kMaxMessageSize_(8192),
- special_service_("special"),
- first_picked_port_(0) {
- GetParam().Log();
- }
-
- void SetUp() override {
- if (GetParam().callback_server && !GetParam().inproc &&
- !grpc_iomgr_run_in_background()) {
- do_not_test_ = true;
- return;
- }
- }
-
- void TearDown() override {
- if (is_server_started_) {
- server_->Shutdown();
- if (proxy_server_) proxy_server_->Shutdown();
- }
- if (first_picked_port_ > 0) {
- grpc_recycle_unused_port(first_picked_port_);
- }
- }
-
- void StartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
- int port = grpc_pick_unused_port_or_die();
- first_picked_port_ = port;
- server_address_ << "127.0.0.1:" << port;
- // Setup server
- BuildAndStartServer(processor);
- }
-
- void RestartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
- if (is_server_started_) {
- server_->Shutdown();
- BuildAndStartServer(processor);
- }
- }
-
- void BuildAndStartServer(
- const std::shared_ptr<AuthMetadataProcessor>& processor) {
- ServerBuilder builder;
- ConfigureServerBuilder(&builder);
- auto server_creds = GetCredentialsProvider()->GetServerCredentials(
- GetParam().credentials_type);
- if (GetParam().credentials_type != kInsecureCredentialsType) {
- server_creds->SetAuthMetadataProcessor(processor);
- }
- if (GetParam().use_interceptors) {
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy server interceptors
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- }
- builder.AddListeningPort(server_address_.str(), server_creds);
- if (!GetParam().callback_server) {
- builder.RegisterService(&service_);
- } else {
- builder.RegisterService(&callback_service_);
- }
- builder.RegisterService("foo.test.youtube.com", &special_service_);
- builder.RegisterService(&dup_pkg_service_);
-
- builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
- builder.SetSyncServerOption(
- ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
-
- server_ = builder.BuildAndStart();
- is_server_started_ = true;
- }
-
- virtual void ConfigureServerBuilder(ServerBuilder* builder) {
- builder->SetMaxMessageSize(
- kMaxMessageSize_); // For testing max message size.
- }
-
- void ResetChannel(
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators = {}) {
- if (!is_server_started_) {
- StartServer(std::shared_ptr<AuthMetadataProcessor>());
- }
- EXPECT_TRUE(is_server_started_);
- ChannelArguments args;
- auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
- GetParam().credentials_type, &args);
- if (!user_agent_prefix_.empty()) {
- args.SetUserAgentPrefix(user_agent_prefix_);
- }
- args.SetString(GRPC_ARG_SECONDARY_USER_AGENT_STRING, "end2end_test");
-
- if (!GetParam().inproc) {
- if (!GetParam().use_interceptors) {
- channel_ = ::grpc::CreateCustomChannel(server_address_.str(),
- channel_creds, args);
- } else {
- channel_ = CreateCustomChannelWithInterceptors(
- server_address_.str(), channel_creds, args,
- interceptor_creators.empty() ? CreateDummyClientInterceptors()
- : std::move(interceptor_creators));
- }
- } else {
- if (!GetParam().use_interceptors) {
- channel_ = server_->InProcessChannel(args);
- } else {
- channel_ = server_->experimental().InProcessChannelWithInterceptors(
- args, interceptor_creators.empty()
- ? CreateDummyClientInterceptors()
- : std::move(interceptor_creators));
- }
- }
- }
-
- void ResetStub(
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators = {}) {
- ResetChannel(std::move(interceptor_creators));
- if (GetParam().use_proxy) {
- proxy_service_.reset(new Proxy(channel_));
- int port = grpc_pick_unused_port_or_die();
- std::ostringstream proxyaddr;
- proxyaddr << "localhost:" << port;
- ServerBuilder builder;
- builder.AddListeningPort(proxyaddr.str(), InsecureServerCredentials());
- builder.RegisterService(proxy_service_.get());
-
- builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
- builder.SetSyncServerOption(
- ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
-
- proxy_server_ = builder.BuildAndStart();
-
- channel_ =
- grpc::CreateChannel(proxyaddr.str(), InsecureChannelCredentials());
- }
-
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- DummyInterceptor::Reset();
- }
-
- bool do_not_test_{false};
- bool is_server_started_;
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::unique_ptr<Server> proxy_server_;
- std::unique_ptr<Proxy> proxy_service_;
- std::ostringstream server_address_;
- const int kMaxMessageSize_;
- TestServiceImpl service_;
- CallbackTestServiceImpl callback_service_;
- TestServiceImpl special_service_;
- TestServiceImplDupPkg dup_pkg_service_;
+ bool callback_server;
+};
+
+static std::ostream& operator<<(std::ostream& out,
+ const TestScenario& scenario) {
+ return out << "TestScenario{use_interceptors="
+ << (scenario.use_interceptors ? "true" : "false")
+ << ", use_proxy=" << (scenario.use_proxy ? "true" : "false")
+ << ", inproc=" << (scenario.inproc ? "true" : "false")
+ << ", server_type="
+ << (scenario.callback_server ? "callback" : "sync")
+ << ", credentials='" << scenario.credentials_type << "'}";
+}
+
+void TestScenario::Log() const {
+ std::ostringstream out;
+ out << *this;
+ gpr_log(GPR_DEBUG, "%s", out.str().c_str());
+}
+
+class End2endTest : public ::testing::TestWithParam<TestScenario> {
+ protected:
+ static void SetUpTestCase() { grpc_init(); }
+ static void TearDownTestCase() { grpc_shutdown(); }
+ End2endTest()
+ : is_server_started_(false),
+ kMaxMessageSize_(8192),
+ special_service_("special"),
+ first_picked_port_(0) {
+ GetParam().Log();
+ }
+
+ void SetUp() override {
+ if (GetParam().callback_server && !GetParam().inproc &&
+ !grpc_iomgr_run_in_background()) {
+ do_not_test_ = true;
+ return;
+ }
+ }
+
+ void TearDown() override {
+ if (is_server_started_) {
+ server_->Shutdown();
+ if (proxy_server_) proxy_server_->Shutdown();
+ }
+ if (first_picked_port_ > 0) {
+ grpc_recycle_unused_port(first_picked_port_);
+ }
+ }
+
+ void StartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
+ int port = grpc_pick_unused_port_or_die();
+ first_picked_port_ = port;
+ server_address_ << "127.0.0.1:" << port;
+ // Setup server
+ BuildAndStartServer(processor);
+ }
+
+ void RestartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
+ if (is_server_started_) {
+ server_->Shutdown();
+ BuildAndStartServer(processor);
+ }
+ }
+
+ void BuildAndStartServer(
+ const std::shared_ptr<AuthMetadataProcessor>& processor) {
+ ServerBuilder builder;
+ ConfigureServerBuilder(&builder);
+ auto server_creds = GetCredentialsProvider()->GetServerCredentials(
+ GetParam().credentials_type);
+ if (GetParam().credentials_type != kInsecureCredentialsType) {
+ server_creds->SetAuthMetadataProcessor(processor);
+ }
+ if (GetParam().use_interceptors) {
+ std::vector<
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy server interceptors
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ }
+ builder.AddListeningPort(server_address_.str(), server_creds);
+ if (!GetParam().callback_server) {
+ builder.RegisterService(&service_);
+ } else {
+ builder.RegisterService(&callback_service_);
+ }
+ builder.RegisterService("foo.test.youtube.com", &special_service_);
+ builder.RegisterService(&dup_pkg_service_);
+
+ builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
+ builder.SetSyncServerOption(
+ ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
+
+ server_ = builder.BuildAndStart();
+ is_server_started_ = true;
+ }
+
+ virtual void ConfigureServerBuilder(ServerBuilder* builder) {
+ builder->SetMaxMessageSize(
+ kMaxMessageSize_); // For testing max message size.
+ }
+
+ void ResetChannel(
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators = {}) {
+ if (!is_server_started_) {
+ StartServer(std::shared_ptr<AuthMetadataProcessor>());
+ }
+ EXPECT_TRUE(is_server_started_);
+ ChannelArguments args;
+ auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
+ GetParam().credentials_type, &args);
+ if (!user_agent_prefix_.empty()) {
+ args.SetUserAgentPrefix(user_agent_prefix_);
+ }
+ args.SetString(GRPC_ARG_SECONDARY_USER_AGENT_STRING, "end2end_test");
+
+ if (!GetParam().inproc) {
+ if (!GetParam().use_interceptors) {
+ channel_ = ::grpc::CreateCustomChannel(server_address_.str(),
+ channel_creds, args);
+ } else {
+ channel_ = CreateCustomChannelWithInterceptors(
+ server_address_.str(), channel_creds, args,
+ interceptor_creators.empty() ? CreateDummyClientInterceptors()
+ : std::move(interceptor_creators));
+ }
+ } else {
+ if (!GetParam().use_interceptors) {
+ channel_ = server_->InProcessChannel(args);
+ } else {
+ channel_ = server_->experimental().InProcessChannelWithInterceptors(
+ args, interceptor_creators.empty()
+ ? CreateDummyClientInterceptors()
+ : std::move(interceptor_creators));
+ }
+ }
+ }
+
+ void ResetStub(
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators = {}) {
+ ResetChannel(std::move(interceptor_creators));
+ if (GetParam().use_proxy) {
+ proxy_service_.reset(new Proxy(channel_));
+ int port = grpc_pick_unused_port_or_die();
+ std::ostringstream proxyaddr;
+ proxyaddr << "localhost:" << port;
+ ServerBuilder builder;
+ builder.AddListeningPort(proxyaddr.str(), InsecureServerCredentials());
+ builder.RegisterService(proxy_service_.get());
+
+ builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
+ builder.SetSyncServerOption(
+ ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
+
+ proxy_server_ = builder.BuildAndStart();
+
+ channel_ =
+ grpc::CreateChannel(proxyaddr.str(), InsecureChannelCredentials());
+ }
+
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ DummyInterceptor::Reset();
+ }
+
+ bool do_not_test_{false};
+ bool is_server_started_;
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::unique_ptr<Server> proxy_server_;
+ std::unique_ptr<Proxy> proxy_service_;
+ std::ostringstream server_address_;
+ const int kMaxMessageSize_;
+ TestServiceImpl service_;
+ CallbackTestServiceImpl callback_service_;
+ TestServiceImpl special_service_;
+ TestServiceImplDupPkg dup_pkg_service_;
TString user_agent_prefix_;
- int first_picked_port_;
-};
-
-static void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
- bool with_binary_metadata) {
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello hello hello hello");
-
- for (int i = 0; i < num_rpcs; ++i) {
- ClientContext context;
- if (with_binary_metadata) {
- char bytes[8] = {'\0', '\1', '\2', '\3',
- '\4', '\5', '\6', static_cast<char>(i)};
+ int first_picked_port_;
+};
+
+static void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
+ bool with_binary_metadata) {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello hello hello hello");
+
+ for (int i = 0; i < num_rpcs; ++i) {
+ ClientContext context;
+ if (with_binary_metadata) {
+ char bytes[8] = {'\0', '\1', '\2', '\3',
+ '\4', '\5', '\6', static_cast<char>(i)};
context.AddMetadata("custom-bin", TString(bytes, 8));
- }
- context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
- Status s = stub->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
- }
-}
-
-// This class is for testing scenarios where RPCs are cancelled on the server
-// by calling ServerContext::TryCancel()
-class End2endServerTryCancelTest : public End2endTest {
- protected:
- // Helper for testing client-streaming RPCs which are cancelled on the server.
- // Depending on the value of server_try_cancel parameter, this will test one
- // of the following three scenarios:
- // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading
- // any messages from the client
- //
- // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
- // messages from the client
- //
- // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
- // the messages from the client
- //
- // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
- void TestRequestStreamServerCancel(
- ServerTryCancelRequestPhase server_try_cancel, int num_msgs_to_send) {
- MAYBE_SKIP_TEST;
- RestartServer(std::shared_ptr<AuthMetadataProcessor>());
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- // Send server_try_cancel value in the client metadata
- context.AddMetadata(kServerTryCancelRequest,
+ }
+ context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
+ Status s = stub->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+ }
+}
+
+// This class is for testing scenarios where RPCs are cancelled on the server
+// by calling ServerContext::TryCancel()
+class End2endServerTryCancelTest : public End2endTest {
+ protected:
+ // Helper for testing client-streaming RPCs which are cancelled on the server.
+ // Depending on the value of server_try_cancel parameter, this will test one
+ // of the following three scenarios:
+ // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading
+ // any messages from the client
+ //
+ // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
+ // messages from the client
+ //
+ // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
+ // the messages from the client
+ //
+ // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
+ void TestRequestStreamServerCancel(
+ ServerTryCancelRequestPhase server_try_cancel, int num_msgs_to_send) {
+ MAYBE_SKIP_TEST;
+ RestartServer(std::shared_ptr<AuthMetadataProcessor>());
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ // Send server_try_cancel value in the client metadata
+ context.AddMetadata(kServerTryCancelRequest,
ToString(server_try_cancel));
-
- auto stream = stub_->RequestStream(&context, &response);
-
- int num_msgs_sent = 0;
- while (num_msgs_sent < num_msgs_to_send) {
- request.set_message("hello");
- if (!stream->Write(request)) {
- break;
- }
- num_msgs_sent++;
- }
- gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
-
- stream->WritesDone();
- Status s = stream->Finish();
-
- // At this point, we know for sure that RPC was cancelled by the server
- // since we passed server_try_cancel value in the metadata. Depending on the
- // value of server_try_cancel, the RPC might have been cancelled by the
- // server at different stages. The following validates our expectations of
- // number of messages sent in various cancellation scenarios:
-
- switch (server_try_cancel) {
- case CANCEL_BEFORE_PROCESSING:
- case CANCEL_DURING_PROCESSING:
- // If the RPC is cancelled by server before / during messages from the
- // client, it means that the client most likely did not get a chance to
- // send all the messages it wanted to send. i.e num_msgs_sent <=
- // num_msgs_to_send
- EXPECT_LE(num_msgs_sent, num_msgs_to_send);
- break;
-
- case CANCEL_AFTER_PROCESSING:
- // If the RPC was cancelled after all messages were read by the server,
- // the client did get a chance to send all its messages
- EXPECT_EQ(num_msgs_sent, num_msgs_to_send);
- break;
-
- default:
- gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
- server_try_cancel);
- EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
- server_try_cancel <= CANCEL_AFTER_PROCESSING);
- break;
- }
-
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
- }
-
- // Helper for testing server-streaming RPCs which are cancelled on the server.
- // Depending on the value of server_try_cancel parameter, this will test one
- // of the following three scenarios:
- // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before writing
- // any messages to the client
- //
- // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while writing
- // messages to the client
- //
- // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after writing all
- // the messages to the client
- //
- // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
- void TestResponseStreamServerCancel(
- ServerTryCancelRequestPhase server_try_cancel) {
- MAYBE_SKIP_TEST;
- RestartServer(std::shared_ptr<AuthMetadataProcessor>());
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- // Send server_try_cancel in the client metadata
- context.AddMetadata(kServerTryCancelRequest,
+
+ auto stream = stub_->RequestStream(&context, &response);
+
+ int num_msgs_sent = 0;
+ while (num_msgs_sent < num_msgs_to_send) {
+ request.set_message("hello");
+ if (!stream->Write(request)) {
+ break;
+ }
+ num_msgs_sent++;
+ }
+ gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
+
+ stream->WritesDone();
+ Status s = stream->Finish();
+
+ // At this point, we know for sure that RPC was cancelled by the server
+ // since we passed server_try_cancel value in the metadata. Depending on the
+ // value of server_try_cancel, the RPC might have been cancelled by the
+ // server at different stages. The following validates our expectations of
+ // number of messages sent in various cancellation scenarios:
+
+ switch (server_try_cancel) {
+ case CANCEL_BEFORE_PROCESSING:
+ case CANCEL_DURING_PROCESSING:
+ // If the RPC is cancelled by server before / during messages from the
+ // client, it means that the client most likely did not get a chance to
+ // send all the messages it wanted to send. i.e num_msgs_sent <=
+ // num_msgs_to_send
+ EXPECT_LE(num_msgs_sent, num_msgs_to_send);
+ break;
+
+ case CANCEL_AFTER_PROCESSING:
+ // If the RPC was cancelled after all messages were read by the server,
+ // the client did get a chance to send all its messages
+ EXPECT_EQ(num_msgs_sent, num_msgs_to_send);
+ break;
+
+ default:
+ gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
+ server_try_cancel);
+ EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
+ server_try_cancel <= CANCEL_AFTER_PROCESSING);
+ break;
+ }
+
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+ }
+
+ // Helper for testing server-streaming RPCs which are cancelled on the server.
+ // Depending on the value of server_try_cancel parameter, this will test one
+ // of the following three scenarios:
+ // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before writing
+ // any messages to the client
+ //
+ // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while writing
+ // messages to the client
+ //
+ // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after writing all
+ // the messages to the client
+ //
+ // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
+ void TestResponseStreamServerCancel(
+ ServerTryCancelRequestPhase server_try_cancel) {
+ MAYBE_SKIP_TEST;
+ RestartServer(std::shared_ptr<AuthMetadataProcessor>());
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ // Send server_try_cancel in the client metadata
+ context.AddMetadata(kServerTryCancelRequest,
ToString(server_try_cancel));
-
- request.set_message("hello");
- auto stream = stub_->ResponseStream(&context, request);
-
- int num_msgs_read = 0;
- while (num_msgs_read < kServerDefaultResponseStreamsToSend) {
- if (!stream->Read(&response)) {
- break;
- }
- EXPECT_EQ(response.message(),
+
+ request.set_message("hello");
+ auto stream = stub_->ResponseStream(&context, request);
+
+ int num_msgs_read = 0;
+ while (num_msgs_read < kServerDefaultResponseStreamsToSend) {
+ if (!stream->Read(&response)) {
+ break;
+ }
+ EXPECT_EQ(response.message(),
request.message() + ToString(num_msgs_read));
- num_msgs_read++;
- }
- gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
-
- Status s = stream->Finish();
-
- // Depending on the value of server_try_cancel, the RPC might have been
- // cancelled by the server at different stages. The following validates our
- // expectations of number of messages read in various cancellation
- // scenarios:
- switch (server_try_cancel) {
- case CANCEL_BEFORE_PROCESSING:
- // Server cancelled before sending any messages. Which means the client
- // wouldn't have read any
- EXPECT_EQ(num_msgs_read, 0);
- break;
-
- case CANCEL_DURING_PROCESSING:
- // Server cancelled while writing messages. Client must have read less
- // than or equal to the expected number of messages
- EXPECT_LE(num_msgs_read, kServerDefaultResponseStreamsToSend);
- break;
-
- case CANCEL_AFTER_PROCESSING:
- // Even though the Server cancelled after writing all messages, the RPC
- // may be cancelled before the Client got a chance to read all the
- // messages.
- EXPECT_LE(num_msgs_read, kServerDefaultResponseStreamsToSend);
- break;
-
- default: {
- gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
- server_try_cancel);
- EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
- server_try_cancel <= CANCEL_AFTER_PROCESSING);
- break;
- }
- }
-
- EXPECT_FALSE(s.ok());
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
- }
-
- // Helper for testing bidirectional-streaming RPCs which are cancelled on the
- // server. Depending on the value of server_try_cancel parameter, this will
- // test one of the following three scenarios:
- // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading/
- // writing any messages from/to the client
- //
- // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading/
- // writing messages from/to the client
- //
- // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading/writing
- // all the messages from/to the client
- //
- // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
- void TestBidiStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel,
- int num_messages) {
- MAYBE_SKIP_TEST;
- RestartServer(std::shared_ptr<AuthMetadataProcessor>());
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- // Send server_try_cancel in the client metadata
- context.AddMetadata(kServerTryCancelRequest,
+ num_msgs_read++;
+ }
+ gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
+
+ Status s = stream->Finish();
+
+ // Depending on the value of server_try_cancel, the RPC might have been
+ // cancelled by the server at different stages. The following validates our
+ // expectations of number of messages read in various cancellation
+ // scenarios:
+ switch (server_try_cancel) {
+ case CANCEL_BEFORE_PROCESSING:
+ // Server cancelled before sending any messages. Which means the client
+ // wouldn't have read any
+ EXPECT_EQ(num_msgs_read, 0);
+ break;
+
+ case CANCEL_DURING_PROCESSING:
+ // Server cancelled while writing messages. Client must have read less
+ // than or equal to the expected number of messages
+ EXPECT_LE(num_msgs_read, kServerDefaultResponseStreamsToSend);
+ break;
+
+ case CANCEL_AFTER_PROCESSING:
+ // Even though the Server cancelled after writing all messages, the RPC
+ // may be cancelled before the Client got a chance to read all the
+ // messages.
+ EXPECT_LE(num_msgs_read, kServerDefaultResponseStreamsToSend);
+ break;
+
+ default: {
+ gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
+ server_try_cancel);
+ EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
+ server_try_cancel <= CANCEL_AFTER_PROCESSING);
+ break;
+ }
+ }
+
+ EXPECT_FALSE(s.ok());
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+ }
+
+ // Helper for testing bidirectional-streaming RPCs which are cancelled on the
+ // server. Depending on the value of server_try_cancel parameter, this will
+ // test one of the following three scenarios:
+ // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading/
+ // writing any messages from/to the client
+ //
+ // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading/
+ // writing messages from/to the client
+ //
+ // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading/writing
+ // all the messages from/to the client
+ //
+ // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
+ void TestBidiStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel,
+ int num_messages) {
+ MAYBE_SKIP_TEST;
+ RestartServer(std::shared_ptr<AuthMetadataProcessor>());
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ // Send server_try_cancel in the client metadata
+ context.AddMetadata(kServerTryCancelRequest,
ToString(server_try_cancel));
-
- auto stream = stub_->BidiStream(&context);
-
- int num_msgs_read = 0;
- int num_msgs_sent = 0;
- while (num_msgs_sent < num_messages) {
+
+ auto stream = stub_->BidiStream(&context);
+
+ int num_msgs_read = 0;
+ int num_msgs_sent = 0;
+ while (num_msgs_sent < num_messages) {
request.set_message("hello " + ToString(num_msgs_sent));
- if (!stream->Write(request)) {
- break;
- }
- num_msgs_sent++;
-
- if (!stream->Read(&response)) {
- break;
- }
- num_msgs_read++;
-
- EXPECT_EQ(response.message(), request.message());
- }
- gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
- gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
-
- stream->WritesDone();
- Status s = stream->Finish();
-
- // Depending on the value of server_try_cancel, the RPC might have been
- // cancelled by the server at different stages. The following validates our
- // expectations of number of messages read in various cancellation
- // scenarios:
- switch (server_try_cancel) {
- case CANCEL_BEFORE_PROCESSING:
- EXPECT_EQ(num_msgs_read, 0);
- break;
-
- case CANCEL_DURING_PROCESSING:
- EXPECT_LE(num_msgs_sent, num_messages);
- EXPECT_LE(num_msgs_read, num_msgs_sent);
- break;
-
- case CANCEL_AFTER_PROCESSING:
- EXPECT_EQ(num_msgs_sent, num_messages);
-
- // The Server cancelled after reading the last message and after writing
- // the message to the client. However, the RPC cancellation might have
- // taken effect before the client actually read the response.
- EXPECT_LE(num_msgs_read, num_msgs_sent);
- break;
-
- default:
- gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
- server_try_cancel);
- EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
- server_try_cancel <= CANCEL_AFTER_PROCESSING);
- break;
- }
-
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- // Make sure that the server interceptors were notified
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
- }
-};
-
-TEST_P(End2endServerTryCancelTest, RequestEchoServerCancel) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- context.AddMetadata(kServerTryCancelRequest,
+ if (!stream->Write(request)) {
+ break;
+ }
+ num_msgs_sent++;
+
+ if (!stream->Read(&response)) {
+ break;
+ }
+ num_msgs_read++;
+
+ EXPECT_EQ(response.message(), request.message());
+ }
+ gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
+ gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
+
+ stream->WritesDone();
+ Status s = stream->Finish();
+
+ // Depending on the value of server_try_cancel, the RPC might have been
+ // cancelled by the server at different stages. The following validates our
+ // expectations of number of messages read in various cancellation
+ // scenarios:
+ switch (server_try_cancel) {
+ case CANCEL_BEFORE_PROCESSING:
+ EXPECT_EQ(num_msgs_read, 0);
+ break;
+
+ case CANCEL_DURING_PROCESSING:
+ EXPECT_LE(num_msgs_sent, num_messages);
+ EXPECT_LE(num_msgs_read, num_msgs_sent);
+ break;
+
+ case CANCEL_AFTER_PROCESSING:
+ EXPECT_EQ(num_msgs_sent, num_messages);
+
+ // The Server cancelled after reading the last message and after writing
+ // the message to the client. However, the RPC cancellation might have
+ // taken effect before the client actually read the response.
+ EXPECT_LE(num_msgs_read, num_msgs_sent);
+ break;
+
+ default:
+ gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
+ server_try_cancel);
+ EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
+ server_try_cancel <= CANCEL_AFTER_PROCESSING);
+ break;
+ }
+
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ // Make sure that the server interceptors were notified
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+ }
+};
+
+TEST_P(End2endServerTryCancelTest, RequestEchoServerCancel) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ context.AddMetadata(kServerTryCancelRequest,
ToString(CANCEL_BEFORE_PROCESSING));
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
-}
-
-// Server to cancel before doing reading the request
-TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelBeforeReads) {
- TestRequestStreamServerCancel(CANCEL_BEFORE_PROCESSING, 1);
-}
-
-// Server to cancel while reading a request from the stream in parallel
-TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelDuringRead) {
- TestRequestStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
-}
-
-// Server to cancel after reading all the requests but before returning to the
-// client
-TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelAfterReads) {
- TestRequestStreamServerCancel(CANCEL_AFTER_PROCESSING, 4);
-}
-
-// Server to cancel before sending any response messages
-TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelBefore) {
- TestResponseStreamServerCancel(CANCEL_BEFORE_PROCESSING);
-}
-
-// Server to cancel while writing a response to the stream in parallel
-TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelDuring) {
- TestResponseStreamServerCancel(CANCEL_DURING_PROCESSING);
-}
-
-// Server to cancel after writing all the respones to the stream but before
-// returning to the client
-TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelAfter) {
- TestResponseStreamServerCancel(CANCEL_AFTER_PROCESSING);
-}
-
-// Server to cancel before reading/writing any requests/responses on the stream
-TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelBefore) {
- TestBidiStreamServerCancel(CANCEL_BEFORE_PROCESSING, 2);
-}
-
-// Server to cancel while reading/writing requests/responses on the stream in
-// parallel
-TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelDuring) {
- TestBidiStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
-}
-
-// Server to cancel after reading/writing all requests/responses on the stream
-// but before returning to the client
-TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelAfter) {
- TestBidiStreamServerCancel(CANCEL_AFTER_PROCESSING, 5);
-}
-
-TEST_P(End2endTest, SimpleRpcWithCustomUserAgentPrefix) {
- MAYBE_SKIP_TEST;
- // User-Agent is an HTTP header for HTTP transports only
- if (GetParam().inproc) {
- return;
- }
- user_agent_prefix_ = "custom_prefix";
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello hello hello hello");
- request.mutable_param()->set_echo_metadata(true);
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
- const auto& trailing_metadata = context.GetServerTrailingMetadata();
- auto iter = trailing_metadata.find("user-agent");
- EXPECT_TRUE(iter != trailing_metadata.end());
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+}
+
+// Server to cancel before doing reading the request
+TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelBeforeReads) {
+ TestRequestStreamServerCancel(CANCEL_BEFORE_PROCESSING, 1);
+}
+
+// Server to cancel while reading a request from the stream in parallel
+TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelDuringRead) {
+ TestRequestStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
+}
+
+// Server to cancel after reading all the requests but before returning to the
+// client
+TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelAfterReads) {
+ TestRequestStreamServerCancel(CANCEL_AFTER_PROCESSING, 4);
+}
+
+// Server to cancel before sending any response messages
+TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelBefore) {
+ TestResponseStreamServerCancel(CANCEL_BEFORE_PROCESSING);
+}
+
+// Server to cancel while writing a response to the stream in parallel
+TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelDuring) {
+ TestResponseStreamServerCancel(CANCEL_DURING_PROCESSING);
+}
+
+// Server to cancel after writing all the respones to the stream but before
+// returning to the client
+TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelAfter) {
+ TestResponseStreamServerCancel(CANCEL_AFTER_PROCESSING);
+}
+
+// Server to cancel before reading/writing any requests/responses on the stream
+TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelBefore) {
+ TestBidiStreamServerCancel(CANCEL_BEFORE_PROCESSING, 2);
+}
+
+// Server to cancel while reading/writing requests/responses on the stream in
+// parallel
+TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelDuring) {
+ TestBidiStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
+}
+
+// Server to cancel after reading/writing all requests/responses on the stream
+// but before returning to the client
+TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelAfter) {
+ TestBidiStreamServerCancel(CANCEL_AFTER_PROCESSING, 5);
+}
+
+TEST_P(End2endTest, SimpleRpcWithCustomUserAgentPrefix) {
+ MAYBE_SKIP_TEST;
+ // User-Agent is an HTTP header for HTTP transports only
+ if (GetParam().inproc) {
+ return;
+ }
+ user_agent_prefix_ = "custom_prefix";
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello hello hello hello");
+ request.mutable_param()->set_echo_metadata(true);
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+ const auto& trailing_metadata = context.GetServerTrailingMetadata();
+ auto iter = trailing_metadata.find("user-agent");
+ EXPECT_TRUE(iter != trailing_metadata.end());
TString expected_prefix = user_agent_prefix_ + " grpc-c++/";
- EXPECT_TRUE(iter->second.starts_with(expected_prefix)) << iter->second;
-}
-
-TEST_P(End2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
- MAYBE_SKIP_TEST;
- ResetStub();
- std::vector<std::thread> threads;
- threads.reserve(10);
- for (int i = 0; i < 10; ++i) {
- threads.emplace_back(SendRpc, stub_.get(), 10, true);
- }
- for (int i = 0; i < 10; ++i) {
- threads[i].join();
- }
-}
-
-TEST_P(End2endTest, MultipleRpcs) {
- MAYBE_SKIP_TEST;
- ResetStub();
- std::vector<std::thread> threads;
- threads.reserve(10);
- for (int i = 0; i < 10; ++i) {
- threads.emplace_back(SendRpc, stub_.get(), 10, false);
- }
- for (int i = 0; i < 10; ++i) {
- threads[i].join();
- }
-}
-
+ EXPECT_TRUE(iter->second.starts_with(expected_prefix)) << iter->second;
+}
+
+TEST_P(End2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ std::vector<std::thread> threads;
+ threads.reserve(10);
+ for (int i = 0; i < 10; ++i) {
+ threads.emplace_back(SendRpc, stub_.get(), 10, true);
+ }
+ for (int i = 0; i < 10; ++i) {
+ threads[i].join();
+ }
+}
+
+TEST_P(End2endTest, MultipleRpcs) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ std::vector<std::thread> threads;
+ threads.reserve(10);
+ for (int i = 0; i < 10; ++i) {
+ threads.emplace_back(SendRpc, stub_.get(), 10, false);
+ }
+ for (int i = 0; i < 10; ++i) {
+ threads[i].join();
+ }
+}
+
TEST_P(End2endTest, ManyStubs) {
MAYBE_SKIP_TEST;
ResetStub();
@@ -887,37 +887,37 @@ TEST_P(End2endTest, ManyStubs) {
EXPECT_GT(peer.registration_attempts(), registration_attempts_pre);
}
-TEST_P(End2endTest, EmptyBinaryMetadata) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello hello hello hello");
- ClientContext context;
- context.AddMetadata("custom-bin", "");
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, ReconnectChannel) {
- MAYBE_SKIP_TEST;
- if (GetParam().inproc) {
- return;
- }
- int poller_slowdown_factor = 1;
- // It needs 2 pollset_works to reconnect the channel with polling engine
- // "poll"
-#ifdef GRPC_POSIX_SOCKET_EV
- grpc_core::UniquePtr<char> poller = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
- if (0 == strcmp(poller.get(), "poll")) {
- poller_slowdown_factor = 2;
- }
-#endif // GRPC_POSIX_SOCKET_EV
- ResetStub();
- SendRpc(stub_.get(), 1, false);
- RestartServer(std::shared_ptr<AuthMetadataProcessor>());
- // It needs more than GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS time to
+TEST_P(End2endTest, EmptyBinaryMetadata) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello hello hello hello");
+ ClientContext context;
+ context.AddMetadata("custom-bin", "");
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, ReconnectChannel) {
+ MAYBE_SKIP_TEST;
+ if (GetParam().inproc) {
+ return;
+ }
+ int poller_slowdown_factor = 1;
+ // It needs 2 pollset_works to reconnect the channel with polling engine
+ // "poll"
+#ifdef GRPC_POSIX_SOCKET_EV
+ grpc_core::UniquePtr<char> poller = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
+ if (0 == strcmp(poller.get(), "poll")) {
+ poller_slowdown_factor = 2;
+ }
+#endif // GRPC_POSIX_SOCKET_EV
+ ResetStub();
+ SendRpc(stub_.get(), 1, false);
+ RestartServer(std::shared_ptr<AuthMetadataProcessor>());
+ // It needs more than GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS time to
// reconnect the channel. Make it a factor of 5x
gpr_sleep_until(
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
@@ -925,309 +925,309 @@ TEST_P(End2endTest, ReconnectChannel) {
poller_slowdown_factor *
grpc_test_slowdown_factor(),
GPR_TIMESPAN)));
- SendRpc(stub_.get(), 1, false);
-}
-
-TEST_P(End2endTest, RequestStreamOneRequest) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- auto stream = stub_->RequestStream(&context, &response);
- request.set_message("hello");
- EXPECT_TRUE(stream->Write(request));
- stream->WritesDone();
- Status s = stream->Finish();
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
- EXPECT_TRUE(context.debug_error_string().empty());
-}
-
-TEST_P(End2endTest, RequestStreamOneRequestWithCoalescingApi) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- context.set_initial_metadata_corked(true);
- auto stream = stub_->RequestStream(&context, &response);
- request.set_message("hello");
- stream->WriteLast(request, WriteOptions());
- Status s = stream->Finish();
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, RequestStreamTwoRequests) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- auto stream = stub_->RequestStream(&context, &response);
- request.set_message("hello");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Write(request));
- stream->WritesDone();
- Status s = stream->Finish();
- EXPECT_EQ(response.message(), "hellohello");
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, RequestStreamTwoRequestsWithWriteThrough) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- auto stream = stub_->RequestStream(&context, &response);
- request.set_message("hello");
- EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
- EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
- stream->WritesDone();
- Status s = stream->Finish();
- EXPECT_EQ(response.message(), "hellohello");
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, RequestStreamTwoRequestsWithCoalescingApi) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- context.set_initial_metadata_corked(true);
- auto stream = stub_->RequestStream(&context, &response);
- request.set_message("hello");
- EXPECT_TRUE(stream->Write(request));
- stream->WriteLast(request, WriteOptions());
- Status s = stream->Finish();
- EXPECT_EQ(response.message(), "hellohello");
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, ResponseStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
-
- auto stream = stub_->ResponseStream(&context, request);
- for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
- EXPECT_TRUE(stream->Read(&response));
+ SendRpc(stub_.get(), 1, false);
+}
+
+TEST_P(End2endTest, RequestStreamOneRequest) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ auto stream = stub_->RequestStream(&context, &response);
+ request.set_message("hello");
+ EXPECT_TRUE(stream->Write(request));
+ stream->WritesDone();
+ Status s = stream->Finish();
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+ EXPECT_TRUE(context.debug_error_string().empty());
+}
+
+TEST_P(End2endTest, RequestStreamOneRequestWithCoalescingApi) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ context.set_initial_metadata_corked(true);
+ auto stream = stub_->RequestStream(&context, &response);
+ request.set_message("hello");
+ stream->WriteLast(request, WriteOptions());
+ Status s = stream->Finish();
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, RequestStreamTwoRequests) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ auto stream = stub_->RequestStream(&context, &response);
+ request.set_message("hello");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Write(request));
+ stream->WritesDone();
+ Status s = stream->Finish();
+ EXPECT_EQ(response.message(), "hellohello");
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, RequestStreamTwoRequestsWithWriteThrough) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ auto stream = stub_->RequestStream(&context, &response);
+ request.set_message("hello");
+ EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
+ EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
+ stream->WritesDone();
+ Status s = stream->Finish();
+ EXPECT_EQ(response.message(), "hellohello");
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, RequestStreamTwoRequestsWithCoalescingApi) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ context.set_initial_metadata_corked(true);
+ auto stream = stub_->RequestStream(&context, &response);
+ request.set_message("hello");
+ EXPECT_TRUE(stream->Write(request));
+ stream->WriteLast(request, WriteOptions());
+ Status s = stream->Finish();
+ EXPECT_EQ(response.message(), "hellohello");
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, ResponseStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+
+ auto stream = stub_->ResponseStream(&context, request);
+ for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
+ EXPECT_TRUE(stream->Read(&response));
EXPECT_EQ(response.message(), request.message() + ToString(i));
- }
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, ResponseStreamWithCoalescingApi) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
- context.AddMetadata(kServerUseCoalescingApi, "1");
-
- auto stream = stub_->ResponseStream(&context, request);
- for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
- EXPECT_TRUE(stream->Read(&response));
+ }
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, ResponseStreamWithCoalescingApi) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+ context.AddMetadata(kServerUseCoalescingApi, "1");
+
+ auto stream = stub_->ResponseStream(&context, request);
+ for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
+ EXPECT_TRUE(stream->Read(&response));
EXPECT_EQ(response.message(), request.message() + ToString(i));
- }
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-// This was added to prevent regression from issue:
-// https://github.com/grpc/grpc/issues/11546
-TEST_P(End2endTest, ResponseStreamWithEverythingCoalesced) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
- context.AddMetadata(kServerUseCoalescingApi, "1");
- // We will only send one message, forcing everything (init metadata, message,
- // trailing) to be coalesced together.
- context.AddMetadata(kServerResponseStreamsToSend, "1");
-
- auto stream = stub_->ResponseStream(&context, request);
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "0");
-
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, BidiStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
+ }
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+// This was added to prevent regression from issue:
+// https://github.com/grpc/grpc/issues/11546
+TEST_P(End2endTest, ResponseStreamWithEverythingCoalesced) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+ context.AddMetadata(kServerUseCoalescingApi, "1");
+ // We will only send one message, forcing everything (init metadata, message,
+ // trailing) to be coalesced together.
+ context.AddMetadata(kServerResponseStreamsToSend, "1");
+
+ auto stream = stub_->ResponseStream(&context, request);
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "0");
+
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, BidiStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
TString msg("hello");
-
- auto stream = stub_->BidiStream(&context);
-
- for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
+
+ auto stream = stub_->BidiStream(&context);
+
+ for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
request.set_message(msg + ToString(i));
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
- }
-
- stream->WritesDone();
- EXPECT_FALSE(stream->Read(&response));
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, BidiStreamWithCoalescingApi) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.AddMetadata(kServerFinishAfterNReads, "3");
- context.set_initial_metadata_corked(true);
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+ }
+
+ stream->WritesDone();
+ EXPECT_FALSE(stream->Read(&response));
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, BidiStreamWithCoalescingApi) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.AddMetadata(kServerFinishAfterNReads, "3");
+ context.set_initial_metadata_corked(true);
TString msg("hello");
-
- auto stream = stub_->BidiStream(&context);
-
- request.set_message(msg + "0");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "1");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "2");
- stream->WriteLast(request, WriteOptions());
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- EXPECT_FALSE(stream->Read(&response));
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-// This was added to prevent regression from issue:
-// https://github.com/grpc/grpc/issues/11546
-TEST_P(End2endTest, BidiStreamWithEverythingCoalesced) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.AddMetadata(kServerFinishAfterNReads, "1");
- context.set_initial_metadata_corked(true);
+
+ auto stream = stub_->BidiStream(&context);
+
+ request.set_message(msg + "0");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "1");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "2");
+ stream->WriteLast(request, WriteOptions());
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ EXPECT_FALSE(stream->Read(&response));
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+// This was added to prevent regression from issue:
+// https://github.com/grpc/grpc/issues/11546
+TEST_P(End2endTest, BidiStreamWithEverythingCoalesced) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.AddMetadata(kServerFinishAfterNReads, "1");
+ context.set_initial_metadata_corked(true);
TString msg("hello");
-
- auto stream = stub_->BidiStream(&context);
-
- request.set_message(msg + "0");
- stream->WriteLast(request, WriteOptions());
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- EXPECT_FALSE(stream->Read(&response));
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-// Talk to the two services with the same name but different package names.
-// The two stubs are created on the same channel.
-TEST_P(End2endTest, DiffPackageServices) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-
- std::unique_ptr<grpc::testing::duplicate::EchoTestService::Stub> dup_pkg_stub(
- grpc::testing::duplicate::EchoTestService::NewStub(channel_));
- ClientContext context2;
- s = dup_pkg_stub->Echo(&context2, request, &response);
- EXPECT_EQ("no package", response.message());
- EXPECT_TRUE(s.ok());
-}
-
-template <class ServiceType>
-void CancelRpc(ClientContext* context, int delay_us, ServiceType* service) {
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(delay_us, GPR_TIMESPAN)));
- while (!service->signal_client()) {
- }
- context->TryCancel();
-}
-
-TEST_P(End2endTest, CancelRpcBeforeStart) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
- context.TryCancel();
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ("", response.message());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
+
+ auto stream = stub_->BidiStream(&context);
+
+ request.set_message(msg + "0");
+ stream->WriteLast(request, WriteOptions());
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ EXPECT_FALSE(stream->Read(&response));
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+// Talk to the two services with the same name but different package names.
+// The two stubs are created on the same channel.
+TEST_P(End2endTest, DiffPackageServices) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+
+ std::unique_ptr<grpc::testing::duplicate::EchoTestService::Stub> dup_pkg_stub(
+ grpc::testing::duplicate::EchoTestService::NewStub(channel_));
+ ClientContext context2;
+ s = dup_pkg_stub->Echo(&context2, request, &response);
+ EXPECT_EQ("no package", response.message());
+ EXPECT_TRUE(s.ok());
+}
+
+template <class ServiceType>
+void CancelRpc(ClientContext* context, int delay_us, ServiceType* service) {
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_micros(delay_us, GPR_TIMESPAN)));
+ while (!service->signal_client()) {
+ }
+ context->TryCancel();
+}
+
+TEST_P(End2endTest, CancelRpcBeforeStart) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+ context.TryCancel();
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ("", response.message());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
TEST_P(End2endTest, CancelRpcAfterStart) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
request.mutable_param()->set_server_notify_client_when_started(true);
- request.mutable_param()->set_skip_cancelled_check(true);
- Status s;
- std::thread echo_thread([this, &s, &context, &request, &response] {
- s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
- });
+ request.mutable_param()->set_skip_cancelled_check(true);
+ Status s;
+ std::thread echo_thread([this, &s, &context, &request, &response] {
+ s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
+ });
if (!GetParam().callback_server) {
service_.ClientWaitUntilRpcStarted();
} else {
callback_service_.ClientWaitUntilRpcStarted();
}
- context.TryCancel();
+ context.TryCancel();
if (!GetParam().callback_server) {
service_.SignalServerToContinue();
@@ -1235,1123 +1235,1123 @@ TEST_P(End2endTest, CancelRpcAfterStart) {
callback_service_.SignalServerToContinue();
}
- echo_thread.join();
- EXPECT_EQ("", response.message());
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Client cancels request stream after sending two messages
-TEST_P(End2endTest, ClientCancelsRequestStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
-
- auto stream = stub_->RequestStream(&context, &response);
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Write(request));
-
- context.TryCancel();
-
- Status s = stream->Finish();
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
-
- EXPECT_EQ(response.message(), "");
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Client cancels server stream after sending some messages
-TEST_P(End2endTest, ClientCancelsResponseStream) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("hello");
-
- auto stream = stub_->ResponseStream(&context, request);
-
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "0");
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "1");
-
- context.TryCancel();
-
- // The cancellation races with responses, so there might be zero or
- // one responses pending, read till failure
-
- if (stream->Read(&response)) {
- EXPECT_EQ(response.message(), request.message() + "2");
- // Since we have cancelled, we expect the next attempt to read to fail
- EXPECT_FALSE(stream->Read(&response));
- }
-
- Status s = stream->Finish();
- // The final status could be either of CANCELLED or OK depending on
- // who won the race.
- EXPECT_GE(grpc::StatusCode::CANCELLED, s.error_code());
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-// Client cancels bidi stream after sending some messages
-TEST_P(End2endTest, ClientCancelsBidi) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
+ echo_thread.join();
+ EXPECT_EQ("", response.message());
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Client cancels request stream after sending two messages
+TEST_P(End2endTest, ClientCancelsRequestStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+
+ auto stream = stub_->RequestStream(&context, &response);
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Write(request));
+
+ context.TryCancel();
+
+ Status s = stream->Finish();
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+
+ EXPECT_EQ(response.message(), "");
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Client cancels server stream after sending some messages
+TEST_P(End2endTest, ClientCancelsResponseStream) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("hello");
+
+ auto stream = stub_->ResponseStream(&context, request);
+
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "0");
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "1");
+
+ context.TryCancel();
+
+ // The cancellation races with responses, so there might be zero or
+ // one responses pending, read till failure
+
+ if (stream->Read(&response)) {
+ EXPECT_EQ(response.message(), request.message() + "2");
+ // Since we have cancelled, we expect the next attempt to read to fail
+ EXPECT_FALSE(stream->Read(&response));
+ }
+
+ Status s = stream->Finish();
+ // The final status could be either of CANCELLED or OK depending on
+ // who won the race.
+ EXPECT_GE(grpc::StatusCode::CANCELLED, s.error_code());
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+// Client cancels bidi stream after sending some messages
+TEST_P(End2endTest, ClientCancelsBidi) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
TString msg("hello");
-
- auto stream = stub_->BidiStream(&context);
-
- request.set_message(msg + "0");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "1");
- EXPECT_TRUE(stream->Write(request));
-
- context.TryCancel();
-
- // The cancellation races with responses, so there might be zero or
- // one responses pending, read till failure
-
- if (stream->Read(&response)) {
- EXPECT_EQ(response.message(), request.message());
- // Since we have cancelled, we expect the next attempt to read to fail
- EXPECT_FALSE(stream->Read(&response));
- }
-
- Status s = stream->Finish();
- EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
- if (GetParam().use_interceptors) {
- EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
- }
-}
-
-TEST_P(End2endTest, RpcMaxMessageSize) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message(string(kMaxMessageSize_ * 2, 'a'));
- request.mutable_param()->set_server_die(true);
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
-}
-
-void ReaderThreadFunc(ClientReaderWriter<EchoRequest, EchoResponse>* stream,
- gpr_event* ev) {
- EchoResponse resp;
- gpr_event_set(ev, (void*)1);
- while (stream->Read(&resp)) {
- gpr_log(GPR_INFO, "Read message");
- }
-}
-
-// Run a Read and a WritesDone simultaneously.
-TEST_P(End2endTest, SimultaneousReadWritesDone) {
- MAYBE_SKIP_TEST;
- ResetStub();
- ClientContext context;
- gpr_event ev;
- gpr_event_init(&ev);
- auto stream = stub_->BidiStream(&context);
- std::thread reader_thread(ReaderThreadFunc, stream.get(), &ev);
- gpr_event_wait(&ev, gpr_inf_future(GPR_CLOCK_REALTIME));
- stream->WritesDone();
- reader_thread.join();
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(End2endTest, ChannelState) {
- MAYBE_SKIP_TEST;
- if (GetParam().inproc) {
- return;
- }
-
- ResetStub();
- // Start IDLE
- EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
-
- // Did not ask to connect, no state change.
- CompletionQueue cq;
- std::chrono::system_clock::time_point deadline =
- std::chrono::system_clock::now() + std::chrono::milliseconds(10);
- channel_->NotifyOnStateChange(GRPC_CHANNEL_IDLE, deadline, &cq, nullptr);
- void* tag;
- bool ok = true;
- cq.Next(&tag, &ok);
- EXPECT_FALSE(ok);
-
- EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
- EXPECT_TRUE(channel_->WaitForStateChange(GRPC_CHANNEL_IDLE,
- gpr_inf_future(GPR_CLOCK_REALTIME)));
- auto state = channel_->GetState(false);
- EXPECT_TRUE(state == GRPC_CHANNEL_CONNECTING || state == GRPC_CHANNEL_READY);
-}
-
-// Takes 10s.
-TEST_P(End2endTest, ChannelStateTimeout) {
- if ((GetParam().credentials_type != kInsecureCredentialsType) ||
- GetParam().inproc) {
- return;
- }
- int port = grpc_pick_unused_port_or_die();
- std::ostringstream server_address;
- server_address << "127.0.0.1:" << port;
- // Channel to non-existing server
- auto channel =
- grpc::CreateChannel(server_address.str(), InsecureChannelCredentials());
- // Start IDLE
- EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(true));
-
- auto state = GRPC_CHANNEL_IDLE;
- for (int i = 0; i < 10; i++) {
- channel->WaitForStateChange(
- state, std::chrono::system_clock::now() + std::chrono::seconds(1));
- state = channel->GetState(false);
- }
-}
-
-// Talking to a non-existing service.
-TEST_P(End2endTest, NonExistingService) {
- MAYBE_SKIP_TEST;
- ResetChannel();
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel_);
-
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- ClientContext context;
- Status s = stub->Unimplemented(&context, request, &response);
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
- EXPECT_EQ("", s.error_message());
-}
-
-// Ask the server to send back a serialized proto in trailer.
-// This is an example of setting error details.
-TEST_P(End2endTest, BinaryTrailerTest) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- request.mutable_param()->set_echo_metadata(true);
- DebugInfo* info = request.mutable_param()->mutable_debug_info();
- info->add_stack_entries("stack_entry_1");
- info->add_stack_entries("stack_entry_2");
- info->add_stack_entries("stack_entry_3");
- info->set_detail("detailed debug info");
+
+ auto stream = stub_->BidiStream(&context);
+
+ request.set_message(msg + "0");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "1");
+ EXPECT_TRUE(stream->Write(request));
+
+ context.TryCancel();
+
+ // The cancellation races with responses, so there might be zero or
+ // one responses pending, read till failure
+
+ if (stream->Read(&response)) {
+ EXPECT_EQ(response.message(), request.message());
+ // Since we have cancelled, we expect the next attempt to read to fail
+ EXPECT_FALSE(stream->Read(&response));
+ }
+
+ Status s = stream->Finish();
+ EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
+ if (GetParam().use_interceptors) {
+ EXPECT_EQ(20, DummyInterceptor::GetNumTimesCancel());
+ }
+}
+
+TEST_P(End2endTest, RpcMaxMessageSize) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message(string(kMaxMessageSize_ * 2, 'a'));
+ request.mutable_param()->set_server_die(true);
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+}
+
+void ReaderThreadFunc(ClientReaderWriter<EchoRequest, EchoResponse>* stream,
+ gpr_event* ev) {
+ EchoResponse resp;
+ gpr_event_set(ev, (void*)1);
+ while (stream->Read(&resp)) {
+ gpr_log(GPR_INFO, "Read message");
+ }
+}
+
+// Run a Read and a WritesDone simultaneously.
+TEST_P(End2endTest, SimultaneousReadWritesDone) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ ClientContext context;
+ gpr_event ev;
+ gpr_event_init(&ev);
+ auto stream = stub_->BidiStream(&context);
+ std::thread reader_thread(ReaderThreadFunc, stream.get(), &ev);
+ gpr_event_wait(&ev, gpr_inf_future(GPR_CLOCK_REALTIME));
+ stream->WritesDone();
+ reader_thread.join();
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(End2endTest, ChannelState) {
+ MAYBE_SKIP_TEST;
+ if (GetParam().inproc) {
+ return;
+ }
+
+ ResetStub();
+ // Start IDLE
+ EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
+
+ // Did not ask to connect, no state change.
+ CompletionQueue cq;
+ std::chrono::system_clock::time_point deadline =
+ std::chrono::system_clock::now() + std::chrono::milliseconds(10);
+ channel_->NotifyOnStateChange(GRPC_CHANNEL_IDLE, deadline, &cq, nullptr);
+ void* tag;
+ bool ok = true;
+ cq.Next(&tag, &ok);
+ EXPECT_FALSE(ok);
+
+ EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
+ EXPECT_TRUE(channel_->WaitForStateChange(GRPC_CHANNEL_IDLE,
+ gpr_inf_future(GPR_CLOCK_REALTIME)));
+ auto state = channel_->GetState(false);
+ EXPECT_TRUE(state == GRPC_CHANNEL_CONNECTING || state == GRPC_CHANNEL_READY);
+}
+
+// Takes 10s.
+TEST_P(End2endTest, ChannelStateTimeout) {
+ if ((GetParam().credentials_type != kInsecureCredentialsType) ||
+ GetParam().inproc) {
+ return;
+ }
+ int port = grpc_pick_unused_port_or_die();
+ std::ostringstream server_address;
+ server_address << "127.0.0.1:" << port;
+ // Channel to non-existing server
+ auto channel =
+ grpc::CreateChannel(server_address.str(), InsecureChannelCredentials());
+ // Start IDLE
+ EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(true));
+
+ auto state = GRPC_CHANNEL_IDLE;
+ for (int i = 0; i < 10; i++) {
+ channel->WaitForStateChange(
+ state, std::chrono::system_clock::now() + std::chrono::seconds(1));
+ state = channel->GetState(false);
+ }
+}
+
+// Talking to a non-existing service.
+TEST_P(End2endTest, NonExistingService) {
+ MAYBE_SKIP_TEST;
+ ResetChannel();
+ std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
+ stub = grpc::testing::UnimplementedEchoService::NewStub(channel_);
+
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ ClientContext context;
+ Status s = stub->Unimplemented(&context, request, &response);
+ EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
+ EXPECT_EQ("", s.error_message());
+}
+
+// Ask the server to send back a serialized proto in trailer.
+// This is an example of setting error details.
+TEST_P(End2endTest, BinaryTrailerTest) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ request.mutable_param()->set_echo_metadata(true);
+ DebugInfo* info = request.mutable_param()->mutable_debug_info();
+ info->add_stack_entries("stack_entry_1");
+ info->add_stack_entries("stack_entry_2");
+ info->add_stack_entries("stack_entry_3");
+ info->set_detail("detailed debug info");
TString expected_string = info->SerializeAsString();
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- auto trailers = context.GetServerTrailingMetadata();
- EXPECT_EQ(1u, trailers.count(kDebugInfoTrailerKey));
- auto iter = trailers.find(kDebugInfoTrailerKey);
- EXPECT_EQ(expected_string, iter->second);
- // Parse the returned trailer into a DebugInfo proto.
- DebugInfo returned_info;
- EXPECT_TRUE(returned_info.ParseFromString(ToString(iter->second)));
-}
-
-TEST_P(End2endTest, ExpectErrorTest) {
- MAYBE_SKIP_TEST;
- ResetStub();
-
- std::vector<ErrorStatus> expected_status;
- expected_status.emplace_back();
- expected_status.back().set_code(13); // INTERNAL
- // No Error message or details
-
- expected_status.emplace_back();
- expected_status.back().set_code(13); // INTERNAL
- expected_status.back().set_error_message("text error message");
- expected_status.back().set_binary_error_details("text error details");
-
- expected_status.emplace_back();
- expected_status.back().set_code(13); // INTERNAL
- expected_status.back().set_error_message("text error message");
- expected_status.back().set_binary_error_details(
- "\x0\x1\x2\x3\x4\x5\x6\x8\x9\xA\xB");
-
- for (auto iter = expected_status.begin(); iter != expected_status.end();
- ++iter) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- request.set_message("Hello");
- auto* error = request.mutable_param()->mutable_expected_error();
- error->set_code(iter->code());
- error->set_error_message(iter->error_message());
- error->set_binary_error_details(iter->binary_error_details());
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(iter->code(), s.error_code());
- EXPECT_EQ(iter->error_message(), s.error_message());
- EXPECT_EQ(iter->binary_error_details(), s.error_details());
- EXPECT_TRUE(context.debug_error_string().find("created") !=
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ auto trailers = context.GetServerTrailingMetadata();
+ EXPECT_EQ(1u, trailers.count(kDebugInfoTrailerKey));
+ auto iter = trailers.find(kDebugInfoTrailerKey);
+ EXPECT_EQ(expected_string, iter->second);
+ // Parse the returned trailer into a DebugInfo proto.
+ DebugInfo returned_info;
+ EXPECT_TRUE(returned_info.ParseFromString(ToString(iter->second)));
+}
+
+TEST_P(End2endTest, ExpectErrorTest) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+
+ std::vector<ErrorStatus> expected_status;
+ expected_status.emplace_back();
+ expected_status.back().set_code(13); // INTERNAL
+ // No Error message or details
+
+ expected_status.emplace_back();
+ expected_status.back().set_code(13); // INTERNAL
+ expected_status.back().set_error_message("text error message");
+ expected_status.back().set_binary_error_details("text error details");
+
+ expected_status.emplace_back();
+ expected_status.back().set_code(13); // INTERNAL
+ expected_status.back().set_error_message("text error message");
+ expected_status.back().set_binary_error_details(
+ "\x0\x1\x2\x3\x4\x5\x6\x8\x9\xA\xB");
+
+ for (auto iter = expected_status.begin(); iter != expected_status.end();
+ ++iter) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ request.set_message("Hello");
+ auto* error = request.mutable_param()->mutable_expected_error();
+ error->set_code(iter->code());
+ error->set_error_message(iter->error_message());
+ error->set_binary_error_details(iter->binary_error_details());
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(iter->code(), s.error_code());
+ EXPECT_EQ(iter->error_message(), s.error_message());
+ EXPECT_EQ(iter->binary_error_details(), s.error_details());
+ EXPECT_TRUE(context.debug_error_string().find("created") !=
TString::npos);
EXPECT_TRUE(context.debug_error_string().find("file") != TString::npos);
EXPECT_TRUE(context.debug_error_string().find("line") != TString::npos);
- EXPECT_TRUE(context.debug_error_string().find("status") !=
+ EXPECT_TRUE(context.debug_error_string().find("status") !=
TString::npos);
EXPECT_TRUE(context.debug_error_string().find("13") != TString::npos);
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-// Test with and without a proxy.
-class ProxyEnd2endTest : public End2endTest {
- protected:
-};
-
-TEST_P(ProxyEnd2endTest, SimpleRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- SendRpc(stub_.get(), 1, false);
-}
-
-TEST_P(ProxyEnd2endTest, SimpleRpcWithEmptyMessages) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(ProxyEnd2endTest, MultipleRpcs) {
- MAYBE_SKIP_TEST;
- ResetStub();
- std::vector<std::thread> threads;
- threads.reserve(10);
- for (int i = 0; i < 10; ++i) {
- threads.emplace_back(SendRpc, stub_.get(), 10, false);
- }
- for (int i = 0; i < 10; ++i) {
- threads[i].join();
- }
-}
-
-// Set a 10us deadline and make sure proper error is returned.
-TEST_P(ProxyEnd2endTest, RpcDeadlineExpires) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- request.mutable_param()->set_skip_cancelled_check(true);
- // Let server sleep for 40 ms first to guarantee expiry.
- // 40 ms might seem a bit extreme but the timer manager would have been just
- // initialized (when ResetStub() was called) and there are some warmup costs
- // i.e the timer thread many not have even started. There might also be other
- // delays in the timer manager thread (in acquiring locks, timer data
- // structure manipulations, starting backup timer threads) that add to the
- // delays. 40ms is still not enough in some cases but this significantly
- // reduces the test flakes
- request.mutable_param()->set_server_sleep_us(40 * 1000);
-
- ClientContext context;
- std::chrono::system_clock::time_point deadline =
- std::chrono::system_clock::now() + std::chrono::milliseconds(1);
- context.set_deadline(deadline);
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.error_code());
-}
-
-// Set a long but finite deadline.
-TEST_P(ProxyEnd2endTest, RpcLongDeadline) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- ClientContext context;
- std::chrono::system_clock::time_point deadline =
- std::chrono::system_clock::now() + std::chrono::hours(1);
- context.set_deadline(deadline);
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-}
-
-// Ask server to echo back the deadline it sees.
-TEST_P(ProxyEnd2endTest, EchoDeadline) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- request.mutable_param()->set_echo_deadline(true);
-
- ClientContext context;
- std::chrono::system_clock::time_point deadline =
- std::chrono::system_clock::now() + std::chrono::seconds(100);
- context.set_deadline(deadline);
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
- gpr_timespec sent_deadline;
- Timepoint2Timespec(deadline, &sent_deadline);
- // We want to allow some reasonable error given:
- // - request_deadline() only has 1sec resolution so the best we can do is +-1
- // - if sent_deadline.tv_nsec is very close to the next second's boundary we
- // can end up being off by 2 in one direction.
- EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 2);
- EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);
-}
-
-// Ask server to echo back the deadline it sees. The rpc has no deadline.
-TEST_P(ProxyEnd2endTest, EchoDeadlineForNoDeadlineRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- request.mutable_param()->set_echo_deadline(true);
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
- EXPECT_EQ(response.param().request_deadline(),
- gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec);
-}
-
-TEST_P(ProxyEnd2endTest, UnimplementedRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- ClientContext context;
- Status s = stub_->Unimplemented(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), grpc::StatusCode::UNIMPLEMENTED);
- EXPECT_EQ(s.error_message(), "");
- EXPECT_EQ(response.message(), "");
-}
-
-// Client cancels rpc after 10ms
-TEST_P(ProxyEnd2endTest, ClientCancelsRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- const int kCancelDelayUs = 10 * 1000;
- request.mutable_param()->set_client_cancel_after_us(kCancelDelayUs);
-
- ClientContext context;
- std::thread cancel_thread;
- if (!GetParam().callback_server) {
- cancel_thread = std::thread(
- [&context, this](int delay) { CancelRpc(&context, delay, &service_); },
- kCancelDelayUs);
- // Note: the unusual pattern above (and below) is caused by a conflict
- // between two sets of compiler expectations. clang allows const to be
- // captured without mention, so there is no need to capture kCancelDelayUs
- // (and indeed clang-tidy complains if you do so). OTOH, a Windows compiler
- // in our tests requires an explicit capture even for const. We square this
- // circle by passing the const value in as an argument to the lambda.
- } else {
- cancel_thread = std::thread(
- [&context, this](int delay) {
- CancelRpc(&context, delay, &callback_service_);
- },
- kCancelDelayUs);
- }
- Status s = stub_->Echo(&context, request, &response);
- cancel_thread.join();
- EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
- EXPECT_EQ(s.error_message(), "Cancelled");
-}
-
-// Server cancels rpc after 1ms
-TEST_P(ProxyEnd2endTest, ServerCancelsRpc) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- request.mutable_param()->set_server_cancel_after_us(1000);
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
- EXPECT_TRUE(s.error_message().empty());
-}
-
-// Make the response larger than the flow control window.
-TEST_P(ProxyEnd2endTest, HugeResponse) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("huge response");
- const size_t kResponseSize = 1024 * (1024 + 10);
- request.mutable_param()->set_response_message_length(kResponseSize);
-
- ClientContext context;
- std::chrono::system_clock::time_point deadline =
- std::chrono::system_clock::now() + std::chrono::seconds(20);
- context.set_deadline(deadline);
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(kResponseSize, response.message().size());
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(ProxyEnd2endTest, Peer) {
- MAYBE_SKIP_TEST;
- // Peer is not meaningful for inproc
- if (GetParam().inproc) {
- return;
- }
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("hello");
- request.mutable_param()->set_echo_peer(true);
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
- EXPECT_TRUE(CheckIsLocalhost(response.param().peer()));
- EXPECT_TRUE(CheckIsLocalhost(context.peer()));
-}
-
-//////////////////////////////////////////////////////////////////////////
-class SecureEnd2endTest : public End2endTest {
- protected:
- SecureEnd2endTest() {
- GPR_ASSERT(!GetParam().use_proxy);
- GPR_ASSERT(GetParam().credentials_type != kInsecureCredentialsType);
- }
-};
-
-TEST_P(SecureEnd2endTest, SimpleRpcWithHost) {
- MAYBE_SKIP_TEST;
- ResetStub();
-
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- ClientContext context;
- context.set_authority("foo.test.youtube.com");
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(response.has_param());
- EXPECT_EQ("special", response.param().host());
- EXPECT_TRUE(s.ok());
-}
-
-bool MetadataContains(
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+// Test with and without a proxy.
+class ProxyEnd2endTest : public End2endTest {
+ protected:
+};
+
+TEST_P(ProxyEnd2endTest, SimpleRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ SendRpc(stub_.get(), 1, false);
+}
+
+TEST_P(ProxyEnd2endTest, SimpleRpcWithEmptyMessages) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(ProxyEnd2endTest, MultipleRpcs) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ std::vector<std::thread> threads;
+ threads.reserve(10);
+ for (int i = 0; i < 10; ++i) {
+ threads.emplace_back(SendRpc, stub_.get(), 10, false);
+ }
+ for (int i = 0; i < 10; ++i) {
+ threads[i].join();
+ }
+}
+
+// Set a 10us deadline and make sure proper error is returned.
+TEST_P(ProxyEnd2endTest, RpcDeadlineExpires) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ request.mutable_param()->set_skip_cancelled_check(true);
+ // Let server sleep for 40 ms first to guarantee expiry.
+ // 40 ms might seem a bit extreme but the timer manager would have been just
+ // initialized (when ResetStub() was called) and there are some warmup costs
+ // i.e the timer thread many not have even started. There might also be other
+ // delays in the timer manager thread (in acquiring locks, timer data
+ // structure manipulations, starting backup timer threads) that add to the
+ // delays. 40ms is still not enough in some cases but this significantly
+ // reduces the test flakes
+ request.mutable_param()->set_server_sleep_us(40 * 1000);
+
+ ClientContext context;
+ std::chrono::system_clock::time_point deadline =
+ std::chrono::system_clock::now() + std::chrono::milliseconds(1);
+ context.set_deadline(deadline);
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.error_code());
+}
+
+// Set a long but finite deadline.
+TEST_P(ProxyEnd2endTest, RpcLongDeadline) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ ClientContext context;
+ std::chrono::system_clock::time_point deadline =
+ std::chrono::system_clock::now() + std::chrono::hours(1);
+ context.set_deadline(deadline);
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+}
+
+// Ask server to echo back the deadline it sees.
+TEST_P(ProxyEnd2endTest, EchoDeadline) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_deadline(true);
+
+ ClientContext context;
+ std::chrono::system_clock::time_point deadline =
+ std::chrono::system_clock::now() + std::chrono::seconds(100);
+ context.set_deadline(deadline);
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+ gpr_timespec sent_deadline;
+ Timepoint2Timespec(deadline, &sent_deadline);
+ // We want to allow some reasonable error given:
+ // - request_deadline() only has 1sec resolution so the best we can do is +-1
+ // - if sent_deadline.tv_nsec is very close to the next second's boundary we
+ // can end up being off by 2 in one direction.
+ EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 2);
+ EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);
+}
+
+// Ask server to echo back the deadline it sees. The rpc has no deadline.
+TEST_P(ProxyEnd2endTest, EchoDeadlineForNoDeadlineRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_deadline(true);
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+ EXPECT_EQ(response.param().request_deadline(),
+ gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec);
+}
+
+TEST_P(ProxyEnd2endTest, UnimplementedRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ ClientContext context;
+ Status s = stub_->Unimplemented(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), grpc::StatusCode::UNIMPLEMENTED);
+ EXPECT_EQ(s.error_message(), "");
+ EXPECT_EQ(response.message(), "");
+}
+
+// Client cancels rpc after 10ms
+TEST_P(ProxyEnd2endTest, ClientCancelsRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ const int kCancelDelayUs = 10 * 1000;
+ request.mutable_param()->set_client_cancel_after_us(kCancelDelayUs);
+
+ ClientContext context;
+ std::thread cancel_thread;
+ if (!GetParam().callback_server) {
+ cancel_thread = std::thread(
+ [&context, this](int delay) { CancelRpc(&context, delay, &service_); },
+ kCancelDelayUs);
+ // Note: the unusual pattern above (and below) is caused by a conflict
+ // between two sets of compiler expectations. clang allows const to be
+ // captured without mention, so there is no need to capture kCancelDelayUs
+ // (and indeed clang-tidy complains if you do so). OTOH, a Windows compiler
+ // in our tests requires an explicit capture even for const. We square this
+ // circle by passing the const value in as an argument to the lambda.
+ } else {
+ cancel_thread = std::thread(
+ [&context, this](int delay) {
+ CancelRpc(&context, delay, &callback_service_);
+ },
+ kCancelDelayUs);
+ }
+ Status s = stub_->Echo(&context, request, &response);
+ cancel_thread.join();
+ EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
+ EXPECT_EQ(s.error_message(), "Cancelled");
+}
+
+// Server cancels rpc after 1ms
+TEST_P(ProxyEnd2endTest, ServerCancelsRpc) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ request.mutable_param()->set_server_cancel_after_us(1000);
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
+ EXPECT_TRUE(s.error_message().empty());
+}
+
+// Make the response larger than the flow control window.
+TEST_P(ProxyEnd2endTest, HugeResponse) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("huge response");
+ const size_t kResponseSize = 1024 * (1024 + 10);
+ request.mutable_param()->set_response_message_length(kResponseSize);
+
+ ClientContext context;
+ std::chrono::system_clock::time_point deadline =
+ std::chrono::system_clock::now() + std::chrono::seconds(20);
+ context.set_deadline(deadline);
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(kResponseSize, response.message().size());
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(ProxyEnd2endTest, Peer) {
+ MAYBE_SKIP_TEST;
+ // Peer is not meaningful for inproc
+ if (GetParam().inproc) {
+ return;
+ }
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("hello");
+ request.mutable_param()->set_echo_peer(true);
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+ EXPECT_TRUE(CheckIsLocalhost(response.param().peer()));
+ EXPECT_TRUE(CheckIsLocalhost(context.peer()));
+}
+
+//////////////////////////////////////////////////////////////////////////
+class SecureEnd2endTest : public End2endTest {
+ protected:
+ SecureEnd2endTest() {
+ GPR_ASSERT(!GetParam().use_proxy);
+ GPR_ASSERT(GetParam().credentials_type != kInsecureCredentialsType);
+ }
+};
+
+TEST_P(SecureEnd2endTest, SimpleRpcWithHost) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ ClientContext context;
+ context.set_authority("foo.test.youtube.com");
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(response.has_param());
+ EXPECT_EQ("special", response.param().host());
+ EXPECT_TRUE(s.ok());
+}
+
+bool MetadataContains(
+ const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
const TString& key, const TString& value) {
- int count = 0;
-
- for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator iter =
- metadata.begin();
- iter != metadata.end(); ++iter) {
- if (ToString(iter->first) == key && ToString(iter->second) == value) {
- count++;
- }
- }
- return count == 1;
-}
-
-TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorSuccess) {
- MAYBE_SKIP_TEST;
- auto* processor = new TestAuthMetadataProcessor(true);
- StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(processor->GetCompatibleClientCreds());
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
- request.mutable_param()->set_expected_client_identity(
- TestAuthMetadataProcessor::kGoodGuy);
- request.mutable_param()->set_expected_transport_security_type(
- GetParam().credentials_type);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
-
- // Metadata should have been consumed by the processor.
- EXPECT_FALSE(MetadataContains(
- context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
+ int count = 0;
+
+ for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator iter =
+ metadata.begin();
+ iter != metadata.end(); ++iter) {
+ if (ToString(iter->first) == key && ToString(iter->second) == value) {
+ count++;
+ }
+ }
+ return count == 1;
+}
+
+TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorSuccess) {
+ MAYBE_SKIP_TEST;
+ auto* processor = new TestAuthMetadataProcessor(true);
+ StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(processor->GetCompatibleClientCreds());
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+ request.mutable_param()->set_expected_client_identity(
+ TestAuthMetadataProcessor::kGoodGuy);
+ request.mutable_param()->set_expected_transport_security_type(
+ GetParam().credentials_type);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+
+ // Metadata should have been consumed by the processor.
+ EXPECT_FALSE(MetadataContains(
+ context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
TString("Bearer ") + TestAuthMetadataProcessor::kGoodGuy));
-}
-
-TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorFailure) {
- MAYBE_SKIP_TEST;
- auto* processor = new TestAuthMetadataProcessor(true);
- StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(processor->GetIncompatibleClientCreds());
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
-}
-
-TEST_P(SecureEnd2endTest, SetPerCallCredentials) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- std::shared_ptr<CallCredentials> creds =
+}
+
+TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorFailure) {
+ MAYBE_SKIP_TEST;
+ auto* processor = new TestAuthMetadataProcessor(true);
+ StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(processor->GetIncompatibleClientCreds());
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
+}
+
+TEST_P(SecureEnd2endTest, SetPerCallCredentials) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ std::shared_ptr<CallCredentials> creds =
GoogleIAMCredentials(kFakeToken, kFakeSelector);
- context.set_credentials(creds);
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
+ context.set_credentials(creds);
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
kFakeToken));
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
kFakeSelector));
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedFakeCredsDebugString);
-}
-
-class CredentialsInterceptor : public experimental::Interceptor {
- public:
- CredentialsInterceptor(experimental::ClientRpcInfo* info) : info_(info) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- std::shared_ptr<CallCredentials> creds =
+}
+
+class CredentialsInterceptor : public experimental::Interceptor {
+ public:
+ CredentialsInterceptor(experimental::ClientRpcInfo* info) : info_(info) {}
+
+ void Intercept(experimental::InterceptorBatchMethods* methods) {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ std::shared_ptr<CallCredentials> creds =
GoogleIAMCredentials(kFakeToken, kFakeSelector);
- info_->client_context()->set_credentials(creds);
- }
- methods->Proceed();
- }
-
- private:
- experimental::ClientRpcInfo* info_ = nullptr;
-};
-
-class CredentialsInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- CredentialsInterceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) {
- return new CredentialsInterceptor(info);
- }
-};
-
-TEST_P(SecureEnd2endTest, CallCredentialsInterception) {
- MAYBE_SKIP_TEST;
- if (!GetParam().use_interceptors) {
- return;
- }
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators;
- interceptor_creators.push_back(std::unique_ptr<CredentialsInterceptorFactory>(
- new CredentialsInterceptorFactory()));
- ResetStub(std::move(interceptor_creators));
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
+ info_->client_context()->set_credentials(creds);
+ }
+ methods->Proceed();
+ }
+
+ private:
+ experimental::ClientRpcInfo* info_ = nullptr;
+};
+
+class CredentialsInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface {
+ CredentialsInterceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* info) {
+ return new CredentialsInterceptor(info);
+ }
+};
+
+TEST_P(SecureEnd2endTest, CallCredentialsInterception) {
+ MAYBE_SKIP_TEST;
+ if (!GetParam().use_interceptors) {
+ return;
+ }
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators;
+ interceptor_creators.push_back(std::unique_ptr<CredentialsInterceptorFactory>(
+ new CredentialsInterceptorFactory()));
+ ResetStub(std::move(interceptor_creators));
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
kFakeToken));
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
kFakeSelector));
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedFakeCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, CallCredentialsInterceptionWithSetCredentials) {
- MAYBE_SKIP_TEST;
- if (!GetParam().use_interceptors) {
- return;
- }
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators;
- interceptor_creators.push_back(std::unique_ptr<CredentialsInterceptorFactory>(
- new CredentialsInterceptorFactory()));
- ResetStub(std::move(interceptor_creators));
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- std::shared_ptr<CallCredentials> creds1 =
+}
+
+TEST_P(SecureEnd2endTest, CallCredentialsInterceptionWithSetCredentials) {
+ MAYBE_SKIP_TEST;
+ if (!GetParam().use_interceptors) {
+ return;
+ }
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators;
+ interceptor_creators.push_back(std::unique_ptr<CredentialsInterceptorFactory>(
+ new CredentialsInterceptorFactory()));
+ ResetStub(std::move(interceptor_creators));
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ std::shared_ptr<CallCredentials> creds1 =
GoogleIAMCredentials(kWrongToken, kWrongSelector);
- context.set_credentials(creds1);
- EXPECT_EQ(context.credentials(), creds1);
+ context.set_credentials(creds1);
+ EXPECT_EQ(context.credentials(), creds1);
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedWrongCredsDebugString);
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
kFakeToken));
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
kFakeSelector));
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedFakeCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, OverridePerCallCredentials) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- std::shared_ptr<CallCredentials> creds1 =
+}
+
+TEST_P(SecureEnd2endTest, OverridePerCallCredentials) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ std::shared_ptr<CallCredentials> creds1 =
GoogleIAMCredentials(kFakeToken1, kFakeSelector1);
- context.set_credentials(creds1);
- EXPECT_EQ(context.credentials(), creds1);
+ context.set_credentials(creds1);
+ EXPECT_EQ(context.credentials(), creds1);
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedFakeCreds1DebugString);
- std::shared_ptr<CallCredentials> creds2 =
+ std::shared_ptr<CallCredentials> creds2 =
GoogleIAMCredentials(kFakeToken2, kFakeSelector2);
- context.set_credentials(creds2);
- EXPECT_EQ(context.credentials(), creds2);
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
+ context.set_credentials(creds2);
+ EXPECT_EQ(context.credentials(), creds2);
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
kFakeToken2));
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
kFakeSelector2));
- EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
+ EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
kFakeToken1));
- EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
- GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
+ EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
+ GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
kFakeSelector1));
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedFakeCreds2DebugString);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
-}
-
-TEST_P(SecureEnd2endTest, AuthMetadataPluginKeyFailure) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(
- TestMetadataCredentialsPlugin::kBadMetadataKey,
- "Does not matter, will fail the key is invalid.", false, true,
- 0))));
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+}
+
+TEST_P(SecureEnd2endTest, AuthMetadataPluginKeyFailure) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(
+ TestMetadataCredentialsPlugin::kBadMetadataKey,
+ "Does not matter, will fail the key is invalid.", false, true,
+ 0))));
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedAuthMetadataPluginKeyFailureCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, AuthMetadataPluginValueFailure) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(
- TestMetadataCredentialsPlugin::kGoodMetadataKey,
- "With illegal \n value.", false, true, 0))));
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
+}
+
+TEST_P(SecureEnd2endTest, AuthMetadataPluginValueFailure) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(
+ TestMetadataCredentialsPlugin::kGoodMetadataKey,
+ "With illegal \n value.", false, true, 0))));
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedAuthMetadataPluginValueFailureCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, AuthMetadataPluginWithDeadline) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- request.mutable_param()->set_skip_cancelled_check(true);
- EchoResponse response;
- ClientContext context;
- const int delay = 100;
- std::chrono::system_clock::time_point deadline =
- std::chrono::system_clock::now() + std::chrono::milliseconds(delay);
- context.set_deadline(deadline);
- context.set_credentials(grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
- true, delay))));
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- if (!s.ok()) {
- EXPECT_TRUE(s.error_code() == StatusCode::DEADLINE_EXCEEDED ||
- s.error_code() == StatusCode::UNAVAILABLE);
- }
+}
+
+TEST_P(SecureEnd2endTest, AuthMetadataPluginWithDeadline) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ request.mutable_param()->set_skip_cancelled_check(true);
+ EchoResponse response;
+ ClientContext context;
+ const int delay = 100;
+ std::chrono::system_clock::time_point deadline =
+ std::chrono::system_clock::now() + std::chrono::milliseconds(delay);
+ context.set_deadline(deadline);
+ context.set_credentials(grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
+ true, delay))));
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ if (!s.ok()) {
+ EXPECT_TRUE(s.error_code() == StatusCode::DEADLINE_EXCEEDED ||
+ s.error_code() == StatusCode::UNAVAILABLE);
+ }
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedAuthMetadataPluginWithDeadlineCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, AuthMetadataPluginWithCancel) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- request.mutable_param()->set_skip_cancelled_check(true);
- EchoResponse response;
- ClientContext context;
- const int delay = 100;
- context.set_credentials(grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
- true, delay))));
- request.set_message("Hello");
-
- std::thread cancel_thread([&] {
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(delay, GPR_TIMESPAN)));
- context.TryCancel();
- });
- Status s = stub_->Echo(&context, request, &response);
- if (!s.ok()) {
- EXPECT_TRUE(s.error_code() == StatusCode::CANCELLED ||
- s.error_code() == StatusCode::UNAVAILABLE);
- }
- cancel_thread.join();
+}
+
+TEST_P(SecureEnd2endTest, AuthMetadataPluginWithCancel) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ request.mutable_param()->set_skip_cancelled_check(true);
+ EchoResponse response;
+ ClientContext context;
+ const int delay = 100;
+ context.set_credentials(grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
+ true, delay))));
+ request.set_message("Hello");
+
+ std::thread cancel_thread([&] {
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_millis(delay, GPR_TIMESPAN)));
+ context.TryCancel();
+ });
+ Status s = stub_->Echo(&context, request, &response);
+ if (!s.ok()) {
+ EXPECT_TRUE(s.error_code() == StatusCode::CANCELLED ||
+ s.error_code() == StatusCode::UNAVAILABLE);
+ }
+ cancel_thread.join();
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedAuthMetadataPluginWithDeadlineCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginFailure) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(
- TestMetadataCredentialsPlugin::kGoodMetadataKey,
- "Does not matter, will fail anyway (see 3rd param)", false, false,
- 0))));
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
- EXPECT_EQ(s.error_message(),
+}
+
+TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginFailure) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(
+ TestMetadataCredentialsPlugin::kGoodMetadataKey,
+ "Does not matter, will fail anyway (see 3rd param)", false, false,
+ 0))));
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
+ EXPECT_EQ(s.error_message(),
TString("Getting metadata from plugin failed with error: ") +
- kTestCredsPluginErrorMsg);
+ kTestCredsPluginErrorMsg);
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedNonBlockingAuthMetadataPluginFailureCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorSuccess) {
- MAYBE_SKIP_TEST;
- auto* processor = new TestAuthMetadataProcessor(false);
- StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(processor->GetCompatibleClientCreds());
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
- request.mutable_param()->set_expected_client_identity(
- TestAuthMetadataProcessor::kGoodGuy);
- request.mutable_param()->set_expected_transport_security_type(
- GetParam().credentials_type);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
-
- // Metadata should have been consumed by the processor.
- EXPECT_FALSE(MetadataContains(
- context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
+}
+
+TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorSuccess) {
+ MAYBE_SKIP_TEST;
+ auto* processor = new TestAuthMetadataProcessor(false);
+ StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(processor->GetCompatibleClientCreds());
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+ request.mutable_param()->set_expected_client_identity(
+ TestAuthMetadataProcessor::kGoodGuy);
+ request.mutable_param()->set_expected_transport_security_type(
+ GetParam().credentials_type);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+
+ // Metadata should have been consumed by the processor.
+ EXPECT_FALSE(MetadataContains(
+ context.GetServerTrailingMetadata(), GRPC_AUTHORIZATION_METADATA_KEY,
TString("Bearer ") + TestAuthMetadataProcessor::kGoodGuy));
EXPECT_EQ(
context.credentials()->DebugString(),
kExpectedNonBlockingAuthMetadataPluginAndProcessorSuccessCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorFailure) {
- MAYBE_SKIP_TEST;
- auto* processor = new TestAuthMetadataProcessor(false);
- StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(processor->GetIncompatibleClientCreds());
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
+}
+
+TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorFailure) {
+ MAYBE_SKIP_TEST;
+ auto* processor = new TestAuthMetadataProcessor(false);
+ StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(processor->GetIncompatibleClientCreds());
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
EXPECT_EQ(
context.credentials()->DebugString(),
kExpectedNonBlockingAuthMetadataPluginAndProcessorFailureCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginFailure) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_credentials(grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(
- TestMetadataCredentialsPlugin::kGoodMetadataKey,
- "Does not matter, will fail anyway (see 3rd param)", true, false,
- 0))));
- request.set_message("Hello");
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
- EXPECT_EQ(s.error_message(),
+}
+
+TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginFailure) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_credentials(grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(
+ TestMetadataCredentialsPlugin::kGoodMetadataKey,
+ "Does not matter, will fail anyway (see 3rd param)", true, false,
+ 0))));
+ request.set_message("Hello");
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
+ EXPECT_EQ(s.error_message(),
TString("Getting metadata from plugin failed with error: ") +
- kTestCredsPluginErrorMsg);
+ kTestCredsPluginErrorMsg);
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedBlockingAuthMetadataPluginFailureCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, CompositeCallCreds) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- const char kMetadataKey1[] = "call-creds-key1";
- const char kMetadataKey2[] = "call-creds-key2";
- const char kMetadataVal1[] = "call-creds-val1";
- const char kMetadataVal2[] = "call-creds-val2";
-
- context.set_credentials(grpc::CompositeCallCredentials(
- grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(kMetadataKey1, kMetadataVal1,
- true, true, 0))),
- grpc::MetadataCredentialsFromPlugin(
- std::unique_ptr<MetadataCredentialsPlugin>(
- new TestMetadataCredentialsPlugin(kMetadataKey2, kMetadataVal2,
- true, true, 0)))));
- request.set_message("Hello");
- request.mutable_param()->set_echo_metadata(true);
-
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_TRUE(s.ok());
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- kMetadataKey1, kMetadataVal1));
- EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
- kMetadataKey2, kMetadataVal2));
+}
+
+TEST_P(SecureEnd2endTest, CompositeCallCreds) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ const char kMetadataKey1[] = "call-creds-key1";
+ const char kMetadataKey2[] = "call-creds-key2";
+ const char kMetadataVal1[] = "call-creds-val1";
+ const char kMetadataVal2[] = "call-creds-val2";
+
+ context.set_credentials(grpc::CompositeCallCredentials(
+ grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(kMetadataKey1, kMetadataVal1,
+ true, true, 0))),
+ grpc::MetadataCredentialsFromPlugin(
+ std::unique_ptr<MetadataCredentialsPlugin>(
+ new TestMetadataCredentialsPlugin(kMetadataKey2, kMetadataVal2,
+ true, true, 0)))));
+ request.set_message("Hello");
+ request.mutable_param()->set_echo_metadata(true);
+
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_TRUE(s.ok());
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ kMetadataKey1, kMetadataVal1));
+ EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
+ kMetadataKey2, kMetadataVal2));
EXPECT_EQ(context.credentials()->DebugString(),
kExpectedCompositeCallCredsDebugString);
-}
-
-TEST_P(SecureEnd2endTest, ClientAuthContext) {
- MAYBE_SKIP_TEST;
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- request.mutable_param()->set_check_auth_context(GetParam().credentials_type ==
- kTlsCredentialsType);
- request.mutable_param()->set_expected_transport_security_type(
- GetParam().credentials_type);
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-
- std::shared_ptr<const AuthContext> auth_ctx = context.auth_context();
- std::vector<grpc::string_ref> tst =
- auth_ctx->FindPropertyValues("transport_security_type");
- ASSERT_EQ(1u, tst.size());
- EXPECT_EQ(GetParam().credentials_type, ToString(tst[0]));
- if (GetParam().credentials_type == kTlsCredentialsType) {
- EXPECT_EQ("x509_subject_alternative_name",
- auth_ctx->GetPeerIdentityPropertyName());
- EXPECT_EQ(4u, auth_ctx->GetPeerIdentity().size());
- EXPECT_EQ("*.test.google.fr", ToString(auth_ctx->GetPeerIdentity()[0]));
- EXPECT_EQ("waterzooi.test.google.be",
- ToString(auth_ctx->GetPeerIdentity()[1]));
- EXPECT_EQ("*.test.youtube.com", ToString(auth_ctx->GetPeerIdentity()[2]));
- EXPECT_EQ("192.168.1.3", ToString(auth_ctx->GetPeerIdentity()[3]));
- }
-}
-
-class ResourceQuotaEnd2endTest : public End2endTest {
- public:
- ResourceQuotaEnd2endTest()
- : server_resource_quota_("server_resource_quota") {}
-
- virtual void ConfigureServerBuilder(ServerBuilder* builder) override {
- builder->SetResourceQuota(server_resource_quota_);
- }
-
- private:
- ResourceQuota server_resource_quota_;
-};
-
-TEST_P(ResourceQuotaEnd2endTest, SimpleRequest) {
- MAYBE_SKIP_TEST;
- ResetStub();
-
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-}
-
-// TODO(vjpai): refactor arguments into a struct if it makes sense
-std::vector<TestScenario> CreateTestScenarios(bool use_proxy,
- bool test_insecure,
- bool test_secure,
- bool test_inproc,
- bool test_callback_server) {
- std::vector<TestScenario> scenarios;
+}
+
+TEST_P(SecureEnd2endTest, ClientAuthContext) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ request.mutable_param()->set_check_auth_context(GetParam().credentials_type ==
+ kTlsCredentialsType);
+ request.mutable_param()->set_expected_transport_security_type(
+ GetParam().credentials_type);
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+
+ std::shared_ptr<const AuthContext> auth_ctx = context.auth_context();
+ std::vector<grpc::string_ref> tst =
+ auth_ctx->FindPropertyValues("transport_security_type");
+ ASSERT_EQ(1u, tst.size());
+ EXPECT_EQ(GetParam().credentials_type, ToString(tst[0]));
+ if (GetParam().credentials_type == kTlsCredentialsType) {
+ EXPECT_EQ("x509_subject_alternative_name",
+ auth_ctx->GetPeerIdentityPropertyName());
+ EXPECT_EQ(4u, auth_ctx->GetPeerIdentity().size());
+ EXPECT_EQ("*.test.google.fr", ToString(auth_ctx->GetPeerIdentity()[0]));
+ EXPECT_EQ("waterzooi.test.google.be",
+ ToString(auth_ctx->GetPeerIdentity()[1]));
+ EXPECT_EQ("*.test.youtube.com", ToString(auth_ctx->GetPeerIdentity()[2]));
+ EXPECT_EQ("192.168.1.3", ToString(auth_ctx->GetPeerIdentity()[3]));
+ }
+}
+
+class ResourceQuotaEnd2endTest : public End2endTest {
+ public:
+ ResourceQuotaEnd2endTest()
+ : server_resource_quota_("server_resource_quota") {}
+
+ virtual void ConfigureServerBuilder(ServerBuilder* builder) override {
+ builder->SetResourceQuota(server_resource_quota_);
+ }
+
+ private:
+ ResourceQuota server_resource_quota_;
+};
+
+TEST_P(ResourceQuotaEnd2endTest, SimpleRequest) {
+ MAYBE_SKIP_TEST;
+ ResetStub();
+
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+}
+
+// TODO(vjpai): refactor arguments into a struct if it makes sense
+std::vector<TestScenario> CreateTestScenarios(bool use_proxy,
+ bool test_insecure,
+ bool test_secure,
+ bool test_inproc,
+ bool test_callback_server) {
+ std::vector<TestScenario> scenarios;
std::vector<TString> credentials_types;
-
+
GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms,
kClientChannelBackupPollIntervalMs);
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
-
- if (test_secure) {
- credentials_types =
- GetCredentialsProvider()->GetSecureCredentialsTypeList();
- }
- auto insec_ok = [] {
- // Only allow insecure credentials type when it is registered with the
- // provider. User may create providers that do not have insecure.
- return GetCredentialsProvider()->GetChannelCredentials(
- kInsecureCredentialsType, nullptr) != nullptr;
- };
- if (test_insecure && insec_ok()) {
- credentials_types.push_back(kInsecureCredentialsType);
- }
-
- // Test callback with inproc or if the event-engine allows it
- GPR_ASSERT(!credentials_types.empty());
- for (const auto& cred : credentials_types) {
- scenarios.emplace_back(false, false, false, cred, false);
- scenarios.emplace_back(true, false, false, cred, false);
- if (test_callback_server) {
- // Note that these scenarios will be dynamically disabled if the event
- // engine doesn't run in the background
- scenarios.emplace_back(false, false, false, cred, true);
- scenarios.emplace_back(true, false, false, cred, true);
- }
- if (use_proxy) {
- scenarios.emplace_back(false, true, false, cred, false);
- scenarios.emplace_back(true, true, false, cred, false);
- }
- }
- if (test_inproc && insec_ok()) {
- scenarios.emplace_back(false, false, true, kInsecureCredentialsType, false);
- scenarios.emplace_back(true, false, true, kInsecureCredentialsType, false);
- if (test_callback_server) {
- scenarios.emplace_back(false, false, true, kInsecureCredentialsType,
- true);
- scenarios.emplace_back(true, false, true, kInsecureCredentialsType, true);
- }
- }
- return scenarios;
-}
-
-INSTANTIATE_TEST_SUITE_P(
- End2end, End2endTest,
- ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
-
-INSTANTIATE_TEST_SUITE_P(
- End2endServerTryCancel, End2endServerTryCancelTest,
- ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
-
-INSTANTIATE_TEST_SUITE_P(
- ProxyEnd2end, ProxyEnd2endTest,
- ::testing::ValuesIn(CreateTestScenarios(true, true, true, true, true)));
-
-INSTANTIATE_TEST_SUITE_P(
- SecureEnd2end, SecureEnd2endTest,
- ::testing::ValuesIn(CreateTestScenarios(false, false, true, false, true)));
-
-INSTANTIATE_TEST_SUITE_P(
- ResourceQuotaEnd2end, ResourceQuotaEnd2endTest,
- ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- int ret = RUN_ALL_TESTS();
- return ret;
-}
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+
+ if (test_secure) {
+ credentials_types =
+ GetCredentialsProvider()->GetSecureCredentialsTypeList();
+ }
+ auto insec_ok = [] {
+ // Only allow insecure credentials type when it is registered with the
+ // provider. User may create providers that do not have insecure.
+ return GetCredentialsProvider()->GetChannelCredentials(
+ kInsecureCredentialsType, nullptr) != nullptr;
+ };
+ if (test_insecure && insec_ok()) {
+ credentials_types.push_back(kInsecureCredentialsType);
+ }
+
+ // Test callback with inproc or if the event-engine allows it
+ GPR_ASSERT(!credentials_types.empty());
+ for (const auto& cred : credentials_types) {
+ scenarios.emplace_back(false, false, false, cred, false);
+ scenarios.emplace_back(true, false, false, cred, false);
+ if (test_callback_server) {
+ // Note that these scenarios will be dynamically disabled if the event
+ // engine doesn't run in the background
+ scenarios.emplace_back(false, false, false, cred, true);
+ scenarios.emplace_back(true, false, false, cred, true);
+ }
+ if (use_proxy) {
+ scenarios.emplace_back(false, true, false, cred, false);
+ scenarios.emplace_back(true, true, false, cred, false);
+ }
+ }
+ if (test_inproc && insec_ok()) {
+ scenarios.emplace_back(false, false, true, kInsecureCredentialsType, false);
+ scenarios.emplace_back(true, false, true, kInsecureCredentialsType, false);
+ if (test_callback_server) {
+ scenarios.emplace_back(false, false, true, kInsecureCredentialsType,
+ true);
+ scenarios.emplace_back(true, false, true, kInsecureCredentialsType, true);
+ }
+ }
+ return scenarios;
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ End2end, End2endTest,
+ ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
+
+INSTANTIATE_TEST_SUITE_P(
+ End2endServerTryCancel, End2endServerTryCancelTest,
+ ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
+
+INSTANTIATE_TEST_SUITE_P(
+ ProxyEnd2end, ProxyEnd2endTest,
+ ::testing::ValuesIn(CreateTestScenarios(true, true, true, true, true)));
+
+INSTANTIATE_TEST_SUITE_P(
+ SecureEnd2end, SecureEnd2endTest,
+ ::testing::ValuesIn(CreateTestScenarios(false, false, true, false, true)));
+
+INSTANTIATE_TEST_SUITE_P(
+ ResourceQuotaEnd2end, ResourceQuotaEnd2endTest,
+ ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)));
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ int ret = RUN_ALL_TESTS();
+ return ret;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/exception_test.cc b/contrib/libs/grpc/test/cpp/end2end/exception_test.cc
index cd29eb8a10..da342f1dfd 100644
--- a/contrib/libs/grpc/test/cpp/end2end/exception_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/exception_test.cc
@@ -1,123 +1,123 @@
-/*
- *
- * Copyright 2017 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.
- *
- */
-
-#include <exception>
-#include <memory>
-
-#include <grpc/impl/codegen/port_platform.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/test_config.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-
-const char* kErrorMessage = "This service caused an exception";
-
-#if GRPC_ALLOW_EXCEPTIONS
-class ExceptingServiceImpl : public ::grpc::testing::EchoTestService::Service {
- public:
- Status Echo(ServerContext* /*server_context*/, const EchoRequest* /*request*/,
- EchoResponse* /*response*/) override {
- throw - 1;
- }
- Status RequestStream(ServerContext* /*context*/,
- ServerReader<EchoRequest>* /*reader*/,
- EchoResponse* /*response*/) override {
- throw ServiceException();
- }
-
- private:
- class ServiceException final : public std::exception {
- public:
- ServiceException() {}
-
- private:
- const char* what() const noexcept override { return kErrorMessage; }
- };
-};
-
-class ExceptionTest : public ::testing::Test {
- protected:
- ExceptionTest() {}
-
- void SetUp() override {
- ServerBuilder builder;
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override { server_->Shutdown(); }
-
- void ResetStub() {
- channel_ = server_->InProcessChannel(ChannelArguments());
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- ExceptingServiceImpl service_;
-};
-
-TEST_F(ExceptionTest, Unary) {
- ResetStub();
- EchoRequest request;
- EchoResponse response;
- request.set_message("test");
-
- for (int i = 0; i < 10; i++) {
- ClientContext context;
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNKNOWN);
- }
-}
-
-TEST_F(ExceptionTest, RequestStream) {
- ResetStub();
- EchoResponse response;
-
- for (int i = 0; i < 10; i++) {
- ClientContext context;
- auto stream = stub_->RequestStream(&context, &response);
- stream->WritesDone();
- Status s = stream->Finish();
-
- EXPECT_FALSE(s.ok());
- EXPECT_EQ(s.error_code(), StatusCode::UNKNOWN);
- }
-}
-
-#endif // GRPC_ALLOW_EXCEPTIONS
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+/*
+ *
+ * Copyright 2017 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.
+ *
+ */
+
+#include <exception>
+#include <memory>
+
+#include <grpc/impl/codegen/port_platform.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/test_config.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+
+const char* kErrorMessage = "This service caused an exception";
+
+#if GRPC_ALLOW_EXCEPTIONS
+class ExceptingServiceImpl : public ::grpc::testing::EchoTestService::Service {
+ public:
+ Status Echo(ServerContext* /*server_context*/, const EchoRequest* /*request*/,
+ EchoResponse* /*response*/) override {
+ throw - 1;
+ }
+ Status RequestStream(ServerContext* /*context*/,
+ ServerReader<EchoRequest>* /*reader*/,
+ EchoResponse* /*response*/) override {
+ throw ServiceException();
+ }
+
+ private:
+ class ServiceException final : public std::exception {
+ public:
+ ServiceException() {}
+
+ private:
+ const char* what() const noexcept override { return kErrorMessage; }
+ };
+};
+
+class ExceptionTest : public ::testing::Test {
+ protected:
+ ExceptionTest() {}
+
+ void SetUp() override {
+ ServerBuilder builder;
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ }
+
+ void TearDown() override { server_->Shutdown(); }
+
+ void ResetStub() {
+ channel_ = server_->InProcessChannel(ChannelArguments());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ ExceptingServiceImpl service_;
+};
+
+TEST_F(ExceptionTest, Unary) {
+ ResetStub();
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("test");
+
+ for (int i = 0; i < 10; i++) {
+ ClientContext context;
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNKNOWN);
+ }
+}
+
+TEST_F(ExceptionTest, RequestStream) {
+ ResetStub();
+ EchoResponse response;
+
+ for (int i = 0; i < 10; i++) {
+ ClientContext context;
+ auto stream = stub_->RequestStream(&context, &response);
+ stream->WritesDone();
+ Status s = stream->Finish();
+
+ EXPECT_FALSE(s.ok());
+ EXPECT_EQ(s.error_code(), StatusCode::UNKNOWN);
+ }
+}
+
+#endif // GRPC_ALLOW_EXCEPTIONS
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/filter_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/filter_end2end_test.cc
index 2f26d0716c..d4724f4ce7 100644
--- a/contrib/libs/grpc/test/cpp/end2end/filter_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/filter_end2end_test.cc
@@ -1,346 +1,346 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <memory>
-#include <mutex>
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <memory>
+#include <mutex>
#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/async_generic_service.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/config.h>
-#include <grpcpp/support/slice.h>
-
-#include "src/cpp/common/channel_filter.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
-
-void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- EXPECT_EQ(expect_ok, ok);
- EXPECT_EQ(tag(i), got_tag);
-}
-
-namespace {
-
-int global_num_connections = 0;
-int global_num_calls = 0;
-std::mutex global_mu;
-
-void IncrementConnectionCounter() {
- std::unique_lock<std::mutex> lock(global_mu);
- ++global_num_connections;
-}
-
-void ResetConnectionCounter() {
- std::unique_lock<std::mutex> lock(global_mu);
- global_num_connections = 0;
-}
-
-int GetConnectionCounterValue() {
- std::unique_lock<std::mutex> lock(global_mu);
- return global_num_connections;
-}
-
-void IncrementCallCounter() {
- std::unique_lock<std::mutex> lock(global_mu);
- ++global_num_calls;
-}
-
-void ResetCallCounter() {
- std::unique_lock<std::mutex> lock(global_mu);
- global_num_calls = 0;
-}
-
-int GetCallCounterValue() {
- std::unique_lock<std::mutex> lock(global_mu);
- return global_num_calls;
-}
-
-} // namespace
-
-class ChannelDataImpl : public ChannelData {
- public:
- grpc_error* Init(grpc_channel_element* /*elem*/,
- grpc_channel_element_args* /*args*/) {
- IncrementConnectionCounter();
- return GRPC_ERROR_NONE;
- }
-};
-
-class CallDataImpl : public CallData {
- public:
- void StartTransportStreamOpBatch(grpc_call_element* elem,
- TransportStreamOpBatch* op) override {
- // Incrementing the counter could be done from Init(), but we want
- // to test that the individual methods are actually called correctly.
- if (op->recv_initial_metadata() != nullptr) IncrementCallCounter();
- grpc_call_next_op(elem, op->op());
- }
-};
-
-class FilterEnd2endTest : public ::testing::Test {
- protected:
- FilterEnd2endTest() : server_host_("localhost") {}
-
- static void SetUpTestCase() {
- // Workaround for
- // https://github.com/google/google-toolbox-for-mac/issues/242
- static bool setup_done = false;
- if (!setup_done) {
- setup_done = true;
- grpc::RegisterChannelFilter<ChannelDataImpl, CallDataImpl>(
- "test-filter", GRPC_SERVER_CHANNEL, INT_MAX, nullptr);
- }
- }
-
- void SetUp() override {
- int port = grpc_pick_unused_port_or_die();
- server_address_ << server_host_ << ":" << port;
- // Setup server
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- InsecureServerCredentials());
- builder.RegisterAsyncGenericService(&generic_service_);
- srv_cq_ = builder.AddCompletionQueue();
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override {
- server_->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- cli_cq_.Shutdown();
- srv_cq_->Shutdown();
- while (cli_cq_.Next(&ignored_tag, &ignored_ok))
- ;
- while (srv_cq_->Next(&ignored_tag, &ignored_ok))
- ;
- }
-
- void ResetStub() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- generic_stub_.reset(new GenericStub(channel));
- ResetConnectionCounter();
- ResetCallCounter();
- }
-
- void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
- void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
- void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
- void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
-
- void SendRpc(int num_rpcs) {
+
+#include <grpc/grpc.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/generic/async_generic_service.h>
+#include <grpcpp/generic/generic_stub.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/config.h>
+#include <grpcpp/support/slice.h>
+
+#include "src/cpp/common/channel_filter.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
+namespace grpc {
+namespace testing {
+namespace {
+
+void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
+
+void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
+ bool ok;
+ void* got_tag;
+ EXPECT_TRUE(cq->Next(&got_tag, &ok));
+ EXPECT_EQ(expect_ok, ok);
+ EXPECT_EQ(tag(i), got_tag);
+}
+
+namespace {
+
+int global_num_connections = 0;
+int global_num_calls = 0;
+std::mutex global_mu;
+
+void IncrementConnectionCounter() {
+ std::unique_lock<std::mutex> lock(global_mu);
+ ++global_num_connections;
+}
+
+void ResetConnectionCounter() {
+ std::unique_lock<std::mutex> lock(global_mu);
+ global_num_connections = 0;
+}
+
+int GetConnectionCounterValue() {
+ std::unique_lock<std::mutex> lock(global_mu);
+ return global_num_connections;
+}
+
+void IncrementCallCounter() {
+ std::unique_lock<std::mutex> lock(global_mu);
+ ++global_num_calls;
+}
+
+void ResetCallCounter() {
+ std::unique_lock<std::mutex> lock(global_mu);
+ global_num_calls = 0;
+}
+
+int GetCallCounterValue() {
+ std::unique_lock<std::mutex> lock(global_mu);
+ return global_num_calls;
+}
+
+} // namespace
+
+class ChannelDataImpl : public ChannelData {
+ public:
+ grpc_error* Init(grpc_channel_element* /*elem*/,
+ grpc_channel_element_args* /*args*/) {
+ IncrementConnectionCounter();
+ return GRPC_ERROR_NONE;
+ }
+};
+
+class CallDataImpl : public CallData {
+ public:
+ void StartTransportStreamOpBatch(grpc_call_element* elem,
+ TransportStreamOpBatch* op) override {
+ // Incrementing the counter could be done from Init(), but we want
+ // to test that the individual methods are actually called correctly.
+ if (op->recv_initial_metadata() != nullptr) IncrementCallCounter();
+ grpc_call_next_op(elem, op->op());
+ }
+};
+
+class FilterEnd2endTest : public ::testing::Test {
+ protected:
+ FilterEnd2endTest() : server_host_("localhost") {}
+
+ static void SetUpTestCase() {
+ // Workaround for
+ // https://github.com/google/google-toolbox-for-mac/issues/242
+ static bool setup_done = false;
+ if (!setup_done) {
+ setup_done = true;
+ grpc::RegisterChannelFilter<ChannelDataImpl, CallDataImpl>(
+ "test-filter", GRPC_SERVER_CHANNEL, INT_MAX, nullptr);
+ }
+ }
+
+ void SetUp() override {
+ int port = grpc_pick_unused_port_or_die();
+ server_address_ << server_host_ << ":" << port;
+ // Setup server
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ InsecureServerCredentials());
+ builder.RegisterAsyncGenericService(&generic_service_);
+ srv_cq_ = builder.AddCompletionQueue();
+ server_ = builder.BuildAndStart();
+ }
+
+ void TearDown() override {
+ server_->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ cli_cq_.Shutdown();
+ srv_cq_->Shutdown();
+ while (cli_cq_.Next(&ignored_tag, &ignored_ok))
+ ;
+ while (srv_cq_->Next(&ignored_tag, &ignored_ok))
+ ;
+ }
+
+ void ResetStub() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ generic_stub_.reset(new GenericStub(channel));
+ ResetConnectionCounter();
+ ResetCallCounter();
+ }
+
+ void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
+ void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
+ void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
+ void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
+
+ void SendRpc(int num_rpcs) {
const TString kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
-
- // The string needs to be long enough to test heap-based slice.
- send_request.set_message("Hello world. Hello world. Hello world.");
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter stream(&srv_ctx);
+
+ // The string needs to be long enough to test heap-based slice.
+ send_request.set_message("Hello world. Hello world. Hello world.");
std::thread request_call([this]() { server_ok(4); });
- std::unique_ptr<GenericClientAsyncReaderWriter> call =
- generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
- call->StartCall(tag(1));
- client_ok(1);
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- call->Write(*send_buffer, tag(2));
- // Send ByteBuffer can be destroyed after calling Write.
- send_buffer.reset();
- client_ok(2);
- call->WritesDone(tag(3));
- client_ok(3);
-
- generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
- srv_cq_.get(), tag(4));
-
+ std::unique_ptr<GenericClientAsyncReaderWriter> call =
+ generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
+ call->StartCall(tag(1));
+ client_ok(1);
+ std::unique_ptr<ByteBuffer> send_buffer =
+ SerializeToByteBuffer(&send_request);
+ call->Write(*send_buffer, tag(2));
+ // Send ByteBuffer can be destroyed after calling Write.
+ send_buffer.reset();
+ client_ok(2);
+ call->WritesDone(tag(3));
+ client_ok(3);
+
+ generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
+ srv_cq_.get(), tag(4));
+
request_call.join();
- EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
- EXPECT_EQ(kMethodName, srv_ctx.method());
- ByteBuffer recv_buffer;
- stream.Read(&recv_buffer, tag(5));
- server_ok(5);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- stream.Write(*send_buffer, tag(6));
- send_buffer.reset();
- server_ok(6);
-
- stream.Finish(Status::OK, tag(7));
- server_ok(7);
-
- recv_buffer.Clear();
- call->Read(&recv_buffer, tag(8));
- client_ok(8);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
-
- call->Finish(&recv_status, tag(9));
- client_ok(9);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
- }
-
- CompletionQueue cli_cq_;
- std::unique_ptr<ServerCompletionQueue> srv_cq_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<grpc::GenericStub> generic_stub_;
- std::unique_ptr<Server> server_;
- AsyncGenericService generic_service_;
+ EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
+ EXPECT_EQ(kMethodName, srv_ctx.method());
+ ByteBuffer recv_buffer;
+ stream.Read(&recv_buffer, tag(5));
+ server_ok(5);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ send_buffer = SerializeToByteBuffer(&send_response);
+ stream.Write(*send_buffer, tag(6));
+ send_buffer.reset();
+ server_ok(6);
+
+ stream.Finish(Status::OK, tag(7));
+ server_ok(7);
+
+ recv_buffer.Clear();
+ call->Read(&recv_buffer, tag(8));
+ client_ok(8);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
+
+ call->Finish(&recv_status, tag(9));
+ client_ok(9);
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+ }
+
+ CompletionQueue cli_cq_;
+ std::unique_ptr<ServerCompletionQueue> srv_cq_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<grpc::GenericStub> generic_stub_;
+ std::unique_ptr<Server> server_;
+ AsyncGenericService generic_service_;
const TString server_host_;
- std::ostringstream server_address_;
-};
-
-TEST_F(FilterEnd2endTest, SimpleRpc) {
- ResetStub();
- EXPECT_EQ(0, GetConnectionCounterValue());
- EXPECT_EQ(0, GetCallCounterValue());
- SendRpc(1);
- EXPECT_EQ(1, GetConnectionCounterValue());
- EXPECT_EQ(1, GetCallCounterValue());
-}
-
-TEST_F(FilterEnd2endTest, SequentialRpcs) {
- ResetStub();
- EXPECT_EQ(0, GetConnectionCounterValue());
- EXPECT_EQ(0, GetCallCounterValue());
- SendRpc(10);
- EXPECT_EQ(1, GetConnectionCounterValue());
- EXPECT_EQ(10, GetCallCounterValue());
-}
-
-// One ping, one pong.
-TEST_F(FilterEnd2endTest, SimpleBidiStreaming) {
- ResetStub();
- EXPECT_EQ(0, GetConnectionCounterValue());
- EXPECT_EQ(0, GetCallCounterValue());
-
+ std::ostringstream server_address_;
+};
+
+TEST_F(FilterEnd2endTest, SimpleRpc) {
+ ResetStub();
+ EXPECT_EQ(0, GetConnectionCounterValue());
+ EXPECT_EQ(0, GetCallCounterValue());
+ SendRpc(1);
+ EXPECT_EQ(1, GetConnectionCounterValue());
+ EXPECT_EQ(1, GetCallCounterValue());
+}
+
+TEST_F(FilterEnd2endTest, SequentialRpcs) {
+ ResetStub();
+ EXPECT_EQ(0, GetConnectionCounterValue());
+ EXPECT_EQ(0, GetCallCounterValue());
+ SendRpc(10);
+ EXPECT_EQ(1, GetConnectionCounterValue());
+ EXPECT_EQ(10, GetCallCounterValue());
+}
+
+// One ping, one pong.
+TEST_F(FilterEnd2endTest, SimpleBidiStreaming) {
+ ResetStub();
+ EXPECT_EQ(0, GetConnectionCounterValue());
+ EXPECT_EQ(0, GetCallCounterValue());
+
const TString kMethodName(
- "/grpc.cpp.test.util.EchoTestService/BidiStream");
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
-
- cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
- send_request.set_message("Hello");
+ "/grpc.cpp.test.util.EchoTestService/BidiStream");
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
+
+ cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
+ send_request.set_message("Hello");
std::thread request_call([this]() { server_ok(2); });
- std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
- generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
- cli_stream->StartCall(tag(1));
- client_ok(1);
-
- generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
- srv_cq_.get(), tag(2));
-
+ std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
+ generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
+ cli_stream->StartCall(tag(1));
+ client_ok(1);
+
+ generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
+ srv_cq_.get(), tag(2));
+
request_call.join();
- EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
- EXPECT_EQ(kMethodName, srv_ctx.method());
-
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- cli_stream->Write(*send_buffer, tag(3));
- send_buffer.reset();
- client_ok(3);
-
- ByteBuffer recv_buffer;
- srv_stream.Read(&recv_buffer, tag(4));
- server_ok(4);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- srv_stream.Write(*send_buffer, tag(5));
- send_buffer.reset();
- server_ok(5);
-
- cli_stream->Read(&recv_buffer, tag(6));
- client_ok(6);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->WritesDone(tag(7));
- client_ok(7);
-
- srv_stream.Read(&recv_buffer, tag(8));
- server_fail(8);
-
- srv_stream.Finish(Status::OK, tag(9));
- server_ok(9);
-
- cli_stream->Finish(&recv_status, tag(10));
- client_ok(10);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-
- EXPECT_EQ(1, GetCallCounterValue());
- EXPECT_EQ(1, GetConnectionCounterValue());
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
+ EXPECT_EQ(kMethodName, srv_ctx.method());
+
+ std::unique_ptr<ByteBuffer> send_buffer =
+ SerializeToByteBuffer(&send_request);
+ cli_stream->Write(*send_buffer, tag(3));
+ send_buffer.reset();
+ client_ok(3);
+
+ ByteBuffer recv_buffer;
+ srv_stream.Read(&recv_buffer, tag(4));
+ server_ok(4);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ send_buffer = SerializeToByteBuffer(&send_response);
+ srv_stream.Write(*send_buffer, tag(5));
+ send_buffer.reset();
+ server_ok(5);
+
+ cli_stream->Read(&recv_buffer, tag(6));
+ client_ok(6);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->WritesDone(tag(7));
+ client_ok(7);
+
+ srv_stream.Read(&recv_buffer, tag(8));
+ server_fail(8);
+
+ srv_stream.Finish(Status::OK, tag(9));
+ server_ok(9);
+
+ cli_stream->Finish(&recv_status, tag(10));
+ client_ok(10);
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+
+ EXPECT_EQ(1, GetCallCounterValue());
+ EXPECT_EQ(1, GetConnectionCounterValue());
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/generic_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/generic_end2end_test.cc
index 59eec49fb2..cbe9289302 100644
--- a/contrib/libs/grpc/test/cpp/end2end/generic_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/generic_end2end_test.cc
@@ -1,430 +1,430 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <memory>
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/async_generic_service.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/slice.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
-
-void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- EXPECT_EQ(expect_ok, ok);
- EXPECT_EQ(tag(i), got_tag);
-}
-
-class GenericEnd2endTest : public ::testing::Test {
- protected:
- GenericEnd2endTest() : server_host_("localhost") {}
-
- void SetUp() override {
- shut_down_ = false;
- int port = grpc_pick_unused_port_or_die();
- server_address_ << server_host_ << ":" << port;
- // Setup server
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- InsecureServerCredentials());
- builder.RegisterAsyncGenericService(&generic_service_);
- // Include a second call to RegisterAsyncGenericService to make sure that
- // we get an error in the log, since it is not allowed to have 2 async
- // generic services
- builder.RegisterAsyncGenericService(&generic_service_);
- srv_cq_ = builder.AddCompletionQueue();
- server_ = builder.BuildAndStart();
- }
-
- void ShutDownServerAndCQs() {
- if (!shut_down_) {
- server_->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- cli_cq_.Shutdown();
- srv_cq_->Shutdown();
- while (cli_cq_.Next(&ignored_tag, &ignored_ok))
- ;
- while (srv_cq_->Next(&ignored_tag, &ignored_ok))
- ;
- shut_down_ = true;
- }
- }
- void TearDown() override { ShutDownServerAndCQs(); }
-
- void ResetStub() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- generic_stub_.reset(new GenericStub(channel));
- }
-
- void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
- void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
- void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
- void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
-
- void SendRpc(int num_rpcs) {
- SendRpc(num_rpcs, false, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
-
- void SendRpc(int num_rpcs, bool check_deadline, gpr_timespec deadline) {
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <memory>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/generic/async_generic_service.h>
+#include <grpcpp/generic/generic_stub.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/slice.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
+namespace grpc {
+namespace testing {
+namespace {
+
+void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
+
+void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
+ bool ok;
+ void* got_tag;
+ EXPECT_TRUE(cq->Next(&got_tag, &ok));
+ EXPECT_EQ(expect_ok, ok);
+ EXPECT_EQ(tag(i), got_tag);
+}
+
+class GenericEnd2endTest : public ::testing::Test {
+ protected:
+ GenericEnd2endTest() : server_host_("localhost") {}
+
+ void SetUp() override {
+ shut_down_ = false;
+ int port = grpc_pick_unused_port_or_die();
+ server_address_ << server_host_ << ":" << port;
+ // Setup server
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ InsecureServerCredentials());
+ builder.RegisterAsyncGenericService(&generic_service_);
+ // Include a second call to RegisterAsyncGenericService to make sure that
+ // we get an error in the log, since it is not allowed to have 2 async
+ // generic services
+ builder.RegisterAsyncGenericService(&generic_service_);
+ srv_cq_ = builder.AddCompletionQueue();
+ server_ = builder.BuildAndStart();
+ }
+
+ void ShutDownServerAndCQs() {
+ if (!shut_down_) {
+ server_->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ cli_cq_.Shutdown();
+ srv_cq_->Shutdown();
+ while (cli_cq_.Next(&ignored_tag, &ignored_ok))
+ ;
+ while (srv_cq_->Next(&ignored_tag, &ignored_ok))
+ ;
+ shut_down_ = true;
+ }
+ }
+ void TearDown() override { ShutDownServerAndCQs(); }
+
+ void ResetStub() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ generic_stub_.reset(new GenericStub(channel));
+ }
+
+ void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
+ void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
+ void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
+ void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
+
+ void SendRpc(int num_rpcs) {
+ SendRpc(num_rpcs, false, gpr_inf_future(GPR_CLOCK_MONOTONIC));
+ }
+
+ void SendRpc(int num_rpcs, bool check_deadline, gpr_timespec deadline) {
const TString kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
-
- // The string needs to be long enough to test heap-based slice.
- send_request.set_message("Hello world. Hello world. Hello world.");
-
- if (check_deadline) {
- cli_ctx.set_deadline(deadline);
- }
-
- // Rather than using the original kMethodName, make a short-lived
- // copy to also confirm that we don't refer to this object beyond
- // the initial call preparation
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter stream(&srv_ctx);
+
+ // The string needs to be long enough to test heap-based slice.
+ send_request.set_message("Hello world. Hello world. Hello world.");
+
+ if (check_deadline) {
+ cli_ctx.set_deadline(deadline);
+ }
+
+ // Rather than using the original kMethodName, make a short-lived
+ // copy to also confirm that we don't refer to this object beyond
+ // the initial call preparation
const TString* method_name = new TString(kMethodName);
-
- std::unique_ptr<GenericClientAsyncReaderWriter> call =
- generic_stub_->PrepareCall(&cli_ctx, *method_name, &cli_cq_);
-
- delete method_name; // Make sure that this is not needed after invocation
-
+
+ std::unique_ptr<GenericClientAsyncReaderWriter> call =
+ generic_stub_->PrepareCall(&cli_ctx, *method_name, &cli_cq_);
+
+ delete method_name; // Make sure that this is not needed after invocation
+
std::thread request_call([this]() { server_ok(4); });
- call->StartCall(tag(1));
- client_ok(1);
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- call->Write(*send_buffer, tag(2));
- // Send ByteBuffer can be destroyed after calling Write.
- send_buffer.reset();
- client_ok(2);
- call->WritesDone(tag(3));
- client_ok(3);
-
- generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
- srv_cq_.get(), tag(4));
-
+ call->StartCall(tag(1));
+ client_ok(1);
+ std::unique_ptr<ByteBuffer> send_buffer =
+ SerializeToByteBuffer(&send_request);
+ call->Write(*send_buffer, tag(2));
+ // Send ByteBuffer can be destroyed after calling Write.
+ send_buffer.reset();
+ client_ok(2);
+ call->WritesDone(tag(3));
+ client_ok(3);
+
+ generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
+ srv_cq_.get(), tag(4));
+
request_call.join();
- EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
- EXPECT_EQ(kMethodName, srv_ctx.method());
-
- if (check_deadline) {
- EXPECT_TRUE(gpr_time_similar(deadline, srv_ctx.raw_deadline(),
- gpr_time_from_millis(1000, GPR_TIMESPAN)));
- }
-
- ByteBuffer recv_buffer;
- stream.Read(&recv_buffer, tag(5));
- server_ok(5);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- stream.Write(*send_buffer, tag(6));
- send_buffer.reset();
- server_ok(6);
-
- stream.Finish(Status::OK, tag(7));
- server_ok(7);
-
- recv_buffer.Clear();
- call->Read(&recv_buffer, tag(8));
- client_ok(8);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
-
- call->Finish(&recv_status, tag(9));
- client_ok(9);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
- }
-
- // Return errors to up to one call that comes in on the supplied completion
- // queue, until the CQ is being shut down (and therefore we can no longer
- // enqueue further events).
- void DriveCompletionQueue() {
- enum class Event : uintptr_t {
- kCallReceived,
- kResponseSent,
- };
- // Request the call, but only if the main thread hasn't beaten us to
- // shutting down the CQ.
- grpc::GenericServerContext server_context;
- grpc::GenericServerAsyncReaderWriter reader_writer(&server_context);
-
- {
- std::lock_guard<std::mutex> lock(shutting_down_mu_);
- if (!shutting_down_) {
- generic_service_.RequestCall(
- &server_context, &reader_writer, srv_cq_.get(), srv_cq_.get(),
- reinterpret_cast<void*>(Event::kCallReceived));
- }
- }
- // Process events.
- {
- Event event;
- bool ok;
- while (srv_cq_->Next(reinterpret_cast<void**>(&event), &ok)) {
- std::lock_guard<std::mutex> lock(shutting_down_mu_);
- if (shutting_down_) {
- // The main thread has started shutting down. Simply continue to drain
- // events.
- continue;
- }
-
- switch (event) {
- case Event::kCallReceived:
- reader_writer.Finish(
- ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "go away"),
- reinterpret_cast<void*>(Event::kResponseSent));
- break;
-
- case Event::kResponseSent:
- // We are done.
- break;
- }
- }
- }
- }
-
- CompletionQueue cli_cq_;
- std::unique_ptr<ServerCompletionQueue> srv_cq_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<grpc::GenericStub> generic_stub_;
- std::unique_ptr<Server> server_;
- AsyncGenericService generic_service_;
+ EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
+ EXPECT_EQ(kMethodName, srv_ctx.method());
+
+ if (check_deadline) {
+ EXPECT_TRUE(gpr_time_similar(deadline, srv_ctx.raw_deadline(),
+ gpr_time_from_millis(1000, GPR_TIMESPAN)));
+ }
+
+ ByteBuffer recv_buffer;
+ stream.Read(&recv_buffer, tag(5));
+ server_ok(5);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ send_buffer = SerializeToByteBuffer(&send_response);
+ stream.Write(*send_buffer, tag(6));
+ send_buffer.reset();
+ server_ok(6);
+
+ stream.Finish(Status::OK, tag(7));
+ server_ok(7);
+
+ recv_buffer.Clear();
+ call->Read(&recv_buffer, tag(8));
+ client_ok(8);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
+
+ call->Finish(&recv_status, tag(9));
+ client_ok(9);
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+ }
+
+ // Return errors to up to one call that comes in on the supplied completion
+ // queue, until the CQ is being shut down (and therefore we can no longer
+ // enqueue further events).
+ void DriveCompletionQueue() {
+ enum class Event : uintptr_t {
+ kCallReceived,
+ kResponseSent,
+ };
+ // Request the call, but only if the main thread hasn't beaten us to
+ // shutting down the CQ.
+ grpc::GenericServerContext server_context;
+ grpc::GenericServerAsyncReaderWriter reader_writer(&server_context);
+
+ {
+ std::lock_guard<std::mutex> lock(shutting_down_mu_);
+ if (!shutting_down_) {
+ generic_service_.RequestCall(
+ &server_context, &reader_writer, srv_cq_.get(), srv_cq_.get(),
+ reinterpret_cast<void*>(Event::kCallReceived));
+ }
+ }
+ // Process events.
+ {
+ Event event;
+ bool ok;
+ while (srv_cq_->Next(reinterpret_cast<void**>(&event), &ok)) {
+ std::lock_guard<std::mutex> lock(shutting_down_mu_);
+ if (shutting_down_) {
+ // The main thread has started shutting down. Simply continue to drain
+ // events.
+ continue;
+ }
+
+ switch (event) {
+ case Event::kCallReceived:
+ reader_writer.Finish(
+ ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "go away"),
+ reinterpret_cast<void*>(Event::kResponseSent));
+ break;
+
+ case Event::kResponseSent:
+ // We are done.
+ break;
+ }
+ }
+ }
+ }
+
+ CompletionQueue cli_cq_;
+ std::unique_ptr<ServerCompletionQueue> srv_cq_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<grpc::GenericStub> generic_stub_;
+ std::unique_ptr<Server> server_;
+ AsyncGenericService generic_service_;
const TString server_host_;
- std::ostringstream server_address_;
- bool shutting_down_;
- bool shut_down_;
- std::mutex shutting_down_mu_;
-};
-
-TEST_F(GenericEnd2endTest, SimpleRpc) {
- ResetStub();
- SendRpc(1);
-}
-
-TEST_F(GenericEnd2endTest, SequentialRpcs) {
- ResetStub();
- SendRpc(10);
-}
-
-TEST_F(GenericEnd2endTest, SequentialUnaryRpcs) {
- ResetStub();
- const int num_rpcs = 10;
+ std::ostringstream server_address_;
+ bool shutting_down_;
+ bool shut_down_;
+ std::mutex shutting_down_mu_;
+};
+
+TEST_F(GenericEnd2endTest, SimpleRpc) {
+ ResetStub();
+ SendRpc(1);
+}
+
+TEST_F(GenericEnd2endTest, SequentialRpcs) {
+ ResetStub();
+ SendRpc(10);
+}
+
+TEST_F(GenericEnd2endTest, SequentialUnaryRpcs) {
+ ResetStub();
+ const int num_rpcs = 10;
const TString kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
-
- // The string needs to be long enough to test heap-based slice.
- send_request.set_message("Hello world. Hello world. Hello world.");
-
- std::unique_ptr<ByteBuffer> cli_send_buffer =
- SerializeToByteBuffer(&send_request);
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter stream(&srv_ctx);
+
+ // The string needs to be long enough to test heap-based slice.
+ send_request.set_message("Hello world. Hello world. Hello world.");
+
+ std::unique_ptr<ByteBuffer> cli_send_buffer =
+ SerializeToByteBuffer(&send_request);
std::thread request_call([this]() { server_ok(4); });
- std::unique_ptr<GenericClientAsyncResponseReader> call =
- generic_stub_->PrepareUnaryCall(&cli_ctx, kMethodName,
- *cli_send_buffer.get(), &cli_cq_);
- call->StartCall();
- ByteBuffer cli_recv_buffer;
- call->Finish(&cli_recv_buffer, &recv_status, tag(1));
- std::thread client_check([this] { client_ok(1); });
-
- generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
- srv_cq_.get(), tag(4));
+ std::unique_ptr<GenericClientAsyncResponseReader> call =
+ generic_stub_->PrepareUnaryCall(&cli_ctx, kMethodName,
+ *cli_send_buffer.get(), &cli_cq_);
+ call->StartCall();
+ ByteBuffer cli_recv_buffer;
+ call->Finish(&cli_recv_buffer, &recv_status, tag(1));
+ std::thread client_check([this] { client_ok(1); });
+
+ generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
+ srv_cq_.get(), tag(4));
request_call.join();
- EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
- EXPECT_EQ(kMethodName, srv_ctx.method());
-
- ByteBuffer srv_recv_buffer;
- stream.Read(&srv_recv_buffer, tag(5));
- server_ok(5);
- EXPECT_TRUE(ParseFromByteBuffer(&srv_recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- std::unique_ptr<ByteBuffer> srv_send_buffer =
- SerializeToByteBuffer(&send_response);
- stream.Write(*srv_send_buffer, tag(6));
- server_ok(6);
-
- stream.Finish(Status::OK, tag(7));
- server_ok(7);
-
- client_check.join();
- EXPECT_TRUE(ParseFromByteBuffer(&cli_recv_buffer, &recv_response));
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
-}
-
-// One ping, one pong.
-TEST_F(GenericEnd2endTest, SimpleBidiStreaming) {
- ResetStub();
-
+ EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
+ EXPECT_EQ(kMethodName, srv_ctx.method());
+
+ ByteBuffer srv_recv_buffer;
+ stream.Read(&srv_recv_buffer, tag(5));
+ server_ok(5);
+ EXPECT_TRUE(ParseFromByteBuffer(&srv_recv_buffer, &recv_request));
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ std::unique_ptr<ByteBuffer> srv_send_buffer =
+ SerializeToByteBuffer(&send_response);
+ stream.Write(*srv_send_buffer, tag(6));
+ server_ok(6);
+
+ stream.Finish(Status::OK, tag(7));
+ server_ok(7);
+
+ client_check.join();
+ EXPECT_TRUE(ParseFromByteBuffer(&cli_recv_buffer, &recv_response));
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+}
+
+// One ping, one pong.
+TEST_F(GenericEnd2endTest, SimpleBidiStreaming) {
+ ResetStub();
+
const TString kMethodName(
- "/grpc.cpp.test.util.EchoTestService/BidiStream");
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
-
- cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
- send_request.set_message("Hello");
+ "/grpc.cpp.test.util.EchoTestService/BidiStream");
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+ ClientContext cli_ctx;
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
+
+ cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
+ send_request.set_message("Hello");
std::thread request_call([this]() { server_ok(2); });
- std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
- generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
- cli_stream->StartCall(tag(1));
- client_ok(1);
-
- generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
- srv_cq_.get(), tag(2));
+ std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
+ generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
+ cli_stream->StartCall(tag(1));
+ client_ok(1);
+
+ generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
+ srv_cq_.get(), tag(2));
request_call.join();
-
- EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
- EXPECT_EQ(kMethodName, srv_ctx.method());
-
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- cli_stream->Write(*send_buffer, tag(3));
- send_buffer.reset();
- client_ok(3);
-
- ByteBuffer recv_buffer;
- srv_stream.Read(&recv_buffer, tag(4));
- server_ok(4);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- srv_stream.Write(*send_buffer, tag(5));
- send_buffer.reset();
- server_ok(5);
-
- cli_stream->Read(&recv_buffer, tag(6));
- client_ok(6);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->WritesDone(tag(7));
- client_ok(7);
-
- srv_stream.Read(&recv_buffer, tag(8));
- server_fail(8);
-
- srv_stream.Finish(Status::OK, tag(9));
- server_ok(9);
-
- cli_stream->Finish(&recv_status, tag(10));
- client_ok(10);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-TEST_F(GenericEnd2endTest, Deadline) {
- ResetStub();
- SendRpc(1, true,
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_seconds(10, GPR_TIMESPAN)));
-}
-
-TEST_F(GenericEnd2endTest, ShortDeadline) {
- ResetStub();
-
- ClientContext cli_ctx;
- EchoRequest request;
- EchoResponse response;
-
- shutting_down_ = false;
- std::thread driver([this] { DriveCompletionQueue(); });
-
- request.set_message("");
- cli_ctx.set_deadline(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(500, GPR_TIMESPAN)));
- Status s = stub_->Echo(&cli_ctx, request, &response);
- EXPECT_FALSE(s.ok());
- {
- std::lock_guard<std::mutex> lock(shutting_down_mu_);
- shutting_down_ = true;
- }
- ShutDownServerAndCQs();
- driver.join();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+
+ EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
+ EXPECT_EQ(kMethodName, srv_ctx.method());
+
+ std::unique_ptr<ByteBuffer> send_buffer =
+ SerializeToByteBuffer(&send_request);
+ cli_stream->Write(*send_buffer, tag(3));
+ send_buffer.reset();
+ client_ok(3);
+
+ ByteBuffer recv_buffer;
+ srv_stream.Read(&recv_buffer, tag(4));
+ server_ok(4);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ send_buffer = SerializeToByteBuffer(&send_response);
+ srv_stream.Write(*send_buffer, tag(5));
+ send_buffer.reset();
+ server_ok(5);
+
+ cli_stream->Read(&recv_buffer, tag(6));
+ client_ok(6);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->WritesDone(tag(7));
+ client_ok(7);
+
+ srv_stream.Read(&recv_buffer, tag(8));
+ server_fail(8);
+
+ srv_stream.Finish(Status::OK, tag(9));
+ server_ok(9);
+
+ cli_stream->Finish(&recv_status, tag(10));
+ client_ok(10);
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+}
+
+TEST_F(GenericEnd2endTest, Deadline) {
+ ResetStub();
+ SendRpc(1, true,
+ gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_seconds(10, GPR_TIMESPAN)));
+}
+
+TEST_F(GenericEnd2endTest, ShortDeadline) {
+ ResetStub();
+
+ ClientContext cli_ctx;
+ EchoRequest request;
+ EchoResponse response;
+
+ shutting_down_ = false;
+ std::thread driver([this] { DriveCompletionQueue(); });
+
+ request.set_message("");
+ cli_ctx.set_deadline(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_micros(500, GPR_TIMESPAN)));
+ Status s = stub_->Echo(&cli_ctx, request, &response);
+ EXPECT_FALSE(s.ok());
+ {
+ std::lock_guard<std::mutex> lock(shutting_down_mu_);
+ shutting_down_ = true;
+ }
+ ShutDownServerAndCQs();
+ driver.join();
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/grpclb_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/grpclb_end2end_test.cc
index 6208dc2535..9111899785 100644
--- a/contrib/libs/grpc/test/cpp/end2end/grpclb_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/grpclb_end2end_test.cc
@@ -1,94 +1,94 @@
-/*
- *
- * Copyright 2017 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.
- *
- */
-
+/*
+ *
+ * Copyright 2017 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.
+ *
+ */
+
#include <deque>
-#include <memory>
-#include <mutex>
-#include <set>
-#include <sstream>
+#include <memory>
+#include <mutex>
+#include <set>
+#include <sstream>
#include <util/generic/string.h>
-#include <thread>
-
+#include <thread>
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/impl/codegen/sync.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-
-#include "src/core/ext/filters/client_channel/backup_poller.h"
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/impl/codegen/sync.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+
+#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
-#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
-#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/ext/filters/client_channel/service_config.h"
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
+#include "src/core/ext/filters/client_channel/server_address.h"
+#include "src/core/ext/filters/client_channel/service_config.h"
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/parse_address.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/security/credentials/fake/fake_credentials.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/security/credentials/fake/fake_credentials.h"
#include "src/core/lib/transport/authority_override.h"
-#include "src/cpp/client/secure_credentials.h"
-#include "src/cpp/server/secure_server_credentials.h"
-
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-// TODO(dgq): Other scenarios in need of testing:
-// - Send a serverlist with faulty ip:port addresses (port > 2^16, etc).
-// - Test reception of invalid serverlist
-// - Test against a non-LB server.
-// - Random LB server closing the stream unexpectedly.
-//
-// Findings from end to end testing to be covered here:
-// - Handling of LB servers restart, including reconnection after backing-off
-// retries.
-// - Destruction of load balanced channel (and therefore of grpclb instance)
-// while:
-// 1) the internal LB call is still active. This should work by virtue
-// of the weak reference the LB call holds. The call should be terminated as
-// part of the grpclb shutdown process.
-// 2) the retry timer is active. Again, the weak reference it holds should
-// prevent a premature call to \a glb_destroy.
-
-using std::chrono::system_clock;
-
+#include "src/cpp/client/secure_credentials.h"
+#include "src/cpp/server/secure_server_credentials.h"
+
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_service_impl.h"
+
+#include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+// TODO(dgq): Other scenarios in need of testing:
+// - Send a serverlist with faulty ip:port addresses (port > 2^16, etc).
+// - Test reception of invalid serverlist
+// - Test against a non-LB server.
+// - Random LB server closing the stream unexpectedly.
+//
+// Findings from end to end testing to be covered here:
+// - Handling of LB servers restart, including reconnection after backing-off
+// retries.
+// - Destruction of load balanced channel (and therefore of grpclb instance)
+// while:
+// 1) the internal LB call is still active. This should work by virtue
+// of the weak reference the LB call holds. The call should be terminated as
+// part of the grpclb shutdown process.
+// 2) the retry timer is active. Again, the weak reference it holds should
+// prevent a premature call to \a glb_destroy.
+
+using std::chrono::system_clock;
+
using grpc::lb::v1::LoadBalancer;
-using grpc::lb::v1::LoadBalanceRequest;
-using grpc::lb::v1::LoadBalanceResponse;
-
-namespace grpc {
-namespace testing {
-namespace {
-
+using grpc::lb::v1::LoadBalanceRequest;
+using grpc::lb::v1::LoadBalanceResponse;
+
+namespace grpc {
+namespace testing {
+namespace {
+
constexpr char kDefaultServiceConfig[] =
"{\n"
" \"loadBalancingConfig\":[\n"
@@ -96,255 +96,255 @@ constexpr char kDefaultServiceConfig[] =
" ]\n"
"}";
-template <typename ServiceType>
-class CountedService : public ServiceType {
- public:
- size_t request_count() {
- grpc::internal::MutexLock lock(&mu_);
- return request_count_;
- }
-
- size_t response_count() {
- grpc::internal::MutexLock lock(&mu_);
- return response_count_;
- }
-
- void IncreaseResponseCount() {
- grpc::internal::MutexLock lock(&mu_);
- ++response_count_;
- }
- void IncreaseRequestCount() {
- grpc::internal::MutexLock lock(&mu_);
- ++request_count_;
- }
-
- void ResetCounters() {
- grpc::internal::MutexLock lock(&mu_);
- request_count_ = 0;
- response_count_ = 0;
- }
-
- protected:
- grpc::internal::Mutex mu_;
-
- private:
- size_t request_count_ = 0;
- size_t response_count_ = 0;
-};
-
-using BackendService = CountedService<TestServiceImpl>;
-using BalancerService = CountedService<LoadBalancer::Service>;
-
-const char g_kCallCredsMdKey[] = "Balancer should not ...";
-const char g_kCallCredsMdValue[] = "... receive me";
-
-class BackendServiceImpl : public BackendService {
- public:
- BackendServiceImpl() {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) override {
- // Backend should receive the call credentials metadata.
- auto call_credentials_entry =
- context->client_metadata().find(g_kCallCredsMdKey);
- EXPECT_NE(call_credentials_entry, context->client_metadata().end());
- if (call_credentials_entry != context->client_metadata().end()) {
- EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
- }
- IncreaseRequestCount();
- const auto status = TestServiceImpl::Echo(context, request, response);
- IncreaseResponseCount();
- AddClient(context->peer().c_str());
- return status;
- }
-
- void Start() {}
-
- void Shutdown() {}
-
+template <typename ServiceType>
+class CountedService : public ServiceType {
+ public:
+ size_t request_count() {
+ grpc::internal::MutexLock lock(&mu_);
+ return request_count_;
+ }
+
+ size_t response_count() {
+ grpc::internal::MutexLock lock(&mu_);
+ return response_count_;
+ }
+
+ void IncreaseResponseCount() {
+ grpc::internal::MutexLock lock(&mu_);
+ ++response_count_;
+ }
+ void IncreaseRequestCount() {
+ grpc::internal::MutexLock lock(&mu_);
+ ++request_count_;
+ }
+
+ void ResetCounters() {
+ grpc::internal::MutexLock lock(&mu_);
+ request_count_ = 0;
+ response_count_ = 0;
+ }
+
+ protected:
+ grpc::internal::Mutex mu_;
+
+ private:
+ size_t request_count_ = 0;
+ size_t response_count_ = 0;
+};
+
+using BackendService = CountedService<TestServiceImpl>;
+using BalancerService = CountedService<LoadBalancer::Service>;
+
+const char g_kCallCredsMdKey[] = "Balancer should not ...";
+const char g_kCallCredsMdValue[] = "... receive me";
+
+class BackendServiceImpl : public BackendService {
+ public:
+ BackendServiceImpl() {}
+
+ Status Echo(ServerContext* context, const EchoRequest* request,
+ EchoResponse* response) override {
+ // Backend should receive the call credentials metadata.
+ auto call_credentials_entry =
+ context->client_metadata().find(g_kCallCredsMdKey);
+ EXPECT_NE(call_credentials_entry, context->client_metadata().end());
+ if (call_credentials_entry != context->client_metadata().end()) {
+ EXPECT_EQ(call_credentials_entry->second, g_kCallCredsMdValue);
+ }
+ IncreaseRequestCount();
+ const auto status = TestServiceImpl::Echo(context, request, response);
+ IncreaseResponseCount();
+ AddClient(context->peer().c_str());
+ return status;
+ }
+
+ void Start() {}
+
+ void Shutdown() {}
+
std::set<TString> clients() {
- grpc::internal::MutexLock lock(&clients_mu_);
- return clients_;
- }
-
- private:
+ grpc::internal::MutexLock lock(&clients_mu_);
+ return clients_;
+ }
+
+ private:
void AddClient(const TString& client) {
- grpc::internal::MutexLock lock(&clients_mu_);
- clients_.insert(client);
- }
-
- grpc::internal::Mutex mu_;
- grpc::internal::Mutex clients_mu_;
+ grpc::internal::MutexLock lock(&clients_mu_);
+ clients_.insert(client);
+ }
+
+ grpc::internal::Mutex mu_;
+ grpc::internal::Mutex clients_mu_;
std::set<TString> clients_;
-};
-
+};
+
TString Ip4ToPackedString(const char* ip_str) {
- struct in_addr ip4;
- GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1);
+ struct in_addr ip4;
+ GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1);
return TString(reinterpret_cast<const char*>(&ip4), sizeof(ip4));
-}
-
-struct ClientStats {
- size_t num_calls_started = 0;
- size_t num_calls_finished = 0;
- size_t num_calls_finished_with_client_failed_to_send = 0;
- size_t num_calls_finished_known_received = 0;
+}
+
+struct ClientStats {
+ size_t num_calls_started = 0;
+ size_t num_calls_finished = 0;
+ size_t num_calls_finished_with_client_failed_to_send = 0;
+ size_t num_calls_finished_known_received = 0;
std::map<TString, size_t> drop_token_counts;
-
- ClientStats& operator+=(const ClientStats& other) {
- num_calls_started += other.num_calls_started;
- num_calls_finished += other.num_calls_finished;
- num_calls_finished_with_client_failed_to_send +=
- other.num_calls_finished_with_client_failed_to_send;
- num_calls_finished_known_received +=
- other.num_calls_finished_known_received;
- for (const auto& p : other.drop_token_counts) {
- drop_token_counts[p.first] += p.second;
- }
- return *this;
- }
-
- void Reset() {
- num_calls_started = 0;
- num_calls_finished = 0;
- num_calls_finished_with_client_failed_to_send = 0;
- num_calls_finished_known_received = 0;
- drop_token_counts.clear();
- }
-};
-
-class BalancerServiceImpl : public BalancerService {
- public:
- using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>;
- using ResponseDelayPair = std::pair<LoadBalanceResponse, int>;
-
- explicit BalancerServiceImpl(int client_load_reporting_interval_seconds)
- : client_load_reporting_interval_seconds_(
- client_load_reporting_interval_seconds) {}
-
- Status BalanceLoad(ServerContext* context, Stream* stream) override {
- gpr_log(GPR_INFO, "LB[%p]: BalanceLoad", this);
- {
- grpc::internal::MutexLock lock(&mu_);
- if (serverlist_done_) goto done;
- }
- {
- // Balancer shouldn't receive the call credentials metadata.
- EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
- context->client_metadata().end());
- LoadBalanceRequest request;
- std::vector<ResponseDelayPair> responses_and_delays;
-
- if (!stream->Read(&request)) {
- goto done;
+
+ ClientStats& operator+=(const ClientStats& other) {
+ num_calls_started += other.num_calls_started;
+ num_calls_finished += other.num_calls_finished;
+ num_calls_finished_with_client_failed_to_send +=
+ other.num_calls_finished_with_client_failed_to_send;
+ num_calls_finished_known_received +=
+ other.num_calls_finished_known_received;
+ for (const auto& p : other.drop_token_counts) {
+ drop_token_counts[p.first] += p.second;
+ }
+ return *this;
+ }
+
+ void Reset() {
+ num_calls_started = 0;
+ num_calls_finished = 0;
+ num_calls_finished_with_client_failed_to_send = 0;
+ num_calls_finished_known_received = 0;
+ drop_token_counts.clear();
+ }
+};
+
+class BalancerServiceImpl : public BalancerService {
+ public:
+ using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>;
+ using ResponseDelayPair = std::pair<LoadBalanceResponse, int>;
+
+ explicit BalancerServiceImpl(int client_load_reporting_interval_seconds)
+ : client_load_reporting_interval_seconds_(
+ client_load_reporting_interval_seconds) {}
+
+ Status BalanceLoad(ServerContext* context, Stream* stream) override {
+ gpr_log(GPR_INFO, "LB[%p]: BalanceLoad", this);
+ {
+ grpc::internal::MutexLock lock(&mu_);
+ if (serverlist_done_) goto done;
+ }
+ {
+ // Balancer shouldn't receive the call credentials metadata.
+ EXPECT_EQ(context->client_metadata().find(g_kCallCredsMdKey),
+ context->client_metadata().end());
+ LoadBalanceRequest request;
+ std::vector<ResponseDelayPair> responses_and_delays;
+
+ if (!stream->Read(&request)) {
+ goto done;
} else {
if (request.has_initial_request()) {
grpc::internal::MutexLock lock(&mu_);
service_names_.push_back(request.initial_request().name());
}
- }
- IncreaseRequestCount();
- gpr_log(GPR_INFO, "LB[%p]: received initial message '%s'", this,
- request.DebugString().c_str());
-
- // TODO(juanlishen): Initial response should always be the first response.
- if (client_load_reporting_interval_seconds_ > 0) {
- LoadBalanceResponse initial_response;
- initial_response.mutable_initial_response()
- ->mutable_client_stats_report_interval()
- ->set_seconds(client_load_reporting_interval_seconds_);
- stream->Write(initial_response);
- }
-
- {
- grpc::internal::MutexLock lock(&mu_);
- responses_and_delays = responses_and_delays_;
- }
- for (const auto& response_and_delay : responses_and_delays) {
- SendResponse(stream, response_and_delay.first,
- response_and_delay.second);
- }
- {
- grpc::internal::MutexLock lock(&mu_);
- serverlist_cond_.WaitUntil(&mu_, [this] { return serverlist_done_; });
- }
-
- if (client_load_reporting_interval_seconds_ > 0) {
- request.Clear();
+ }
+ IncreaseRequestCount();
+ gpr_log(GPR_INFO, "LB[%p]: received initial message '%s'", this,
+ request.DebugString().c_str());
+
+ // TODO(juanlishen): Initial response should always be the first response.
+ if (client_load_reporting_interval_seconds_ > 0) {
+ LoadBalanceResponse initial_response;
+ initial_response.mutable_initial_response()
+ ->mutable_client_stats_report_interval()
+ ->set_seconds(client_load_reporting_interval_seconds_);
+ stream->Write(initial_response);
+ }
+
+ {
+ grpc::internal::MutexLock lock(&mu_);
+ responses_and_delays = responses_and_delays_;
+ }
+ for (const auto& response_and_delay : responses_and_delays) {
+ SendResponse(stream, response_and_delay.first,
+ response_and_delay.second);
+ }
+ {
+ grpc::internal::MutexLock lock(&mu_);
+ serverlist_cond_.WaitUntil(&mu_, [this] { return serverlist_done_; });
+ }
+
+ if (client_load_reporting_interval_seconds_ > 0) {
+ request.Clear();
while (stream->Read(&request)) {
- gpr_log(GPR_INFO, "LB[%p]: received client load report message '%s'",
- this, request.DebugString().c_str());
- GPR_ASSERT(request.has_client_stats());
+ gpr_log(GPR_INFO, "LB[%p]: received client load report message '%s'",
+ this, request.DebugString().c_str());
+ GPR_ASSERT(request.has_client_stats());
ClientStats load_report;
load_report.num_calls_started =
- request.client_stats().num_calls_started();
+ request.client_stats().num_calls_started();
load_report.num_calls_finished =
- request.client_stats().num_calls_finished();
+ request.client_stats().num_calls_finished();
load_report.num_calls_finished_with_client_failed_to_send =
- request.client_stats()
- .num_calls_finished_with_client_failed_to_send();
+ request.client_stats()
+ .num_calls_finished_with_client_failed_to_send();
load_report.num_calls_finished_known_received =
- request.client_stats().num_calls_finished_known_received();
- for (const auto& drop_token_count :
- request.client_stats().calls_finished_with_drop()) {
+ request.client_stats().num_calls_finished_known_received();
+ for (const auto& drop_token_count :
+ request.client_stats().calls_finished_with_drop()) {
load_report
.drop_token_counts[drop_token_count.load_balance_token()] =
- drop_token_count.num_calls();
- }
+ drop_token_count.num_calls();
+ }
// We need to acquire the lock here in order to prevent the notify_one
// below from firing before its corresponding wait is executed.
grpc::internal::MutexLock lock(&mu_);
load_report_queue_.emplace_back(std::move(load_report));
if (load_report_cond_ != nullptr) load_report_cond_->Signal();
- }
- }
- }
- done:
- gpr_log(GPR_INFO, "LB[%p]: done", this);
- return Status::OK;
- }
-
- void add_response(const LoadBalanceResponse& response, int send_after_ms) {
- grpc::internal::MutexLock lock(&mu_);
- responses_and_delays_.push_back(std::make_pair(response, send_after_ms));
- }
-
- void Start() {
- grpc::internal::MutexLock lock(&mu_);
- serverlist_done_ = false;
- responses_and_delays_.clear();
+ }
+ }
+ }
+ done:
+ gpr_log(GPR_INFO, "LB[%p]: done", this);
+ return Status::OK;
+ }
+
+ void add_response(const LoadBalanceResponse& response, int send_after_ms) {
+ grpc::internal::MutexLock lock(&mu_);
+ responses_and_delays_.push_back(std::make_pair(response, send_after_ms));
+ }
+
+ void Start() {
+ grpc::internal::MutexLock lock(&mu_);
+ serverlist_done_ = false;
+ responses_and_delays_.clear();
load_report_queue_.clear();
- }
-
- void Shutdown() {
- NotifyDoneWithServerlists();
- gpr_log(GPR_INFO, "LB[%p]: shut down", this);
- }
-
- static LoadBalanceResponse BuildResponseForBackends(
- const std::vector<int>& backend_ports,
+ }
+
+ void Shutdown() {
+ NotifyDoneWithServerlists();
+ gpr_log(GPR_INFO, "LB[%p]: shut down", this);
+ }
+
+ static LoadBalanceResponse BuildResponseForBackends(
+ const std::vector<int>& backend_ports,
const std::map<TString, size_t>& drop_token_counts) {
- LoadBalanceResponse response;
- for (const auto& drop_token_count : drop_token_counts) {
- for (size_t i = 0; i < drop_token_count.second; ++i) {
- auto* server = response.mutable_server_list()->add_servers();
- server->set_drop(true);
- server->set_load_balance_token(drop_token_count.first);
- }
- }
- for (const int& backend_port : backend_ports) {
- auto* server = response.mutable_server_list()->add_servers();
- server->set_ip_address(Ip4ToPackedString("127.0.0.1"));
- server->set_port(backend_port);
- static int token_count = 0;
+ LoadBalanceResponse response;
+ for (const auto& drop_token_count : drop_token_counts) {
+ for (size_t i = 0; i < drop_token_count.second; ++i) {
+ auto* server = response.mutable_server_list()->add_servers();
+ server->set_drop(true);
+ server->set_load_balance_token(drop_token_count.first);
+ }
+ }
+ for (const int& backend_port : backend_ports) {
+ auto* server = response.mutable_server_list()->add_servers();
+ server->set_ip_address(Ip4ToPackedString("127.0.0.1"));
+ server->set_port(backend_port);
+ static int token_count = 0;
server->set_load_balance_token(
y_absl::StrFormat("token%03d", ++token_count));
- }
- return response;
- }
-
+ }
+ return response;
+ }
+
ClientStats WaitForLoadReport() {
- grpc::internal::MutexLock lock(&mu_);
+ grpc::internal::MutexLock lock(&mu_);
grpc::internal::CondVar cv;
if (load_report_queue_.empty()) {
load_report_cond_ = &cv;
@@ -355,216 +355,216 @@ class BalancerServiceImpl : public BalancerService {
ClientStats load_report = std::move(load_report_queue_.front());
load_report_queue_.pop_front();
return load_report;
- }
-
- void NotifyDoneWithServerlists() {
- grpc::internal::MutexLock lock(&mu_);
- if (!serverlist_done_) {
- serverlist_done_ = true;
- serverlist_cond_.Broadcast();
- }
- }
-
+ }
+
+ void NotifyDoneWithServerlists() {
+ grpc::internal::MutexLock lock(&mu_);
+ if (!serverlist_done_) {
+ serverlist_done_ = true;
+ serverlist_cond_.Broadcast();
+ }
+ }
+
std::vector<TString> service_names() {
grpc::internal::MutexLock lock(&mu_);
return service_names_;
}
- private:
- void SendResponse(Stream* stream, const LoadBalanceResponse& response,
- int delay_ms) {
- gpr_log(GPR_INFO, "LB[%p]: sleeping for %d ms...", this, delay_ms);
- if (delay_ms > 0) {
- gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
- }
- gpr_log(GPR_INFO, "LB[%p]: Woke up! Sending response '%s'", this,
- response.DebugString().c_str());
- IncreaseResponseCount();
- stream->Write(response);
- }
-
- const int client_load_reporting_interval_seconds_;
- std::vector<ResponseDelayPair> responses_and_delays_;
+ private:
+ void SendResponse(Stream* stream, const LoadBalanceResponse& response,
+ int delay_ms) {
+ gpr_log(GPR_INFO, "LB[%p]: sleeping for %d ms...", this, delay_ms);
+ if (delay_ms > 0) {
+ gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
+ }
+ gpr_log(GPR_INFO, "LB[%p]: Woke up! Sending response '%s'", this,
+ response.DebugString().c_str());
+ IncreaseResponseCount();
+ stream->Write(response);
+ }
+
+ const int client_load_reporting_interval_seconds_;
+ std::vector<ResponseDelayPair> responses_and_delays_;
std::vector<TString> service_names_;
- grpc::internal::Mutex mu_;
- grpc::internal::CondVar serverlist_cond_;
- bool serverlist_done_ = false;
+ grpc::internal::Mutex mu_;
+ grpc::internal::CondVar serverlist_cond_;
+ bool serverlist_done_ = false;
grpc::internal::CondVar* load_report_cond_ = nullptr;
std::deque<ClientStats> load_report_queue_;
-};
-
-class GrpclbEnd2endTest : public ::testing::Test {
- protected:
- GrpclbEnd2endTest(size_t num_backends, size_t num_balancers,
- int client_load_reporting_interval_seconds)
- : server_host_("localhost"),
- num_backends_(num_backends),
- num_balancers_(num_balancers),
- client_load_reporting_interval_seconds_(
- client_load_reporting_interval_seconds) {}
-
- static void SetUpTestCase() {
- // Make the backup poller poll very frequently in order to pick up
- // updates from all the subchannels's FDs.
- GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
- grpc_init();
- }
-
- static void TearDownTestCase() { grpc_shutdown(); }
-
- void SetUp() override {
- response_generator_ =
- grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
- // Start the backends.
- for (size_t i = 0; i < num_backends_; ++i) {
- backends_.emplace_back(new ServerThread<BackendServiceImpl>("backend"));
- backends_.back()->Start(server_host_);
- }
- // Start the load balancers.
- for (size_t i = 0; i < num_balancers_; ++i) {
- balancers_.emplace_back(new ServerThread<BalancerServiceImpl>(
- "balancer", client_load_reporting_interval_seconds_));
- balancers_.back()->Start(server_host_);
- }
- ResetStub();
- }
-
- void TearDown() override {
- ShutdownAllBackends();
- for (auto& balancer : balancers_) balancer->Shutdown();
- }
-
- void StartAllBackends() {
- for (auto& backend : backends_) backend->Start(server_host_);
- }
-
- void StartBackend(size_t index) { backends_[index]->Start(server_host_); }
-
- void ShutdownAllBackends() {
- for (auto& backend : backends_) backend->Shutdown();
- }
-
- void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
-
- void ResetStub(int fallback_timeout = 0,
+};
+
+class GrpclbEnd2endTest : public ::testing::Test {
+ protected:
+ GrpclbEnd2endTest(size_t num_backends, size_t num_balancers,
+ int client_load_reporting_interval_seconds)
+ : server_host_("localhost"),
+ num_backends_(num_backends),
+ num_balancers_(num_balancers),
+ client_load_reporting_interval_seconds_(
+ client_load_reporting_interval_seconds) {}
+
+ static void SetUpTestCase() {
+ // Make the backup poller poll very frequently in order to pick up
+ // updates from all the subchannels's FDs.
+ GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+ grpc_init();
+ }
+
+ static void TearDownTestCase() { grpc_shutdown(); }
+
+ void SetUp() override {
+ response_generator_ =
+ grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
+ // Start the backends.
+ for (size_t i = 0; i < num_backends_; ++i) {
+ backends_.emplace_back(new ServerThread<BackendServiceImpl>("backend"));
+ backends_.back()->Start(server_host_);
+ }
+ // Start the load balancers.
+ for (size_t i = 0; i < num_balancers_; ++i) {
+ balancers_.emplace_back(new ServerThread<BalancerServiceImpl>(
+ "balancer", client_load_reporting_interval_seconds_));
+ balancers_.back()->Start(server_host_);
+ }
+ ResetStub();
+ }
+
+ void TearDown() override {
+ ShutdownAllBackends();
+ for (auto& balancer : balancers_) balancer->Shutdown();
+ }
+
+ void StartAllBackends() {
+ for (auto& backend : backends_) backend->Start(server_host_);
+ }
+
+ void StartBackend(size_t index) { backends_[index]->Start(server_host_); }
+
+ void ShutdownAllBackends() {
+ for (auto& backend : backends_) backend->Shutdown();
+ }
+
+ void ShutdownBackend(size_t index) { backends_[index]->Shutdown(); }
+
+ void ResetStub(int fallback_timeout = 0,
const TString& expected_targets = "") {
- ChannelArguments args;
- if (fallback_timeout > 0) args.SetGrpclbFallbackTimeout(fallback_timeout);
- args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
- response_generator_.get());
- if (!expected_targets.empty()) {
- args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
- }
- std::ostringstream uri;
- uri << "fake:///" << kApplicationTargetName_;
- // TODO(dgq): templatize tests to run everything using both secure and
- // insecure channel credentials.
- grpc_channel_credentials* channel_creds =
- grpc_fake_transport_security_credentials_create();
- grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
- g_kCallCredsMdKey, g_kCallCredsMdValue, false);
- std::shared_ptr<ChannelCredentials> creds(
- new SecureChannelCredentials(grpc_composite_channel_credentials_create(
- channel_creds, call_creds, nullptr)));
- call_creds->Unref();
- channel_creds->Unref();
- channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args);
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- void ResetBackendCounters() {
- for (auto& backend : backends_) backend->service_.ResetCounters();
- }
-
- ClientStats WaitForLoadReports() {
- ClientStats client_stats;
- for (auto& balancer : balancers_) {
- client_stats += balancer->service_.WaitForLoadReport();
- }
- return client_stats;
- }
-
- bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) {
- if (stop_index == 0) stop_index = backends_.size();
- for (size_t i = start_index; i < stop_index; ++i) {
- if (backends_[i]->service_.request_count() == 0) return false;
- }
- return true;
- }
-
- void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
- int* num_drops) {
- const Status status = SendRpc();
- if (status.ok()) {
- ++*num_ok;
- } else {
- if (status.error_message() == "Call dropped by load balancing policy") {
- ++*num_drops;
- } else {
- ++*num_failure;
- }
- }
- ++*num_total;
- }
-
- std::tuple<int, int, int> WaitForAllBackends(int num_requests_multiple_of = 1,
- size_t start_index = 0,
- size_t stop_index = 0) {
- int num_ok = 0;
- int num_failure = 0;
- int num_drops = 0;
- int num_total = 0;
- while (!SeenAllBackends(start_index, stop_index)) {
- SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
- }
- while (num_total % num_requests_multiple_of != 0) {
- SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
- }
- ResetBackendCounters();
- gpr_log(GPR_INFO,
- "Performed %d warm up requests (a multiple of %d) against the "
- "backends. %d succeeded, %d failed, %d dropped.",
- num_total, num_requests_multiple_of, num_ok, num_failure,
- num_drops);
- return std::make_tuple(num_ok, num_failure, num_drops);
- }
-
- void WaitForBackend(size_t backend_idx) {
- do {
- (void)SendRpc();
- } while (backends_[backend_idx]->service_.request_count() == 0);
- ResetBackendCounters();
- }
-
- struct AddressData {
- int port;
+ ChannelArguments args;
+ if (fallback_timeout > 0) args.SetGrpclbFallbackTimeout(fallback_timeout);
+ args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
+ response_generator_.get());
+ if (!expected_targets.empty()) {
+ args.SetString(GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
+ }
+ std::ostringstream uri;
+ uri << "fake:///" << kApplicationTargetName_;
+ // TODO(dgq): templatize tests to run everything using both secure and
+ // insecure channel credentials.
+ grpc_channel_credentials* channel_creds =
+ grpc_fake_transport_security_credentials_create();
+ grpc_call_credentials* call_creds = grpc_md_only_test_credentials_create(
+ g_kCallCredsMdKey, g_kCallCredsMdValue, false);
+ std::shared_ptr<ChannelCredentials> creds(
+ new SecureChannelCredentials(grpc_composite_channel_credentials_create(
+ channel_creds, call_creds, nullptr)));
+ call_creds->Unref();
+ channel_creds->Unref();
+ channel_ = ::grpc::CreateCustomChannel(uri.str(), creds, args);
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ void ResetBackendCounters() {
+ for (auto& backend : backends_) backend->service_.ResetCounters();
+ }
+
+ ClientStats WaitForLoadReports() {
+ ClientStats client_stats;
+ for (auto& balancer : balancers_) {
+ client_stats += balancer->service_.WaitForLoadReport();
+ }
+ return client_stats;
+ }
+
+ bool SeenAllBackends(size_t start_index = 0, size_t stop_index = 0) {
+ if (stop_index == 0) stop_index = backends_.size();
+ for (size_t i = start_index; i < stop_index; ++i) {
+ if (backends_[i]->service_.request_count() == 0) return false;
+ }
+ return true;
+ }
+
+ void SendRpcAndCount(int* num_total, int* num_ok, int* num_failure,
+ int* num_drops) {
+ const Status status = SendRpc();
+ if (status.ok()) {
+ ++*num_ok;
+ } else {
+ if (status.error_message() == "Call dropped by load balancing policy") {
+ ++*num_drops;
+ } else {
+ ++*num_failure;
+ }
+ }
+ ++*num_total;
+ }
+
+ std::tuple<int, int, int> WaitForAllBackends(int num_requests_multiple_of = 1,
+ size_t start_index = 0,
+ size_t stop_index = 0) {
+ int num_ok = 0;
+ int num_failure = 0;
+ int num_drops = 0;
+ int num_total = 0;
+ while (!SeenAllBackends(start_index, stop_index)) {
+ SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
+ }
+ while (num_total % num_requests_multiple_of != 0) {
+ SendRpcAndCount(&num_total, &num_ok, &num_failure, &num_drops);
+ }
+ ResetBackendCounters();
+ gpr_log(GPR_INFO,
+ "Performed %d warm up requests (a multiple of %d) against the "
+ "backends. %d succeeded, %d failed, %d dropped.",
+ num_total, num_requests_multiple_of, num_ok, num_failure,
+ num_drops);
+ return std::make_tuple(num_ok, num_failure, num_drops);
+ }
+
+ void WaitForBackend(size_t backend_idx) {
+ do {
+ (void)SendRpc();
+ } while (backends_[backend_idx]->service_.request_count() == 0);
+ ResetBackendCounters();
+ }
+
+ struct AddressData {
+ int port;
TString balancer_name;
- };
-
+ };
+
static grpc_core::ServerAddressList CreateLbAddressesFromAddressDataList(
- const std::vector<AddressData>& address_data) {
- grpc_core::ServerAddressList addresses;
- for (const auto& addr : address_data) {
+ const std::vector<AddressData>& address_data) {
+ grpc_core::ServerAddressList addresses;
+ for (const auto& addr : address_data) {
TString lb_uri_str = y_absl::StrCat("ipv4:127.0.0.1:", addr.port);
grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str.c_str(), true);
- GPR_ASSERT(lb_uri != nullptr);
- grpc_resolved_address address;
- GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
+ GPR_ASSERT(lb_uri != nullptr);
+ grpc_resolved_address address;
+ GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
grpc_arg arg = grpc_core::CreateAuthorityOverrideChannelArg(
addr.balancer_name.c_str());
grpc_channel_args* args =
grpc_channel_args_copy_and_add(nullptr, &arg, 1);
- addresses.emplace_back(address.addr, address.len, args);
- grpc_uri_destroy(lb_uri);
- }
- return addresses;
- }
-
+ addresses.emplace_back(address.addr, address.len, args);
+ grpc_uri_destroy(lb_uri);
+ }
+ return addresses;
+ }
+
static grpc_core::Resolver::Result MakeResolverResult(
const std::vector<AddressData>& balancer_address_data,
const std::vector<AddressData>& backend_address_data = {},
@@ -583,191 +583,191 @@ class GrpclbEnd2endTest : public ::testing::Test {
return result;
}
- void SetNextResolutionAllBalancers(
+ void SetNextResolutionAllBalancers(
const char* service_config_json = kDefaultServiceConfig) {
- std::vector<AddressData> addresses;
- for (size_t i = 0; i < balancers_.size(); ++i) {
+ std::vector<AddressData> addresses;
+ for (size_t i = 0; i < balancers_.size(); ++i) {
addresses.emplace_back(AddressData{balancers_[i]->port_, ""});
- }
+ }
SetNextResolution(addresses, {}, service_config_json);
- }
-
+ }
+
void SetNextResolution(
const std::vector<AddressData>& balancer_address_data,
const std::vector<AddressData>& backend_address_data = {},
const char* service_config_json = kDefaultServiceConfig) {
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result = MakeResolverResult(
balancer_address_data, backend_address_data, service_config_json);
- response_generator_->SetResponse(std::move(result));
- }
-
- void SetNextReresolutionResponse(
+ response_generator_->SetResponse(std::move(result));
+ }
+
+ void SetNextReresolutionResponse(
const std::vector<AddressData>& balancer_address_data,
const std::vector<AddressData>& backend_address_data = {},
const char* service_config_json = kDefaultServiceConfig) {
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result = MakeResolverResult(
balancer_address_data, backend_address_data, service_config_json);
- response_generator_->SetReresolutionResponse(std::move(result));
- }
-
- const std::vector<int> GetBackendPorts(size_t start_index = 0,
- size_t stop_index = 0) const {
- if (stop_index == 0) stop_index = backends_.size();
- std::vector<int> backend_ports;
- for (size_t i = start_index; i < stop_index; ++i) {
- backend_ports.push_back(backends_[i]->port_);
- }
- return backend_ports;
- }
-
- void ScheduleResponseForBalancer(size_t i,
- const LoadBalanceResponse& response,
- int delay_ms) {
- balancers_[i]->service_.add_response(response, delay_ms);
- }
-
- Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 1000,
+ response_generator_->SetReresolutionResponse(std::move(result));
+ }
+
+ const std::vector<int> GetBackendPorts(size_t start_index = 0,
+ size_t stop_index = 0) const {
+ if (stop_index == 0) stop_index = backends_.size();
+ std::vector<int> backend_ports;
+ for (size_t i = start_index; i < stop_index; ++i) {
+ backend_ports.push_back(backends_[i]->port_);
+ }
+ return backend_ports;
+ }
+
+ void ScheduleResponseForBalancer(size_t i,
+ const LoadBalanceResponse& response,
+ int delay_ms) {
+ balancers_[i]->service_.add_response(response, delay_ms);
+ }
+
+ Status SendRpc(EchoResponse* response = nullptr, int timeout_ms = 1000,
bool wait_for_ready = false,
const Status& expected_status = Status::OK) {
- const bool local_response = (response == nullptr);
- if (local_response) response = new EchoResponse;
- EchoRequest request;
- request.set_message(kRequestMessage_);
+ const bool local_response = (response == nullptr);
+ if (local_response) response = new EchoResponse;
+ EchoRequest request;
+ request.set_message(kRequestMessage_);
if (!expected_status.ok()) {
auto* error = request.mutable_param()->mutable_expected_error();
error->set_code(expected_status.error_code());
error->set_error_message(expected_status.error_message());
}
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
- if (wait_for_ready) context.set_wait_for_ready(true);
- Status status = stub_->Echo(&context, request, response);
- if (local_response) delete response;
- return status;
- }
-
- void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 1000,
- bool wait_for_ready = false) {
- for (size_t i = 0; i < times; ++i) {
- EchoResponse response;
- const Status status = SendRpc(&response, timeout_ms, wait_for_ready);
- EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
- << " message=" << status.error_message();
- EXPECT_EQ(response.message(), kRequestMessage_);
- }
- }
-
- void CheckRpcSendFailure() {
- const Status status = SendRpc();
- EXPECT_FALSE(status.ok());
- }
-
- template <typename T>
- struct ServerThread {
- template <typename... Args>
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
+ if (wait_for_ready) context.set_wait_for_ready(true);
+ Status status = stub_->Echo(&context, request, response);
+ if (local_response) delete response;
+ return status;
+ }
+
+ void CheckRpcSendOk(const size_t times = 1, const int timeout_ms = 1000,
+ bool wait_for_ready = false) {
+ for (size_t i = 0; i < times; ++i) {
+ EchoResponse response;
+ const Status status = SendRpc(&response, timeout_ms, wait_for_ready);
+ EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
+ << " message=" << status.error_message();
+ EXPECT_EQ(response.message(), kRequestMessage_);
+ }
+ }
+
+ void CheckRpcSendFailure() {
+ const Status status = SendRpc();
+ EXPECT_FALSE(status.ok());
+ }
+
+ template <typename T>
+ struct ServerThread {
+ template <typename... Args>
explicit ServerThread(const TString& type, Args&&... args)
- : port_(grpc_pick_unused_port_or_die()),
- type_(type),
- service_(std::forward<Args>(args)...) {}
-
+ : port_(grpc_pick_unused_port_or_die()),
+ type_(type),
+ service_(std::forward<Args>(args)...) {}
+
void Start(const TString& server_host) {
- gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
- GPR_ASSERT(!running_);
- running_ = true;
- service_.Start();
- grpc::internal::Mutex mu;
- // We need to acquire the lock here in order to prevent the notify_one
- // by ServerThread::Serve from firing before the wait below is hit.
- grpc::internal::MutexLock lock(&mu);
- grpc::internal::CondVar cond;
- thread_.reset(new std::thread(
- std::bind(&ServerThread::Serve, this, server_host, &mu, &cond)));
- cond.Wait(&mu);
- gpr_log(GPR_INFO, "%s server startup complete", type_.c_str());
- }
-
+ gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
+ GPR_ASSERT(!running_);
+ running_ = true;
+ service_.Start();
+ grpc::internal::Mutex mu;
+ // We need to acquire the lock here in order to prevent the notify_one
+ // by ServerThread::Serve from firing before the wait below is hit.
+ grpc::internal::MutexLock lock(&mu);
+ grpc::internal::CondVar cond;
+ thread_.reset(new std::thread(
+ std::bind(&ServerThread::Serve, this, server_host, &mu, &cond)));
+ cond.Wait(&mu);
+ gpr_log(GPR_INFO, "%s server startup complete", type_.c_str());
+ }
+
void Serve(const TString& server_host, grpc::internal::Mutex* mu,
- grpc::internal::CondVar* cond) {
- // We need to acquire the lock here in order to prevent the notify_one
- // below from firing before its corresponding wait is executed.
- grpc::internal::MutexLock lock(mu);
- std::ostringstream server_address;
- server_address << server_host << ":" << port_;
- ServerBuilder builder;
- std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
- grpc_fake_transport_security_server_credentials_create()));
- builder.AddListeningPort(server_address.str(), creds);
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- cond->Signal();
- }
-
- void Shutdown() {
- if (!running_) return;
- gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str());
- service_.Shutdown();
- server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
- thread_->join();
- gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
- running_ = false;
- }
-
- const int port_;
+ grpc::internal::CondVar* cond) {
+ // We need to acquire the lock here in order to prevent the notify_one
+ // below from firing before its corresponding wait is executed.
+ grpc::internal::MutexLock lock(mu);
+ std::ostringstream server_address;
+ server_address << server_host << ":" << port_;
+ ServerBuilder builder;
+ std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
+ grpc_fake_transport_security_server_credentials_create()));
+ builder.AddListeningPort(server_address.str(), creds);
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ cond->Signal();
+ }
+
+ void Shutdown() {
+ if (!running_) return;
+ gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str());
+ service_.Shutdown();
+ server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
+ thread_->join();
+ gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
+ running_ = false;
+ }
+
+ const int port_;
TString type_;
- T service_;
- std::unique_ptr<Server> server_;
- std::unique_ptr<std::thread> thread_;
- bool running_ = false;
- };
-
+ T service_;
+ std::unique_ptr<Server> server_;
+ std::unique_ptr<std::thread> thread_;
+ bool running_ = false;
+ };
+
const TString server_host_;
- const size_t num_backends_;
- const size_t num_balancers_;
- const int client_load_reporting_interval_seconds_;
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::vector<std::unique_ptr<ServerThread<BackendServiceImpl>>> backends_;
- std::vector<std::unique_ptr<ServerThread<BalancerServiceImpl>>> balancers_;
- grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
- response_generator_;
+ const size_t num_backends_;
+ const size_t num_balancers_;
+ const int client_load_reporting_interval_seconds_;
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::vector<std::unique_ptr<ServerThread<BackendServiceImpl>>> backends_;
+ std::vector<std::unique_ptr<ServerThread<BalancerServiceImpl>>> balancers_;
+ grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
+ response_generator_;
const TString kRequestMessage_ = "Live long and prosper.";
const TString kApplicationTargetName_ = "application_target_name";
-};
-
-class SingleBalancerTest : public GrpclbEnd2endTest {
- public:
- SingleBalancerTest() : GrpclbEnd2endTest(4, 1, 0) {}
-};
-
-TEST_F(SingleBalancerTest, Vanilla) {
- SetNextResolutionAllBalancers();
- const size_t kNumRpcsPerAddress = 100;
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- // Make sure that trying to connect works without a call.
- channel_->GetState(true /* try_to_connect */);
- // We need to wait for all backends to come online.
- WaitForAllBackends();
- // Send kNumRpcsPerAddress RPCs per server.
- CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
-
- // Each backend should have gotten 100 requests.
- for (size_t i = 0; i < backends_.size(); ++i) {
- EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
- }
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-
- // Check LB policy name for the channel.
- EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
-}
-
+};
+
+class SingleBalancerTest : public GrpclbEnd2endTest {
+ public:
+ SingleBalancerTest() : GrpclbEnd2endTest(4, 1, 0) {}
+};
+
+TEST_F(SingleBalancerTest, Vanilla) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumRpcsPerAddress = 100;
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ // Make sure that trying to connect works without a call.
+ channel_->GetState(true /* try_to_connect */);
+ // We need to wait for all backends to come online.
+ WaitForAllBackends();
+ // Send kNumRpcsPerAddress RPCs per server.
+ CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
+
+ // Each backend should have gotten 100 requests.
+ for (size_t i = 0; i < backends_.size(); ++i) {
+ EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
+ }
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+
+ // Check LB policy name for the channel.
+ EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
+}
+
TEST_F(SingleBalancerTest, ReturnServerStatus) {
SetNextResolutionAllBalancers();
ScheduleResponseForBalancer(
@@ -784,550 +784,550 @@ TEST_F(SingleBalancerTest, ReturnServerStatus) {
EXPECT_EQ(actual.error_message(), expected.error_message());
}
-TEST_F(SingleBalancerTest, SelectGrpclbWithMigrationServiceConfig) {
- SetNextResolutionAllBalancers(
- "{\n"
- " \"loadBalancingConfig\":[\n"
- " { \"does_not_exist\":{} },\n"
- " { \"grpclb\":{} }\n"
- " ]\n"
- "}");
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- CheckRpcSendOk(1, 1000 /* timeout_ms */, true /* wait_for_ready */);
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- // Check LB policy name for the channel.
- EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
-}
-
-TEST_F(SingleBalancerTest,
- SelectGrpclbWithMigrationServiceConfigAndNoAddresses) {
- const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
- ResetStub(kFallbackTimeoutMs);
+TEST_F(SingleBalancerTest, SelectGrpclbWithMigrationServiceConfig) {
+ SetNextResolutionAllBalancers(
+ "{\n"
+ " \"loadBalancingConfig\":[\n"
+ " { \"does_not_exist\":{} },\n"
+ " { \"grpclb\":{} }\n"
+ " ]\n"
+ "}");
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ CheckRpcSendOk(1, 1000 /* timeout_ms */, true /* wait_for_ready */);
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ // Check LB policy name for the channel.
+ EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
+}
+
+TEST_F(SingleBalancerTest,
+ SelectGrpclbWithMigrationServiceConfigAndNoAddresses) {
+ const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
+ ResetStub(kFallbackTimeoutMs);
SetNextResolution({}, {},
- "{\n"
- " \"loadBalancingConfig\":[\n"
- " { \"does_not_exist\":{} },\n"
- " { \"grpclb\":{} }\n"
- " ]\n"
- "}");
- // Try to connect.
- EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
- // Should go into state TRANSIENT_FAILURE when we enter fallback mode.
- const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(1);
- grpc_connectivity_state state;
- while ((state = channel_->GetState(false)) !=
- GRPC_CHANNEL_TRANSIENT_FAILURE) {
- ASSERT_TRUE(channel_->WaitForStateChange(state, deadline));
- }
- // Check LB policy name for the channel.
- EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
-}
-
-TEST_F(SingleBalancerTest, UsePickFirstChildPolicy) {
- SetNextResolutionAllBalancers(
- "{\n"
- " \"loadBalancingConfig\":[\n"
- " { \"grpclb\":{\n"
- " \"childPolicy\":[\n"
- " { \"pick_first\":{} }\n"
- " ]\n"
- " } }\n"
- " ]\n"
- "}");
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- const size_t kNumRpcs = num_backends_ * 2;
- CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // Check that all requests went to the first backend. This verifies
- // that we used pick_first instead of round_robin as the child policy.
- EXPECT_EQ(backends_[0]->service_.request_count(), kNumRpcs);
- for (size_t i = 1; i < backends_.size(); ++i) {
- EXPECT_EQ(backends_[i]->service_.request_count(), 0UL);
- }
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- // Check LB policy name for the channel.
- EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
-}
-
-TEST_F(SingleBalancerTest, SwapChildPolicy) {
- SetNextResolutionAllBalancers(
- "{\n"
- " \"loadBalancingConfig\":[\n"
- " { \"grpclb\":{\n"
- " \"childPolicy\":[\n"
- " { \"pick_first\":{} }\n"
- " ]\n"
- " } }\n"
- " ]\n"
- "}");
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- const size_t kNumRpcs = num_backends_ * 2;
- CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
- // Check that all requests went to the first backend. This verifies
- // that we used pick_first instead of round_robin as the child policy.
- EXPECT_EQ(backends_[0]->service_.request_count(), kNumRpcs);
- for (size_t i = 1; i < backends_.size(); ++i) {
- EXPECT_EQ(backends_[i]->service_.request_count(), 0UL);
- }
- // Send new resolution that removes child policy from service config.
+ "{\n"
+ " \"loadBalancingConfig\":[\n"
+ " { \"does_not_exist\":{} },\n"
+ " { \"grpclb\":{} }\n"
+ " ]\n"
+ "}");
+ // Try to connect.
+ EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
+ // Should go into state TRANSIENT_FAILURE when we enter fallback mode.
+ const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(1);
+ grpc_connectivity_state state;
+ while ((state = channel_->GetState(false)) !=
+ GRPC_CHANNEL_TRANSIENT_FAILURE) {
+ ASSERT_TRUE(channel_->WaitForStateChange(state, deadline));
+ }
+ // Check LB policy name for the channel.
+ EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
+}
+
+TEST_F(SingleBalancerTest, UsePickFirstChildPolicy) {
+ SetNextResolutionAllBalancers(
+ "{\n"
+ " \"loadBalancingConfig\":[\n"
+ " { \"grpclb\":{\n"
+ " \"childPolicy\":[\n"
+ " { \"pick_first\":{} }\n"
+ " ]\n"
+ " } }\n"
+ " ]\n"
+ "}");
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ const size_t kNumRpcs = num_backends_ * 2;
+ CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // Check that all requests went to the first backend. This verifies
+ // that we used pick_first instead of round_robin as the child policy.
+ EXPECT_EQ(backends_[0]->service_.request_count(), kNumRpcs);
+ for (size_t i = 1; i < backends_.size(); ++i) {
+ EXPECT_EQ(backends_[i]->service_.request_count(), 0UL);
+ }
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ // Check LB policy name for the channel.
+ EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
+}
+
+TEST_F(SingleBalancerTest, SwapChildPolicy) {
+ SetNextResolutionAllBalancers(
+ "{\n"
+ " \"loadBalancingConfig\":[\n"
+ " { \"grpclb\":{\n"
+ " \"childPolicy\":[\n"
+ " { \"pick_first\":{} }\n"
+ " ]\n"
+ " } }\n"
+ " ]\n"
+ "}");
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ const size_t kNumRpcs = num_backends_ * 2;
+ CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
+ // Check that all requests went to the first backend. This verifies
+ // that we used pick_first instead of round_robin as the child policy.
+ EXPECT_EQ(backends_[0]->service_.request_count(), kNumRpcs);
+ for (size_t i = 1; i < backends_.size(); ++i) {
+ EXPECT_EQ(backends_[i]->service_.request_count(), 0UL);
+ }
+ // Send new resolution that removes child policy from service config.
SetNextResolutionAllBalancers();
- WaitForAllBackends();
- CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
- // Check that every backend saw the same number of requests. This verifies
- // that we used round_robin.
- for (size_t i = 0; i < backends_.size(); ++i) {
- EXPECT_EQ(backends_[i]->service_.request_count(), 2UL);
- }
- // Done.
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- // Check LB policy name for the channel.
- EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
-}
-
-TEST_F(SingleBalancerTest, SameBackendListedMultipleTimes) {
- SetNextResolutionAllBalancers();
- // Same backend listed twice.
- std::vector<int> ports;
- ports.push_back(backends_[0]->port_);
- ports.push_back(backends_[0]->port_);
- const size_t kNumRpcsPerAddress = 10;
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0);
- // We need to wait for the backend to come online.
- WaitForBackend(0);
- // Send kNumRpcsPerAddress RPCs per server.
- CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
- // Backend should have gotten 20 requests.
- EXPECT_EQ(kNumRpcsPerAddress * 2, backends_[0]->service_.request_count());
- // And they should have come from a single client port, because of
- // subchannel sharing.
- EXPECT_EQ(1UL, backends_[0]->service_.clients().size());
- balancers_[0]->service_.NotifyDoneWithServerlists();
-}
-
-TEST_F(SingleBalancerTest, SecureNaming) {
- ResetStub(0, kApplicationTargetName_ + ";lb");
+ WaitForAllBackends();
+ CheckRpcSendOk(kNumRpcs, 1000 /* timeout_ms */, true /* wait_for_ready */);
+ // Check that every backend saw the same number of requests. This verifies
+ // that we used round_robin.
+ for (size_t i = 0; i < backends_.size(); ++i) {
+ EXPECT_EQ(backends_[i]->service_.request_count(), 2UL);
+ }
+ // Done.
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ // Check LB policy name for the channel.
+ EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
+}
+
+TEST_F(SingleBalancerTest, SameBackendListedMultipleTimes) {
+ SetNextResolutionAllBalancers();
+ // Same backend listed twice.
+ std::vector<int> ports;
+ ports.push_back(backends_[0]->port_);
+ ports.push_back(backends_[0]->port_);
+ const size_t kNumRpcsPerAddress = 10;
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0);
+ // We need to wait for the backend to come online.
+ WaitForBackend(0);
+ // Send kNumRpcsPerAddress RPCs per server.
+ CheckRpcSendOk(kNumRpcsPerAddress * ports.size());
+ // Backend should have gotten 20 requests.
+ EXPECT_EQ(kNumRpcsPerAddress * 2, backends_[0]->service_.request_count());
+ // And they should have come from a single client port, because of
+ // subchannel sharing.
+ EXPECT_EQ(1UL, backends_[0]->service_.clients().size());
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+}
+
+TEST_F(SingleBalancerTest, SecureNaming) {
+ ResetStub(0, kApplicationTargetName_ + ";lb");
SetNextResolution({AddressData{balancers_[0]->port_, "lb"}});
- const size_t kNumRpcsPerAddress = 100;
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- // Make sure that trying to connect works without a call.
- channel_->GetState(true /* try_to_connect */);
- // We need to wait for all backends to come online.
- WaitForAllBackends();
- // Send kNumRpcsPerAddress RPCs per server.
- CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
-
- // Each backend should have gotten 100 requests.
- for (size_t i = 0; i < backends_.size(); ++i) {
- EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
- }
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- // Check LB policy name for the channel.
- EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
-}
-
-TEST_F(SingleBalancerTest, SecureNamingDeathTest) {
- ::testing::FLAGS_gtest_death_test_style = "threadsafe";
- // Make sure that we blow up (via abort() from the security connector) when
- // the name from the balancer doesn't match expectations.
- ASSERT_DEATH_IF_SUPPORTED(
- {
- ResetStub(0, kApplicationTargetName_ + ";lb");
+ const size_t kNumRpcsPerAddress = 100;
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ // Make sure that trying to connect works without a call.
+ channel_->GetState(true /* try_to_connect */);
+ // We need to wait for all backends to come online.
+ WaitForAllBackends();
+ // Send kNumRpcsPerAddress RPCs per server.
+ CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
+
+ // Each backend should have gotten 100 requests.
+ for (size_t i = 0; i < backends_.size(); ++i) {
+ EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
+ }
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ // Check LB policy name for the channel.
+ EXPECT_EQ("grpclb", channel_->GetLoadBalancingPolicyName());
+}
+
+TEST_F(SingleBalancerTest, SecureNamingDeathTest) {
+ ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+ // Make sure that we blow up (via abort() from the security connector) when
+ // the name from the balancer doesn't match expectations.
+ ASSERT_DEATH_IF_SUPPORTED(
+ {
+ ResetStub(0, kApplicationTargetName_ + ";lb");
SetNextResolution({AddressData{balancers_[0]->port_, "woops"}});
- channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
- },
- "");
-}
-
-TEST_F(SingleBalancerTest, InitiallyEmptyServerlist) {
- SetNextResolutionAllBalancers();
- const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
- const int kCallDeadlineMs = kServerlistDelayMs * 2;
- // First response is an empty serverlist, sent right away.
- ScheduleResponseForBalancer(0, LoadBalanceResponse(), 0);
- // Send non-empty serverlist only after kServerlistDelayMs
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- kServerlistDelayMs);
- const auto t0 = system_clock::now();
- // Client will block: LB will initially send empty serverlist.
- CheckRpcSendOk(1, kCallDeadlineMs, true /* wait_for_ready */);
- const auto ellapsed_ms =
- std::chrono::duration_cast<std::chrono::milliseconds>(
- system_clock::now() - t0);
- // but eventually, the LB sends a serverlist update that allows the call to
- // proceed. The call delay must be larger than the delay in sending the
- // populated serverlist but under the call's deadline (which is enforced by
- // the call's deadline).
- EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent two responses.
- EXPECT_EQ(2U, balancers_[0]->service_.response_count());
-}
-
-TEST_F(SingleBalancerTest, AllServersUnreachableFailFast) {
- SetNextResolutionAllBalancers();
- const size_t kNumUnreachableServers = 5;
- std::vector<int> ports;
- for (size_t i = 0; i < kNumUnreachableServers; ++i) {
- ports.push_back(grpc_pick_unused_port_or_die());
- }
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0);
- const Status status = SendRpc();
- // The error shouldn't be DEADLINE_EXCEEDED.
- EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-}
-
-TEST_F(SingleBalancerTest, Fallback) {
- SetNextResolutionAllBalancers();
- const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
- const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
- const size_t kNumBackendsInResolution = backends_.size() / 2;
-
- ResetStub(kFallbackTimeoutMs);
+ channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(1));
+ },
+ "");
+}
+
+TEST_F(SingleBalancerTest, InitiallyEmptyServerlist) {
+ SetNextResolutionAllBalancers();
+ const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
+ const int kCallDeadlineMs = kServerlistDelayMs * 2;
+ // First response is an empty serverlist, sent right away.
+ ScheduleResponseForBalancer(0, LoadBalanceResponse(), 0);
+ // Send non-empty serverlist only after kServerlistDelayMs
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ kServerlistDelayMs);
+ const auto t0 = system_clock::now();
+ // Client will block: LB will initially send empty serverlist.
+ CheckRpcSendOk(1, kCallDeadlineMs, true /* wait_for_ready */);
+ const auto ellapsed_ms =
+ std::chrono::duration_cast<std::chrono::milliseconds>(
+ system_clock::now() - t0);
+ // but eventually, the LB sends a serverlist update that allows the call to
+ // proceed. The call delay must be larger than the delay in sending the
+ // populated serverlist but under the call's deadline (which is enforced by
+ // the call's deadline).
+ EXPECT_GT(ellapsed_ms.count(), kServerlistDelayMs);
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent two responses.
+ EXPECT_EQ(2U, balancers_[0]->service_.response_count());
+}
+
+TEST_F(SingleBalancerTest, AllServersUnreachableFailFast) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumUnreachableServers = 5;
+ std::vector<int> ports;
+ for (size_t i = 0; i < kNumUnreachableServers; ++i) {
+ ports.push_back(grpc_pick_unused_port_or_die());
+ }
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(ports, {}), 0);
+ const Status status = SendRpc();
+ // The error shouldn't be DEADLINE_EXCEEDED.
+ EXPECT_EQ(StatusCode::UNAVAILABLE, status.error_code());
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+}
+
+TEST_F(SingleBalancerTest, Fallback) {
+ SetNextResolutionAllBalancers();
+ const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
+ const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
+ const size_t kNumBackendsInResolution = backends_.size() / 2;
+
+ ResetStub(kFallbackTimeoutMs);
std::vector<AddressData> balancer_addresses;
balancer_addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
std::vector<AddressData> backend_addresses;
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
backend_addresses.emplace_back(AddressData{backends_[i]->port_, ""});
- }
+ }
SetNextResolution(balancer_addresses, backend_addresses);
-
- // Send non-empty serverlist only after kServerlistDelayMs.
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumBackendsInResolution /* start_index */), {}),
- kServerlistDelayMs);
-
- // Wait until all the fallback backends are reachable.
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
- WaitForBackend(i);
- }
-
- // The first request.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(kNumBackendsInResolution);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
-
- // Fallback is used: each backend returned by the resolver should have
- // gotten one request.
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
- EXPECT_EQ(1U, backends_[i]->service_.request_count());
- }
- for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
- EXPECT_EQ(0U, backends_[i]->service_.request_count());
- }
-
- // Wait until the serverlist reception has been processed and all backends
- // in the serverlist are reachable.
- for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
- WaitForBackend(i);
- }
-
- // Send out the second request.
- gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
- CheckRpcSendOk(backends_.size() - kNumBackendsInResolution);
- gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
-
- // Serverlist is used: each backend returned by the balancer should
- // have gotten one request.
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
- EXPECT_EQ(0U, backends_[i]->service_.request_count());
- }
- for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
- EXPECT_EQ(1U, backends_[i]->service_.request_count());
- }
-
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-}
-
-TEST_F(SingleBalancerTest, FallbackUpdate) {
- SetNextResolutionAllBalancers();
- const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
- const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
- const size_t kNumBackendsInResolution = backends_.size() / 3;
- const size_t kNumBackendsInResolutionUpdate = backends_.size() / 3;
-
- ResetStub(kFallbackTimeoutMs);
+
+ // Send non-empty serverlist only after kServerlistDelayMs.
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumBackendsInResolution /* start_index */), {}),
+ kServerlistDelayMs);
+
+ // Wait until all the fallback backends are reachable.
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ WaitForBackend(i);
+ }
+
+ // The first request.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(kNumBackendsInResolution);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+
+ // Fallback is used: each backend returned by the resolver should have
+ // gotten one request.
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ EXPECT_EQ(1U, backends_[i]->service_.request_count());
+ }
+ for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
+ EXPECT_EQ(0U, backends_[i]->service_.request_count());
+ }
+
+ // Wait until the serverlist reception has been processed and all backends
+ // in the serverlist are reachable.
+ for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
+ WaitForBackend(i);
+ }
+
+ // Send out the second request.
+ gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
+ CheckRpcSendOk(backends_.size() - kNumBackendsInResolution);
+ gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
+
+ // Serverlist is used: each backend returned by the balancer should
+ // have gotten one request.
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ EXPECT_EQ(0U, backends_[i]->service_.request_count());
+ }
+ for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
+ EXPECT_EQ(1U, backends_[i]->service_.request_count());
+ }
+
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+}
+
+TEST_F(SingleBalancerTest, FallbackUpdate) {
+ SetNextResolutionAllBalancers();
+ const int kFallbackTimeoutMs = 200 * grpc_test_slowdown_factor();
+ const int kServerlistDelayMs = 500 * grpc_test_slowdown_factor();
+ const size_t kNumBackendsInResolution = backends_.size() / 3;
+ const size_t kNumBackendsInResolutionUpdate = backends_.size() / 3;
+
+ ResetStub(kFallbackTimeoutMs);
std::vector<AddressData> balancer_addresses;
balancer_addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
std::vector<AddressData> backend_addresses;
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
backend_addresses.emplace_back(AddressData{backends_[i]->port_, ""});
- }
+ }
SetNextResolution(balancer_addresses, backend_addresses);
-
- // Send non-empty serverlist only after kServerlistDelayMs.
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumBackendsInResolution +
- kNumBackendsInResolutionUpdate /* start_index */),
- {}),
- kServerlistDelayMs);
-
- // Wait until all the fallback backends are reachable.
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
- WaitForBackend(i);
- }
-
- // The first request.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(kNumBackendsInResolution);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
-
- // Fallback is used: each backend returned by the resolver should have
- // gotten one request.
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
- EXPECT_EQ(1U, backends_[i]->service_.request_count());
- }
- for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
- EXPECT_EQ(0U, backends_[i]->service_.request_count());
- }
-
+
+ // Send non-empty serverlist only after kServerlistDelayMs.
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumBackendsInResolution +
+ kNumBackendsInResolutionUpdate /* start_index */),
+ {}),
+ kServerlistDelayMs);
+
+ // Wait until all the fallback backends are reachable.
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ WaitForBackend(i);
+ }
+
+ // The first request.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(kNumBackendsInResolution);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+
+ // Fallback is used: each backend returned by the resolver should have
+ // gotten one request.
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ EXPECT_EQ(1U, backends_[i]->service_.request_count());
+ }
+ for (size_t i = kNumBackendsInResolution; i < backends_.size(); ++i) {
+ EXPECT_EQ(0U, backends_[i]->service_.request_count());
+ }
+
balancer_addresses.clear();
balancer_addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
backend_addresses.clear();
- for (size_t i = kNumBackendsInResolution;
- i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
+ for (size_t i = kNumBackendsInResolution;
+ i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
backend_addresses.emplace_back(AddressData{backends_[i]->port_, ""});
- }
+ }
SetNextResolution(balancer_addresses, backend_addresses);
-
- // Wait until the resolution update has been processed and all the new
- // fallback backends are reachable.
- for (size_t i = kNumBackendsInResolution;
- i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
- WaitForBackend(i);
- }
-
- // Send out the second request.
- gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
- CheckRpcSendOk(kNumBackendsInResolutionUpdate);
- gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
-
- // The resolution update is used: each backend in the resolution update should
- // have gotten one request.
- for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
- EXPECT_EQ(0U, backends_[i]->service_.request_count());
- }
- for (size_t i = kNumBackendsInResolution;
- i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
- EXPECT_EQ(1U, backends_[i]->service_.request_count());
- }
- for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
- i < backends_.size(); ++i) {
- EXPECT_EQ(0U, backends_[i]->service_.request_count());
- }
-
- // Wait until the serverlist reception has been processed and all backends
- // in the serverlist are reachable.
- for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
- i < backends_.size(); ++i) {
- WaitForBackend(i);
- }
-
- // Send out the third request.
- gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
- CheckRpcSendOk(backends_.size() - kNumBackendsInResolution -
- kNumBackendsInResolutionUpdate);
- gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
-
- // Serverlist is used: each backend returned by the balancer should
- // have gotten one request.
- for (size_t i = 0;
- i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
- EXPECT_EQ(0U, backends_[i]->service_.request_count());
- }
- for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
- i < backends_.size(); ++i) {
- EXPECT_EQ(1U, backends_[i]->service_.request_count());
- }
-
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-}
-
-TEST_F(SingleBalancerTest,
- FallbackAfterStartup_LoseContactWithBalancerThenBackends) {
- // First two backends are fallback, last two are pointed to by balancer.
- const size_t kNumFallbackBackends = 2;
- const size_t kNumBalancerBackends = backends_.size() - kNumFallbackBackends;
+
+ // Wait until the resolution update has been processed and all the new
+ // fallback backends are reachable.
+ for (size_t i = kNumBackendsInResolution;
+ i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
+ WaitForBackend(i);
+ }
+
+ // Send out the second request.
+ gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
+ CheckRpcSendOk(kNumBackendsInResolutionUpdate);
+ gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
+
+ // The resolution update is used: each backend in the resolution update should
+ // have gotten one request.
+ for (size_t i = 0; i < kNumBackendsInResolution; ++i) {
+ EXPECT_EQ(0U, backends_[i]->service_.request_count());
+ }
+ for (size_t i = kNumBackendsInResolution;
+ i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
+ EXPECT_EQ(1U, backends_[i]->service_.request_count());
+ }
+ for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
+ i < backends_.size(); ++i) {
+ EXPECT_EQ(0U, backends_[i]->service_.request_count());
+ }
+
+ // Wait until the serverlist reception has been processed and all backends
+ // in the serverlist are reachable.
+ for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
+ i < backends_.size(); ++i) {
+ WaitForBackend(i);
+ }
+
+ // Send out the third request.
+ gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
+ CheckRpcSendOk(backends_.size() - kNumBackendsInResolution -
+ kNumBackendsInResolutionUpdate);
+ gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
+
+ // Serverlist is used: each backend returned by the balancer should
+ // have gotten one request.
+ for (size_t i = 0;
+ i < kNumBackendsInResolution + kNumBackendsInResolutionUpdate; ++i) {
+ EXPECT_EQ(0U, backends_[i]->service_.request_count());
+ }
+ for (size_t i = kNumBackendsInResolution + kNumBackendsInResolutionUpdate;
+ i < backends_.size(); ++i) {
+ EXPECT_EQ(1U, backends_[i]->service_.request_count());
+ }
+
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+}
+
+TEST_F(SingleBalancerTest,
+ FallbackAfterStartup_LoseContactWithBalancerThenBackends) {
+ // First two backends are fallback, last two are pointed to by balancer.
+ const size_t kNumFallbackBackends = 2;
+ const size_t kNumBalancerBackends = backends_.size() - kNumFallbackBackends;
std::vector<AddressData> backend_addresses;
- for (size_t i = 0; i < kNumFallbackBackends; ++i) {
+ for (size_t i = 0; i < kNumFallbackBackends; ++i) {
backend_addresses.emplace_back(AddressData{backends_[i]->port_, ""});
- }
+ }
std::vector<AddressData> balancer_addresses;
- for (size_t i = 0; i < balancers_.size(); ++i) {
+ for (size_t i = 0; i < balancers_.size(); ++i) {
balancer_addresses.emplace_back(AddressData{balancers_[i]->port_, ""});
- }
+ }
SetNextResolution(balancer_addresses, backend_addresses);
- ScheduleResponseForBalancer(0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumFallbackBackends), {}),
- 0);
- // Try to connect.
- channel_->GetState(true /* try_to_connect */);
- WaitForAllBackends(1 /* num_requests_multiple_of */,
- kNumFallbackBackends /* start_index */);
- // Stop balancer. RPCs should continue going to backends from balancer.
- balancers_[0]->Shutdown();
- CheckRpcSendOk(100 * kNumBalancerBackends);
- for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
- EXPECT_EQ(100UL, backends_[i]->service_.request_count());
- }
- // Stop backends from balancer. This should put us in fallback mode.
- for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
- ShutdownBackend(i);
- }
- WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */,
- kNumFallbackBackends /* stop_index */);
- // Restart the backends from the balancer. We should *not* start
- // sending traffic back to them at this point (although the behavior
- // in xds may be different).
- for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
- StartBackend(i);
- }
- CheckRpcSendOk(100 * kNumBalancerBackends);
- for (size_t i = 0; i < kNumFallbackBackends; ++i) {
- EXPECT_EQ(100UL, backends_[i]->service_.request_count());
- }
- // Now start the balancer again. This should cause us to exit
- // fallback mode.
- balancers_[0]->Start(server_host_);
- ScheduleResponseForBalancer(0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumFallbackBackends), {}),
- 0);
- WaitForAllBackends(1 /* num_requests_multiple_of */,
- kNumFallbackBackends /* start_index */);
-}
-
-TEST_F(SingleBalancerTest,
- FallbackAfterStartup_LoseContactWithBackendsThenBalancer) {
- // First two backends are fallback, last two are pointed to by balancer.
- const size_t kNumFallbackBackends = 2;
- const size_t kNumBalancerBackends = backends_.size() - kNumFallbackBackends;
+ ScheduleResponseForBalancer(0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumFallbackBackends), {}),
+ 0);
+ // Try to connect.
+ channel_->GetState(true /* try_to_connect */);
+ WaitForAllBackends(1 /* num_requests_multiple_of */,
+ kNumFallbackBackends /* start_index */);
+ // Stop balancer. RPCs should continue going to backends from balancer.
+ balancers_[0]->Shutdown();
+ CheckRpcSendOk(100 * kNumBalancerBackends);
+ for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
+ EXPECT_EQ(100UL, backends_[i]->service_.request_count());
+ }
+ // Stop backends from balancer. This should put us in fallback mode.
+ for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
+ ShutdownBackend(i);
+ }
+ WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */,
+ kNumFallbackBackends /* stop_index */);
+ // Restart the backends from the balancer. We should *not* start
+ // sending traffic back to them at this point (although the behavior
+ // in xds may be different).
+ for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
+ StartBackend(i);
+ }
+ CheckRpcSendOk(100 * kNumBalancerBackends);
+ for (size_t i = 0; i < kNumFallbackBackends; ++i) {
+ EXPECT_EQ(100UL, backends_[i]->service_.request_count());
+ }
+ // Now start the balancer again. This should cause us to exit
+ // fallback mode.
+ balancers_[0]->Start(server_host_);
+ ScheduleResponseForBalancer(0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumFallbackBackends), {}),
+ 0);
+ WaitForAllBackends(1 /* num_requests_multiple_of */,
+ kNumFallbackBackends /* start_index */);
+}
+
+TEST_F(SingleBalancerTest,
+ FallbackAfterStartup_LoseContactWithBackendsThenBalancer) {
+ // First two backends are fallback, last two are pointed to by balancer.
+ const size_t kNumFallbackBackends = 2;
+ const size_t kNumBalancerBackends = backends_.size() - kNumFallbackBackends;
std::vector<AddressData> backend_addresses;
- for (size_t i = 0; i < kNumFallbackBackends; ++i) {
+ for (size_t i = 0; i < kNumFallbackBackends; ++i) {
backend_addresses.emplace_back(AddressData{backends_[i]->port_, ""});
- }
+ }
std::vector<AddressData> balancer_addresses;
- for (size_t i = 0; i < balancers_.size(); ++i) {
+ for (size_t i = 0; i < balancers_.size(); ++i) {
balancer_addresses.emplace_back(AddressData{balancers_[i]->port_, ""});
- }
+ }
SetNextResolution(balancer_addresses, backend_addresses);
- ScheduleResponseForBalancer(0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumFallbackBackends), {}),
- 0);
- // Try to connect.
- channel_->GetState(true /* try_to_connect */);
- WaitForAllBackends(1 /* num_requests_multiple_of */,
- kNumFallbackBackends /* start_index */);
- // Stop backends from balancer. Since we are still in contact with
- // the balancer at this point, RPCs should be failing.
- for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
- ShutdownBackend(i);
- }
- CheckRpcSendFailure();
- // Stop balancer. This should put us in fallback mode.
- balancers_[0]->Shutdown();
- WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */,
- kNumFallbackBackends /* stop_index */);
- // Restart the backends from the balancer. We should *not* start
- // sending traffic back to them at this point (although the behavior
- // in xds may be different).
- for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
- StartBackend(i);
- }
- CheckRpcSendOk(100 * kNumBalancerBackends);
- for (size_t i = 0; i < kNumFallbackBackends; ++i) {
- EXPECT_EQ(100UL, backends_[i]->service_.request_count());
- }
- // Now start the balancer again. This should cause us to exit
- // fallback mode.
- balancers_[0]->Start(server_host_);
- ScheduleResponseForBalancer(0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumFallbackBackends), {}),
- 0);
- WaitForAllBackends(1 /* num_requests_multiple_of */,
- kNumFallbackBackends /* start_index */);
-}
-
-TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerChannelFails) {
- const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
- ResetStub(kFallbackTimeoutMs);
- // Return an unreachable balancer and one fallback backend.
+ ScheduleResponseForBalancer(0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumFallbackBackends), {}),
+ 0);
+ // Try to connect.
+ channel_->GetState(true /* try_to_connect */);
+ WaitForAllBackends(1 /* num_requests_multiple_of */,
+ kNumFallbackBackends /* start_index */);
+ // Stop backends from balancer. Since we are still in contact with
+ // the balancer at this point, RPCs should be failing.
+ for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
+ ShutdownBackend(i);
+ }
+ CheckRpcSendFailure();
+ // Stop balancer. This should put us in fallback mode.
+ balancers_[0]->Shutdown();
+ WaitForAllBackends(1 /* num_requests_multiple_of */, 0 /* start_index */,
+ kNumFallbackBackends /* stop_index */);
+ // Restart the backends from the balancer. We should *not* start
+ // sending traffic back to them at this point (although the behavior
+ // in xds may be different).
+ for (size_t i = kNumFallbackBackends; i < backends_.size(); ++i) {
+ StartBackend(i);
+ }
+ CheckRpcSendOk(100 * kNumBalancerBackends);
+ for (size_t i = 0; i < kNumFallbackBackends; ++i) {
+ EXPECT_EQ(100UL, backends_[i]->service_.request_count());
+ }
+ // Now start the balancer again. This should cause us to exit
+ // fallback mode.
+ balancers_[0]->Start(server_host_);
+ ScheduleResponseForBalancer(0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumFallbackBackends), {}),
+ 0);
+ WaitForAllBackends(1 /* num_requests_multiple_of */,
+ kNumFallbackBackends /* start_index */);
+}
+
+TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerChannelFails) {
+ const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
+ ResetStub(kFallbackTimeoutMs);
+ // Return an unreachable balancer and one fallback backend.
std::vector<AddressData> balancer_addresses;
balancer_addresses.emplace_back(
AddressData{grpc_pick_unused_port_or_die(), ""});
std::vector<AddressData> backend_addresses;
backend_addresses.emplace_back(AddressData{backends_[0]->port_, ""});
SetNextResolution(balancer_addresses, backend_addresses);
- // Send RPC with deadline less than the fallback timeout and make sure it
- // succeeds.
- CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
- /* wait_for_ready */ false);
-}
-
-TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerCallFails) {
- const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
- ResetStub(kFallbackTimeoutMs);
+ // Send RPC with deadline less than the fallback timeout and make sure it
+ // succeeds.
+ CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
+ /* wait_for_ready */ false);
+}
+
+TEST_F(SingleBalancerTest, FallbackEarlyWhenBalancerCallFails) {
+ const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
+ ResetStub(kFallbackTimeoutMs);
// Return one balancer and one fallback backend.
std::vector<AddressData> balancer_addresses;
balancer_addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
std::vector<AddressData> backend_addresses;
backend_addresses.emplace_back(AddressData{backends_[0]->port_, ""});
SetNextResolution(balancer_addresses, backend_addresses);
- // Balancer drops call without sending a serverlist.
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // Send RPC with deadline less than the fallback timeout and make sure it
- // succeeds.
- CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
- /* wait_for_ready */ false);
-}
-
+ // Balancer drops call without sending a serverlist.
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // Send RPC with deadline less than the fallback timeout and make sure it
+ // succeeds.
+ CheckRpcSendOk(/* times */ 1, /* timeout_ms */ 1000,
+ /* wait_for_ready */ false);
+}
+
TEST_F(SingleBalancerTest, FallbackControlledByBalancer_BeforeFirstServerlist) {
const int kFallbackTimeoutMs = 10000 * grpc_test_slowdown_factor();
ResetStub(kFallbackTimeoutMs);
@@ -1371,29 +1371,29 @@ TEST_F(SingleBalancerTest, FallbackControlledByBalancer_AfterFirstServerlist) {
WaitForBackend(1);
}
-TEST_F(SingleBalancerTest, BackendsRestart) {
- SetNextResolutionAllBalancers();
- const size_t kNumRpcsPerAddress = 100;
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- // Make sure that trying to connect works without a call.
- channel_->GetState(true /* try_to_connect */);
- // Send kNumRpcsPerAddress RPCs per server.
- CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
- // Stop backends. RPCs should fail.
- ShutdownAllBackends();
- CheckRpcSendFailure();
- // Restart backends. RPCs should start succeeding again.
- StartAllBackends();
- CheckRpcSendOk(1 /* times */, 2000 /* timeout_ms */,
- true /* wait_for_ready */);
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-}
-
+TEST_F(SingleBalancerTest, BackendsRestart) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumRpcsPerAddress = 100;
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ // Make sure that trying to connect works without a call.
+ channel_->GetState(true /* try_to_connect */);
+ // Send kNumRpcsPerAddress RPCs per server.
+ CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
+ // Stop backends. RPCs should fail.
+ ShutdownAllBackends();
+ CheckRpcSendFailure();
+ // Restart backends. RPCs should start succeeding again.
+ StartAllBackends();
+ CheckRpcSendOk(1 /* times */, 2000 /* timeout_ms */,
+ true /* wait_for_ready */);
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+}
+
TEST_F(SingleBalancerTest, ServiceNameFromLbPolicyConfig) {
constexpr char kServiceConfigWithTarget[] =
"{\n"
@@ -1415,277 +1415,277 @@ TEST_F(SingleBalancerTest, ServiceNameFromLbPolicyConfig) {
EXPECT_EQ(balancers_[0]->service_.service_names().back(), "test_service");
}
-class UpdatesTest : public GrpclbEnd2endTest {
- public:
- UpdatesTest() : GrpclbEnd2endTest(4, 3, 0) {}
-};
-
-TEST_F(UpdatesTest, UpdateBalancersButKeepUsingOriginalBalancer) {
- SetNextResolutionAllBalancers();
- const std::vector<int> first_backend{GetBackendPorts()[0]};
- const std::vector<int> second_backend{GetBackendPorts()[1]};
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
- ScheduleResponseForBalancer(
- 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
-
- // Wait until the first backend is ready.
- WaitForBackend(0);
-
- // Send 10 requests.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
-
- // All 10 requests should have gone to the first backend.
- EXPECT_EQ(10U, backends_[0]->service_.request_count());
-
- // Balancer 0 got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- EXPECT_EQ(0U, balancers_[1]->service_.request_count());
- EXPECT_EQ(0U, balancers_[1]->service_.response_count());
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-
- std::vector<AddressData> addresses;
+class UpdatesTest : public GrpclbEnd2endTest {
+ public:
+ UpdatesTest() : GrpclbEnd2endTest(4, 3, 0) {}
+};
+
+TEST_F(UpdatesTest, UpdateBalancersButKeepUsingOriginalBalancer) {
+ SetNextResolutionAllBalancers();
+ const std::vector<int> first_backend{GetBackendPorts()[0]};
+ const std::vector<int> second_backend{GetBackendPorts()[1]};
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
+ ScheduleResponseForBalancer(
+ 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
+
+ // Wait until the first backend is ready.
+ WaitForBackend(0);
+
+ // Send 10 requests.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+
+ // All 10 requests should have gone to the first backend.
+ EXPECT_EQ(10U, backends_[0]->service_.request_count());
+
+ // Balancer 0 got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+
+ std::vector<AddressData> addresses;
addresses.emplace_back(AddressData{balancers_[1]->port_, ""});
- gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
- SetNextResolution(addresses);
- gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
-
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
- gpr_timespec deadline = gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
- // Send 10 seconds worth of RPCs
- do {
- CheckRpcSendOk();
- } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
- // The current LB call is still working, so grpclb continued using it to the
- // first balancer, which doesn't assign the second backend.
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
-
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- EXPECT_EQ(0U, balancers_[1]->service_.request_count());
- EXPECT_EQ(0U, balancers_[1]->service_.response_count());
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-}
-
-// Send an update with the same set of LBs as the one in SetUp() in order to
-// verify that the LB channel inside grpclb keeps the initial connection (which
-// by definition is also present in the update).
-TEST_F(UpdatesTest, UpdateBalancersRepeated) {
- SetNextResolutionAllBalancers();
- const std::vector<int> first_backend{GetBackendPorts()[0]};
- const std::vector<int> second_backend{GetBackendPorts()[0]};
-
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
- ScheduleResponseForBalancer(
- 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
-
- // Wait until the first backend is ready.
- WaitForBackend(0);
-
- // Send 10 requests.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
-
- // All 10 requests should have gone to the first backend.
- EXPECT_EQ(10U, backends_[0]->service_.request_count());
-
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // Balancer 0 got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- EXPECT_EQ(0U, balancers_[1]->service_.request_count());
- EXPECT_EQ(0U, balancers_[1]->service_.response_count());
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-
- std::vector<AddressData> addresses;
+ gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
+ SetNextResolution(addresses);
+ gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
+
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+ gpr_timespec deadline = gpr_time_add(
+ gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
+ // Send 10 seconds worth of RPCs
+ do {
+ CheckRpcSendOk();
+ } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
+ // The current LB call is still working, so grpclb continued using it to the
+ // first balancer, which doesn't assign the second backend.
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+}
+
+// Send an update with the same set of LBs as the one in SetUp() in order to
+// verify that the LB channel inside grpclb keeps the initial connection (which
+// by definition is also present in the update).
+TEST_F(UpdatesTest, UpdateBalancersRepeated) {
+ SetNextResolutionAllBalancers();
+ const std::vector<int> first_backend{GetBackendPorts()[0]};
+ const std::vector<int> second_backend{GetBackendPorts()[0]};
+
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
+ ScheduleResponseForBalancer(
+ 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
+
+ // Wait until the first backend is ready.
+ WaitForBackend(0);
+
+ // Send 10 requests.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+
+ // All 10 requests should have gone to the first backend.
+ EXPECT_EQ(10U, backends_[0]->service_.request_count());
+
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // Balancer 0 got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+
+ std::vector<AddressData> addresses;
addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
addresses.emplace_back(AddressData{balancers_[1]->port_, ""});
addresses.emplace_back(AddressData{balancers_[2]->port_, ""});
- gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
- SetNextResolution(addresses);
- gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
-
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
- gpr_timespec deadline = gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
- // Send 10 seconds worth of RPCs
- do {
- CheckRpcSendOk();
- } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
- // grpclb continued using the original LB call to the first balancer, which
- // doesn't assign the second backend.
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
- balancers_[0]->service_.NotifyDoneWithServerlists();
-
- addresses.clear();
+ gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
+ SetNextResolution(addresses);
+ gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
+
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+ gpr_timespec deadline = gpr_time_add(
+ gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_millis(10000, GPR_TIMESPAN));
+ // Send 10 seconds worth of RPCs
+ do {
+ CheckRpcSendOk();
+ } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
+ // grpclb continued using the original LB call to the first balancer, which
+ // doesn't assign the second backend.
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+
+ addresses.clear();
addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
addresses.emplace_back(AddressData{balancers_[1]->port_, ""});
- gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
- SetNextResolution(addresses);
- gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
-
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
- deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(10000, GPR_TIMESPAN));
- // Send 10 seconds worth of RPCs
- do {
- CheckRpcSendOk();
- } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
- // grpclb continued using the original LB call to the first balancer, which
- // doesn't assign the second backend.
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
- balancers_[0]->service_.NotifyDoneWithServerlists();
-}
-
-TEST_F(UpdatesTest, UpdateBalancersDeadUpdate) {
- std::vector<AddressData> addresses;
+ gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 2 ==========");
+ SetNextResolution(addresses);
+ gpr_log(GPR_INFO, "========= UPDATE 2 DONE ==========");
+
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+ deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_millis(10000, GPR_TIMESPAN));
+ // Send 10 seconds worth of RPCs
+ do {
+ CheckRpcSendOk();
+ } while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0);
+ // grpclb continued using the original LB call to the first balancer, which
+ // doesn't assign the second backend.
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+}
+
+TEST_F(UpdatesTest, UpdateBalancersDeadUpdate) {
+ std::vector<AddressData> addresses;
addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
- SetNextResolution(addresses);
- const std::vector<int> first_backend{GetBackendPorts()[0]};
- const std::vector<int> second_backend{GetBackendPorts()[1]};
-
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
- ScheduleResponseForBalancer(
- 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
-
- // Start servers and send 10 RPCs per server.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
- // All 10 requests should have gone to the first backend.
- EXPECT_EQ(10U, backends_[0]->service_.request_count());
-
- // Kill balancer 0
- gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
- balancers_[0]->Shutdown();
- gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
-
- // This is serviced by the existing RR policy
- gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
- // All 10 requests should again have gone to the first backend.
- EXPECT_EQ(20U, backends_[0]->service_.request_count());
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
-
- // Balancer 0 got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- EXPECT_EQ(0U, balancers_[1]->service_.request_count());
- EXPECT_EQ(0U, balancers_[1]->service_.response_count());
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-
- addresses.clear();
+ SetNextResolution(addresses);
+ const std::vector<int> first_backend{GetBackendPorts()[0]};
+ const std::vector<int> second_backend{GetBackendPorts()[1]};
+
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(first_backend, {}), 0);
+ ScheduleResponseForBalancer(
+ 1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
+
+ // Start servers and send 10 RPCs per server.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+ // All 10 requests should have gone to the first backend.
+ EXPECT_EQ(10U, backends_[0]->service_.request_count());
+
+ // Kill balancer 0
+ gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
+ balancers_[0]->Shutdown();
+ gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
+
+ // This is serviced by the existing RR policy
+ gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
+ // All 10 requests should again have gone to the first backend.
+ EXPECT_EQ(20U, backends_[0]->service_.request_count());
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+
+ // Balancer 0 got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+
+ addresses.clear();
addresses.emplace_back(AddressData{balancers_[1]->port_, ""});
- gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
- SetNextResolution(addresses);
- gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
-
- // Wait until update has been processed, as signaled by the second backend
- // receiving a request. In the meantime, the client continues to be serviced
- // (by the first backend) without interruption.
- EXPECT_EQ(0U, backends_[1]->service_.request_count());
- WaitForBackend(1);
-
- // This is serviced by the updated RR policy
- backends_[1]->service_.ResetCounters();
- gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
- // All 10 requests should have gone to the second backend.
- EXPECT_EQ(10U, backends_[1]->service_.request_count());
-
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- // The second balancer, published as part of the first update, may end up
- // getting two requests (that is, 1 <= #req <= 2) if the LB call retry timer
- // firing races with the arrival of the update containing the second
- // balancer.
- EXPECT_GE(balancers_[1]->service_.request_count(), 1U);
- EXPECT_GE(balancers_[1]->service_.response_count(), 1U);
- EXPECT_LE(balancers_[1]->service_.request_count(), 2U);
- EXPECT_LE(balancers_[1]->service_.response_count(), 2U);
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-}
-
-TEST_F(UpdatesTest, ReresolveDeadBackend) {
- ResetStub(500);
- // The first resolution contains the addresses of a balancer that never
- // responds, and a fallback backend.
+ gpr_log(GPR_INFO, "========= ABOUT TO UPDATE 1 ==========");
+ SetNextResolution(addresses);
+ gpr_log(GPR_INFO, "========= UPDATE 1 DONE ==========");
+
+ // Wait until update has been processed, as signaled by the second backend
+ // receiving a request. In the meantime, the client continues to be serviced
+ // (by the first backend) without interruption.
+ EXPECT_EQ(0U, backends_[1]->service_.request_count());
+ WaitForBackend(1);
+
+ // This is serviced by the updated RR policy
+ backends_[1]->service_.ResetCounters();
+ gpr_log(GPR_INFO, "========= BEFORE THIRD BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH THIRD BATCH ==========");
+ // All 10 requests should have gone to the second backend.
+ EXPECT_EQ(10U, backends_[1]->service_.request_count());
+
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ // The second balancer, published as part of the first update, may end up
+ // getting two requests (that is, 1 <= #req <= 2) if the LB call retry timer
+ // firing races with the arrival of the update containing the second
+ // balancer.
+ EXPECT_GE(balancers_[1]->service_.request_count(), 1U);
+ EXPECT_GE(balancers_[1]->service_.response_count(), 1U);
+ EXPECT_LE(balancers_[1]->service_.request_count(), 2U);
+ EXPECT_LE(balancers_[1]->service_.response_count(), 2U);
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+}
+
+TEST_F(UpdatesTest, ReresolveDeadBackend) {
+ ResetStub(500);
+ // The first resolution contains the addresses of a balancer that never
+ // responds, and a fallback backend.
std::vector<AddressData> balancer_addresses;
balancer_addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
std::vector<AddressData> backend_addresses;
backend_addresses.emplace_back(AddressData{backends_[0]->port_, ""});
SetNextResolution(balancer_addresses, backend_addresses);
- // Ask channel to connect to trigger resolver creation.
- channel_->GetState(true);
- // The re-resolution result will contain the addresses of the same balancer
- // and a new fallback backend.
+ // Ask channel to connect to trigger resolver creation.
+ channel_->GetState(true);
+ // The re-resolution result will contain the addresses of the same balancer
+ // and a new fallback backend.
balancer_addresses.clear();
balancer_addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
backend_addresses.clear();
backend_addresses.emplace_back(AddressData{backends_[1]->port_, ""});
SetNextReresolutionResponse(balancer_addresses, backend_addresses);
-
- // Start servers and send 10 RPCs per server.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
- // All 10 requests should have gone to the fallback backend.
- EXPECT_EQ(10U, backends_[0]->service_.request_count());
-
- // Kill backend 0.
- gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
- backends_[0]->Shutdown();
- gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
-
- // Wait until re-resolution has finished, as signaled by the second backend
- // receiving a request.
- WaitForBackend(1);
-
- gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
- // All 10 requests should have gone to the second backend.
- EXPECT_EQ(10U, backends_[1]->service_.request_count());
-
- balancers_[0]->service_.NotifyDoneWithServerlists();
- balancers_[1]->service_.NotifyDoneWithServerlists();
- balancers_[2]->service_.NotifyDoneWithServerlists();
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- EXPECT_EQ(0U, balancers_[0]->service_.response_count());
- EXPECT_EQ(0U, balancers_[1]->service_.request_count());
- EXPECT_EQ(0U, balancers_[1]->service_.response_count());
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-}
-
-// TODO(juanlishen): Should be removed when the first response is always the
-// initial response. Currently, if client load reporting is not enabled, the
-// balancer doesn't send initial response. When the backend shuts down, an
-// unexpected re-resolution will happen. This test configuration is a workaround
-// for test ReresolveDeadBalancer.
-class UpdatesWithClientLoadReportingTest : public GrpclbEnd2endTest {
- public:
- UpdatesWithClientLoadReportingTest() : GrpclbEnd2endTest(4, 3, 2) {}
-};
-
-TEST_F(UpdatesWithClientLoadReportingTest, ReresolveDeadBalancer) {
+
+ // Start servers and send 10 RPCs per server.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+ // All 10 requests should have gone to the fallback backend.
+ EXPECT_EQ(10U, backends_[0]->service_.request_count());
+
+ // Kill backend 0.
+ gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
+ backends_[0]->Shutdown();
+ gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
+
+ // Wait until re-resolution has finished, as signaled by the second backend
+ // receiving a request.
+ WaitForBackend(1);
+
+ gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
+ // All 10 requests should have gone to the second backend.
+ EXPECT_EQ(10U, backends_[1]->service_.request_count());
+
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ balancers_[1]->service_.NotifyDoneWithServerlists();
+ balancers_[2]->service_.NotifyDoneWithServerlists();
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[0]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+}
+
+// TODO(juanlishen): Should be removed when the first response is always the
+// initial response. Currently, if client load reporting is not enabled, the
+// balancer doesn't send initial response. When the backend shuts down, an
+// unexpected re-resolution will happen. This test configuration is a workaround
+// for test ReresolveDeadBalancer.
+class UpdatesWithClientLoadReportingTest : public GrpclbEnd2endTest {
+ public:
+ UpdatesWithClientLoadReportingTest() : GrpclbEnd2endTest(4, 3, 2) {}
+};
+
+TEST_F(UpdatesWithClientLoadReportingTest, ReresolveDeadBalancer) {
const std::vector<int> first_backend{GetBackendPorts()[0]};
const std::vector<int> second_backend{GetBackendPorts()[1]};
ScheduleResponseForBalancer(
@@ -1693,337 +1693,337 @@ TEST_F(UpdatesWithClientLoadReportingTest, ReresolveDeadBalancer) {
ScheduleResponseForBalancer(
1, BalancerServiceImpl::BuildResponseForBackends(second_backend, {}), 0);
- // Ask channel to connect to trigger resolver creation.
- channel_->GetState(true);
- std::vector<AddressData> addresses;
+ // Ask channel to connect to trigger resolver creation.
+ channel_->GetState(true);
+ std::vector<AddressData> addresses;
addresses.emplace_back(AddressData{balancers_[0]->port_, ""});
- SetNextResolution(addresses);
- addresses.clear();
+ SetNextResolution(addresses);
+ addresses.clear();
addresses.emplace_back(AddressData{balancers_[1]->port_, ""});
- SetNextReresolutionResponse(addresses);
-
- // Start servers and send 10 RPCs per server.
- gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
- // All 10 requests should have gone to the first backend.
- EXPECT_EQ(10U, backends_[0]->service_.request_count());
-
- // Kill backend 0.
- gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
- backends_[0]->Shutdown();
- gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
-
- CheckRpcSendFailure();
-
- // Balancer 0 got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- EXPECT_EQ(0U, balancers_[1]->service_.request_count());
- EXPECT_EQ(0U, balancers_[1]->service_.response_count());
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-
- // Kill balancer 0.
- gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
- balancers_[0]->Shutdown();
- gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
-
- // Wait until re-resolution has finished, as signaled by the second backend
- // receiving a request.
- WaitForBackend(1);
-
- // This is serviced by the new serverlist.
- gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
- CheckRpcSendOk(10);
- gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
- // All 10 requests should have gone to the second backend.
- EXPECT_EQ(10U, backends_[1]->service_.request_count());
-
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
- // After balancer 0 is killed, we restart an LB call immediately (because we
- // disconnect to a previously connected balancer). Although we will cancel
- // this call when the re-resolution update is done and another LB call restart
- // is needed, this old call may still succeed reaching the LB server if
- // re-resolution is slow. So balancer 1 may have received 2 requests and sent
- // 2 responses.
- EXPECT_GE(balancers_[1]->service_.request_count(), 1U);
- EXPECT_GE(balancers_[1]->service_.response_count(), 1U);
- EXPECT_LE(balancers_[1]->service_.request_count(), 2U);
- EXPECT_LE(balancers_[1]->service_.response_count(), 2U);
- EXPECT_EQ(0U, balancers_[2]->service_.request_count());
- EXPECT_EQ(0U, balancers_[2]->service_.response_count());
-}
-
-TEST_F(SingleBalancerTest, Drop) {
- SetNextResolutionAllBalancers();
- const size_t kNumRpcsPerAddress = 100;
- const int num_of_drop_by_rate_limiting_addresses = 1;
- const int num_of_drop_by_load_balancing_addresses = 2;
- const int num_of_drop_addresses = num_of_drop_by_rate_limiting_addresses +
- num_of_drop_by_load_balancing_addresses;
- const int num_total_addresses = num_backends_ + num_of_drop_addresses;
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(),
- {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
- {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
- 0);
- // Wait until all backends are ready.
- WaitForAllBackends();
- // Send kNumRpcsPerAddress RPCs for each server and drop address.
- size_t num_drops = 0;
- for (size_t i = 0; i < kNumRpcsPerAddress * num_total_addresses; ++i) {
- EchoResponse response;
- const Status status = SendRpc(&response);
- if (!status.ok() &&
- status.error_message() == "Call dropped by load balancing policy") {
- ++num_drops;
- } else {
- EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
- << " message=" << status.error_message();
- EXPECT_EQ(response.message(), kRequestMessage_);
- }
- }
- EXPECT_EQ(kNumRpcsPerAddress * num_of_drop_addresses, num_drops);
- // Each backend should have gotten 100 requests.
- for (size_t i = 0; i < backends_.size(); ++i) {
- EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
- }
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-}
-
-TEST_F(SingleBalancerTest, DropAllFirst) {
- SetNextResolutionAllBalancers();
- // All registered addresses are marked as "drop".
- const int num_of_drop_by_rate_limiting_addresses = 1;
- const int num_of_drop_by_load_balancing_addresses = 1;
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- {}, {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
- {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
- 0);
- const Status status = SendRpc(nullptr, 1000, true);
- EXPECT_FALSE(status.ok());
- EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
-}
-
-TEST_F(SingleBalancerTest, DropAll) {
- SetNextResolutionAllBalancers();
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- const int num_of_drop_by_rate_limiting_addresses = 1;
- const int num_of_drop_by_load_balancing_addresses = 1;
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- {}, {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
- {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
- 1000);
-
- // First call succeeds.
- CheckRpcSendOk();
- // But eventually, the update with only dropped servers is processed and calls
- // fail.
- Status status;
- do {
- status = SendRpc(nullptr, 1000, true);
- } while (status.ok());
- EXPECT_FALSE(status.ok());
- EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
-}
-
-class SingleBalancerWithClientLoadReportingTest : public GrpclbEnd2endTest {
- public:
- SingleBalancerWithClientLoadReportingTest() : GrpclbEnd2endTest(4, 1, 3) {}
-};
-
-TEST_F(SingleBalancerWithClientLoadReportingTest, Vanilla) {
- SetNextResolutionAllBalancers();
- const size_t kNumRpcsPerAddress = 100;
- ScheduleResponseForBalancer(
- 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
- 0);
- // Wait until all backends are ready.
- int num_ok = 0;
- int num_failure = 0;
- int num_drops = 0;
- std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
- // Send kNumRpcsPerAddress RPCs per server.
- CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
- // Each backend should have gotten 100 requests.
- for (size_t i = 0; i < backends_.size(); ++i) {
- EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
- }
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-
+ SetNextReresolutionResponse(addresses);
+
+ // Start servers and send 10 RPCs per server.
+ gpr_log(GPR_INFO, "========= BEFORE FIRST BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH FIRST BATCH ==========");
+ // All 10 requests should have gone to the first backend.
+ EXPECT_EQ(10U, backends_[0]->service_.request_count());
+
+ // Kill backend 0.
+ gpr_log(GPR_INFO, "********** ABOUT TO KILL BACKEND 0 *************");
+ backends_[0]->Shutdown();
+ gpr_log(GPR_INFO, "********** KILLED BACKEND 0 *************");
+
+ CheckRpcSendFailure();
+
+ // Balancer 0 got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[1]->service_.response_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+
+ // Kill balancer 0.
+ gpr_log(GPR_INFO, "********** ABOUT TO KILL BALANCER 0 *************");
+ balancers_[0]->Shutdown();
+ gpr_log(GPR_INFO, "********** KILLED BALANCER 0 *************");
+
+ // Wait until re-resolution has finished, as signaled by the second backend
+ // receiving a request.
+ WaitForBackend(1);
+
+ // This is serviced by the new serverlist.
+ gpr_log(GPR_INFO, "========= BEFORE SECOND BATCH ==========");
+ CheckRpcSendOk(10);
+ gpr_log(GPR_INFO, "========= DONE WITH SECOND BATCH ==========");
+ // All 10 requests should have gone to the second backend.
+ EXPECT_EQ(10U, backends_[1]->service_.request_count());
+
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+ // After balancer 0 is killed, we restart an LB call immediately (because we
+ // disconnect to a previously connected balancer). Although we will cancel
+ // this call when the re-resolution update is done and another LB call restart
+ // is needed, this old call may still succeed reaching the LB server if
+ // re-resolution is slow. So balancer 1 may have received 2 requests and sent
+ // 2 responses.
+ EXPECT_GE(balancers_[1]->service_.request_count(), 1U);
+ EXPECT_GE(balancers_[1]->service_.response_count(), 1U);
+ EXPECT_LE(balancers_[1]->service_.request_count(), 2U);
+ EXPECT_LE(balancers_[1]->service_.response_count(), 2U);
+ EXPECT_EQ(0U, balancers_[2]->service_.request_count());
+ EXPECT_EQ(0U, balancers_[2]->service_.response_count());
+}
+
+TEST_F(SingleBalancerTest, Drop) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumRpcsPerAddress = 100;
+ const int num_of_drop_by_rate_limiting_addresses = 1;
+ const int num_of_drop_by_load_balancing_addresses = 2;
+ const int num_of_drop_addresses = num_of_drop_by_rate_limiting_addresses +
+ num_of_drop_by_load_balancing_addresses;
+ const int num_total_addresses = num_backends_ + num_of_drop_addresses;
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(),
+ {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
+ {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
+ 0);
+ // Wait until all backends are ready.
+ WaitForAllBackends();
+ // Send kNumRpcsPerAddress RPCs for each server and drop address.
+ size_t num_drops = 0;
+ for (size_t i = 0; i < kNumRpcsPerAddress * num_total_addresses; ++i) {
+ EchoResponse response;
+ const Status status = SendRpc(&response);
+ if (!status.ok() &&
+ status.error_message() == "Call dropped by load balancing policy") {
+ ++num_drops;
+ } else {
+ EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
+ << " message=" << status.error_message();
+ EXPECT_EQ(response.message(), kRequestMessage_);
+ }
+ }
+ EXPECT_EQ(kNumRpcsPerAddress * num_of_drop_addresses, num_drops);
+ // Each backend should have gotten 100 requests.
+ for (size_t i = 0; i < backends_.size(); ++i) {
+ EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
+ }
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+}
+
+TEST_F(SingleBalancerTest, DropAllFirst) {
+ SetNextResolutionAllBalancers();
+ // All registered addresses are marked as "drop".
+ const int num_of_drop_by_rate_limiting_addresses = 1;
+ const int num_of_drop_by_load_balancing_addresses = 1;
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ {}, {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
+ {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
+ 0);
+ const Status status = SendRpc(nullptr, 1000, true);
+ EXPECT_FALSE(status.ok());
+ EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
+}
+
+TEST_F(SingleBalancerTest, DropAll) {
+ SetNextResolutionAllBalancers();
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ const int num_of_drop_by_rate_limiting_addresses = 1;
+ const int num_of_drop_by_load_balancing_addresses = 1;
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ {}, {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
+ {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
+ 1000);
+
+ // First call succeeds.
+ CheckRpcSendOk();
+ // But eventually, the update with only dropped servers is processed and calls
+ // fail.
+ Status status;
+ do {
+ status = SendRpc(nullptr, 1000, true);
+ } while (status.ok());
+ EXPECT_FALSE(status.ok());
+ EXPECT_EQ(status.error_message(), "Call dropped by load balancing policy");
+}
+
+class SingleBalancerWithClientLoadReportingTest : public GrpclbEnd2endTest {
+ public:
+ SingleBalancerWithClientLoadReportingTest() : GrpclbEnd2endTest(4, 1, 3) {}
+};
+
+TEST_F(SingleBalancerWithClientLoadReportingTest, Vanilla) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumRpcsPerAddress = 100;
+ ScheduleResponseForBalancer(
+ 0, BalancerServiceImpl::BuildResponseForBackends(GetBackendPorts(), {}),
+ 0);
+ // Wait until all backends are ready.
+ int num_ok = 0;
+ int num_failure = 0;
+ int num_drops = 0;
+ std::tie(num_ok, num_failure, num_drops) = WaitForAllBackends();
+ // Send kNumRpcsPerAddress RPCs per server.
+ CheckRpcSendOk(kNumRpcsPerAddress * num_backends_);
+ // Each backend should have gotten 100 requests.
+ for (size_t i = 0; i < backends_.size(); ++i) {
+ EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
+ }
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+
ClientStats client_stats;
do {
client_stats += WaitForLoadReports();
} while (client_stats.num_calls_finished !=
kNumRpcsPerAddress * num_backends_ + num_ok);
- EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
- client_stats.num_calls_started);
- EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
- client_stats.num_calls_finished);
- EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
- EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + (num_ok + num_drops),
- client_stats.num_calls_finished_known_received);
- EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
-}
-
-TEST_F(SingleBalancerWithClientLoadReportingTest, BalancerRestart) {
- SetNextResolutionAllBalancers();
- const size_t kNumBackendsFirstPass = 2;
- const size_t kNumBackendsSecondPass =
- backends_.size() - kNumBackendsFirstPass;
- // Balancer returns backends starting at index 1.
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(0, kNumBackendsFirstPass), {}),
- 0);
- // Wait until all backends returned by the balancer are ready.
- int num_ok = 0;
- int num_failure = 0;
- int num_drops = 0;
- std::tie(num_ok, num_failure, num_drops) =
- WaitForAllBackends(/* num_requests_multiple_of */ 1, /* start_index */ 0,
- /* stop_index */ kNumBackendsFirstPass);
- balancers_[0]->service_.NotifyDoneWithServerlists();
- ClientStats client_stats = WaitForLoadReports();
- EXPECT_EQ(static_cast<size_t>(num_ok), client_stats.num_calls_started);
- EXPECT_EQ(static_cast<size_t>(num_ok), client_stats.num_calls_finished);
- EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
- EXPECT_EQ(static_cast<size_t>(num_ok),
- client_stats.num_calls_finished_known_received);
- EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
- // Shut down the balancer.
- balancers_[0]->Shutdown();
- // Send 10 more requests per backend. This will continue using the
- // last serverlist we received from the balancer before it was shut down.
- ResetBackendCounters();
- CheckRpcSendOk(kNumBackendsFirstPass);
- // Each backend should have gotten 1 request.
- for (size_t i = 0; i < kNumBackendsFirstPass; ++i) {
- EXPECT_EQ(1UL, backends_[i]->service_.request_count());
- }
- // Now restart the balancer, this time pointing to all backends.
- balancers_[0]->Start(server_host_);
- ScheduleResponseForBalancer(0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(kNumBackendsFirstPass), {}),
- 0);
- // Wait for queries to start going to one of the new backends.
- // This tells us that we're now using the new serverlist.
- do {
- CheckRpcSendOk();
- } while (backends_[2]->service_.request_count() == 0 &&
- backends_[3]->service_.request_count() == 0);
- // Send one RPC per backend.
- CheckRpcSendOk(kNumBackendsSecondPass);
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // Check client stats.
- client_stats = WaitForLoadReports();
- EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats.num_calls_started);
- EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats.num_calls_finished);
- EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
- EXPECT_EQ(kNumBackendsSecondPass + 1,
- client_stats.num_calls_finished_known_received);
- EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
-}
-
-TEST_F(SingleBalancerWithClientLoadReportingTest, Drop) {
- SetNextResolutionAllBalancers();
- const size_t kNumRpcsPerAddress = 3;
- const int num_of_drop_by_rate_limiting_addresses = 2;
- const int num_of_drop_by_load_balancing_addresses = 1;
- const int num_of_drop_addresses = num_of_drop_by_rate_limiting_addresses +
- num_of_drop_by_load_balancing_addresses;
- const int num_total_addresses = num_backends_ + num_of_drop_addresses;
- ScheduleResponseForBalancer(
- 0,
- BalancerServiceImpl::BuildResponseForBackends(
- GetBackendPorts(),
- {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
- {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
- 0);
- // Wait until all backends are ready.
- int num_warmup_ok = 0;
- int num_warmup_failure = 0;
- int num_warmup_drops = 0;
- std::tie(num_warmup_ok, num_warmup_failure, num_warmup_drops) =
- WaitForAllBackends(num_total_addresses /* num_requests_multiple_of */);
- const int num_total_warmup_requests =
- num_warmup_ok + num_warmup_failure + num_warmup_drops;
- size_t num_drops = 0;
- for (size_t i = 0; i < kNumRpcsPerAddress * num_total_addresses; ++i) {
- EchoResponse response;
- const Status status = SendRpc(&response);
- if (!status.ok() &&
- status.error_message() == "Call dropped by load balancing policy") {
- ++num_drops;
- } else {
- EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
- << " message=" << status.error_message();
- EXPECT_EQ(response.message(), kRequestMessage_);
- }
- }
- EXPECT_EQ(kNumRpcsPerAddress * num_of_drop_addresses, num_drops);
- // Each backend should have gotten 100 requests.
- for (size_t i = 0; i < backends_.size(); ++i) {
- EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
- }
- balancers_[0]->service_.NotifyDoneWithServerlists();
- // The balancer got a single request.
- EXPECT_EQ(1U, balancers_[0]->service_.request_count());
- // and sent a single response.
- EXPECT_EQ(1U, balancers_[0]->service_.response_count());
-
- const ClientStats client_stats = WaitForLoadReports();
- EXPECT_EQ(
- kNumRpcsPerAddress * num_total_addresses + num_total_warmup_requests,
- client_stats.num_calls_started);
- EXPECT_EQ(
- kNumRpcsPerAddress * num_total_addresses + num_total_warmup_requests,
- client_stats.num_calls_finished);
- EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
- EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_warmup_ok,
- client_stats.num_calls_finished_known_received);
- // The number of warmup request is a multiple of the number of addresses.
- // Therefore, all addresses in the scheduled balancer response are hit the
- // same number of times.
- const int num_times_drop_addresses_hit =
- num_warmup_drops / num_of_drop_addresses;
- EXPECT_THAT(
- client_stats.drop_token_counts,
- ::testing::ElementsAre(
- ::testing::Pair("load_balancing",
- (kNumRpcsPerAddress + num_times_drop_addresses_hit)),
- ::testing::Pair(
- "rate_limiting",
- (kNumRpcsPerAddress + num_times_drop_addresses_hit) * 2)));
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- const auto result = RUN_ALL_TESTS();
- return result;
-}
+ EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
+ client_stats.num_calls_started);
+ EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_ok,
+ client_stats.num_calls_finished);
+ EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
+ EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + (num_ok + num_drops),
+ client_stats.num_calls_finished_known_received);
+ EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
+}
+
+TEST_F(SingleBalancerWithClientLoadReportingTest, BalancerRestart) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumBackendsFirstPass = 2;
+ const size_t kNumBackendsSecondPass =
+ backends_.size() - kNumBackendsFirstPass;
+ // Balancer returns backends starting at index 1.
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(0, kNumBackendsFirstPass), {}),
+ 0);
+ // Wait until all backends returned by the balancer are ready.
+ int num_ok = 0;
+ int num_failure = 0;
+ int num_drops = 0;
+ std::tie(num_ok, num_failure, num_drops) =
+ WaitForAllBackends(/* num_requests_multiple_of */ 1, /* start_index */ 0,
+ /* stop_index */ kNumBackendsFirstPass);
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ ClientStats client_stats = WaitForLoadReports();
+ EXPECT_EQ(static_cast<size_t>(num_ok), client_stats.num_calls_started);
+ EXPECT_EQ(static_cast<size_t>(num_ok), client_stats.num_calls_finished);
+ EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
+ EXPECT_EQ(static_cast<size_t>(num_ok),
+ client_stats.num_calls_finished_known_received);
+ EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
+ // Shut down the balancer.
+ balancers_[0]->Shutdown();
+ // Send 10 more requests per backend. This will continue using the
+ // last serverlist we received from the balancer before it was shut down.
+ ResetBackendCounters();
+ CheckRpcSendOk(kNumBackendsFirstPass);
+ // Each backend should have gotten 1 request.
+ for (size_t i = 0; i < kNumBackendsFirstPass; ++i) {
+ EXPECT_EQ(1UL, backends_[i]->service_.request_count());
+ }
+ // Now restart the balancer, this time pointing to all backends.
+ balancers_[0]->Start(server_host_);
+ ScheduleResponseForBalancer(0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(kNumBackendsFirstPass), {}),
+ 0);
+ // Wait for queries to start going to one of the new backends.
+ // This tells us that we're now using the new serverlist.
+ do {
+ CheckRpcSendOk();
+ } while (backends_[2]->service_.request_count() == 0 &&
+ backends_[3]->service_.request_count() == 0);
+ // Send one RPC per backend.
+ CheckRpcSendOk(kNumBackendsSecondPass);
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // Check client stats.
+ client_stats = WaitForLoadReports();
+ EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats.num_calls_started);
+ EXPECT_EQ(kNumBackendsSecondPass + 1, client_stats.num_calls_finished);
+ EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
+ EXPECT_EQ(kNumBackendsSecondPass + 1,
+ client_stats.num_calls_finished_known_received);
+ EXPECT_THAT(client_stats.drop_token_counts, ::testing::ElementsAre());
+}
+
+TEST_F(SingleBalancerWithClientLoadReportingTest, Drop) {
+ SetNextResolutionAllBalancers();
+ const size_t kNumRpcsPerAddress = 3;
+ const int num_of_drop_by_rate_limiting_addresses = 2;
+ const int num_of_drop_by_load_balancing_addresses = 1;
+ const int num_of_drop_addresses = num_of_drop_by_rate_limiting_addresses +
+ num_of_drop_by_load_balancing_addresses;
+ const int num_total_addresses = num_backends_ + num_of_drop_addresses;
+ ScheduleResponseForBalancer(
+ 0,
+ BalancerServiceImpl::BuildResponseForBackends(
+ GetBackendPorts(),
+ {{"rate_limiting", num_of_drop_by_rate_limiting_addresses},
+ {"load_balancing", num_of_drop_by_load_balancing_addresses}}),
+ 0);
+ // Wait until all backends are ready.
+ int num_warmup_ok = 0;
+ int num_warmup_failure = 0;
+ int num_warmup_drops = 0;
+ std::tie(num_warmup_ok, num_warmup_failure, num_warmup_drops) =
+ WaitForAllBackends(num_total_addresses /* num_requests_multiple_of */);
+ const int num_total_warmup_requests =
+ num_warmup_ok + num_warmup_failure + num_warmup_drops;
+ size_t num_drops = 0;
+ for (size_t i = 0; i < kNumRpcsPerAddress * num_total_addresses; ++i) {
+ EchoResponse response;
+ const Status status = SendRpc(&response);
+ if (!status.ok() &&
+ status.error_message() == "Call dropped by load balancing policy") {
+ ++num_drops;
+ } else {
+ EXPECT_TRUE(status.ok()) << "code=" << status.error_code()
+ << " message=" << status.error_message();
+ EXPECT_EQ(response.message(), kRequestMessage_);
+ }
+ }
+ EXPECT_EQ(kNumRpcsPerAddress * num_of_drop_addresses, num_drops);
+ // Each backend should have gotten 100 requests.
+ for (size_t i = 0; i < backends_.size(); ++i) {
+ EXPECT_EQ(kNumRpcsPerAddress, backends_[i]->service_.request_count());
+ }
+ balancers_[0]->service_.NotifyDoneWithServerlists();
+ // The balancer got a single request.
+ EXPECT_EQ(1U, balancers_[0]->service_.request_count());
+ // and sent a single response.
+ EXPECT_EQ(1U, balancers_[0]->service_.response_count());
+
+ const ClientStats client_stats = WaitForLoadReports();
+ EXPECT_EQ(
+ kNumRpcsPerAddress * num_total_addresses + num_total_warmup_requests,
+ client_stats.num_calls_started);
+ EXPECT_EQ(
+ kNumRpcsPerAddress * num_total_addresses + num_total_warmup_requests,
+ client_stats.num_calls_finished);
+ EXPECT_EQ(0U, client_stats.num_calls_finished_with_client_failed_to_send);
+ EXPECT_EQ(kNumRpcsPerAddress * num_backends_ + num_warmup_ok,
+ client_stats.num_calls_finished_known_received);
+ // The number of warmup request is a multiple of the number of addresses.
+ // Therefore, all addresses in the scheduled balancer response are hit the
+ // same number of times.
+ const int num_times_drop_addresses_hit =
+ num_warmup_drops / num_of_drop_addresses;
+ EXPECT_THAT(
+ client_stats.drop_token_counts,
+ ::testing::ElementsAre(
+ ::testing::Pair("load_balancing",
+ (kNumRpcsPerAddress + num_times_drop_addresses_hit)),
+ ::testing::Pair(
+ "rate_limiting",
+ (kNumRpcsPerAddress + num_times_drop_addresses_hit) * 2)));
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ const auto result = RUN_ALL_TESTS();
+ return result;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/health/ya.make b/contrib/libs/grpc/test/cpp/end2end/health/ya.make
index 7330129b73..0eda6bab65 100644
--- a/contrib/libs/grpc/test/cpp/end2end/health/ya.make
+++ b/contrib/libs/grpc/test/cpp/end2end/health/ya.make
@@ -1,33 +1,33 @@
GTEST_UGLY()
-
-OWNER(
- dvshkurko
- g:ymake
-)
-
-ADDINCL(
+
+OWNER(
+ dvshkurko
+ g:ymake
+)
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/health/v1
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- health_service_end2end_test.cc
-)
-
-END()
+ ${ARCADIA_ROOT}/contrib/libs/grpc
+)
+
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/health/v1
+ contrib/libs/grpc/src/proto/grpc/core
+ contrib/libs/grpc/src/proto/grpc/testing
+ contrib/libs/grpc/src/proto/grpc/testing/duplicate
+ contrib/libs/grpc/test/core/util
+ contrib/libs/grpc/test/cpp/end2end
+ contrib/libs/grpc/test/cpp/util
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(
+ contrib/libs/grpc/test/cpp/end2end
+)
+
+SRCS(
+ health_service_end2end_test.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
index 516b3a4c81..628917274b 100644
--- a/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
@@ -1,374 +1,374 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <memory>
-#include <mutex>
-#include <thread>
-#include <vector>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/ext/health_check_service_server_builder_option.h>
-#include <grpcpp/health_check_service_interface.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_health_check_service_impl.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <gtest/gtest.h>
-
-using grpc::health::v1::Health;
-using grpc::health::v1::HealthCheckRequest;
-using grpc::health::v1::HealthCheckResponse;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-// A custom implementation of the health checking service interface. This is
-// used to test that it prevents the server from creating a default service and
-// also serves as an example of how to override the default service.
-class CustomHealthCheckService : public HealthCheckServiceInterface {
- public:
- explicit CustomHealthCheckService(HealthCheckServiceImpl* impl)
- : impl_(impl) {
- impl_->SetStatus("", HealthCheckResponse::SERVING);
- }
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <memory>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/ext/health_check_service_server_builder_option.h>
+#include <grpcpp/health_check_service_interface.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/health/v1/health.grpc.pb.h"
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_health_check_service_impl.h"
+#include "test/cpp/end2end/test_service_impl.h"
+
+#include <gtest/gtest.h>
+
+using grpc::health::v1::Health;
+using grpc::health::v1::HealthCheckRequest;
+using grpc::health::v1::HealthCheckResponse;
+
+namespace grpc {
+namespace testing {
+namespace {
+
+// A custom implementation of the health checking service interface. This is
+// used to test that it prevents the server from creating a default service and
+// also serves as an example of how to override the default service.
+class CustomHealthCheckService : public HealthCheckServiceInterface {
+ public:
+ explicit CustomHealthCheckService(HealthCheckServiceImpl* impl)
+ : impl_(impl) {
+ impl_->SetStatus("", HealthCheckResponse::SERVING);
+ }
void SetServingStatus(const TString& service_name,
- bool serving) override {
- impl_->SetStatus(service_name, serving ? HealthCheckResponse::SERVING
- : HealthCheckResponse::NOT_SERVING);
- }
-
- void SetServingStatus(bool serving) override {
- impl_->SetAll(serving ? HealthCheckResponse::SERVING
- : HealthCheckResponse::NOT_SERVING);
- }
-
- void Shutdown() override { impl_->Shutdown(); }
-
- private:
- HealthCheckServiceImpl* impl_; // not owned
-};
-
-class HealthServiceEnd2endTest : public ::testing::Test {
- protected:
- HealthServiceEnd2endTest() {}
-
- void SetUpServer(bool register_sync_test_service, bool add_async_cq,
- bool explicit_health_service,
- std::unique_ptr<HealthCheckServiceInterface> service) {
- int port = 5001; // grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port;
-
- bool register_sync_health_service_impl =
- explicit_health_service && service != nullptr;
-
- // Setup server
- ServerBuilder builder;
- if (explicit_health_service) {
- std::unique_ptr<ServerBuilderOption> option(
- new HealthCheckServiceServerBuilderOption(std::move(service)));
- builder.SetOption(std::move(option));
- }
- builder.AddListeningPort(server_address_.str(),
- grpc::InsecureServerCredentials());
- if (register_sync_test_service) {
- // Register a sync service.
- builder.RegisterService(&echo_test_service_);
- }
- if (register_sync_health_service_impl) {
- builder.RegisterService(&health_check_service_impl_);
- }
- if (add_async_cq) {
- cq_ = builder.AddCompletionQueue();
- }
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override {
- if (server_) {
- server_->Shutdown();
- if (cq_ != nullptr) {
- cq_->Shutdown();
- }
- if (cq_thread_.joinable()) {
- cq_thread_.join();
- }
- }
- }
-
- void ResetStubs() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- hc_stub_ = grpc::health::v1::Health::NewStub(channel);
- }
-
- // When the expected_status is NOT OK, we do not care about the response.
+ bool serving) override {
+ impl_->SetStatus(service_name, serving ? HealthCheckResponse::SERVING
+ : HealthCheckResponse::NOT_SERVING);
+ }
+
+ void SetServingStatus(bool serving) override {
+ impl_->SetAll(serving ? HealthCheckResponse::SERVING
+ : HealthCheckResponse::NOT_SERVING);
+ }
+
+ void Shutdown() override { impl_->Shutdown(); }
+
+ private:
+ HealthCheckServiceImpl* impl_; // not owned
+};
+
+class HealthServiceEnd2endTest : public ::testing::Test {
+ protected:
+ HealthServiceEnd2endTest() {}
+
+ void SetUpServer(bool register_sync_test_service, bool add_async_cq,
+ bool explicit_health_service,
+ std::unique_ptr<HealthCheckServiceInterface> service) {
+ int port = 5001; // grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port;
+
+ bool register_sync_health_service_impl =
+ explicit_health_service && service != nullptr;
+
+ // Setup server
+ ServerBuilder builder;
+ if (explicit_health_service) {
+ std::unique_ptr<ServerBuilderOption> option(
+ new HealthCheckServiceServerBuilderOption(std::move(service)));
+ builder.SetOption(std::move(option));
+ }
+ builder.AddListeningPort(server_address_.str(),
+ grpc::InsecureServerCredentials());
+ if (register_sync_test_service) {
+ // Register a sync service.
+ builder.RegisterService(&echo_test_service_);
+ }
+ if (register_sync_health_service_impl) {
+ builder.RegisterService(&health_check_service_impl_);
+ }
+ if (add_async_cq) {
+ cq_ = builder.AddCompletionQueue();
+ }
+ server_ = builder.BuildAndStart();
+ }
+
+ void TearDown() override {
+ if (server_) {
+ server_->Shutdown();
+ if (cq_ != nullptr) {
+ cq_->Shutdown();
+ }
+ if (cq_thread_.joinable()) {
+ cq_thread_.join();
+ }
+ }
+ }
+
+ void ResetStubs() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ hc_stub_ = grpc::health::v1::Health::NewStub(channel);
+ }
+
+ // When the expected_status is NOT OK, we do not care about the response.
void SendHealthCheckRpc(const TString& service_name,
- const Status& expected_status) {
- EXPECT_FALSE(expected_status.ok());
- SendHealthCheckRpc(service_name, expected_status,
- HealthCheckResponse::UNKNOWN);
- }
-
- void SendHealthCheckRpc(
+ const Status& expected_status) {
+ EXPECT_FALSE(expected_status.ok());
+ SendHealthCheckRpc(service_name, expected_status,
+ HealthCheckResponse::UNKNOWN);
+ }
+
+ void SendHealthCheckRpc(
const TString& service_name, const Status& expected_status,
- HealthCheckResponse::ServingStatus expected_serving_status) {
- HealthCheckRequest request;
- request.set_service(service_name);
- HealthCheckResponse response;
- ClientContext context;
- Status s = hc_stub_->Check(&context, request, &response);
- EXPECT_EQ(expected_status.error_code(), s.error_code());
- if (s.ok()) {
- EXPECT_EQ(expected_serving_status, response.status());
- }
- }
-
- void VerifyHealthCheckService() {
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service != nullptr);
+ HealthCheckResponse::ServingStatus expected_serving_status) {
+ HealthCheckRequest request;
+ request.set_service(service_name);
+ HealthCheckResponse response;
+ ClientContext context;
+ Status s = hc_stub_->Check(&context, request, &response);
+ EXPECT_EQ(expected_status.error_code(), s.error_code());
+ if (s.ok()) {
+ EXPECT_EQ(expected_serving_status, response.status());
+ }
+ }
+
+ void VerifyHealthCheckService() {
+ HealthCheckServiceInterface* service = server_->GetHealthCheckService();
+ EXPECT_TRUE(service != nullptr);
const TString kHealthyService("healthy_service");
const TString kUnhealthyService("unhealthy_service");
const TString kNotRegisteredService("not_registered");
- service->SetServingStatus(kHealthyService, true);
- service->SetServingStatus(kUnhealthyService, false);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
-
- service->SetServingStatus(false);
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
- }
-
- void VerifyHealthCheckServiceStreaming() {
+ service->SetServingStatus(kHealthyService, true);
+ service->SetServingStatus(kUnhealthyService, false);
+
+ ResetStubs();
+
+ SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
+ SendHealthCheckRpc(kHealthyService, Status::OK,
+ HealthCheckResponse::SERVING);
+ SendHealthCheckRpc(kUnhealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kNotRegisteredService,
+ Status(StatusCode::NOT_FOUND, ""));
+
+ service->SetServingStatus(false);
+ SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kHealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kUnhealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kNotRegisteredService,
+ Status(StatusCode::NOT_FOUND, ""));
+ }
+
+ void VerifyHealthCheckServiceStreaming() {
const TString kServiceName("service_name");
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- // Start Watch for service.
- ClientContext context;
- HealthCheckRequest request;
- request.set_service(kServiceName);
- std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
- hc_stub_->Watch(&context, request);
- // Initial response will be SERVICE_UNKNOWN.
- HealthCheckResponse response;
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVICE_UNKNOWN, response.status());
- response.Clear();
- // Now set service to NOT_SERVING and make sure we get an update.
- service->SetServingStatus(kServiceName, false);
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.NOT_SERVING, response.status());
- response.Clear();
- // Now set service to SERVING and make sure we get another update.
- service->SetServingStatus(kServiceName, true);
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVING, response.status());
- // Finish call.
- context.TryCancel();
- }
-
- // Verify that after HealthCheckServiceInterface::Shutdown is called
- // 1. unary client will see NOT_SERVING.
- // 2. unary client still sees NOT_SERVING after a SetServing(true) is called.
- // 3. streaming (Watch) client will see an update.
- // 4. setting a new service to serving after shutdown will add the service
- // name but return NOT_SERVING to client.
- // This has to be called last.
- void VerifyHealthCheckServiceShutdown() {
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service != nullptr);
+ HealthCheckServiceInterface* service = server_->GetHealthCheckService();
+ // Start Watch for service.
+ ClientContext context;
+ HealthCheckRequest request;
+ request.set_service(kServiceName);
+ std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
+ hc_stub_->Watch(&context, request);
+ // Initial response will be SERVICE_UNKNOWN.
+ HealthCheckResponse response;
+ EXPECT_TRUE(reader->Read(&response));
+ EXPECT_EQ(response.SERVICE_UNKNOWN, response.status());
+ response.Clear();
+ // Now set service to NOT_SERVING and make sure we get an update.
+ service->SetServingStatus(kServiceName, false);
+ EXPECT_TRUE(reader->Read(&response));
+ EXPECT_EQ(response.NOT_SERVING, response.status());
+ response.Clear();
+ // Now set service to SERVING and make sure we get another update.
+ service->SetServingStatus(kServiceName, true);
+ EXPECT_TRUE(reader->Read(&response));
+ EXPECT_EQ(response.SERVING, response.status());
+ // Finish call.
+ context.TryCancel();
+ }
+
+ // Verify that after HealthCheckServiceInterface::Shutdown is called
+ // 1. unary client will see NOT_SERVING.
+ // 2. unary client still sees NOT_SERVING after a SetServing(true) is called.
+ // 3. streaming (Watch) client will see an update.
+ // 4. setting a new service to serving after shutdown will add the service
+ // name but return NOT_SERVING to client.
+ // This has to be called last.
+ void VerifyHealthCheckServiceShutdown() {
+ HealthCheckServiceInterface* service = server_->GetHealthCheckService();
+ EXPECT_TRUE(service != nullptr);
const TString kHealthyService("healthy_service");
const TString kUnhealthyService("unhealthy_service");
const TString kNotRegisteredService("not_registered");
const TString kNewService("add_after_shutdown");
- service->SetServingStatus(kHealthyService, true);
- service->SetServingStatus(kUnhealthyService, false);
-
- ResetStubs();
-
- // Start Watch for service.
- ClientContext context;
- HealthCheckRequest request;
- request.set_service(kHealthyService);
- std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
- hc_stub_->Watch(&context, request);
-
- HealthCheckResponse response;
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVING, response.status());
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
- SendHealthCheckRpc(kNewService, Status(StatusCode::NOT_FOUND, ""));
-
- // Shutdown health check service.
- service->Shutdown();
-
- // Watch client gets another update.
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.NOT_SERVING, response.status());
- // Finish Watch call.
- context.TryCancel();
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
-
- // Setting status after Shutdown has no effect.
- service->SetServingStatus(kHealthyService, true);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
-
- // Adding serving status for a new service after shutdown will return
- // NOT_SERVING.
- service->SetServingStatus(kNewService, true);
- SendHealthCheckRpc(kNewService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- }
-
- TestServiceImpl echo_test_service_;
- HealthCheckServiceImpl health_check_service_impl_;
- std::unique_ptr<Health::Stub> hc_stub_;
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- std::thread cq_thread_;
-};
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceDisabled) {
- EnableDefaultHealthCheckService(false);
- EXPECT_FALSE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- HealthCheckServiceInterface* default_service =
- server_->GetHealthCheckService();
- EXPECT_TRUE(default_service == nullptr);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
-}
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthService) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- VerifyHealthCheckService();
- VerifyHealthCheckServiceStreaming();
-
- // The default service has a size limit of the service name.
+ service->SetServingStatus(kHealthyService, true);
+ service->SetServingStatus(kUnhealthyService, false);
+
+ ResetStubs();
+
+ // Start Watch for service.
+ ClientContext context;
+ HealthCheckRequest request;
+ request.set_service(kHealthyService);
+ std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
+ hc_stub_->Watch(&context, request);
+
+ HealthCheckResponse response;
+ EXPECT_TRUE(reader->Read(&response));
+ EXPECT_EQ(response.SERVING, response.status());
+
+ SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
+ SendHealthCheckRpc(kHealthyService, Status::OK,
+ HealthCheckResponse::SERVING);
+ SendHealthCheckRpc(kUnhealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kNotRegisteredService,
+ Status(StatusCode::NOT_FOUND, ""));
+ SendHealthCheckRpc(kNewService, Status(StatusCode::NOT_FOUND, ""));
+
+ // Shutdown health check service.
+ service->Shutdown();
+
+ // Watch client gets another update.
+ EXPECT_TRUE(reader->Read(&response));
+ EXPECT_EQ(response.NOT_SERVING, response.status());
+ // Finish Watch call.
+ context.TryCancel();
+
+ SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kHealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kUnhealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ SendHealthCheckRpc(kNotRegisteredService,
+ Status(StatusCode::NOT_FOUND, ""));
+
+ // Setting status after Shutdown has no effect.
+ service->SetServingStatus(kHealthyService, true);
+ SendHealthCheckRpc(kHealthyService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+
+ // Adding serving status for a new service after shutdown will return
+ // NOT_SERVING.
+ service->SetServingStatus(kNewService, true);
+ SendHealthCheckRpc(kNewService, Status::OK,
+ HealthCheckResponse::NOT_SERVING);
+ }
+
+ TestServiceImpl echo_test_service_;
+ HealthCheckServiceImpl health_check_service_impl_;
+ std::unique_ptr<Health::Stub> hc_stub_;
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+ std::thread cq_thread_;
+};
+
+TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceDisabled) {
+ EnableDefaultHealthCheckService(false);
+ EXPECT_FALSE(DefaultHealthCheckServiceEnabled());
+ SetUpServer(true, false, false, nullptr);
+ HealthCheckServiceInterface* default_service =
+ server_->GetHealthCheckService();
+ EXPECT_TRUE(default_service == nullptr);
+
+ ResetStubs();
+
+ SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
+}
+
+TEST_F(HealthServiceEnd2endTest, DefaultHealthService) {
+ EnableDefaultHealthCheckService(true);
+ EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
+ SetUpServer(true, false, false, nullptr);
+ VerifyHealthCheckService();
+ VerifyHealthCheckServiceStreaming();
+
+ // The default service has a size limit of the service name.
const TString kTooLongServiceName(201, 'x');
- SendHealthCheckRpc(kTooLongServiceName,
- Status(StatusCode::INVALID_ARGUMENT, ""));
-}
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceShutdown) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- VerifyHealthCheckServiceShutdown();
-}
-
-// Provide an empty service to disable the default service.
-TEST_F(HealthServiceEnd2endTest, ExplicitlyDisableViaOverride) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> empty_service;
- SetUpServer(true, false, true, std::move(empty_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == nullptr);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
-}
-
-// Provide an explicit override of health checking service interface.
-TEST_F(HealthServiceEnd2endTest, ExplicitlyOverride) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> override_service(
- new CustomHealthCheckService(&health_check_service_impl_));
- HealthCheckServiceInterface* underlying_service = override_service.get();
- SetUpServer(false, false, true, std::move(override_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == underlying_service);
-
- ResetStubs();
-
- VerifyHealthCheckService();
- VerifyHealthCheckServiceStreaming();
-}
-
-TEST_F(HealthServiceEnd2endTest, ExplicitlyHealthServiceShutdown) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> override_service(
- new CustomHealthCheckService(&health_check_service_impl_));
- HealthCheckServiceInterface* underlying_service = override_service.get();
- SetUpServer(false, false, true, std::move(override_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == underlying_service);
-
- ResetStubs();
-
- VerifyHealthCheckServiceShutdown();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ SendHealthCheckRpc(kTooLongServiceName,
+ Status(StatusCode::INVALID_ARGUMENT, ""));
+}
+
+TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceShutdown) {
+ EnableDefaultHealthCheckService(true);
+ EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
+ SetUpServer(true, false, false, nullptr);
+ VerifyHealthCheckServiceShutdown();
+}
+
+// Provide an empty service to disable the default service.
+TEST_F(HealthServiceEnd2endTest, ExplicitlyDisableViaOverride) {
+ EnableDefaultHealthCheckService(true);
+ EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
+ std::unique_ptr<HealthCheckServiceInterface> empty_service;
+ SetUpServer(true, false, true, std::move(empty_service));
+ HealthCheckServiceInterface* service = server_->GetHealthCheckService();
+ EXPECT_TRUE(service == nullptr);
+
+ ResetStubs();
+
+ SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
+}
+
+// Provide an explicit override of health checking service interface.
+TEST_F(HealthServiceEnd2endTest, ExplicitlyOverride) {
+ EnableDefaultHealthCheckService(true);
+ EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
+ std::unique_ptr<HealthCheckServiceInterface> override_service(
+ new CustomHealthCheckService(&health_check_service_impl_));
+ HealthCheckServiceInterface* underlying_service = override_service.get();
+ SetUpServer(false, false, true, std::move(override_service));
+ HealthCheckServiceInterface* service = server_->GetHealthCheckService();
+ EXPECT_TRUE(service == underlying_service);
+
+ ResetStubs();
+
+ VerifyHealthCheckService();
+ VerifyHealthCheckServiceStreaming();
+}
+
+TEST_F(HealthServiceEnd2endTest, ExplicitlyHealthServiceShutdown) {
+ EnableDefaultHealthCheckService(true);
+ EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
+ std::unique_ptr<HealthCheckServiceInterface> override_service(
+ new CustomHealthCheckService(&health_check_service_impl_));
+ HealthCheckServiceInterface* underlying_service = override_service.get();
+ SetUpServer(false, false, true, std::move(override_service));
+ HealthCheckServiceInterface* service = server_->GetHealthCheckService();
+ EXPECT_TRUE(service == underlying_service);
+
+ ResetStubs();
+
+ VerifyHealthCheckServiceShutdown();
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/hybrid_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/hybrid_end2end_test.cc
index e4ebee8e93..9fc5cc1ba7 100644
--- a/contrib/libs/grpc/test/cpp/end2end/hybrid_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/hybrid_end2end_test.cc
@@ -1,987 +1,987 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <memory>
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/async_generic_service.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <memory>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/generic/async_generic_service.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+namespace {
+
#ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
using ::grpc::experimental::CallbackGenericService;
using ::grpc::experimental::GenericCallbackServerContext;
using ::grpc::experimental::ServerGenericBidiReactor;
#endif
-void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
-
-bool VerifyReturnSuccess(CompletionQueue* cq, int i) {
- void* got_tag;
- bool ok;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- EXPECT_EQ(tag(i), got_tag);
- return ok;
-}
-
-void Verify(CompletionQueue* cq, int i, bool expect_ok) {
- EXPECT_EQ(expect_ok, VerifyReturnSuccess(cq, i));
-}
-
-// Handlers to handle async request at a server. To be run in a separate thread.
-template <class Service>
-void HandleEcho(Service* service, ServerCompletionQueue* cq, bool dup_service) {
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
- EchoRequest recv_request;
- EchoResponse send_response;
- service->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq, cq,
- tag(1));
- Verify(cq, 1, true);
- send_response.set_message(recv_request.message());
- if (dup_service) {
- send_response.mutable_message()->append("_dup");
- }
- response_writer.Finish(send_response, Status::OK, tag(2));
- Verify(cq, 2, true);
-}
-
-// Handlers to handle raw request at a server. To be run in a
-// separate thread. Note that this is the same as the async version, except
-// that the req/resp are ByteBuffers
-template <class Service>
-void HandleRawEcho(Service* service, ServerCompletionQueue* cq,
- bool /*dup_service*/) {
- ServerContext srv_ctx;
- GenericServerAsyncResponseWriter response_writer(&srv_ctx);
- ByteBuffer recv_buffer;
- service->RequestEcho(&srv_ctx, &recv_buffer, &response_writer, cq, cq,
- tag(1));
- Verify(cq, 1, true);
- EchoRequest recv_request;
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EchoResponse send_response;
- send_response.set_message(recv_request.message());
- auto send_buffer = SerializeToByteBuffer(&send_response);
- response_writer.Finish(*send_buffer, Status::OK, tag(2));
- Verify(cq, 2, true);
-}
-
-template <class Service>
-void HandleClientStreaming(Service* service, ServerCompletionQueue* cq) {
- ServerContext srv_ctx;
- EchoRequest recv_request;
- EchoResponse send_response;
- ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
- service->RequestRequestStream(&srv_ctx, &srv_stream, cq, cq, tag(1));
- Verify(cq, 1, true);
- int i = 1;
- do {
- i++;
- send_response.mutable_message()->append(recv_request.message());
- srv_stream.Read(&recv_request, tag(i));
- } while (VerifyReturnSuccess(cq, i));
- srv_stream.Finish(send_response, Status::OK, tag(100));
- Verify(cq, 100, true);
-}
-
-template <class Service>
-void HandleRawClientStreaming(Service* service, ServerCompletionQueue* cq) {
- ServerContext srv_ctx;
- ByteBuffer recv_buffer;
- EchoRequest recv_request;
- EchoResponse send_response;
- GenericServerAsyncReader srv_stream(&srv_ctx);
- service->RequestRequestStream(&srv_ctx, &srv_stream, cq, cq, tag(1));
- Verify(cq, 1, true);
- int i = 1;
- while (true) {
- i++;
- srv_stream.Read(&recv_buffer, tag(i));
- if (!VerifyReturnSuccess(cq, i)) {
- break;
- }
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- send_response.mutable_message()->append(recv_request.message());
- }
- auto send_buffer = SerializeToByteBuffer(&send_response);
- srv_stream.Finish(*send_buffer, Status::OK, tag(100));
- Verify(cq, 100, true);
-}
-
-template <class Service>
-void HandleServerStreaming(Service* service, ServerCompletionQueue* cq) {
- ServerContext srv_ctx;
- EchoRequest recv_request;
- EchoResponse send_response;
- ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
- service->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream, cq, cq,
- tag(1));
- Verify(cq, 1, true);
- send_response.set_message(recv_request.message() + "0");
- srv_stream.Write(send_response, tag(2));
- Verify(cq, 2, true);
- send_response.set_message(recv_request.message() + "1");
- srv_stream.Write(send_response, tag(3));
- Verify(cq, 3, true);
- send_response.set_message(recv_request.message() + "2");
- srv_stream.Write(send_response, tag(4));
- Verify(cq, 4, true);
- srv_stream.Finish(Status::OK, tag(5));
- Verify(cq, 5, true);
-}
-
-void HandleGenericEcho(GenericServerAsyncReaderWriter* stream,
- CompletionQueue* cq) {
- ByteBuffer recv_buffer;
- stream->Read(&recv_buffer, tag(2));
- Verify(cq, 2, true);
- EchoRequest recv_request;
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EchoResponse send_response;
- send_response.set_message(recv_request.message());
- auto send_buffer = SerializeToByteBuffer(&send_response);
- stream->Write(*send_buffer, tag(3));
- Verify(cq, 3, true);
- stream->Finish(Status::OK, tag(4));
- Verify(cq, 4, true);
-}
-
-void HandleGenericRequestStream(GenericServerAsyncReaderWriter* stream,
- CompletionQueue* cq) {
- ByteBuffer recv_buffer;
- EchoRequest recv_request;
- EchoResponse send_response;
- int i = 1;
- while (true) {
- i++;
- stream->Read(&recv_buffer, tag(i));
- if (!VerifyReturnSuccess(cq, i)) {
- break;
- }
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- send_response.mutable_message()->append(recv_request.message());
- }
- auto send_buffer = SerializeToByteBuffer(&send_response);
- stream->Write(*send_buffer, tag(99));
- Verify(cq, 99, true);
- stream->Finish(Status::OK, tag(100));
- Verify(cq, 100, true);
-}
-
-// Request and handle one generic call.
-void HandleGenericCall(AsyncGenericService* service,
- ServerCompletionQueue* cq) {
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
- service->RequestCall(&srv_ctx, &stream, cq, cq, tag(1));
- Verify(cq, 1, true);
- if (srv_ctx.method() == "/grpc.testing.EchoTestService/Echo") {
- HandleGenericEcho(&stream, cq);
- } else if (srv_ctx.method() ==
- "/grpc.testing.EchoTestService/RequestStream") {
- HandleGenericRequestStream(&stream, cq);
- } else { // other methods not handled yet.
- gpr_log(GPR_ERROR, "method: %s", srv_ctx.method().c_str());
- GPR_ASSERT(0);
- }
-}
-
-class TestServiceImplDupPkg
- : public ::grpc::testing::duplicate::EchoTestService::Service {
- public:
- Status Echo(ServerContext* /*context*/, const EchoRequest* request,
- EchoResponse* response) override {
- response->set_message(request->message() + "_dup");
- return Status::OK;
- }
-};
-
-class HybridEnd2endTest : public ::testing::TestWithParam<bool> {
- protected:
- HybridEnd2endTest() {}
-
- static void SetUpTestCase() {
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
- }
-
- void SetUp() override {
- inproc_ = (::testing::UnitTest::GetInstance()
- ->current_test_info()
- ->value_param() != nullptr)
- ? GetParam()
- : false;
- }
-
+void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
+
+bool VerifyReturnSuccess(CompletionQueue* cq, int i) {
+ void* got_tag;
+ bool ok;
+ EXPECT_TRUE(cq->Next(&got_tag, &ok));
+ EXPECT_EQ(tag(i), got_tag);
+ return ok;
+}
+
+void Verify(CompletionQueue* cq, int i, bool expect_ok) {
+ EXPECT_EQ(expect_ok, VerifyReturnSuccess(cq, i));
+}
+
+// Handlers to handle async request at a server. To be run in a separate thread.
+template <class Service>
+void HandleEcho(Service* service, ServerCompletionQueue* cq, bool dup_service) {
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ service->RequestEcho(&srv_ctx, &recv_request, &response_writer, cq, cq,
+ tag(1));
+ Verify(cq, 1, true);
+ send_response.set_message(recv_request.message());
+ if (dup_service) {
+ send_response.mutable_message()->append("_dup");
+ }
+ response_writer.Finish(send_response, Status::OK, tag(2));
+ Verify(cq, 2, true);
+}
+
+// Handlers to handle raw request at a server. To be run in a
+// separate thread. Note that this is the same as the async version, except
+// that the req/resp are ByteBuffers
+template <class Service>
+void HandleRawEcho(Service* service, ServerCompletionQueue* cq,
+ bool /*dup_service*/) {
+ ServerContext srv_ctx;
+ GenericServerAsyncResponseWriter response_writer(&srv_ctx);
+ ByteBuffer recv_buffer;
+ service->RequestEcho(&srv_ctx, &recv_buffer, &response_writer, cq, cq,
+ tag(1));
+ Verify(cq, 1, true);
+ EchoRequest recv_request;
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EchoResponse send_response;
+ send_response.set_message(recv_request.message());
+ auto send_buffer = SerializeToByteBuffer(&send_response);
+ response_writer.Finish(*send_buffer, Status::OK, tag(2));
+ Verify(cq, 2, true);
+}
+
+template <class Service>
+void HandleClientStreaming(Service* service, ServerCompletionQueue* cq) {
+ ServerContext srv_ctx;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+ service->RequestRequestStream(&srv_ctx, &srv_stream, cq, cq, tag(1));
+ Verify(cq, 1, true);
+ int i = 1;
+ do {
+ i++;
+ send_response.mutable_message()->append(recv_request.message());
+ srv_stream.Read(&recv_request, tag(i));
+ } while (VerifyReturnSuccess(cq, i));
+ srv_stream.Finish(send_response, Status::OK, tag(100));
+ Verify(cq, 100, true);
+}
+
+template <class Service>
+void HandleRawClientStreaming(Service* service, ServerCompletionQueue* cq) {
+ ServerContext srv_ctx;
+ ByteBuffer recv_buffer;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ GenericServerAsyncReader srv_stream(&srv_ctx);
+ service->RequestRequestStream(&srv_ctx, &srv_stream, cq, cq, tag(1));
+ Verify(cq, 1, true);
+ int i = 1;
+ while (true) {
+ i++;
+ srv_stream.Read(&recv_buffer, tag(i));
+ if (!VerifyReturnSuccess(cq, i)) {
+ break;
+ }
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ send_response.mutable_message()->append(recv_request.message());
+ }
+ auto send_buffer = SerializeToByteBuffer(&send_response);
+ srv_stream.Finish(*send_buffer, Status::OK, tag(100));
+ Verify(cq, 100, true);
+}
+
+template <class Service>
+void HandleServerStreaming(Service* service, ServerCompletionQueue* cq) {
+ ServerContext srv_ctx;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
+ service->RequestResponseStream(&srv_ctx, &recv_request, &srv_stream, cq, cq,
+ tag(1));
+ Verify(cq, 1, true);
+ send_response.set_message(recv_request.message() + "0");
+ srv_stream.Write(send_response, tag(2));
+ Verify(cq, 2, true);
+ send_response.set_message(recv_request.message() + "1");
+ srv_stream.Write(send_response, tag(3));
+ Verify(cq, 3, true);
+ send_response.set_message(recv_request.message() + "2");
+ srv_stream.Write(send_response, tag(4));
+ Verify(cq, 4, true);
+ srv_stream.Finish(Status::OK, tag(5));
+ Verify(cq, 5, true);
+}
+
+void HandleGenericEcho(GenericServerAsyncReaderWriter* stream,
+ CompletionQueue* cq) {
+ ByteBuffer recv_buffer;
+ stream->Read(&recv_buffer, tag(2));
+ Verify(cq, 2, true);
+ EchoRequest recv_request;
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EchoResponse send_response;
+ send_response.set_message(recv_request.message());
+ auto send_buffer = SerializeToByteBuffer(&send_response);
+ stream->Write(*send_buffer, tag(3));
+ Verify(cq, 3, true);
+ stream->Finish(Status::OK, tag(4));
+ Verify(cq, 4, true);
+}
+
+void HandleGenericRequestStream(GenericServerAsyncReaderWriter* stream,
+ CompletionQueue* cq) {
+ ByteBuffer recv_buffer;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ int i = 1;
+ while (true) {
+ i++;
+ stream->Read(&recv_buffer, tag(i));
+ if (!VerifyReturnSuccess(cq, i)) {
+ break;
+ }
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ send_response.mutable_message()->append(recv_request.message());
+ }
+ auto send_buffer = SerializeToByteBuffer(&send_response);
+ stream->Write(*send_buffer, tag(99));
+ Verify(cq, 99, true);
+ stream->Finish(Status::OK, tag(100));
+ Verify(cq, 100, true);
+}
+
+// Request and handle one generic call.
+void HandleGenericCall(AsyncGenericService* service,
+ ServerCompletionQueue* cq) {
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter stream(&srv_ctx);
+ service->RequestCall(&srv_ctx, &stream, cq, cq, tag(1));
+ Verify(cq, 1, true);
+ if (srv_ctx.method() == "/grpc.testing.EchoTestService/Echo") {
+ HandleGenericEcho(&stream, cq);
+ } else if (srv_ctx.method() ==
+ "/grpc.testing.EchoTestService/RequestStream") {
+ HandleGenericRequestStream(&stream, cq);
+ } else { // other methods not handled yet.
+ gpr_log(GPR_ERROR, "method: %s", srv_ctx.method().c_str());
+ GPR_ASSERT(0);
+ }
+}
+
+class TestServiceImplDupPkg
+ : public ::grpc::testing::duplicate::EchoTestService::Service {
+ public:
+ Status Echo(ServerContext* /*context*/, const EchoRequest* request,
+ EchoResponse* response) override {
+ response->set_message(request->message() + "_dup");
+ return Status::OK;
+ }
+};
+
+class HybridEnd2endTest : public ::testing::TestWithParam<bool> {
+ protected:
+ HybridEnd2endTest() {}
+
+ static void SetUpTestCase() {
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+ }
+
+ void SetUp() override {
+ inproc_ = (::testing::UnitTest::GetInstance()
+ ->current_test_info()
+ ->value_param() != nullptr)
+ ? GetParam()
+ : false;
+ }
+
bool SetUpServer(::grpc::Service* service1, ::grpc::Service* service2,
AsyncGenericService* generic_service,
CallbackGenericService* callback_generic_service,
int max_message_size = 0) {
- int port = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port;
-
- // Setup server
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- grpc::InsecureServerCredentials());
- // Always add a sync unimplemented service: we rely on having at least one
- // synchronous method to get a listening cq
- builder.RegisterService(&unimplemented_service_);
- builder.RegisterService(service1);
- if (service2) {
- builder.RegisterService(service2);
- }
- if (generic_service) {
- builder.RegisterAsyncGenericService(generic_service);
- }
- if (callback_generic_service) {
+ int port = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port;
+
+ // Setup server
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ grpc::InsecureServerCredentials());
+ // Always add a sync unimplemented service: we rely on having at least one
+ // synchronous method to get a listening cq
+ builder.RegisterService(&unimplemented_service_);
+ builder.RegisterService(service1);
+ if (service2) {
+ builder.RegisterService(service2);
+ }
+ if (generic_service) {
+ builder.RegisterAsyncGenericService(generic_service);
+ }
+ if (callback_generic_service) {
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
builder.RegisterCallbackGenericService(callback_generic_service);
#else
- builder.experimental().RegisterCallbackGenericService(
- callback_generic_service);
+ builder.experimental().RegisterCallbackGenericService(
+ callback_generic_service);
#endif
- }
-
- if (max_message_size != 0) {
- builder.SetMaxMessageSize(max_message_size);
- }
-
- // Create a separate cq for each potential handler.
- for (int i = 0; i < 5; i++) {
- cqs_.push_back(builder.AddCompletionQueue(false));
- }
- server_ = builder.BuildAndStart();
-
- // If there is a generic callback service, this setup is only successful if
- // we have an iomgr that can run in the background or are inprocess
- return !callback_generic_service || grpc_iomgr_run_in_background() ||
- inproc_;
- }
-
- void TearDown() override {
- if (server_) {
- server_->Shutdown();
- }
- void* ignored_tag;
- bool ignored_ok;
- for (auto it = cqs_.begin(); it != cqs_.end(); ++it) {
- (*it)->Shutdown();
- while ((*it)->Next(&ignored_tag, &ignored_ok))
- ;
- }
- }
-
- void ResetStub() {
- std::shared_ptr<Channel> channel =
- inproc_ ? server_->InProcessChannel(ChannelArguments())
- : grpc::CreateChannel(server_address_.str(),
- InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- // Test all rpc methods.
- void TestAllMethods() {
- SendEcho();
- SendSimpleClientStreaming();
- SendSimpleServerStreaming();
- SendBidiStreaming();
- }
-
- void SendEcho() {
- EchoRequest send_request;
- EchoResponse recv_response;
- ClientContext cli_ctx;
- cli_ctx.set_wait_for_ready(true);
- send_request.set_message("Hello");
- Status recv_status = stub_->Echo(&cli_ctx, send_request, &recv_response);
- EXPECT_EQ(send_request.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
-
- void SendEchoToDupService() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- auto stub = grpc::testing::duplicate::EchoTestService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
- ClientContext cli_ctx;
- cli_ctx.set_wait_for_ready(true);
- send_request.set_message("Hello");
- Status recv_status = stub->Echo(&cli_ctx, send_request, &recv_response);
- EXPECT_EQ(send_request.message() + "_dup", recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
-
- void SendSimpleClientStreaming() {
- EchoRequest send_request;
- EchoResponse recv_response;
+ }
+
+ if (max_message_size != 0) {
+ builder.SetMaxMessageSize(max_message_size);
+ }
+
+ // Create a separate cq for each potential handler.
+ for (int i = 0; i < 5; i++) {
+ cqs_.push_back(builder.AddCompletionQueue(false));
+ }
+ server_ = builder.BuildAndStart();
+
+ // If there is a generic callback service, this setup is only successful if
+ // we have an iomgr that can run in the background or are inprocess
+ return !callback_generic_service || grpc_iomgr_run_in_background() ||
+ inproc_;
+ }
+
+ void TearDown() override {
+ if (server_) {
+ server_->Shutdown();
+ }
+ void* ignored_tag;
+ bool ignored_ok;
+ for (auto it = cqs_.begin(); it != cqs_.end(); ++it) {
+ (*it)->Shutdown();
+ while ((*it)->Next(&ignored_tag, &ignored_ok))
+ ;
+ }
+ }
+
+ void ResetStub() {
+ std::shared_ptr<Channel> channel =
+ inproc_ ? server_->InProcessChannel(ChannelArguments())
+ : grpc::CreateChannel(server_address_.str(),
+ InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ // Test all rpc methods.
+ void TestAllMethods() {
+ SendEcho();
+ SendSimpleClientStreaming();
+ SendSimpleServerStreaming();
+ SendBidiStreaming();
+ }
+
+ void SendEcho() {
+ EchoRequest send_request;
+ EchoResponse recv_response;
+ ClientContext cli_ctx;
+ cli_ctx.set_wait_for_ready(true);
+ send_request.set_message("Hello");
+ Status recv_status = stub_->Echo(&cli_ctx, send_request, &recv_response);
+ EXPECT_EQ(send_request.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+
+ void SendEchoToDupService() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ auto stub = grpc::testing::duplicate::EchoTestService::NewStub(channel);
+ EchoRequest send_request;
+ EchoResponse recv_response;
+ ClientContext cli_ctx;
+ cli_ctx.set_wait_for_ready(true);
+ send_request.set_message("Hello");
+ Status recv_status = stub->Echo(&cli_ctx, send_request, &recv_response);
+ EXPECT_EQ(send_request.message() + "_dup", recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+
+ void SendSimpleClientStreaming() {
+ EchoRequest send_request;
+ EchoResponse recv_response;
TString expected_message;
- ClientContext cli_ctx;
- cli_ctx.set_wait_for_ready(true);
- send_request.set_message("Hello");
- auto stream = stub_->RequestStream(&cli_ctx, &recv_response);
- for (int i = 0; i < 5; i++) {
- EXPECT_TRUE(stream->Write(send_request));
- expected_message.append(send_request.message());
- }
- stream->WritesDone();
- Status recv_status = stream->Finish();
- EXPECT_EQ(expected_message, recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
-
- void SendSimpleServerStreaming() {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_wait_for_ready(true);
- request.set_message("hello");
-
- auto stream = stub_->ResponseStream(&context, request);
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "0");
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "1");
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "2");
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
- }
-
- void SendSimpleServerStreamingToDupService() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- auto stub = grpc::testing::duplicate::EchoTestService::NewStub(channel);
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_wait_for_ready(true);
- request.set_message("hello");
-
- auto stream = stub->ResponseStream(&context, request);
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "0_dup");
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "1_dup");
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message() + "2_dup");
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
- }
-
- void SendBidiStreaming() {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_wait_for_ready(true);
+ ClientContext cli_ctx;
+ cli_ctx.set_wait_for_ready(true);
+ send_request.set_message("Hello");
+ auto stream = stub_->RequestStream(&cli_ctx, &recv_response);
+ for (int i = 0; i < 5; i++) {
+ EXPECT_TRUE(stream->Write(send_request));
+ expected_message.append(send_request.message());
+ }
+ stream->WritesDone();
+ Status recv_status = stream->Finish();
+ EXPECT_EQ(expected_message, recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+
+ void SendSimpleServerStreaming() {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_wait_for_ready(true);
+ request.set_message("hello");
+
+ auto stream = stub_->ResponseStream(&context, request);
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "0");
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "1");
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "2");
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+ }
+
+ void SendSimpleServerStreamingToDupService() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ auto stub = grpc::testing::duplicate::EchoTestService::NewStub(channel);
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_wait_for_ready(true);
+ request.set_message("hello");
+
+ auto stream = stub->ResponseStream(&context, request);
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "0_dup");
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "1_dup");
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message() + "2_dup");
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+ }
+
+ void SendBidiStreaming() {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_wait_for_ready(true);
TString msg("hello");
-
- auto stream = stub_->BidiStream(&context);
-
- request.set_message(msg + "0");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "1");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "2");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- stream->WritesDone();
- EXPECT_FALSE(stream->Read(&response));
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
- }
-
- grpc::testing::UnimplementedEchoService::Service unimplemented_service_;
- std::vector<std::unique_ptr<ServerCompletionQueue>> cqs_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- bool inproc_;
-};
-
-TEST_F(HybridEnd2endTest, AsyncEcho) {
- typedef EchoTestService::WithAsyncMethod_Echo<TestServiceImpl> SType;
- SType service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- ResetStub();
- std::thread echo_handler_thread(HandleEcho<SType>, &service, cqs_[0].get(),
- false);
- TestAllMethods();
- echo_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, RawEcho) {
- typedef EchoTestService::WithRawMethod_Echo<TestServiceImpl> SType;
- SType service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- ResetStub();
- std::thread echo_handler_thread(HandleRawEcho<SType>, &service, cqs_[0].get(),
- false);
- TestAllMethods();
- echo_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, RawRequestStream) {
- typedef EchoTestService::WithRawMethod_RequestStream<TestServiceImpl> SType;
- SType service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- ResetStub();
- std::thread request_stream_handler_thread(HandleRawClientStreaming<SType>,
- &service, cqs_[0].get());
- TestAllMethods();
- request_stream_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, AsyncEchoRawRequestStream) {
- typedef EchoTestService::WithRawMethod_RequestStream<
- EchoTestService::WithAsyncMethod_Echo<TestServiceImpl>>
- SType;
- SType service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- ResetStub();
- std::thread echo_handler_thread(HandleEcho<SType>, &service, cqs_[0].get(),
- false);
- std::thread request_stream_handler_thread(HandleRawClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- request_stream_handler_thread.join();
- echo_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, GenericEchoRawRequestStream) {
- typedef EchoTestService::WithRawMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
- SType;
- SType service;
- AsyncGenericService generic_service;
- SetUpServer(&service, nullptr, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- std::thread request_stream_handler_thread(HandleRawClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- generic_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, AsyncEchoRequestStream) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_Echo<TestServiceImpl>>
- SType;
- SType service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- ResetStub();
- std::thread echo_handler_thread(HandleEcho<SType>, &service, cqs_[0].get(),
- false);
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- echo_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, AsyncRequestStreamResponseStream) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service with one sync method.
-TEST_F(HybridEnd2endTest, AsyncRequestStreamResponseStream_SyncDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- TestServiceImplDupPkg dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendEchoToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service with one sync streamed unary method.
-class StreamedUnaryDupPkg
- : public duplicate::EchoTestService::WithStreamedUnaryMethod_Echo<
- TestServiceImplDupPkg> {
- public:
- Status StreamedEcho(
- ServerContext* /*context*/,
- ServerUnaryStreamer<EchoRequest, EchoResponse>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- uint32_t next_msg_sz;
- stream->NextMessageSize(&next_msg_sz);
- gpr_log(GPR_INFO, "Streamed Unary Next Message Size is %u", next_msg_sz);
- GPR_ASSERT(stream->Read(&req));
- resp.set_message(req.message() + "_dup");
- GPR_ASSERT(stream->Write(resp));
- return Status::OK;
- }
-};
-
-TEST_F(HybridEnd2endTest,
- AsyncRequestStreamResponseStream_SyncStreamedUnaryDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- StreamedUnaryDupPkg dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendEchoToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service that is fully Streamed Unary
-class FullyStreamedUnaryDupPkg
- : public duplicate::EchoTestService::StreamedUnaryService {
- public:
- Status StreamedEcho(
- ServerContext* /*context*/,
- ServerUnaryStreamer<EchoRequest, EchoResponse>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- uint32_t next_msg_sz;
- stream->NextMessageSize(&next_msg_sz);
- gpr_log(GPR_INFO, "Streamed Unary Next Message Size is %u", next_msg_sz);
- GPR_ASSERT(stream->Read(&req));
- resp.set_message(req.message() + "_dup");
- GPR_ASSERT(stream->Write(resp));
- return Status::OK;
- }
-};
-
-TEST_F(HybridEnd2endTest,
- AsyncRequestStreamResponseStream_SyncFullyStreamedUnaryDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- FullyStreamedUnaryDupPkg dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendEchoToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service with one sync split server streaming method.
-class SplitResponseStreamDupPkg
- : public duplicate::EchoTestService::
- WithSplitStreamingMethod_ResponseStream<TestServiceImplDupPkg> {
- public:
- Status StreamedResponseStream(
- ServerContext* /*context*/,
- ServerSplitStreamer<EchoRequest, EchoResponse>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- uint32_t next_msg_sz;
- stream->NextMessageSize(&next_msg_sz);
- gpr_log(GPR_INFO, "Split Streamed Next Message Size is %u", next_msg_sz);
- GPR_ASSERT(stream->Read(&req));
- for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
+
+ auto stream = stub_->BidiStream(&context);
+
+ request.set_message(msg + "0");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "1");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "2");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ stream->WritesDone();
+ EXPECT_FALSE(stream->Read(&response));
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+ }
+
+ grpc::testing::UnimplementedEchoService::Service unimplemented_service_;
+ std::vector<std::unique_ptr<ServerCompletionQueue>> cqs_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+ bool inproc_;
+};
+
+TEST_F(HybridEnd2endTest, AsyncEcho) {
+ typedef EchoTestService::WithAsyncMethod_Echo<TestServiceImpl> SType;
+ SType service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ ResetStub();
+ std::thread echo_handler_thread(HandleEcho<SType>, &service, cqs_[0].get(),
+ false);
+ TestAllMethods();
+ echo_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, RawEcho) {
+ typedef EchoTestService::WithRawMethod_Echo<TestServiceImpl> SType;
+ SType service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ ResetStub();
+ std::thread echo_handler_thread(HandleRawEcho<SType>, &service, cqs_[0].get(),
+ false);
+ TestAllMethods();
+ echo_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, RawRequestStream) {
+ typedef EchoTestService::WithRawMethod_RequestStream<TestServiceImpl> SType;
+ SType service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ ResetStub();
+ std::thread request_stream_handler_thread(HandleRawClientStreaming<SType>,
+ &service, cqs_[0].get());
+ TestAllMethods();
+ request_stream_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, AsyncEchoRawRequestStream) {
+ typedef EchoTestService::WithRawMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_Echo<TestServiceImpl>>
+ SType;
+ SType service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ ResetStub();
+ std::thread echo_handler_thread(HandleEcho<SType>, &service, cqs_[0].get(),
+ false);
+ std::thread request_stream_handler_thread(HandleRawClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ request_stream_handler_thread.join();
+ echo_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, GenericEchoRawRequestStream) {
+ typedef EchoTestService::WithRawMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
+ SType;
+ SType service;
+ AsyncGenericService generic_service;
+ SetUpServer(&service, nullptr, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleRawClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ generic_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, AsyncEchoRequestStream) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_Echo<TestServiceImpl>>
+ SType;
+ SType service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ ResetStub();
+ std::thread echo_handler_thread(HandleEcho<SType>, &service, cqs_[0].get(),
+ false);
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ echo_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, AsyncRequestStreamResponseStream) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service with one sync method.
+TEST_F(HybridEnd2endTest, AsyncRequestStreamResponseStream_SyncDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ TestServiceImplDupPkg dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendEchoToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service with one sync streamed unary method.
+class StreamedUnaryDupPkg
+ : public duplicate::EchoTestService::WithStreamedUnaryMethod_Echo<
+ TestServiceImplDupPkg> {
+ public:
+ Status StreamedEcho(
+ ServerContext* /*context*/,
+ ServerUnaryStreamer<EchoRequest, EchoResponse>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ uint32_t next_msg_sz;
+ stream->NextMessageSize(&next_msg_sz);
+ gpr_log(GPR_INFO, "Streamed Unary Next Message Size is %u", next_msg_sz);
+ GPR_ASSERT(stream->Read(&req));
+ resp.set_message(req.message() + "_dup");
+ GPR_ASSERT(stream->Write(resp));
+ return Status::OK;
+ }
+};
+
+TEST_F(HybridEnd2endTest,
+ AsyncRequestStreamResponseStream_SyncStreamedUnaryDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ StreamedUnaryDupPkg dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendEchoToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service that is fully Streamed Unary
+class FullyStreamedUnaryDupPkg
+ : public duplicate::EchoTestService::StreamedUnaryService {
+ public:
+ Status StreamedEcho(
+ ServerContext* /*context*/,
+ ServerUnaryStreamer<EchoRequest, EchoResponse>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ uint32_t next_msg_sz;
+ stream->NextMessageSize(&next_msg_sz);
+ gpr_log(GPR_INFO, "Streamed Unary Next Message Size is %u", next_msg_sz);
+ GPR_ASSERT(stream->Read(&req));
+ resp.set_message(req.message() + "_dup");
+ GPR_ASSERT(stream->Write(resp));
+ return Status::OK;
+ }
+};
+
+TEST_F(HybridEnd2endTest,
+ AsyncRequestStreamResponseStream_SyncFullyStreamedUnaryDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ FullyStreamedUnaryDupPkg dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendEchoToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service with one sync split server streaming method.
+class SplitResponseStreamDupPkg
+ : public duplicate::EchoTestService::
+ WithSplitStreamingMethod_ResponseStream<TestServiceImplDupPkg> {
+ public:
+ Status StreamedResponseStream(
+ ServerContext* /*context*/,
+ ServerSplitStreamer<EchoRequest, EchoResponse>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ uint32_t next_msg_sz;
+ stream->NextMessageSize(&next_msg_sz);
+ gpr_log(GPR_INFO, "Split Streamed Next Message Size is %u", next_msg_sz);
+ GPR_ASSERT(stream->Read(&req));
+ for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
resp.set_message(req.message() + ToString(i) + "_dup");
- GPR_ASSERT(stream->Write(resp));
- }
- return Status::OK;
- }
-};
-
-TEST_F(HybridEnd2endTest,
- AsyncRequestStreamResponseStream_SyncSplitStreamedDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- SplitResponseStreamDupPkg dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendSimpleServerStreamingToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service that is fully split server streamed
-class FullySplitStreamedDupPkg
- : public duplicate::EchoTestService::SplitStreamedService {
- public:
- Status StreamedResponseStream(
- ServerContext* /*context*/,
- ServerSplitStreamer<EchoRequest, EchoResponse>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- uint32_t next_msg_sz;
- stream->NextMessageSize(&next_msg_sz);
- gpr_log(GPR_INFO, "Split Streamed Next Message Size is %u", next_msg_sz);
- GPR_ASSERT(stream->Read(&req));
- for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
+ GPR_ASSERT(stream->Write(resp));
+ }
+ return Status::OK;
+ }
+};
+
+TEST_F(HybridEnd2endTest,
+ AsyncRequestStreamResponseStream_SyncSplitStreamedDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ SplitResponseStreamDupPkg dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendSimpleServerStreamingToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service that is fully split server streamed
+class FullySplitStreamedDupPkg
+ : public duplicate::EchoTestService::SplitStreamedService {
+ public:
+ Status StreamedResponseStream(
+ ServerContext* /*context*/,
+ ServerSplitStreamer<EchoRequest, EchoResponse>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ uint32_t next_msg_sz;
+ stream->NextMessageSize(&next_msg_sz);
+ gpr_log(GPR_INFO, "Split Streamed Next Message Size is %u", next_msg_sz);
+ GPR_ASSERT(stream->Read(&req));
+ for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
resp.set_message(req.message() + ToString(i) + "_dup");
- GPR_ASSERT(stream->Write(resp));
- }
- return Status::OK;
- }
-};
-
-TEST_F(HybridEnd2endTest,
- AsyncRequestStreamResponseStream_FullySplitStreamedDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- FullySplitStreamedDupPkg dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendSimpleServerStreamingToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service that is fully server streamed
-class FullyStreamedDupPkg : public duplicate::EchoTestService::StreamedService {
- public:
- Status StreamedEcho(
- ServerContext* /*context*/,
- ServerUnaryStreamer<EchoRequest, EchoResponse>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- uint32_t next_msg_sz;
- stream->NextMessageSize(&next_msg_sz);
- gpr_log(GPR_INFO, "Streamed Unary Next Message Size is %u", next_msg_sz);
- GPR_ASSERT(stream->Read(&req));
- resp.set_message(req.message() + "_dup");
- GPR_ASSERT(stream->Write(resp));
- return Status::OK;
- }
- Status StreamedResponseStream(
- ServerContext* /*context*/,
- ServerSplitStreamer<EchoRequest, EchoResponse>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- uint32_t next_msg_sz;
- stream->NextMessageSize(&next_msg_sz);
- gpr_log(GPR_INFO, "Split Streamed Next Message Size is %u", next_msg_sz);
- GPR_ASSERT(stream->Read(&req));
- for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
+ GPR_ASSERT(stream->Write(resp));
+ }
+ return Status::OK;
+ }
+};
+
+TEST_F(HybridEnd2endTest,
+ AsyncRequestStreamResponseStream_FullySplitStreamedDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ FullySplitStreamedDupPkg dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendSimpleServerStreamingToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service that is fully server streamed
+class FullyStreamedDupPkg : public duplicate::EchoTestService::StreamedService {
+ public:
+ Status StreamedEcho(
+ ServerContext* /*context*/,
+ ServerUnaryStreamer<EchoRequest, EchoResponse>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ uint32_t next_msg_sz;
+ stream->NextMessageSize(&next_msg_sz);
+ gpr_log(GPR_INFO, "Streamed Unary Next Message Size is %u", next_msg_sz);
+ GPR_ASSERT(stream->Read(&req));
+ resp.set_message(req.message() + "_dup");
+ GPR_ASSERT(stream->Write(resp));
+ return Status::OK;
+ }
+ Status StreamedResponseStream(
+ ServerContext* /*context*/,
+ ServerSplitStreamer<EchoRequest, EchoResponse>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ uint32_t next_msg_sz;
+ stream->NextMessageSize(&next_msg_sz);
+ gpr_log(GPR_INFO, "Split Streamed Next Message Size is %u", next_msg_sz);
+ GPR_ASSERT(stream->Read(&req));
+ for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
resp.set_message(req.message() + ToString(i) + "_dup");
- GPR_ASSERT(stream->Write(resp));
- }
- return Status::OK;
- }
-};
-
-TEST_F(HybridEnd2endTest,
- AsyncRequestStreamResponseStream_FullyStreamedDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- FullyStreamedDupPkg dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendEchoToDupService();
- SendSimpleServerStreamingToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service with one async method.
-TEST_F(HybridEnd2endTest, AsyncRequestStreamResponseStream_AsyncDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
- SType;
- SType service;
- duplicate::EchoTestService::AsyncService dup_service;
- SetUpServer(&service, &dup_service, nullptr, nullptr);
- ResetStub();
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- std::thread echo_handler_thread(
- HandleEcho<duplicate::EchoTestService::AsyncService>, &dup_service,
- cqs_[2].get(), true);
- TestAllMethods();
- SendEchoToDupService();
- response_stream_handler_thread.join();
- request_stream_handler_thread.join();
- echo_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, GenericEcho) {
- EchoTestService::WithGenericMethod_Echo<TestServiceImpl> service;
- AsyncGenericService generic_service;
- SetUpServer(&service, nullptr, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- TestAllMethods();
- generic_handler_thread.join();
-}
-
-TEST_P(HybridEnd2endTest, CallbackGenericEcho) {
- EchoTestService::WithGenericMethod_Echo<TestServiceImpl> service;
+ GPR_ASSERT(stream->Write(resp));
+ }
+ return Status::OK;
+ }
+};
+
+TEST_F(HybridEnd2endTest,
+ AsyncRequestStreamResponseStream_FullyStreamedDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ FullyStreamedDupPkg dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr, 8192);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendEchoToDupService();
+ SendSimpleServerStreamingToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service with one async method.
+TEST_F(HybridEnd2endTest, AsyncRequestStreamResponseStream_AsyncDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>
+ SType;
+ SType service;
+ duplicate::EchoTestService::AsyncService dup_service;
+ SetUpServer(&service, &dup_service, nullptr, nullptr);
+ ResetStub();
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ std::thread echo_handler_thread(
+ HandleEcho<duplicate::EchoTestService::AsyncService>, &dup_service,
+ cqs_[2].get(), true);
+ TestAllMethods();
+ SendEchoToDupService();
+ response_stream_handler_thread.join();
+ request_stream_handler_thread.join();
+ echo_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, GenericEcho) {
+ EchoTestService::WithGenericMethod_Echo<TestServiceImpl> service;
+ AsyncGenericService generic_service;
+ SetUpServer(&service, nullptr, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ TestAllMethods();
+ generic_handler_thread.join();
+}
+
+TEST_P(HybridEnd2endTest, CallbackGenericEcho) {
+ EchoTestService::WithGenericMethod_Echo<TestServiceImpl> service;
class GenericEchoService : public CallbackGenericService {
- private:
+ private:
ServerGenericBidiReactor* CreateReactor(
GenericCallbackServerContext* context) override {
- EXPECT_EQ(context->method(), "/grpc.testing.EchoTestService/Echo");
+ EXPECT_EQ(context->method(), "/grpc.testing.EchoTestService/Echo");
gpr_log(GPR_DEBUG, "Constructor of generic service %d",
static_cast<int>(context->deadline().time_since_epoch().count()));
-
+
class Reactor : public ServerGenericBidiReactor {
- public:
- Reactor() { StartRead(&request_); }
-
- private:
- void OnDone() override { delete this; }
- void OnReadDone(bool ok) override {
- if (!ok) {
- EXPECT_EQ(reads_complete_, 1);
- } else {
- EXPECT_EQ(reads_complete_++, 0);
- response_ = request_;
- StartWrite(&response_);
- StartRead(&request_);
- }
- }
- void OnWriteDone(bool ok) override {
- Finish(ok ? Status::OK
- : Status(StatusCode::UNKNOWN, "Unexpected failure"));
- }
- ByteBuffer request_;
- ByteBuffer response_;
- std::atomic_int reads_complete_{0};
- };
- return new Reactor;
- }
- } generic_service;
-
- if (!SetUpServer(&service, nullptr, nullptr, &generic_service)) {
- return;
- }
- ResetStub();
- TestAllMethods();
-}
-
-TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStream) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
- SType;
- SType service;
- AsyncGenericService generic_service;
- SetUpServer(&service, nullptr, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- generic_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service with one sync method.
-TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStream_SyncDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
- SType;
- SType service;
- AsyncGenericService generic_service;
- TestServiceImplDupPkg dup_service;
- SetUpServer(&service, &dup_service, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- TestAllMethods();
- SendEchoToDupService();
- generic_handler_thread.join();
- request_stream_handler_thread.join();
-}
-
-// Add a second service with one async method.
-TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStream_AsyncDupService) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
- SType;
- SType service;
- AsyncGenericService generic_service;
- duplicate::EchoTestService::AsyncService dup_service;
- SetUpServer(&service, &dup_service, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- std::thread echo_handler_thread(
- HandleEcho<duplicate::EchoTestService::AsyncService>, &dup_service,
- cqs_[2].get(), true);
- TestAllMethods();
- SendEchoToDupService();
- generic_handler_thread.join();
- request_stream_handler_thread.join();
- echo_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStreamResponseStream) {
- typedef EchoTestService::WithAsyncMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>>
- SType;
- SType service;
- AsyncGenericService generic_service;
- SetUpServer(&service, nullptr, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
- &service, cqs_[1].get());
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[2].get());
- TestAllMethods();
- generic_handler_thread.join();
- request_stream_handler_thread.join();
- response_stream_handler_thread.join();
-}
-
-TEST_F(HybridEnd2endTest, GenericEchoRequestStreamAsyncResponseStream) {
- typedef EchoTestService::WithGenericMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>>
- SType;
- SType service;
- AsyncGenericService generic_service;
- SetUpServer(&service, nullptr, &generic_service, nullptr);
- ResetStub();
- std::thread generic_handler_thread(HandleGenericCall, &generic_service,
- cqs_[0].get());
- std::thread generic_handler_thread2(HandleGenericCall, &generic_service,
- cqs_[1].get());
- std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
- &service, cqs_[2].get());
- TestAllMethods();
- generic_handler_thread.join();
- generic_handler_thread2.join();
- response_stream_handler_thread.join();
-}
-
-// If WithGenericMethod is called and no generic service is registered, the
-// server will fail to build.
-TEST_F(HybridEnd2endTest, GenericMethodWithoutGenericService) {
- EchoTestService::WithGenericMethod_RequestStream<
- EchoTestService::WithGenericMethod_Echo<
- EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>>
- service;
- SetUpServer(&service, nullptr, nullptr, nullptr);
- EXPECT_EQ(nullptr, server_.get());
-}
-
-INSTANTIATE_TEST_SUITE_P(HybridEnd2endTest, HybridEnd2endTest,
- ::testing::Bool());
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ public:
+ Reactor() { StartRead(&request_); }
+
+ private:
+ void OnDone() override { delete this; }
+ void OnReadDone(bool ok) override {
+ if (!ok) {
+ EXPECT_EQ(reads_complete_, 1);
+ } else {
+ EXPECT_EQ(reads_complete_++, 0);
+ response_ = request_;
+ StartWrite(&response_);
+ StartRead(&request_);
+ }
+ }
+ void OnWriteDone(bool ok) override {
+ Finish(ok ? Status::OK
+ : Status(StatusCode::UNKNOWN, "Unexpected failure"));
+ }
+ ByteBuffer request_;
+ ByteBuffer response_;
+ std::atomic_int reads_complete_{0};
+ };
+ return new Reactor;
+ }
+ } generic_service;
+
+ if (!SetUpServer(&service, nullptr, nullptr, &generic_service)) {
+ return;
+ }
+ ResetStub();
+ TestAllMethods();
+}
+
+TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStream) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
+ SType;
+ SType service;
+ AsyncGenericService generic_service;
+ SetUpServer(&service, nullptr, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ generic_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service with one sync method.
+TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStream_SyncDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
+ SType;
+ SType service;
+ AsyncGenericService generic_service;
+ TestServiceImplDupPkg dup_service;
+ SetUpServer(&service, &dup_service, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ TestAllMethods();
+ SendEchoToDupService();
+ generic_handler_thread.join();
+ request_stream_handler_thread.join();
+}
+
+// Add a second service with one async method.
+TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStream_AsyncDupService) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<TestServiceImpl>>
+ SType;
+ SType service;
+ AsyncGenericService generic_service;
+ duplicate::EchoTestService::AsyncService dup_service;
+ SetUpServer(&service, &dup_service, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ std::thread echo_handler_thread(
+ HandleEcho<duplicate::EchoTestService::AsyncService>, &dup_service,
+ cqs_[2].get(), true);
+ TestAllMethods();
+ SendEchoToDupService();
+ generic_handler_thread.join();
+ request_stream_handler_thread.join();
+ echo_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, GenericEchoAsyncRequestStreamResponseStream) {
+ typedef EchoTestService::WithAsyncMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>>
+ SType;
+ SType service;
+ AsyncGenericService generic_service;
+ SetUpServer(&service, nullptr, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ std::thread request_stream_handler_thread(HandleClientStreaming<SType>,
+ &service, cqs_[1].get());
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[2].get());
+ TestAllMethods();
+ generic_handler_thread.join();
+ request_stream_handler_thread.join();
+ response_stream_handler_thread.join();
+}
+
+TEST_F(HybridEnd2endTest, GenericEchoRequestStreamAsyncResponseStream) {
+ typedef EchoTestService::WithGenericMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>>
+ SType;
+ SType service;
+ AsyncGenericService generic_service;
+ SetUpServer(&service, nullptr, &generic_service, nullptr);
+ ResetStub();
+ std::thread generic_handler_thread(HandleGenericCall, &generic_service,
+ cqs_[0].get());
+ std::thread generic_handler_thread2(HandleGenericCall, &generic_service,
+ cqs_[1].get());
+ std::thread response_stream_handler_thread(HandleServerStreaming<SType>,
+ &service, cqs_[2].get());
+ TestAllMethods();
+ generic_handler_thread.join();
+ generic_handler_thread2.join();
+ response_stream_handler_thread.join();
+}
+
+// If WithGenericMethod is called and no generic service is registered, the
+// server will fail to build.
+TEST_F(HybridEnd2endTest, GenericMethodWithoutGenericService) {
+ EchoTestService::WithGenericMethod_RequestStream<
+ EchoTestService::WithGenericMethod_Echo<
+ EchoTestService::WithAsyncMethod_ResponseStream<TestServiceImpl>>>
+ service;
+ SetUpServer(&service, nullptr, nullptr, nullptr);
+ EXPECT_EQ(nullptr, server_.get());
+}
+
+INSTANTIATE_TEST_SUITE_P(HybridEnd2endTest, HybridEnd2endTest,
+ ::testing::Bool());
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
index ff88953651..2d9bcfcbec 100644
--- a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
@@ -1,102 +1,102 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include "test/cpp/end2end/interceptors_util.h"
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include "test/cpp/end2end/interceptors_util.h"
#include <util/string/cast.h>
-
-namespace grpc {
-namespace testing {
-
-std::atomic<int> DummyInterceptor::num_times_run_;
-std::atomic<int> DummyInterceptor::num_times_run_reverse_;
-std::atomic<int> DummyInterceptor::num_times_cancel_;
-
-void MakeCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- Status s = stub->Echo(&ctx, req, &resp);
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), "Hello");
-}
-
-void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
+
+namespace grpc {
+namespace testing {
+
+std::atomic<int> DummyInterceptor::num_times_run_;
+std::atomic<int> DummyInterceptor::num_times_run_reverse_;
+std::atomic<int> DummyInterceptor::num_times_cancel_;
+
+void MakeCall(const std::shared_ptr<Channel>& channel) {
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ req.mutable_param()->set_echo_metadata(true);
+ ctx.AddMetadata("testkey", "testvalue");
+ req.set_message("Hello");
+ EchoResponse resp;
+ Status s = stub->Echo(&ctx, req, &resp);
+ EXPECT_EQ(s.ok(), true);
+ EXPECT_EQ(resp.message(), "Hello");
+}
+
+void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel) {
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ req.mutable_param()->set_echo_metadata(true);
+ ctx.AddMetadata("testkey", "testvalue");
+ req.set_message("Hello");
+ EchoResponse resp;
string expected_resp = "";
- auto writer = stub->RequestStream(&ctx, &resp);
- for (int i = 0; i < kNumStreamingMessages; i++) {
- writer->Write(req);
- expected_resp += "Hello";
- }
- writer->WritesDone();
- Status s = writer->Finish();
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), expected_resp);
-}
-
-void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
+ auto writer = stub->RequestStream(&ctx, &resp);
+ for (int i = 0; i < kNumStreamingMessages; i++) {
+ writer->Write(req);
+ expected_resp += "Hello";
+ }
+ writer->WritesDone();
+ Status s = writer->Finish();
+ EXPECT_EQ(s.ok(), true);
+ EXPECT_EQ(resp.message(), expected_resp);
+}
+
+void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel) {
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ req.mutable_param()->set_echo_metadata(true);
+ ctx.AddMetadata("testkey", "testvalue");
+ req.set_message("Hello");
+ EchoResponse resp;
+ auto reader = stub->ResponseStream(&ctx, req);
+ int count = 0;
+ while (reader->Read(&resp)) {
+ EXPECT_EQ(resp.message(), "Hello");
+ count++;
+ }
+ ASSERT_EQ(count, kNumStreamingMessages);
+ Status s = reader->Finish();
+ EXPECT_EQ(s.ok(), true);
+}
+
+void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ EchoResponse resp;
+ ctx.AddMetadata("testkey", "testvalue");
req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- auto reader = stub->ResponseStream(&ctx, req);
- int count = 0;
- while (reader->Read(&resp)) {
- EXPECT_EQ(resp.message(), "Hello");
- count++;
- }
- ASSERT_EQ(count, kNumStreamingMessages);
- Status s = reader->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- ctx.AddMetadata("testkey", "testvalue");
- req.mutable_param()->set_echo_metadata(true);
- auto stream = stub->BidiStream(&ctx);
- for (auto i = 0; i < kNumStreamingMessages; i++) {
+ auto stream = stub->BidiStream(&ctx);
+ for (auto i = 0; i < kNumStreamingMessages; i++) {
req.set_message(TString("Hello") + ::ToString(i));
- stream->Write(req);
- stream->Read(&resp);
- EXPECT_EQ(req.message(), resp.message());
- }
- ASSERT_TRUE(stream->WritesDone());
- Status s = stream->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
+ stream->Write(req);
+ stream->Read(&resp);
+ EXPECT_EQ(req.message(), resp.message());
+ }
+ ASSERT_TRUE(stream->WritesDone());
+ Status s = stream->Finish();
+ EXPECT_EQ(s.ok(), true);
+}
+
void MakeAsyncCQCall(const std::shared_ptr<Channel>& channel) {
auto stub = grpc::testing::EchoTestService::NewStub(channel);
CompletionQueue cq;
@@ -152,63 +152,63 @@ void MakeAsyncCQBidiStreamingCall(const std::shared_ptr<Channel>& /*channel*/) {
// TODO(yashykt) : Fill this out
}
-void MakeCallbackCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- stub->experimental_async()->Echo(&ctx, &req, &resp,
- [&resp, &mu, &done, &cv](Status s) {
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), "Hello");
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
- const string& key, const string& value) {
- for (const auto& pair : map) {
- if (pair.first.starts_with(key) && pair.second.starts_with(value)) {
- return true;
- }
- }
- return false;
-}
-
+void MakeCallbackCall(const std::shared_ptr<Channel>& channel) {
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ std::mutex mu;
+ std::condition_variable cv;
+ bool done = false;
+ req.mutable_param()->set_echo_metadata(true);
+ ctx.AddMetadata("testkey", "testvalue");
+ req.set_message("Hello");
+ EchoResponse resp;
+ stub->experimental_async()->Echo(&ctx, &req, &resp,
+ [&resp, &mu, &done, &cv](Status s) {
+ EXPECT_EQ(s.ok(), true);
+ EXPECT_EQ(resp.message(), "Hello");
+ std::lock_guard<std::mutex> l(mu);
+ done = true;
+ cv.notify_one();
+ });
+ std::unique_lock<std::mutex> l(mu);
+ while (!done) {
+ cv.wait(l);
+ }
+}
+
+bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
+ const string& key, const string& value) {
+ for (const auto& pair : map) {
+ if (pair.first.starts_with(key) && pair.second.starts_with(value)) {
+ return true;
+ }
+ }
+ return false;
+}
+
bool CheckMetadata(const std::multimap<TString, TString>& map,
- const string& key, const string& value) {
- for (const auto& pair : map) {
- if (pair.first == key.c_str() && pair.second == value.c_str()) {
- return true;
- }
- }
- return false;
-}
-
-std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
-CreateDummyClientInterceptors() {
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 dummy interceptors before hijacking interceptor
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- return creators;
-}
-
-} // namespace testing
-} // namespace grpc
+ const string& key, const string& value) {
+ for (const auto& pair : map) {
+ if (pair.first == key.c_str() && pair.second == value.c_str()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+CreateDummyClientInterceptors() {
+ std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ creators;
+ // Add 20 dummy interceptors before hijacking interceptor
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ return creators;
+}
+
+} // namespace testing
+} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
index c95170bbbc..832a3870c8 100644
--- a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
+++ b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
@@ -1,107 +1,107 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <condition_variable>
-
-#include <grpcpp/channel.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-/* This interceptor does nothing. Just keeps a global count on the number of
- * times it was invoked. */
-class DummyInterceptor : public experimental::Interceptor {
- public:
- DummyInterceptor() {}
-
- virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- num_times_run_++;
- } else if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::
- POST_RECV_INITIAL_METADATA)) {
- num_times_run_reverse_++;
- } else if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CANCEL)) {
- num_times_cancel_++;
- }
- methods->Proceed();
- }
-
- static void Reset() {
- num_times_run_.store(0);
- num_times_run_reverse_.store(0);
- num_times_cancel_.store(0);
- }
-
- static int GetNumTimesRun() {
- EXPECT_EQ(num_times_run_.load(), num_times_run_reverse_.load());
- return num_times_run_.load();
- }
-
- static int GetNumTimesCancel() { return num_times_cancel_.load(); }
-
- private:
- static std::atomic<int> num_times_run_;
- static std::atomic<int> num_times_run_reverse_;
- static std::atomic<int> num_times_cancel_;
-};
-
-class DummyInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface,
- public experimental::ServerInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* /*info*/) override {
- return new DummyInterceptor();
- }
-
- virtual experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* /*info*/) override {
- return new DummyInterceptor();
- }
-};
-
-/* This interceptor factory returns nullptr on interceptor creation */
-class NullInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface,
- public experimental::ServerInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* /*info*/) override {
- return nullptr;
- }
-
- virtual experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* /*info*/) override {
- return nullptr;
- }
-};
-
-class EchoTestServiceStreamingImpl : public EchoTestService::Service {
- public:
- ~EchoTestServiceStreamingImpl() override {}
-
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <condition_variable>
+
+#include <grpcpp/channel.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/cpp/util/string_ref_helper.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+/* This interceptor does nothing. Just keeps a global count on the number of
+ * times it was invoked. */
+class DummyInterceptor : public experimental::Interceptor {
+ public:
+ DummyInterceptor() {}
+
+ virtual void Intercept(experimental::InterceptorBatchMethods* methods) {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ num_times_run_++;
+ } else if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::
+ POST_RECV_INITIAL_METADATA)) {
+ num_times_run_reverse_++;
+ } else if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_CANCEL)) {
+ num_times_cancel_++;
+ }
+ methods->Proceed();
+ }
+
+ static void Reset() {
+ num_times_run_.store(0);
+ num_times_run_reverse_.store(0);
+ num_times_cancel_.store(0);
+ }
+
+ static int GetNumTimesRun() {
+ EXPECT_EQ(num_times_run_.load(), num_times_run_reverse_.load());
+ return num_times_run_.load();
+ }
+
+ static int GetNumTimesCancel() { return num_times_cancel_.load(); }
+
+ private:
+ static std::atomic<int> num_times_run_;
+ static std::atomic<int> num_times_run_reverse_;
+ static std::atomic<int> num_times_cancel_;
+};
+
+class DummyInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface,
+ public experimental::ServerInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* /*info*/) override {
+ return new DummyInterceptor();
+ }
+
+ virtual experimental::Interceptor* CreateServerInterceptor(
+ experimental::ServerRpcInfo* /*info*/) override {
+ return new DummyInterceptor();
+ }
+};
+
+/* This interceptor factory returns nullptr on interceptor creation */
+class NullInterceptorFactory
+ : public experimental::ClientInterceptorFactoryInterface,
+ public experimental::ServerInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateClientInterceptor(
+ experimental::ClientRpcInfo* /*info*/) override {
+ return nullptr;
+ }
+
+ virtual experimental::Interceptor* CreateServerInterceptor(
+ experimental::ServerRpcInfo* /*info*/) override {
+ return nullptr;
+ }
+};
+
+class EchoTestServiceStreamingImpl : public EchoTestService::Service {
+ public:
+ ~EchoTestServiceStreamingImpl() override {}
+
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
auto client_metadata = context->client_metadata();
@@ -112,66 +112,66 @@ class EchoTestServiceStreamingImpl : public EchoTestService::Service {
return Status::OK;
}
- Status BidiStream(
- ServerContext* context,
- grpc::ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- while (stream->Read(&req)) {
- resp.set_message(req.message());
- EXPECT_TRUE(stream->Write(resp, grpc::WriteOptions()));
- }
- return Status::OK;
- }
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
- EchoResponse* resp) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- EchoRequest req;
+ Status BidiStream(
+ ServerContext* context,
+ grpc::ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
+ EchoRequest req;
+ EchoResponse resp;
+ auto client_metadata = context->client_metadata();
+ for (const auto& pair : client_metadata) {
+ context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
+ }
+
+ while (stream->Read(&req)) {
+ resp.set_message(req.message());
+ EXPECT_TRUE(stream->Write(resp, grpc::WriteOptions()));
+ }
+ return Status::OK;
+ }
+
+ Status RequestStream(ServerContext* context,
+ ServerReader<EchoRequest>* reader,
+ EchoResponse* resp) override {
+ auto client_metadata = context->client_metadata();
+ for (const auto& pair : client_metadata) {
+ context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
+ }
+
+ EchoRequest req;
string response_str = "";
- while (reader->Read(&req)) {
- response_str += req.message();
- }
- resp->set_message(response_str);
- return Status::OK;
- }
-
- Status ResponseStream(ServerContext* context, const EchoRequest* req,
- ServerWriter<EchoResponse>* writer) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- EchoResponse resp;
- resp.set_message(req->message());
- for (int i = 0; i < 10; i++) {
- EXPECT_TRUE(writer->Write(resp));
- }
- return Status::OK;
- }
-};
-
-constexpr int kNumStreamingMessages = 10;
-
-void MakeCall(const std::shared_ptr<Channel>& channel);
-
-void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel);
-
+ while (reader->Read(&req)) {
+ response_str += req.message();
+ }
+ resp->set_message(response_str);
+ return Status::OK;
+ }
+
+ Status ResponseStream(ServerContext* context, const EchoRequest* req,
+ ServerWriter<EchoResponse>* writer) override {
+ auto client_metadata = context->client_metadata();
+ for (const auto& pair : client_metadata) {
+ context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
+ }
+
+ EchoResponse resp;
+ resp.set_message(req->message());
+ for (int i = 0; i < 10; i++) {
+ EXPECT_TRUE(writer->Write(resp));
+ }
+ return Status::OK;
+ }
+};
+
+constexpr int kNumStreamingMessages = 10;
+
+void MakeCall(const std::shared_ptr<Channel>& channel);
+
+void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel);
+
+void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel);
+
+void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel);
+
void MakeAsyncCQCall(const std::shared_ptr<Channel>& channel);
void MakeAsyncCQClientStreamingCall(const std::shared_ptr<Channel>& channel);
@@ -180,138 +180,138 @@ void MakeAsyncCQServerStreamingCall(const std::shared_ptr<Channel>& channel);
void MakeAsyncCQBidiStreamingCall(const std::shared_ptr<Channel>& channel);
-void MakeCallbackCall(const std::shared_ptr<Channel>& channel);
-
-bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
- const string& key, const string& value);
-
+void MakeCallbackCall(const std::shared_ptr<Channel>& channel);
+
+bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
+ const string& key, const string& value);
+
bool CheckMetadata(const std::multimap<TString, TString>& map,
- const string& key, const string& value);
-
-std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
-CreateDummyClientInterceptors();
-
-inline void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
-inline int detag(void* p) {
- return static_cast<int>(reinterpret_cast<intptr_t>(p));
-}
-
-class Verifier {
- public:
- Verifier() : lambda_run_(false) {}
- // Expect sets the expected ok value for a specific tag
- Verifier& Expect(int i, bool expect_ok) {
- return ExpectUnless(i, expect_ok, false);
- }
- // ExpectUnless sets the expected ok value for a specific tag
- // unless the tag was already marked seen (as a result of ExpectMaybe)
- Verifier& ExpectUnless(int i, bool expect_ok, bool seen) {
- if (!seen) {
- expectations_[tag(i)] = expect_ok;
- }
- return *this;
- }
- // ExpectMaybe sets the expected ok value for a specific tag, but does not
- // require it to appear
- // If it does, sets *seen to true
- Verifier& ExpectMaybe(int i, bool expect_ok, bool* seen) {
- if (!*seen) {
- maybe_expectations_[tag(i)] = MaybeExpect{expect_ok, seen};
- }
- return *this;
- }
-
- // Next waits for 1 async tag to complete, checks its
- // expectations, and returns the tag
- int Next(CompletionQueue* cq, bool ignore_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- GotTag(got_tag, ok, ignore_ok);
- return detag(got_tag);
- }
-
- template <typename T>
- CompletionQueue::NextStatus DoOnceThenAsyncNext(
- CompletionQueue* cq, void** got_tag, bool* ok, T deadline,
- std::function<void(void)> lambda) {
- if (lambda_run_) {
- return cq->AsyncNext(got_tag, ok, deadline);
- } else {
- lambda_run_ = true;
- return cq->DoThenAsyncNext(lambda, got_tag, ok, deadline);
- }
- }
-
- // Verify keeps calling Next until all currently set
- // expected tags are complete
- void Verify(CompletionQueue* cq) { Verify(cq, false); }
-
- // This version of Verify allows optionally ignoring the
- // outcome of the expectation
- void Verify(CompletionQueue* cq, bool ignore_ok) {
- GPR_ASSERT(!expectations_.empty() || !maybe_expectations_.empty());
- while (!expectations_.empty()) {
- Next(cq, ignore_ok);
- }
- }
-
- // This version of Verify stops after a certain deadline, and uses the
- // DoThenAsyncNext API
- // to call the lambda
- void Verify(CompletionQueue* cq,
- std::chrono::system_clock::time_point deadline,
- const std::function<void(void)>& lambda) {
- if (expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::TIMEOUT);
- } else {
- while (!expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::GOT_EVENT);
- GotTag(got_tag, ok, false);
- }
- }
- }
-
- private:
- void GotTag(void* got_tag, bool ok, bool ignore_ok) {
- auto it = expectations_.find(got_tag);
- if (it != expectations_.end()) {
- if (!ignore_ok) {
- EXPECT_EQ(it->second, ok);
- }
- expectations_.erase(it);
- } else {
- auto it2 = maybe_expectations_.find(got_tag);
- if (it2 != maybe_expectations_.end()) {
- if (it2->second.seen != nullptr) {
- EXPECT_FALSE(*it2->second.seen);
- *it2->second.seen = true;
- }
- if (!ignore_ok) {
- EXPECT_EQ(it2->second.ok, ok);
- }
- } else {
- gpr_log(GPR_ERROR, "Unexpected tag: %p", got_tag);
- abort();
- }
- }
- }
-
- struct MaybeExpect {
- bool ok;
- bool* seen;
- };
-
- std::map<void*, bool> expectations_;
- std::map<void*, MaybeExpect> maybe_expectations_;
- bool lambda_run_;
-};
-
-} // namespace testing
-} // namespace grpc
+ const string& key, const string& value);
+
+std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+CreateDummyClientInterceptors();
+
+inline void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
+inline int detag(void* p) {
+ return static_cast<int>(reinterpret_cast<intptr_t>(p));
+}
+
+class Verifier {
+ public:
+ Verifier() : lambda_run_(false) {}
+ // Expect sets the expected ok value for a specific tag
+ Verifier& Expect(int i, bool expect_ok) {
+ return ExpectUnless(i, expect_ok, false);
+ }
+ // ExpectUnless sets the expected ok value for a specific tag
+ // unless the tag was already marked seen (as a result of ExpectMaybe)
+ Verifier& ExpectUnless(int i, bool expect_ok, bool seen) {
+ if (!seen) {
+ expectations_[tag(i)] = expect_ok;
+ }
+ return *this;
+ }
+ // ExpectMaybe sets the expected ok value for a specific tag, but does not
+ // require it to appear
+ // If it does, sets *seen to true
+ Verifier& ExpectMaybe(int i, bool expect_ok, bool* seen) {
+ if (!*seen) {
+ maybe_expectations_[tag(i)] = MaybeExpect{expect_ok, seen};
+ }
+ return *this;
+ }
+
+ // Next waits for 1 async tag to complete, checks its
+ // expectations, and returns the tag
+ int Next(CompletionQueue* cq, bool ignore_ok) {
+ bool ok;
+ void* got_tag;
+ EXPECT_TRUE(cq->Next(&got_tag, &ok));
+ GotTag(got_tag, ok, ignore_ok);
+ return detag(got_tag);
+ }
+
+ template <typename T>
+ CompletionQueue::NextStatus DoOnceThenAsyncNext(
+ CompletionQueue* cq, void** got_tag, bool* ok, T deadline,
+ std::function<void(void)> lambda) {
+ if (lambda_run_) {
+ return cq->AsyncNext(got_tag, ok, deadline);
+ } else {
+ lambda_run_ = true;
+ return cq->DoThenAsyncNext(lambda, got_tag, ok, deadline);
+ }
+ }
+
+ // Verify keeps calling Next until all currently set
+ // expected tags are complete
+ void Verify(CompletionQueue* cq) { Verify(cq, false); }
+
+ // This version of Verify allows optionally ignoring the
+ // outcome of the expectation
+ void Verify(CompletionQueue* cq, bool ignore_ok) {
+ GPR_ASSERT(!expectations_.empty() || !maybe_expectations_.empty());
+ while (!expectations_.empty()) {
+ Next(cq, ignore_ok);
+ }
+ }
+
+ // This version of Verify stops after a certain deadline, and uses the
+ // DoThenAsyncNext API
+ // to call the lambda
+ void Verify(CompletionQueue* cq,
+ std::chrono::system_clock::time_point deadline,
+ const std::function<void(void)>& lambda) {
+ if (expectations_.empty()) {
+ bool ok;
+ void* got_tag;
+ EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
+ CompletionQueue::TIMEOUT);
+ } else {
+ while (!expectations_.empty()) {
+ bool ok;
+ void* got_tag;
+ EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
+ CompletionQueue::GOT_EVENT);
+ GotTag(got_tag, ok, false);
+ }
+ }
+ }
+
+ private:
+ void GotTag(void* got_tag, bool ok, bool ignore_ok) {
+ auto it = expectations_.find(got_tag);
+ if (it != expectations_.end()) {
+ if (!ignore_ok) {
+ EXPECT_EQ(it->second, ok);
+ }
+ expectations_.erase(it);
+ } else {
+ auto it2 = maybe_expectations_.find(got_tag);
+ if (it2 != maybe_expectations_.end()) {
+ if (it2->second.seen != nullptr) {
+ EXPECT_FALSE(*it2->second.seen);
+ *it2->second.seen = true;
+ }
+ if (!ignore_ok) {
+ EXPECT_EQ(it2->second.ok, ok);
+ }
+ } else {
+ gpr_log(GPR_ERROR, "Unexpected tag: %p", got_tag);
+ abort();
+ }
+ }
+ }
+
+ struct MaybeExpect {
+ bool ok;
+ bool* seen;
+ };
+
+ std::map<void*, bool> expectations_;
+ std::map<void*, MaybeExpect> maybe_expectations_;
+ bool lambda_run_;
+};
+
+} // namespace testing
+} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/mock_test.cc b/contrib/libs/grpc/test/cpp/end2end/mock_test.cc
index a3d61c4e98..623fac0020 100644
--- a/contrib/libs/grpc/test/cpp/end2end/mock_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/mock_test.cc
@@ -1,47 +1,47 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <climits>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/test/default_reactor_test_peer.h>
-
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "src/proto/grpc/testing/echo_mock.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-
-#include <grpcpp/test/mock_stream.h>
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include <iostream>
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <climits>
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/test/default_reactor_test_peer.h>
+
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "src/proto/grpc/testing/echo_mock.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+
+#include <grpcpp/test/mock_stream.h>
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <iostream>
+
using grpc::testing::DefaultReactorTestPeer;
using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
@@ -50,385 +50,385 @@ using grpc::testing::MockClientReaderWriter;
using std::vector;
using std::chrono::system_clock;
using ::testing::_;
-using ::testing::AtLeast;
-using ::testing::DoAll;
-using ::testing::Invoke;
-using ::testing::Return;
-using ::testing::SaveArg;
-using ::testing::SetArgPointee;
-using ::testing::WithArg;
-
-namespace grpc {
-namespace testing {
-
-namespace {
-class FakeClient {
- public:
- explicit FakeClient(EchoTestService::StubInterface* stub) : stub_(stub) {}
-
- void DoEcho() {
- ClientContext context;
- EchoRequest request;
- EchoResponse response;
- request.set_message("hello world");
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(request.message(), response.message());
- EXPECT_TRUE(s.ok());
- }
-
- void DoRequestStream() {
- EchoRequest request;
- EchoResponse response;
-
- ClientContext context;
+using ::testing::AtLeast;
+using ::testing::DoAll;
+using ::testing::Invoke;
+using ::testing::Return;
+using ::testing::SaveArg;
+using ::testing::SetArgPointee;
+using ::testing::WithArg;
+
+namespace grpc {
+namespace testing {
+
+namespace {
+class FakeClient {
+ public:
+ explicit FakeClient(EchoTestService::StubInterface* stub) : stub_(stub) {}
+
+ void DoEcho() {
+ ClientContext context;
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("hello world");
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(request.message(), response.message());
+ EXPECT_TRUE(s.ok());
+ }
+
+ void DoRequestStream() {
+ EchoRequest request;
+ EchoResponse response;
+
+ ClientContext context;
TString msg("hello");
TString exp(msg);
-
- std::unique_ptr<ClientWriterInterface<EchoRequest>> cstream =
- stub_->RequestStream(&context, &response);
-
- request.set_message(msg);
- EXPECT_TRUE(cstream->Write(request));
-
- msg = ", world";
- request.set_message(msg);
- exp.append(msg);
- EXPECT_TRUE(cstream->Write(request));
-
- cstream->WritesDone();
- Status s = cstream->Finish();
-
- EXPECT_EQ(exp, response.message());
- EXPECT_TRUE(s.ok());
- }
-
- void DoResponseStream() {
- EchoRequest request;
- EchoResponse response;
- request.set_message("hello world");
-
- ClientContext context;
- std::unique_ptr<ClientReaderInterface<EchoResponse>> cstream =
- stub_->ResponseStream(&context, request);
-
+
+ std::unique_ptr<ClientWriterInterface<EchoRequest>> cstream =
+ stub_->RequestStream(&context, &response);
+
+ request.set_message(msg);
+ EXPECT_TRUE(cstream->Write(request));
+
+ msg = ", world";
+ request.set_message(msg);
+ exp.append(msg);
+ EXPECT_TRUE(cstream->Write(request));
+
+ cstream->WritesDone();
+ Status s = cstream->Finish();
+
+ EXPECT_EQ(exp, response.message());
+ EXPECT_TRUE(s.ok());
+ }
+
+ void DoResponseStream() {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("hello world");
+
+ ClientContext context;
+ std::unique_ptr<ClientReaderInterface<EchoResponse>> cstream =
+ stub_->ResponseStream(&context, request);
+
TString exp = "";
- EXPECT_TRUE(cstream->Read(&response));
- exp.append(response.message() + " ");
-
- EXPECT_TRUE(cstream->Read(&response));
- exp.append(response.message());
-
- EXPECT_FALSE(cstream->Read(&response));
- EXPECT_EQ(request.message(), exp);
-
- Status s = cstream->Finish();
- EXPECT_TRUE(s.ok());
- }
-
- void DoBidiStream() {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
+ EXPECT_TRUE(cstream->Read(&response));
+ exp.append(response.message() + " ");
+
+ EXPECT_TRUE(cstream->Read(&response));
+ exp.append(response.message());
+
+ EXPECT_FALSE(cstream->Read(&response));
+ EXPECT_EQ(request.message(), exp);
+
+ Status s = cstream->Finish();
+ EXPECT_TRUE(s.ok());
+ }
+
+ void DoBidiStream() {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
TString msg("hello");
-
- std::unique_ptr<ClientReaderWriterInterface<EchoRequest, EchoResponse>>
- stream = stub_->BidiStream(&context);
-
- request.set_message(msg + "0");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "1");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- request.set_message(msg + "2");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(response.message(), request.message());
-
- stream->WritesDone();
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- EXPECT_TRUE(s.ok());
- }
-
- void ResetStub(EchoTestService::StubInterface* stub) { stub_ = stub; }
-
- private:
- EchoTestService::StubInterface* stub_;
-};
-
-class CallbackTestServiceImpl
- : public EchoTestService::ExperimentalCallbackService {
- public:
- experimental::ServerUnaryReactor* Echo(
- experimental::CallbackServerContext* context, const EchoRequest* request,
- EchoResponse* response) override {
- // Make the mock service explicitly treat empty input messages as invalid
- // arguments so that we can test various results of status. In general, a
- // mocked service should just use the original service methods, but we are
- // adding this variance in Status return value just to improve coverage in
- // this test.
- auto* reactor = context->DefaultReactor();
- if (request->message().length() > 0) {
- response->set_message(request->message());
- reactor->Finish(Status::OK);
- } else {
- reactor->Finish(Status(StatusCode::INVALID_ARGUMENT, "Invalid request"));
- }
- return reactor;
- }
-};
-
-class MockCallbackTest : public ::testing::Test {
- protected:
- CallbackTestServiceImpl service_;
- ServerContext context_;
-};
-
-TEST_F(MockCallbackTest, MockedCallSucceedsWithWait) {
- experimental::CallbackServerContext ctx;
- EchoRequest req;
- EchoResponse resp;
- grpc::internal::Mutex mu;
- grpc::internal::CondVar cv;
- grpc::Status status;
- bool status_set = false;
- DefaultReactorTestPeer peer(&ctx, [&](::grpc::Status s) {
- grpc::internal::MutexLock l(&mu);
- status_set = true;
- status = std::move(s);
- cv.Signal();
- });
-
- req.set_message("mock 1");
- auto* reactor = service_.Echo(&ctx, &req, &resp);
- cv.WaitUntil(&mu, [&] {
- grpc::internal::MutexLock l(&mu);
- return status_set;
- });
- EXPECT_EQ(reactor, peer.reactor());
- EXPECT_TRUE(peer.test_status_set());
- EXPECT_TRUE(peer.test_status().ok());
- EXPECT_TRUE(status_set);
- EXPECT_TRUE(status.ok());
- EXPECT_EQ(req.message(), resp.message());
-}
-
-TEST_F(MockCallbackTest, MockedCallSucceeds) {
- experimental::CallbackServerContext ctx;
- EchoRequest req;
- EchoResponse resp;
- DefaultReactorTestPeer peer(&ctx);
-
- req.set_message("ha ha, consider yourself mocked.");
- auto* reactor = service_.Echo(&ctx, &req, &resp);
- EXPECT_EQ(reactor, peer.reactor());
- EXPECT_TRUE(peer.test_status_set());
- EXPECT_TRUE(peer.test_status().ok());
-}
-
-TEST_F(MockCallbackTest, MockedCallFails) {
- experimental::CallbackServerContext ctx;
- EchoRequest req;
- EchoResponse resp;
- DefaultReactorTestPeer peer(&ctx);
-
- auto* reactor = service_.Echo(&ctx, &req, &resp);
- EXPECT_EQ(reactor, peer.reactor());
- EXPECT_TRUE(peer.test_status_set());
- EXPECT_EQ(peer.test_status().error_code(), StatusCode::INVALID_ARGUMENT);
-}
-
-class TestServiceImpl : public EchoTestService::Service {
- public:
- Status Echo(ServerContext* /*context*/, const EchoRequest* request,
- EchoResponse* response) override {
- response->set_message(request->message());
- return Status::OK;
- }
-
- Status RequestStream(ServerContext* /*context*/,
- ServerReader<EchoRequest>* reader,
- EchoResponse* response) override {
- EchoRequest request;
+
+ std::unique_ptr<ClientReaderWriterInterface<EchoRequest, EchoResponse>>
+ stream = stub_->BidiStream(&context);
+
+ request.set_message(msg + "0");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "1");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ request.set_message(msg + "2");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(response.message(), request.message());
+
+ stream->WritesDone();
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ EXPECT_TRUE(s.ok());
+ }
+
+ void ResetStub(EchoTestService::StubInterface* stub) { stub_ = stub; }
+
+ private:
+ EchoTestService::StubInterface* stub_;
+};
+
+class CallbackTestServiceImpl
+ : public EchoTestService::ExperimentalCallbackService {
+ public:
+ experimental::ServerUnaryReactor* Echo(
+ experimental::CallbackServerContext* context, const EchoRequest* request,
+ EchoResponse* response) override {
+ // Make the mock service explicitly treat empty input messages as invalid
+ // arguments so that we can test various results of status. In general, a
+ // mocked service should just use the original service methods, but we are
+ // adding this variance in Status return value just to improve coverage in
+ // this test.
+ auto* reactor = context->DefaultReactor();
+ if (request->message().length() > 0) {
+ response->set_message(request->message());
+ reactor->Finish(Status::OK);
+ } else {
+ reactor->Finish(Status(StatusCode::INVALID_ARGUMENT, "Invalid request"));
+ }
+ return reactor;
+ }
+};
+
+class MockCallbackTest : public ::testing::Test {
+ protected:
+ CallbackTestServiceImpl service_;
+ ServerContext context_;
+};
+
+TEST_F(MockCallbackTest, MockedCallSucceedsWithWait) {
+ experimental::CallbackServerContext ctx;
+ EchoRequest req;
+ EchoResponse resp;
+ grpc::internal::Mutex mu;
+ grpc::internal::CondVar cv;
+ grpc::Status status;
+ bool status_set = false;
+ DefaultReactorTestPeer peer(&ctx, [&](::grpc::Status s) {
+ grpc::internal::MutexLock l(&mu);
+ status_set = true;
+ status = std::move(s);
+ cv.Signal();
+ });
+
+ req.set_message("mock 1");
+ auto* reactor = service_.Echo(&ctx, &req, &resp);
+ cv.WaitUntil(&mu, [&] {
+ grpc::internal::MutexLock l(&mu);
+ return status_set;
+ });
+ EXPECT_EQ(reactor, peer.reactor());
+ EXPECT_TRUE(peer.test_status_set());
+ EXPECT_TRUE(peer.test_status().ok());
+ EXPECT_TRUE(status_set);
+ EXPECT_TRUE(status.ok());
+ EXPECT_EQ(req.message(), resp.message());
+}
+
+TEST_F(MockCallbackTest, MockedCallSucceeds) {
+ experimental::CallbackServerContext ctx;
+ EchoRequest req;
+ EchoResponse resp;
+ DefaultReactorTestPeer peer(&ctx);
+
+ req.set_message("ha ha, consider yourself mocked.");
+ auto* reactor = service_.Echo(&ctx, &req, &resp);
+ EXPECT_EQ(reactor, peer.reactor());
+ EXPECT_TRUE(peer.test_status_set());
+ EXPECT_TRUE(peer.test_status().ok());
+}
+
+TEST_F(MockCallbackTest, MockedCallFails) {
+ experimental::CallbackServerContext ctx;
+ EchoRequest req;
+ EchoResponse resp;
+ DefaultReactorTestPeer peer(&ctx);
+
+ auto* reactor = service_.Echo(&ctx, &req, &resp);
+ EXPECT_EQ(reactor, peer.reactor());
+ EXPECT_TRUE(peer.test_status_set());
+ EXPECT_EQ(peer.test_status().error_code(), StatusCode::INVALID_ARGUMENT);
+}
+
+class TestServiceImpl : public EchoTestService::Service {
+ public:
+ Status Echo(ServerContext* /*context*/, const EchoRequest* request,
+ EchoResponse* response) override {
+ response->set_message(request->message());
+ return Status::OK;
+ }
+
+ Status RequestStream(ServerContext* /*context*/,
+ ServerReader<EchoRequest>* reader,
+ EchoResponse* response) override {
+ EchoRequest request;
TString resp("");
- while (reader->Read(&request)) {
- gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
- resp.append(request.message());
- }
- response->set_message(resp);
- return Status::OK;
- }
-
- Status ResponseStream(ServerContext* /*context*/, const EchoRequest* request,
- ServerWriter<EchoResponse>* writer) override {
- EchoResponse response;
+ while (reader->Read(&request)) {
+ gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
+ resp.append(request.message());
+ }
+ response->set_message(resp);
+ return Status::OK;
+ }
+
+ Status ResponseStream(ServerContext* /*context*/, const EchoRequest* request,
+ ServerWriter<EchoResponse>* writer) override {
+ EchoResponse response;
vector<TString> tokens = split(request->message());
for (const TString& token : tokens) {
- response.set_message(token);
- writer->Write(response);
- }
- return Status::OK;
- }
-
- Status BidiStream(
- ServerContext* /*context*/,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- EchoRequest request;
- EchoResponse response;
- while (stream->Read(&request)) {
- gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
- response.set_message(request.message());
- stream->Write(response);
- }
- return Status::OK;
- }
-
- private:
+ response.set_message(token);
+ writer->Write(response);
+ }
+ return Status::OK;
+ }
+
+ Status BidiStream(
+ ServerContext* /*context*/,
+ ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
+ EchoRequest request;
+ EchoResponse response;
+ while (stream->Read(&request)) {
+ gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
+ response.set_message(request.message());
+ stream->Write(response);
+ }
+ return Status::OK;
+ }
+
+ private:
const vector<TString> split(const TString& input) {
TString buff("");
vector<TString> result;
-
- for (auto n : input) {
- if (n != ' ') {
- buff += n;
- continue;
- }
- if (buff == "") continue;
- result.push_back(buff);
- buff = "";
- }
- if (buff != "") result.push_back(buff);
-
- return result;
- }
-};
-
-class MockTest : public ::testing::Test {
- protected:
- MockTest() {}
-
- void SetUp() override {
- int port = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port;
- // Setup server
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- InsecureServerCredentials());
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override { server_->Shutdown(); }
-
- void ResetStub() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- TestServiceImpl service_;
-};
-
-// Do one real rpc and one mocked one
-TEST_F(MockTest, SimpleRpc) {
- ResetStub();
- FakeClient client(stub_.get());
- client.DoEcho();
- MockEchoTestServiceStub stub;
- EchoResponse resp;
- resp.set_message("hello world");
- EXPECT_CALL(stub, Echo(_, _, _))
- .Times(AtLeast(1))
- .WillOnce(DoAll(SetArgPointee<2>(resp), Return(Status::OK)));
- client.ResetStub(&stub);
- client.DoEcho();
-}
-
-TEST_F(MockTest, ClientStream) {
- ResetStub();
- FakeClient client(stub_.get());
- client.DoRequestStream();
-
- MockEchoTestServiceStub stub;
- auto w = new MockClientWriter<EchoRequest>();
- EchoResponse resp;
- resp.set_message("hello, world");
-
- EXPECT_CALL(*w, Write(_, _)).Times(2).WillRepeatedly(Return(true));
- EXPECT_CALL(*w, WritesDone());
- EXPECT_CALL(*w, Finish()).WillOnce(Return(Status::OK));
-
- EXPECT_CALL(stub, RequestStreamRaw(_, _))
- .WillOnce(DoAll(SetArgPointee<1>(resp), Return(w)));
- client.ResetStub(&stub);
- client.DoRequestStream();
-}
-
-TEST_F(MockTest, ServerStream) {
- ResetStub();
- FakeClient client(stub_.get());
- client.DoResponseStream();
-
- MockEchoTestServiceStub stub;
- auto r = new MockClientReader<EchoResponse>();
- EchoResponse resp1;
- resp1.set_message("hello");
- EchoResponse resp2;
- resp2.set_message("world");
-
- EXPECT_CALL(*r, Read(_))
- .WillOnce(DoAll(SetArgPointee<0>(resp1), Return(true)))
- .WillOnce(DoAll(SetArgPointee<0>(resp2), Return(true)))
- .WillOnce(Return(false));
- EXPECT_CALL(*r, Finish()).WillOnce(Return(Status::OK));
-
- EXPECT_CALL(stub, ResponseStreamRaw(_, _)).WillOnce(Return(r));
-
- client.ResetStub(&stub);
- client.DoResponseStream();
-}
-
-ACTION_P(copy, msg) { arg0->set_message(msg->message()); }
-
-TEST_F(MockTest, BidiStream) {
- ResetStub();
- FakeClient client(stub_.get());
- client.DoBidiStream();
- MockEchoTestServiceStub stub;
- auto rw = new MockClientReaderWriter<EchoRequest, EchoResponse>();
- EchoRequest msg;
-
- EXPECT_CALL(*rw, Write(_, _))
- .Times(3)
- .WillRepeatedly(DoAll(SaveArg<0>(&msg), Return(true)));
- EXPECT_CALL(*rw, Read(_))
- .WillOnce(DoAll(WithArg<0>(copy(&msg)), Return(true)))
- .WillOnce(DoAll(WithArg<0>(copy(&msg)), Return(true)))
- .WillOnce(DoAll(WithArg<0>(copy(&msg)), Return(true)))
- .WillOnce(Return(false));
- EXPECT_CALL(*rw, WritesDone());
- EXPECT_CALL(*rw, Finish()).WillOnce(Return(Status::OK));
-
- EXPECT_CALL(stub, BidiStreamRaw(_)).WillOnce(Return(rw));
- client.ResetStub(&stub);
- client.DoBidiStream();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+
+ for (auto n : input) {
+ if (n != ' ') {
+ buff += n;
+ continue;
+ }
+ if (buff == "") continue;
+ result.push_back(buff);
+ buff = "";
+ }
+ if (buff != "") result.push_back(buff);
+
+ return result;
+ }
+};
+
+class MockTest : public ::testing::Test {
+ protected:
+ MockTest() {}
+
+ void SetUp() override {
+ int port = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port;
+ // Setup server
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ }
+
+ void TearDown() override { server_->Shutdown(); }
+
+ void ResetStub() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+ TestServiceImpl service_;
+};
+
+// Do one real rpc and one mocked one
+TEST_F(MockTest, SimpleRpc) {
+ ResetStub();
+ FakeClient client(stub_.get());
+ client.DoEcho();
+ MockEchoTestServiceStub stub;
+ EchoResponse resp;
+ resp.set_message("hello world");
+ EXPECT_CALL(stub, Echo(_, _, _))
+ .Times(AtLeast(1))
+ .WillOnce(DoAll(SetArgPointee<2>(resp), Return(Status::OK)));
+ client.ResetStub(&stub);
+ client.DoEcho();
+}
+
+TEST_F(MockTest, ClientStream) {
+ ResetStub();
+ FakeClient client(stub_.get());
+ client.DoRequestStream();
+
+ MockEchoTestServiceStub stub;
+ auto w = new MockClientWriter<EchoRequest>();
+ EchoResponse resp;
+ resp.set_message("hello, world");
+
+ EXPECT_CALL(*w, Write(_, _)).Times(2).WillRepeatedly(Return(true));
+ EXPECT_CALL(*w, WritesDone());
+ EXPECT_CALL(*w, Finish()).WillOnce(Return(Status::OK));
+
+ EXPECT_CALL(stub, RequestStreamRaw(_, _))
+ .WillOnce(DoAll(SetArgPointee<1>(resp), Return(w)));
+ client.ResetStub(&stub);
+ client.DoRequestStream();
+}
+
+TEST_F(MockTest, ServerStream) {
+ ResetStub();
+ FakeClient client(stub_.get());
+ client.DoResponseStream();
+
+ MockEchoTestServiceStub stub;
+ auto r = new MockClientReader<EchoResponse>();
+ EchoResponse resp1;
+ resp1.set_message("hello");
+ EchoResponse resp2;
+ resp2.set_message("world");
+
+ EXPECT_CALL(*r, Read(_))
+ .WillOnce(DoAll(SetArgPointee<0>(resp1), Return(true)))
+ .WillOnce(DoAll(SetArgPointee<0>(resp2), Return(true)))
+ .WillOnce(Return(false));
+ EXPECT_CALL(*r, Finish()).WillOnce(Return(Status::OK));
+
+ EXPECT_CALL(stub, ResponseStreamRaw(_, _)).WillOnce(Return(r));
+
+ client.ResetStub(&stub);
+ client.DoResponseStream();
+}
+
+ACTION_P(copy, msg) { arg0->set_message(msg->message()); }
+
+TEST_F(MockTest, BidiStream) {
+ ResetStub();
+ FakeClient client(stub_.get());
+ client.DoBidiStream();
+ MockEchoTestServiceStub stub;
+ auto rw = new MockClientReaderWriter<EchoRequest, EchoResponse>();
+ EchoRequest msg;
+
+ EXPECT_CALL(*rw, Write(_, _))
+ .Times(3)
+ .WillRepeatedly(DoAll(SaveArg<0>(&msg), Return(true)));
+ EXPECT_CALL(*rw, Read(_))
+ .WillOnce(DoAll(WithArg<0>(copy(&msg)), Return(true)))
+ .WillOnce(DoAll(WithArg<0>(copy(&msg)), Return(true)))
+ .WillOnce(DoAll(WithArg<0>(copy(&msg)), Return(true)))
+ .WillOnce(Return(false));
+ EXPECT_CALL(*rw, WritesDone());
+ EXPECT_CALL(*rw, Finish()).WillOnce(Return(Status::OK));
+
+ EXPECT_CALL(stub, BidiStreamRaw(_)).WillOnce(Return(rw));
+ client.ResetStub(&stub);
+ client.DoBidiStream();
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/nonblocking_test.cc b/contrib/libs/grpc/test/cpp/end2end/nonblocking_test.cc
index 4be070ec71..37e696adaa 100644
--- a/contrib/libs/grpc/test/cpp/end2end/nonblocking_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/nonblocking_test.cc
@@ -1,203 +1,203 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <memory>
-
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/iomgr/port.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-
-#ifdef GRPC_POSIX_SOCKET
-#include "src/core/lib/iomgr/ev_posix.h"
-#endif // GRPC_POSIX_SOCKET
-
-#include <gtest/gtest.h>
-
-#ifdef GRPC_POSIX_SOCKET
-// Thread-local variable to so that only polls from this test assert
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <memory>
+
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/lib/gpr/tls.h"
+#include "src/core/lib/iomgr/port.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+
+#ifdef GRPC_POSIX_SOCKET
+#include "src/core/lib/iomgr/ev_posix.h"
+#endif // GRPC_POSIX_SOCKET
+
+#include <gtest/gtest.h>
+
+#ifdef GRPC_POSIX_SOCKET
+// Thread-local variable to so that only polls from this test assert
// non-blocking (not polls from resolver, timer thread, etc), and only when the
// thread is waiting on polls caused by CompletionQueue::AsyncNext (not for
// picking a port or other reasons).
GPR_TLS_DECL(g_is_nonblocking_poll);
-
-namespace {
-
-int maybe_assert_non_blocking_poll(struct pollfd* pfds, nfds_t nfds,
- int timeout) {
+
+namespace {
+
+int maybe_assert_non_blocking_poll(struct pollfd* pfds, nfds_t nfds,
+ int timeout) {
// Only assert that this poll should have zero timeout if we're in the
// middle of a zero-timeout CQ Next.
if (gpr_tls_get(&g_is_nonblocking_poll)) {
- GPR_ASSERT(timeout == 0);
- }
- return poll(pfds, nfds, timeout);
-}
-
-} // namespace
-
-namespace grpc {
-namespace testing {
-namespace {
-
-void* tag(int i) { return reinterpret_cast<void*>(static_cast<intptr_t>(i)); }
-int detag(void* p) { return static_cast<int>(reinterpret_cast<intptr_t>(p)); }
-
-class NonblockingTest : public ::testing::Test {
- protected:
- NonblockingTest() {}
-
- void SetUp() override {
- port_ = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port_;
-
- // Setup server
- BuildAndStartServer();
- }
-
- bool LoopForTag(void** tag, bool* ok) {
+ GPR_ASSERT(timeout == 0);
+ }
+ return poll(pfds, nfds, timeout);
+}
+
+} // namespace
+
+namespace grpc {
+namespace testing {
+namespace {
+
+void* tag(int i) { return reinterpret_cast<void*>(static_cast<intptr_t>(i)); }
+int detag(void* p) { return static_cast<int>(reinterpret_cast<intptr_t>(p)); }
+
+class NonblockingTest : public ::testing::Test {
+ protected:
+ NonblockingTest() {}
+
+ void SetUp() override {
+ port_ = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port_;
+
+ // Setup server
+ BuildAndStartServer();
+ }
+
+ bool LoopForTag(void** tag, bool* ok) {
// Temporarily set the thread-local nonblocking poll flag so that the polls
// caused by this loop are indeed sent by the library with zero timeout.
intptr_t orig_val = gpr_tls_get(&g_is_nonblocking_poll);
gpr_tls_set(&g_is_nonblocking_poll, static_cast<intptr_t>(true));
- for (;;) {
- auto r = cq_->AsyncNext(tag, ok, gpr_time_0(GPR_CLOCK_REALTIME));
- if (r == CompletionQueue::SHUTDOWN) {
+ for (;;) {
+ auto r = cq_->AsyncNext(tag, ok, gpr_time_0(GPR_CLOCK_REALTIME));
+ if (r == CompletionQueue::SHUTDOWN) {
gpr_tls_set(&g_is_nonblocking_poll, orig_val);
- return false;
- } else if (r == CompletionQueue::GOT_EVENT) {
+ return false;
+ } else if (r == CompletionQueue::GOT_EVENT) {
gpr_tls_set(&g_is_nonblocking_poll, orig_val);
- return true;
- }
- }
- }
-
- void TearDown() override {
- server_->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- cq_->Shutdown();
- while (LoopForTag(&ignored_tag, &ignored_ok))
- ;
- stub_.reset();
- grpc_recycle_unused_port(port_);
- }
-
- void BuildAndStartServer() {
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- grpc::InsecureServerCredentials());
- service_.reset(new grpc::testing::EchoTestService::AsyncService());
- builder.RegisterService(service_.get());
- cq_ = builder.AddCompletionQueue();
- server_ = builder.BuildAndStart();
- }
-
- void ResetStub() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), grpc::InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- void SendRpc(int num_rpcs) {
- for (int i = 0; i < num_rpcs; i++) {
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message("hello non-blocking world");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->PrepareAsyncEcho(&cli_ctx, send_request, cq_.get()));
-
- response_reader->StartCall();
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- service_->RequestEcho(&srv_ctx, &recv_request, &response_writer,
- cq_.get(), cq_.get(), tag(2));
-
- void* got_tag;
- bool ok;
- EXPECT_TRUE(LoopForTag(&got_tag, &ok));
- EXPECT_TRUE(ok);
- EXPECT_EQ(detag(got_tag), 2);
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
-
- int tagsum = 0;
- int tagprod = 1;
- EXPECT_TRUE(LoopForTag(&got_tag, &ok));
- EXPECT_TRUE(ok);
- tagsum += detag(got_tag);
- tagprod *= detag(got_tag);
-
- EXPECT_TRUE(LoopForTag(&got_tag, &ok));
- EXPECT_TRUE(ok);
- tagsum += detag(got_tag);
- tagprod *= detag(got_tag);
-
- EXPECT_EQ(tagsum, 7);
- EXPECT_EQ(tagprod, 12);
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- }
- }
-
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::unique_ptr<grpc::testing::EchoTestService::AsyncService> service_;
- std::ostringstream server_address_;
- int port_;
-};
-
-TEST_F(NonblockingTest, SimpleRpc) {
- ResetStub();
- SendRpc(10);
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_POSIX_SOCKET
-
-int main(int argc, char** argv) {
-#ifdef GRPC_POSIX_SOCKET
- // Override the poll function before anything else can happen
- grpc_poll_function = maybe_assert_non_blocking_poll;
-
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
+ return true;
+ }
+ }
+ }
+
+ void TearDown() override {
+ server_->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ cq_->Shutdown();
+ while (LoopForTag(&ignored_tag, &ignored_ok))
+ ;
+ stub_.reset();
+ grpc_recycle_unused_port(port_);
+ }
+
+ void BuildAndStartServer() {
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ grpc::InsecureServerCredentials());
+ service_.reset(new grpc::testing::EchoTestService::AsyncService());
+ builder.RegisterService(service_.get());
+ cq_ = builder.AddCompletionQueue();
+ server_ = builder.BuildAndStart();
+ }
+
+ void ResetStub() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), grpc::InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ void SendRpc(int num_rpcs) {
+ for (int i = 0; i < num_rpcs; i++) {
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message("hello non-blocking world");
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->PrepareAsyncEcho(&cli_ctx, send_request, cq_.get()));
+
+ response_reader->StartCall();
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ service_->RequestEcho(&srv_ctx, &recv_request, &response_writer,
+ cq_.get(), cq_.get(), tag(2));
+
+ void* got_tag;
+ bool ok;
+ EXPECT_TRUE(LoopForTag(&got_tag, &ok));
+ EXPECT_TRUE(ok);
+ EXPECT_EQ(detag(got_tag), 2);
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(3));
+
+ int tagsum = 0;
+ int tagprod = 1;
+ EXPECT_TRUE(LoopForTag(&got_tag, &ok));
+ EXPECT_TRUE(ok);
+ tagsum += detag(got_tag);
+ tagprod *= detag(got_tag);
+
+ EXPECT_TRUE(LoopForTag(&got_tag, &ok));
+ EXPECT_TRUE(ok);
+ tagsum += detag(got_tag);
+ tagprod *= detag(got_tag);
+
+ EXPECT_EQ(tagsum, 7);
+ EXPECT_EQ(tagprod, 12);
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ }
+ }
+
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::unique_ptr<grpc::testing::EchoTestService::AsyncService> service_;
+ std::ostringstream server_address_;
+ int port_;
+};
+
+TEST_F(NonblockingTest, SimpleRpc) {
+ ResetStub();
+ SendRpc(10);
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+#endif // GRPC_POSIX_SOCKET
+
+int main(int argc, char** argv) {
+#ifdef GRPC_POSIX_SOCKET
+ // Override the poll function before anything else can happen
+ grpc_poll_function = maybe_assert_non_blocking_poll;
+
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
gpr_tls_init(&g_is_nonblocking_poll);
// Start the nonblocking poll thread-local variable as false because the
@@ -205,10 +205,10 @@ int main(int argc, char** argv) {
// timeout).
gpr_tls_set(&g_is_nonblocking_poll, static_cast<intptr_t>(false));
- int ret = RUN_ALL_TESTS();
+ int ret = RUN_ALL_TESTS();
gpr_tls_destroy(&g_is_nonblocking_poll);
- return ret;
+ return ret;
#else // GRPC_POSIX_SOCKET
return 0;
#endif // GRPC_POSIX_SOCKET
-}
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/proto_server_reflection_test.cc b/contrib/libs/grpc/test/cpp/end2end/proto_server_reflection_test.cc
index d79b33da70..3418cc9fd2 100644
--- a/contrib/libs/grpc/test/cpp/end2end/proto_server_reflection_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/proto_server_reflection_test.cc
@@ -1,150 +1,150 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/ext/proto_server_reflection_plugin.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-
-class ProtoServerReflectionTest : public ::testing::Test {
- public:
- ProtoServerReflectionTest() {}
-
- void SetUp() override {
- port_ = grpc_pick_unused_port_or_die();
- ref_desc_pool_ = protobuf::DescriptorPool::generated_pool();
-
- ServerBuilder builder;
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/ext/proto_server_reflection_plugin.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/proto_reflection_descriptor_database.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+
+class ProtoServerReflectionTest : public ::testing::Test {
+ public:
+ ProtoServerReflectionTest() {}
+
+ void SetUp() override {
+ port_ = grpc_pick_unused_port_or_die();
+ ref_desc_pool_ = protobuf::DescriptorPool::generated_pool();
+
+ ServerBuilder builder;
TString server_address = "localhost:" + to_string(port_);
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- server_ = builder.BuildAndStart();
- }
-
- void ResetStub() {
- string target = "dns:localhost:" + to_string(port_);
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(target, InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- desc_db_.reset(new ProtoReflectionDescriptorDatabase(channel));
- desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));
- }
-
- string to_string(const int number) {
- std::stringstream strs;
- strs << number;
- return strs.str();
- }
-
+ builder.AddListeningPort(server_address, InsecureServerCredentials());
+ server_ = builder.BuildAndStart();
+ }
+
+ void ResetStub() {
+ string target = "dns:localhost:" + to_string(port_);
+ std::shared_ptr<Channel> channel =
+ grpc::CreateChannel(target, InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ desc_db_.reset(new ProtoReflectionDescriptorDatabase(channel));
+ desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));
+ }
+
+ string to_string(const int number) {
+ std::stringstream strs;
+ strs << number;
+ return strs.str();
+ }
+
void CompareService(const TString& service) {
- const protobuf::ServiceDescriptor* service_desc =
- desc_pool_->FindServiceByName(service);
- const protobuf::ServiceDescriptor* ref_service_desc =
- ref_desc_pool_->FindServiceByName(service);
- EXPECT_TRUE(service_desc != nullptr);
- EXPECT_TRUE(ref_service_desc != nullptr);
- EXPECT_EQ(service_desc->DebugString(), ref_service_desc->DebugString());
-
- const protobuf::FileDescriptor* file_desc = service_desc->file();
- if (known_files_.find(file_desc->package() + "/" + file_desc->name()) !=
- known_files_.end()) {
- EXPECT_EQ(file_desc->DebugString(),
- ref_service_desc->file()->DebugString());
- known_files_.insert(file_desc->package() + "/" + file_desc->name());
- }
-
- for (int i = 0; i < service_desc->method_count(); ++i) {
- CompareMethod(service_desc->method(i)->full_name());
- }
- }
-
+ const protobuf::ServiceDescriptor* service_desc =
+ desc_pool_->FindServiceByName(service);
+ const protobuf::ServiceDescriptor* ref_service_desc =
+ ref_desc_pool_->FindServiceByName(service);
+ EXPECT_TRUE(service_desc != nullptr);
+ EXPECT_TRUE(ref_service_desc != nullptr);
+ EXPECT_EQ(service_desc->DebugString(), ref_service_desc->DebugString());
+
+ const protobuf::FileDescriptor* file_desc = service_desc->file();
+ if (known_files_.find(file_desc->package() + "/" + file_desc->name()) !=
+ known_files_.end()) {
+ EXPECT_EQ(file_desc->DebugString(),
+ ref_service_desc->file()->DebugString());
+ known_files_.insert(file_desc->package() + "/" + file_desc->name());
+ }
+
+ for (int i = 0; i < service_desc->method_count(); ++i) {
+ CompareMethod(service_desc->method(i)->full_name());
+ }
+ }
+
void CompareMethod(const TString& method) {
- const protobuf::MethodDescriptor* method_desc =
- desc_pool_->FindMethodByName(method);
- const protobuf::MethodDescriptor* ref_method_desc =
- ref_desc_pool_->FindMethodByName(method);
- EXPECT_TRUE(method_desc != nullptr);
- EXPECT_TRUE(ref_method_desc != nullptr);
- EXPECT_EQ(method_desc->DebugString(), ref_method_desc->DebugString());
-
- CompareType(method_desc->input_type()->full_name());
- CompareType(method_desc->output_type()->full_name());
- }
-
+ const protobuf::MethodDescriptor* method_desc =
+ desc_pool_->FindMethodByName(method);
+ const protobuf::MethodDescriptor* ref_method_desc =
+ ref_desc_pool_->FindMethodByName(method);
+ EXPECT_TRUE(method_desc != nullptr);
+ EXPECT_TRUE(ref_method_desc != nullptr);
+ EXPECT_EQ(method_desc->DebugString(), ref_method_desc->DebugString());
+
+ CompareType(method_desc->input_type()->full_name());
+ CompareType(method_desc->output_type()->full_name());
+ }
+
void CompareType(const TString& type) {
- if (known_types_.find(type) != known_types_.end()) {
- return;
- }
-
- const protobuf::Descriptor* desc = desc_pool_->FindMessageTypeByName(type);
- const protobuf::Descriptor* ref_desc =
- ref_desc_pool_->FindMessageTypeByName(type);
- EXPECT_TRUE(desc != nullptr);
- EXPECT_TRUE(ref_desc != nullptr);
- EXPECT_EQ(desc->DebugString(), ref_desc->DebugString());
- }
-
- protected:
- std::unique_ptr<Server> server_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<ProtoReflectionDescriptorDatabase> desc_db_;
- std::unique_ptr<protobuf::DescriptorPool> desc_pool_;
- std::unordered_set<string> known_files_;
- std::unordered_set<string> known_types_;
- const protobuf::DescriptorPool* ref_desc_pool_;
- int port_;
- reflection::ProtoServerReflectionPlugin plugin_;
-};
-
-TEST_F(ProtoServerReflectionTest, CheckResponseWithLocalDescriptorPool) {
- ResetStub();
-
+ if (known_types_.find(type) != known_types_.end()) {
+ return;
+ }
+
+ const protobuf::Descriptor* desc = desc_pool_->FindMessageTypeByName(type);
+ const protobuf::Descriptor* ref_desc =
+ ref_desc_pool_->FindMessageTypeByName(type);
+ EXPECT_TRUE(desc != nullptr);
+ EXPECT_TRUE(ref_desc != nullptr);
+ EXPECT_EQ(desc->DebugString(), ref_desc->DebugString());
+ }
+
+ protected:
+ std::unique_ptr<Server> server_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<ProtoReflectionDescriptorDatabase> desc_db_;
+ std::unique_ptr<protobuf::DescriptorPool> desc_pool_;
+ std::unordered_set<string> known_files_;
+ std::unordered_set<string> known_types_;
+ const protobuf::DescriptorPool* ref_desc_pool_;
+ int port_;
+ reflection::ProtoServerReflectionPlugin plugin_;
+};
+
+TEST_F(ProtoServerReflectionTest, CheckResponseWithLocalDescriptorPool) {
+ ResetStub();
+
std::vector<TString> services;
- desc_db_->GetServices(&services);
- // The service list has at least one service (reflection servcie).
- EXPECT_TRUE(services.size() > 0);
-
- for (auto it = services.begin(); it != services.end(); ++it) {
- CompareService(*it);
- }
-}
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ desc_db_->GetServices(&services);
+ // The service list has at least one service (reflection servcie).
+ EXPECT_TRUE(services.size() > 0);
+
+ for (auto it = services.begin(); it != services.end(); ++it) {
+ CompareService(*it);
+ }
+}
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/raw_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/raw_end2end_test.cc
index 184dc1e5f5..42df83324b 100644
--- a/contrib/libs/grpc/test/cpp/end2end/raw_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/raw_end2end_test.cc
@@ -1,370 +1,370 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <cinttypes>
-#include <memory>
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/iomgr/port.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
-int detag(void* p) { return static_cast<int>(reinterpret_cast<intptr_t>(p)); }
-
-class Verifier {
- public:
- Verifier() {}
-
- // Expect sets the expected ok value for a specific tag
- Verifier& Expect(int i, bool expect_ok) {
- expectations_[tag(i)] = expect_ok;
- return *this;
- }
-
- // Next waits for 1 async tag to complete, checks its
- // expectations, and returns the tag
- int Next(CompletionQueue* cq, bool ignore_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- GotTag(got_tag, ok, ignore_ok);
- return detag(got_tag);
- }
-
- // Verify keeps calling Next until all currently set
- // expected tags are complete
- void Verify(CompletionQueue* cq) {
- GPR_ASSERT(!expectations_.empty());
- while (!expectations_.empty()) {
- Next(cq, false);
- }
- }
-
- private:
- void GotTag(void* got_tag, bool ok, bool ignore_ok) {
- auto it = expectations_.find(got_tag);
- if (it != expectations_.end()) {
- if (!ignore_ok) {
- EXPECT_EQ(it->second, ok);
- }
- expectations_.erase(it);
- }
- }
-
- std::map<void*, bool> expectations_;
-};
-
-class RawEnd2EndTest : public ::testing::Test {
- protected:
- RawEnd2EndTest() {}
-
- void SetUp() override {
- port_ = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port_;
- }
-
- void TearDown() override {
- server_->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- cq_->Shutdown();
- while (cq_->Next(&ignored_tag, &ignored_ok))
- ;
- stub_.reset();
- grpc_recycle_unused_port(port_);
- }
-
- template <typename ServerType>
- std::unique_ptr<ServerType> BuildAndStartServer() {
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- grpc::InsecureServerCredentials());
- std::unique_ptr<ServerType> service(new ServerType());
- builder.RegisterService(service.get());
- cq_ = builder.AddCompletionQueue();
- server_ = builder.BuildAndStart();
- return service;
- }
-
- void ResetStub() {
- ChannelArguments args;
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), grpc::InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- int port_;
-
- // For the client application to populate and send to server.
- EchoRequest send_request_;
- ::grpc::ByteBuffer send_request_buffer_;
-
- // For the server to give to gRPC to be populated by incoming request
- // from client.
- EchoRequest recv_request_;
- ::grpc::ByteBuffer recv_request_buffer_;
-
- // For the server application to populate and send back to client.
- EchoResponse send_response_;
- ::grpc::ByteBuffer send_response_buffer_;
-
- // For the client to give to gRPC to be populated by incoming response
- // from server.
- EchoResponse recv_response_;
- ::grpc::ByteBuffer recv_response_buffer_;
- Status recv_status_;
-
- // Both sides need contexts
- ClientContext cli_ctx_;
- ServerContext srv_ctx_;
-};
-
-// Regular Async, both peers use proto
-TEST_F(RawEnd2EndTest, PureAsyncService) {
- typedef grpc::testing::EchoTestService::AsyncService SType;
- ResetStub();
- auto service = BuildAndStartServer<SType>();
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx_);
-
- send_request_.set_message("hello");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx_, send_request_, cq_.get()));
- service->RequestEcho(&srv_ctx_, &recv_request_, &response_writer, cq_.get(),
- cq_.get(), tag(2));
- response_reader->Finish(&recv_response_, &recv_status_, tag(4));
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_EQ(send_request_.message(), recv_request_.message());
- send_response_.set_message(recv_request_.message());
- response_writer.Finish(send_response_, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response_.message(), recv_response_.message());
- EXPECT_TRUE(recv_status_.ok());
-}
-
-// Client uses proto, server uses generic codegen, unary
-TEST_F(RawEnd2EndTest, RawServerUnary) {
- typedef grpc::testing::EchoTestService::WithRawMethod_Echo<
- grpc::testing::EchoTestService::Service>
- SType;
- ResetStub();
- auto service = BuildAndStartServer<SType>();
- grpc::GenericServerAsyncResponseWriter response_writer(&srv_ctx_);
-
- send_request_.set_message("hello unary");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub_->AsyncEcho(&cli_ctx_, send_request_, cq_.get()));
- service->RequestEcho(&srv_ctx_, &recv_request_buffer_, &response_writer,
- cq_.get(), cq_.get(), tag(2));
- response_reader->Finish(&recv_response_, &recv_status_, tag(4));
- Verifier().Expect(2, true).Verify(cq_.get());
- EXPECT_TRUE(ParseFromByteBuffer(&recv_request_buffer_, &recv_request_));
- EXPECT_EQ(send_request_.message(), recv_request_.message());
- send_response_.set_message(recv_request_.message());
- EXPECT_TRUE(
- SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_));
- response_writer.Finish(send_response_buffer_, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response_.message(), recv_response_.message());
- EXPECT_TRUE(recv_status_.ok());
-}
-
-// Client uses proto, server uses generic codegen, client streaming
-TEST_F(RawEnd2EndTest, RawServerClientStreaming) {
- typedef grpc::testing::EchoTestService::WithRawMethod_RequestStream<
- grpc::testing::EchoTestService::Service>
- SType;
- ResetStub();
- auto service = BuildAndStartServer<SType>();
-
- grpc::GenericServerAsyncReader srv_stream(&srv_ctx_);
-
- send_request_.set_message("hello client streaming");
- std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
- stub_->AsyncRequestStream(&cli_ctx_, &recv_response_, cq_.get(), tag(1)));
-
- service->RequestRequestStream(&srv_ctx_, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- Verifier().Expect(2, true).Expect(1, true).Verify(cq_.get());
-
- cli_stream->Write(send_request_, tag(3));
- srv_stream.Read(&recv_request_buffer_, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
- EXPECT_EQ(send_request_.message(), recv_request_.message());
-
- cli_stream->Write(send_request_, tag(5));
- srv_stream.Read(&recv_request_buffer_, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
-
- ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
- EXPECT_EQ(send_request_.message(), recv_request_.message());
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request_buffer_, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
- send_response_.set_message(recv_request_.message());
- SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_);
- srv_stream.Finish(send_response_buffer_, Status::OK, tag(9));
- cli_stream->Finish(&recv_status_, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
-
- EXPECT_EQ(send_response_.message(), recv_response_.message());
- EXPECT_TRUE(recv_status_.ok());
-}
-
-// Client uses proto, server uses generic codegen, server streaming
-TEST_F(RawEnd2EndTest, RawServerServerStreaming) {
- typedef grpc::testing::EchoTestService::WithRawMethod_ResponseStream<
- grpc::testing::EchoTestService::Service>
- SType;
- ResetStub();
- auto service = BuildAndStartServer<SType>();
- grpc::GenericServerAsyncWriter srv_stream(&srv_ctx_);
-
- send_request_.set_message("hello server streaming");
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub_->AsyncResponseStream(&cli_ctx_, send_request_, cq_.get(), tag(1)));
-
- service->RequestResponseStream(&srv_ctx_, &recv_request_buffer_, &srv_stream,
- cq_.get(), cq_.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
- ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
- EXPECT_EQ(send_request_.message(), recv_request_.message());
-
- send_response_.set_message(recv_request_.message());
- SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_);
- srv_stream.Write(send_response_buffer_, tag(3));
- cli_stream->Read(&recv_response_, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- EXPECT_EQ(send_response_.message(), recv_response_.message());
-
- srv_stream.Write(send_response_buffer_, tag(5));
- cli_stream->Read(&recv_response_, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
- EXPECT_EQ(send_response_.message(), recv_response_.message());
-
- srv_stream.Finish(Status::OK, tag(7));
- cli_stream->Read(&recv_response_, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- cli_stream->Finish(&recv_status_, tag(9));
- Verifier().Expect(9, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status_.ok());
-}
-
-// Client uses proto, server uses generic codegen, bidi streaming
-TEST_F(RawEnd2EndTest, RawServerBidiStreaming) {
- typedef grpc::testing::EchoTestService::WithRawMethod_BidiStream<
- grpc::testing::EchoTestService::Service>
- SType;
- ResetStub();
- auto service = BuildAndStartServer<SType>();
-
- grpc::GenericServerAsyncReaderWriter srv_stream(&srv_ctx_);
-
- send_request_.set_message("hello bidi streaming");
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub_->AsyncBidiStream(&cli_ctx_, cq_.get(), tag(1)));
-
- service->RequestBidiStream(&srv_ctx_, &srv_stream, cq_.get(), cq_.get(),
- tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
-
- cli_stream->Write(send_request_, tag(3));
- srv_stream.Read(&recv_request_buffer_, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
- ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
- EXPECT_EQ(send_request_.message(), recv_request_.message());
-
- send_response_.set_message(recv_request_.message());
- SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_);
- srv_stream.Write(send_response_buffer_, tag(5));
- cli_stream->Read(&recv_response_, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
- EXPECT_EQ(send_response_.message(), recv_response_.message());
-
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request_buffer_, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
-
- srv_stream.Finish(Status::OK, tag(9));
- cli_stream->Finish(&recv_status_, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
-
- EXPECT_TRUE(recv_status_.ok());
-}
-
-// Testing that this pattern compiles
-TEST_F(RawEnd2EndTest, CompileTest) {
- typedef grpc::testing::EchoTestService::WithRawMethod_Echo<
- grpc::testing::EchoTestService::AsyncService>
- SType;
- ResetStub();
- auto service = BuildAndStartServer<SType>();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- // Change the backup poll interval from 5s to 100ms to speed up the
- // ReconnectChannel test
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- int ret = RUN_ALL_TESTS();
- return ret;
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <cinttypes>
+#include <memory>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/iomgr/port.h"
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+#include "test/cpp/util/string_ref_helper.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+
+namespace grpc {
+namespace testing {
+
+namespace {
+
+void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
+int detag(void* p) { return static_cast<int>(reinterpret_cast<intptr_t>(p)); }
+
+class Verifier {
+ public:
+ Verifier() {}
+
+ // Expect sets the expected ok value for a specific tag
+ Verifier& Expect(int i, bool expect_ok) {
+ expectations_[tag(i)] = expect_ok;
+ return *this;
+ }
+
+ // Next waits for 1 async tag to complete, checks its
+ // expectations, and returns the tag
+ int Next(CompletionQueue* cq, bool ignore_ok) {
+ bool ok;
+ void* got_tag;
+ EXPECT_TRUE(cq->Next(&got_tag, &ok));
+ GotTag(got_tag, ok, ignore_ok);
+ return detag(got_tag);
+ }
+
+ // Verify keeps calling Next until all currently set
+ // expected tags are complete
+ void Verify(CompletionQueue* cq) {
+ GPR_ASSERT(!expectations_.empty());
+ while (!expectations_.empty()) {
+ Next(cq, false);
+ }
+ }
+
+ private:
+ void GotTag(void* got_tag, bool ok, bool ignore_ok) {
+ auto it = expectations_.find(got_tag);
+ if (it != expectations_.end()) {
+ if (!ignore_ok) {
+ EXPECT_EQ(it->second, ok);
+ }
+ expectations_.erase(it);
+ }
+ }
+
+ std::map<void*, bool> expectations_;
+};
+
+class RawEnd2EndTest : public ::testing::Test {
+ protected:
+ RawEnd2EndTest() {}
+
+ void SetUp() override {
+ port_ = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port_;
+ }
+
+ void TearDown() override {
+ server_->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ cq_->Shutdown();
+ while (cq_->Next(&ignored_tag, &ignored_ok))
+ ;
+ stub_.reset();
+ grpc_recycle_unused_port(port_);
+ }
+
+ template <typename ServerType>
+ std::unique_ptr<ServerType> BuildAndStartServer() {
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ grpc::InsecureServerCredentials());
+ std::unique_ptr<ServerType> service(new ServerType());
+ builder.RegisterService(service.get());
+ cq_ = builder.AddCompletionQueue();
+ server_ = builder.BuildAndStart();
+ return service;
+ }
+
+ void ResetStub() {
+ ChannelArguments args;
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), grpc::InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+ int port_;
+
+ // For the client application to populate and send to server.
+ EchoRequest send_request_;
+ ::grpc::ByteBuffer send_request_buffer_;
+
+ // For the server to give to gRPC to be populated by incoming request
+ // from client.
+ EchoRequest recv_request_;
+ ::grpc::ByteBuffer recv_request_buffer_;
+
+ // For the server application to populate and send back to client.
+ EchoResponse send_response_;
+ ::grpc::ByteBuffer send_response_buffer_;
+
+ // For the client to give to gRPC to be populated by incoming response
+ // from server.
+ EchoResponse recv_response_;
+ ::grpc::ByteBuffer recv_response_buffer_;
+ Status recv_status_;
+
+ // Both sides need contexts
+ ClientContext cli_ctx_;
+ ServerContext srv_ctx_;
+};
+
+// Regular Async, both peers use proto
+TEST_F(RawEnd2EndTest, PureAsyncService) {
+ typedef grpc::testing::EchoTestService::AsyncService SType;
+ ResetStub();
+ auto service = BuildAndStartServer<SType>();
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx_);
+
+ send_request_.set_message("hello");
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx_, send_request_, cq_.get()));
+ service->RequestEcho(&srv_ctx_, &recv_request_, &response_writer, cq_.get(),
+ cq_.get(), tag(2));
+ response_reader->Finish(&recv_response_, &recv_status_, tag(4));
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_EQ(send_request_.message(), recv_request_.message());
+ send_response_.set_message(recv_request_.message());
+ response_writer.Finish(send_response_, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response_.message(), recv_response_.message());
+ EXPECT_TRUE(recv_status_.ok());
+}
+
+// Client uses proto, server uses generic codegen, unary
+TEST_F(RawEnd2EndTest, RawServerUnary) {
+ typedef grpc::testing::EchoTestService::WithRawMethod_Echo<
+ grpc::testing::EchoTestService::Service>
+ SType;
+ ResetStub();
+ auto service = BuildAndStartServer<SType>();
+ grpc::GenericServerAsyncResponseWriter response_writer(&srv_ctx_);
+
+ send_request_.set_message("hello unary");
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub_->AsyncEcho(&cli_ctx_, send_request_, cq_.get()));
+ service->RequestEcho(&srv_ctx_, &recv_request_buffer_, &response_writer,
+ cq_.get(), cq_.get(), tag(2));
+ response_reader->Finish(&recv_response_, &recv_status_, tag(4));
+ Verifier().Expect(2, true).Verify(cq_.get());
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_request_buffer_, &recv_request_));
+ EXPECT_EQ(send_request_.message(), recv_request_.message());
+ send_response_.set_message(recv_request_.message());
+ EXPECT_TRUE(
+ SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_));
+ response_writer.Finish(send_response_buffer_, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response_.message(), recv_response_.message());
+ EXPECT_TRUE(recv_status_.ok());
+}
+
+// Client uses proto, server uses generic codegen, client streaming
+TEST_F(RawEnd2EndTest, RawServerClientStreaming) {
+ typedef grpc::testing::EchoTestService::WithRawMethod_RequestStream<
+ grpc::testing::EchoTestService::Service>
+ SType;
+ ResetStub();
+ auto service = BuildAndStartServer<SType>();
+
+ grpc::GenericServerAsyncReader srv_stream(&srv_ctx_);
+
+ send_request_.set_message("hello client streaming");
+ std::unique_ptr<ClientAsyncWriter<EchoRequest>> cli_stream(
+ stub_->AsyncRequestStream(&cli_ctx_, &recv_response_, cq_.get(), tag(1)));
+
+ service->RequestRequestStream(&srv_ctx_, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ Verifier().Expect(2, true).Expect(1, true).Verify(cq_.get());
+
+ cli_stream->Write(send_request_, tag(3));
+ srv_stream.Read(&recv_request_buffer_, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
+ EXPECT_EQ(send_request_.message(), recv_request_.message());
+
+ cli_stream->Write(send_request_, tag(5));
+ srv_stream.Read(&recv_request_buffer_, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+
+ ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
+ EXPECT_EQ(send_request_.message(), recv_request_.message());
+ cli_stream->WritesDone(tag(7));
+ srv_stream.Read(&recv_request_buffer_, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
+ send_response_.set_message(recv_request_.message());
+ SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_);
+ srv_stream.Finish(send_response_buffer_, Status::OK, tag(9));
+ cli_stream->Finish(&recv_status_, tag(10));
+ Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
+
+ EXPECT_EQ(send_response_.message(), recv_response_.message());
+ EXPECT_TRUE(recv_status_.ok());
+}
+
+// Client uses proto, server uses generic codegen, server streaming
+TEST_F(RawEnd2EndTest, RawServerServerStreaming) {
+ typedef grpc::testing::EchoTestService::WithRawMethod_ResponseStream<
+ grpc::testing::EchoTestService::Service>
+ SType;
+ ResetStub();
+ auto service = BuildAndStartServer<SType>();
+ grpc::GenericServerAsyncWriter srv_stream(&srv_ctx_);
+
+ send_request_.set_message("hello server streaming");
+ std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
+ stub_->AsyncResponseStream(&cli_ctx_, send_request_, cq_.get(), tag(1)));
+
+ service->RequestResponseStream(&srv_ctx_, &recv_request_buffer_, &srv_stream,
+ cq_.get(), cq_.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+ ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
+ EXPECT_EQ(send_request_.message(), recv_request_.message());
+
+ send_response_.set_message(recv_request_.message());
+ SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_);
+ srv_stream.Write(send_response_buffer_, tag(3));
+ cli_stream->Read(&recv_response_, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ EXPECT_EQ(send_response_.message(), recv_response_.message());
+
+ srv_stream.Write(send_response_buffer_, tag(5));
+ cli_stream->Read(&recv_response_, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+ EXPECT_EQ(send_response_.message(), recv_response_.message());
+
+ srv_stream.Finish(Status::OK, tag(7));
+ cli_stream->Read(&recv_response_, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ cli_stream->Finish(&recv_status_, tag(9));
+ Verifier().Expect(9, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status_.ok());
+}
+
+// Client uses proto, server uses generic codegen, bidi streaming
+TEST_F(RawEnd2EndTest, RawServerBidiStreaming) {
+ typedef grpc::testing::EchoTestService::WithRawMethod_BidiStream<
+ grpc::testing::EchoTestService::Service>
+ SType;
+ ResetStub();
+ auto service = BuildAndStartServer<SType>();
+
+ grpc::GenericServerAsyncReaderWriter srv_stream(&srv_ctx_);
+
+ send_request_.set_message("hello bidi streaming");
+ std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
+ cli_stream(stub_->AsyncBidiStream(&cli_ctx_, cq_.get(), tag(1)));
+
+ service->RequestBidiStream(&srv_ctx_, &srv_stream, cq_.get(), cq_.get(),
+ tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq_.get());
+
+ cli_stream->Write(send_request_, tag(3));
+ srv_stream.Read(&recv_request_buffer_, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq_.get());
+ ParseFromByteBuffer(&recv_request_buffer_, &recv_request_);
+ EXPECT_EQ(send_request_.message(), recv_request_.message());
+
+ send_response_.set_message(recv_request_.message());
+ SerializeToByteBufferInPlace(&send_response_, &send_response_buffer_);
+ srv_stream.Write(send_response_buffer_, tag(5));
+ cli_stream->Read(&recv_response_, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq_.get());
+ EXPECT_EQ(send_response_.message(), recv_response_.message());
+
+ cli_stream->WritesDone(tag(7));
+ srv_stream.Read(&recv_request_buffer_, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq_.get());
+
+ srv_stream.Finish(Status::OK, tag(9));
+ cli_stream->Finish(&recv_status_, tag(10));
+ Verifier().Expect(9, true).Expect(10, true).Verify(cq_.get());
+
+ EXPECT_TRUE(recv_status_.ok());
+}
+
+// Testing that this pattern compiles
+TEST_F(RawEnd2EndTest, CompileTest) {
+ typedef grpc::testing::EchoTestService::WithRawMethod_Echo<
+ grpc::testing::EchoTestService::AsyncService>
+ SType;
+ ResetStub();
+ auto service = BuildAndStartServer<SType>();
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ // Change the backup poll interval from 5s to 100ms to speed up the
+ // ReconnectChannel test
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ int ret = RUN_ALL_TESTS();
+ return ret;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_builder_plugin_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_builder_plugin_test.cc
index 004902cad3..cc368bbb90 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_builder_plugin_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/server_builder_plugin_test.cc
@@ -1,265 +1,265 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/impl/server_builder_option.h>
-#include <grpcpp/impl/server_builder_plugin.h>
-#include <grpcpp/impl/server_initializer.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <gtest/gtest.h>
-
-#define PLUGIN_NAME "TestServerBuilderPlugin"
-
-namespace grpc {
-namespace testing {
-
-class TestServerBuilderPlugin : public ServerBuilderPlugin {
- public:
- TestServerBuilderPlugin() : service_(new TestServiceImpl()) {
- init_server_is_called_ = false;
- finish_is_called_ = false;
- change_arguments_is_called_ = false;
- register_service_ = false;
- }
-
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/impl/server_builder_option.h>
+#include <grpcpp/impl/server_builder_plugin.h>
+#include <grpcpp/impl/server_initializer.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_service_impl.h"
+
+#include <gtest/gtest.h>
+
+#define PLUGIN_NAME "TestServerBuilderPlugin"
+
+namespace grpc {
+namespace testing {
+
+class TestServerBuilderPlugin : public ServerBuilderPlugin {
+ public:
+ TestServerBuilderPlugin() : service_(new TestServiceImpl()) {
+ init_server_is_called_ = false;
+ finish_is_called_ = false;
+ change_arguments_is_called_ = false;
+ register_service_ = false;
+ }
+
TString name() override { return PLUGIN_NAME; }
-
- void InitServer(ServerInitializer* si) override {
- init_server_is_called_ = true;
- if (register_service_) {
- si->RegisterService(service_);
- }
- }
-
- void Finish(ServerInitializer* /*si*/) override { finish_is_called_ = true; }
-
+
+ void InitServer(ServerInitializer* si) override {
+ init_server_is_called_ = true;
+ if (register_service_) {
+ si->RegisterService(service_);
+ }
+ }
+
+ void Finish(ServerInitializer* /*si*/) override { finish_is_called_ = true; }
+
void ChangeArguments(const TString& /*name*/, void* /*value*/) override {
- change_arguments_is_called_ = true;
- }
-
- bool has_async_methods() const override {
- if (register_service_) {
- return service_->has_async_methods();
- }
- return false;
- }
-
- bool has_sync_methods() const override {
- if (register_service_) {
- return service_->has_synchronous_methods();
- }
- return false;
- }
-
- void SetRegisterService() { register_service_ = true; }
-
- bool init_server_is_called() { return init_server_is_called_; }
- bool finish_is_called() { return finish_is_called_; }
- bool change_arguments_is_called() { return change_arguments_is_called_; }
-
- private:
- bool init_server_is_called_;
- bool finish_is_called_;
- bool change_arguments_is_called_;
- bool register_service_;
- std::shared_ptr<TestServiceImpl> service_;
-};
-
-class InsertPluginServerBuilderOption : public ServerBuilderOption {
- public:
- InsertPluginServerBuilderOption() { register_service_ = false; }
-
- void UpdateArguments(ChannelArguments* /*arg*/) override {}
-
- void UpdatePlugins(
- std::vector<std::unique_ptr<ServerBuilderPlugin>>* plugins) override {
- plugins->clear();
-
- std::unique_ptr<TestServerBuilderPlugin> plugin(
- new TestServerBuilderPlugin());
- if (register_service_) plugin->SetRegisterService();
- plugins->emplace_back(std::move(plugin));
- }
-
- void SetRegisterService() { register_service_ = true; }
-
- private:
- bool register_service_;
-};
-
-std::unique_ptr<ServerBuilderPlugin> CreateTestServerBuilderPlugin() {
- return std::unique_ptr<ServerBuilderPlugin>(new TestServerBuilderPlugin());
-}
-
-// Force AddServerBuilderPlugin() to be called at static initialization time.
-struct StaticTestPluginInitializer {
+ change_arguments_is_called_ = true;
+ }
+
+ bool has_async_methods() const override {
+ if (register_service_) {
+ return service_->has_async_methods();
+ }
+ return false;
+ }
+
+ bool has_sync_methods() const override {
+ if (register_service_) {
+ return service_->has_synchronous_methods();
+ }
+ return false;
+ }
+
+ void SetRegisterService() { register_service_ = true; }
+
+ bool init_server_is_called() { return init_server_is_called_; }
+ bool finish_is_called() { return finish_is_called_; }
+ bool change_arguments_is_called() { return change_arguments_is_called_; }
+
+ private:
+ bool init_server_is_called_;
+ bool finish_is_called_;
+ bool change_arguments_is_called_;
+ bool register_service_;
+ std::shared_ptr<TestServiceImpl> service_;
+};
+
+class InsertPluginServerBuilderOption : public ServerBuilderOption {
+ public:
+ InsertPluginServerBuilderOption() { register_service_ = false; }
+
+ void UpdateArguments(ChannelArguments* /*arg*/) override {}
+
+ void UpdatePlugins(
+ std::vector<std::unique_ptr<ServerBuilderPlugin>>* plugins) override {
+ plugins->clear();
+
+ std::unique_ptr<TestServerBuilderPlugin> plugin(
+ new TestServerBuilderPlugin());
+ if (register_service_) plugin->SetRegisterService();
+ plugins->emplace_back(std::move(plugin));
+ }
+
+ void SetRegisterService() { register_service_ = true; }
+
+ private:
+ bool register_service_;
+};
+
+std::unique_ptr<ServerBuilderPlugin> CreateTestServerBuilderPlugin() {
+ return std::unique_ptr<ServerBuilderPlugin>(new TestServerBuilderPlugin());
+}
+
+// Force AddServerBuilderPlugin() to be called at static initialization time.
+struct StaticTestPluginInitializer {
StaticTestPluginInitializer() {
::grpc::ServerBuilder::InternalAddPluginFactory(
&CreateTestServerBuilderPlugin);
}
-} static_plugin_initializer_test_;
-
-// When the param boolean is true, the ServerBuilder plugin will be added at the
-// time of static initialization. When it's false, the ServerBuilder plugin will
-// be added using ServerBuilder::SetOption().
-class ServerBuilderPluginTest : public ::testing::TestWithParam<bool> {
- public:
- ServerBuilderPluginTest() {}
-
- void SetUp() override {
- port_ = grpc_pick_unused_port_or_die();
- builder_.reset(new ServerBuilder());
- }
-
- void InsertPlugin() {
- if (GetParam()) {
- // Add ServerBuilder plugin in static initialization
- CheckPresent();
- } else {
- // Add ServerBuilder plugin using ServerBuilder::SetOption()
- builder_->SetOption(std::unique_ptr<ServerBuilderOption>(
- new InsertPluginServerBuilderOption()));
- }
- }
-
- void InsertPluginWithTestService() {
- if (GetParam()) {
- // Add ServerBuilder plugin in static initialization
- auto plugin = CheckPresent();
- EXPECT_TRUE(plugin);
- plugin->SetRegisterService();
- } else {
- // Add ServerBuilder plugin using ServerBuilder::SetOption()
- std::unique_ptr<InsertPluginServerBuilderOption> option(
- new InsertPluginServerBuilderOption());
- option->SetRegisterService();
- builder_->SetOption(std::move(option));
- }
- }
-
- void StartServer() {
+} static_plugin_initializer_test_;
+
+// When the param boolean is true, the ServerBuilder plugin will be added at the
+// time of static initialization. When it's false, the ServerBuilder plugin will
+// be added using ServerBuilder::SetOption().
+class ServerBuilderPluginTest : public ::testing::TestWithParam<bool> {
+ public:
+ ServerBuilderPluginTest() {}
+
+ void SetUp() override {
+ port_ = grpc_pick_unused_port_or_die();
+ builder_.reset(new ServerBuilder());
+ }
+
+ void InsertPlugin() {
+ if (GetParam()) {
+ // Add ServerBuilder plugin in static initialization
+ CheckPresent();
+ } else {
+ // Add ServerBuilder plugin using ServerBuilder::SetOption()
+ builder_->SetOption(std::unique_ptr<ServerBuilderOption>(
+ new InsertPluginServerBuilderOption()));
+ }
+ }
+
+ void InsertPluginWithTestService() {
+ if (GetParam()) {
+ // Add ServerBuilder plugin in static initialization
+ auto plugin = CheckPresent();
+ EXPECT_TRUE(plugin);
+ plugin->SetRegisterService();
+ } else {
+ // Add ServerBuilder plugin using ServerBuilder::SetOption()
+ std::unique_ptr<InsertPluginServerBuilderOption> option(
+ new InsertPluginServerBuilderOption());
+ option->SetRegisterService();
+ builder_->SetOption(std::move(option));
+ }
+ }
+
+ void StartServer() {
TString server_address = "localhost:" + to_string(port_);
- builder_->AddListeningPort(server_address, InsecureServerCredentials());
- // we run some tests without a service, and for those we need to supply a
- // frequently polled completion queue
- cq_ = builder_->AddCompletionQueue();
- cq_thread_ = new std::thread(&ServerBuilderPluginTest::RunCQ, this);
- server_ = builder_->BuildAndStart();
- EXPECT_TRUE(CheckPresent());
- }
-
- void ResetStub() {
- string target = "dns:localhost:" + to_string(port_);
- channel_ = grpc::CreateChannel(target, InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- void TearDown() override {
- auto plugin = CheckPresent();
- EXPECT_TRUE(plugin);
- EXPECT_TRUE(plugin->init_server_is_called());
- EXPECT_TRUE(plugin->finish_is_called());
- server_->Shutdown();
- cq_->Shutdown();
- cq_thread_->join();
- delete cq_thread_;
- }
-
- string to_string(const int number) {
- std::stringstream strs;
- strs << number;
- return strs.str();
- }
-
- protected:
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<ServerBuilder> builder_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<Server> server_;
- std::thread* cq_thread_;
- TestServiceImpl service_;
- int port_;
-
- private:
- TestServerBuilderPlugin* CheckPresent() {
- auto it = builder_->plugins_.begin();
- for (; it != builder_->plugins_.end(); it++) {
- if ((*it)->name() == PLUGIN_NAME) break;
- }
- if (it != builder_->plugins_.end()) {
- return static_cast<TestServerBuilderPlugin*>(it->get());
- } else {
- return nullptr;
- }
- }
-
- void RunCQ() {
- void* tag;
- bool ok;
- while (cq_->Next(&tag, &ok))
- ;
- }
-};
-
-TEST_P(ServerBuilderPluginTest, PluginWithoutServiceTest) {
- InsertPlugin();
- StartServer();
-}
-
-TEST_P(ServerBuilderPluginTest, PluginWithServiceTest) {
- InsertPluginWithTestService();
- StartServer();
- ResetStub();
-
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello hello hello hello");
- ClientContext context;
- context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
- Status s = stub_->Echo(&context, request, &response);
- EXPECT_EQ(response.message(), request.message());
- EXPECT_TRUE(s.ok());
-}
-
-INSTANTIATE_TEST_SUITE_P(ServerBuilderPluginTest, ServerBuilderPluginTest,
- ::testing::Values(false, true));
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ builder_->AddListeningPort(server_address, InsecureServerCredentials());
+ // we run some tests without a service, and for those we need to supply a
+ // frequently polled completion queue
+ cq_ = builder_->AddCompletionQueue();
+ cq_thread_ = new std::thread(&ServerBuilderPluginTest::RunCQ, this);
+ server_ = builder_->BuildAndStart();
+ EXPECT_TRUE(CheckPresent());
+ }
+
+ void ResetStub() {
+ string target = "dns:localhost:" + to_string(port_);
+ channel_ = grpc::CreateChannel(target, InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ void TearDown() override {
+ auto plugin = CheckPresent();
+ EXPECT_TRUE(plugin);
+ EXPECT_TRUE(plugin->init_server_is_called());
+ EXPECT_TRUE(plugin->finish_is_called());
+ server_->Shutdown();
+ cq_->Shutdown();
+ cq_thread_->join();
+ delete cq_thread_;
+ }
+
+ string to_string(const int number) {
+ std::stringstream strs;
+ strs << number;
+ return strs.str();
+ }
+
+ protected:
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<ServerBuilder> builder_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ std::unique_ptr<Server> server_;
+ std::thread* cq_thread_;
+ TestServiceImpl service_;
+ int port_;
+
+ private:
+ TestServerBuilderPlugin* CheckPresent() {
+ auto it = builder_->plugins_.begin();
+ for (; it != builder_->plugins_.end(); it++) {
+ if ((*it)->name() == PLUGIN_NAME) break;
+ }
+ if (it != builder_->plugins_.end()) {
+ return static_cast<TestServerBuilderPlugin*>(it->get());
+ } else {
+ return nullptr;
+ }
+ }
+
+ void RunCQ() {
+ void* tag;
+ bool ok;
+ while (cq_->Next(&tag, &ok))
+ ;
+ }
+};
+
+TEST_P(ServerBuilderPluginTest, PluginWithoutServiceTest) {
+ InsertPlugin();
+ StartServer();
+}
+
+TEST_P(ServerBuilderPluginTest, PluginWithServiceTest) {
+ InsertPluginWithTestService();
+ StartServer();
+ ResetStub();
+
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello hello hello hello");
+ ClientContext context;
+ context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
+ Status s = stub_->Echo(&context, request, &response);
+ EXPECT_EQ(response.message(), request.message());
+ EXPECT_TRUE(s.ok());
+}
+
+INSTANTIATE_TEST_SUITE_P(ServerBuilderPluginTest, ServerBuilderPluginTest,
+ ::testing::Values(false, true));
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_crash_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_crash_test.cc
index 3616d680f9..f8e4ea8eae 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_crash_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/server_crash_test.cc
@@ -1,160 +1,160 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/subprocess.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/subprocess.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
static TString g_root;
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-class ServiceImpl final : public ::grpc::testing::EchoTestService::Service {
- public:
- ServiceImpl() : bidi_stream_count_(0), response_stream_count_(0) {}
-
- Status BidiStream(
- ServerContext* /*context*/,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- bidi_stream_count_++;
- EchoRequest request;
- EchoResponse response;
- while (stream->Read(&request)) {
- gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
- response.set_message(request.message());
- stream->Write(response);
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_seconds(1, GPR_TIMESPAN)));
- }
- return Status::OK;
- }
-
- Status ResponseStream(ServerContext* /*context*/,
- const EchoRequest* /*request*/,
- ServerWriter<EchoResponse>* writer) override {
- EchoResponse response;
- response_stream_count_++;
- for (int i = 0;; i++) {
- std::ostringstream msg;
- msg << "Hello " << i;
- response.set_message(msg.str());
- if (!writer->Write(response)) break;
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_seconds(1, GPR_TIMESPAN)));
- }
- return Status::OK;
- }
-
- int bidi_stream_count() { return bidi_stream_count_; }
-
- int response_stream_count() { return response_stream_count_; }
-
- private:
- int bidi_stream_count_;
- int response_stream_count_;
-};
-
-class CrashTest : public ::testing::Test {
- protected:
- CrashTest() {}
-
+
+namespace grpc {
+namespace testing {
+
+namespace {
+
+class ServiceImpl final : public ::grpc::testing::EchoTestService::Service {
+ public:
+ ServiceImpl() : bidi_stream_count_(0), response_stream_count_(0) {}
+
+ Status BidiStream(
+ ServerContext* /*context*/,
+ ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
+ bidi_stream_count_++;
+ EchoRequest request;
+ EchoResponse response;
+ while (stream->Read(&request)) {
+ gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
+ response.set_message(request.message());
+ stream->Write(response);
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_seconds(1, GPR_TIMESPAN)));
+ }
+ return Status::OK;
+ }
+
+ Status ResponseStream(ServerContext* /*context*/,
+ const EchoRequest* /*request*/,
+ ServerWriter<EchoResponse>* writer) override {
+ EchoResponse response;
+ response_stream_count_++;
+ for (int i = 0;; i++) {
+ std::ostringstream msg;
+ msg << "Hello " << i;
+ response.set_message(msg.str());
+ if (!writer->Write(response)) break;
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_seconds(1, GPR_TIMESPAN)));
+ }
+ return Status::OK;
+ }
+
+ int bidi_stream_count() { return bidi_stream_count_; }
+
+ int response_stream_count() { return response_stream_count_; }
+
+ private:
+ int bidi_stream_count_;
+ int response_stream_count_;
+};
+
+class CrashTest : public ::testing::Test {
+ protected:
+ CrashTest() {}
+
std::unique_ptr<Server> CreateServerAndClient(const TString& mode) {
- auto port = grpc_pick_unused_port_or_die();
- std::ostringstream addr_stream;
- addr_stream << "localhost:" << port;
- auto addr = addr_stream.str();
- client_.reset(new SubProcess({g_root + "/server_crash_test_client",
- "--address=" + addr, "--mode=" + mode}));
- GPR_ASSERT(client_);
-
- ServerBuilder builder;
- builder.AddListeningPort(addr, grpc::InsecureServerCredentials());
- builder.RegisterService(&service_);
- return builder.BuildAndStart();
- }
-
- void KillClient() { client_.reset(); }
-
- bool HadOneBidiStream() { return service_.bidi_stream_count() == 1; }
-
- bool HadOneResponseStream() { return service_.response_stream_count() == 1; }
-
- private:
- std::unique_ptr<SubProcess> client_;
- ServiceImpl service_;
-};
-
-TEST_F(CrashTest, ResponseStream) {
- auto server = CreateServerAndClient("response");
-
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_seconds(60, GPR_TIMESPAN)));
- KillClient();
- server->Shutdown();
- GPR_ASSERT(HadOneResponseStream());
-}
-
-TEST_F(CrashTest, BidiStream) {
- auto server = CreateServerAndClient("bidi");
-
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_seconds(60, GPR_TIMESPAN)));
- KillClient();
- server->Shutdown();
- GPR_ASSERT(HadOneBidiStream());
-}
-
-} // namespace
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
+ auto port = grpc_pick_unused_port_or_die();
+ std::ostringstream addr_stream;
+ addr_stream << "localhost:" << port;
+ auto addr = addr_stream.str();
+ client_.reset(new SubProcess({g_root + "/server_crash_test_client",
+ "--address=" + addr, "--mode=" + mode}));
+ GPR_ASSERT(client_);
+
+ ServerBuilder builder;
+ builder.AddListeningPort(addr, grpc::InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ return builder.BuildAndStart();
+ }
+
+ void KillClient() { client_.reset(); }
+
+ bool HadOneBidiStream() { return service_.bidi_stream_count() == 1; }
+
+ bool HadOneResponseStream() { return service_.response_stream_count() == 1; }
+
+ private:
+ std::unique_ptr<SubProcess> client_;
+ ServiceImpl service_;
+};
+
+TEST_F(CrashTest, ResponseStream) {
+ auto server = CreateServerAndClient("response");
+
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_seconds(60, GPR_TIMESPAN)));
+ KillClient();
+ server->Shutdown();
+ GPR_ASSERT(HadOneResponseStream());
+}
+
+TEST_F(CrashTest, BidiStream) {
+ auto server = CreateServerAndClient("bidi");
+
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_seconds(60, GPR_TIMESPAN)));
+ KillClient();
+ server->Shutdown();
+ GPR_ASSERT(HadOneBidiStream());
+}
+
+} // namespace
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
TString me = argv[0];
- auto lslash = me.rfind('/');
+ auto lslash = me.rfind('/');
if (lslash != TString::npos) {
- g_root = me.substr(0, lslash);
- } else {
- g_root = ".";
- }
-
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ g_root = me.substr(0, lslash);
+ } else {
+ g_root = ".";
+ }
+
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_crash_test_client.cc b/contrib/libs/grpc/test/cpp/end2end/server_crash_test_client.cc
index 202fb2836c..99e8259aa9 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_crash_test_client.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/server_crash_test_client.cc
@@ -1,72 +1,72 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <gflags/gflags.h>
-#include <iostream>
-#include <memory>
-#include <sstream>
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <gflags/gflags.h>
+#include <iostream>
+#include <memory>
+#include <sstream>
#include <util/generic/string.h>
-
-#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/test_config.h"
-
-DEFINE_string(address, "", "Address to connect to");
-DEFINE_string(mode, "", "Test mode to use");
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-
-int main(int argc, char** argv) {
- grpc::testing::InitTest(&argc, &argv, true);
- auto stub = grpc::testing::EchoTestService::NewStub(
- grpc::CreateChannel(FLAGS_address, grpc::InsecureChannelCredentials()));
-
- EchoRequest request;
- EchoResponse response;
- grpc::ClientContext context;
- context.set_wait_for_ready(true);
-
- if (FLAGS_mode == "bidi") {
- auto stream = stub->BidiStream(&context);
- for (int i = 0;; i++) {
- std::ostringstream msg;
- msg << "Hello " << i;
- request.set_message(msg.str());
- GPR_ASSERT(stream->Write(request));
- GPR_ASSERT(stream->Read(&response));
- GPR_ASSERT(response.message() == request.message());
- }
- } else if (FLAGS_mode == "response") {
- EchoRequest request;
- request.set_message("Hello");
- auto stream = stub->ResponseStream(&context, request);
- for (;;) {
- GPR_ASSERT(stream->Read(&response));
- }
- } else {
- gpr_log(GPR_ERROR, "invalid test mode '%s'", FLAGS_mode.c_str());
- return 1;
- }
-
- return 0;
-}
+
+#include <grpc/support/log.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/cpp/util/test_config.h"
+
+DEFINE_string(address, "", "Address to connect to");
+DEFINE_string(mode, "", "Test mode to use");
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+
+int main(int argc, char** argv) {
+ grpc::testing::InitTest(&argc, &argv, true);
+ auto stub = grpc::testing::EchoTestService::NewStub(
+ grpc::CreateChannel(FLAGS_address, grpc::InsecureChannelCredentials()));
+
+ EchoRequest request;
+ EchoResponse response;
+ grpc::ClientContext context;
+ context.set_wait_for_ready(true);
+
+ if (FLAGS_mode == "bidi") {
+ auto stream = stub->BidiStream(&context);
+ for (int i = 0;; i++) {
+ std::ostringstream msg;
+ msg << "Hello " << i;
+ request.set_message(msg.str());
+ GPR_ASSERT(stream->Write(request));
+ GPR_ASSERT(stream->Read(&response));
+ GPR_ASSERT(response.message() == request.message());
+ }
+ } else if (FLAGS_mode == "response") {
+ EchoRequest request;
+ request.set_message("Hello");
+ auto stream = stub->ResponseStream(&context, request);
+ for (;;) {
+ GPR_ASSERT(stream->Read(&response));
+ }
+ } else {
+ gpr_log(GPR_ERROR, "invalid test mode '%s'", FLAGS_mode.c_str());
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_early_return_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_early_return_test.cc
index 0f340516b0..973168411c 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_early_return_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/server_early_return_test.cc
@@ -1,232 +1,232 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-
-const char kServerReturnStatusCode[] = "server_return_status_code";
-const char kServerDelayBeforeReturnUs[] = "server_delay_before_return_us";
-const char kServerReturnAfterNReads[] = "server_return_after_n_reads";
-
-class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
- public:
- // Unused methods are not implemented.
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
- EchoResponse* response) override {
- int server_return_status_code =
- GetIntValueFromMetadata(context, kServerReturnStatusCode, 0);
- int server_delay_before_return_us =
- GetIntValueFromMetadata(context, kServerDelayBeforeReturnUs, 0);
- int server_return_after_n_reads =
- GetIntValueFromMetadata(context, kServerReturnAfterNReads, 0);
-
- EchoRequest request;
- while (server_return_after_n_reads--) {
- EXPECT_TRUE(reader->Read(&request));
- }
-
- response->set_message("response msg");
-
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(server_delay_before_return_us, GPR_TIMESPAN)));
-
- return Status(static_cast<StatusCode>(server_return_status_code), "");
- }
-
- Status BidiStream(
- ServerContext* context,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- int server_return_status_code =
- GetIntValueFromMetadata(context, kServerReturnStatusCode, 0);
- int server_delay_before_return_us =
- GetIntValueFromMetadata(context, kServerDelayBeforeReturnUs, 0);
- int server_return_after_n_reads =
- GetIntValueFromMetadata(context, kServerReturnAfterNReads, 0);
-
- EchoRequest request;
- EchoResponse response;
- while (server_return_after_n_reads--) {
- EXPECT_TRUE(stream->Read(&request));
- response.set_message(request.message());
- EXPECT_TRUE(stream->Write(response));
- }
-
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(server_delay_before_return_us, GPR_TIMESPAN)));
-
- return Status(static_cast<StatusCode>(server_return_status_code), "");
- }
-
- int GetIntValueFromMetadata(ServerContext* context, const char* key,
- int default_value) {
- auto metadata = context->client_metadata();
- if (metadata.find(key) != metadata.end()) {
- std::istringstream iss(ToString(metadata.find(key)->second));
- iss >> default_value;
- }
- return default_value;
- }
-};
-
-class ServerEarlyReturnTest : public ::testing::Test {
- protected:
- ServerEarlyReturnTest() : picked_port_(0) {}
-
- void SetUp() override {
- int port = grpc_pick_unused_port_or_die();
- picked_port_ = port;
- server_address_ << "127.0.0.1:" << port;
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- InsecureServerCredentials());
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
-
- channel_ = grpc::CreateChannel(server_address_.str(),
- InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- void TearDown() override {
- server_->Shutdown();
- if (picked_port_ > 0) {
- grpc_recycle_unused_port(picked_port_);
- }
- }
-
- // Client sends 20 requests and the server returns after reading 10 requests.
- // If return_cancel is true, server returns CANCELLED status. Otherwise it
- // returns OK.
- void DoBidiStream(bool return_cancelled) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- context.AddMetadata(kServerReturnAfterNReads, "10");
- if (return_cancelled) {
- // "1" means CANCELLED
- context.AddMetadata(kServerReturnStatusCode, "1");
- }
- context.AddMetadata(kServerDelayBeforeReturnUs, "10000");
-
- auto stream = stub_->BidiStream(&context);
-
- for (int i = 0; i < 20; i++) {
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/string_ref_helper.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+namespace {
+
+const char kServerReturnStatusCode[] = "server_return_status_code";
+const char kServerDelayBeforeReturnUs[] = "server_delay_before_return_us";
+const char kServerReturnAfterNReads[] = "server_return_after_n_reads";
+
+class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
+ public:
+ // Unused methods are not implemented.
+
+ Status RequestStream(ServerContext* context,
+ ServerReader<EchoRequest>* reader,
+ EchoResponse* response) override {
+ int server_return_status_code =
+ GetIntValueFromMetadata(context, kServerReturnStatusCode, 0);
+ int server_delay_before_return_us =
+ GetIntValueFromMetadata(context, kServerDelayBeforeReturnUs, 0);
+ int server_return_after_n_reads =
+ GetIntValueFromMetadata(context, kServerReturnAfterNReads, 0);
+
+ EchoRequest request;
+ while (server_return_after_n_reads--) {
+ EXPECT_TRUE(reader->Read(&request));
+ }
+
+ response->set_message("response msg");
+
+ gpr_sleep_until(gpr_time_add(
+ gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_micros(server_delay_before_return_us, GPR_TIMESPAN)));
+
+ return Status(static_cast<StatusCode>(server_return_status_code), "");
+ }
+
+ Status BidiStream(
+ ServerContext* context,
+ ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
+ int server_return_status_code =
+ GetIntValueFromMetadata(context, kServerReturnStatusCode, 0);
+ int server_delay_before_return_us =
+ GetIntValueFromMetadata(context, kServerDelayBeforeReturnUs, 0);
+ int server_return_after_n_reads =
+ GetIntValueFromMetadata(context, kServerReturnAfterNReads, 0);
+
+ EchoRequest request;
+ EchoResponse response;
+ while (server_return_after_n_reads--) {
+ EXPECT_TRUE(stream->Read(&request));
+ response.set_message(request.message());
+ EXPECT_TRUE(stream->Write(response));
+ }
+
+ gpr_sleep_until(gpr_time_add(
+ gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_micros(server_delay_before_return_us, GPR_TIMESPAN)));
+
+ return Status(static_cast<StatusCode>(server_return_status_code), "");
+ }
+
+ int GetIntValueFromMetadata(ServerContext* context, const char* key,
+ int default_value) {
+ auto metadata = context->client_metadata();
+ if (metadata.find(key) != metadata.end()) {
+ std::istringstream iss(ToString(metadata.find(key)->second));
+ iss >> default_value;
+ }
+ return default_value;
+ }
+};
+
+class ServerEarlyReturnTest : public ::testing::Test {
+ protected:
+ ServerEarlyReturnTest() : picked_port_(0) {}
+
+ void SetUp() override {
+ int port = grpc_pick_unused_port_or_die();
+ picked_port_ = port;
+ server_address_ << "127.0.0.1:" << port;
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+
+ channel_ = grpc::CreateChannel(server_address_.str(),
+ InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ void TearDown() override {
+ server_->Shutdown();
+ if (picked_port_ > 0) {
+ grpc_recycle_unused_port(picked_port_);
+ }
+ }
+
+ // Client sends 20 requests and the server returns after reading 10 requests.
+ // If return_cancel is true, server returns CANCELLED status. Otherwise it
+ // returns OK.
+ void DoBidiStream(bool return_cancelled) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ context.AddMetadata(kServerReturnAfterNReads, "10");
+ if (return_cancelled) {
+ // "1" means CANCELLED
+ context.AddMetadata(kServerReturnStatusCode, "1");
+ }
+ context.AddMetadata(kServerDelayBeforeReturnUs, "10000");
+
+ auto stream = stub_->BidiStream(&context);
+
+ for (int i = 0; i < 20; i++) {
request.set_message(TString("hello") + ToString(i));
- bool write_ok = stream->Write(request);
- bool read_ok = stream->Read(&response);
- if (i < 10) {
- EXPECT_TRUE(write_ok);
- EXPECT_TRUE(read_ok);
- EXPECT_EQ(response.message(), request.message());
- } else {
- EXPECT_FALSE(read_ok);
- }
- }
-
- stream->WritesDone();
- EXPECT_FALSE(stream->Read(&response));
-
- Status s = stream->Finish();
- if (return_cancelled) {
- EXPECT_EQ(s.error_code(), StatusCode::CANCELLED);
- } else {
- EXPECT_TRUE(s.ok());
- }
- }
-
- void DoRequestStream(bool return_cancelled) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
-
- context.AddMetadata(kServerReturnAfterNReads, "10");
- if (return_cancelled) {
- // "1" means CANCELLED
- context.AddMetadata(kServerReturnStatusCode, "1");
- }
- context.AddMetadata(kServerDelayBeforeReturnUs, "10000");
-
- auto stream = stub_->RequestStream(&context, &response);
- for (int i = 0; i < 20; i++) {
+ bool write_ok = stream->Write(request);
+ bool read_ok = stream->Read(&response);
+ if (i < 10) {
+ EXPECT_TRUE(write_ok);
+ EXPECT_TRUE(read_ok);
+ EXPECT_EQ(response.message(), request.message());
+ } else {
+ EXPECT_FALSE(read_ok);
+ }
+ }
+
+ stream->WritesDone();
+ EXPECT_FALSE(stream->Read(&response));
+
+ Status s = stream->Finish();
+ if (return_cancelled) {
+ EXPECT_EQ(s.error_code(), StatusCode::CANCELLED);
+ } else {
+ EXPECT_TRUE(s.ok());
+ }
+ }
+
+ void DoRequestStream(bool return_cancelled) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+
+ context.AddMetadata(kServerReturnAfterNReads, "10");
+ if (return_cancelled) {
+ // "1" means CANCELLED
+ context.AddMetadata(kServerReturnStatusCode, "1");
+ }
+ context.AddMetadata(kServerDelayBeforeReturnUs, "10000");
+
+ auto stream = stub_->RequestStream(&context, &response);
+ for (int i = 0; i < 20; i++) {
request.set_message(TString("hello") + ToString(i));
- bool written = stream->Write(request);
- if (i < 10) {
- EXPECT_TRUE(written);
- }
- }
- stream->WritesDone();
- Status s = stream->Finish();
- if (return_cancelled) {
- EXPECT_EQ(s.error_code(), StatusCode::CANCELLED);
- } else {
- EXPECT_TRUE(s.ok());
- }
- }
-
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- TestServiceImpl service_;
- int picked_port_;
-};
-
-TEST_F(ServerEarlyReturnTest, BidiStreamEarlyOk) { DoBidiStream(false); }
-
-TEST_F(ServerEarlyReturnTest, BidiStreamEarlyCancel) { DoBidiStream(true); }
-
-TEST_F(ServerEarlyReturnTest, RequestStreamEarlyOK) { DoRequestStream(false); }
-TEST_F(ServerEarlyReturnTest, RequestStreamEarlyCancel) {
- DoRequestStream(true);
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ bool written = stream->Write(request);
+ if (i < 10) {
+ EXPECT_TRUE(written);
+ }
+ }
+ stream->WritesDone();
+ Status s = stream->Finish();
+ if (return_cancelled) {
+ EXPECT_EQ(s.error_code(), StatusCode::CANCELLED);
+ } else {
+ EXPECT_TRUE(s.ok());
+ }
+ }
+
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+ TestServiceImpl service_;
+ int picked_port_;
+};
+
+TEST_F(ServerEarlyReturnTest, BidiStreamEarlyOk) { DoBidiStream(false); }
+
+TEST_F(ServerEarlyReturnTest, BidiStreamEarlyCancel) { DoBidiStream(true); }
+
+TEST_F(ServerEarlyReturnTest, RequestStreamEarlyOK) { DoRequestStream(false); }
+TEST_F(ServerEarlyReturnTest, RequestStreamEarlyCancel) {
+ DoRequestStream(true);
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make b/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
index 161176f141..4405208f4c 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
+++ b/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
@@ -1,32 +1,32 @@
GTEST_UGLY()
-
-OWNER(
- dvshkurko
- g:ymake
-)
-
-ADDINCL(
+
+OWNER(
+ dvshkurko
+ g:ymake
+)
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- server_interceptors_end2end_test.cc
-)
-
-END()
+ ${ARCADIA_ROOT}/contrib/libs/grpc
+)
+
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/core
+ contrib/libs/grpc/src/proto/grpc/testing
+ contrib/libs/grpc/src/proto/grpc/testing/duplicate
+ contrib/libs/grpc/test/core/util
+ contrib/libs/grpc/test/cpp/end2end
+ contrib/libs/grpc/test/cpp/util
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(
+ contrib/libs/grpc/test/cpp/end2end
+)
+
+SRCS(
+ server_interceptors_end2end_test.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
index 6d2dc772ef..2f6a71ebd4 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
@@ -1,708 +1,708 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <memory>
-#include <vector>
-
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/server_interceptor.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/interceptors_util.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-#include <gtest/gtest.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-
-class LoggingInterceptor : public experimental::Interceptor {
- public:
- LoggingInterceptor(experimental::ServerRpcInfo* info) {
- info_ = info;
-
- // Check the method name and compare to the type
- const char* method = info->method();
- experimental::ServerRpcInfo::Type type = info->type();
-
- // Check that we use one of our standard methods with expected type.
- // Also allow the health checking service.
- // We accept BIDI_STREAMING for Echo in case it's an AsyncGenericService
- // being tested (the GenericRpc test).
- // The empty method is for the Unimplemented requests that arise
- // when draining the CQ.
- EXPECT_TRUE(
- strstr(method, "/grpc.health") == method ||
- (strcmp(method, "/grpc.testing.EchoTestService/Echo") == 0 &&
- (type == experimental::ServerRpcInfo::Type::UNARY ||
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING)) ||
- (strcmp(method, "/grpc.testing.EchoTestService/RequestStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::CLIENT_STREAMING) ||
- (strcmp(method, "/grpc.testing.EchoTestService/ResponseStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::SERVER_STREAMING) ||
- (strcmp(method, "/grpc.testing.EchoTestService/BidiStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING) ||
- strcmp(method, "/grpc.testing.EchoTestService/Unimplemented") == 0 ||
- (strcmp(method, "") == 0 &&
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING));
- }
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Got nothing better to do here for now
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_TRUE(req.message().find("Hello") == 0);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_STATUS)) {
- auto* map = methods->GetSendTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.find("testkey") == 0 &&
- pair.second.find("testvalue") == 0;
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto status = methods->GetSendStatus();
- EXPECT_EQ(status.ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.find("testkey") == 0 &&
- pair.second.find("testvalue") == 0;
- if (found) break;
- }
- EXPECT_EQ(found, true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- if (resp != nullptr) {
- EXPECT_TRUE(resp->message().find("Hello") == 0);
- }
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_CLOSE)) {
- // Got nothing interesting to do here
- }
- methods->Proceed();
- }
-
- private:
- experimental::ServerRpcInfo* info_;
-};
-
-class LoggingInterceptorFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new LoggingInterceptor(info);
- }
-};
-
-// Test if SendMessage function family works as expected for sync/callback apis
-class SyncSendMessageTester : public experimental::Interceptor {
- public:
- SyncSendMessageTester(experimental::ServerRpcInfo* /*info*/) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- string old_msg =
- static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
- EXPECT_EQ(old_msg.find("Hello"), 0u);
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <memory>
+#include <vector>
+
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/generic/generic_stub.h>
+#include <grpcpp/impl/codegen/proto_utils.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/server_interceptor.h>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/interceptors_util.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/byte_buffer_proto_helper.h"
+
+#include <gtest/gtest.h>
+
+namespace grpc {
+namespace testing {
+namespace {
+
+class LoggingInterceptor : public experimental::Interceptor {
+ public:
+ LoggingInterceptor(experimental::ServerRpcInfo* info) {
+ info_ = info;
+
+ // Check the method name and compare to the type
+ const char* method = info->method();
+ experimental::ServerRpcInfo::Type type = info->type();
+
+ // Check that we use one of our standard methods with expected type.
+ // Also allow the health checking service.
+ // We accept BIDI_STREAMING for Echo in case it's an AsyncGenericService
+ // being tested (the GenericRpc test).
+ // The empty method is for the Unimplemented requests that arise
+ // when draining the CQ.
+ EXPECT_TRUE(
+ strstr(method, "/grpc.health") == method ||
+ (strcmp(method, "/grpc.testing.EchoTestService/Echo") == 0 &&
+ (type == experimental::ServerRpcInfo::Type::UNARY ||
+ type == experimental::ServerRpcInfo::Type::BIDI_STREAMING)) ||
+ (strcmp(method, "/grpc.testing.EchoTestService/RequestStream") == 0 &&
+ type == experimental::ServerRpcInfo::Type::CLIENT_STREAMING) ||
+ (strcmp(method, "/grpc.testing.EchoTestService/ResponseStream") == 0 &&
+ type == experimental::ServerRpcInfo::Type::SERVER_STREAMING) ||
+ (strcmp(method, "/grpc.testing.EchoTestService/BidiStream") == 0 &&
+ type == experimental::ServerRpcInfo::Type::BIDI_STREAMING) ||
+ strcmp(method, "/grpc.testing.EchoTestService/Unimplemented") == 0 ||
+ (strcmp(method, "") == 0 &&
+ type == experimental::ServerRpcInfo::Type::BIDI_STREAMING));
+ }
+
+ void Intercept(experimental::InterceptorBatchMethods* methods) override {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
+ auto* map = methods->GetSendInitialMetadata();
+ // Got nothing better to do here for now
+ EXPECT_EQ(map->size(), static_cast<unsigned>(0));
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ EchoRequest req;
+ auto* buffer = methods->GetSerializedSendMessage();
+ auto copied_buffer = *buffer;
+ EXPECT_TRUE(
+ SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
+ .ok());
+ EXPECT_TRUE(req.message().find("Hello") == 0);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_STATUS)) {
+ auto* map = methods->GetSendTrailingMetadata();
+ bool found = false;
+ // Check that we received the metadata as an echo
+ for (const auto& pair : *map) {
+ found = pair.first.find("testkey") == 0 &&
+ pair.second.find("testvalue") == 0;
+ if (found) break;
+ }
+ EXPECT_EQ(found, true);
+ auto status = methods->GetSendStatus();
+ EXPECT_EQ(status.ok(), true);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
+ auto* map = methods->GetRecvInitialMetadata();
+ bool found = false;
+ // Check that we received the metadata as an echo
+ for (const auto& pair : *map) {
+ found = pair.first.find("testkey") == 0 &&
+ pair.second.find("testvalue") == 0;
+ if (found) break;
+ }
+ EXPECT_EQ(found, true);
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
+ EchoResponse* resp =
+ static_cast<EchoResponse*>(methods->GetRecvMessage());
+ if (resp != nullptr) {
+ EXPECT_TRUE(resp->message().find("Hello") == 0);
+ }
+ }
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::POST_RECV_CLOSE)) {
+ // Got nothing interesting to do here
+ }
+ methods->Proceed();
+ }
+
+ private:
+ experimental::ServerRpcInfo* info_;
+};
+
+class LoggingInterceptorFactory
+ : public experimental::ServerInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateServerInterceptor(
+ experimental::ServerRpcInfo* info) override {
+ return new LoggingInterceptor(info);
+ }
+};
+
+// Test if SendMessage function family works as expected for sync/callback apis
+class SyncSendMessageTester : public experimental::Interceptor {
+ public:
+ SyncSendMessageTester(experimental::ServerRpcInfo* /*info*/) {}
+
+ void Intercept(experimental::InterceptorBatchMethods* methods) override {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ string old_msg =
+ static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
+ EXPECT_EQ(old_msg.find("Hello"), 0u);
new_msg_.set_message(TString("World" + old_msg).c_str());
- methods->ModifySendMessage(&new_msg_);
- }
- methods->Proceed();
- }
-
- private:
- EchoRequest new_msg_;
-};
-
-class SyncSendMessageTesterFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new SyncSendMessageTester(info);
- }
-};
-
-// Test if SendMessage function family works as expected for sync/callback apis
-class SyncSendMessageVerifier : public experimental::Interceptor {
- public:
- SyncSendMessageVerifier(experimental::ServerRpcInfo* /*info*/) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- // Make sure that the changes made in SyncSendMessageTester persisted
+ methods->ModifySendMessage(&new_msg_);
+ }
+ methods->Proceed();
+ }
+
+ private:
+ EchoRequest new_msg_;
+};
+
+class SyncSendMessageTesterFactory
+ : public experimental::ServerInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateServerInterceptor(
+ experimental::ServerRpcInfo* info) override {
+ return new SyncSendMessageTester(info);
+ }
+};
+
+// Test if SendMessage function family works as expected for sync/callback apis
+class SyncSendMessageVerifier : public experimental::Interceptor {
+ public:
+ SyncSendMessageVerifier(experimental::ServerRpcInfo* /*info*/) {}
+
+ void Intercept(experimental::InterceptorBatchMethods* methods) override {
+ if (methods->QueryInterceptionHookPoint(
+ experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
+ // Make sure that the changes made in SyncSendMessageTester persisted
string old_msg =
- static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
- EXPECT_EQ(old_msg.find("World"), 0u);
-
- // Remove the "World" part of the string that we added earlier
- new_msg_.set_message(old_msg.erase(0, 5));
- methods->ModifySendMessage(&new_msg_);
-
- // LoggingInterceptor verifies that changes got reverted
- }
- methods->Proceed();
- }
-
- private:
- EchoRequest new_msg_;
-};
-
-class SyncSendMessageVerifierFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- virtual experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new SyncSendMessageVerifier(info);
- }
-};
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- ctx.AddMetadata("testkey", "testvalue");
- auto stream = stub->BidiStream(&ctx);
- for (auto i = 0; i < 10; i++) {
+ static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
+ EXPECT_EQ(old_msg.find("World"), 0u);
+
+ // Remove the "World" part of the string that we added earlier
+ new_msg_.set_message(old_msg.erase(0, 5));
+ methods->ModifySendMessage(&new_msg_);
+
+ // LoggingInterceptor verifies that changes got reverted
+ }
+ methods->Proceed();
+ }
+
+ private:
+ EchoRequest new_msg_;
+};
+
+class SyncSendMessageVerifierFactory
+ : public experimental::ServerInterceptorFactoryInterface {
+ public:
+ virtual experimental::Interceptor* CreateServerInterceptor(
+ experimental::ServerRpcInfo* info) override {
+ return new SyncSendMessageVerifier(info);
+ }
+};
+
+void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+ ClientContext ctx;
+ EchoRequest req;
+ EchoResponse resp;
+ ctx.AddMetadata("testkey", "testvalue");
+ auto stream = stub->BidiStream(&ctx);
+ for (auto i = 0; i < 10; i++) {
req.set_message("Hello" + ::ToString(i));
- stream->Write(req);
- stream->Read(&resp);
- EXPECT_EQ(req.message(), resp.message());
- }
- ASSERT_TRUE(stream->WritesDone());
- Status s = stream->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-class ServerInterceptorsEnd2endSyncUnaryTest : public ::testing::Test {
- protected:
- ServerInterceptorsEnd2endSyncUnaryTest() {
- int port = 5004; // grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
+ stream->Write(req);
+ stream->Read(&resp);
+ EXPECT_EQ(req.message(), resp.message());
+ }
+ ASSERT_TRUE(stream->WritesDone());
+ Status s = stream->Finish();
+ EXPECT_EQ(s.ok(), true);
+}
+
+class ServerInterceptorsEnd2endSyncUnaryTest : public ::testing::Test {
+ protected:
+ ServerInterceptorsEnd2endSyncUnaryTest() {
+ int port = 5004; // grpc_pick_unused_port_or_die();
+
+ ServerBuilder builder;
server_address_ = "localhost:" + ::ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
-
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageTesterFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageVerifierFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- // Add 20 dummy interceptor factories and null interceptor factories
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- creators.push_back(std::unique_ptr<NullInterceptorFactory>(
- new NullInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- server_ = builder.BuildAndStart();
- }
+ builder.AddListeningPort(server_address_, InsecureServerCredentials());
+ builder.RegisterService(&service_);
+
+ std::vector<
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new SyncSendMessageTesterFactory()));
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new SyncSendMessageVerifierFactory()));
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new LoggingInterceptorFactory()));
+ // Add 20 dummy interceptor factories and null interceptor factories
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ creators.push_back(std::unique_ptr<NullInterceptorFactory>(
+ new NullInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ server_ = builder.BuildAndStart();
+ }
TString server_address_;
- TestServiceImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ServerInterceptorsEnd2endSyncUnaryTest, UnaryTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeCall(channel);
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ServerInterceptorsEnd2endSyncStreamingTest : public ::testing::Test {
- protected:
- ServerInterceptorsEnd2endSyncStreamingTest() {
- int port = 5005; // grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
+ TestServiceImpl service_;
+ std::unique_ptr<Server> server_;
+};
+
+TEST_F(ServerInterceptorsEnd2endSyncUnaryTest, UnaryTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ auto channel =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ MakeCall(channel);
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+class ServerInterceptorsEnd2endSyncStreamingTest : public ::testing::Test {
+ protected:
+ ServerInterceptorsEnd2endSyncStreamingTest() {
+ int port = 5005; // grpc_pick_unused_port_or_die();
+
+ ServerBuilder builder;
server_address_ = "localhost:" + ::ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
-
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageTesterFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageVerifierFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- server_ = builder.BuildAndStart();
- }
+ builder.AddListeningPort(server_address_, InsecureServerCredentials());
+ builder.RegisterService(&service_);
+
+ std::vector<
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new SyncSendMessageTesterFactory()));
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new SyncSendMessageVerifierFactory()));
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new LoggingInterceptorFactory()));
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ server_ = builder.BuildAndStart();
+ }
TString server_address_;
- EchoTestServiceStreamingImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ClientStreamingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeClientStreamingCall(channel);
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ServerStreamingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeServerStreamingCall(channel);
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, BidiStreamingTest) {
- ChannelArguments args;
- DummyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeBidiStreamingCall(channel);
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ServerInterceptorsAsyncEnd2endTest : public ::testing::Test {};
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, UnaryTest) {
- DummyInterceptor::Reset();
- int port = 5006; // grpc_pick_unused_port_or_die();
+ EchoTestServiceStreamingImpl service_;
+ std::unique_ptr<Server> server_;
+};
+
+TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ClientStreamingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ auto channel =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ MakeClientStreamingCall(channel);
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ServerStreamingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ auto channel =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ MakeServerStreamingCall(channel);
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, BidiStreamingTest) {
+ ChannelArguments args;
+ DummyInterceptor::Reset();
+ auto channel =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ MakeBidiStreamingCall(channel);
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+}
+
+class ServerInterceptorsAsyncEnd2endTest : public ::testing::Test {};
+
+TEST_F(ServerInterceptorsAsyncEnd2endTest, UnaryTest) {
+ DummyInterceptor::Reset();
+ int port = 5006; // grpc_pick_unused_port_or_die();
string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- EchoTestService::AsyncService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncEcho(&cli_ctx, send_request, cq.get()));
-
- service.RequestEcho(&srv_ctx, &recv_request, &response_writer, cq.get(),
- cq.get(), tag(2));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- Verifier().Expect(2, true).Verify(cq.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok))
- ;
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, BidiStreamingTest) {
- DummyInterceptor::Reset();
- int port = 5007; // grpc_pick_unused_port_or_die();
+ ServerBuilder builder;
+ EchoTestService::AsyncService service;
+ builder.AddListeningPort(server_address, InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new LoggingInterceptorFactory()));
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ auto cq = builder.AddCompletionQueue();
+ auto server = builder.BuildAndStart();
+
+ ChannelArguments args;
+ auto channel =
+ grpc::CreateChannel(server_address, InsecureChannelCredentials());
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
+
+ send_request.set_message("Hello");
+ cli_ctx.AddMetadata("testkey", "testvalue");
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub->AsyncEcho(&cli_ctx, send_request, cq.get()));
+
+ service.RequestEcho(&srv_ctx, &recv_request, &response_writer, cq.get(),
+ cq.get(), tag(2));
+
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+
+ Verifier().Expect(2, true).Verify(cq.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
+ srv_ctx.AddTrailingMetadata("testkey", "testvalue");
+
+ send_response.set_message(recv_request.message());
+ response_writer.Finish(send_response, Status::OK, tag(3));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
+ "testvalue"));
+
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+
+ server->Shutdown();
+ cq->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ while (cq->Next(&ignored_tag, &ignored_ok))
+ ;
+ // grpc_recycle_unused_port(port);
+}
+
+TEST_F(ServerInterceptorsAsyncEnd2endTest, BidiStreamingTest) {
+ DummyInterceptor::Reset();
+ int port = 5007; // grpc_pick_unused_port_or_die();
string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- EchoTestService::AsyncService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub->AsyncBidiStream(&cli_ctx, cq.get(), tag(1)));
-
- service.RequestBidiStream(&srv_ctx, &srv_stream, cq.get(), cq.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq.get());
-
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- cli_stream->Write(send_request, tag(3));
- srv_stream.Read(&recv_request, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq.get());
-
- srv_stream.Finish(Status::OK, tag(9));
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq.get());
-
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok))
- ;
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, GenericRPCTest) {
- DummyInterceptor::Reset();
- int port = 5008; // grpc_pick_unused_port_or_die();
+ ServerBuilder builder;
+ EchoTestService::AsyncService service;
+ builder.AddListeningPort(server_address, InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.push_back(
+ std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
+ new LoggingInterceptorFactory()));
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ auto cq = builder.AddCompletionQueue();
+ auto server = builder.BuildAndStart();
+
+ ChannelArguments args;
+ auto channel =
+ grpc::CreateChannel(server_address, InsecureChannelCredentials());
+ auto stub = grpc::testing::EchoTestService::NewStub(channel);
+
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ ServerContext srv_ctx;
+ grpc::ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
+
+ send_request.set_message("Hello");
+ cli_ctx.AddMetadata("testkey", "testvalue");
+ std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
+ cli_stream(stub->AsyncBidiStream(&cli_ctx, cq.get(), tag(1)));
+
+ service.RequestBidiStream(&srv_ctx, &srv_stream, cq.get(), cq.get(), tag(2));
+
+ Verifier().Expect(1, true).Expect(2, true).Verify(cq.get());
+
+ EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
+ srv_ctx.AddTrailingMetadata("testkey", "testvalue");
+
+ cli_stream->Write(send_request, tag(3));
+ srv_stream.Read(&recv_request, tag(4));
+ Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ srv_stream.Write(send_response, tag(5));
+ cli_stream->Read(&recv_response, tag(6));
+ Verifier().Expect(5, true).Expect(6, true).Verify(cq.get());
+ EXPECT_EQ(send_response.message(), recv_response.message());
+
+ cli_stream->WritesDone(tag(7));
+ srv_stream.Read(&recv_request, tag(8));
+ Verifier().Expect(7, true).Expect(8, false).Verify(cq.get());
+
+ srv_stream.Finish(Status::OK, tag(9));
+ cli_stream->Finish(&recv_status, tag(10));
+ Verifier().Expect(9, true).Expect(10, true).Verify(cq.get());
+
+ EXPECT_TRUE(recv_status.ok());
+ EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
+ "testvalue"));
+
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+
+ server->Shutdown();
+ cq->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ while (cq->Next(&ignored_tag, &ignored_ok))
+ ;
+ // grpc_recycle_unused_port(port);
+}
+
+TEST_F(ServerInterceptorsAsyncEnd2endTest, GenericRPCTest) {
+ DummyInterceptor::Reset();
+ int port = 5008; // grpc_pick_unused_port_or_die();
string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- AsyncGenericService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterAsyncGenericService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto srv_cq = builder.AddCompletionQueue();
- CompletionQueue cli_cq;
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- GenericStub generic_stub(channel);
-
+ ServerBuilder builder;
+ AsyncGenericService service;
+ builder.AddListeningPort(server_address, InsecureServerCredentials());
+ builder.RegisterAsyncGenericService(&service);
+ std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ auto srv_cq = builder.AddCompletionQueue();
+ CompletionQueue cli_cq;
+ auto server = builder.BuildAndStart();
+
+ ChannelArguments args;
+ auto channel =
+ grpc::CreateChannel(server_address, InsecureChannelCredentials());
+ GenericStub generic_stub(channel);
+
const TString kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
-
- // The string needs to be long enough to test heap-based slice.
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
-
+ EchoRequest send_request;
+ EchoRequest recv_request;
+ EchoResponse send_response;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ GenericServerContext srv_ctx;
+ GenericServerAsyncReaderWriter stream(&srv_ctx);
+
+ // The string needs to be long enough to test heap-based slice.
+ send_request.set_message("Hello");
+ cli_ctx.AddMetadata("testkey", "testvalue");
+
CompletionQueue* cq = srv_cq.get();
std::thread request_call([cq]() { Verifier().Expect(4, true).Verify(cq); });
- std::unique_ptr<GenericClientAsyncReaderWriter> call =
- generic_stub.PrepareCall(&cli_ctx, kMethodName, &cli_cq);
- call->StartCall(tag(1));
- Verifier().Expect(1, true).Verify(&cli_cq);
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- call->Write(*send_buffer, tag(2));
- // Send ByteBuffer can be destroyed after calling Write.
- send_buffer.reset();
- Verifier().Expect(2, true).Verify(&cli_cq);
- call->WritesDone(tag(3));
- Verifier().Expect(3, true).Verify(&cli_cq);
-
- service.RequestCall(&srv_ctx, &stream, srv_cq.get(), srv_cq.get(), tag(4));
-
+ std::unique_ptr<GenericClientAsyncReaderWriter> call =
+ generic_stub.PrepareCall(&cli_ctx, kMethodName, &cli_cq);
+ call->StartCall(tag(1));
+ Verifier().Expect(1, true).Verify(&cli_cq);
+ std::unique_ptr<ByteBuffer> send_buffer =
+ SerializeToByteBuffer(&send_request);
+ call->Write(*send_buffer, tag(2));
+ // Send ByteBuffer can be destroyed after calling Write.
+ send_buffer.reset();
+ Verifier().Expect(2, true).Verify(&cli_cq);
+ call->WritesDone(tag(3));
+ Verifier().Expect(3, true).Verify(&cli_cq);
+
+ service.RequestCall(&srv_ctx, &stream, srv_cq.get(), srv_cq.get(), tag(4));
+
request_call.join();
- EXPECT_EQ(kMethodName, srv_ctx.method());
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- ByteBuffer recv_buffer;
- stream.Read(&recv_buffer, tag(5));
- Verifier().Expect(5, true).Verify(srv_cq.get());
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- stream.Write(*send_buffer, tag(6));
- send_buffer.reset();
- Verifier().Expect(6, true).Verify(srv_cq.get());
-
- stream.Finish(Status::OK, tag(7));
- // Shutdown srv_cq before we try to get the tag back, to verify that the
- // interception API handles completion queue shutdowns that take place before
- // all the tags are returned
- srv_cq->Shutdown();
- Verifier().Expect(7, true).Verify(srv_cq.get());
-
- recv_buffer.Clear();
- call->Read(&recv_buffer, tag(8));
- Verifier().Expect(8, true).Verify(&cli_cq);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
-
- call->Finish(&recv_status, tag(9));
- cli_cq.Shutdown();
- Verifier().Expect(9, true).Verify(&cli_cq);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cli_cq.Next(&ignored_tag, &ignored_ok))
- ;
- while (srv_cq->Next(&ignored_tag, &ignored_ok))
- ;
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, UnimplementedRpcTest) {
- DummyInterceptor::Reset();
- int port = 5009; // grpc_pick_unused_port_or_die();
+ EXPECT_EQ(kMethodName, srv_ctx.method());
+ EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
+ srv_ctx.AddTrailingMetadata("testkey", "testvalue");
+
+ ByteBuffer recv_buffer;
+ stream.Read(&recv_buffer, tag(5));
+ Verifier().Expect(5, true).Verify(srv_cq.get());
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
+ EXPECT_EQ(send_request.message(), recv_request.message());
+
+ send_response.set_message(recv_request.message());
+ send_buffer = SerializeToByteBuffer(&send_response);
+ stream.Write(*send_buffer, tag(6));
+ send_buffer.reset();
+ Verifier().Expect(6, true).Verify(srv_cq.get());
+
+ stream.Finish(Status::OK, tag(7));
+ // Shutdown srv_cq before we try to get the tag back, to verify that the
+ // interception API handles completion queue shutdowns that take place before
+ // all the tags are returned
+ srv_cq->Shutdown();
+ Verifier().Expect(7, true).Verify(srv_cq.get());
+
+ recv_buffer.Clear();
+ call->Read(&recv_buffer, tag(8));
+ Verifier().Expect(8, true).Verify(&cli_cq);
+ EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
+
+ call->Finish(&recv_status, tag(9));
+ cli_cq.Shutdown();
+ Verifier().Expect(9, true).Verify(&cli_cq);
+
+ EXPECT_EQ(send_response.message(), recv_response.message());
+ EXPECT_TRUE(recv_status.ok());
+ EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
+ "testvalue"));
+
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+
+ server->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ while (cli_cq.Next(&ignored_tag, &ignored_ok))
+ ;
+ while (srv_cq->Next(&ignored_tag, &ignored_ok))
+ ;
+ // grpc_recycle_unused_port(port);
+}
+
+TEST_F(ServerInterceptorsAsyncEnd2endTest, UnimplementedRpcTest) {
+ DummyInterceptor::Reset();
+ int port = 5009; // grpc_pick_unused_port_or_die();
string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- send_request.set_message("Hello");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncUnimplemented(&cli_ctx, send_request, cq.get()));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
- Verifier().Expect(4, true).Verify(cq.get());
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok))
- ;
- // grpc_recycle_unused_port(port);
-}
-
-class ServerInterceptorsSyncUnimplementedEnd2endTest : public ::testing::Test {
-};
-
-TEST_F(ServerInterceptorsSyncUnimplementedEnd2endTest, UnimplementedRpcTest) {
- DummyInterceptor::Reset();
- int port = 5010; // grpc_pick_unused_port_or_die();
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address, InsecureServerCredentials());
+ std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ auto cq = builder.AddCompletionQueue();
+ auto server = builder.BuildAndStart();
+
+ ChannelArguments args;
+ std::shared_ptr<Channel> channel =
+ grpc::CreateChannel(server_address, InsecureChannelCredentials());
+ std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
+ stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
+ EchoRequest send_request;
+ EchoResponse recv_response;
+ Status recv_status;
+
+ ClientContext cli_ctx;
+ send_request.set_message("Hello");
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
+ stub->AsyncUnimplemented(&cli_ctx, send_request, cq.get()));
+
+ response_reader->Finish(&recv_response, &recv_status, tag(4));
+ Verifier().Expect(4, true).Verify(cq.get());
+
+ EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
+ EXPECT_EQ("", recv_status.error_message());
+
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+
+ server->Shutdown();
+ cq->Shutdown();
+ void* ignored_tag;
+ bool ignored_ok;
+ while (cq->Next(&ignored_tag, &ignored_ok))
+ ;
+ // grpc_recycle_unused_port(port);
+}
+
+class ServerInterceptorsSyncUnimplementedEnd2endTest : public ::testing::Test {
+};
+
+TEST_F(ServerInterceptorsSyncUnimplementedEnd2endTest, UnimplementedRpcTest) {
+ DummyInterceptor::Reset();
+ int port = 5010; // grpc_pick_unused_port_or_die();
string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- TestServiceImpl service;
- builder.RegisterService(&service);
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
- new DummyInterceptorFactory()));
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
-
- ClientContext cli_ctx;
- send_request.set_message("Hello");
- Status recv_status =
- stub->Unimplemented(&cli_ctx, send_request, &recv_response);
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-
- // Make sure all 20 dummy interceptors were run
- EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- // grpc_recycle_unused_port(port);
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ ServerBuilder builder;
+ TestServiceImpl service;
+ builder.RegisterService(&service);
+ builder.AddListeningPort(server_address, InsecureServerCredentials());
+ std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
+ creators;
+ creators.reserve(20);
+ for (auto i = 0; i < 20; i++) {
+ creators.push_back(std::unique_ptr<DummyInterceptorFactory>(
+ new DummyInterceptorFactory()));
+ }
+ builder.experimental().SetInterceptorCreators(std::move(creators));
+ auto server = builder.BuildAndStart();
+
+ ChannelArguments args;
+ std::shared_ptr<Channel> channel =
+ grpc::CreateChannel(server_address, InsecureChannelCredentials());
+ std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
+ stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
+ EchoRequest send_request;
+ EchoResponse recv_response;
+
+ ClientContext cli_ctx;
+ send_request.set_message("Hello");
+ Status recv_status =
+ stub->Unimplemented(&cli_ctx, send_request, &recv_response);
+
+ EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
+ EXPECT_EQ("", recv_status.error_message());
+
+ // Make sure all 20 dummy interceptors were run
+ EXPECT_EQ(DummyInterceptor::GetNumTimesRun(), 20);
+
+ server->Shutdown();
+ // grpc_recycle_unused_port(port);
+}
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_load_reporting_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_load_reporting_end2end_test.cc
index 13833cf66c..d06b74e363 100644
--- a/contrib/libs/grpc/test/cpp/end2end/server_load_reporting_end2end_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/server_load_reporting_end2end_test.cc
@@ -1,192 +1,192 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <thread>
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-#include <grpc++/grpc++.h>
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpcpp/ext/server_load_reporting.h>
-#include <grpcpp/server_builder.h>
-
-#include "src/proto/grpc/lb/v1/load_reporter.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <thread>
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <grpc++/grpc++.h>
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpcpp/ext/server_load_reporting.h>
+#include <grpcpp/server_builder.h>
+
+#include "src/proto/grpc/lb/v1/load_reporter.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
-
-namespace grpc {
-namespace testing {
-namespace {
-
-constexpr double kMetricValue = 3.1415;
-constexpr char kMetricName[] = "METRIC_PI";
-
-// Different messages result in different response statuses. For simplicity in
-// computing request bytes, the message sizes should be the same.
-const char kOkMessage[] = "hello";
-const char kServerErrorMessage[] = "sverr";
-const char kClientErrorMessage[] = "clerr";
-
-class EchoTestServiceImpl : public EchoTestService::Service {
- public:
- ~EchoTestServiceImpl() override {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) override {
- if (request->message() == kServerErrorMessage) {
- return Status(StatusCode::UNKNOWN, "Server error requested");
- }
- if (request->message() == kClientErrorMessage) {
- return Status(StatusCode::FAILED_PRECONDITION, "Client error requested");
- }
- response->set_message(request->message());
- ::grpc::load_reporter::experimental::AddLoadReportingCost(
- context, kMetricName, kMetricValue);
- return Status::OK;
- }
-};
-
-class ServerLoadReportingEnd2endTest : public ::testing::Test {
- protected:
- void SetUp() override {
- server_address_ =
+
+namespace grpc {
+namespace testing {
+namespace {
+
+constexpr double kMetricValue = 3.1415;
+constexpr char kMetricName[] = "METRIC_PI";
+
+// Different messages result in different response statuses. For simplicity in
+// computing request bytes, the message sizes should be the same.
+const char kOkMessage[] = "hello";
+const char kServerErrorMessage[] = "sverr";
+const char kClientErrorMessage[] = "clerr";
+
+class EchoTestServiceImpl : public EchoTestService::Service {
+ public:
+ ~EchoTestServiceImpl() override {}
+
+ Status Echo(ServerContext* context, const EchoRequest* request,
+ EchoResponse* response) override {
+ if (request->message() == kServerErrorMessage) {
+ return Status(StatusCode::UNKNOWN, "Server error requested");
+ }
+ if (request->message() == kClientErrorMessage) {
+ return Status(StatusCode::FAILED_PRECONDITION, "Client error requested");
+ }
+ response->set_message(request->message());
+ ::grpc::load_reporter::experimental::AddLoadReportingCost(
+ context, kMetricName, kMetricValue);
+ return Status::OK;
+ }
+};
+
+class ServerLoadReportingEnd2endTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ server_address_ =
"localhost:" + ToString(grpc_pick_unused_port_or_die());
- server_ =
- ServerBuilder()
- .AddListeningPort(server_address_, InsecureServerCredentials())
- .RegisterService(&echo_service_)
- .SetOption(std::unique_ptr<::grpc::ServerBuilderOption>(
- new ::grpc::load_reporter::experimental::
- LoadReportingServiceServerBuilderOption()))
- .BuildAndStart();
- server_thread_ =
- std::thread(&ServerLoadReportingEnd2endTest::RunServerLoop, this);
- }
-
- void RunServerLoop() { server_->Wait(); }
-
- void TearDown() override {
- server_->Shutdown();
- server_thread_.join();
- }
-
+ server_ =
+ ServerBuilder()
+ .AddListeningPort(server_address_, InsecureServerCredentials())
+ .RegisterService(&echo_service_)
+ .SetOption(std::unique_ptr<::grpc::ServerBuilderOption>(
+ new ::grpc::load_reporter::experimental::
+ LoadReportingServiceServerBuilderOption()))
+ .BuildAndStart();
+ server_thread_ =
+ std::thread(&ServerLoadReportingEnd2endTest::RunServerLoop, this);
+ }
+
+ void RunServerLoop() { server_->Wait(); }
+
+ void TearDown() override {
+ server_->Shutdown();
+ server_thread_.join();
+ }
+
void ClientMakeEchoCalls(const TString& lb_id, const TString& lb_tag,
const TString& message, size_t num_requests) {
- auto stub = EchoTestService::NewStub(
- grpc::CreateChannel(server_address_, InsecureChannelCredentials()));
+ auto stub = EchoTestService::NewStub(
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials()));
TString lb_token = lb_id + lb_tag;
- for (int i = 0; i < num_requests; ++i) {
- ClientContext ctx;
- if (!lb_token.empty()) ctx.AddMetadata(GRPC_LB_TOKEN_MD_KEY, lb_token);
- EchoRequest request;
- EchoResponse response;
- request.set_message(message);
- Status status = stub->Echo(&ctx, request, &response);
- if (message == kOkMessage) {
- ASSERT_EQ(status.error_code(), StatusCode::OK);
- ASSERT_EQ(request.message(), response.message());
- } else if (message == kServerErrorMessage) {
- ASSERT_EQ(status.error_code(), StatusCode::UNKNOWN);
- } else if (message == kClientErrorMessage) {
- ASSERT_EQ(status.error_code(), StatusCode::FAILED_PRECONDITION);
- }
- }
- }
-
+ for (int i = 0; i < num_requests; ++i) {
+ ClientContext ctx;
+ if (!lb_token.empty()) ctx.AddMetadata(GRPC_LB_TOKEN_MD_KEY, lb_token);
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message(message);
+ Status status = stub->Echo(&ctx, request, &response);
+ if (message == kOkMessage) {
+ ASSERT_EQ(status.error_code(), StatusCode::OK);
+ ASSERT_EQ(request.message(), response.message());
+ } else if (message == kServerErrorMessage) {
+ ASSERT_EQ(status.error_code(), StatusCode::UNKNOWN);
+ } else if (message == kClientErrorMessage) {
+ ASSERT_EQ(status.error_code(), StatusCode::FAILED_PRECONDITION);
+ }
+ }
+ }
+
TString server_address_;
- std::unique_ptr<Server> server_;
- std::thread server_thread_;
- EchoTestServiceImpl echo_service_;
-};
-
-TEST_F(ServerLoadReportingEnd2endTest, NoCall) {}
-
-TEST_F(ServerLoadReportingEnd2endTest, BasicReport) {
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- auto stub = ::grpc::lb::v1::LoadReporter::NewStub(channel);
- ClientContext ctx;
- auto stream = stub->ReportLoad(&ctx);
- ::grpc::lb::v1::LoadReportRequest request;
- request.mutable_initial_request()->set_load_balanced_hostname(
- server_address_);
- request.mutable_initial_request()->set_load_key("LOAD_KEY");
- request.mutable_initial_request()
- ->mutable_load_report_interval()
- ->set_seconds(5);
- stream->Write(request);
- gpr_log(GPR_INFO, "Initial request sent.");
- ::grpc::lb::v1::LoadReportResponse response;
- stream->Read(&response);
+ std::unique_ptr<Server> server_;
+ std::thread server_thread_;
+ EchoTestServiceImpl echo_service_;
+};
+
+TEST_F(ServerLoadReportingEnd2endTest, NoCall) {}
+
+TEST_F(ServerLoadReportingEnd2endTest, BasicReport) {
+ auto channel =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ auto stub = ::grpc::lb::v1::LoadReporter::NewStub(channel);
+ ClientContext ctx;
+ auto stream = stub->ReportLoad(&ctx);
+ ::grpc::lb::v1::LoadReportRequest request;
+ request.mutable_initial_request()->set_load_balanced_hostname(
+ server_address_);
+ request.mutable_initial_request()->set_load_key("LOAD_KEY");
+ request.mutable_initial_request()
+ ->mutable_load_report_interval()
+ ->set_seconds(5);
+ stream->Write(request);
+ gpr_log(GPR_INFO, "Initial request sent.");
+ ::grpc::lb::v1::LoadReportResponse response;
+ stream->Read(&response);
const TString& lb_id = response.initial_response().load_balancer_id();
- gpr_log(GPR_INFO, "Initial response received (lb_id: %s).", lb_id.c_str());
- ClientMakeEchoCalls(lb_id, "LB_TAG", kOkMessage, 1);
- while (true) {
- stream->Read(&response);
- if (!response.load().empty()) {
- ASSERT_EQ(response.load().size(), 3);
- for (const auto& load : response.load()) {
- if (load.in_progress_report_case()) {
- // The special load record that reports the number of in-progress
- // calls.
- ASSERT_EQ(load.num_calls_in_progress(), 1);
- } else if (load.orphaned_load_case()) {
- // The call from the balancer doesn't have any valid LB token.
- ASSERT_EQ(load.orphaned_load_case(), load.kLoadKeyUnknown);
- ASSERT_EQ(load.num_calls_started(), 1);
- ASSERT_EQ(load.num_calls_finished_without_error(), 0);
- ASSERT_EQ(load.num_calls_finished_with_error(), 0);
- } else {
- // This corresponds to the calls from the client.
- ASSERT_EQ(load.num_calls_started(), 1);
- ASSERT_EQ(load.num_calls_finished_without_error(), 1);
- ASSERT_EQ(load.num_calls_finished_with_error(), 0);
- ASSERT_GE(load.total_bytes_received(), sizeof(kOkMessage));
- ASSERT_GE(load.total_bytes_sent(), sizeof(kOkMessage));
- ASSERT_EQ(load.metric_data().size(), 1);
- ASSERT_EQ(load.metric_data().Get(0).metric_name(), kMetricName);
- ASSERT_EQ(load.metric_data().Get(0).num_calls_finished_with_metric(),
- 1);
- ASSERT_EQ(load.metric_data().Get(0).total_metric_value(),
- kMetricValue);
- }
- }
- break;
- }
- }
- stream->WritesDone();
- ASSERT_EQ(stream->Finish().error_code(), StatusCode::CANCELLED);
-}
-
-// TODO(juanlishen): Add more tests.
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
+ gpr_log(GPR_INFO, "Initial response received (lb_id: %s).", lb_id.c_str());
+ ClientMakeEchoCalls(lb_id, "LB_TAG", kOkMessage, 1);
+ while (true) {
+ stream->Read(&response);
+ if (!response.load().empty()) {
+ ASSERT_EQ(response.load().size(), 3);
+ for (const auto& load : response.load()) {
+ if (load.in_progress_report_case()) {
+ // The special load record that reports the number of in-progress
+ // calls.
+ ASSERT_EQ(load.num_calls_in_progress(), 1);
+ } else if (load.orphaned_load_case()) {
+ // The call from the balancer doesn't have any valid LB token.
+ ASSERT_EQ(load.orphaned_load_case(), load.kLoadKeyUnknown);
+ ASSERT_EQ(load.num_calls_started(), 1);
+ ASSERT_EQ(load.num_calls_finished_without_error(), 0);
+ ASSERT_EQ(load.num_calls_finished_with_error(), 0);
+ } else {
+ // This corresponds to the calls from the client.
+ ASSERT_EQ(load.num_calls_started(), 1);
+ ASSERT_EQ(load.num_calls_finished_without_error(), 1);
+ ASSERT_EQ(load.num_calls_finished_with_error(), 0);
+ ASSERT_GE(load.total_bytes_received(), sizeof(kOkMessage));
+ ASSERT_GE(load.total_bytes_sent(), sizeof(kOkMessage));
+ ASSERT_EQ(load.metric_data().size(), 1);
+ ASSERT_EQ(load.metric_data().Get(0).metric_name(), kMetricName);
+ ASSERT_EQ(load.metric_data().Get(0).num_calls_finished_with_metric(),
+ 1);
+ ASSERT_EQ(load.metric_data().Get(0).total_metric_value(),
+ kMetricValue);
+ }
+ }
+ break;
+ }
+ }
+ stream->WritesDone();
+ ASSERT_EQ(stream->Finish().error_code(), StatusCode::CANCELLED);
+}
+
+// TODO(juanlishen): Add more tests.
+
+} // namespace
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/shutdown_test.cc b/contrib/libs/grpc/test/cpp/end2end/shutdown_test.cc
index 3aa7a766c4..e980c7ce7c 100644
--- a/contrib/libs/grpc/test/cpp/end2end/shutdown_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/shutdown_test.cc
@@ -1,170 +1,170 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/lib/gpr/env.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/util/test_credentials_provider.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-
-namespace grpc {
-namespace testing {
-
-class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
- public:
- explicit TestServiceImpl(gpr_event* ev) : ev_(ev) {}
-
- Status Echo(ServerContext* context, const EchoRequest* /*request*/,
- EchoResponse* /*response*/) override {
- gpr_event_set(ev_, (void*)1);
- while (!context->IsCancelled()) {
- }
- return Status::OK;
- }
-
- private:
- gpr_event* ev_;
-};
-
-class ShutdownTest : public ::testing::TestWithParam<string> {
- public:
- ShutdownTest() : shutdown_(false), service_(&ev_) { gpr_event_init(&ev_); }
-
- void SetUp() override {
- port_ = grpc_pick_unused_port_or_die();
- server_ = SetUpServer(port_);
- }
-
- std::unique_ptr<Server> SetUpServer(const int port) {
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/lib/gpr/env.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/util/test_credentials_provider.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+
+namespace grpc {
+namespace testing {
+
+class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
+ public:
+ explicit TestServiceImpl(gpr_event* ev) : ev_(ev) {}
+
+ Status Echo(ServerContext* context, const EchoRequest* /*request*/,
+ EchoResponse* /*response*/) override {
+ gpr_event_set(ev_, (void*)1);
+ while (!context->IsCancelled()) {
+ }
+ return Status::OK;
+ }
+
+ private:
+ gpr_event* ev_;
+};
+
+class ShutdownTest : public ::testing::TestWithParam<string> {
+ public:
+ ShutdownTest() : shutdown_(false), service_(&ev_) { gpr_event_init(&ev_); }
+
+ void SetUp() override {
+ port_ = grpc_pick_unused_port_or_die();
+ server_ = SetUpServer(port_);
+ }
+
+ std::unique_ptr<Server> SetUpServer(const int port) {
TString server_address = "localhost:" + to_string(port);
-
- ServerBuilder builder;
- auto server_creds =
- GetCredentialsProvider()->GetServerCredentials(GetParam());
- builder.AddListeningPort(server_address, server_creds);
- builder.RegisterService(&service_);
- std::unique_ptr<Server> server = builder.BuildAndStart();
- return server;
- }
-
- void TearDown() override { GPR_ASSERT(shutdown_); }
-
- void ResetStub() {
- string target = "dns:localhost:" + to_string(port_);
- ChannelArguments args;
- auto channel_creds =
- GetCredentialsProvider()->GetChannelCredentials(GetParam(), &args);
- channel_ = ::grpc::CreateCustomChannel(target, channel_creds, args);
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- string to_string(const int number) {
- std::stringstream strs;
- strs << number;
- return strs.str();
- }
-
- void SendRequest() {
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
- ClientContext context;
- GPR_ASSERT(!shutdown_);
- Status s = stub_->Echo(&context, request, &response);
- GPR_ASSERT(shutdown_);
- }
-
- protected:
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- bool shutdown_;
- int port_;
- gpr_event ev_;
- TestServiceImpl service_;
-};
-
-std::vector<string> GetAllCredentialsTypeList() {
+
+ ServerBuilder builder;
+ auto server_creds =
+ GetCredentialsProvider()->GetServerCredentials(GetParam());
+ builder.AddListeningPort(server_address, server_creds);
+ builder.RegisterService(&service_);
+ std::unique_ptr<Server> server = builder.BuildAndStart();
+ return server;
+ }
+
+ void TearDown() override { GPR_ASSERT(shutdown_); }
+
+ void ResetStub() {
+ string target = "dns:localhost:" + to_string(port_);
+ ChannelArguments args;
+ auto channel_creds =
+ GetCredentialsProvider()->GetChannelCredentials(GetParam(), &args);
+ channel_ = ::grpc::CreateCustomChannel(target, channel_creds, args);
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ string to_string(const int number) {
+ std::stringstream strs;
+ strs << number;
+ return strs.str();
+ }
+
+ void SendRequest() {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+ ClientContext context;
+ GPR_ASSERT(!shutdown_);
+ Status s = stub_->Echo(&context, request, &response);
+ GPR_ASSERT(shutdown_);
+ }
+
+ protected:
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ bool shutdown_;
+ int port_;
+ gpr_event ev_;
+ TestServiceImpl service_;
+};
+
+std::vector<string> GetAllCredentialsTypeList() {
std::vector<TString> credentials_types;
- if (GetCredentialsProvider()->GetChannelCredentials(kInsecureCredentialsType,
- nullptr) != nullptr) {
- credentials_types.push_back(kInsecureCredentialsType);
- }
- auto sec_list = GetCredentialsProvider()->GetSecureCredentialsTypeList();
- for (auto sec = sec_list.begin(); sec != sec_list.end(); sec++) {
- credentials_types.push_back(*sec);
- }
- GPR_ASSERT(!credentials_types.empty());
-
+ if (GetCredentialsProvider()->GetChannelCredentials(kInsecureCredentialsType,
+ nullptr) != nullptr) {
+ credentials_types.push_back(kInsecureCredentialsType);
+ }
+ auto sec_list = GetCredentialsProvider()->GetSecureCredentialsTypeList();
+ for (auto sec = sec_list.begin(); sec != sec_list.end(); sec++) {
+ credentials_types.push_back(*sec);
+ }
+ GPR_ASSERT(!credentials_types.empty());
+
TString credentials_type_list("credentials types:");
- for (const string& type : credentials_types) {
- credentials_type_list.append(" " + type);
- }
- gpr_log(GPR_INFO, "%s", credentials_type_list.c_str());
- return credentials_types;
-}
-
-INSTANTIATE_TEST_SUITE_P(End2EndShutdown, ShutdownTest,
- ::testing::ValuesIn(GetAllCredentialsTypeList()));
-
-// TODO(ctiller): leaked objects in this test
-TEST_P(ShutdownTest, ShutdownTest) {
- ResetStub();
-
- // send the request in a background thread
- std::thread thr(std::bind(&ShutdownTest::SendRequest, this));
-
- // wait for the server to get the event
- gpr_event_wait(&ev_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
-
- shutdown_ = true;
-
- // shutdown should trigger cancellation causing everything to shutdown
- auto deadline =
- std::chrono::system_clock::now() + std::chrono::microseconds(100);
- server_->Shutdown(deadline);
- EXPECT_GE(std::chrono::system_clock::now(), deadline);
-
- thr.join();
-}
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ for (const string& type : credentials_types) {
+ credentials_type_list.append(" " + type);
+ }
+ gpr_log(GPR_INFO, "%s", credentials_type_list.c_str());
+ return credentials_types;
+}
+
+INSTANTIATE_TEST_SUITE_P(End2EndShutdown, ShutdownTest,
+ ::testing::ValuesIn(GetAllCredentialsTypeList()));
+
+// TODO(ctiller): leaked objects in this test
+TEST_P(ShutdownTest, ShutdownTest) {
+ ResetStub();
+
+ // send the request in a background thread
+ std::thread thr(std::bind(&ShutdownTest::SendRequest, this));
+
+ // wait for the server to get the event
+ gpr_event_wait(&ev_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
+
+ shutdown_ = true;
+
+ // shutdown should trigger cancellation causing everything to shutdown
+ auto deadline =
+ std::chrono::system_clock::now() + std::chrono::microseconds(100);
+ server_->Shutdown(deadline);
+ EXPECT_GE(std::chrono::system_clock::now(), deadline);
+
+ thr.join();
+}
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/streaming_throughput_test.cc b/contrib/libs/grpc/test/cpp/end2end/streaming_throughput_test.cc
index f2252063fb..1c6f9806f0 100644
--- a/contrib/libs/grpc/test/cpp/end2end/streaming_throughput_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/streaming_throughput_test.cc
@@ -1,193 +1,193 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <time.h>
-#include <mutex>
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
-const char* kLargeString =
- "("
- "To be, or not to be- that is the question:"
- "Whether 'tis nobler in the mind to suffer"
- "The slings and arrows of outrageous fortune"
- "Or to take arms against a sea of troubles,"
- "And by opposing end them. To die- to sleep-"
- "No more; and by a sleep to say we end"
- "The heartache, and the thousand natural shock"
- "That flesh is heir to. 'Tis a consummation"
- "Devoutly to be wish'd. To die- to sleep."
- "To sleep- perchance to dream: ay, there's the rub!"
- "For in that sleep of death what dreams may come"
- "When we have shuffled off this mortal coil,"
- "Must give us pause. There's the respect"
- "That makes calamity of so long life."
- "For who would bear the whips and scorns of time,"
- "Th' oppressor's wrong, the proud man's contumely,"
- "The pangs of despis'd love, the law's delay,"
- "The insolence of office, and the spurns"
- "That patient merit of th' unworthy takes,"
- "When he himself might his quietus make"
- "With a bare bodkin? Who would these fardels bear,"
- "To grunt and sweat under a weary life,"
- "But that the dread of something after death-"
- "The undiscover'd country, from whose bourn"
- "No traveller returns- puzzles the will,"
- "And makes us rather bear those ills we have"
- "Than fly to others that we know not of?"
- "Thus conscience does make cowards of us all,"
- "And thus the native hue of resolution"
- "Is sicklied o'er with the pale cast of thought,"
- "And enterprises of great pith and moment"
- "With this regard their currents turn awry"
- "And lose the name of action.- Soft you now!"
- "The fair Ophelia!- Nymph, in thy orisons"
- "Be all my sins rememb'red.";
-
-namespace grpc {
-namespace testing {
-
-class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
- public:
- static void BidiStream_Sender(
- ServerReaderWriter<EchoResponse, EchoRequest>* stream,
- gpr_atm* should_exit) {
- EchoResponse response;
- response.set_message(kLargeString);
- while (gpr_atm_acq_load(should_exit) == static_cast<gpr_atm>(0)) {
- struct timespec tv = {0, 1000000}; // 1 ms
- struct timespec rem;
- // TODO (vpai): Mark this blocking
- while (nanosleep(&tv, &rem) != 0) {
- tv = rem;
- };
-
- stream->Write(response);
- }
- }
-
- // Only implement the one method we will be calling for brevity.
- Status BidiStream(
- ServerContext* /*context*/,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- EchoRequest request;
- gpr_atm should_exit;
- gpr_atm_rel_store(&should_exit, static_cast<gpr_atm>(0));
-
- std::thread sender(
- std::bind(&TestServiceImpl::BidiStream_Sender, stream, &should_exit));
-
- while (stream->Read(&request)) {
- struct timespec tv = {0, 3000000}; // 3 ms
- struct timespec rem;
- // TODO (vpai): Mark this blocking
- while (nanosleep(&tv, &rem) != 0) {
- tv = rem;
- };
- }
- gpr_atm_rel_store(&should_exit, static_cast<gpr_atm>(1));
- sender.join();
- return Status::OK;
- }
-};
-
-class End2endTest : public ::testing::Test {
- protected:
- void SetUp() override {
- int port = grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port;
- // Setup server
- ServerBuilder builder;
- builder.AddListeningPort(server_address_.str(),
- InsecureServerCredentials());
- builder.RegisterService(&service_);
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override { server_->Shutdown(); }
-
- void ResetStub() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
-
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- TestServiceImpl service_;
-};
-
-static void Drainer(ClientReaderWriter<EchoRequest, EchoResponse>* reader) {
- EchoResponse response;
- while (reader->Read(&response)) {
- // Just drain out the responses as fast as possible.
- }
-}
-
-TEST_F(End2endTest, StreamingThroughput) {
- ResetStub();
- grpc::ClientContext context;
- auto stream = stub_->BidiStream(&context);
-
- auto reader = stream.get();
- std::thread receiver(std::bind(Drainer, reader));
-
- for (int i = 0; i < 10000; i++) {
- EchoRequest request;
- request.set_message(kLargeString);
- ASSERT_TRUE(stream->Write(request));
- if (i % 1000 == 0) {
- gpr_log(GPR_INFO, "Send count = %d", i);
- }
- }
- stream->WritesDone();
- receiver.join();
-}
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <time.h>
+#include <mutex>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
+const char* kLargeString =
+ "("
+ "To be, or not to be- that is the question:"
+ "Whether 'tis nobler in the mind to suffer"
+ "The slings and arrows of outrageous fortune"
+ "Or to take arms against a sea of troubles,"
+ "And by opposing end them. To die- to sleep-"
+ "No more; and by a sleep to say we end"
+ "The heartache, and the thousand natural shock"
+ "That flesh is heir to. 'Tis a consummation"
+ "Devoutly to be wish'd. To die- to sleep."
+ "To sleep- perchance to dream: ay, there's the rub!"
+ "For in that sleep of death what dreams may come"
+ "When we have shuffled off this mortal coil,"
+ "Must give us pause. There's the respect"
+ "That makes calamity of so long life."
+ "For who would bear the whips and scorns of time,"
+ "Th' oppressor's wrong, the proud man's contumely,"
+ "The pangs of despis'd love, the law's delay,"
+ "The insolence of office, and the spurns"
+ "That patient merit of th' unworthy takes,"
+ "When he himself might his quietus make"
+ "With a bare bodkin? Who would these fardels bear,"
+ "To grunt and sweat under a weary life,"
+ "But that the dread of something after death-"
+ "The undiscover'd country, from whose bourn"
+ "No traveller returns- puzzles the will,"
+ "And makes us rather bear those ills we have"
+ "Than fly to others that we know not of?"
+ "Thus conscience does make cowards of us all,"
+ "And thus the native hue of resolution"
+ "Is sicklied o'er with the pale cast of thought,"
+ "And enterprises of great pith and moment"
+ "With this regard their currents turn awry"
+ "And lose the name of action.- Soft you now!"
+ "The fair Ophelia!- Nymph, in thy orisons"
+ "Be all my sins rememb'red.";
+
+namespace grpc {
+namespace testing {
+
+class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
+ public:
+ static void BidiStream_Sender(
+ ServerReaderWriter<EchoResponse, EchoRequest>* stream,
+ gpr_atm* should_exit) {
+ EchoResponse response;
+ response.set_message(kLargeString);
+ while (gpr_atm_acq_load(should_exit) == static_cast<gpr_atm>(0)) {
+ struct timespec tv = {0, 1000000}; // 1 ms
+ struct timespec rem;
+ // TODO (vpai): Mark this blocking
+ while (nanosleep(&tv, &rem) != 0) {
+ tv = rem;
+ };
+
+ stream->Write(response);
+ }
+ }
+
+ // Only implement the one method we will be calling for brevity.
+ Status BidiStream(
+ ServerContext* /*context*/,
+ ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
+ EchoRequest request;
+ gpr_atm should_exit;
+ gpr_atm_rel_store(&should_exit, static_cast<gpr_atm>(0));
+
+ std::thread sender(
+ std::bind(&TestServiceImpl::BidiStream_Sender, stream, &should_exit));
+
+ while (stream->Read(&request)) {
+ struct timespec tv = {0, 3000000}; // 3 ms
+ struct timespec rem;
+ // TODO (vpai): Mark this blocking
+ while (nanosleep(&tv, &rem) != 0) {
+ tv = rem;
+ };
+ }
+ gpr_atm_rel_store(&should_exit, static_cast<gpr_atm>(1));
+ sender.join();
+ return Status::OK;
+ }
+};
+
+class End2endTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ int port = grpc_pick_unused_port_or_die();
+ server_address_ << "localhost:" << port;
+ // Setup server
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address_.str(),
+ InsecureServerCredentials());
+ builder.RegisterService(&service_);
+ server_ = builder.BuildAndStart();
+ }
+
+ void TearDown() override { server_->Shutdown(); }
+
+ void ResetStub() {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+ std::ostringstream server_address_;
+ TestServiceImpl service_;
+};
+
+static void Drainer(ClientReaderWriter<EchoRequest, EchoResponse>* reader) {
+ EchoResponse response;
+ while (reader->Read(&response)) {
+ // Just drain out the responses as fast as possible.
+ }
+}
+
+TEST_F(End2endTest, StreamingThroughput) {
+ ResetStub();
+ grpc::ClientContext context;
+ auto stream = stub_->BidiStream(&context);
+
+ auto reader = stream.get();
+ std::thread receiver(std::bind(Drainer, reader));
+
+ for (int i = 0; i < 10000; i++) {
+ EchoRequest request;
+ request.set_message(kLargeString);
+ ASSERT_TRUE(stream->Write(request));
+ if (i % 1000 == 0) {
+ gpr_log(GPR_INFO, "Send count = %d", i);
+ }
+ }
+ stream->WritesDone();
+ receiver.join();
+}
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
index 5b212cba31..225cb2624b 100644
--- a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
@@ -1,98 +1,98 @@
-/*
- *
- * Copyright 2018 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.
- *
- */
-
-#include "test/cpp/end2end/test_health_check_service_impl.h"
-
-#include <grpc/grpc.h>
-
-using grpc::health::v1::HealthCheckRequest;
-using grpc::health::v1::HealthCheckResponse;
-
-namespace grpc {
-namespace testing {
-
-Status HealthCheckServiceImpl::Check(ServerContext* /*context*/,
- const HealthCheckRequest* request,
- HealthCheckResponse* response) {
- std::lock_guard<std::mutex> lock(mu_);
- auto iter = status_map_.find(request->service());
- if (iter == status_map_.end()) {
- return Status(StatusCode::NOT_FOUND, "");
- }
- response->set_status(iter->second);
- return Status::OK;
-}
-
-Status HealthCheckServiceImpl::Watch(
- ServerContext* context, const HealthCheckRequest* request,
- ::grpc::ServerWriter<HealthCheckResponse>* writer) {
- auto last_state = HealthCheckResponse::UNKNOWN;
- while (!context->IsCancelled()) {
- {
- std::lock_guard<std::mutex> lock(mu_);
- HealthCheckResponse response;
- auto iter = status_map_.find(request->service());
- if (iter == status_map_.end()) {
- response.set_status(response.SERVICE_UNKNOWN);
- } else {
- response.set_status(iter->second);
- }
- if (response.status() != last_state) {
- writer->Write(response, ::grpc::WriteOptions());
- last_state = response.status();
- }
- }
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(1000, GPR_TIMESPAN)));
- }
- return Status::OK;
-}
-
-void HealthCheckServiceImpl::SetStatus(
+/*
+ *
+ * Copyright 2018 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.
+ *
+ */
+
+#include "test/cpp/end2end/test_health_check_service_impl.h"
+
+#include <grpc/grpc.h>
+
+using grpc::health::v1::HealthCheckRequest;
+using grpc::health::v1::HealthCheckResponse;
+
+namespace grpc {
+namespace testing {
+
+Status HealthCheckServiceImpl::Check(ServerContext* /*context*/,
+ const HealthCheckRequest* request,
+ HealthCheckResponse* response) {
+ std::lock_guard<std::mutex> lock(mu_);
+ auto iter = status_map_.find(request->service());
+ if (iter == status_map_.end()) {
+ return Status(StatusCode::NOT_FOUND, "");
+ }
+ response->set_status(iter->second);
+ return Status::OK;
+}
+
+Status HealthCheckServiceImpl::Watch(
+ ServerContext* context, const HealthCheckRequest* request,
+ ::grpc::ServerWriter<HealthCheckResponse>* writer) {
+ auto last_state = HealthCheckResponse::UNKNOWN;
+ while (!context->IsCancelled()) {
+ {
+ std::lock_guard<std::mutex> lock(mu_);
+ HealthCheckResponse response;
+ auto iter = status_map_.find(request->service());
+ if (iter == status_map_.end()) {
+ response.set_status(response.SERVICE_UNKNOWN);
+ } else {
+ response.set_status(iter->second);
+ }
+ if (response.status() != last_state) {
+ writer->Write(response, ::grpc::WriteOptions());
+ last_state = response.status();
+ }
+ }
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_millis(1000, GPR_TIMESPAN)));
+ }
+ return Status::OK;
+}
+
+void HealthCheckServiceImpl::SetStatus(
const TString& service_name,
- HealthCheckResponse::ServingStatus status) {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- status = HealthCheckResponse::NOT_SERVING;
- }
- status_map_[service_name] = status;
-}
-
-void HealthCheckServiceImpl::SetAll(HealthCheckResponse::ServingStatus status) {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- return;
- }
- for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
- iter->second = status;
- }
-}
-
-void HealthCheckServiceImpl::Shutdown() {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- return;
- }
- shutdown_ = true;
- for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
- iter->second = HealthCheckResponse::NOT_SERVING;
- }
-}
-
-} // namespace testing
-} // namespace grpc
+ HealthCheckResponse::ServingStatus status) {
+ std::lock_guard<std::mutex> lock(mu_);
+ if (shutdown_) {
+ status = HealthCheckResponse::NOT_SERVING;
+ }
+ status_map_[service_name] = status;
+}
+
+void HealthCheckServiceImpl::SetAll(HealthCheckResponse::ServingStatus status) {
+ std::lock_guard<std::mutex> lock(mu_);
+ if (shutdown_) {
+ return;
+ }
+ for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
+ iter->second = status;
+ }
+}
+
+void HealthCheckServiceImpl::Shutdown() {
+ std::lock_guard<std::mutex> lock(mu_);
+ if (shutdown_) {
+ return;
+ }
+ shutdown_ = true;
+ for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
+ iter->second = HealthCheckResponse::NOT_SERVING;
+ }
+}
+
+} // namespace testing
+} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
index d370e4693a..3bb4d4f9ca 100644
--- a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
+++ b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
@@ -1,58 +1,58 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-#ifndef GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
-#define GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
-
-#include <map>
-#include <mutex>
-
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/status.h>
-
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-
-namespace grpc {
-namespace testing {
-
-// A sample sync implementation of the health checking service. This does the
-// same thing as the default one.
-class HealthCheckServiceImpl : public health::v1::Health::Service {
- public:
- Status Check(ServerContext* context,
- const health::v1::HealthCheckRequest* request,
- health::v1::HealthCheckResponse* response) override;
- Status Watch(ServerContext* context,
- const health::v1::HealthCheckRequest* request,
- ServerWriter<health::v1::HealthCheckResponse>* writer) override;
+/*
+ *
+ * Copyright 2018 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+#ifndef GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
+#define GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
+
+#include <map>
+#include <mutex>
+
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/status.h>
+
+#include "src/proto/grpc/health/v1/health.grpc.pb.h"
+
+namespace grpc {
+namespace testing {
+
+// A sample sync implementation of the health checking service. This does the
+// same thing as the default one.
+class HealthCheckServiceImpl : public health::v1::Health::Service {
+ public:
+ Status Check(ServerContext* context,
+ const health::v1::HealthCheckRequest* request,
+ health::v1::HealthCheckResponse* response) override;
+ Status Watch(ServerContext* context,
+ const health::v1::HealthCheckRequest* request,
+ ServerWriter<health::v1::HealthCheckResponse>* writer) override;
void SetStatus(const TString& service_name,
- health::v1::HealthCheckResponse::ServingStatus status);
- void SetAll(health::v1::HealthCheckResponse::ServingStatus status);
-
- void Shutdown();
-
- private:
- std::mutex mu_;
- bool shutdown_ = false;
+ health::v1::HealthCheckResponse::ServingStatus status);
+ void SetAll(health::v1::HealthCheckResponse::ServingStatus status);
+
+ void Shutdown();
+
+ private:
+ std::mutex mu_;
+ bool shutdown_ = false;
std::map<const TString, health::v1::HealthCheckResponse::ServingStatus>
- status_map_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
+ status_map_;
+};
+
+} // namespace testing
+} // namespace grpc
+
+#endif // GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
index 078977e824..55821905e4 100644
--- a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
@@ -1,144 +1,144 @@
-/*
- *
- * Copyright 2016 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.
- *
- */
-
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <grpc/support/log.h>
+/*
+ *
+ * Copyright 2016 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.
+ *
+ */
+
+#include "test/cpp/end2end/test_service_impl.h"
+
+#include <grpc/support/log.h>
#include <grpcpp/alarm.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
-#include <gtest/gtest.h>
-
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/server_context.h>
+#include <gtest/gtest.h>
+
#include <util/generic/string.h>
-#include <thread>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-using std::chrono::system_clock;
-
-namespace grpc {
-namespace testing {
+#include <thread>
+
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/cpp/util/string_ref_helper.h"
+
+using std::chrono::system_clock;
+
+namespace grpc {
+namespace testing {
namespace internal {
-
-// When echo_deadline is requested, deadline seen in the ServerContext is set in
-// the response in seconds.
-void MaybeEchoDeadline(experimental::ServerContextBase* context,
- const EchoRequest* request, EchoResponse* response) {
- if (request->has_param() && request->param().echo_deadline()) {
- gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
- if (context->deadline() != system_clock::time_point::max()) {
- Timepoint2Timespec(context->deadline(), &deadline);
- }
- response->mutable_param()->set_request_deadline(deadline.tv_sec);
- }
-}
-
+
+// When echo_deadline is requested, deadline seen in the ServerContext is set in
+// the response in seconds.
+void MaybeEchoDeadline(experimental::ServerContextBase* context,
+ const EchoRequest* request, EchoResponse* response) {
+ if (request->has_param() && request->param().echo_deadline()) {
+ gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
+ if (context->deadline() != system_clock::time_point::max()) {
+ Timepoint2Timespec(context->deadline(), &deadline);
+ }
+ response->mutable_param()->set_request_deadline(deadline.tv_sec);
+ }
+}
+
void CheckServerAuthContext(const experimental::ServerContextBase* context,
const TString& expected_transport_security_type,
const TString& expected_client_identity) {
- std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
- std::vector<grpc::string_ref> tst =
- auth_ctx->FindPropertyValues("transport_security_type");
- EXPECT_EQ(1u, tst.size());
- EXPECT_EQ(expected_transport_security_type.c_str(), ToString(tst[0]));
- if (expected_client_identity.empty()) {
- EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
- EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
- EXPECT_FALSE(auth_ctx->IsPeerAuthenticated());
- } else {
- auto identity = auth_ctx->GetPeerIdentity();
- EXPECT_TRUE(auth_ctx->IsPeerAuthenticated());
- EXPECT_EQ(1u, identity.size());
+ std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
+ std::vector<grpc::string_ref> tst =
+ auth_ctx->FindPropertyValues("transport_security_type");
+ EXPECT_EQ(1u, tst.size());
+ EXPECT_EQ(expected_transport_security_type.c_str(), ToString(tst[0]));
+ if (expected_client_identity.empty()) {
+ EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
+ EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
+ EXPECT_FALSE(auth_ctx->IsPeerAuthenticated());
+ } else {
+ auto identity = auth_ctx->GetPeerIdentity();
+ EXPECT_TRUE(auth_ctx->IsPeerAuthenticated());
+ EXPECT_EQ(1u, identity.size());
EXPECT_EQ(expected_client_identity.c_str(), ToString(identity[0]));
- }
-}
-
-// Returns the number of pairs in metadata that exactly match the given
-// key-value pair. Returns -1 if the pair wasn't found.
-int MetadataMatchCount(
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
+ }
+}
+
+// Returns the number of pairs in metadata that exactly match the given
+// key-value pair. Returns -1 if the pair wasn't found.
+int MetadataMatchCount(
+ const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
const TString& key, const TString& value) {
- int count = 0;
- for (const auto& metadatum : metadata) {
- if (ToString(metadatum.first) == key &&
- ToString(metadatum.second) == value) {
- count++;
- }
- }
- return count;
-}
-
-int GetIntValueFromMetadataHelper(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value) {
- if (metadata.find(key) != metadata.end()) {
- std::istringstream iss(ToString(metadata.find(key)->second));
- iss >> default_value;
- gpr_log(GPR_INFO, "%s : %d", key, default_value);
- }
-
- return default_value;
-}
-
-int GetIntValueFromMetadata(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value) {
- return GetIntValueFromMetadataHelper(key, metadata, default_value);
-}
-
-void ServerTryCancel(ServerContext* context) {
- EXPECT_FALSE(context->IsCancelled());
- context->TryCancel();
- gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
- // Now wait until it's really canceled
- while (!context->IsCancelled()) {
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(1000, GPR_TIMESPAN)));
- }
-}
-
-void ServerTryCancelNonblocking(experimental::CallbackServerContext* context) {
- EXPECT_FALSE(context->IsCancelled());
- context->TryCancel();
+ int count = 0;
+ for (const auto& metadatum : metadata) {
+ if (ToString(metadatum.first) == key &&
+ ToString(metadatum.second) == value) {
+ count++;
+ }
+ }
+ return count;
+}
+
+int GetIntValueFromMetadataHelper(
+ const char* key,
+ const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
+ int default_value) {
+ if (metadata.find(key) != metadata.end()) {
+ std::istringstream iss(ToString(metadata.find(key)->second));
+ iss >> default_value;
+ gpr_log(GPR_INFO, "%s : %d", key, default_value);
+ }
+
+ return default_value;
+}
+
+int GetIntValueFromMetadata(
+ const char* key,
+ const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
+ int default_value) {
+ return GetIntValueFromMetadataHelper(key, metadata, default_value);
+}
+
+void ServerTryCancel(ServerContext* context) {
+ EXPECT_FALSE(context->IsCancelled());
+ context->TryCancel();
+ gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
+ // Now wait until it's really canceled
+ while (!context->IsCancelled()) {
+ gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_micros(1000, GPR_TIMESPAN)));
+ }
+}
+
+void ServerTryCancelNonblocking(experimental::CallbackServerContext* context) {
+ EXPECT_FALSE(context->IsCancelled());
+ context->TryCancel();
gpr_log(GPR_INFO,
"Server called TryCancelNonblocking() to cancel the request");
-}
-
+}
+
} // namespace internal
-
-experimental::ServerUnaryReactor* CallbackTestServiceImpl::Echo(
- experimental::CallbackServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- class Reactor : public ::grpc::experimental::ServerUnaryReactor {
- public:
- Reactor(CallbackTestServiceImpl* service,
- experimental::CallbackServerContext* ctx,
- const EchoRequest* request, EchoResponse* response)
- : service_(service), ctx_(ctx), req_(request), resp_(response) {
- // It should be safe to call IsCancelled here, even though we don't know
- // the result. Call it asynchronously to see if we trigger any data races.
+
+experimental::ServerUnaryReactor* CallbackTestServiceImpl::Echo(
+ experimental::CallbackServerContext* context, const EchoRequest* request,
+ EchoResponse* response) {
+ class Reactor : public ::grpc::experimental::ServerUnaryReactor {
+ public:
+ Reactor(CallbackTestServiceImpl* service,
+ experimental::CallbackServerContext* ctx,
+ const EchoRequest* request, EchoResponse* response)
+ : service_(service), ctx_(ctx), req_(request), resp_(response) {
+ // It should be safe to call IsCancelled here, even though we don't know
+ // the result. Call it asynchronously to see if we trigger any data races.
// Join it in OnDone (technically that could be blocking but shouldn't be
// for very long).
- async_cancel_check_ = std::thread([this] { (void)ctx_->IsCancelled(); });
-
+ async_cancel_check_ = std::thread([this] { (void)ctx_->IsCancelled(); });
+
started_ = true;
if (request->has_param() &&
@@ -158,349 +158,349 @@ experimental::ServerUnaryReactor* CallbackTestServiceImpl::Echo(
void StartRpc() {
if (req_->has_param() && req_->param().server_sleep_us() > 0) {
- // Set an alarm for that much time
- alarm_.experimental().Set(
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ // Set an alarm for that much time
+ alarm_.experimental().Set(
+ gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_micros(req_->param().server_sleep_us(),
GPR_TIMESPAN)),
- [this](bool ok) { NonDelayed(ok); });
+ [this](bool ok) { NonDelayed(ok); });
return;
- }
+ }
NonDelayed(true);
- }
- void OnSendInitialMetadataDone(bool ok) override {
- EXPECT_TRUE(ok);
- initial_metadata_sent_ = true;
- }
- void OnCancel() override {
- EXPECT_TRUE(started_);
- EXPECT_TRUE(ctx_->IsCancelled());
- on_cancel_invoked_ = true;
+ }
+ void OnSendInitialMetadataDone(bool ok) override {
+ EXPECT_TRUE(ok);
+ initial_metadata_sent_ = true;
+ }
+ void OnCancel() override {
+ EXPECT_TRUE(started_);
+ EXPECT_TRUE(ctx_->IsCancelled());
+ on_cancel_invoked_ = true;
std::lock_guard<std::mutex> l(cancel_mu_);
cancel_cv_.notify_one();
- }
- void OnDone() override {
- if (req_->has_param() && req_->param().echo_metadata_initially()) {
- EXPECT_TRUE(initial_metadata_sent_);
- }
- EXPECT_EQ(ctx_->IsCancelled(), on_cancel_invoked_);
+ }
+ void OnDone() override {
+ if (req_->has_param() && req_->param().echo_metadata_initially()) {
+ EXPECT_TRUE(initial_metadata_sent_);
+ }
+ EXPECT_EQ(ctx_->IsCancelled(), on_cancel_invoked_);
// Validate that finishing with a non-OK status doesn't cause cancellation
if (req_->has_param() && req_->param().has_expected_error()) {
EXPECT_FALSE(on_cancel_invoked_);
}
- async_cancel_check_.join();
+ async_cancel_check_.join();
if (rpc_wait_thread_.joinable()) {
rpc_wait_thread_.join();
}
if (finish_when_cancelled_.joinable()) {
finish_when_cancelled_.join();
}
- delete this;
- }
-
- private:
- void NonDelayed(bool ok) {
- if (!ok) {
- EXPECT_TRUE(ctx_->IsCancelled());
- Finish(Status::CANCELLED);
- return;
- }
- if (req_->has_param() && req_->param().server_die()) {
- gpr_log(GPR_ERROR, "The request should not reach application handler.");
- GPR_ASSERT(0);
- }
- if (req_->has_param() && req_->param().has_expected_error()) {
- const auto& error = req_->param().expected_error();
- Finish(Status(static_cast<StatusCode>(error.code()),
- error.error_message(), error.binary_error_details()));
- return;
- }
+ delete this;
+ }
+
+ private:
+ void NonDelayed(bool ok) {
+ if (!ok) {
+ EXPECT_TRUE(ctx_->IsCancelled());
+ Finish(Status::CANCELLED);
+ return;
+ }
+ if (req_->has_param() && req_->param().server_die()) {
+ gpr_log(GPR_ERROR, "The request should not reach application handler.");
+ GPR_ASSERT(0);
+ }
+ if (req_->has_param() && req_->param().has_expected_error()) {
+ const auto& error = req_->param().expected_error();
+ Finish(Status(static_cast<StatusCode>(error.code()),
+ error.error_message(), error.binary_error_details()));
+ return;
+ }
int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, ctx_->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel != DO_NOT_CANCEL) {
- // Since this is a unary RPC, by the time this server handler is called,
- // the 'request' message is already read from the client. So the
- // scenarios in server_try_cancel don't make much sense. Just cancel the
- // RPC as long as server_try_cancel is not DO_NOT_CANCEL
- EXPECT_FALSE(ctx_->IsCancelled());
- ctx_->TryCancel();
- gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
+ kServerTryCancelRequest, ctx_->client_metadata(), DO_NOT_CANCEL);
+ if (server_try_cancel != DO_NOT_CANCEL) {
+ // Since this is a unary RPC, by the time this server handler is called,
+ // the 'request' message is already read from the client. So the
+ // scenarios in server_try_cancel don't make much sense. Just cancel the
+ // RPC as long as server_try_cancel is not DO_NOT_CANCEL
+ EXPECT_FALSE(ctx_->IsCancelled());
+ ctx_->TryCancel();
+ gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
FinishWhenCancelledAsync();
- return;
- }
- resp_->set_message(req_->message());
+ return;
+ }
+ resp_->set_message(req_->message());
internal::MaybeEchoDeadline(ctx_, req_, resp_);
- if (service_->host_) {
- resp_->mutable_param()->set_host(*service_->host_);
- }
- if (req_->has_param() && req_->param().client_cancel_after_us()) {
- {
- std::unique_lock<std::mutex> lock(service_->mu_);
- service_->signal_client_ = true;
- }
+ if (service_->host_) {
+ resp_->mutable_param()->set_host(*service_->host_);
+ }
+ if (req_->has_param() && req_->param().client_cancel_after_us()) {
+ {
+ std::unique_lock<std::mutex> lock(service_->mu_);
+ service_->signal_client_ = true;
+ }
FinishWhenCancelledAsync();
- return;
- } else if (req_->has_param() && req_->param().server_cancel_after_us()) {
- alarm_.experimental().Set(
- gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(req_->param().server_cancel_after_us(),
- GPR_TIMESPAN)),
- [this](bool) { Finish(Status::CANCELLED); });
- return;
- } else if (!req_->has_param() || !req_->param().skip_cancelled_check()) {
- EXPECT_FALSE(ctx_->IsCancelled());
- }
-
- if (req_->has_param() && req_->param().echo_metadata_initially()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>&
- client_metadata = ctx_->client_metadata();
- for (const auto& metadatum : client_metadata) {
- ctx_->AddInitialMetadata(ToString(metadatum.first),
- ToString(metadatum.second));
- }
- StartSendInitialMetadata();
- }
-
- if (req_->has_param() && req_->param().echo_metadata()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>&
- client_metadata = ctx_->client_metadata();
- for (const auto& metadatum : client_metadata) {
- ctx_->AddTrailingMetadata(ToString(metadatum.first),
- ToString(metadatum.second));
- }
- // Terminate rpc with error and debug info in trailer.
- if (req_->param().debug_info().stack_entries_size() ||
- !req_->param().debug_info().detail().empty()) {
+ return;
+ } else if (req_->has_param() && req_->param().server_cancel_after_us()) {
+ alarm_.experimental().Set(
+ gpr_time_add(
+ gpr_now(GPR_CLOCK_REALTIME),
+ gpr_time_from_micros(req_->param().server_cancel_after_us(),
+ GPR_TIMESPAN)),
+ [this](bool) { Finish(Status::CANCELLED); });
+ return;
+ } else if (!req_->has_param() || !req_->param().skip_cancelled_check()) {
+ EXPECT_FALSE(ctx_->IsCancelled());
+ }
+
+ if (req_->has_param() && req_->param().echo_metadata_initially()) {
+ const std::multimap<grpc::string_ref, grpc::string_ref>&
+ client_metadata = ctx_->client_metadata();
+ for (const auto& metadatum : client_metadata) {
+ ctx_->AddInitialMetadata(ToString(metadatum.first),
+ ToString(metadatum.second));
+ }
+ StartSendInitialMetadata();
+ }
+
+ if (req_->has_param() && req_->param().echo_metadata()) {
+ const std::multimap<grpc::string_ref, grpc::string_ref>&
+ client_metadata = ctx_->client_metadata();
+ for (const auto& metadatum : client_metadata) {
+ ctx_->AddTrailingMetadata(ToString(metadatum.first),
+ ToString(metadatum.second));
+ }
+ // Terminate rpc with error and debug info in trailer.
+ if (req_->param().debug_info().stack_entries_size() ||
+ !req_->param().debug_info().detail().empty()) {
TString serialized_debug_info =
- req_->param().debug_info().SerializeAsString();
- ctx_->AddTrailingMetadata(kDebugInfoTrailerKey,
- serialized_debug_info);
- Finish(Status::CANCELLED);
- return;
- }
- }
- if (req_->has_param() &&
- (req_->param().expected_client_identity().length() > 0 ||
- req_->param().check_auth_context())) {
+ req_->param().debug_info().SerializeAsString();
+ ctx_->AddTrailingMetadata(kDebugInfoTrailerKey,
+ serialized_debug_info);
+ Finish(Status::CANCELLED);
+ return;
+ }
+ }
+ if (req_->has_param() &&
+ (req_->param().expected_client_identity().length() > 0 ||
+ req_->param().check_auth_context())) {
internal::CheckServerAuthContext(
ctx_, req_->param().expected_transport_security_type(),
req_->param().expected_client_identity());
- }
- if (req_->has_param() && req_->param().response_message_length() > 0) {
- resp_->set_message(
+ }
+ if (req_->has_param() && req_->param().response_message_length() > 0) {
+ resp_->set_message(
TString(req_->param().response_message_length(), '\0'));
- }
- if (req_->has_param() && req_->param().echo_peer()) {
- resp_->mutable_param()->set_peer(ctx_->peer().c_str());
- }
- Finish(Status::OK);
- }
+ }
+ if (req_->has_param() && req_->param().echo_peer()) {
+ resp_->mutable_param()->set_peer(ctx_->peer().c_str());
+ }
+ Finish(Status::OK);
+ }
void FinishWhenCancelledAsync() {
finish_when_cancelled_ = std::thread([this] {
std::unique_lock<std::mutex> l(cancel_mu_);
cancel_cv_.wait(l, [this] { return ctx_->IsCancelled(); });
- Finish(Status::CANCELLED);
+ Finish(Status::CANCELLED);
});
- }
-
- CallbackTestServiceImpl* const service_;
- experimental::CallbackServerContext* const ctx_;
- const EchoRequest* const req_;
- EchoResponse* const resp_;
- Alarm alarm_;
+ }
+
+ CallbackTestServiceImpl* const service_;
+ experimental::CallbackServerContext* const ctx_;
+ const EchoRequest* const req_;
+ EchoResponse* const resp_;
+ Alarm alarm_;
std::mutex cancel_mu_;
std::condition_variable cancel_cv_;
bool initial_metadata_sent_ = false;
bool started_ = false;
bool on_cancel_invoked_ = false;
- std::thread async_cancel_check_;
+ std::thread async_cancel_check_;
std::thread rpc_wait_thread_;
std::thread finish_when_cancelled_;
- };
-
- return new Reactor(this, context, request, response);
-}
-
-experimental::ServerUnaryReactor*
-CallbackTestServiceImpl::CheckClientInitialMetadata(
+ };
+
+ return new Reactor(this, context, request, response);
+}
+
+experimental::ServerUnaryReactor*
+CallbackTestServiceImpl::CheckClientInitialMetadata(
experimental::CallbackServerContext* context, const SimpleRequest42*,
SimpleResponse42*) {
- class Reactor : public ::grpc::experimental::ServerUnaryReactor {
- public:
- explicit Reactor(experimental::CallbackServerContext* ctx) {
+ class Reactor : public ::grpc::experimental::ServerUnaryReactor {
+ public:
+ explicit Reactor(experimental::CallbackServerContext* ctx) {
EXPECT_EQ(internal::MetadataMatchCount(ctx->client_metadata(),
kCheckClientInitialMetadataKey,
kCheckClientInitialMetadataVal),
- 1);
- EXPECT_EQ(ctx->client_metadata().count(kCheckClientInitialMetadataKey),
- 1u);
- Finish(Status::OK);
- }
- void OnDone() override { delete this; }
- };
-
- return new Reactor(context);
-}
-
-experimental::ServerReadReactor<EchoRequest>*
-CallbackTestServiceImpl::RequestStream(
- experimental::CallbackServerContext* context, EchoResponse* response) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
+ 1);
+ EXPECT_EQ(ctx->client_metadata().count(kCheckClientInitialMetadataKey),
+ 1u);
+ Finish(Status::OK);
+ }
+ void OnDone() override { delete this; }
+ };
+
+ return new Reactor(context);
+}
+
+experimental::ServerReadReactor<EchoRequest>*
+CallbackTestServiceImpl::RequestStream(
+ experimental::CallbackServerContext* context, EchoResponse* response) {
+ // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
+ // the server by calling ServerContext::TryCancel() depending on the
+ // value:
+ // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
+ // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
+ // is cancelled while the server is reading messages from the client
+ // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
+ // all the messages from the client
int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
+ kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
+ if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
internal::ServerTryCancelNonblocking(context);
- // Don't need to provide a reactor since the RPC is canceled
- return nullptr;
- }
-
- class Reactor : public ::grpc::experimental::ServerReadReactor<EchoRequest> {
- public:
- Reactor(experimental::CallbackServerContext* ctx, EchoResponse* response,
- int server_try_cancel)
- : ctx_(ctx),
- response_(response),
- server_try_cancel_(server_try_cancel) {
- EXPECT_NE(server_try_cancel, CANCEL_BEFORE_PROCESSING);
- response->set_message("");
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- // Don't wait for it here
- }
- StartRead(&request_);
- setup_done_ = true;
- }
- void OnDone() override { delete this; }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnReadDone(bool ok) override {
- if (ok) {
- response_->mutable_message()->append(request_.message());
- num_msgs_read_++;
- StartRead(&request_);
- } else {
- gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read_);
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel recover this
- return;
- }
- if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
+ // Don't need to provide a reactor since the RPC is canceled
+ return nullptr;
+ }
+
+ class Reactor : public ::grpc::experimental::ServerReadReactor<EchoRequest> {
+ public:
+ Reactor(experimental::CallbackServerContext* ctx, EchoResponse* response,
+ int server_try_cancel)
+ : ctx_(ctx),
+ response_(response),
+ server_try_cancel_(server_try_cancel) {
+ EXPECT_NE(server_try_cancel, CANCEL_BEFORE_PROCESSING);
+ response->set_message("");
+
+ if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
+ ctx->TryCancel();
+ // Don't wait for it here
+ }
+ StartRead(&request_);
+ setup_done_ = true;
+ }
+ void OnDone() override { delete this; }
+ void OnCancel() override {
+ EXPECT_TRUE(setup_done_);
+ EXPECT_TRUE(ctx_->IsCancelled());
+ FinishOnce(Status::CANCELLED);
+ }
+ void OnReadDone(bool ok) override {
+ if (ok) {
+ response_->mutable_message()->append(request_.message());
+ num_msgs_read_++;
+ StartRead(&request_);
+ } else {
+ gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read_);
+
+ if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
+ // Let OnCancel recover this
+ return;
+ }
+ if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
internal::ServerTryCancelNonblocking(ctx_);
- return;
- }
- FinishOnce(Status::OK);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- Finish(s);
- finished_ = true;
- }
- }
-
- experimental::CallbackServerContext* const ctx_;
- EchoResponse* const response_;
- EchoRequest request_;
- int num_msgs_read_{0};
- int server_try_cancel_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- };
-
- return new Reactor(context, response, server_try_cancel);
-}
-
-// Return 'kNumResponseStreamMsgs' messages.
-// TODO(yangg) make it generic by adding a parameter into EchoRequest
-experimental::ServerWriteReactor<EchoResponse>*
-CallbackTestServiceImpl::ResponseStream(
- experimental::CallbackServerContext* context, const EchoRequest* request) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
+ return;
+ }
+ FinishOnce(Status::OK);
+ }
+ }
+
+ private:
+ void FinishOnce(const Status& s) {
+ std::lock_guard<std::mutex> l(finish_mu_);
+ if (!finished_) {
+ Finish(s);
+ finished_ = true;
+ }
+ }
+
+ experimental::CallbackServerContext* const ctx_;
+ EchoResponse* const response_;
+ EchoRequest request_;
+ int num_msgs_read_{0};
+ int server_try_cancel_;
+ std::mutex finish_mu_;
+ bool finished_{false};
+ bool setup_done_{false};
+ };
+
+ return new Reactor(context, response, server_try_cancel);
+}
+
+// Return 'kNumResponseStreamMsgs' messages.
+// TODO(yangg) make it generic by adding a parameter into EchoRequest
+experimental::ServerWriteReactor<EchoResponse>*
+CallbackTestServiceImpl::ResponseStream(
+ experimental::CallbackServerContext* context, const EchoRequest* request) {
+ // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
+ // the server by calling ServerContext::TryCancel() depending on the
+ // value:
+ // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
+ // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
+ // is cancelled while the server is reading messages from the client
+ // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
+ // all the messages from the client
int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
+ kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
+ if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
internal::ServerTryCancelNonblocking(context);
- }
-
- class Reactor
- : public ::grpc::experimental::ServerWriteReactor<EchoResponse> {
- public:
- Reactor(experimental::CallbackServerContext* ctx,
- const EchoRequest* request, int server_try_cancel)
- : ctx_(ctx), request_(request), server_try_cancel_(server_try_cancel) {
+ }
+
+ class Reactor
+ : public ::grpc::experimental::ServerWriteReactor<EchoResponse> {
+ public:
+ Reactor(experimental::CallbackServerContext* ctx,
+ const EchoRequest* request, int server_try_cancel)
+ : ctx_(ctx), request_(request), server_try_cancel_(server_try_cancel) {
server_coalescing_api_ = internal::GetIntValueFromMetadata(
- kServerUseCoalescingApi, ctx->client_metadata(), 0);
+ kServerUseCoalescingApi, ctx->client_metadata(), 0);
server_responses_to_send_ = internal::GetIntValueFromMetadata(
- kServerResponseStreamsToSend, ctx->client_metadata(),
- kServerDefaultResponseStreamsToSend);
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- }
- if (server_try_cancel_ != CANCEL_BEFORE_PROCESSING) {
- if (num_msgs_sent_ < server_responses_to_send_) {
- NextWrite();
- }
- }
- setup_done_ = true;
- }
- void OnDone() override { delete this; }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnWriteDone(bool /*ok*/) override {
- if (num_msgs_sent_ < server_responses_to_send_) {
- NextWrite();
- } else if (server_coalescing_api_ != 0) {
- // We would have already done Finish just after the WriteLast
- } else if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel recover this
- } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
+ kServerResponseStreamsToSend, ctx->client_metadata(),
+ kServerDefaultResponseStreamsToSend);
+ if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
+ ctx->TryCancel();
+ }
+ if (server_try_cancel_ != CANCEL_BEFORE_PROCESSING) {
+ if (num_msgs_sent_ < server_responses_to_send_) {
+ NextWrite();
+ }
+ }
+ setup_done_ = true;
+ }
+ void OnDone() override { delete this; }
+ void OnCancel() override {
+ EXPECT_TRUE(setup_done_);
+ EXPECT_TRUE(ctx_->IsCancelled());
+ FinishOnce(Status::CANCELLED);
+ }
+ void OnWriteDone(bool /*ok*/) override {
+ if (num_msgs_sent_ < server_responses_to_send_) {
+ NextWrite();
+ } else if (server_coalescing_api_ != 0) {
+ // We would have already done Finish just after the WriteLast
+ } else if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
+ // Let OnCancel recover this
+ } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
internal::ServerTryCancelNonblocking(ctx_);
- } else {
- FinishOnce(Status::OK);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- Finish(s);
- finished_ = true;
- }
- }
-
- void NextWrite() {
- response_.set_message(request_->message() +
+ } else {
+ FinishOnce(Status::OK);
+ }
+ }
+
+ private:
+ void FinishOnce(const Status& s) {
+ std::lock_guard<std::mutex> l(finish_mu_);
+ if (!finished_) {
+ Finish(s);
+ finished_ = true;
+ }
+ }
+
+ void NextWrite() {
+ response_.set_message(request_->message() +
::ToString(num_msgs_sent_));
- if (num_msgs_sent_ == server_responses_to_send_ - 1 &&
- server_coalescing_api_ != 0) {
+ if (num_msgs_sent_ == server_responses_to_send_ - 1 &&
+ server_coalescing_api_ != 0) {
{
std::lock_guard<std::mutex> l(finish_mu_);
if (!finished_) {
@@ -508,59 +508,59 @@ CallbackTestServiceImpl::ResponseStream(
StartWriteLast(&response_, WriteOptions());
}
}
- // If we use WriteLast, we shouldn't wait before attempting Finish
- FinishOnce(Status::OK);
- } else {
+ // If we use WriteLast, we shouldn't wait before attempting Finish
+ FinishOnce(Status::OK);
+ } else {
std::lock_guard<std::mutex> l(finish_mu_);
if (!finished_) {
num_msgs_sent_++;
StartWrite(&response_);
}
- }
- }
- experimental::CallbackServerContext* const ctx_;
- const EchoRequest* const request_;
- EchoResponse response_;
- int num_msgs_sent_{0};
- int server_try_cancel_;
- int server_coalescing_api_;
- int server_responses_to_send_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- };
- return new Reactor(context, request, server_try_cancel);
-}
-
-experimental::ServerBidiReactor<EchoRequest, EchoResponse>*
-CallbackTestServiceImpl::BidiStream(
- experimental::CallbackServerContext* context) {
- class Reactor : public ::grpc::experimental::ServerBidiReactor<EchoRequest,
- EchoResponse> {
- public:
- explicit Reactor(experimental::CallbackServerContext* ctx) : ctx_(ctx) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
+ }
+ }
+ experimental::CallbackServerContext* const ctx_;
+ const EchoRequest* const request_;
+ EchoResponse response_;
+ int num_msgs_sent_{0};
+ int server_try_cancel_;
+ int server_coalescing_api_;
+ int server_responses_to_send_;
+ std::mutex finish_mu_;
+ bool finished_{false};
+ bool setup_done_{false};
+ };
+ return new Reactor(context, request, server_try_cancel);
+}
+
+experimental::ServerBidiReactor<EchoRequest, EchoResponse>*
+CallbackTestServiceImpl::BidiStream(
+ experimental::CallbackServerContext* context) {
+ class Reactor : public ::grpc::experimental::ServerBidiReactor<EchoRequest,
+ EchoResponse> {
+ public:
+ explicit Reactor(experimental::CallbackServerContext* ctx) : ctx_(ctx) {
+ // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
+ // the server by calling ServerContext::TryCancel() depending on the
+ // value:
+ // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
+ // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
+ // is cancelled while the server is reading messages from the client
+ // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
+ // all the messages from the client
server_try_cancel_ = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, ctx->client_metadata(), DO_NOT_CANCEL);
+ kServerTryCancelRequest, ctx->client_metadata(), DO_NOT_CANCEL);
server_write_last_ = internal::GetIntValueFromMetadata(
kServerFinishAfterNReads, ctx->client_metadata(), 0);
- if (server_try_cancel_ == CANCEL_BEFORE_PROCESSING) {
+ if (server_try_cancel_ == CANCEL_BEFORE_PROCESSING) {
internal::ServerTryCancelNonblocking(ctx);
- } else {
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- }
- StartRead(&request_);
- }
- setup_done_ = true;
- }
+ } else {
+ if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
+ ctx->TryCancel();
+ }
+ StartRead(&request_);
+ }
+ setup_done_ = true;
+ }
void OnDone() override {
{
// Use the same lock as finish to make sure that OnDone isn't inlined.
@@ -570,15 +570,15 @@ CallbackTestServiceImpl::BidiStream(
}
delete this;
}
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnReadDone(bool ok) override {
- if (ok) {
- num_msgs_read_++;
- response_.set_message(request_.message());
+ void OnCancel() override {
+ EXPECT_TRUE(setup_done_);
+ EXPECT_TRUE(ctx_->IsCancelled());
+ FinishOnce(Status::CANCELLED);
+ }
+ void OnReadDone(bool ok) override {
+ if (ok) {
+ num_msgs_read_++;
+ response_.set_message(request_.message());
std::lock_guard<std::mutex> l(finish_mu_);
if (!finished_) {
if (num_msgs_read_ == server_write_last_) {
@@ -588,51 +588,51 @@ CallbackTestServiceImpl::BidiStream(
StartWrite(&response_);
return;
}
- }
- }
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel handle this
- } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
+ }
+ }
+
+ if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
+ // Let OnCancel handle this
+ } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
internal::ServerTryCancelNonblocking(ctx_);
- } else {
- FinishOnce(Status::OK);
- }
- }
- void OnWriteDone(bool /*ok*/) override {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- StartRead(&request_);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- finished_ = true;
+ } else {
+ FinishOnce(Status::OK);
+ }
+ }
+ void OnWriteDone(bool /*ok*/) override {
+ std::lock_guard<std::mutex> l(finish_mu_);
+ if (!finished_) {
+ StartRead(&request_);
+ }
+ }
+
+ private:
+ void FinishOnce(const Status& s) {
+ std::lock_guard<std::mutex> l(finish_mu_);
+ if (!finished_) {
+ finished_ = true;
// Finish asynchronously to make sure that there are no deadlocks.
finish_thread_ = std::thread([this, s] {
std::lock_guard<std::mutex> l(finish_mu_);
Finish(s);
});
- }
- }
-
- experimental::CallbackServerContext* const ctx_;
- EchoRequest request_;
- EchoResponse response_;
- int num_msgs_read_{0};
- int server_try_cancel_;
- int server_write_last_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
+ }
+ }
+
+ experimental::CallbackServerContext* const ctx_;
+ EchoRequest request_;
+ EchoResponse response_;
+ int num_msgs_read_{0};
+ int server_try_cancel_;
+ int server_write_last_;
+ std::mutex finish_mu_;
+ bool finished_{false};
+ bool setup_done_{false};
std::thread finish_thread_;
- };
-
- return new Reactor(context);
-}
-
-} // namespace testing
-} // namespace grpc
+ };
+
+ return new Reactor(context);
+}
+
+} // namespace testing
+} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
index 5f207f1979..b3adaa3b85 100644
--- a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
+++ b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
@@ -1,64 +1,64 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
-#define GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
-
+/*
+ *
+ * Copyright 2016 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
+#define GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
+
#include <condition_variable>
-#include <memory>
-#include <mutex>
-
-#include <grpc/grpc.h>
+#include <memory>
+#include <mutex>
+
+#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/alarm.h>
#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
+#include <grpcpp/server_context.h>
#include <gtest/gtest.h>
-
+
#include <util/generic/string.h>
#include <thread>
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/cpp/util/string_ref_helper.h"
-
+
#include <util/string/cast.h>
using std::chrono::system_clock;
-namespace grpc {
-namespace testing {
-
-const int kServerDefaultResponseStreamsToSend = 3;
-const char* const kServerResponseStreamsToSend = "server_responses_to_send";
-const char* const kServerTryCancelRequest = "server_try_cancel";
-const char* const kDebugInfoTrailerKey = "debug-info-bin";
-const char* const kServerFinishAfterNReads = "server_finish_after_n_reads";
-const char* const kServerUseCoalescingApi = "server_use_coalescing_api";
-const char* const kCheckClientInitialMetadataKey = "custom_client_metadata";
-const char* const kCheckClientInitialMetadataVal = "Value for client metadata";
-
-typedef enum {
- DO_NOT_CANCEL = 0,
- CANCEL_BEFORE_PROCESSING,
- CANCEL_DURING_PROCESSING,
- CANCEL_AFTER_PROCESSING
-} ServerTryCancelRequestPhase;
-
+namespace grpc {
+namespace testing {
+
+const int kServerDefaultResponseStreamsToSend = 3;
+const char* const kServerResponseStreamsToSend = "server_responses_to_send";
+const char* const kServerTryCancelRequest = "server_try_cancel";
+const char* const kDebugInfoTrailerKey = "debug-info-bin";
+const char* const kServerFinishAfterNReads = "server_finish_after_n_reads";
+const char* const kServerUseCoalescingApi = "server_use_coalescing_api";
+const char* const kCheckClientInitialMetadataKey = "custom_client_metadata";
+const char* const kCheckClientInitialMetadataVal = "Value for client metadata";
+
+typedef enum {
+ DO_NOT_CANCEL = 0,
+ CANCEL_BEFORE_PROCESSING,
+ CANCEL_DURING_PROCESSING,
+ CANCEL_AFTER_PROCESSING
+} ServerTryCancelRequestPhase;
+
namespace internal {
// When echo_deadline is requested, deadline seen in the ServerContext is set in
// the response in seconds.
@@ -119,19 +119,19 @@ class TestServiceSignaller {
template <typename RpcService>
class TestMultipleServiceImpl : public RpcService {
- public:
+ public:
TestMultipleServiceImpl() : signal_client_(false), host_() {}
explicit TestMultipleServiceImpl(const TString& host)
: signal_client_(false), host_(new TString(host)) {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
+
+ Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) {
if (request->has_param() &&
request->param().server_notify_client_when_started()) {
signaller_.SignalClientThatRpcStarted();
signaller_.ServerWaitToContinue();
}
-
+
// A bit of sleep to make sure that short deadline tests fail
if (request->has_param() && request->param().server_sleep_us() > 0) {
gpr_sleep_until(
@@ -248,7 +248,7 @@ class TestMultipleServiceImpl : public RpcService {
return Echo(context, request, response);
}
- Status CheckClientInitialMetadata(ServerContext* context,
+ Status CheckClientInitialMetadata(ServerContext* context,
const SimpleRequest42* /*request*/,
SimpleResponse42* /*response*/) {
EXPECT_EQ(internal::MetadataMatchCount(context->client_metadata(),
@@ -259,11 +259,11 @@ class TestMultipleServiceImpl : public RpcService {
context->client_metadata().count(kCheckClientInitialMetadataKey));
return Status::OK;
}
-
- // Unimplemented is left unimplemented to test the returned error.
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
+
+ // Unimplemented is left unimplemented to test the returned error.
+
+ Status RequestStream(ServerContext* context,
+ ServerReader<EchoRequest>* reader,
EchoResponse* response) {
// If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
// the server by calling ServerContext::TryCancel() depending on the value:
@@ -275,7 +275,7 @@ class TestMultipleServiceImpl : public RpcService {
// all the messages from the client
int server_try_cancel = internal::GetIntValueFromMetadata(
kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
+
EchoRequest request;
response->set_message("");
@@ -312,7 +312,7 @@ class TestMultipleServiceImpl : public RpcService {
// Return 'kNumResponseStreamMsgs' messages.
// TODO(yangg) make it generic by adding a parameter into EchoRequest
- Status ResponseStream(ServerContext* context, const EchoRequest* request,
+ Status ResponseStream(ServerContext* context, const EchoRequest* request,
ServerWriter<EchoResponse>* writer) {
// If server_try_cancel is set in the metadata, the RPC is cancelled by the
// server by calling ServerContext::TryCancel() depending on the value:
@@ -324,10 +324,10 @@ class TestMultipleServiceImpl : public RpcService {
// all the messages to the client
int server_try_cancel = internal::GetIntValueFromMetadata(
kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
+
int server_coalescing_api = internal::GetIntValueFromMetadata(
kServerUseCoalescingApi, context->client_metadata(), 0);
-
+
int server_responses_to_send = internal::GetIntValueFromMetadata(
kServerResponseStreamsToSend, context->client_metadata(),
kServerDefaultResponseStreamsToSend);
@@ -426,70 +426,70 @@ class TestMultipleServiceImpl : public RpcService {
}
// Unimplemented is left unimplemented to test the returned error.
- bool signal_client() {
- std::unique_lock<std::mutex> lock(mu_);
- return signal_client_;
- }
+ bool signal_client() {
+ std::unique_lock<std::mutex> lock(mu_);
+ return signal_client_;
+ }
void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
uint64_t RpcsWaitingForClientCancel() {
std::unique_lock<std::mutex> lock(mu_);
return rpcs_waiting_for_client_cancel_;
}
-
- private:
- bool signal_client_;
- std::mutex mu_;
+
+ private:
+ bool signal_client_;
+ std::mutex mu_;
TestServiceSignaller signaller_;
std::unique_ptr<TString> host_;
uint64_t rpcs_waiting_for_client_cancel_ = 0;
-};
-
-class CallbackTestServiceImpl
- : public ::grpc::testing::EchoTestService::ExperimentalCallbackService {
- public:
- CallbackTestServiceImpl() : signal_client_(false), host_() {}
+};
+
+class CallbackTestServiceImpl
+ : public ::grpc::testing::EchoTestService::ExperimentalCallbackService {
+ public:
+ CallbackTestServiceImpl() : signal_client_(false), host_() {}
explicit CallbackTestServiceImpl(const TString& host)
: signal_client_(false), host_(new TString(host)) {}
-
- experimental::ServerUnaryReactor* Echo(
- experimental::CallbackServerContext* context, const EchoRequest* request,
- EchoResponse* response) override;
-
- experimental::ServerUnaryReactor* CheckClientInitialMetadata(
+
+ experimental::ServerUnaryReactor* Echo(
+ experimental::CallbackServerContext* context, const EchoRequest* request,
+ EchoResponse* response) override;
+
+ experimental::ServerUnaryReactor* CheckClientInitialMetadata(
experimental::CallbackServerContext* context, const SimpleRequest42*,
SimpleResponse42*) override;
-
- experimental::ServerReadReactor<EchoRequest>* RequestStream(
- experimental::CallbackServerContext* context,
- EchoResponse* response) override;
-
- experimental::ServerWriteReactor<EchoResponse>* ResponseStream(
- experimental::CallbackServerContext* context,
- const EchoRequest* request) override;
-
- experimental::ServerBidiReactor<EchoRequest, EchoResponse>* BidiStream(
- experimental::CallbackServerContext* context) override;
-
- // Unimplemented is left unimplemented to test the returned error.
- bool signal_client() {
- std::unique_lock<std::mutex> lock(mu_);
- return signal_client_;
- }
+
+ experimental::ServerReadReactor<EchoRequest>* RequestStream(
+ experimental::CallbackServerContext* context,
+ EchoResponse* response) override;
+
+ experimental::ServerWriteReactor<EchoResponse>* ResponseStream(
+ experimental::CallbackServerContext* context,
+ const EchoRequest* request) override;
+
+ experimental::ServerBidiReactor<EchoRequest, EchoResponse>* BidiStream(
+ experimental::CallbackServerContext* context) override;
+
+ // Unimplemented is left unimplemented to test the returned error.
+ bool signal_client() {
+ std::unique_lock<std::mutex> lock(mu_);
+ return signal_client_;
+ }
void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
-
- private:
- bool signal_client_;
- std::mutex mu_;
+
+ private:
+ bool signal_client_;
+ std::mutex mu_;
TestServiceSignaller signaller_;
std::unique_ptr<TString> host_;
-};
-
+};
+
using TestServiceImpl =
TestMultipleServiceImpl<::grpc::testing::EchoTestService::Service>;
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
+} // namespace testing
+} // namespace grpc
+
+#endif // GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
diff --git a/contrib/libs/grpc/test/cpp/end2end/thread/ya.make_ b/contrib/libs/grpc/test/cpp/end2end/thread/ya.make_
index afabda1c8f..296111dfc2 100644
--- a/contrib/libs/grpc/test/cpp/end2end/thread/ya.make_
+++ b/contrib/libs/grpc/test/cpp/end2end/thread/ya.make_
@@ -1,31 +1,31 @@
GTEST_UGLY()
-
-OWNER(
- dvshkurko
- g:ymake
-)
-
-ADDINCL(
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- thread_stress_test.cc
-)
-
-END()
+
+OWNER(
+ dvshkurko
+ g:ymake
+)
+
+ADDINCL(
+ ${ARCADIA_ROOT}/contrib/libs/grpc
+)
+
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/core
+ contrib/libs/grpc/src/proto/grpc/testing
+ contrib/libs/grpc/src/proto/grpc/testing/duplicate
+ contrib/libs/grpc/test/core/util
+ contrib/libs/grpc/test/cpp/end2end
+ contrib/libs/grpc/test/cpp/util
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(
+ contrib/libs/grpc/test/cpp/end2end
+)
+
+SRCS(
+ thread_stress_test.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/thread_stress_test.cc b/contrib/libs/grpc/test/cpp/end2end/thread_stress_test.cc
index 8acb953729..d187a8a952 100644
--- a/contrib/libs/grpc/test/cpp/end2end/thread_stress_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/thread_stress_test.cc
@@ -1,442 +1,442 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-#include <cinttypes>
-#include <mutex>
-#include <thread>
-
-#include <grpc/grpc.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/impl/codegen/sync.h>
-#include <grpcpp/resource_quota.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-
-#include <gtest/gtest.h>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-using std::chrono::system_clock;
-
-const int kNumThreads = 100; // Number of threads
-const int kNumAsyncSendThreads = 2;
-const int kNumAsyncReceiveThreads = 50;
-const int kNumAsyncServerThreads = 50;
-const int kNumRpcs = 1000; // Number of RPCs per thread
-
-namespace grpc {
-namespace testing {
-
-class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
- public:
- TestServiceImpl() {}
-
- Status Echo(ServerContext* /*context*/, const EchoRequest* request,
- EchoResponse* response) override {
- response->set_message(request->message());
- return Status::OK;
- }
-};
-
-template <class Service>
-class CommonStressTest {
- public:
- CommonStressTest() : kMaxMessageSize_(8192) {
-#if TARGET_OS_IPHONE
- // Workaround Apple CFStream bug
- gpr_setenv("grpc_cfstream", "0");
-#endif
- }
- virtual ~CommonStressTest() {}
- virtual void SetUp() = 0;
- virtual void TearDown() = 0;
- virtual void ResetStub() = 0;
- virtual bool AllowExhaustion() = 0;
- grpc::testing::EchoTestService::Stub* GetStub() { return stub_.get(); }
-
- protected:
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
- std::unique_ptr<Server> server_;
-
- virtual void SetUpStart(ServerBuilder* builder, Service* service) = 0;
- void SetUpStartCommon(ServerBuilder* builder, Service* service) {
- builder->RegisterService(service);
- builder->SetMaxMessageSize(
- kMaxMessageSize_); // For testing max message size.
- }
- void SetUpEnd(ServerBuilder* builder) { server_ = builder->BuildAndStart(); }
- void TearDownStart() { server_->Shutdown(); }
- void TearDownEnd() {}
-
- private:
- const int kMaxMessageSize_;
-};
-
-template <class Service>
-class CommonStressTestInsecure : public CommonStressTest<Service> {
- public:
- void ResetStub() override {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- this->stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
- bool AllowExhaustion() override { return false; }
-
- protected:
- void SetUpStart(ServerBuilder* builder, Service* service) override {
- int port = 5003; // grpc_pick_unused_port_or_die();
- this->server_address_ << "localhost:" << port;
- // Setup server
- builder->AddListeningPort(server_address_.str(),
- InsecureServerCredentials());
- this->SetUpStartCommon(builder, service);
- }
-
- private:
- std::ostringstream server_address_;
-};
-
-template <class Service, bool allow_resource_exhaustion>
-class CommonStressTestInproc : public CommonStressTest<Service> {
- public:
- void ResetStub() override {
- ChannelArguments args;
- std::shared_ptr<Channel> channel = this->server_->InProcessChannel(args);
- this->stub_ = grpc::testing::EchoTestService::NewStub(channel);
- }
- bool AllowExhaustion() override { return allow_resource_exhaustion; }
-
- protected:
- void SetUpStart(ServerBuilder* builder, Service* service) override {
- this->SetUpStartCommon(builder, service);
- }
-};
-
-template <class BaseClass>
-class CommonStressTestSyncServer : public BaseClass {
- public:
- void SetUp() override {
- ServerBuilder builder;
- this->SetUpStart(&builder, &service_);
- this->SetUpEnd(&builder);
- }
- void TearDown() override {
- this->TearDownStart();
- this->TearDownEnd();
- }
-
- private:
- TestServiceImpl service_;
-};
-
-template <class BaseClass>
-class CommonStressTestSyncServerLowThreadCount : public BaseClass {
- public:
- void SetUp() override {
- ServerBuilder builder;
- ResourceQuota quota;
- this->SetUpStart(&builder, &service_);
- quota.SetMaxThreads(4);
- builder.SetResourceQuota(quota);
- this->SetUpEnd(&builder);
- }
- void TearDown() override {
- this->TearDownStart();
- this->TearDownEnd();
- }
-
- private:
- TestServiceImpl service_;
-};
-
-template <class BaseClass>
-class CommonStressTestAsyncServer : public BaseClass {
- public:
- CommonStressTestAsyncServer() : contexts_(kNumAsyncServerThreads * 100) {}
- void SetUp() override {
- shutting_down_ = false;
- ServerBuilder builder;
- this->SetUpStart(&builder, &service_);
- cq_ = builder.AddCompletionQueue();
- this->SetUpEnd(&builder);
- for (int i = 0; i < kNumAsyncServerThreads * 100; i++) {
- RefreshContext(i);
- }
- for (int i = 0; i < kNumAsyncServerThreads; i++) {
- server_threads_.emplace_back(&CommonStressTestAsyncServer::ProcessRpcs,
- this);
- }
- }
- void TearDown() override {
- {
- grpc::internal::MutexLock l(&mu_);
- this->TearDownStart();
- shutting_down_ = true;
- cq_->Shutdown();
- }
-
- for (int i = 0; i < kNumAsyncServerThreads; i++) {
- server_threads_[i].join();
- }
-
- void* ignored_tag;
- bool ignored_ok;
- while (cq_->Next(&ignored_tag, &ignored_ok))
- ;
- this->TearDownEnd();
- }
-
- private:
- void ProcessRpcs() {
- void* tag;
- bool ok;
- while (cq_->Next(&tag, &ok)) {
- if (ok) {
- int i = static_cast<int>(reinterpret_cast<intptr_t>(tag));
- switch (contexts_[i].state) {
- case Context::READY: {
- contexts_[i].state = Context::DONE;
- EchoResponse send_response;
- send_response.set_message(contexts_[i].recv_request.message());
- contexts_[i].response_writer->Finish(send_response, Status::OK,
- tag);
- break;
- }
- case Context::DONE:
- RefreshContext(i);
- break;
- }
- }
- }
- }
- void RefreshContext(int i) {
- grpc::internal::MutexLock l(&mu_);
- if (!shutting_down_) {
- contexts_[i].state = Context::READY;
- contexts_[i].srv_ctx.reset(new ServerContext);
- contexts_[i].response_writer.reset(
- new grpc::ServerAsyncResponseWriter<EchoResponse>(
- contexts_[i].srv_ctx.get()));
- service_.RequestEcho(contexts_[i].srv_ctx.get(),
- &contexts_[i].recv_request,
- contexts_[i].response_writer.get(), cq_.get(),
- cq_.get(), (void*)static_cast<intptr_t>(i));
- }
- }
- struct Context {
- std::unique_ptr<ServerContext> srv_ctx;
- std::unique_ptr<grpc::ServerAsyncResponseWriter<EchoResponse>>
- response_writer;
- EchoRequest recv_request;
- enum { READY, DONE } state;
- };
- std::vector<Context> contexts_;
- ::grpc::testing::EchoTestService::AsyncService service_;
- std::unique_ptr<ServerCompletionQueue> cq_;
- bool shutting_down_;
- grpc::internal::Mutex mu_;
- std::vector<std::thread> server_threads_;
-};
-
-template <class Common>
-class End2endTest : public ::testing::Test {
- protected:
- End2endTest() {}
- void SetUp() override { common_.SetUp(); }
- void TearDown() override { common_.TearDown(); }
- void ResetStub() { common_.ResetStub(); }
-
- Common common_;
-};
-
-static void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
- bool allow_exhaustion, gpr_atm* errors) {
- EchoRequest request;
- EchoResponse response;
- request.set_message("Hello");
-
- for (int i = 0; i < num_rpcs; ++i) {
- ClientContext context;
- Status s = stub->Echo(&context, request, &response);
- EXPECT_TRUE(s.ok() || (allow_exhaustion &&
- s.error_code() == StatusCode::RESOURCE_EXHAUSTED));
- if (!s.ok()) {
- if (!(allow_exhaustion &&
- s.error_code() == StatusCode::RESOURCE_EXHAUSTED)) {
- gpr_log(GPR_ERROR, "RPC error: %d: %s", s.error_code(),
- s.error_message().c_str());
- }
- gpr_atm_no_barrier_fetch_add(errors, static_cast<gpr_atm>(1));
- } else {
- EXPECT_EQ(response.message(), request.message());
- }
- }
-}
-
-typedef ::testing::Types<
- CommonStressTestSyncServer<CommonStressTestInsecure<TestServiceImpl>>,
- CommonStressTestSyncServer<CommonStressTestInproc<TestServiceImpl, false>>,
- CommonStressTestSyncServerLowThreadCount<
- CommonStressTestInproc<TestServiceImpl, true>>,
- CommonStressTestAsyncServer<
- CommonStressTestInsecure<grpc::testing::EchoTestService::AsyncService>>,
- CommonStressTestAsyncServer<CommonStressTestInproc<
- grpc::testing::EchoTestService::AsyncService, false>>>
- CommonTypes;
-TYPED_TEST_SUITE(End2endTest, CommonTypes);
-TYPED_TEST(End2endTest, ThreadStress) {
- this->common_.ResetStub();
- std::vector<std::thread> threads;
- gpr_atm errors;
- gpr_atm_rel_store(&errors, static_cast<gpr_atm>(0));
- threads.reserve(kNumThreads);
- for (int i = 0; i < kNumThreads; ++i) {
- threads.emplace_back(SendRpc, this->common_.GetStub(), kNumRpcs,
- this->common_.AllowExhaustion(), &errors);
- }
- for (int i = 0; i < kNumThreads; ++i) {
- threads[i].join();
- }
- uint64_t error_cnt = static_cast<uint64_t>(gpr_atm_no_barrier_load(&errors));
- if (error_cnt != 0) {
- gpr_log(GPR_INFO, "RPC error count: %" PRIu64, error_cnt);
- }
- // If this test allows resource exhaustion, expect that it actually sees some
- if (this->common_.AllowExhaustion()) {
- EXPECT_GT(error_cnt, static_cast<uint64_t>(0));
- }
-}
-
-template <class Common>
-class AsyncClientEnd2endTest : public ::testing::Test {
- protected:
- AsyncClientEnd2endTest() : rpcs_outstanding_(0) {}
-
- void SetUp() override { common_.SetUp(); }
- void TearDown() override {
- void* ignored_tag;
- bool ignored_ok;
- while (cq_.Next(&ignored_tag, &ignored_ok))
- ;
- common_.TearDown();
- }
-
- void Wait() {
- grpc::internal::MutexLock l(&mu_);
- while (rpcs_outstanding_ != 0) {
- cv_.Wait(&mu_);
- }
-
- cq_.Shutdown();
- }
-
- struct AsyncClientCall {
- EchoResponse response;
- ClientContext context;
- Status status;
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
- };
-
- void AsyncSendRpc(int num_rpcs) {
- for (int i = 0; i < num_rpcs; ++i) {
- AsyncClientCall* call = new AsyncClientCall;
- EchoRequest request;
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+#include <cinttypes>
+#include <mutex>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/impl/codegen/sync.h>
+#include <grpcpp/resource_quota.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+
+#include <gtest/gtest.h>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+using std::chrono::system_clock;
+
+const int kNumThreads = 100; // Number of threads
+const int kNumAsyncSendThreads = 2;
+const int kNumAsyncReceiveThreads = 50;
+const int kNumAsyncServerThreads = 50;
+const int kNumRpcs = 1000; // Number of RPCs per thread
+
+namespace grpc {
+namespace testing {
+
+class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
+ public:
+ TestServiceImpl() {}
+
+ Status Echo(ServerContext* /*context*/, const EchoRequest* request,
+ EchoResponse* response) override {
+ response->set_message(request->message());
+ return Status::OK;
+ }
+};
+
+template <class Service>
+class CommonStressTest {
+ public:
+ CommonStressTest() : kMaxMessageSize_(8192) {
+#if TARGET_OS_IPHONE
+ // Workaround Apple CFStream bug
+ gpr_setenv("grpc_cfstream", "0");
+#endif
+ }
+ virtual ~CommonStressTest() {}
+ virtual void SetUp() = 0;
+ virtual void TearDown() = 0;
+ virtual void ResetStub() = 0;
+ virtual bool AllowExhaustion() = 0;
+ grpc::testing::EchoTestService::Stub* GetStub() { return stub_.get(); }
+
+ protected:
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+ std::unique_ptr<Server> server_;
+
+ virtual void SetUpStart(ServerBuilder* builder, Service* service) = 0;
+ void SetUpStartCommon(ServerBuilder* builder, Service* service) {
+ builder->RegisterService(service);
+ builder->SetMaxMessageSize(
+ kMaxMessageSize_); // For testing max message size.
+ }
+ void SetUpEnd(ServerBuilder* builder) { server_ = builder->BuildAndStart(); }
+ void TearDownStart() { server_->Shutdown(); }
+ void TearDownEnd() {}
+
+ private:
+ const int kMaxMessageSize_;
+};
+
+template <class Service>
+class CommonStressTestInsecure : public CommonStressTest<Service> {
+ public:
+ void ResetStub() override {
+ std::shared_ptr<Channel> channel = grpc::CreateChannel(
+ server_address_.str(), InsecureChannelCredentials());
+ this->stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+ bool AllowExhaustion() override { return false; }
+
+ protected:
+ void SetUpStart(ServerBuilder* builder, Service* service) override {
+ int port = 5003; // grpc_pick_unused_port_or_die();
+ this->server_address_ << "localhost:" << port;
+ // Setup server
+ builder->AddListeningPort(server_address_.str(),
+ InsecureServerCredentials());
+ this->SetUpStartCommon(builder, service);
+ }
+
+ private:
+ std::ostringstream server_address_;
+};
+
+template <class Service, bool allow_resource_exhaustion>
+class CommonStressTestInproc : public CommonStressTest<Service> {
+ public:
+ void ResetStub() override {
+ ChannelArguments args;
+ std::shared_ptr<Channel> channel = this->server_->InProcessChannel(args);
+ this->stub_ = grpc::testing::EchoTestService::NewStub(channel);
+ }
+ bool AllowExhaustion() override { return allow_resource_exhaustion; }
+
+ protected:
+ void SetUpStart(ServerBuilder* builder, Service* service) override {
+ this->SetUpStartCommon(builder, service);
+ }
+};
+
+template <class BaseClass>
+class CommonStressTestSyncServer : public BaseClass {
+ public:
+ void SetUp() override {
+ ServerBuilder builder;
+ this->SetUpStart(&builder, &service_);
+ this->SetUpEnd(&builder);
+ }
+ void TearDown() override {
+ this->TearDownStart();
+ this->TearDownEnd();
+ }
+
+ private:
+ TestServiceImpl service_;
+};
+
+template <class BaseClass>
+class CommonStressTestSyncServerLowThreadCount : public BaseClass {
+ public:
+ void SetUp() override {
+ ServerBuilder builder;
+ ResourceQuota quota;
+ this->SetUpStart(&builder, &service_);
+ quota.SetMaxThreads(4);
+ builder.SetResourceQuota(quota);
+ this->SetUpEnd(&builder);
+ }
+ void TearDown() override {
+ this->TearDownStart();
+ this->TearDownEnd();
+ }
+
+ private:
+ TestServiceImpl service_;
+};
+
+template <class BaseClass>
+class CommonStressTestAsyncServer : public BaseClass {
+ public:
+ CommonStressTestAsyncServer() : contexts_(kNumAsyncServerThreads * 100) {}
+ void SetUp() override {
+ shutting_down_ = false;
+ ServerBuilder builder;
+ this->SetUpStart(&builder, &service_);
+ cq_ = builder.AddCompletionQueue();
+ this->SetUpEnd(&builder);
+ for (int i = 0; i < kNumAsyncServerThreads * 100; i++) {
+ RefreshContext(i);
+ }
+ for (int i = 0; i < kNumAsyncServerThreads; i++) {
+ server_threads_.emplace_back(&CommonStressTestAsyncServer::ProcessRpcs,
+ this);
+ }
+ }
+ void TearDown() override {
+ {
+ grpc::internal::MutexLock l(&mu_);
+ this->TearDownStart();
+ shutting_down_ = true;
+ cq_->Shutdown();
+ }
+
+ for (int i = 0; i < kNumAsyncServerThreads; i++) {
+ server_threads_[i].join();
+ }
+
+ void* ignored_tag;
+ bool ignored_ok;
+ while (cq_->Next(&ignored_tag, &ignored_ok))
+ ;
+ this->TearDownEnd();
+ }
+
+ private:
+ void ProcessRpcs() {
+ void* tag;
+ bool ok;
+ while (cq_->Next(&tag, &ok)) {
+ if (ok) {
+ int i = static_cast<int>(reinterpret_cast<intptr_t>(tag));
+ switch (contexts_[i].state) {
+ case Context::READY: {
+ contexts_[i].state = Context::DONE;
+ EchoResponse send_response;
+ send_response.set_message(contexts_[i].recv_request.message());
+ contexts_[i].response_writer->Finish(send_response, Status::OK,
+ tag);
+ break;
+ }
+ case Context::DONE:
+ RefreshContext(i);
+ break;
+ }
+ }
+ }
+ }
+ void RefreshContext(int i) {
+ grpc::internal::MutexLock l(&mu_);
+ if (!shutting_down_) {
+ contexts_[i].state = Context::READY;
+ contexts_[i].srv_ctx.reset(new ServerContext);
+ contexts_[i].response_writer.reset(
+ new grpc::ServerAsyncResponseWriter<EchoResponse>(
+ contexts_[i].srv_ctx.get()));
+ service_.RequestEcho(contexts_[i].srv_ctx.get(),
+ &contexts_[i].recv_request,
+ contexts_[i].response_writer.get(), cq_.get(),
+ cq_.get(), (void*)static_cast<intptr_t>(i));
+ }
+ }
+ struct Context {
+ std::unique_ptr<ServerContext> srv_ctx;
+ std::unique_ptr<grpc::ServerAsyncResponseWriter<EchoResponse>>
+ response_writer;
+ EchoRequest recv_request;
+ enum { READY, DONE } state;
+ };
+ std::vector<Context> contexts_;
+ ::grpc::testing::EchoTestService::AsyncService service_;
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ bool shutting_down_;
+ grpc::internal::Mutex mu_;
+ std::vector<std::thread> server_threads_;
+};
+
+template <class Common>
+class End2endTest : public ::testing::Test {
+ protected:
+ End2endTest() {}
+ void SetUp() override { common_.SetUp(); }
+ void TearDown() override { common_.TearDown(); }
+ void ResetStub() { common_.ResetStub(); }
+
+ Common common_;
+};
+
+static void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
+ bool allow_exhaustion, gpr_atm* errors) {
+ EchoRequest request;
+ EchoResponse response;
+ request.set_message("Hello");
+
+ for (int i = 0; i < num_rpcs; ++i) {
+ ClientContext context;
+ Status s = stub->Echo(&context, request, &response);
+ EXPECT_TRUE(s.ok() || (allow_exhaustion &&
+ s.error_code() == StatusCode::RESOURCE_EXHAUSTED));
+ if (!s.ok()) {
+ if (!(allow_exhaustion &&
+ s.error_code() == StatusCode::RESOURCE_EXHAUSTED)) {
+ gpr_log(GPR_ERROR, "RPC error: %d: %s", s.error_code(),
+ s.error_message().c_str());
+ }
+ gpr_atm_no_barrier_fetch_add(errors, static_cast<gpr_atm>(1));
+ } else {
+ EXPECT_EQ(response.message(), request.message());
+ }
+ }
+}
+
+typedef ::testing::Types<
+ CommonStressTestSyncServer<CommonStressTestInsecure<TestServiceImpl>>,
+ CommonStressTestSyncServer<CommonStressTestInproc<TestServiceImpl, false>>,
+ CommonStressTestSyncServerLowThreadCount<
+ CommonStressTestInproc<TestServiceImpl, true>>,
+ CommonStressTestAsyncServer<
+ CommonStressTestInsecure<grpc::testing::EchoTestService::AsyncService>>,
+ CommonStressTestAsyncServer<CommonStressTestInproc<
+ grpc::testing::EchoTestService::AsyncService, false>>>
+ CommonTypes;
+TYPED_TEST_SUITE(End2endTest, CommonTypes);
+TYPED_TEST(End2endTest, ThreadStress) {
+ this->common_.ResetStub();
+ std::vector<std::thread> threads;
+ gpr_atm errors;
+ gpr_atm_rel_store(&errors, static_cast<gpr_atm>(0));
+ threads.reserve(kNumThreads);
+ for (int i = 0; i < kNumThreads; ++i) {
+ threads.emplace_back(SendRpc, this->common_.GetStub(), kNumRpcs,
+ this->common_.AllowExhaustion(), &errors);
+ }
+ for (int i = 0; i < kNumThreads; ++i) {
+ threads[i].join();
+ }
+ uint64_t error_cnt = static_cast<uint64_t>(gpr_atm_no_barrier_load(&errors));
+ if (error_cnt != 0) {
+ gpr_log(GPR_INFO, "RPC error count: %" PRIu64, error_cnt);
+ }
+ // If this test allows resource exhaustion, expect that it actually sees some
+ if (this->common_.AllowExhaustion()) {
+ EXPECT_GT(error_cnt, static_cast<uint64_t>(0));
+ }
+}
+
+template <class Common>
+class AsyncClientEnd2endTest : public ::testing::Test {
+ protected:
+ AsyncClientEnd2endTest() : rpcs_outstanding_(0) {}
+
+ void SetUp() override { common_.SetUp(); }
+ void TearDown() override {
+ void* ignored_tag;
+ bool ignored_ok;
+ while (cq_.Next(&ignored_tag, &ignored_ok))
+ ;
+ common_.TearDown();
+ }
+
+ void Wait() {
+ grpc::internal::MutexLock l(&mu_);
+ while (rpcs_outstanding_ != 0) {
+ cv_.Wait(&mu_);
+ }
+
+ cq_.Shutdown();
+ }
+
+ struct AsyncClientCall {
+ EchoResponse response;
+ ClientContext context;
+ Status status;
+ std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
+ };
+
+ void AsyncSendRpc(int num_rpcs) {
+ for (int i = 0; i < num_rpcs; ++i) {
+ AsyncClientCall* call = new AsyncClientCall;
+ EchoRequest request;
request.set_message(TString("Hello: " + grpc::to_string(i)).c_str());
- call->response_reader =
- common_.GetStub()->AsyncEcho(&call->context, request, &cq_);
- call->response_reader->Finish(&call->response, &call->status,
- (void*)call);
-
- grpc::internal::MutexLock l(&mu_);
- rpcs_outstanding_++;
- }
- }
-
- void AsyncCompleteRpc() {
- while (true) {
- void* got_tag;
- bool ok = false;
- if (!cq_.Next(&got_tag, &ok)) break;
- AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
- if (!ok) {
- gpr_log(GPR_DEBUG, "Error: %d", call->status.error_code());
- }
- delete call;
-
- bool notify;
- {
- grpc::internal::MutexLock l(&mu_);
- rpcs_outstanding_--;
- notify = (rpcs_outstanding_ == 0);
- }
- if (notify) {
- cv_.Signal();
- }
- }
- }
-
- Common common_;
- CompletionQueue cq_;
- grpc::internal::Mutex mu_;
- grpc::internal::CondVar cv_;
- int rpcs_outstanding_;
-};
-
-TYPED_TEST_SUITE(AsyncClientEnd2endTest, CommonTypes);
-TYPED_TEST(AsyncClientEnd2endTest, ThreadStress) {
- this->common_.ResetStub();
- std::vector<std::thread> send_threads, completion_threads;
- for (int i = 0; i < kNumAsyncReceiveThreads; ++i) {
- completion_threads.emplace_back(
- &AsyncClientEnd2endTest_ThreadStress_Test<TypeParam>::AsyncCompleteRpc,
- this);
- }
- for (int i = 0; i < kNumAsyncSendThreads; ++i) {
- send_threads.emplace_back(
- &AsyncClientEnd2endTest_ThreadStress_Test<TypeParam>::AsyncSendRpc,
- this, kNumRpcs);
- }
- for (int i = 0; i < kNumAsyncSendThreads; ++i) {
- send_threads[i].join();
- }
-
- this->Wait();
- for (int i = 0; i < kNumAsyncReceiveThreads; ++i) {
- completion_threads[i].join();
- }
-}
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
+ call->response_reader =
+ common_.GetStub()->AsyncEcho(&call->context, request, &cq_);
+ call->response_reader->Finish(&call->response, &call->status,
+ (void*)call);
+
+ grpc::internal::MutexLock l(&mu_);
+ rpcs_outstanding_++;
+ }
+ }
+
+ void AsyncCompleteRpc() {
+ while (true) {
+ void* got_tag;
+ bool ok = false;
+ if (!cq_.Next(&got_tag, &ok)) break;
+ AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
+ if (!ok) {
+ gpr_log(GPR_DEBUG, "Error: %d", call->status.error_code());
+ }
+ delete call;
+
+ bool notify;
+ {
+ grpc::internal::MutexLock l(&mu_);
+ rpcs_outstanding_--;
+ notify = (rpcs_outstanding_ == 0);
+ }
+ if (notify) {
+ cv_.Signal();
+ }
+ }
+ }
+
+ Common common_;
+ CompletionQueue cq_;
+ grpc::internal::Mutex mu_;
+ grpc::internal::CondVar cv_;
+ int rpcs_outstanding_;
+};
+
+TYPED_TEST_SUITE(AsyncClientEnd2endTest, CommonTypes);
+TYPED_TEST(AsyncClientEnd2endTest, ThreadStress) {
+ this->common_.ResetStub();
+ std::vector<std::thread> send_threads, completion_threads;
+ for (int i = 0; i < kNumAsyncReceiveThreads; ++i) {
+ completion_threads.emplace_back(
+ &AsyncClientEnd2endTest_ThreadStress_Test<TypeParam>::AsyncCompleteRpc,
+ this);
+ }
+ for (int i = 0; i < kNumAsyncSendThreads; ++i) {
+ send_threads.emplace_back(
+ &AsyncClientEnd2endTest_ThreadStress_Test<TypeParam>::AsyncSendRpc,
+ this, kNumRpcs);
+ }
+ for (int i = 0; i < kNumAsyncSendThreads; ++i) {
+ send_threads[i].join();
+ }
+
+ this->Wait();
+ for (int i = 0; i < kNumAsyncReceiveThreads; ++i) {
+ completion_threads[i].join();
+ }
+}
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/time_change_test.cc b/contrib/libs/grpc/test/cpp/end2end/time_change_test.cc
index 48b9eace12..d83b0ae7a4 100644
--- a/contrib/libs/grpc/test/cpp/end2end/time_change_test.cc
+++ b/contrib/libs/grpc/test/cpp/end2end/time_change_test.cc
@@ -1,367 +1,367 @@
-/*
- *
- * Copyright 2019 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/core/lib/iomgr/timer.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/subprocess.h"
-
-#include <gtest/gtest.h>
-#include <sys/time.h>
-#include <thread>
-
-using grpc::testing::EchoRequest;
-using grpc::testing::EchoResponse;
-
+/*
+ *
+ * Copyright 2019 gRPC authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/server.h>
+#include <grpcpp/server_builder.h>
+#include <grpcpp/server_context.h>
+
+#include "src/core/lib/iomgr/timer.h"
+#include "src/proto/grpc/testing/echo.grpc.pb.h"
+#include "test/core/util/port.h"
+#include "test/core/util/test_config.h"
+#include "test/cpp/end2end/test_service_impl.h"
+#include "test/cpp/util/subprocess.h"
+
+#include <gtest/gtest.h>
+#include <sys/time.h>
+#include <thread>
+
+using grpc::testing::EchoRequest;
+using grpc::testing::EchoResponse;
+
static TString g_root;
-
-static gpr_mu g_mu;
-extern gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type);
-gpr_timespec (*gpr_now_impl_orig)(gpr_clock_type clock_type) = gpr_now_impl;
-static int g_time_shift_sec = 0;
-static int g_time_shift_nsec = 0;
-static gpr_timespec now_impl(gpr_clock_type clock) {
- auto ts = gpr_now_impl_orig(clock);
- // We only manipulate the realtime clock to simulate changes in wall-clock
- // time
- if (clock != GPR_CLOCK_REALTIME) {
- return ts;
- }
- GPR_ASSERT(ts.tv_nsec >= 0);
- GPR_ASSERT(ts.tv_nsec < GPR_NS_PER_SEC);
- gpr_mu_lock(&g_mu);
- ts.tv_sec += g_time_shift_sec;
- ts.tv_nsec += g_time_shift_nsec;
- gpr_mu_unlock(&g_mu);
- if (ts.tv_nsec >= GPR_NS_PER_SEC) {
- ts.tv_nsec -= GPR_NS_PER_SEC;
- ++ts.tv_sec;
- } else if (ts.tv_nsec < 0) {
- --ts.tv_sec;
- ts.tv_nsec = GPR_NS_PER_SEC + ts.tv_nsec;
- }
- return ts;
-}
-
-// offset the value returned by gpr_now(GPR_CLOCK_REALTIME) by msecs
-// milliseconds
-static void set_now_offset(int msecs) {
- gpr_mu_lock(&g_mu);
- g_time_shift_sec = msecs / 1000;
- g_time_shift_nsec = (msecs % 1000) * 1e6;
- gpr_mu_unlock(&g_mu);
-}
-
-// restore the original implementation of gpr_now()
-static void reset_now_offset() {
- gpr_mu_lock(&g_mu);
- g_time_shift_sec = 0;
- g_time_shift_nsec = 0;
- gpr_mu_unlock(&g_mu);
-}
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-// gpr_now() is called with invalid clock_type
-TEST(TimespecTest, GprNowInvalidClockType) {
- // initialize to some junk value
- gpr_clock_type invalid_clock_type = (gpr_clock_type)32641;
- EXPECT_DEATH(gpr_now(invalid_clock_type), ".*");
-}
-
-// Add timespan with negative nanoseconds
-TEST(TimespecTest, GprTimeAddNegativeNs) {
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- gpr_timespec bad_ts = {1, -1000, GPR_TIMESPAN};
- EXPECT_DEATH(gpr_time_add(now, bad_ts), ".*");
-}
-
-// Subtract timespan with negative nanoseconds
-TEST(TimespecTest, GprTimeSubNegativeNs) {
- // Nanoseconds must always be positive. Negative timestamps are represented by
- // (negative seconds, positive nanoseconds)
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- gpr_timespec bad_ts = {1, -1000, GPR_TIMESPAN};
- EXPECT_DEATH(gpr_time_sub(now, bad_ts), ".*");
-}
-
-// Add negative milliseconds to gpr_timespec
-TEST(TimespecTest, GrpcNegativeMillisToTimespec) {
- // -1500 milliseconds converts to timespec (-2 secs, 5 * 10^8 nsec)
- gpr_timespec ts = grpc_millis_to_timespec(-1500, GPR_CLOCK_MONOTONIC);
- GPR_ASSERT(ts.tv_sec = -2);
- GPR_ASSERT(ts.tv_nsec = 5e8);
- GPR_ASSERT(ts.clock_type == GPR_CLOCK_MONOTONIC);
-}
-
-class TimeChangeTest : public ::testing::Test {
- protected:
- TimeChangeTest() {}
-
- static void SetUpTestCase() {
- auto port = grpc_pick_unused_port_or_die();
- std::ostringstream addr_stream;
- addr_stream << "localhost:" << port;
- server_address_ = addr_stream.str();
- server_.reset(new SubProcess({
- g_root + "/client_crash_test_server",
- "--address=" + server_address_,
- }));
- GPR_ASSERT(server_);
- // connect to server and make sure it's reachable.
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- GPR_ASSERT(channel);
- EXPECT_TRUE(channel->WaitForConnected(
- grpc_timeout_milliseconds_to_deadline(30000)));
- }
-
- static void TearDownTestCase() { server_.reset(); }
-
- void SetUp() {
- channel_ =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- GPR_ASSERT(channel_);
- stub_ = grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- void TearDown() { reset_now_offset(); }
-
- std::unique_ptr<grpc::testing::EchoTestService::Stub> CreateStub() {
- return grpc::testing::EchoTestService::NewStub(channel_);
- }
-
- std::shared_ptr<Channel> GetChannel() { return channel_; }
- // time jump offsets in milliseconds
- const int TIME_OFFSET1 = 20123;
- const int TIME_OFFSET2 = 5678;
-
- private:
+
+static gpr_mu g_mu;
+extern gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type);
+gpr_timespec (*gpr_now_impl_orig)(gpr_clock_type clock_type) = gpr_now_impl;
+static int g_time_shift_sec = 0;
+static int g_time_shift_nsec = 0;
+static gpr_timespec now_impl(gpr_clock_type clock) {
+ auto ts = gpr_now_impl_orig(clock);
+ // We only manipulate the realtime clock to simulate changes in wall-clock
+ // time
+ if (clock != GPR_CLOCK_REALTIME) {
+ return ts;
+ }
+ GPR_ASSERT(ts.tv_nsec >= 0);
+ GPR_ASSERT(ts.tv_nsec < GPR_NS_PER_SEC);
+ gpr_mu_lock(&g_mu);
+ ts.tv_sec += g_time_shift_sec;
+ ts.tv_nsec += g_time_shift_nsec;
+ gpr_mu_unlock(&g_mu);
+ if (ts.tv_nsec >= GPR_NS_PER_SEC) {
+ ts.tv_nsec -= GPR_NS_PER_SEC;
+ ++ts.tv_sec;
+ } else if (ts.tv_nsec < 0) {
+ --ts.tv_sec;
+ ts.tv_nsec = GPR_NS_PER_SEC + ts.tv_nsec;
+ }
+ return ts;
+}
+
+// offset the value returned by gpr_now(GPR_CLOCK_REALTIME) by msecs
+// milliseconds
+static void set_now_offset(int msecs) {
+ gpr_mu_lock(&g_mu);
+ g_time_shift_sec = msecs / 1000;
+ g_time_shift_nsec = (msecs % 1000) * 1e6;
+ gpr_mu_unlock(&g_mu);
+}
+
+// restore the original implementation of gpr_now()
+static void reset_now_offset() {
+ gpr_mu_lock(&g_mu);
+ g_time_shift_sec = 0;
+ g_time_shift_nsec = 0;
+ gpr_mu_unlock(&g_mu);
+}
+
+namespace grpc {
+namespace testing {
+
+namespace {
+
+// gpr_now() is called with invalid clock_type
+TEST(TimespecTest, GprNowInvalidClockType) {
+ // initialize to some junk value
+ gpr_clock_type invalid_clock_type = (gpr_clock_type)32641;
+ EXPECT_DEATH(gpr_now(invalid_clock_type), ".*");
+}
+
+// Add timespan with negative nanoseconds
+TEST(TimespecTest, GprTimeAddNegativeNs) {
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ gpr_timespec bad_ts = {1, -1000, GPR_TIMESPAN};
+ EXPECT_DEATH(gpr_time_add(now, bad_ts), ".*");
+}
+
+// Subtract timespan with negative nanoseconds
+TEST(TimespecTest, GprTimeSubNegativeNs) {
+ // Nanoseconds must always be positive. Negative timestamps are represented by
+ // (negative seconds, positive nanoseconds)
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ gpr_timespec bad_ts = {1, -1000, GPR_TIMESPAN};
+ EXPECT_DEATH(gpr_time_sub(now, bad_ts), ".*");
+}
+
+// Add negative milliseconds to gpr_timespec
+TEST(TimespecTest, GrpcNegativeMillisToTimespec) {
+ // -1500 milliseconds converts to timespec (-2 secs, 5 * 10^8 nsec)
+ gpr_timespec ts = grpc_millis_to_timespec(-1500, GPR_CLOCK_MONOTONIC);
+ GPR_ASSERT(ts.tv_sec = -2);
+ GPR_ASSERT(ts.tv_nsec = 5e8);
+ GPR_ASSERT(ts.clock_type == GPR_CLOCK_MONOTONIC);
+}
+
+class TimeChangeTest : public ::testing::Test {
+ protected:
+ TimeChangeTest() {}
+
+ static void SetUpTestCase() {
+ auto port = grpc_pick_unused_port_or_die();
+ std::ostringstream addr_stream;
+ addr_stream << "localhost:" << port;
+ server_address_ = addr_stream.str();
+ server_.reset(new SubProcess({
+ g_root + "/client_crash_test_server",
+ "--address=" + server_address_,
+ }));
+ GPR_ASSERT(server_);
+ // connect to server and make sure it's reachable.
+ auto channel =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ GPR_ASSERT(channel);
+ EXPECT_TRUE(channel->WaitForConnected(
+ grpc_timeout_milliseconds_to_deadline(30000)));
+ }
+
+ static void TearDownTestCase() { server_.reset(); }
+
+ void SetUp() {
+ channel_ =
+ grpc::CreateChannel(server_address_, InsecureChannelCredentials());
+ GPR_ASSERT(channel_);
+ stub_ = grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ void TearDown() { reset_now_offset(); }
+
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> CreateStub() {
+ return grpc::testing::EchoTestService::NewStub(channel_);
+ }
+
+ std::shared_ptr<Channel> GetChannel() { return channel_; }
+ // time jump offsets in milliseconds
+ const int TIME_OFFSET1 = 20123;
+ const int TIME_OFFSET2 = 5678;
+
+ private:
static TString server_address_;
- static std::unique_ptr<SubProcess> server_;
- std::shared_ptr<Channel> channel_;
- std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
-};
+ static std::unique_ptr<SubProcess> server_;
+ std::shared_ptr<Channel> channel_;
+ std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
+};
TString TimeChangeTest::server_address_;
-std::unique_ptr<SubProcess> TimeChangeTest::server_;
-
-// Wall-clock time jumps forward on client before bidi stream is created
-TEST_F(TimeChangeTest, TimeJumpForwardBeforeStreamCreated) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
- context.AddMetadata(kServerResponseStreamsToSend, "1");
-
- auto channel = GetChannel();
- GPR_ASSERT(channel);
- EXPECT_TRUE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
- auto stub = CreateStub();
-
- // time jumps forward by TIME_OFFSET1 milliseconds
- set_now_offset(TIME_OFFSET1);
- auto stream = stub->BidiStream(&context);
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
-
- EXPECT_TRUE(stream->WritesDone());
- EXPECT_TRUE(stream->Read(&response));
-
- auto status = stream->Finish();
- EXPECT_TRUE(status.ok());
-}
-
-// Wall-clock time jumps back on client before bidi stream is created
-TEST_F(TimeChangeTest, TimeJumpBackBeforeStreamCreated) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
- context.AddMetadata(kServerResponseStreamsToSend, "1");
-
- auto channel = GetChannel();
- GPR_ASSERT(channel);
- EXPECT_TRUE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
- auto stub = CreateStub();
-
- // time jumps back by TIME_OFFSET1 milliseconds
- set_now_offset(-TIME_OFFSET1);
- auto stream = stub->BidiStream(&context);
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
-
- EXPECT_TRUE(stream->WritesDone());
- EXPECT_TRUE(stream->Read(&response));
- EXPECT_EQ(request.message(), response.message());
-
- auto status = stream->Finish();
- EXPECT_TRUE(status.ok());
-}
-
-// Wall-clock time jumps forward on client while call is in progress
-TEST_F(TimeChangeTest, TimeJumpForwardAfterStreamCreated) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
- context.AddMetadata(kServerResponseStreamsToSend, "2");
-
- auto channel = GetChannel();
- GPR_ASSERT(channel);
- EXPECT_TRUE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
- auto stub = CreateStub();
-
- auto stream = stub->BidiStream(&context);
-
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
-
- // time jumps forward by TIME_OFFSET1 milliseconds.
- set_now_offset(TIME_OFFSET1);
-
- request.set_message("World");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->WritesDone());
- EXPECT_TRUE(stream->Read(&response));
-
- auto status = stream->Finish();
- EXPECT_TRUE(status.ok());
-}
-
-// Wall-clock time jumps back on client while call is in progress
-TEST_F(TimeChangeTest, TimeJumpBackAfterStreamCreated) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
- context.AddMetadata(kServerResponseStreamsToSend, "2");
-
- auto channel = GetChannel();
- GPR_ASSERT(channel);
- EXPECT_TRUE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
- auto stub = CreateStub();
-
- auto stream = stub->BidiStream(&context);
-
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->Read(&response));
-
- // time jumps back TIME_OFFSET1 milliseconds.
- set_now_offset(-TIME_OFFSET1);
-
- request.set_message("World");
- EXPECT_TRUE(stream->Write(request));
- EXPECT_TRUE(stream->WritesDone());
- EXPECT_TRUE(stream->Read(&response));
-
- auto status = stream->Finish();
- EXPECT_TRUE(status.ok());
-}
-
-// Wall-clock time jumps forward and backwards during call
-TEST_F(TimeChangeTest, TimeJumpForwardAndBackDuringCall) {
- EchoRequest request;
- EchoResponse response;
- ClientContext context;
- context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
- context.AddMetadata(kServerResponseStreamsToSend, "2");
-
- auto channel = GetChannel();
- GPR_ASSERT(channel);
-
- EXPECT_TRUE(
- channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
- auto stub = CreateStub();
- auto stream = stub->BidiStream(&context);
-
- request.set_message("Hello");
- EXPECT_TRUE(stream->Write(request));
-
- // time jumps back by TIME_OFFSET2 milliseconds
- set_now_offset(-TIME_OFFSET2);
-
- EXPECT_TRUE(stream->Read(&response));
- request.set_message("World");
-
- // time jumps forward by TIME_OFFSET milliseconds
- set_now_offset(TIME_OFFSET1);
-
- EXPECT_TRUE(stream->Write(request));
-
- // time jumps back by TIME_OFFSET2 milliseconds
- set_now_offset(-TIME_OFFSET2);
-
- EXPECT_TRUE(stream->WritesDone());
-
- // time jumps back by TIME_OFFSET2 milliseconds
- set_now_offset(-TIME_OFFSET2);
-
- EXPECT_TRUE(stream->Read(&response));
-
- // time jumps back by TIME_OFFSET2 milliseconds
- set_now_offset(-TIME_OFFSET2);
-
- auto status = stream->Finish();
- EXPECT_TRUE(status.ok());
-}
-
-} // namespace
-
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
+std::unique_ptr<SubProcess> TimeChangeTest::server_;
+
+// Wall-clock time jumps forward on client before bidi stream is created
+TEST_F(TimeChangeTest, TimeJumpForwardBeforeStreamCreated) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
+ context.AddMetadata(kServerResponseStreamsToSend, "1");
+
+ auto channel = GetChannel();
+ GPR_ASSERT(channel);
+ EXPECT_TRUE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
+ auto stub = CreateStub();
+
+ // time jumps forward by TIME_OFFSET1 milliseconds
+ set_now_offset(TIME_OFFSET1);
+ auto stream = stub->BidiStream(&context);
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+
+ EXPECT_TRUE(stream->WritesDone());
+ EXPECT_TRUE(stream->Read(&response));
+
+ auto status = stream->Finish();
+ EXPECT_TRUE(status.ok());
+}
+
+// Wall-clock time jumps back on client before bidi stream is created
+TEST_F(TimeChangeTest, TimeJumpBackBeforeStreamCreated) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
+ context.AddMetadata(kServerResponseStreamsToSend, "1");
+
+ auto channel = GetChannel();
+ GPR_ASSERT(channel);
+ EXPECT_TRUE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
+ auto stub = CreateStub();
+
+ // time jumps back by TIME_OFFSET1 milliseconds
+ set_now_offset(-TIME_OFFSET1);
+ auto stream = stub->BidiStream(&context);
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+
+ EXPECT_TRUE(stream->WritesDone());
+ EXPECT_TRUE(stream->Read(&response));
+ EXPECT_EQ(request.message(), response.message());
+
+ auto status = stream->Finish();
+ EXPECT_TRUE(status.ok());
+}
+
+// Wall-clock time jumps forward on client while call is in progress
+TEST_F(TimeChangeTest, TimeJumpForwardAfterStreamCreated) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
+ context.AddMetadata(kServerResponseStreamsToSend, "2");
+
+ auto channel = GetChannel();
+ GPR_ASSERT(channel);
+ EXPECT_TRUE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
+ auto stub = CreateStub();
+
+ auto stream = stub->BidiStream(&context);
+
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+
+ // time jumps forward by TIME_OFFSET1 milliseconds.
+ set_now_offset(TIME_OFFSET1);
+
+ request.set_message("World");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->WritesDone());
+ EXPECT_TRUE(stream->Read(&response));
+
+ auto status = stream->Finish();
+ EXPECT_TRUE(status.ok());
+}
+
+// Wall-clock time jumps back on client while call is in progress
+TEST_F(TimeChangeTest, TimeJumpBackAfterStreamCreated) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
+ context.AddMetadata(kServerResponseStreamsToSend, "2");
+
+ auto channel = GetChannel();
+ GPR_ASSERT(channel);
+ EXPECT_TRUE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
+ auto stub = CreateStub();
+
+ auto stream = stub->BidiStream(&context);
+
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->Read(&response));
+
+ // time jumps back TIME_OFFSET1 milliseconds.
+ set_now_offset(-TIME_OFFSET1);
+
+ request.set_message("World");
+ EXPECT_TRUE(stream->Write(request));
+ EXPECT_TRUE(stream->WritesDone());
+ EXPECT_TRUE(stream->Read(&response));
+
+ auto status = stream->Finish();
+ EXPECT_TRUE(status.ok());
+}
+
+// Wall-clock time jumps forward and backwards during call
+TEST_F(TimeChangeTest, TimeJumpForwardAndBackDuringCall) {
+ EchoRequest request;
+ EchoResponse response;
+ ClientContext context;
+ context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
+ context.AddMetadata(kServerResponseStreamsToSend, "2");
+
+ auto channel = GetChannel();
+ GPR_ASSERT(channel);
+
+ EXPECT_TRUE(
+ channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
+ auto stub = CreateStub();
+ auto stream = stub->BidiStream(&context);
+
+ request.set_message("Hello");
+ EXPECT_TRUE(stream->Write(request));
+
+ // time jumps back by TIME_OFFSET2 milliseconds
+ set_now_offset(-TIME_OFFSET2);
+
+ EXPECT_TRUE(stream->Read(&response));
+ request.set_message("World");
+
+ // time jumps forward by TIME_OFFSET milliseconds
+ set_now_offset(TIME_OFFSET1);
+
+ EXPECT_TRUE(stream->Write(request));
+
+ // time jumps back by TIME_OFFSET2 milliseconds
+ set_now_offset(-TIME_OFFSET2);
+
+ EXPECT_TRUE(stream->WritesDone());
+
+ // time jumps back by TIME_OFFSET2 milliseconds
+ set_now_offset(-TIME_OFFSET2);
+
+ EXPECT_TRUE(stream->Read(&response));
+
+ // time jumps back by TIME_OFFSET2 milliseconds
+ set_now_offset(-TIME_OFFSET2);
+
+ auto status = stream->Finish();
+ EXPECT_TRUE(status.ok());
+}
+
+} // namespace
+
+} // namespace testing
+} // namespace grpc
+
+int main(int argc, char** argv) {
TString me = argv[0];
- // get index of last slash in path to test binary
- auto lslash = me.rfind('/');
- // set g_root = path to directory containing test binary
+ // get index of last slash in path to test binary
+ auto lslash = me.rfind('/');
+ // set g_root = path to directory containing test binary
if (lslash != TString::npos) {
- g_root = me.substr(0, lslash);
- } else {
- g_root = ".";
- }
-
- gpr_mu_init(&g_mu);
- gpr_now_impl = now_impl;
-
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- auto ret = RUN_ALL_TESTS();
- return ret;
-}
+ g_root = me.substr(0, lslash);
+ } else {
+ g_root = ".";
+ }
+
+ gpr_mu_init(&g_mu);
+ gpr_now_impl = now_impl;
+
+ grpc::testing::TestEnvironment env(argc, argv);
+ ::testing::InitGoogleTest(&argc, argv);
+ auto ret = RUN_ALL_TESTS();
+ return ret;
+}
diff --git a/contrib/libs/grpc/test/cpp/end2end/ya.make b/contrib/libs/grpc/test/cpp/end2end/ya.make
index b9c1dc7fe0..56b0d699f3 100644
--- a/contrib/libs/grpc/test/cpp/end2end/ya.make
+++ b/contrib/libs/grpc/test/cpp/end2end/ya.make
@@ -1,67 +1,67 @@
-LIBRARY()
-
+LIBRARY()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
+
OWNER(dvshkurko)
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/health/v1
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/cpp/util
- contrib/libs/grpc
+PEERDIR(
+ contrib/libs/grpc/src/proto/grpc/health/v1
+ contrib/libs/grpc/src/proto/grpc/testing
+ contrib/libs/grpc/src/proto/grpc/testing/duplicate
+ contrib/libs/grpc/test/cpp/util
+ contrib/libs/grpc
contrib/restricted/googletest/googlemock
contrib/restricted/googletest/googletest
-)
-
+)
+
ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
contrib/libs/grpc
)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- # async_end2end_test.cc
- # channelz_service_test.cc
- # client_callback_end2end_test.cc
- # client_crash_test.cc
- # client_crash_test_server.cc
- # client_interceptors_end2end_test.cc
- # client_lb_end2end_test.cc lb needs opencensus, not enabled.
- # end2end_test.cc
- # exception_test.cc
- # filter_end2end_test.cc
- # generic_end2end_test.cc
- # grpclb_end2end_test.cc lb needs opencensus, not enabled.
- # health_service_end2end_test.cc
- # hybrid_end2end_test.cc
- interceptors_util.cc
- # mock_test.cc
- # nonblocking_test.cc
- # proto_server_reflection_test.cc
- # raw_end2end_test.cc
- # server_builder_plugin_test.cc
- # server_crash_test.cc
- # server_crash_test_client.cc
- # server_early_return_test.cc
- # server_interceptors_end2end_test.cc
- # server_load_reporting_end2end_test.cc
- # shutdown_test.cc
- # streaming_throughput_test.cc
- test_health_check_service_impl.cc
- test_service_impl.cc
- # thread_stress_test.cc
- # time_change_test.cc
-)
-
-END()
-
-RECURSE_FOR_TESTS(
- health
- server_interceptors
- # Needs new gtest
- # thread
-)
+
+NO_COMPILER_WARNINGS()
+
+SRCS(
+ # async_end2end_test.cc
+ # channelz_service_test.cc
+ # client_callback_end2end_test.cc
+ # client_crash_test.cc
+ # client_crash_test_server.cc
+ # client_interceptors_end2end_test.cc
+ # client_lb_end2end_test.cc lb needs opencensus, not enabled.
+ # end2end_test.cc
+ # exception_test.cc
+ # filter_end2end_test.cc
+ # generic_end2end_test.cc
+ # grpclb_end2end_test.cc lb needs opencensus, not enabled.
+ # health_service_end2end_test.cc
+ # hybrid_end2end_test.cc
+ interceptors_util.cc
+ # mock_test.cc
+ # nonblocking_test.cc
+ # proto_server_reflection_test.cc
+ # raw_end2end_test.cc
+ # server_builder_plugin_test.cc
+ # server_crash_test.cc
+ # server_crash_test_client.cc
+ # server_early_return_test.cc
+ # server_interceptors_end2end_test.cc
+ # server_load_reporting_end2end_test.cc
+ # shutdown_test.cc
+ # streaming_throughput_test.cc
+ test_health_check_service_impl.cc
+ test_service_impl.cc
+ # thread_stress_test.cc
+ # time_change_test.cc
+)
+
+END()
+
+RECURSE_FOR_TESTS(
+ health
+ server_interceptors
+ # Needs new gtest
+ # thread
+)
diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc b/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc
index c63f351a8f..2354b46f51 100644
--- a/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc
+++ b/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc
@@ -38,13 +38,13 @@ namespace {
const char* kContent1 = "hello xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char* kContent2 = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy world";
-class ByteBufferTest : public ::testing::Test {
- protected:
- static void SetUpTestCase() { grpc_init(); }
-
- static void TearDownTestCase() { grpc_shutdown(); }
-};
+class ByteBufferTest : public ::testing::Test {
+ protected:
+ static void SetUpTestCase() { grpc_init(); }
+ static void TearDownTestCase() { grpc_shutdown(); }
+};
+
TEST_F(ByteBufferTest, CopyCtor) {
ByteBuffer buffer1;
EXPECT_FALSE(buffer1.Valid());
diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.h b/contrib/libs/grpc/test/cpp/util/cli_call.h
index 79d00d99f4..5284b00084 100644
--- a/contrib/libs/grpc/test/cpp/util/cli_call.h
+++ b/contrib/libs/grpc/test/cpp/util/cli_call.h
@@ -27,7 +27,7 @@
#include <map>
-namespace grpc {
+namespace grpc {
class ClientContext;
diff --git a/contrib/libs/grpc/test/cpp/util/cli_call_test.cc b/contrib/libs/grpc/test/cpp/util/cli_call_test.cc
index 4f0544b2e5..e99c6a28b9 100644
--- a/contrib/libs/grpc/test/cpp/util/cli_call_test.cc
+++ b/contrib/libs/grpc/test/cpp/util/cli_call_test.cc
@@ -74,8 +74,8 @@ class CliCallTest : public ::testing::Test {
void TearDown() override { server_->Shutdown(); }
void ResetStub() {
- channel_ = grpc::CreateChannel(server_address_.str(),
- InsecureChannelCredentials());
+ channel_ = grpc::CreateChannel(server_address_.str(),
+ InsecureChannelCredentials());
stub_ = grpc::testing::EchoTestService::NewStub(channel_);
}
diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc b/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
index efd548eb9b..e7127f9296 100644
--- a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
+++ b/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
@@ -41,11 +41,11 @@ DEFINE_string(
"validation.");
DEFINE_string(
ssl_client_cert, "",
- "If not empty, load this PEM formatted client certificate file. Requires "
+ "If not empty, load this PEM formatted client certificate file. Requires "
"use of --ssl_client_key.");
DEFINE_string(
ssl_client_key, "",
- "If not empty, load this PEM formatted private key. Requires use of "
+ "If not empty, load this PEM formatted private key. Requires use of "
"--ssl_client_cert");
DEFINE_string(
local_connect_type, "local_tcp",
diff --git a/contrib/libs/grpc/test/cpp/util/create_test_channel.cc b/contrib/libs/grpc/test/cpp/util/create_test_channel.cc
index 86d8e22af1..d660428537 100644
--- a/contrib/libs/grpc/test/cpp/util/create_test_channel.cc
+++ b/contrib/libs/grpc/test/cpp/util/create_test_channel.cc
@@ -42,8 +42,8 @@ const char kProdTlsCredentialsType[] = "prod_ssl";
class SslCredentialProvider : public testing::CredentialTypeProvider {
public:
std::shared_ptr<ChannelCredentials> GetChannelCredentials(
- grpc::ChannelArguments* /*args*/) override {
- return grpc::SslCredentials(SslCredentialsOptions());
+ grpc::ChannelArguments* /*args*/) override {
+ return grpc::SslCredentials(SslCredentialsOptions());
}
std::shared_ptr<ServerCredentials> GetServerCredentials() override {
return nullptr;
@@ -90,76 +90,76 @@ std::shared_ptr<Channel> CreateTestChannel(
const TString& override_hostname, bool use_prod_roots,
const std::shared_ptr<CallCredentials>& creds,
const ChannelArguments& args) {
- return CreateTestChannel(server, cred_type, override_hostname, use_prod_roots,
- creds, args,
- /*interceptor_creators=*/{});
-}
-
-std::shared_ptr<Channel> CreateTestChannel(
+ return CreateTestChannel(server, cred_type, override_hostname, use_prod_roots,
+ creds, args,
+ /*interceptor_creators=*/{});
+}
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
- testing::transport_security security_type, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds,
- const ChannelArguments& args) {
- return CreateTestChannel(server, override_hostname, security_type,
- use_prod_roots, creds, args,
- /*interceptor_creators=*/{});
-}
-
-std::shared_ptr<Channel> CreateTestChannel(
+ testing::transport_security security_type, bool use_prod_roots,
+ const std::shared_ptr<CallCredentials>& creds,
+ const ChannelArguments& args) {
+ return CreateTestChannel(server, override_hostname, security_type,
+ use_prod_roots, creds, args,
+ /*interceptor_creators=*/{});
+}
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
- testing::transport_security security_type, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds) {
- return CreateTestChannel(server, override_hostname, security_type,
- use_prod_roots, creds, ChannelArguments());
-}
-
-std::shared_ptr<Channel> CreateTestChannel(
+ testing::transport_security security_type, bool use_prod_roots,
+ const std::shared_ptr<CallCredentials>& creds) {
+ return CreateTestChannel(server, override_hostname, security_type,
+ use_prod_roots, creds, ChannelArguments());
+}
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
- testing::transport_security security_type, bool use_prod_roots) {
- return CreateTestChannel(server, override_hostname, security_type,
- use_prod_roots, std::shared_ptr<CallCredentials>());
-}
-
-// Shortcut for end2end and interop tests.
-std::shared_ptr<Channel> CreateTestChannel(
+ testing::transport_security security_type, bool use_prod_roots) {
+ return CreateTestChannel(server, override_hostname, security_type,
+ use_prod_roots, std::shared_ptr<CallCredentials>());
+}
+
+// Shortcut for end2end and interop tests.
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, testing::transport_security security_type) {
- return CreateTestChannel(server, "foo.test.google.fr", security_type, false);
-}
-
-std::shared_ptr<Channel> CreateTestChannel(
+ return CreateTestChannel(server, "foo.test.google.fr", security_type, false);
+}
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& credential_type,
- const std::shared_ptr<CallCredentials>& creds) {
- ChannelArguments channel_args;
+ const std::shared_ptr<CallCredentials>& creds) {
+ ChannelArguments channel_args;
MaybeSetCustomChannelArgs(&channel_args);
- std::shared_ptr<ChannelCredentials> channel_creds =
- testing::GetCredentialsProvider()->GetChannelCredentials(credential_type,
- &channel_args);
- GPR_ASSERT(channel_creds != nullptr);
- if (creds.get()) {
- channel_creds = grpc::CompositeChannelCredentials(channel_creds, creds);
- }
- return ::grpc::CreateCustomChannel(server, channel_creds, channel_args);
-}
-
-std::shared_ptr<Channel> CreateTestChannel(
+ std::shared_ptr<ChannelCredentials> channel_creds =
+ testing::GetCredentialsProvider()->GetChannelCredentials(credential_type,
+ &channel_args);
+ GPR_ASSERT(channel_creds != nullptr);
+ if (creds.get()) {
+ channel_creds = grpc::CompositeChannelCredentials(channel_creds, creds);
+ }
+ return ::grpc::CreateCustomChannel(server, channel_creds, channel_args);
+}
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& cred_type,
const TString& override_hostname, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators) {
+ const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators) {
ChannelArguments channel_args(args);
MaybeSetCustomChannelArgs(&channel_args);
std::shared_ptr<ChannelCredentials> channel_creds;
if (cred_type.empty()) {
- if (interceptor_creators.empty()) {
- return ::grpc::CreateCustomChannel(server, InsecureChannelCredentials(),
+ if (interceptor_creators.empty()) {
+ return ::grpc::CreateCustomChannel(server, InsecureChannelCredentials(),
channel_args);
- } else {
- return experimental::CreateCustomChannelWithInterceptors(
+ } else {
+ return experimental::CreateCustomChannelWithInterceptors(
server, InsecureChannelCredentials(), channel_args,
- std::move(interceptor_creators));
- }
+ std::move(interceptor_creators));
+ }
} else if (cred_type == testing::kTlsCredentialsType) { // cred_type == "ssl"
if (use_prod_roots) {
gpr_once_init(&g_once_init_add_prod_ssl_provider, &AddProdSslType);
@@ -177,65 +177,65 @@ std::shared_ptr<Channel> CreateTestChannel(
const TString& connect_to = server.empty() ? override_hostname : server;
if (creds.get()) {
- channel_creds = grpc::CompositeChannelCredentials(channel_creds, creds);
- }
- if (interceptor_creators.empty()) {
- return ::grpc::CreateCustomChannel(connect_to, channel_creds,
- channel_args);
- } else {
- return experimental::CreateCustomChannelWithInterceptors(
- connect_to, channel_creds, channel_args,
- std::move(interceptor_creators));
+ channel_creds = grpc::CompositeChannelCredentials(channel_creds, creds);
}
+ if (interceptor_creators.empty()) {
+ return ::grpc::CreateCustomChannel(connect_to, channel_creds,
+ channel_args);
+ } else {
+ return experimental::CreateCustomChannelWithInterceptors(
+ connect_to, channel_creds, channel_args,
+ std::move(interceptor_creators));
+ }
} else {
channel_creds = testing::GetCredentialsProvider()->GetChannelCredentials(
cred_type, &channel_args);
GPR_ASSERT(channel_creds != nullptr);
- if (interceptor_creators.empty()) {
+ if (interceptor_creators.empty()) {
return ::grpc::CreateCustomChannel(server, channel_creds, channel_args);
- } else {
- return experimental::CreateCustomChannelWithInterceptors(
+ } else {
+ return experimental::CreateCustomChannelWithInterceptors(
server, channel_creds, channel_args, std::move(interceptor_creators));
- }
+ }
}
}
std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
testing::transport_security security_type, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators) {
+ const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators) {
TString credential_type =
security_type == testing::ALTS
? testing::kAltsCredentialsType
: (security_type == testing::TLS ? testing::kTlsCredentialsType
: testing::kInsecureCredentialsType);
- return CreateTestChannel(server, credential_type, override_hostname,
- use_prod_roots, creds, args,
- std::move(interceptor_creators));
+ return CreateTestChannel(server, credential_type, override_hostname,
+ use_prod_roots, creds, args,
+ std::move(interceptor_creators));
}
std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
testing::transport_security security_type, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators) {
+ const std::shared_ptr<CallCredentials>& creds,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators) {
return CreateTestChannel(server, override_hostname, security_type,
- use_prod_roots, creds, ChannelArguments(),
- std::move(interceptor_creators));
+ use_prod_roots, creds, ChannelArguments(),
+ std::move(interceptor_creators));
}
std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& credential_type,
- const std::shared_ptr<CallCredentials>& creds,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators) {
+ const std::shared_ptr<CallCredentials>& creds,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators) {
ChannelArguments channel_args;
MaybeSetCustomChannelArgs(&channel_args);
std::shared_ptr<ChannelCredentials> channel_creds =
@@ -243,10 +243,10 @@ std::shared_ptr<Channel> CreateTestChannel(
&channel_args);
GPR_ASSERT(channel_creds != nullptr);
if (creds.get()) {
- channel_creds = grpc::CompositeChannelCredentials(channel_creds, creds);
+ channel_creds = grpc::CompositeChannelCredentials(channel_creds, creds);
}
- return experimental::CreateCustomChannelWithInterceptors(
- server, channel_creds, channel_args, std::move(interceptor_creators));
+ return experimental::CreateCustomChannelWithInterceptors(
+ server, channel_creds, channel_args, std::move(interceptor_creators));
}
} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/create_test_channel.h b/contrib/libs/grpc/test/cpp/util/create_test_channel.h
index ed4ce6c11b..9ce9ca7fc5 100644
--- a/contrib/libs/grpc/test/cpp/util/create_test_channel.h
+++ b/contrib/libs/grpc/test/cpp/util/create_test_channel.h
@@ -21,10 +21,10 @@
#include <memory>
-#include <grpcpp/channel.h>
-#include <grpcpp/impl/codegen/client_interceptor.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/impl/codegen/client_interceptor.h>
#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/channel_arguments.h>
+#include <grpcpp/support/channel_arguments.h>
namespace grpc {
class Channel;
@@ -63,37 +63,37 @@ std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& credential_type,
const std::shared_ptr<CallCredentials>& creds);
-std::shared_ptr<Channel> CreateTestChannel(
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
- testing::transport_security security_type, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators);
-
-std::shared_ptr<Channel> CreateTestChannel(
+ testing::transport_security security_type, bool use_prod_roots,
+ const std::shared_ptr<CallCredentials>& creds,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators);
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& override_hostname,
- testing::transport_security security_type, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators);
-
-std::shared_ptr<Channel> CreateTestChannel(
+ testing::transport_security security_type, bool use_prod_roots,
+ const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators);
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& cred_type,
const TString& override_hostname, bool use_prod_roots,
- const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators);
-
-std::shared_ptr<Channel> CreateTestChannel(
+ const std::shared_ptr<CallCredentials>& creds, const ChannelArguments& args,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators);
+
+std::shared_ptr<Channel> CreateTestChannel(
const TString& server, const TString& credential_type,
- const std::shared_ptr<CallCredentials>& creds,
- std::vector<
- std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- interceptor_creators);
-
+ const std::shared_ptr<CallCredentials>& creds,
+ std::vector<
+ std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
+ interceptor_creators);
+
} // namespace grpc
#endif // GRPC_TEST_CPP_UTIL_CREATE_TEST_CHANNEL_H
diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc b/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
index 30f3024e25..850ff70803 100644
--- a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
+++ b/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
@@ -233,8 +233,8 @@ std::shared_ptr<grpc::Channel> CreateCliChannel(
args.SetString(GRPC_ARG_SERVICE_CONFIG,
FLAGS_default_service_config.c_str());
}
- return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(),
- args);
+ return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(),
+ args);
}
struct Command {
@@ -443,7 +443,7 @@ bool GrpcTool::ListServices(int argc, const char** argv,
return callback(output);
}
-bool GrpcTool::PrintType(int /*argc*/, const char** argv,
+bool GrpcTool::PrintType(int /*argc*/, const char** argv,
const CliCredentials& cred,
GrpcToolOutputCallback callback) {
CommandUsage(
@@ -485,8 +485,8 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
" fallback when parsing request/response\n"
" --proto_path ; The search path of proto files, valid"
" only when --protofiles is given\n"
- " --noremotedb ; Don't attempt to use reflection service"
- " at all\n"
+ " --noremotedb ; Don't attempt to use reflection service"
+ " at all\n"
" --metadata ; The metadata to be sent to the server\n"
" --infile ; Input filename (defaults to stdin)\n"
" --outfile ; Output filename (defaults to stdout)\n"
@@ -618,7 +618,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
call.WritesDoneAndWait();
read_thread.join();
- gpr_mu_destroy(&parser_mu);
+ gpr_mu_destroy(&parser_mu);
std::multimap<grpc::string_ref, grpc::string_ref> server_trailing_metadata;
Status status = call.Finish(&server_trailing_metadata);
@@ -847,8 +847,8 @@ bool GrpcTool::ParseMessage(int argc, const char** argv,
" fallback when parsing request/response\n"
" --proto_path ; The search path of proto files, valid"
" only when --protofiles is given\n"
- " --noremotedb ; Don't attempt to use reflection service"
- " at all\n"
+ " --noremotedb ; Don't attempt to use reflection service"
+ " at all\n"
" --infile ; Input filename (defaults to stdin)\n"
" --outfile ; Output filename (defaults to stdout)\n"
" --binary_input ; Input in binary format\n"
diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc b/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc
index ff610daadd..ebabc74772 100644
--- a/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc
+++ b/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc
@@ -471,9 +471,9 @@ TEST_F(GrpcToolTest, TypeNotFound) {
const char* argv[] = {"grpc_cli", "type", server_address.c_str(),
"grpc.testing.DummyRequest"};
- EXPECT_TRUE(1 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
- std::bind(PrintStream, &output_stream,
- std::placeholders::_1)));
+ EXPECT_TRUE(1 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
+ std::bind(PrintStream, &output_stream,
+ std::placeholders::_1)));
ShutdownServer();
}
diff --git a/contrib/libs/grpc/test/cpp/util/metrics_server.cc b/contrib/libs/grpc/test/cpp/util/metrics_server.cc
index 0493da053e..69a17cf384 100644
--- a/contrib/libs/grpc/test/cpp/util/metrics_server.cc
+++ b/contrib/libs/grpc/test/cpp/util/metrics_server.cc
@@ -51,7 +51,7 @@ long QpsGauge::Get() {
}
grpc::Status MetricsServiceImpl::GetAllGauges(
- ServerContext* /*context*/, const EmptyMessage* /*request*/,
+ ServerContext* /*context*/, const EmptyMessage* /*request*/,
ServerWriter<GaugeResponse>* writer) {
gpr_log(GPR_DEBUG, "GetAllGauges called");
@@ -66,7 +66,7 @@ grpc::Status MetricsServiceImpl::GetAllGauges(
return Status::OK;
}
-grpc::Status MetricsServiceImpl::GetGauge(ServerContext* /*context*/,
+grpc::Status MetricsServiceImpl::GetGauge(ServerContext* /*context*/,
const GaugeRequest* request,
GaugeResponse* response) {
std::lock_guard<std::mutex> lock(mu_);
diff --git a/contrib/libs/grpc/test/cpp/util/metrics_server.h b/contrib/libs/grpc/test/cpp/util/metrics_server.h
index 10ffa7b4dd..2c3c358d1c 100644
--- a/contrib/libs/grpc/test/cpp/util/metrics_server.h
+++ b/contrib/libs/grpc/test/cpp/util/metrics_server.h
@@ -21,8 +21,8 @@
#include <map>
#include <mutex>
-#include <grpcpp/server.h>
-
+#include <grpcpp/server.h>
+
#include "src/proto/grpc/testing/metrics.grpc.pb.h"
#include "src/proto/grpc/testing/metrics.pb.h"
diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h b/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
index c0445641c7..8ae383001c 100644
--- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
+++ b/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
@@ -62,7 +62,7 @@ class ProtoFileParser {
/// \param is_json_format if \c true the \c formatted_proto is treated as a
/// json-formatted proto, otherwise it is treated as a text-formatted
/// proto
- /// \return the serialised binary proto representation of \c formatted_proto
+ /// \return the serialised binary proto representation of \c formatted_proto
TString GetSerializedProtoFromMethod(const TString& method,
const TString& formatted_proto,
bool is_request,
@@ -71,7 +71,7 @@ class ProtoFileParser {
/// Converts a text or json string to its proto representation for the given
/// message type.
/// \param formatted_proto the text- or json-formatted proto string
- /// \return the serialised binary proto representation of \c formatted_proto
+ /// \return the serialised binary proto representation of \c formatted_proto
TString GetSerializedProtoFromMessageType(
const TString& message_type_name, const TString& formatted_proto,
bool is_json_format);
diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
index 27a4c1e4cf..488f382999 100644
--- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
+++ b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
@@ -44,16 +44,16 @@ ProtoReflectionDescriptorDatabase::~ProtoReflectionDescriptorDatabase() {
Status status = stream_->Finish();
if (!status.ok()) {
if (status.error_code() == StatusCode::UNIMPLEMENTED) {
- fprintf(stderr,
+ fprintf(stderr,
"Reflection request not implemented; "
- "is the ServerReflection service enabled?\n");
- } else {
- fprintf(stderr,
- "ServerReflectionInfo rpc failed. Error code: %d, message: %s, "
- "debug info: %s\n",
- static_cast<int>(status.error_code()),
- status.error_message().c_str(),
- ctx_.debug_error_string().c_str());
+ "is the ServerReflection service enabled?\n");
+ } else {
+ fprintf(stderr,
+ "ServerReflectionInfo rpc failed. Error code: %d, message: %s, "
+ "debug info: %s\n",
+ static_cast<int>(status.error_code()),
+ status.error_message().c_str(),
+ ctx_.debug_error_string().c_str());
}
}
}
diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
index cdd6f0cccd..6f6244278e 100644
--- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
+++ b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
@@ -44,7 +44,7 @@ class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase {
// The following four methods implement DescriptorDatabase interfaces.
//
- // Find a file by file name. Fills in *output and returns true if found.
+ // Find a file by file name. Fills in *output and returns true if found.
// Otherwise, returns false, leaving the contents of *output undefined.
bool FindFileByName(const google::protobuf::string& filename,
protobuf::FileDescriptorProto* output) override;
diff --git a/contrib/libs/grpc/test/cpp/util/slice_test.cc b/contrib/libs/grpc/test/cpp/util/slice_test.cc
index d7e945ae38..eeab4b298c 100644
--- a/contrib/libs/grpc/test/cpp/util/slice_test.cc
+++ b/contrib/libs/grpc/test/cpp/util/slice_test.cc
@@ -35,10 +35,10 @@ const char* kContent = "hello xxxxxxxxxxxxxxxxxxxx world";
class SliceTest : public ::testing::Test {
protected:
- static void SetUpTestCase() { grpc_init(); }
-
- static void TearDownTestCase() { grpc_shutdown(); }
-
+ static void SetUpTestCase() { grpc_init(); }
+
+ static void TearDownTestCase() { grpc_shutdown(); }
+
void CheckSliceSize(const Slice& s, const TString& content) {
EXPECT_EQ(content.size(), s.size());
}
@@ -82,7 +82,7 @@ TEST_F(SliceTest, SliceNew) {
}
TEST_F(SliceTest, SliceNewDoNothing) {
- Slice spp(const_cast<char*>(kContent), strlen(kContent), [](void* /*p*/) {});
+ Slice spp(const_cast<char*>(kContent), strlen(kContent), [](void* /*p*/) {});
CheckSlice(spp, kContent);
}
@@ -106,7 +106,7 @@ TEST_F(SliceTest, SliceNewWithUserData) {
TEST_F(SliceTest, SliceNewLen) {
Slice spp(const_cast<char*>(kContent), strlen(kContent),
- [](void* /*p*/, size_t l) { EXPECT_EQ(l, strlen(kContent)); });
+ [](void* /*p*/, size_t l) { EXPECT_EQ(l, strlen(kContent)); });
CheckSlice(spp, kContent);
}
diff --git a/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc b/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc
index f7134b773f..98a89b51ee 100644
--- a/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc
+++ b/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc
@@ -19,50 +19,50 @@
#include "test/cpp/util/test_credentials_provider.h"
-#include <cstdio>
-#include <fstream>
-#include <iostream>
-
+#include <cstdio>
+#include <fstream>
+#include <iostream>
+
#include <mutex>
#include <unordered_map>
-#include <gflags/gflags.h>
+#include <gflags/gflags.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
-#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/security/server_credentials.h>
#include "test/core/end2end/data/ssl_test_data.h"
-DEFINE_string(tls_cert_file, "", "The TLS cert file used when --use_tls=true");
-DEFINE_string(tls_key_file, "", "The TLS key file used when --use_tls=true");
-
+DEFINE_string(tls_cert_file, "", "The TLS cert file used when --use_tls=true");
+DEFINE_string(tls_key_file, "", "The TLS key file used when --use_tls=true");
+
namespace grpc {
namespace testing {
namespace {
TString ReadFile(const TString& src_path) {
- std::ifstream src;
- src.open(src_path, std::ifstream::in | std::ifstream::binary);
-
+ std::ifstream src;
+ src.open(src_path, std::ifstream::in | std::ifstream::binary);
+
TString contents;
- src.seekg(0, std::ios::end);
- contents.reserve(src.tellg());
- src.seekg(0, std::ios::beg);
- contents.assign((std::istreambuf_iterator<char>(src)),
- (std::istreambuf_iterator<char>()));
- return contents;
-}
-
+ src.seekg(0, std::ios::end);
+ contents.reserve(src.tellg());
+ src.seekg(0, std::ios::beg);
+ contents.assign((std::istreambuf_iterator<char>(src)),
+ (std::istreambuf_iterator<char>()));
+ return contents;
+}
+
class DefaultCredentialsProvider : public CredentialsProvider {
public:
- DefaultCredentialsProvider() {
- if (!FLAGS_tls_key_file.empty()) {
- custom_server_key_ = ReadFile(FLAGS_tls_key_file);
- }
- if (!FLAGS_tls_cert_file.empty()) {
- custom_server_cert_ = ReadFile(FLAGS_tls_cert_file);
- }
- }
+ DefaultCredentialsProvider() {
+ if (!FLAGS_tls_key_file.empty()) {
+ custom_server_key_ = ReadFile(FLAGS_tls_key_file);
+ }
+ if (!FLAGS_tls_cert_file.empty()) {
+ custom_server_cert_ = ReadFile(FLAGS_tls_cert_file);
+ }
+ }
~DefaultCredentialsProvider() override {}
void AddSecureType(
@@ -92,7 +92,7 @@ class DefaultCredentialsProvider : public CredentialsProvider {
} else if (type == grpc::testing::kTlsCredentialsType) {
SslCredentialsOptions ssl_opts = {test_root_cert, "", ""};
args->SetSslTargetNameOverride("foo.test.google.fr");
- return grpc::SslCredentials(ssl_opts);
+ return grpc::SslCredentials(ssl_opts);
} else if (type == grpc::testing::kGoogleDefaultCredentialsType) {
return grpc::GoogleDefaultCredentials();
} else {
@@ -118,15 +118,15 @@ class DefaultCredentialsProvider : public CredentialsProvider {
} else if (type == grpc::testing::kTlsCredentialsType) {
SslServerCredentialsOptions ssl_opts;
ssl_opts.pem_root_certs = "";
- if (!custom_server_key_.empty() && !custom_server_cert_.empty()) {
- SslServerCredentialsOptions::PemKeyCertPair pkcp = {
- custom_server_key_, custom_server_cert_};
- ssl_opts.pem_key_cert_pairs.push_back(pkcp);
- } else {
- SslServerCredentialsOptions::PemKeyCertPair pkcp = {test_server1_key,
- test_server1_cert};
- ssl_opts.pem_key_cert_pairs.push_back(pkcp);
- }
+ if (!custom_server_key_.empty() && !custom_server_cert_.empty()) {
+ SslServerCredentialsOptions::PemKeyCertPair pkcp = {
+ custom_server_key_, custom_server_cert_};
+ ssl_opts.pem_key_cert_pairs.push_back(pkcp);
+ } else {
+ SslServerCredentialsOptions::PemKeyCertPair pkcp = {test_server1_key,
+ test_server1_cert};
+ ssl_opts.pem_key_cert_pairs.push_back(pkcp);
+ }
return SslServerCredentials(ssl_opts);
} else {
std::unique_lock<std::mutex> lock(mu_);
diff --git a/contrib/libs/grpc/test/cpp/util/ya.make b/contrib/libs/grpc/test/cpp/util/ya.make
index f043cc5b14..72346d2811 100644
--- a/contrib/libs/grpc/test/cpp/util/ya.make
+++ b/contrib/libs/grpc/test/cpp/util/ya.make
@@ -9,7 +9,7 @@ OWNER(orivej)
PEERDIR(
contrib/libs/gflags
contrib/libs/protoc
- contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
+ contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
contrib/restricted/googletest/googlemock
contrib/restricted/googletest/googletest
)
@@ -22,14 +22,14 @@ ADDINCL(
NO_COMPILER_WARNINGS()
SRCS(
- byte_buffer_proto_helper.cc
+ byte_buffer_proto_helper.cc
# grpc_cli_libs:
cli_call.cc
cli_credentials.cc
grpc_tool.cc
proto_file_parser.cc
service_describer.cc
- string_ref_helper.cc
+ string_ref_helper.cc
# grpc++_proto_reflection_desc_db:
proto_reflection_descriptor_database.cc
# grpc++_test_config:
diff --git a/contrib/libs/grpc/third_party/address_sorting/address_sorting.c b/contrib/libs/grpc/third_party/address_sorting/address_sorting.c
index 9aee0a5419..ade584c9e3 100644
--- a/contrib/libs/grpc/third_party/address_sorting/address_sorting.c
+++ b/contrib/libs/grpc/third_party/address_sorting/address_sorting.c
@@ -1,375 +1,375 @@
-/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
-/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/*
- * This is an adaptation of Android's implementation of RFC 6724
- * (in Android's getaddrinfo.c). It has some cosmetic differences
- * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
- * used as a guide or example of a way to implement the RFC 6724 spec when
- * this was written.
- */
-
-#include "address_sorting_internal.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-
-// Scope values increase with increase in scope.
-static const int kIPv6AddrScopeLinkLocal = 1;
-static const int kIPv6AddrScopeSiteLocal = 2;
-static const int kIPv6AddrScopeGlobal = 3;
-
-static address_sorting_source_addr_factory* g_current_source_addr_factory =
- NULL;
-
-static bool address_sorting_get_source_addr(const address_sorting_address* dest,
- address_sorting_address* source) {
- return g_current_source_addr_factory->vtable->get_source_addr(
- g_current_source_addr_factory, dest, source);
-}
-
-bool address_sorting_get_source_addr_for_testing(
- const address_sorting_address* dest, address_sorting_address* source) {
- return address_sorting_get_source_addr(dest, source);
-}
-
-static int ipv6_prefix_match_length(const struct sockaddr_in6* sa,
- const struct sockaddr_in6* sb) {
- unsigned char* a = (unsigned char*)&sa->sin6_addr;
- unsigned char* b = (unsigned char*)&sb->sin6_addr;
- int cur_bit = 0;
- while (cur_bit < 128) {
- int high_bit = 1 << (CHAR_BIT - 1);
- int a_val = a[cur_bit / CHAR_BIT] & (high_bit >> (cur_bit % CHAR_BIT));
- int b_val = b[cur_bit / CHAR_BIT] & (high_bit >> (cur_bit % CHAR_BIT));
- if (a_val == b_val) {
- cur_bit++;
- } else {
- break;
- }
- }
- return cur_bit;
-}
-
-static int in6_is_addr_loopback(const struct in6_addr* ipv6_address) {
- uint32_t* bits32 = (uint32_t*)ipv6_address;
- return bits32[0] == 0 && bits32[1] == 0 && bits32[2] == 0 &&
- bits32[3] == htonl(1);
-}
-
-static int in6_is_addr_v4mapped(const struct in6_addr* ipv6_address) {
- uint32_t* bits32 = (uint32_t*)ipv6_address;
- return bits32[0] == 0 && bits32[1] == 0 && bits32[2] == htonl(0x0000ffff);
-}
-
-static int in6_is_addr_v4compat(const struct in6_addr* ipv6_address) {
- uint32_t* bits32 = (uint32_t*)ipv6_address;
- return bits32[0] == 0 && bits32[1] == 0 && bits32[2] == 0 && bits32[3] != 0 &&
- bits32[3] != htonl(1);
-}
-
-static int in6_is_addr_sitelocal(const struct in6_addr* ipv6_address) {
- uint8_t* bytes = (uint8_t*)ipv6_address;
- return bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0xc0;
-}
-
-static int in6_is_addr_linklocal(const struct in6_addr* ipv6_address) {
- uint8_t* bytes = (uint8_t*)ipv6_address;
- return bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80;
-}
-
-static int in6_is_addr_6to4(const struct in6_addr* ipv6_address) {
- uint8_t* bytes = (uint8_t*)ipv6_address;
- return bytes[0] == 0x20 && bytes[1] == 0x02;
-}
-
-static int in6_is_addr_ula(const struct in6_addr* ipv6_address) {
- uint8_t* bytes = (uint8_t*)ipv6_address;
- return (bytes[0] & 0xfe) == 0xfc;
-}
-
-static int in6_is_addr_teredo(const struct in6_addr* ipv6_address) {
- uint8_t* bytes = (uint8_t*)ipv6_address;
- return bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x00 &&
- bytes[3] == 0x00;
-}
-
-static int in6_is_addr_6bone(const struct in6_addr* ipv6_address) {
- uint8_t* bytes = (uint8_t*)ipv6_address;
- return bytes[0] == 0x3f && bytes[1] == 0xfe;
-}
-
-address_sorting_family address_sorting_abstract_get_family(
- const address_sorting_address* address) {
- switch (((struct sockaddr*)address)->sa_family) {
- case AF_INET:
- return ADDRESS_SORTING_AF_INET;
- case AF_INET6:
- return ADDRESS_SORTING_AF_INET6;
- default:
- return ADDRESS_SORTING_UNKNOWN_FAMILY;
- }
-}
-
-static int get_label_value(const address_sorting_address* resolved_addr) {
- if (address_sorting_abstract_get_family(resolved_addr) ==
- ADDRESS_SORTING_AF_INET) {
- return 4;
- } else if (address_sorting_abstract_get_family(resolved_addr) !=
- ADDRESS_SORTING_AF_INET6) {
- return 1;
- }
- struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)&resolved_addr->addr;
- if (in6_is_addr_loopback(&ipv6_addr->sin6_addr)) {
- return 0;
- } else if (in6_is_addr_v4mapped(&ipv6_addr->sin6_addr)) {
- return 4;
- } else if (in6_is_addr_6to4(&ipv6_addr->sin6_addr)) {
- return 2;
- } else if (in6_is_addr_teredo(&ipv6_addr->sin6_addr)) {
- return 5;
- } else if (in6_is_addr_ula(&ipv6_addr->sin6_addr)) {
- return 13;
- } else if (in6_is_addr_v4compat(&ipv6_addr->sin6_addr)) {
- return 3;
- } else if (in6_is_addr_sitelocal(&ipv6_addr->sin6_addr)) {
- return 11;
- } else if (in6_is_addr_6bone(&ipv6_addr->sin6_addr)) {
- return 12;
- }
- return 1;
-}
-
-static int get_precedence_value(const address_sorting_address* resolved_addr) {
- if (address_sorting_abstract_get_family(resolved_addr) ==
- ADDRESS_SORTING_AF_INET) {
- return 35;
- } else if (address_sorting_abstract_get_family(resolved_addr) !=
- ADDRESS_SORTING_AF_INET6) {
- return 1;
- }
- struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)&resolved_addr->addr;
- if (in6_is_addr_loopback(&ipv6_addr->sin6_addr)) {
- return 50;
- } else if (in6_is_addr_v4mapped(&ipv6_addr->sin6_addr)) {
- return 35;
- } else if (in6_is_addr_6to4(&ipv6_addr->sin6_addr)) {
- return 30;
- } else if (in6_is_addr_teredo(&ipv6_addr->sin6_addr)) {
- return 5;
- } else if (in6_is_addr_ula(&ipv6_addr->sin6_addr)) {
- return 3;
- } else if (in6_is_addr_v4compat(&ipv6_addr->sin6_addr) ||
- in6_is_addr_sitelocal(&ipv6_addr->sin6_addr) ||
- in6_is_addr_6bone(&ipv6_addr->sin6_addr)) {
- return 1;
- }
- return 40;
-}
-
-static int sockaddr_get_scope(const address_sorting_address* resolved_addr) {
- if (address_sorting_abstract_get_family(resolved_addr) ==
- ADDRESS_SORTING_AF_INET) {
- return kIPv6AddrScopeGlobal;
- } else if (address_sorting_abstract_get_family(resolved_addr) ==
- ADDRESS_SORTING_AF_INET6) {
- struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)&resolved_addr->addr;
- if (in6_is_addr_loopback(&ipv6_addr->sin6_addr) ||
- in6_is_addr_linklocal(&ipv6_addr->sin6_addr)) {
- return kIPv6AddrScopeLinkLocal;
- }
- if (in6_is_addr_sitelocal(&ipv6_addr->sin6_addr)) {
- return kIPv6AddrScopeSiteLocal;
- }
- return kIPv6AddrScopeGlobal;
- }
- return 0;
-}
-
-static int compare_source_addr_exists(const address_sorting_sortable* first,
- const address_sorting_sortable* second) {
- if (first->source_addr_exists != second->source_addr_exists) {
- return first->source_addr_exists ? -1 : 1;
- }
- return 0;
-}
-
-static int compare_source_dest_scope_matches(
- const address_sorting_sortable* first,
- const address_sorting_sortable* second) {
- bool first_src_dst_scope_matches = false;
- if (sockaddr_get_scope(&first->dest_addr) ==
- sockaddr_get_scope(&first->source_addr)) {
- first_src_dst_scope_matches = true;
- }
- bool second_src_dst_scope_matches = false;
- if (sockaddr_get_scope(&second->dest_addr) ==
- sockaddr_get_scope(&second->source_addr)) {
- second_src_dst_scope_matches = true;
- }
- if (first_src_dst_scope_matches != second_src_dst_scope_matches) {
- return first_src_dst_scope_matches ? -1 : 1;
- }
- return 0;
-}
-
-static int compare_source_dest_labels_match(
- const address_sorting_sortable* first,
- const address_sorting_sortable* second) {
- bool first_label_matches = false;
- if (get_label_value(&first->dest_addr) ==
- get_label_value(&first->source_addr)) {
- first_label_matches = true;
- }
- bool second_label_matches = false;
- if (get_label_value(&second->dest_addr) ==
- get_label_value(&second->source_addr)) {
- second_label_matches = true;
- }
- if (first_label_matches != second_label_matches) {
- return first_label_matches ? -1 : 1;
- }
- return 0;
-}
-
-static int compare_dest_precedence(const address_sorting_sortable* first,
- const address_sorting_sortable* second) {
- return get_precedence_value(&second->dest_addr) -
- get_precedence_value(&first->dest_addr);
-}
-
-static int compare_dest_scope(const address_sorting_sortable* first,
- const address_sorting_sortable* second) {
- return sockaddr_get_scope(&first->dest_addr) -
- sockaddr_get_scope(&second->dest_addr);
-}
-
-static int compare_source_dest_prefix_match_lengths(
- const address_sorting_sortable* first,
- const address_sorting_sortable* second) {
- if (first->source_addr_exists &&
- address_sorting_abstract_get_family(&first->source_addr) ==
- ADDRESS_SORTING_AF_INET6 &&
- second->source_addr_exists &&
- address_sorting_abstract_get_family(&second->source_addr) ==
- ADDRESS_SORTING_AF_INET6) {
- int first_match_length =
- ipv6_prefix_match_length((struct sockaddr_in6*)&first->source_addr.addr,
- (struct sockaddr_in6*)&first->dest_addr.addr);
- int second_match_length = ipv6_prefix_match_length(
- (struct sockaddr_in6*)&second->source_addr.addr,
- (struct sockaddr_in6*)&second->dest_addr.addr);
- return second_match_length - first_match_length;
- }
- return 0;
-}
-
-static int rfc_6724_compare(const void* a, const void* b) {
- const address_sorting_sortable* first = (address_sorting_sortable*)a;
- const address_sorting_sortable* second = (address_sorting_sortable*)b;
- int out = 0;
- if ((out = compare_source_addr_exists(first, second))) {
- return out;
- }
- if ((out = compare_source_dest_scope_matches(first, second))) {
- return out;
- }
- if ((out = compare_source_dest_labels_match(first, second))) {
- return out;
- }
- // TODO: Implement rule 3; avoid deprecated addresses.
- // TODO: Implement rule 4; avoid temporary addresses.
- if ((out = compare_dest_precedence(first, second))) {
- return out;
- }
- // TODO: Implement rule 7; prefer native transports.
- if ((out = compare_dest_scope(first, second))) {
- return out;
- }
- if ((out = compare_source_dest_prefix_match_lengths(first, second))) {
- return out;
- }
- // Prefer that the sort be stable otherwise
- return (int)(first->original_index - second->original_index);
-}
-
-void address_sorting_override_source_addr_factory_for_testing(
- address_sorting_source_addr_factory* factory) {
- if (g_current_source_addr_factory == NULL) {
- abort();
- }
- g_current_source_addr_factory->vtable->destroy(g_current_source_addr_factory);
- g_current_source_addr_factory = factory;
-}
-
-static void sanity_check_private_fields_are_unused(
- const address_sorting_sortable* sortable) {
- address_sorting_address expected_source_addr;
- memset(&expected_source_addr, 0, sizeof(expected_source_addr));
- if (memcmp(&expected_source_addr, &sortable->source_addr,
- sizeof(address_sorting_address)) ||
- sortable->original_index || sortable->source_addr_exists) {
- abort();
- }
-}
-
-void address_sorting_rfc_6724_sort(address_sorting_sortable* sortables,
- size_t sortables_len) {
- for (size_t i = 0; i < sortables_len; i++) {
- sanity_check_private_fields_are_unused(&sortables[i]);
- sortables[i].original_index = i;
- sortables[i].source_addr_exists = address_sorting_get_source_addr(
- &sortables[i].dest_addr, &sortables[i].source_addr);
- }
- qsort(sortables, sortables_len, sizeof(address_sorting_sortable),
- rfc_6724_compare);
-}
-
-void address_sorting_init() {
- if (g_current_source_addr_factory != NULL) {
- abort();
- }
- g_current_source_addr_factory =
- address_sorting_create_source_addr_factory_for_current_platform();
-}
-
-void address_sorting_shutdown() {
- if (g_current_source_addr_factory == NULL) {
- abort();
- }
- g_current_source_addr_factory->vtable->destroy(g_current_source_addr_factory);
- g_current_source_addr_factory = NULL;
-}
+/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
+/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the project nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ * This is an adaptation of Android's implementation of RFC 6724
+ * (in Android's getaddrinfo.c). It has some cosmetic differences
+ * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
+ * used as a guide or example of a way to implement the RFC 6724 spec when
+ * this was written.
+ */
+
+#include "address_sorting_internal.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+
+// Scope values increase with increase in scope.
+static const int kIPv6AddrScopeLinkLocal = 1;
+static const int kIPv6AddrScopeSiteLocal = 2;
+static const int kIPv6AddrScopeGlobal = 3;
+
+static address_sorting_source_addr_factory* g_current_source_addr_factory =
+ NULL;
+
+static bool address_sorting_get_source_addr(const address_sorting_address* dest,
+ address_sorting_address* source) {
+ return g_current_source_addr_factory->vtable->get_source_addr(
+ g_current_source_addr_factory, dest, source);
+}
+
+bool address_sorting_get_source_addr_for_testing(
+ const address_sorting_address* dest, address_sorting_address* source) {
+ return address_sorting_get_source_addr(dest, source);
+}
+
+static int ipv6_prefix_match_length(const struct sockaddr_in6* sa,
+ const struct sockaddr_in6* sb) {
+ unsigned char* a = (unsigned char*)&sa->sin6_addr;
+ unsigned char* b = (unsigned char*)&sb->sin6_addr;
+ int cur_bit = 0;
+ while (cur_bit < 128) {
+ int high_bit = 1 << (CHAR_BIT - 1);
+ int a_val = a[cur_bit / CHAR_BIT] & (high_bit >> (cur_bit % CHAR_BIT));
+ int b_val = b[cur_bit / CHAR_BIT] & (high_bit >> (cur_bit % CHAR_BIT));
+ if (a_val == b_val) {
+ cur_bit++;
+ } else {
+ break;
+ }
+ }
+ return cur_bit;
+}
+
+static int in6_is_addr_loopback(const struct in6_addr* ipv6_address) {
+ uint32_t* bits32 = (uint32_t*)ipv6_address;
+ return bits32[0] == 0 && bits32[1] == 0 && bits32[2] == 0 &&
+ bits32[3] == htonl(1);
+}
+
+static int in6_is_addr_v4mapped(const struct in6_addr* ipv6_address) {
+ uint32_t* bits32 = (uint32_t*)ipv6_address;
+ return bits32[0] == 0 && bits32[1] == 0 && bits32[2] == htonl(0x0000ffff);
+}
+
+static int in6_is_addr_v4compat(const struct in6_addr* ipv6_address) {
+ uint32_t* bits32 = (uint32_t*)ipv6_address;
+ return bits32[0] == 0 && bits32[1] == 0 && bits32[2] == 0 && bits32[3] != 0 &&
+ bits32[3] != htonl(1);
+}
+
+static int in6_is_addr_sitelocal(const struct in6_addr* ipv6_address) {
+ uint8_t* bytes = (uint8_t*)ipv6_address;
+ return bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0xc0;
+}
+
+static int in6_is_addr_linklocal(const struct in6_addr* ipv6_address) {
+ uint8_t* bytes = (uint8_t*)ipv6_address;
+ return bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80;
+}
+
+static int in6_is_addr_6to4(const struct in6_addr* ipv6_address) {
+ uint8_t* bytes = (uint8_t*)ipv6_address;
+ return bytes[0] == 0x20 && bytes[1] == 0x02;
+}
+
+static int in6_is_addr_ula(const struct in6_addr* ipv6_address) {
+ uint8_t* bytes = (uint8_t*)ipv6_address;
+ return (bytes[0] & 0xfe) == 0xfc;
+}
+
+static int in6_is_addr_teredo(const struct in6_addr* ipv6_address) {
+ uint8_t* bytes = (uint8_t*)ipv6_address;
+ return bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x00 &&
+ bytes[3] == 0x00;
+}
+
+static int in6_is_addr_6bone(const struct in6_addr* ipv6_address) {
+ uint8_t* bytes = (uint8_t*)ipv6_address;
+ return bytes[0] == 0x3f && bytes[1] == 0xfe;
+}
+
+address_sorting_family address_sorting_abstract_get_family(
+ const address_sorting_address* address) {
+ switch (((struct sockaddr*)address)->sa_family) {
+ case AF_INET:
+ return ADDRESS_SORTING_AF_INET;
+ case AF_INET6:
+ return ADDRESS_SORTING_AF_INET6;
+ default:
+ return ADDRESS_SORTING_UNKNOWN_FAMILY;
+ }
+}
+
+static int get_label_value(const address_sorting_address* resolved_addr) {
+ if (address_sorting_abstract_get_family(resolved_addr) ==
+ ADDRESS_SORTING_AF_INET) {
+ return 4;
+ } else if (address_sorting_abstract_get_family(resolved_addr) !=
+ ADDRESS_SORTING_AF_INET6) {
+ return 1;
+ }
+ struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)&resolved_addr->addr;
+ if (in6_is_addr_loopback(&ipv6_addr->sin6_addr)) {
+ return 0;
+ } else if (in6_is_addr_v4mapped(&ipv6_addr->sin6_addr)) {
+ return 4;
+ } else if (in6_is_addr_6to4(&ipv6_addr->sin6_addr)) {
+ return 2;
+ } else if (in6_is_addr_teredo(&ipv6_addr->sin6_addr)) {
+ return 5;
+ } else if (in6_is_addr_ula(&ipv6_addr->sin6_addr)) {
+ return 13;
+ } else if (in6_is_addr_v4compat(&ipv6_addr->sin6_addr)) {
+ return 3;
+ } else if (in6_is_addr_sitelocal(&ipv6_addr->sin6_addr)) {
+ return 11;
+ } else if (in6_is_addr_6bone(&ipv6_addr->sin6_addr)) {
+ return 12;
+ }
+ return 1;
+}
+
+static int get_precedence_value(const address_sorting_address* resolved_addr) {
+ if (address_sorting_abstract_get_family(resolved_addr) ==
+ ADDRESS_SORTING_AF_INET) {
+ return 35;
+ } else if (address_sorting_abstract_get_family(resolved_addr) !=
+ ADDRESS_SORTING_AF_INET6) {
+ return 1;
+ }
+ struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)&resolved_addr->addr;
+ if (in6_is_addr_loopback(&ipv6_addr->sin6_addr)) {
+ return 50;
+ } else if (in6_is_addr_v4mapped(&ipv6_addr->sin6_addr)) {
+ return 35;
+ } else if (in6_is_addr_6to4(&ipv6_addr->sin6_addr)) {
+ return 30;
+ } else if (in6_is_addr_teredo(&ipv6_addr->sin6_addr)) {
+ return 5;
+ } else if (in6_is_addr_ula(&ipv6_addr->sin6_addr)) {
+ return 3;
+ } else if (in6_is_addr_v4compat(&ipv6_addr->sin6_addr) ||
+ in6_is_addr_sitelocal(&ipv6_addr->sin6_addr) ||
+ in6_is_addr_6bone(&ipv6_addr->sin6_addr)) {
+ return 1;
+ }
+ return 40;
+}
+
+static int sockaddr_get_scope(const address_sorting_address* resolved_addr) {
+ if (address_sorting_abstract_get_family(resolved_addr) ==
+ ADDRESS_SORTING_AF_INET) {
+ return kIPv6AddrScopeGlobal;
+ } else if (address_sorting_abstract_get_family(resolved_addr) ==
+ ADDRESS_SORTING_AF_INET6) {
+ struct sockaddr_in6* ipv6_addr = (struct sockaddr_in6*)&resolved_addr->addr;
+ if (in6_is_addr_loopback(&ipv6_addr->sin6_addr) ||
+ in6_is_addr_linklocal(&ipv6_addr->sin6_addr)) {
+ return kIPv6AddrScopeLinkLocal;
+ }
+ if (in6_is_addr_sitelocal(&ipv6_addr->sin6_addr)) {
+ return kIPv6AddrScopeSiteLocal;
+ }
+ return kIPv6AddrScopeGlobal;
+ }
+ return 0;
+}
+
+static int compare_source_addr_exists(const address_sorting_sortable* first,
+ const address_sorting_sortable* second) {
+ if (first->source_addr_exists != second->source_addr_exists) {
+ return first->source_addr_exists ? -1 : 1;
+ }
+ return 0;
+}
+
+static int compare_source_dest_scope_matches(
+ const address_sorting_sortable* first,
+ const address_sorting_sortable* second) {
+ bool first_src_dst_scope_matches = false;
+ if (sockaddr_get_scope(&first->dest_addr) ==
+ sockaddr_get_scope(&first->source_addr)) {
+ first_src_dst_scope_matches = true;
+ }
+ bool second_src_dst_scope_matches = false;
+ if (sockaddr_get_scope(&second->dest_addr) ==
+ sockaddr_get_scope(&second->source_addr)) {
+ second_src_dst_scope_matches = true;
+ }
+ if (first_src_dst_scope_matches != second_src_dst_scope_matches) {
+ return first_src_dst_scope_matches ? -1 : 1;
+ }
+ return 0;
+}
+
+static int compare_source_dest_labels_match(
+ const address_sorting_sortable* first,
+ const address_sorting_sortable* second) {
+ bool first_label_matches = false;
+ if (get_label_value(&first->dest_addr) ==
+ get_label_value(&first->source_addr)) {
+ first_label_matches = true;
+ }
+ bool second_label_matches = false;
+ if (get_label_value(&second->dest_addr) ==
+ get_label_value(&second->source_addr)) {
+ second_label_matches = true;
+ }
+ if (first_label_matches != second_label_matches) {
+ return first_label_matches ? -1 : 1;
+ }
+ return 0;
+}
+
+static int compare_dest_precedence(const address_sorting_sortable* first,
+ const address_sorting_sortable* second) {
+ return get_precedence_value(&second->dest_addr) -
+ get_precedence_value(&first->dest_addr);
+}
+
+static int compare_dest_scope(const address_sorting_sortable* first,
+ const address_sorting_sortable* second) {
+ return sockaddr_get_scope(&first->dest_addr) -
+ sockaddr_get_scope(&second->dest_addr);
+}
+
+static int compare_source_dest_prefix_match_lengths(
+ const address_sorting_sortable* first,
+ const address_sorting_sortable* second) {
+ if (first->source_addr_exists &&
+ address_sorting_abstract_get_family(&first->source_addr) ==
+ ADDRESS_SORTING_AF_INET6 &&
+ second->source_addr_exists &&
+ address_sorting_abstract_get_family(&second->source_addr) ==
+ ADDRESS_SORTING_AF_INET6) {
+ int first_match_length =
+ ipv6_prefix_match_length((struct sockaddr_in6*)&first->source_addr.addr,
+ (struct sockaddr_in6*)&first->dest_addr.addr);
+ int second_match_length = ipv6_prefix_match_length(
+ (struct sockaddr_in6*)&second->source_addr.addr,
+ (struct sockaddr_in6*)&second->dest_addr.addr);
+ return second_match_length - first_match_length;
+ }
+ return 0;
+}
+
+static int rfc_6724_compare(const void* a, const void* b) {
+ const address_sorting_sortable* first = (address_sorting_sortable*)a;
+ const address_sorting_sortable* second = (address_sorting_sortable*)b;
+ int out = 0;
+ if ((out = compare_source_addr_exists(first, second))) {
+ return out;
+ }
+ if ((out = compare_source_dest_scope_matches(first, second))) {
+ return out;
+ }
+ if ((out = compare_source_dest_labels_match(first, second))) {
+ return out;
+ }
+ // TODO: Implement rule 3; avoid deprecated addresses.
+ // TODO: Implement rule 4; avoid temporary addresses.
+ if ((out = compare_dest_precedence(first, second))) {
+ return out;
+ }
+ // TODO: Implement rule 7; prefer native transports.
+ if ((out = compare_dest_scope(first, second))) {
+ return out;
+ }
+ if ((out = compare_source_dest_prefix_match_lengths(first, second))) {
+ return out;
+ }
+ // Prefer that the sort be stable otherwise
+ return (int)(first->original_index - second->original_index);
+}
+
+void address_sorting_override_source_addr_factory_for_testing(
+ address_sorting_source_addr_factory* factory) {
+ if (g_current_source_addr_factory == NULL) {
+ abort();
+ }
+ g_current_source_addr_factory->vtable->destroy(g_current_source_addr_factory);
+ g_current_source_addr_factory = factory;
+}
+
+static void sanity_check_private_fields_are_unused(
+ const address_sorting_sortable* sortable) {
+ address_sorting_address expected_source_addr;
+ memset(&expected_source_addr, 0, sizeof(expected_source_addr));
+ if (memcmp(&expected_source_addr, &sortable->source_addr,
+ sizeof(address_sorting_address)) ||
+ sortable->original_index || sortable->source_addr_exists) {
+ abort();
+ }
+}
+
+void address_sorting_rfc_6724_sort(address_sorting_sortable* sortables,
+ size_t sortables_len) {
+ for (size_t i = 0; i < sortables_len; i++) {
+ sanity_check_private_fields_are_unused(&sortables[i]);
+ sortables[i].original_index = i;
+ sortables[i].source_addr_exists = address_sorting_get_source_addr(
+ &sortables[i].dest_addr, &sortables[i].source_addr);
+ }
+ qsort(sortables, sortables_len, sizeof(address_sorting_sortable),
+ rfc_6724_compare);
+}
+
+void address_sorting_init() {
+ if (g_current_source_addr_factory != NULL) {
+ abort();
+ }
+ g_current_source_addr_factory =
+ address_sorting_create_source_addr_factory_for_current_platform();
+}
+
+void address_sorting_shutdown() {
+ if (g_current_source_addr_factory == NULL) {
+ abort();
+ }
+ g_current_source_addr_factory->vtable->destroy(g_current_source_addr_factory);
+ g_current_source_addr_factory = NULL;
+}
diff --git a/contrib/libs/grpc/third_party/address_sorting/address_sorting_internal.h b/contrib/libs/grpc/third_party/address_sorting/address_sorting_internal.h
index be59d44fee..1235c30d73 100644
--- a/contrib/libs/grpc/third_party/address_sorting/address_sorting_internal.h
+++ b/contrib/libs/grpc/third_party/address_sorting/address_sorting_internal.h
@@ -1,70 +1,70 @@
-/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
-/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/*
- * This is an adaptation of Android's implementation of RFC 6724
- * (in Android's getaddrinfo.c). It has some cosmetic differences
- * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
- * used as a guide or example of a way to implement the RFC 6724 spec when
- * this was written.
- */
-
-#ifndef ADDRESS_SORTING_INTERNAL_H
-#define ADDRESS_SORTING_INTERNAL_H
-
-#if defined(_WIN64) || defined(WIN64) || defined(_WIN32) || defined(WIN32)
-#include <winsock2.h>
-#include <ws2tcpip.h>
-// comment to prevent formatter from moving mswock.h upwards
-#include <mswsock.h>
-#define ADDRESS_SORTING_WINDOWS 1
-#else
-/* Workaround for issue described in
- *
- * https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/1187301 */
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-#include <arpa/inet.h>
-#include <netinet/in.h>
-#include <sys/socket.h>
-#define ADDRESS_SORTING_POSIX 1
-#endif
-
-#include <stdbool.h>
-
-#include <address_sorting/address_sorting.h>
-
-address_sorting_source_addr_factory*
-address_sorting_create_source_addr_factory_for_current_platform();
-
-#endif // ADDRESS_SORTING_INTERNAL_H
+/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
+/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the project nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ * This is an adaptation of Android's implementation of RFC 6724
+ * (in Android's getaddrinfo.c). It has some cosmetic differences
+ * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
+ * used as a guide or example of a way to implement the RFC 6724 spec when
+ * this was written.
+ */
+
+#ifndef ADDRESS_SORTING_INTERNAL_H
+#define ADDRESS_SORTING_INTERNAL_H
+
+#if defined(_WIN64) || defined(WIN64) || defined(_WIN32) || defined(WIN32)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+// comment to prevent formatter from moving mswock.h upwards
+#include <mswsock.h>
+#define ADDRESS_SORTING_WINDOWS 1
+#else
+/* Workaround for issue described in
+ *
+ * https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/1187301 */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#define ADDRESS_SORTING_POSIX 1
+#endif
+
+#include <stdbool.h>
+
+#include <address_sorting/address_sorting.h>
+
+address_sorting_source_addr_factory*
+address_sorting_create_source_addr_factory_for_current_platform();
+
+#endif // ADDRESS_SORTING_INTERNAL_H
diff --git a/contrib/libs/grpc/third_party/address_sorting/address_sorting_posix.c b/contrib/libs/grpc/third_party/address_sorting/address_sorting_posix.c
index d0dfe12469..f447dc949a 100644
--- a/contrib/libs/grpc/third_party/address_sorting/address_sorting_posix.c
+++ b/contrib/libs/grpc/third_party/address_sorting/address_sorting_posix.c
@@ -1,97 +1,97 @@
-/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
-/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/*
- * This is an adaptation of Android's implementation of RFC 6724
- * (in Android's getaddrinfo.c). It has some cosmetic differences
- * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
- * used as a guide or example of a way to implement the RFC 6724 spec when
- * this was written.
- */
-
-#include "address_sorting_internal.h"
-
-#if defined(ADDRESS_SORTING_POSIX)
-
-#include <errno.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-static bool posix_source_addr_factory_get_source_addr(
- address_sorting_source_addr_factory* factory,
- const address_sorting_address* dest_addr,
- address_sorting_address* source_addr) {
- bool source_addr_exists = false;
- // Android sets SOCK_CLOEXEC. Don't set this here for portability.
- int s = socket(((struct sockaddr*)dest_addr)->sa_family, SOCK_DGRAM, 0);
- if (s != -1) {
- if (connect(s, (const struct sockaddr*)&dest_addr->addr,
- (socklen_t)dest_addr->len) != -1) {
- address_sorting_address found_source_addr;
- memset(&found_source_addr, 0, sizeof(found_source_addr));
- found_source_addr.len = sizeof(found_source_addr.addr);
- if (getsockname(s, (struct sockaddr*)&found_source_addr.addr,
- (socklen_t*)&found_source_addr.len) != -1) {
- source_addr_exists = true;
- *source_addr = found_source_addr;
- }
- }
- }
- close(s);
- return source_addr_exists;
-}
-
-static void posix_source_addr_factory_destroy(
- address_sorting_source_addr_factory* self) {
- free(self);
-}
-
-static const address_sorting_source_addr_factory_vtable
- posix_source_addr_factory_vtable = {
- posix_source_addr_factory_get_source_addr,
- posix_source_addr_factory_destroy,
-};
-
-address_sorting_source_addr_factory*
-address_sorting_create_source_addr_factory_for_current_platform() {
- address_sorting_source_addr_factory* factory =
- malloc(sizeof(address_sorting_source_addr_factory));
- memset(factory, 0, sizeof(address_sorting_source_addr_factory));
- factory->vtable = &posix_source_addr_factory_vtable;
- return factory;
-}
-
-#endif // defined(ADDRESS_SORTING_POSIX)
+/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
+/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the project nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ * This is an adaptation of Android's implementation of RFC 6724
+ * (in Android's getaddrinfo.c). It has some cosmetic differences
+ * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
+ * used as a guide or example of a way to implement the RFC 6724 spec when
+ * this was written.
+ */
+
+#include "address_sorting_internal.h"
+
+#if defined(ADDRESS_SORTING_POSIX)
+
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+static bool posix_source_addr_factory_get_source_addr(
+ address_sorting_source_addr_factory* factory,
+ const address_sorting_address* dest_addr,
+ address_sorting_address* source_addr) {
+ bool source_addr_exists = false;
+ // Android sets SOCK_CLOEXEC. Don't set this here for portability.
+ int s = socket(((struct sockaddr*)dest_addr)->sa_family, SOCK_DGRAM, 0);
+ if (s != -1) {
+ if (connect(s, (const struct sockaddr*)&dest_addr->addr,
+ (socklen_t)dest_addr->len) != -1) {
+ address_sorting_address found_source_addr;
+ memset(&found_source_addr, 0, sizeof(found_source_addr));
+ found_source_addr.len = sizeof(found_source_addr.addr);
+ if (getsockname(s, (struct sockaddr*)&found_source_addr.addr,
+ (socklen_t*)&found_source_addr.len) != -1) {
+ source_addr_exists = true;
+ *source_addr = found_source_addr;
+ }
+ }
+ }
+ close(s);
+ return source_addr_exists;
+}
+
+static void posix_source_addr_factory_destroy(
+ address_sorting_source_addr_factory* self) {
+ free(self);
+}
+
+static const address_sorting_source_addr_factory_vtable
+ posix_source_addr_factory_vtable = {
+ posix_source_addr_factory_get_source_addr,
+ posix_source_addr_factory_destroy,
+};
+
+address_sorting_source_addr_factory*
+address_sorting_create_source_addr_factory_for_current_platform() {
+ address_sorting_source_addr_factory* factory =
+ malloc(sizeof(address_sorting_source_addr_factory));
+ memset(factory, 0, sizeof(address_sorting_source_addr_factory));
+ factory->vtable = &posix_source_addr_factory_vtable;
+ return factory;
+}
+
+#endif // defined(ADDRESS_SORTING_POSIX)
diff --git a/contrib/libs/grpc/third_party/address_sorting/address_sorting_windows.c b/contrib/libs/grpc/third_party/address_sorting/address_sorting_windows.c
index 662a88248e..1f960173a3 100644
--- a/contrib/libs/grpc/third_party/address_sorting/address_sorting_windows.c
+++ b/contrib/libs/grpc/third_party/address_sorting/address_sorting_windows.c
@@ -1,95 +1,95 @@
-/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
-/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/*
- * This is an adaptation of Android's implementation of RFC 6724
- * (in Android's getaddrinfo.c). It has some cosmetic differences
- * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
- * used as a guide or example of a way to implement the RFC 6724 spec when
- * this was written.
- */
-
-#include "address_sorting_internal.h"
-
-#if defined(ADDRESS_SORTING_WINDOWS)
-
-#include <errno.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-
-static bool windows_source_addr_factory_get_source_addr(
- address_sorting_source_addr_factory* factory,
- const address_sorting_address* dest_addr,
- address_sorting_address* source_addr) {
- bool source_addr_exists = false;
- SOCKET s = socket(((struct sockaddr_in6*)dest_addr)->sin6_family, SOCK_DGRAM,
- IPPROTO_UDP);
- if (s != INVALID_SOCKET) {
- if (connect(s, (struct sockaddr*)dest_addr, (int)dest_addr->len) == 0) {
- address_sorting_address found_source_addr;
- memset(&found_source_addr, 0, sizeof(found_source_addr));
- found_source_addr.len = sizeof(found_source_addr.addr);
- if (getsockname(s, (struct sockaddr*)&found_source_addr.addr,
- (socklen_t*)&found_source_addr.len) == 0) {
- source_addr_exists = true;
- *source_addr = found_source_addr;
- }
- }
- closesocket(s);
- }
- return source_addr_exists;
-}
-
-static void windows_source_addr_factory_destroy(
- address_sorting_source_addr_factory* self) {
- free(self);
-}
-
-static const address_sorting_source_addr_factory_vtable
- windows_source_addr_factory_vtable = {
- windows_source_addr_factory_get_source_addr,
- windows_source_addr_factory_destroy,
-};
-
-address_sorting_source_addr_factory*
-address_sorting_create_source_addr_factory_for_current_platform() {
- address_sorting_source_addr_factory* factory =
- malloc(sizeof(address_sorting_source_addr_factory));
- memset(factory, 0, sizeof(address_sorting_source_addr_factory));
- factory->vtable = &windows_source_addr_factory_vtable;
- return factory;
-}
-
-#endif // defined(ADDRESS_SORTING_WINDOWS)
+/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
+/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the project nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ * This is an adaptation of Android's implementation of RFC 6724
+ * (in Android's getaddrinfo.c). It has some cosmetic differences
+ * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
+ * used as a guide or example of a way to implement the RFC 6724 spec when
+ * this was written.
+ */
+
+#include "address_sorting_internal.h"
+
+#if defined(ADDRESS_SORTING_WINDOWS)
+
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+
+static bool windows_source_addr_factory_get_source_addr(
+ address_sorting_source_addr_factory* factory,
+ const address_sorting_address* dest_addr,
+ address_sorting_address* source_addr) {
+ bool source_addr_exists = false;
+ SOCKET s = socket(((struct sockaddr_in6*)dest_addr)->sin6_family, SOCK_DGRAM,
+ IPPROTO_UDP);
+ if (s != INVALID_SOCKET) {
+ if (connect(s, (struct sockaddr*)dest_addr, (int)dest_addr->len) == 0) {
+ address_sorting_address found_source_addr;
+ memset(&found_source_addr, 0, sizeof(found_source_addr));
+ found_source_addr.len = sizeof(found_source_addr.addr);
+ if (getsockname(s, (struct sockaddr*)&found_source_addr.addr,
+ (socklen_t*)&found_source_addr.len) == 0) {
+ source_addr_exists = true;
+ *source_addr = found_source_addr;
+ }
+ }
+ closesocket(s);
+ }
+ return source_addr_exists;
+}
+
+static void windows_source_addr_factory_destroy(
+ address_sorting_source_addr_factory* self) {
+ free(self);
+}
+
+static const address_sorting_source_addr_factory_vtable
+ windows_source_addr_factory_vtable = {
+ windows_source_addr_factory_get_source_addr,
+ windows_source_addr_factory_destroy,
+};
+
+address_sorting_source_addr_factory*
+address_sorting_create_source_addr_factory_for_current_platform() {
+ address_sorting_source_addr_factory* factory =
+ malloc(sizeof(address_sorting_source_addr_factory));
+ memset(factory, 0, sizeof(address_sorting_source_addr_factory));
+ factory->vtable = &windows_source_addr_factory_vtable;
+ return factory;
+}
+
+#endif // defined(ADDRESS_SORTING_WINDOWS)
diff --git a/contrib/libs/grpc/third_party/address_sorting/include/address_sorting/address_sorting.h b/contrib/libs/grpc/third_party/address_sorting/include/address_sorting/address_sorting.h
index c58fafe3f7..2931da0adb 100644
--- a/contrib/libs/grpc/third_party/address_sorting/include/address_sorting/address_sorting.h
+++ b/contrib/libs/grpc/third_party/address_sorting/include/address_sorting/address_sorting.h
@@ -1,113 +1,113 @@
-/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
-/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
-/*
- * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- */
-
-/*
- * This is an adaptation of Android's implementation of RFC 6724
- * (in Android's getaddrinfo.c). It has some cosmetic differences
- * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
- * used as a guide or example of a way to implement the RFC 6724 spec when
- * this was written.
- */
-
-#ifndef ADDRESS_SORTING_H
-#define ADDRESS_SORTING_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct address_sorting_address {
- char addr[128];
- size_t len;
-} address_sorting_address;
-
-/* address_sorting_sortable represents one entry in a list of destination
- * IP addresses to sort. It contains the destination IP address
- * "sorting key", along with placeholder and scratch fields. */
-typedef struct address_sorting_sortable {
- // input data; sorting key
- address_sorting_address dest_addr;
- // input data; optional value to attach to the sorting key
- void* user_data;
- // internal fields, these must be zero'd when passed to sort function
- address_sorting_address source_addr;
- bool source_addr_exists;
- size_t original_index;
-} address_sorting_sortable;
-
-void address_sorting_rfc_6724_sort(address_sorting_sortable* sortables,
- size_t sortables_len);
-
-void address_sorting_init();
-void address_sorting_shutdown();
-
-struct address_sorting_source_addr_factory;
-
-/* The interfaces below are exposed only for testing */
-typedef struct {
- /* Gets the source address that would be used for the passed-in destination
- * address, and fills in *source_addr* with it if one exists.
- * Returns true if a source address exists for the destination address,
- * and false otherwise. */
- bool (*get_source_addr)(struct address_sorting_source_addr_factory* factory,
- const address_sorting_address* dest_addr,
- address_sorting_address* source_addr);
- void (*destroy)(struct address_sorting_source_addr_factory* factory);
-} address_sorting_source_addr_factory_vtable;
-
-typedef struct address_sorting_source_addr_factory {
- const address_sorting_source_addr_factory_vtable* vtable;
-} address_sorting_source_addr_factory;
-
-/* Platform-compatible address family types */
-typedef enum {
- ADDRESS_SORTING_AF_INET,
- ADDRESS_SORTING_AF_INET6,
- ADDRESS_SORTING_UNKNOWN_FAMILY,
-} address_sorting_family;
-
-/* Indicates whether the address is AF_INET, AF_INET6, or another address
- * family. */
-address_sorting_family address_sorting_abstract_get_family(
- const address_sorting_address* address);
-
-void address_sorting_override_source_addr_factory_for_testing(
- address_sorting_source_addr_factory* factory);
-
-bool address_sorting_get_source_addr_for_testing(
- const address_sorting_address* dest, address_sorting_address* source);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // ADDRESS_SORTING_H
+/* $NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $ */
+/* $KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $ */
+/*
+ * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the project nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ * This is an adaptation of Android's implementation of RFC 6724
+ * (in Android's getaddrinfo.c). It has some cosmetic differences
+ * from Android's getaddrinfo.c, but Android's getaddrinfo.c was
+ * used as a guide or example of a way to implement the RFC 6724 spec when
+ * this was written.
+ */
+
+#ifndef ADDRESS_SORTING_H
+#define ADDRESS_SORTING_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct address_sorting_address {
+ char addr[128];
+ size_t len;
+} address_sorting_address;
+
+/* address_sorting_sortable represents one entry in a list of destination
+ * IP addresses to sort. It contains the destination IP address
+ * "sorting key", along with placeholder and scratch fields. */
+typedef struct address_sorting_sortable {
+ // input data; sorting key
+ address_sorting_address dest_addr;
+ // input data; optional value to attach to the sorting key
+ void* user_data;
+ // internal fields, these must be zero'd when passed to sort function
+ address_sorting_address source_addr;
+ bool source_addr_exists;
+ size_t original_index;
+} address_sorting_sortable;
+
+void address_sorting_rfc_6724_sort(address_sorting_sortable* sortables,
+ size_t sortables_len);
+
+void address_sorting_init();
+void address_sorting_shutdown();
+
+struct address_sorting_source_addr_factory;
+
+/* The interfaces below are exposed only for testing */
+typedef struct {
+ /* Gets the source address that would be used for the passed-in destination
+ * address, and fills in *source_addr* with it if one exists.
+ * Returns true if a source address exists for the destination address,
+ * and false otherwise. */
+ bool (*get_source_addr)(struct address_sorting_source_addr_factory* factory,
+ const address_sorting_address* dest_addr,
+ address_sorting_address* source_addr);
+ void (*destroy)(struct address_sorting_source_addr_factory* factory);
+} address_sorting_source_addr_factory_vtable;
+
+typedef struct address_sorting_source_addr_factory {
+ const address_sorting_source_addr_factory_vtable* vtable;
+} address_sorting_source_addr_factory;
+
+/* Platform-compatible address family types */
+typedef enum {
+ ADDRESS_SORTING_AF_INET,
+ ADDRESS_SORTING_AF_INET6,
+ ADDRESS_SORTING_UNKNOWN_FAMILY,
+} address_sorting_family;
+
+/* Indicates whether the address is AF_INET, AF_INET6, or another address
+ * family. */
+address_sorting_family address_sorting_abstract_get_family(
+ const address_sorting_address* address);
+
+void address_sorting_override_source_addr_factory_for_testing(
+ address_sorting_source_addr_factory* factory);
+
+bool address_sorting_get_source_addr_for_testing(
+ const address_sorting_address* dest, address_sorting_address* source);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ADDRESS_SORTING_H
diff --git a/contrib/libs/grpc/third_party/address_sorting/ya.make b/contrib/libs/grpc/third_party/address_sorting/ya.make
index 66919eb97a..f48b8d3f9a 100644
--- a/contrib/libs/grpc/third_party/address_sorting/ya.make
+++ b/contrib/libs/grpc/third_party/address_sorting/ya.make
@@ -1,33 +1,33 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
OWNER(g:cpp-contrib)
-
+
LICENSE(BSD-3-Clause)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-ADDINCL(
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/third_party/address_sorting/include
-)
-
-NO_COMPILER_WARNINGS()
-
+ contrib/libs/grpc
+ contrib/libs/grpc/third_party/address_sorting/include
+)
+
+NO_COMPILER_WARNINGS()
+
NO_RUNTIME()
-IF (OS_LINUX OR OS_DARWIN)
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- address_sorting.c
- address_sorting_posix.c
- address_sorting_windows.c
-)
-
-END()
+ENDIF()
+
+SRCS(
+ address_sorting.c
+ address_sorting_posix.c
+ address_sorting_windows.c
+)
+
+END()
diff --git a/contrib/libs/grpc/third_party/upb/README.md b/contrib/libs/grpc/third_party/upb/README.md
index a08aa0e909..b7379a3bf7 100644
--- a/contrib/libs/grpc/third_party/upb/README.md
+++ b/contrib/libs/grpc/third_party/upb/README.md
@@ -1,134 +1,134 @@
-
-# μpb - a small protobuf implementation in C
-
-|Platform|Build Status|
-|--------|------------|
-|macOS|[![Build Status](https://storage.googleapis.com/upb-kokoro-results/status-badge/macos.png)](https://fusion.corp.google.com/projectanalysis/summary/KOKORO/prod%3Aupb%2Fmacos%2Fcontinuous)|
-|ubuntu|[![Build Status](https://storage.googleapis.com/upb-kokoro-results/status-badge/ubuntu.png)](https://fusion.corp.google.com/projectanalysis/summary/KOKORO/prod%3Aupb%2Fubuntu%2Fcontinuous)|
-
-μpb (often written 'upb') is a small protobuf implementation written in C.
-
-upb generates a C API for creating, parsing, and serializing messages
-as declared in `.proto` files. upb is heavily arena-based: all
-messages always live in an arena (note: the arena can live in stack or
-static memory if desired). Here is a simple example:
-
-```c
-#include "conformance/conformance.upb.h"
-
-void foo(const char* data, size_t size) {
- upb_arena *arena;
-
- /* Generated message type. */
- conformance_ConformanceRequest *request;
- conformance_ConformanceResponse *response;
-
- arena = upb_arena_new();
- request = conformance_ConformanceRequest_parse(data, size, arena);
- response = conformance_ConformanceResponse_new(arena);
-
- switch (conformance_ConformanceRequest_payload_case(request)) {
- case conformance_ConformanceRequest_payload_protobuf_payload: {
- upb_strview payload = conformance_ConformanceRequest_protobuf_payload(request);
- // ...
- break;
- }
-
- case conformance_ConformanceRequest_payload_NOT_SET:
- fprintf(stderr, "conformance_upb: Request didn't have payload.\n");
- break;
-
- default: {
- static const char msg[] = "Unsupported input format.";
- conformance_ConformanceResponse_set_skipped(
- response, upb_strview_make(msg, sizeof(msg)));
- break;
- }
- }
-
- /* Frees all messages on the arena. */
- upb_arena_free(arena);
-}
-```
-
-API and ABI are both subject to change! Please do not distribute
-as a shared library for this reason (for now at least).
-
-## Using upb in your project
-
-Currently only Bazel is supported (CMake support is partial and incomplete
-but full CMake support is an eventual goal).
-
-To use upb in your Bazel project, first add upb to your `WORKSPACE` file,
-either as a `git_repository()` or as a `new_local_repository()` with a
-Git Submodule. (For an example, see `examples/bazel/ in this repo).
-
-```python
-# Add this to your WORKSPACE file.
-load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
-
-git_repository(
- name = "upb",
- remote = "https://github.com/protocolbuffers/upb.git",
- commit = "d16bf99ac4658793748cda3251226059892b3b7b",
-)
-
-load("@upb//bazel:workspace_deps.bzl", "upb_deps")
-
-upb_deps()
-```
-
-Then in your BUILD file you can add `upb_proto_library()` rules that
-generate code for a corresponding `proto_library()` rule. For
-example:
-
-```python
-# Add this to your BUILD file.
-load("@upb//bazel:upb_proto_library.bzl", "upb_proto_library")
-
-proto_library(
- name = "foo_proto",
- srcs = ["foo.proto"],
-)
-
-upb_proto_library(
- name = "foo_upbproto",
- deps = [":foo_proto"],
-)
-
-cc_binary(
- name = "test_binary",
- srcs = ["test_binary.c"],
- deps = [":foo_upbproto"],
-)
-```
-
-Then in your `.c` file you can #include the generated header:
-
-```c
-#include "foo.upb.h"
-
-/* Insert code that uses generated types. */
-```
-
-## Old "handlers" interfaces
-
-This library contains several semi-deprecated interfaces (see BUILD
-file for more info about which interfaces are deprecated). These
-deprecated interfaces are still used in some significant projects,
-such as the Ruby and PHP C bindings for protobuf in the [main protobuf
-repo](https://github.com/protocolbuffers/protobuf). The goal is to
-migrate the Ruby/PHP bindings to use the newer, simpler interfaces
-instead. Please do not use the old interfaces in new code.
-
-## Lua bindings
-
-This repo has some Lua bindings for the core library. These are
-experimental and very incomplete. These are currently included in
-order to validate that the C API is suitable for wrapping. As the
-project matures these Lua bindings may become publicly available.
-
-## Contact
-
-Author: Josh Haberman ([jhaberman@gmail.com](mailto:jhaberman@gmail.com),
-[haberman@google.com](mailto:haberman@google.com))
+
+# μpb - a small protobuf implementation in C
+
+|Platform|Build Status|
+|--------|------------|
+|macOS|[![Build Status](https://storage.googleapis.com/upb-kokoro-results/status-badge/macos.png)](https://fusion.corp.google.com/projectanalysis/summary/KOKORO/prod%3Aupb%2Fmacos%2Fcontinuous)|
+|ubuntu|[![Build Status](https://storage.googleapis.com/upb-kokoro-results/status-badge/ubuntu.png)](https://fusion.corp.google.com/projectanalysis/summary/KOKORO/prod%3Aupb%2Fubuntu%2Fcontinuous)|
+
+μpb (often written 'upb') is a small protobuf implementation written in C.
+
+upb generates a C API for creating, parsing, and serializing messages
+as declared in `.proto` files. upb is heavily arena-based: all
+messages always live in an arena (note: the arena can live in stack or
+static memory if desired). Here is a simple example:
+
+```c
+#include "conformance/conformance.upb.h"
+
+void foo(const char* data, size_t size) {
+ upb_arena *arena;
+
+ /* Generated message type. */
+ conformance_ConformanceRequest *request;
+ conformance_ConformanceResponse *response;
+
+ arena = upb_arena_new();
+ request = conformance_ConformanceRequest_parse(data, size, arena);
+ response = conformance_ConformanceResponse_new(arena);
+
+ switch (conformance_ConformanceRequest_payload_case(request)) {
+ case conformance_ConformanceRequest_payload_protobuf_payload: {
+ upb_strview payload = conformance_ConformanceRequest_protobuf_payload(request);
+ // ...
+ break;
+ }
+
+ case conformance_ConformanceRequest_payload_NOT_SET:
+ fprintf(stderr, "conformance_upb: Request didn't have payload.\n");
+ break;
+
+ default: {
+ static const char msg[] = "Unsupported input format.";
+ conformance_ConformanceResponse_set_skipped(
+ response, upb_strview_make(msg, sizeof(msg)));
+ break;
+ }
+ }
+
+ /* Frees all messages on the arena. */
+ upb_arena_free(arena);
+}
+```
+
+API and ABI are both subject to change! Please do not distribute
+as a shared library for this reason (for now at least).
+
+## Using upb in your project
+
+Currently only Bazel is supported (CMake support is partial and incomplete
+but full CMake support is an eventual goal).
+
+To use upb in your Bazel project, first add upb to your `WORKSPACE` file,
+either as a `git_repository()` or as a `new_local_repository()` with a
+Git Submodule. (For an example, see `examples/bazel/ in this repo).
+
+```python
+# Add this to your WORKSPACE file.
+load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
+
+git_repository(
+ name = "upb",
+ remote = "https://github.com/protocolbuffers/upb.git",
+ commit = "d16bf99ac4658793748cda3251226059892b3b7b",
+)
+
+load("@upb//bazel:workspace_deps.bzl", "upb_deps")
+
+upb_deps()
+```
+
+Then in your BUILD file you can add `upb_proto_library()` rules that
+generate code for a corresponding `proto_library()` rule. For
+example:
+
+```python
+# Add this to your BUILD file.
+load("@upb//bazel:upb_proto_library.bzl", "upb_proto_library")
+
+proto_library(
+ name = "foo_proto",
+ srcs = ["foo.proto"],
+)
+
+upb_proto_library(
+ name = "foo_upbproto",
+ deps = [":foo_proto"],
+)
+
+cc_binary(
+ name = "test_binary",
+ srcs = ["test_binary.c"],
+ deps = [":foo_upbproto"],
+)
+```
+
+Then in your `.c` file you can #include the generated header:
+
+```c
+#include "foo.upb.h"
+
+/* Insert code that uses generated types. */
+```
+
+## Old "handlers" interfaces
+
+This library contains several semi-deprecated interfaces (see BUILD
+file for more info about which interfaces are deprecated). These
+deprecated interfaces are still used in some significant projects,
+such as the Ruby and PHP C bindings for protobuf in the [main protobuf
+repo](https://github.com/protocolbuffers/protobuf). The goal is to
+migrate the Ruby/PHP bindings to use the newer, simpler interfaces
+instead. Please do not use the old interfaces in new code.
+
+## Lua bindings
+
+This repo has some Lua bindings for the core library. These are
+experimental and very incomplete. These are currently included in
+order to validate that the C API is suitable for wrapping. As the
+project matures these Lua bindings may become publicly available.
+
+## Contact
+
+Author: Josh Haberman ([jhaberman@gmail.com](mailto:jhaberman@gmail.com),
+[haberman@google.com](mailto:haberman@google.com))
diff --git a/contrib/libs/grpc/third_party/upb/upb/decode.c b/contrib/libs/grpc/third_party/upb/upb/decode.c
index a9f1cf548a..39e333ae26 100644
--- a/contrib/libs/grpc/third_party/upb/upb/decode.c
+++ b/contrib/libs/grpc/third_party/upb/upb/decode.c
@@ -1,13 +1,13 @@
-
+
#include <setjmp.h>
-#include <string.h>
+#include <string.h>
#include "upb/decode.h"
-#include "upb/upb.h"
-
-#include "upb/port_def.inc"
-
-/* Maps descriptor type -> upb field type. */
+#include "upb/upb.h"
+
+#include "upb/port_def.inc"
+
+/* Maps descriptor type -> upb field type. */
static const uint8_t desctype_to_fieldtype[] = {
-1, /* invalid descriptor type */
UPB_TYPE_DOUBLE, /* DOUBLE */
@@ -28,8 +28,8 @@ static const uint8_t desctype_to_fieldtype[] = {
UPB_TYPE_INT64, /* SFIXED64 */
UPB_TYPE_INT32, /* SINT32 */
UPB_TYPE_INT64, /* SINT64 */
-};
-
+};
+
/* Maps descriptor type -> upb map size. */
static const uint8_t desctype_to_mapsize[] = {
-1, /* invalid descriptor type */
@@ -52,15 +52,15 @@ static const uint8_t desctype_to_mapsize[] = {
4, /* SINT32 */
8, /* SINT64 */
};
-
+
static const unsigned fixed32_ok = (1 << UPB_DTYPE_FLOAT) |
(1 << UPB_DTYPE_FIXED32) |
(1 << UPB_DTYPE_SFIXED32);
-
+
static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
(1 << UPB_DTYPE_FIXED64) |
(1 << UPB_DTYPE_SFIXED64);
-
+
/* Op: an action to be performed for a wire-type/field-type combination. */
#define OP_SCALAR_LG2(n) (n) /* n in [0, 2, 3] => op in [0, 2, 3] */
#define OP_STRING 4
@@ -69,7 +69,7 @@ static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
/* Ops above are scalar-only. Repeated fields can use any op. */
#define OP_FIXPCK_LG2(n) (n + 5) /* n in [2, 3] => op in [7, 8] */
#define OP_VARPCK_LG2(n) (n + 9) /* n in [0, 2, 3] => op in [9, 11, 12] */
-
+
static const int8_t varint_ops[19] = {
-1, /* field not found */
-1, /* DOUBLE */
@@ -91,7 +91,7 @@ static const int8_t varint_ops[19] = {
OP_SCALAR_LG2(2), /* SINT32 */
OP_SCALAR_LG2(3), /* SINT64 */
};
-
+
static const int8_t delim_ops[37] = {
/* For non-repeated field type. */
-1, /* field not found */
@@ -133,7 +133,7 @@ static const int8_t delim_ops[37] = {
OP_VARPCK_LG2(2), /* REPEATED SINT32 */
OP_VARPCK_LG2(3), /* REPEATED SINT64 */
};
-
+
/* Data pertaining to the parse. */
typedef struct {
const char *limit; /* End of delimited region or end of buffer. */
@@ -142,19 +142,19 @@ typedef struct {
uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
jmp_buf err;
} upb_decstate;
-
+
typedef union {
bool bool_val;
uint32_t uint32_val;
uint64_t uint64_val;
upb_strview str_val;
} wireval;
-
+
static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
const upb_msglayout *layout);
-
+
UPB_NORETURN static void decode_err(upb_decstate *d) { longjmp(d->err, 1); }
-
+
void decode_verifyutf8(upb_decstate *d, const char *buf, int len) {
static const uint8_t utf8_offset[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -169,41 +169,41 @@ void decode_verifyutf8(upb_decstate *d, const char *buf, int len) {
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0,
};
-
+
int i, j;
uint8_t offset;
-
+
i = 0;
while (i < len) {
offset = utf8_offset[(uint8_t)buf[i]];
if (offset == 0 || i + offset > len) {
decode_err(d);
- }
+ }
for (j = i + 1; j < i + offset; j++) {
if ((buf[j] & 0xc0) != 0x80) {
decode_err(d);
}
- }
+ }
i += offset;
- }
+ }
if (i != len) decode_err(d);
-}
-
+}
+
static bool decode_reserve(upb_decstate *d, upb_array *arr, size_t elem) {
bool need_realloc = arr->size - arr->len < elem;
if (need_realloc && !_upb_array_realloc(arr, arr->len + elem, d->arena)) {
decode_err(d);
- }
+ }
return need_realloc;
-}
-
+}
+
UPB_NOINLINE
static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
const char *limit, uint64_t *val) {
uint8_t byte;
int bitpos = 0;
uint64_t out = 0;
-
+
do {
if (bitpos >= 70 || ptr == limit) decode_err(d);
byte = *ptr;
@@ -211,11 +211,11 @@ static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
ptr++;
bitpos += 7;
} while (byte & 0x80);
-
+
*val = out;
return ptr;
-}
-
+}
+
UPB_FORCEINLINE
static const char *decode_varint64(upb_decstate *d, const char *ptr,
const char *limit, uint64_t *val) {
@@ -224,9 +224,9 @@ static const char *decode_varint64(upb_decstate *d, const char *ptr,
return ptr + 1;
} else {
return decode_longvarint64(d, ptr, limit, val);
- }
-}
-
+ }
+}
+
static const char *decode_varint32(upb_decstate *d, const char *ptr,
const char *limit, uint32_t *val) {
uint64_t u64;
@@ -234,8 +234,8 @@ static const char *decode_varint32(upb_decstate *d, const char *ptr,
if (u64 > UINT32_MAX) decode_err(d);
*val = (uint32_t)u64;
return ptr;
-}
-
+}
+
static void decode_munge(int type, wireval *val) {
switch (type) {
case UPB_DESCRIPTOR_TYPE_BOOL:
@@ -258,13 +258,13 @@ static void decode_munge(int type, wireval *val) {
val->uint32_val = val->uint64_val;
}
break;
- }
-}
-
+ }
+}
+
static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
uint32_t field_number) {
static upb_msglayout_field none = {0, 0, 0, 0, 0, 0};
-
+
/* Lots of optimization opportunities here. */
int i;
if (l == NULL) return &none;
@@ -272,17 +272,17 @@ static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
if (l->fields[i].number == field_number) {
return &l->fields[i];
}
- }
-
+ }
+
return &none; /* Unknown field. */
-}
-
+}
+
static upb_msg *decode_newsubmsg(upb_decstate *d, const upb_msglayout *layout,
const upb_msglayout_field *field) {
const upb_msglayout *subl = layout->submsgs[field->submsg_index];
return _upb_msg_new(subl, d->arena);
-}
-
+}
+
static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
const upb_msglayout *layout,
const upb_msglayout_field *field, upb_strview val) {
@@ -294,8 +294,8 @@ static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
d->limit = saved_limit;
if (d->end_group != 0) decode_err(d);
d->depth++;
-}
-
+}
+
static const char *decode_group(upb_decstate *d, const char *ptr,
upb_msg *submsg, const upb_msglayout *subl,
uint32_t number) {
@@ -305,15 +305,15 @@ static const char *decode_group(upb_decstate *d, const char *ptr,
d->end_group = 0;
d->depth++;
return ptr;
-}
-
+}
+
static const char *decode_togroup(upb_decstate *d, const char *ptr,
upb_msg *submsg, const upb_msglayout *layout,
- const upb_msglayout_field *field) {
+ const upb_msglayout_field *field) {
const upb_msglayout *subl = layout->submsgs[field->submsg_index];
return decode_group(d, ptr, submsg, subl, field->number);
-}
-
+}
+
static const char *decode_toarray(upb_decstate *d, const char *ptr,
upb_msg *msg, const upb_msglayout *layout,
const upb_msglayout_field *field, wireval val,
@@ -321,16 +321,16 @@ static const char *decode_toarray(upb_decstate *d, const char *ptr,
upb_array **arrp = UPB_PTR_AT(msg, field->offset, void);
upb_array *arr = *arrp;
void *mem;
-
+
if (!arr) {
upb_fieldtype_t type = desctype_to_fieldtype[field->descriptortype];
arr = _upb_array_new(d->arena, type);
if (!arr) decode_err(d);
*arrp = arr;
}
-
+
decode_reserve(d, arr, 1);
-
+
switch (op) {
case OP_SCALAR_LG2(0):
case OP_SCALAR_LG2(2):
@@ -362,7 +362,7 @@ static const char *decode_toarray(upb_decstate *d, const char *ptr,
decode_tosubmsg(d, submsg, layout, field, val.str_val);
}
return ptr;
- }
+ }
case OP_FIXPCK_LG2(2):
case OP_FIXPCK_LG2(3): {
/* Fixed packed. */
@@ -377,7 +377,7 @@ static const char *decode_toarray(upb_decstate *d, const char *ptr,
arr->len += count;
memcpy(mem, val.str_val.data, val.str_val.size);
return ptr;
- }
+ }
case OP_VARPCK_LG2(0):
case OP_VARPCK_LG2(2):
case OP_VARPCK_LG2(3): {
@@ -400,12 +400,12 @@ static const char *decode_toarray(upb_decstate *d, const char *ptr,
}
if (ptr != end) decode_err(d);
return ptr;
- }
- default:
+ }
+ default:
UPB_UNREACHABLE();
- }
-}
-
+ }
+}
+
static void decode_tomap(upb_decstate *d, upb_msg *msg,
const upb_msglayout *layout,
const upb_msglayout_field *field, wireval val) {
@@ -413,7 +413,7 @@ static void decode_tomap(upb_decstate *d, upb_msg *msg,
upb_map *map = *map_p;
upb_map_entry ent;
const upb_msglayout *entry = layout->submsgs[field->submsg_index];
-
+
if (!map) {
/* Lazily create map. */
const upb_msglayout *entry = layout->submsgs[field->submsg_index];
@@ -425,42 +425,42 @@ static void decode_tomap(upb_decstate *d, upb_msg *msg,
UPB_ASSERT(val_field->offset == sizeof(upb_strview));
map = _upb_map_new(d->arena, key_size, val_size);
*map_p = map;
- }
-
+ }
+
/* Parse map entry. */
memset(&ent, 0, sizeof(ent));
-
+
if (entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_GROUP) {
/* Create proactively to handle the case where it doesn't appear. */
ent.v.val = upb_value_ptr(_upb_msg_new(entry->submsgs[0], d->arena));
- }
-
+ }
+
decode_tosubmsg(d, &ent.k, layout, field, val.str_val);
-
+
/* Insert into map. */
_upb_map_set(map, &ent.k, map->key_size, &ent.v, map->val_size, d->arena);
-}
-
+}
+
static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
const upb_msglayout *layout,
const upb_msglayout_field *field, wireval val,
int op) {
void *mem = UPB_PTR_AT(msg, field->offset, void);
int type = field->descriptortype;
-
+
/* Set presence if necessary. */
if (field->presence < 0) {
/* Oneof case */
uint32_t *oneof_case = _upb_oneofcase_field(msg, field);
if (op == OP_SUBMSG && *oneof_case != field->number) {
memset(mem, 0, sizeof(void*));
- }
+ }
*oneof_case = field->number;
} else if (field->presence > 0) {
_upb_sethas_field(msg, field);
- }
-
+ }
+
/* Store into message. */
switch (op) {
case OP_SUBMSG: {
@@ -469,14 +469,14 @@ static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
if (!submsg) {
submsg = decode_newsubmsg(d, layout, field);
*submsgp = submsg;
- }
+ }
if (UPB_UNLIKELY(type == UPB_DTYPE_GROUP)) {
ptr = decode_togroup(d, ptr, submsg, layout, field);
} else {
decode_tosubmsg(d, submsg, layout, field, val.str_val);
- }
+ }
break;
- }
+ }
case OP_STRING:
decode_verifyutf8(d, val.str_val.data, val.str_val.size);
/* Fallthrough. */
@@ -494,11 +494,11 @@ static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
break;
default:
UPB_UNREACHABLE();
- }
+ }
return ptr;
-}
-
+}
+
static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
const upb_msglayout *layout) {
while (ptr < d->limit) {
@@ -509,20 +509,20 @@ static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
const char *field_start = ptr;
wireval val;
int op;
-
+
ptr = decode_varint32(d, ptr, d->limit, &tag);
field_number = tag >> 3;
wire_type = tag & 7;
-
+
field = upb_find_field(layout, field_number);
-
+
switch (wire_type) {
- case UPB_WIRE_TYPE_VARINT:
+ case UPB_WIRE_TYPE_VARINT:
ptr = decode_varint64(d, ptr, d->limit, &val.uint64_val);
op = varint_ops[field->descriptortype];
decode_munge(field->descriptortype, &val);
break;
- case UPB_WIRE_TYPE_32BIT:
+ case UPB_WIRE_TYPE_32BIT:
if (d->limit - ptr < 4) decode_err(d);
memcpy(&val.uint32_val, ptr, 4);
val.uint32_val = _upb_be_swap32(val.uint32_val);
@@ -530,7 +530,7 @@ static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
op = OP_SCALAR_LG2(2);
if (((1 << field->descriptortype) & fixed32_ok) == 0) goto unknown;
break;
- case UPB_WIRE_TYPE_64BIT:
+ case UPB_WIRE_TYPE_64BIT:
if (d->limit - ptr < 8) decode_err(d);
memcpy(&val.uint64_val, ptr, 8);
val.uint64_val = _upb_be_swap64(val.uint64_val);
@@ -545,25 +545,25 @@ static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
ptr = decode_varint32(d, ptr, d->limit, &size);
if (size >= INT32_MAX || (size_t)(d->limit - ptr) < size) {
decode_err(d); /* Length overflow. */
- }
+ }
val.str_val.data = ptr;
val.str_val.size = size;
ptr += size;
op = delim_ops[ndx];
break;
- }
+ }
case UPB_WIRE_TYPE_START_GROUP:
val.uint32_val = field_number;
op = OP_SUBMSG;
if (field->descriptortype != UPB_DTYPE_GROUP) goto unknown;
break;
- case UPB_WIRE_TYPE_END_GROUP:
- d->end_group = field_number;
+ case UPB_WIRE_TYPE_END_GROUP:
+ d->end_group = field_number;
return ptr;
- default:
+ default:
decode_err(d);
- }
-
+ }
+
if (op >= 0) {
/* Parse, using op for dispatch. */
switch (field->label) {
@@ -592,28 +592,28 @@ static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
}
}
}
- }
-
+ }
+
if (ptr != d->limit) decode_err(d);
return ptr;
-}
-
-bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
- upb_arena *arena) {
- upb_decstate state;
- state.limit = buf + size;
- state.arena = arena;
- state.depth = 64;
- state.end_group = 0;
-
+}
+
+bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
+ upb_arena *arena) {
+ upb_decstate state;
+ state.limit = buf + size;
+ state.arena = arena;
+ state.depth = 64;
+ state.end_group = 0;
+
if (setjmp(state.err)) return false;
if (size == 0) return true;
decode_msg(&state, buf, msg, l);
- return state.end_group == 0;
-}
-
+ return state.end_group == 0;
+}
+
#undef OP_SCALAR_LG2
#undef OP_FIXPCK_LG2
#undef OP_VARPCK_LG2
diff --git a/contrib/libs/grpc/third_party/upb/upb/decode.h b/contrib/libs/grpc/third_party/upb/upb/decode.h
index 9de8638de5..1b56be4111 100644
--- a/contrib/libs/grpc/third_party/upb/upb/decode.h
+++ b/contrib/libs/grpc/third_party/upb/upb/decode.h
@@ -1,21 +1,21 @@
-/*
-** upb_decode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_DECODE_H_
-#define UPB_DECODE_H_
-
-#include "upb/msg.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-bool upb_decode(const char *buf, size_t size, upb_msg *msg,
- const upb_msglayout *l, upb_arena *arena);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_DECODE_H_ */
+/*
+** upb_decode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_DECODE_H_
+#define UPB_DECODE_H_
+
+#include "upb/msg.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+bool upb_decode(const char *buf, size_t size, upb_msg *msg,
+ const upb_msglayout *l, upb_arena *arena);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* UPB_DECODE_H_ */
diff --git a/contrib/libs/grpc/third_party/upb/upb/encode.c b/contrib/libs/grpc/third_party/upb/upb/encode.c
index a6ce62bfa5..c3e994ec3d 100644
--- a/contrib/libs/grpc/third_party/upb/upb/encode.c
+++ b/contrib/libs/grpc/third_party/upb/upb/encode.c
@@ -1,121 +1,121 @@
-/* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
-
-#include "upb/encode.h"
-
-#include <string.h>
-
-#include "upb/msg.h"
-#include "upb/upb.h"
-
-#include "upb/port_def.inc"
-
-#define UPB_PB_VARINT_MAX_LEN 10
-#define CHK(x) do { if (!(x)) { return false; } } while(0)
-
-static size_t upb_encode_varint(uint64_t val, char *buf) {
- size_t i;
- if (val < 128) { buf[0] = val; return 1; }
- i = 0;
- while (val) {
- uint8_t byte = val & 0x7fU;
- val >>= 7;
- if (val) byte |= 0x80U;
- buf[i++] = byte;
- }
- return i;
-}
-
-static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
-static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
-
-typedef struct {
- upb_alloc *alloc;
- char *buf, *ptr, *limit;
-} upb_encstate;
-
-static size_t upb_roundup_pow2(size_t bytes) {
- size_t ret = 128;
- while (ret < bytes) {
- ret *= 2;
- }
- return ret;
-}
-
-static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
- size_t old_size = e->limit - e->buf;
- size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
- char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
- CHK(new_buf);
-
- /* We want previous data at the end, realloc() put it at the beginning. */
- if (old_size > 0) {
- memmove(new_buf + new_size - old_size, e->buf, old_size);
- }
-
- e->ptr = new_buf + new_size - (e->limit - e->ptr);
- e->limit = new_buf + new_size;
- e->buf = new_buf;
- return true;
-}
-
-/* Call to ensure that at least "bytes" bytes are available for writing at
- * e->ptr. Returns false if the bytes could not be allocated. */
-static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
- CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
- upb_encode_growbuffer(e, bytes));
-
- e->ptr -= bytes;
- return true;
-}
-
-/* Writes the given bytes to the buffer, handling reserve/advance. */
-static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
+/* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
+
+#include "upb/encode.h"
+
+#include <string.h>
+
+#include "upb/msg.h"
+#include "upb/upb.h"
+
+#include "upb/port_def.inc"
+
+#define UPB_PB_VARINT_MAX_LEN 10
+#define CHK(x) do { if (!(x)) { return false; } } while(0)
+
+static size_t upb_encode_varint(uint64_t val, char *buf) {
+ size_t i;
+ if (val < 128) { buf[0] = val; return 1; }
+ i = 0;
+ while (val) {
+ uint8_t byte = val & 0x7fU;
+ val >>= 7;
+ if (val) byte |= 0x80U;
+ buf[i++] = byte;
+ }
+ return i;
+}
+
+static uint32_t upb_zzencode_32(int32_t n) { return ((uint32_t)n << 1) ^ (n >> 31); }
+static uint64_t upb_zzencode_64(int64_t n) { return ((uint64_t)n << 1) ^ (n >> 63); }
+
+typedef struct {
+ upb_alloc *alloc;
+ char *buf, *ptr, *limit;
+} upb_encstate;
+
+static size_t upb_roundup_pow2(size_t bytes) {
+ size_t ret = 128;
+ while (ret < bytes) {
+ ret *= 2;
+ }
+ return ret;
+}
+
+static bool upb_encode_growbuffer(upb_encstate *e, size_t bytes) {
+ size_t old_size = e->limit - e->buf;
+ size_t new_size = upb_roundup_pow2(bytes + (e->limit - e->ptr));
+ char *new_buf = upb_realloc(e->alloc, e->buf, old_size, new_size);
+ CHK(new_buf);
+
+ /* We want previous data at the end, realloc() put it at the beginning. */
+ if (old_size > 0) {
+ memmove(new_buf + new_size - old_size, e->buf, old_size);
+ }
+
+ e->ptr = new_buf + new_size - (e->limit - e->ptr);
+ e->limit = new_buf + new_size;
+ e->buf = new_buf;
+ return true;
+}
+
+/* Call to ensure that at least "bytes" bytes are available for writing at
+ * e->ptr. Returns false if the bytes could not be allocated. */
+static bool upb_encode_reserve(upb_encstate *e, size_t bytes) {
+ CHK(UPB_LIKELY((size_t)(e->ptr - e->buf) >= bytes) ||
+ upb_encode_growbuffer(e, bytes));
+
+ e->ptr -= bytes;
+ return true;
+}
+
+/* Writes the given bytes to the buffer, handling reserve/advance. */
+static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
if (len == 0) return true;
- CHK(upb_encode_reserve(e, len));
- memcpy(e->ptr, data, len);
- return true;
-}
-
-static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
+ CHK(upb_encode_reserve(e, len));
+ memcpy(e->ptr, data, len);
+ return true;
+}
+
+static bool upb_put_fixed64(upb_encstate *e, uint64_t val) {
val = _upb_be_swap64(val);
- return upb_put_bytes(e, &val, sizeof(uint64_t));
-}
-
-static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
+ return upb_put_bytes(e, &val, sizeof(uint64_t));
+}
+
+static bool upb_put_fixed32(upb_encstate *e, uint32_t val) {
val = _upb_be_swap32(val);
- return upb_put_bytes(e, &val, sizeof(uint32_t));
-}
-
-static bool upb_put_varint(upb_encstate *e, uint64_t val) {
- size_t len;
- char *start;
- CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
- len = upb_encode_varint(val, e->ptr);
- start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
- memmove(start, e->ptr, len);
- e->ptr = start;
- return true;
-}
-
-static bool upb_put_double(upb_encstate *e, double d) {
- uint64_t u64;
- UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
- memcpy(&u64, &d, sizeof(uint64_t));
- return upb_put_fixed64(e, u64);
-}
-
-static bool upb_put_float(upb_encstate *e, float d) {
- uint32_t u32;
- UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
- memcpy(&u32, &d, sizeof(uint32_t));
- return upb_put_fixed32(e, u32);
-}
-
-static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
- return upb_put_varint(e, (field_number << 3) | wire_type);
-}
-
-static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
+ return upb_put_bytes(e, &val, sizeof(uint32_t));
+}
+
+static bool upb_put_varint(upb_encstate *e, uint64_t val) {
+ size_t len;
+ char *start;
+ CHK(upb_encode_reserve(e, UPB_PB_VARINT_MAX_LEN));
+ len = upb_encode_varint(val, e->ptr);
+ start = e->ptr + UPB_PB_VARINT_MAX_LEN - len;
+ memmove(start, e->ptr, len);
+ e->ptr = start;
+ return true;
+}
+
+static bool upb_put_double(upb_encstate *e, double d) {
+ uint64_t u64;
+ UPB_ASSERT(sizeof(double) == sizeof(uint64_t));
+ memcpy(&u64, &d, sizeof(uint64_t));
+ return upb_put_fixed64(e, u64);
+}
+
+static bool upb_put_float(upb_encstate *e, float d) {
+ uint32_t u32;
+ UPB_ASSERT(sizeof(float) == sizeof(uint32_t));
+ memcpy(&u32, &d, sizeof(uint32_t));
+ return upb_put_fixed32(e, u32);
+}
+
+static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
+ return upb_put_varint(e, (field_number << 3) | wire_type);
+}
+
+static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
size_t elem_size, uint32_t tag) {
size_t bytes = arr->len * elem_size;
const char* data = _upb_array_constptr(arr);
@@ -130,11 +130,11 @@ static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
} else {
return upb_put_bytes(e, data, bytes) && upb_put_varint(e, bytes);
}
-}
-
-bool upb_encode_message(upb_encstate *e, const char *msg,
- const upb_msglayout *m, size_t *size);
-
+}
+
+bool upb_encode_message(upb_encstate *e, const char *msg,
+ const upb_msglayout *m, size_t *size);
+
static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
const upb_msglayout *m,
const upb_msglayout_field *f,
@@ -211,16 +211,16 @@ static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
UPB_UNREACHABLE();
}
-static bool upb_encode_array(upb_encstate *e, const char *field_mem,
- const upb_msglayout *m,
- const upb_msglayout_field *f) {
- const upb_array *arr = *(const upb_array**)field_mem;
+static bool upb_encode_array(upb_encstate *e, const char *field_mem,
+ const upb_msglayout *m,
+ const upb_msglayout_field *f) {
+ const upb_array *arr = *(const upb_array**)field_mem;
bool packed = f->label == _UPB_LABEL_PACKED;
-
- if (arr == NULL || arr->len == 0) {
- return true;
- }
-
+
+ if (arr == NULL || arr->len == 0) {
+ return true;
+ }
+
#define VARINT_CASE(ctype, encode) \
{ \
const ctype *start = _upb_array_constptr(arr); \
@@ -238,85 +238,85 @@ static bool upb_encode_array(upb_encstate *e, const char *field_mem,
do { \
; \
} while (0)
-
+
#define TAG(wire_type) (packed ? 0 : (f->number << 3 | wire_type))
- switch (f->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ switch (f->descriptortype) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
CHK(upb_put_fixedarray(e, arr, sizeof(double), TAG(UPB_WIRE_TYPE_64BIT)));
- break;
- case UPB_DESCRIPTOR_TYPE_FLOAT:
+ break;
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
CHK(upb_put_fixedarray(e, arr, sizeof(float), TAG(UPB_WIRE_TYPE_32BIT)));
- break;
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
+ break;
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t), TAG(UPB_WIRE_TYPE_64BIT)));
- break;
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ break;
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t), TAG(UPB_WIRE_TYPE_32BIT)));
- break;
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- VARINT_CASE(uint64_t, *ptr);
- case UPB_DESCRIPTOR_TYPE_UINT32:
- VARINT_CASE(uint32_t, *ptr);
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_ENUM:
- VARINT_CASE(int32_t, (int64_t)*ptr);
- case UPB_DESCRIPTOR_TYPE_BOOL:
- VARINT_CASE(bool, *ptr);
- case UPB_DESCRIPTOR_TYPE_SINT32:
- VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
- case UPB_DESCRIPTOR_TYPE_SINT64:
- VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ VARINT_CASE(uint32_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ VARINT_CASE(int32_t, (int64_t)*ptr);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, *ptr);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
const upb_strview *start = _upb_array_constptr(arr);
const upb_strview *ptr = start + arr->len;
- do {
- ptr--;
- CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
- upb_put_varint(e, ptr->size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- } while (ptr != start);
- return true;
- }
- case UPB_DESCRIPTOR_TYPE_GROUP: {
+ do {
+ ptr--;
+ CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
+ upb_put_varint(e, ptr->size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
const void *const*start = _upb_array_constptr(arr);
const void *const*ptr = start + arr->len;
- const upb_msglayout *subm = m->submsgs[f->submsg_index];
- do {
- size_t size;
- ptr--;
- CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
- upb_encode_message(e, *ptr, subm, &size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
- } while (ptr != start);
- return true;
- }
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ const upb_msglayout *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
const void *const*start = _upb_array_constptr(arr);
const void *const*ptr = start + arr->len;
- const upb_msglayout *subm = m->submsgs[f->submsg_index];
- do {
- size_t size;
- ptr--;
- CHK(upb_encode_message(e, *ptr, subm, &size) &&
- upb_put_varint(e, size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- } while (ptr != start);
- return true;
- }
- }
-#undef VARINT_CASE
-
+ const upb_msglayout *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ }
+#undef VARINT_CASE
+
if (packed) {
CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
}
- return true;
-}
-
+ return true;
+}
+
static bool upb_encode_map(upb_encstate *e, const char *field_mem,
const upb_msglayout *m,
const upb_msglayout_field *f) {
@@ -328,7 +328,7 @@ static bool upb_encode_map(upb_encstate *e, const char *field_mem,
if (map == NULL) {
return true;
}
-
+
upb_strtable_begin(&i, &map->table);
for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
size_t pre_len = e->limit - e->ptr;
@@ -343,78 +343,78 @@ static bool upb_encode_map(upb_encstate *e, const char *field_mem,
size = (e->limit - e->ptr) - pre_len;
CHK(upb_put_varint(e, size));
CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- }
+ }
return true;
-}
-
-
-bool upb_encode_message(upb_encstate *e, const char *msg,
- const upb_msglayout *m, size_t *size) {
- int i;
- size_t pre_len = e->limit - e->ptr;
- const char *unknown;
- size_t unknown_size;
-
+}
+
+
+bool upb_encode_message(upb_encstate *e, const char *msg,
+ const upb_msglayout *m, size_t *size) {
+ int i;
+ size_t pre_len = e->limit - e->ptr;
+ const char *unknown;
+ size_t unknown_size;
+
unknown = upb_msg_getunknown(msg, &unknown_size);
if (unknown) {
upb_put_bytes(e, unknown, unknown_size);
}
- for (i = m->field_count - 1; i >= 0; i--) {
- const upb_msglayout_field *f = &m->fields[i];
-
+ for (i = m->field_count - 1; i >= 0; i--) {
+ const upb_msglayout_field *f = &m->fields[i];
+
if (_upb_isrepeated(f)) {
- CHK(upb_encode_array(e, msg + f->offset, m, f));
+ CHK(upb_encode_array(e, msg + f->offset, m, f));
} else if (f->label == _UPB_LABEL_MAP) {
CHK(upb_encode_map(e, msg + f->offset, m, f));
- } else {
- bool skip_empty = false;
- if (f->presence == 0) {
- /* Proto3 presence. */
- skip_empty = true;
- } else if (f->presence > 0) {
- /* Proto2 presence: hasbit. */
+ } else {
+ bool skip_empty = false;
+ if (f->presence == 0) {
+ /* Proto3 presence. */
+ skip_empty = true;
+ } else if (f->presence > 0) {
+ /* Proto2 presence: hasbit. */
if (!_upb_hasbit_field(msg, f)) {
- continue;
- }
- } else {
- /* Field is in a oneof. */
+ continue;
+ }
+ } else {
+ /* Field is in a oneof. */
if (_upb_getoneofcase_field(msg, f) != f->number) {
- continue;
- }
- }
- CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
- }
- }
-
- *size = (e->limit - e->ptr) - pre_len;
- return true;
-}
-
-char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
- size_t *size) {
- upb_encstate e;
- e.alloc = upb_arena_alloc(arena);
- e.buf = NULL;
- e.limit = NULL;
- e.ptr = NULL;
-
- if (!upb_encode_message(&e, msg, m, size)) {
- *size = 0;
- return NULL;
- }
-
- *size = e.limit - e.ptr;
-
- if (*size == 0) {
- static char ch;
- return &ch;
- } else {
- UPB_ASSERT(e.ptr);
- return e.ptr;
- }
-}
-
-#undef CHK
+ continue;
+ }
+ }
+ CHK(upb_encode_scalarfield(e, msg + f->offset, m, f, skip_empty));
+ }
+ }
+
+ *size = (e->limit - e->ptr) - pre_len;
+ return true;
+}
+
+char *upb_encode(const void *msg, const upb_msglayout *m, upb_arena *arena,
+ size_t *size) {
+ upb_encstate e;
+ e.alloc = upb_arena_alloc(arena);
+ e.buf = NULL;
+ e.limit = NULL;
+ e.ptr = NULL;
+
+ if (!upb_encode_message(&e, msg, m, size)) {
+ *size = 0;
+ return NULL;
+ }
+
+ *size = e.limit - e.ptr;
+
+ if (*size == 0) {
+ static char ch;
+ return &ch;
+ } else {
+ UPB_ASSERT(e.ptr);
+ return e.ptr;
+ }
+}
+
+#undef CHK
diff --git a/contrib/libs/grpc/third_party/upb/upb/encode.h b/contrib/libs/grpc/third_party/upb/upb/encode.h
index 6842777058..4f6535bd78 100644
--- a/contrib/libs/grpc/third_party/upb/upb/encode.h
+++ b/contrib/libs/grpc/third_party/upb/upb/encode.h
@@ -1,21 +1,21 @@
-/*
-** upb_encode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_ENCODE_H_
-#define UPB_ENCODE_H_
-
-#include "upb/msg.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-char *upb_encode(const void *msg, const upb_msglayout *l, upb_arena *arena,
- size_t *size);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_ENCODE_H_ */
+/*
+** upb_encode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_ENCODE_H_
+#define UPB_ENCODE_H_
+
+#include "upb/msg.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char *upb_encode(const void *msg, const upb_msglayout *l, upb_arena *arena,
+ size_t *size);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* UPB_ENCODE_H_ */
diff --git a/contrib/libs/grpc/third_party/upb/upb/msg.c b/contrib/libs/grpc/third_party/upb/upb/msg.c
index 25747c8481..17dc961fe0 100644
--- a/contrib/libs/grpc/third_party/upb/upb/msg.c
+++ b/contrib/libs/grpc/third_party/upb/upb/msg.c
@@ -1,12 +1,12 @@
-
-#include "upb/msg.h"
-
-#include "upb/table.int.h"
-
-#include "upb/port_def.inc"
-
+
+#include "upb/msg.h"
+
+#include "upb/table.int.h"
+
+#include "upb/port_def.inc"
+
/** upb_msg *******************************************************************/
-
+
static const char _upb_fieldtype_to_sizelg2[12] = {
0,
0, /* UPB_TYPE_BOOL */
@@ -21,76 +21,76 @@ static const char _upb_fieldtype_to_sizelg2[12] = {
UPB_SIZE(3, 4), /* UPB_TYPE_STRING */
UPB_SIZE(3, 4), /* UPB_TYPE_BYTES */
};
-
+
static uintptr_t tag_arrptr(void* ptr, int elem_size_lg2) {
UPB_ASSERT(elem_size_lg2 <= 4);
return (uintptr_t)ptr | elem_size_lg2;
}
-
-static int upb_msg_internalsize(const upb_msglayout *l) {
- return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
-}
-
-static size_t upb_msg_sizeof(const upb_msglayout *l) {
- return l->size + upb_msg_internalsize(l);
-}
-
+
+static int upb_msg_internalsize(const upb_msglayout *l) {
+ return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
+}
+
+static size_t upb_msg_sizeof(const upb_msglayout *l) {
+ return l->size + upb_msg_internalsize(l);
+}
+
static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
ptrdiff_t size = sizeof(upb_msg_internal);
return UPB_PTR_AT(msg, -size, upb_msg_internal);
-}
-
+}
+
static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
return (upb_msg_internal*)upb_msg_getinternal_const(msg);
-}
-
+}
+
void _upb_msg_clear(upb_msg *msg, const upb_msglayout *l) {
ptrdiff_t internal = upb_msg_internalsize(l);
void *mem = UPB_PTR_AT(msg, -internal, char);
memset(mem, 0, l->size + internal);
-}
-
+}
+
upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a) {
void *mem = upb_arena_malloc(a, upb_msg_sizeof(l));
- upb_msg *msg;
-
- if (!mem) {
- return NULL;
- }
-
+ upb_msg *msg;
+
+ if (!mem) {
+ return NULL;
+ }
+
msg = UPB_PTR_AT(mem, upb_msg_internalsize(l), upb_msg);
_upb_msg_clear(msg, l);
- return msg;
-}
-
+ return msg;
+}
+
bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
upb_arena *arena) {
- upb_msg_internal *in = upb_msg_getinternal(msg);
- if (len > in->unknown_size - in->unknown_len) {
- upb_alloc *alloc = upb_arena_alloc(arena);
- size_t need = in->unknown_size + len;
- size_t newsize = UPB_MAX(in->unknown_size * 2, need);
+ upb_msg_internal *in = upb_msg_getinternal(msg);
+ if (len > in->unknown_size - in->unknown_len) {
+ upb_alloc *alloc = upb_arena_alloc(arena);
+ size_t need = in->unknown_size + len;
+ size_t newsize = UPB_MAX(in->unknown_size * 2, need);
void *mem = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
if (!mem) return false;
in->unknown = mem;
- in->unknown_size = newsize;
- }
- memcpy(in->unknown + in->unknown_len, data, len);
- in->unknown_len += len;
+ in->unknown_size = newsize;
+ }
+ memcpy(in->unknown + in->unknown_len, data, len);
+ in->unknown_len += len;
return true;
-}
-
+}
+
void _upb_msg_discardunknown_shallow(upb_msg *msg) {
upb_msg_internal *in = upb_msg_getinternal(msg);
in->unknown_len = 0;
}
-const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
+const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
const upb_msg_internal *in = upb_msg_getinternal_const(msg);
- *len = in->unknown_len;
- return in->unknown;
-}
-
+ *len = in->unknown_len;
+ return in->unknown;
+}
+
/** upb_array *****************************************************************/
upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type) {
diff --git a/contrib/libs/grpc/third_party/upb/upb/msg.h b/contrib/libs/grpc/third_party/upb/upb/msg.h
index 695c278b21..10af8d6b7c 100644
--- a/contrib/libs/grpc/third_party/upb/upb/msg.h
+++ b/contrib/libs/grpc/third_party/upb/upb/msg.h
@@ -1,35 +1,35 @@
-/*
+/*
** Our memory representation for parsing tables and messages themselves.
** Functions in this file are used by generated code and possibly reflection.
-**
-** The definitions in this file are internal to upb.
-**/
-
-#ifndef UPB_MSG_H_
-#define UPB_MSG_H_
-
-#include <stdint.h>
-#include <string.h>
+**
+** The definitions in this file are internal to upb.
+**/
+
+#ifndef UPB_MSG_H_
+#define UPB_MSG_H_
+
+#include <stdint.h>
+#include <string.h>
#include "upb/table.int.h"
-#include "upb/upb.h"
-
+#include "upb/upb.h"
+
#include "upb/port_def.inc"
-#ifdef __cplusplus
-extern "C" {
-#endif
-
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#define PTR_AT(msg, ofs, type) (type*)((const char*)msg + ofs)
-typedef void upb_msg;
-
-/** upb_msglayout *************************************************************/
-
-/* upb_msglayout represents the memory layout of a given upb_msgdef. The
- * members are public so generated code can initialize them, but users MUST NOT
- * read or write any of its members. */
-
+typedef void upb_msg;
+
+/** upb_msglayout *************************************************************/
+
+/* upb_msglayout represents the memory layout of a given upb_msgdef. The
+ * members are public so generated code can initialize them, but users MUST NOT
+ * read or write any of its members. */
+
/* These aren't real labels according to descriptor.proto, but in the table we
* use these for map/packed fields instead of UPB_LABEL_REPEATED. */
enum {
@@ -37,33 +37,33 @@ enum {
_UPB_LABEL_PACKED = 7 /* Low 3 bits are common with UPB_LABEL_REPEATED. */
};
-typedef struct {
- uint32_t number;
- uint16_t offset;
+typedef struct {
+ uint32_t number;
+ uint16_t offset;
int16_t presence; /* If >0, hasbit_index. If <0, ~oneof_index. */
- uint16_t submsg_index; /* undefined if descriptortype != MESSAGE or GROUP. */
- uint8_t descriptortype;
+ uint16_t submsg_index; /* undefined if descriptortype != MESSAGE or GROUP. */
+ uint8_t descriptortype;
uint8_t label; /* google.protobuf.Label or _UPB_LABEL_* above. */
-} upb_msglayout_field;
-
-typedef struct upb_msglayout {
- const struct upb_msglayout *const* submsgs;
- const upb_msglayout_field *fields;
- /* Must be aligned to sizeof(void*). Doesn't include internal members like
- * unknown fields, extension dict, pointer to msglayout, etc. */
- uint16_t size;
- uint16_t field_count;
- bool extendable;
-} upb_msglayout;
-
+} upb_msglayout_field;
+
+typedef struct upb_msglayout {
+ const struct upb_msglayout *const* submsgs;
+ const upb_msglayout_field *fields;
+ /* Must be aligned to sizeof(void*). Doesn't include internal members like
+ * unknown fields, extension dict, pointer to msglayout, etc. */
+ uint16_t size;
+ uint16_t field_count;
+ bool extendable;
+} upb_msglayout;
+
/** upb_msg *******************************************************************/
-
+
/* Internal members of a upb_msg. We can change this without breaking binary
* compatibility. We put these before the user's data. The user's upb_msg*
* points after the upb_msg_internal. */
/* Used when a message is not extendable. */
-typedef struct {
+typedef struct {
char *unknown;
size_t unknown_len;
size_t unknown_size;
@@ -171,21 +171,21 @@ UPB_INLINE bool _upb_repeated_or_map(const upb_msglayout_field *field) {
/* Our internal representation for repeated fields. */
typedef struct {
uintptr_t data; /* Tagged ptr: low 3 bits of ptr are lg2(elem size). */
- size_t len; /* Measured in elements. */
- size_t size; /* Measured in elements. */
-} upb_array;
-
+ size_t len; /* Measured in elements. */
+ size_t size; /* Measured in elements. */
+} upb_array;
+
UPB_INLINE const void *_upb_array_constptr(const upb_array *arr) {
return (void*)(arr->data & ~(uintptr_t)7);
}
-
+
UPB_INLINE void *_upb_array_ptr(upb_array *arr) {
return (void*)_upb_array_constptr(arr);
}
-
+
/* Creates a new array on the given arena. */
upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type);
-
+
/* Resizes the capacity of the array to be at least min_size. */
bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena);
@@ -464,10 +464,10 @@ UPB_INLINE void _upb_msg_map_set_value(void* msg, const void* val, size_t size)
#undef PTR_AT
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
#include "upb/port_undef.inc"
-#endif /* UPB_MSG_H_ */
+#endif /* UPB_MSG_H_ */
diff --git a/contrib/libs/grpc/third_party/upb/upb/port.c b/contrib/libs/grpc/third_party/upb/upb/port.c
index 9ecf135167..9c65c55f6e 100644
--- a/contrib/libs/grpc/third_party/upb/upb/port.c
+++ b/contrib/libs/grpc/third_party/upb/upb/port.c
@@ -1,26 +1,26 @@
-
-#include "upb/port_def.inc"
-
-#ifdef UPB_MSVC_VSNPRINTF
-/* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
- * vsnprintf. To support them, missing functions are manually implemented
- * using the existing secure functions. */
-int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
- if (!s) {
- return _vscprintf(format, arg);
- }
- int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
- if (ret < 0) {
- ret = _vscprintf(format, arg);
- }
- return ret;
-}
-
-int msvc_snprintf(char* s, size_t n, const char* format, ...) {
- va_list arg;
- va_start(arg, format);
- int ret = msvc_vsnprintf(s, n, format, arg);
- va_end(arg);
- return ret;
-}
-#endif
+
+#include "upb/port_def.inc"
+
+#ifdef UPB_MSVC_VSNPRINTF
+/* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
+ * vsnprintf. To support them, missing functions are manually implemented
+ * using the existing secure functions. */
+int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
+ if (!s) {
+ return _vscprintf(format, arg);
+ }
+ int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
+ if (ret < 0) {
+ ret = _vscprintf(format, arg);
+ }
+ return ret;
+}
+
+int msvc_snprintf(char* s, size_t n, const char* format, ...) {
+ va_list arg;
+ va_start(arg, format);
+ int ret = msvc_vsnprintf(s, n, format, arg);
+ va_end(arg);
+ return ret;
+}
+#endif
diff --git a/contrib/libs/grpc/third_party/upb/upb/port_def.inc b/contrib/libs/grpc/third_party/upb/upb/port_def.inc
index 2c144dc066..b2cf29346f 100644
--- a/contrib/libs/grpc/third_party/upb/upb/port_def.inc
+++ b/contrib/libs/grpc/third_party/upb/upb/port_def.inc
@@ -1,138 +1,138 @@
-/*
-* This is where we define macros used across upb.
-*
-* All of these macros are undef'd in port_undef.inc to avoid leaking them to
-* users.
-*
-* The correct usage is:
-*
-* #include "upb/foobar.h"
-* #include "upb/baz.h"
-*
-* // MUST be last included header.
-* #include "upb/port_def.inc"
-*
-* // Code for this file.
-* // <...>
-*
-* // Can be omitted for .c files, required for .h.
-* #include "upb/port_undef.inc"
-*
-* This file is private and must not be included by users!
-*/
+/*
+* This is where we define macros used across upb.
+*
+* All of these macros are undef'd in port_undef.inc to avoid leaking them to
+* users.
+*
+* The correct usage is:
+*
+* #include "upb/foobar.h"
+* #include "upb/baz.h"
+*
+* // MUST be last included header.
+* #include "upb/port_def.inc"
+*
+* // Code for this file.
+* // <...>
+*
+* // Can be omitted for .c files, required for .h.
+* #include "upb/port_undef.inc"
+*
+* This file is private and must not be included by users!
+*/
#include <stdint.h>
#include <stddef.h>
-
-#if UINTPTR_MAX == 0xffffffff
-#define UPB_SIZE(size32, size64) size32
-#else
-#define UPB_SIZE(size32, size64) size64
-#endif
-
+
+#if UINTPTR_MAX == 0xffffffff
+#define UPB_SIZE(size32, size64) size32
+#else
+#define UPB_SIZE(size32, size64) size64
+#endif
+
/* If we always read/write as a consistent type to each address, this shouldn't
* violate aliasing.
*/
#define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
-
-#define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
+
+#define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
*UPB_PTR_AT(msg, case_offset, int) == case_val \
? *UPB_PTR_AT(msg, offset, fieldtype) \
- : default
-
-#define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
+ : default
+
+#define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
*UPB_PTR_AT(msg, case_offset, int) = case_val; \
*UPB_PTR_AT(msg, offset, fieldtype) = value;
-
+
#define UPB_MAPTYPE_STRING 0
-/* UPB_INLINE: inline if possible, emit standalone code if required. */
-#ifdef __cplusplus
-#define UPB_INLINE inline
-#elif defined (__GNUC__) || defined(__clang__)
-#define UPB_INLINE static __inline__
-#else
-#define UPB_INLINE static
-#endif
-
+/* UPB_INLINE: inline if possible, emit standalone code if required. */
+#ifdef __cplusplus
+#define UPB_INLINE inline
+#elif defined (__GNUC__) || defined(__clang__)
+#define UPB_INLINE static __inline__
+#else
+#define UPB_INLINE static
+#endif
+
#define UPB_ALIGN_UP(size, align) (((size) + (align) - 1) / (align) * (align))
#define UPB_ALIGN_DOWN(size, align) ((size) / (align) * (align))
#define UPB_ALIGN_MALLOC(size) UPB_ALIGN_UP(size, 16)
#define UPB_ALIGN_OF(type) offsetof (struct { char c; type member; }, member)
-/* Hints to the compiler about likely/unlikely branches. */
-#if defined (__GNUC__) || defined(__clang__)
-#define UPB_LIKELY(x) __builtin_expect((x),1)
-#define UPB_UNLIKELY(x) __builtin_expect((x),0)
-#else
-#define UPB_LIKELY(x) (x)
-#define UPB_UNLIKELY(x) (x)
-#endif
-
-/* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
- * doesn't provide these preprocessor symbols. */
-#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
-#define UPB_BIG_ENDIAN
-#endif
-
-/* Macros for function attributes on compilers that support them. */
-#ifdef __GNUC__
-#define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
-#define UPB_NOINLINE __attribute__((noinline))
-#define UPB_NORETURN __attribute__((__noreturn__))
-#else /* !defined(__GNUC__) */
-#define UPB_FORCEINLINE
-#define UPB_NOINLINE
-#define UPB_NORETURN
-#endif
-
-#if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
-/* C99/C++11 versions. */
-#include <stdio.h>
-#define _upb_snprintf snprintf
-#define _upb_vsnprintf vsnprintf
-#define _upb_va_copy(a, b) va_copy(a, b)
-#elif defined(_MSC_VER)
-/* Microsoft C/C++ versions. */
-#include <stdarg.h>
-#include <stdio.h>
-#if _MSC_VER < 1900
-int msvc_snprintf(char* s, size_t n, const char* format, ...);
-int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
-#define UPB_MSVC_VSNPRINTF
-#define _upb_snprintf msvc_snprintf
-#define _upb_vsnprintf msvc_vsnprintf
-#else
-#define _upb_snprintf snprintf
-#define _upb_vsnprintf vsnprintf
-#endif
-#define _upb_va_copy(a, b) va_copy(a, b)
-#elif defined __GNUC__
-/* A few hacky workarounds for functions not in C89.
- * For internal use only!
- * TODO(haberman): fix these by including our own implementations, or finding
- * another workaround.
- */
-#define _upb_snprintf __builtin_snprintf
-#define _upb_vsnprintf __builtin_vsnprintf
-#define _upb_va_copy(a, b) __va_copy(a, b)
-#else
-#error Need implementations of [v]snprintf and va_copy
-#endif
-
-#ifdef __cplusplus
-#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
- (defined(_MSC_VER) && _MSC_VER >= 1900)
-/* C++11 is present */
-#else
-#error upb requires C++11 for C++ support
-#endif
-#endif
-
-#define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
-#define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
-
-#define UPB_UNUSED(var) (void)var
-
+/* Hints to the compiler about likely/unlikely branches. */
+#if defined (__GNUC__) || defined(__clang__)
+#define UPB_LIKELY(x) __builtin_expect((x),1)
+#define UPB_UNLIKELY(x) __builtin_expect((x),0)
+#else
+#define UPB_LIKELY(x) (x)
+#define UPB_UNLIKELY(x) (x)
+#endif
+
+/* Define UPB_BIG_ENDIAN manually if you're on big endian and your compiler
+ * doesn't provide these preprocessor symbols. */
+#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
+#define UPB_BIG_ENDIAN
+#endif
+
+/* Macros for function attributes on compilers that support them. */
+#ifdef __GNUC__
+#define UPB_FORCEINLINE __inline__ __attribute__((always_inline))
+#define UPB_NOINLINE __attribute__((noinline))
+#define UPB_NORETURN __attribute__((__noreturn__))
+#else /* !defined(__GNUC__) */
+#define UPB_FORCEINLINE
+#define UPB_NOINLINE
+#define UPB_NORETURN
+#endif
+
+#if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L
+/* C99/C++11 versions. */
+#include <stdio.h>
+#define _upb_snprintf snprintf
+#define _upb_vsnprintf vsnprintf
+#define _upb_va_copy(a, b) va_copy(a, b)
+#elif defined(_MSC_VER)
+/* Microsoft C/C++ versions. */
+#include <stdarg.h>
+#include <stdio.h>
+#if _MSC_VER < 1900
+int msvc_snprintf(char* s, size_t n, const char* format, ...);
+int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
+#define UPB_MSVC_VSNPRINTF
+#define _upb_snprintf msvc_snprintf
+#define _upb_vsnprintf msvc_vsnprintf
+#else
+#define _upb_snprintf snprintf
+#define _upb_vsnprintf vsnprintf
+#endif
+#define _upb_va_copy(a, b) va_copy(a, b)
+#elif defined __GNUC__
+/* A few hacky workarounds for functions not in C89.
+ * For internal use only!
+ * TODO(haberman): fix these by including our own implementations, or finding
+ * another workaround.
+ */
+#define _upb_snprintf __builtin_snprintf
+#define _upb_vsnprintf __builtin_vsnprintf
+#define _upb_va_copy(a, b) __va_copy(a, b)
+#else
+#error Need implementations of [v]snprintf and va_copy
+#endif
+
+#ifdef __cplusplus
+#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
+ (defined(_MSC_VER) && _MSC_VER >= 1900)
+/* C++11 is present */
+#else
+#error upb requires C++11 for C++ support
+#endif
+#endif
+
+#define UPB_MAX(x, y) ((x) > (y) ? (x) : (y))
+#define UPB_MIN(x, y) ((x) < (y) ? (x) : (y))
+
+#define UPB_UNUSED(var) (void)var
+
/* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
*/
#ifdef NDEBUG
@@ -147,31 +147,31 @@ int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg);
#define UPB_ASSUME(expr) assert(expr)
#endif
-/* UPB_ASSERT(): in release mode, we use the expression without letting it be
- * evaluated. This prevents "unused variable" warnings. */
-#ifdef NDEBUG
-#define UPB_ASSERT(expr) do {} while (false && (expr))
-#else
-#define UPB_ASSERT(expr) assert(expr)
-#endif
-
-/* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
- * exist in debug mode. This turns into regular assert. */
-#define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
-
-#if defined(__GNUC__) || defined(__clang__)
-#define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
-#else
-#define UPB_UNREACHABLE() do { assert(0); } while(0)
-#endif
-
-/* UPB_INFINITY representing floating-point positive infinity. */
-#include <math.h>
-#ifdef INFINITY
-#define UPB_INFINITY INFINITY
-#else
-#define UPB_INFINITY (1.0 / 0.0)
-#endif
+/* UPB_ASSERT(): in release mode, we use the expression without letting it be
+ * evaluated. This prevents "unused variable" warnings. */
+#ifdef NDEBUG
+#define UPB_ASSERT(expr) do {} while (false && (expr))
+#else
+#define UPB_ASSERT(expr) assert(expr)
+#endif
+
+/* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
+ * exist in debug mode. This turns into regular assert. */
+#define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
+
+#if defined(__GNUC__) || defined(__clang__)
+#define UPB_UNREACHABLE() do { assert(0); __builtin_unreachable(); } while(0)
+#else
+#define UPB_UNREACHABLE() do { assert(0); } while(0)
+#endif
+
+/* UPB_INFINITY representing floating-point positive infinity. */
+#include <math.h>
+#ifdef INFINITY
+#define UPB_INFINITY INFINITY
+#else
+#define UPB_INFINITY (1.0 / 0.0)
+#endif
#ifdef NAN
#define UPB_NAN NAN
#else
diff --git a/contrib/libs/grpc/third_party/upb/upb/port_undef.inc b/contrib/libs/grpc/third_party/upb/upb/port_undef.inc
index c2b5f4a322..b7a966bd7c 100644
--- a/contrib/libs/grpc/third_party/upb/upb/port_undef.inc
+++ b/contrib/libs/grpc/third_party/upb/upb/port_undef.inc
@@ -1,28 +1,28 @@
-/* See port_def.inc. This should #undef all macros #defined there. */
-
+/* See port_def.inc. This should #undef all macros #defined there. */
+
#undef UPB_MAPTYPE_STRING
-#undef UPB_SIZE
+#undef UPB_SIZE
#undef UPB_PTR_AT
-#undef UPB_READ_ONEOF
-#undef UPB_WRITE_ONEOF
-#undef UPB_INLINE
+#undef UPB_READ_ONEOF
+#undef UPB_WRITE_ONEOF
+#undef UPB_INLINE
#undef UPB_ALIGN_UP
#undef UPB_ALIGN_DOWN
#undef UPB_ALIGN_MALLOC
#undef UPB_ALIGN_OF
-#undef UPB_FORCEINLINE
-#undef UPB_NOINLINE
-#undef UPB_NORETURN
-#undef UPB_MAX
-#undef UPB_MIN
-#undef UPB_UNUSED
+#undef UPB_FORCEINLINE
+#undef UPB_NOINLINE
+#undef UPB_NORETURN
+#undef UPB_MAX
+#undef UPB_MIN
+#undef UPB_UNUSED
#undef UPB_ASSUME
-#undef UPB_ASSERT
-#undef UPB_ASSERT_DEBUGVAR
-#undef UPB_UNREACHABLE
-#undef UPB_INFINITY
+#undef UPB_ASSERT
+#undef UPB_ASSERT_DEBUGVAR
+#undef UPB_UNREACHABLE
+#undef UPB_INFINITY
#undef UPB_NAN
-#undef UPB_MSVC_VSNPRINTF
-#undef _upb_snprintf
-#undef _upb_vsnprintf
-#undef _upb_va_copy
+#undef UPB_MSVC_VSNPRINTF
+#undef _upb_snprintf
+#undef _upb_vsnprintf
+#undef _upb_va_copy
diff --git a/contrib/libs/grpc/third_party/upb/upb/table.c b/contrib/libs/grpc/third_party/upb/upb/table.c
index 34a20530d8..b4af42a015 100644
--- a/contrib/libs/grpc/third_party/upb/upb/table.c
+++ b/contrib/libs/grpc/third_party/upb/upb/table.c
@@ -1,880 +1,880 @@
-/*
-** upb_table Implementation
-**
-** Implementation is heavily inspired by Lua's ltable.c.
-*/
-
-#include "upb/table.int.h"
-
-#include <string.h>
-
-#include "upb/port_def.inc"
-
-#define UPB_MAXARRSIZE 16 /* 64k. */
-
-/* From Chromium. */
-#define ARRAY_SIZE(x) \
- ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
-
-static const double MAX_LOAD = 0.85;
-
-/* The minimum utilization of the array part of a mixed hash/array table. This
- * is a speed/memory-usage tradeoff (though it's not straightforward because of
- * cache effects). The lower this is, the more memory we'll use. */
-static const double MIN_DENSITY = 0.1;
-
-bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
-
-int log2ceil(uint64_t v) {
- int ret = 0;
- bool pow2 = is_pow2(v);
- while (v >>= 1) ret++;
- ret = pow2 ? ret : ret + 1; /* Ceiling. */
- return UPB_MIN(UPB_MAXARRSIZE, ret);
-}
-
-char *upb_strdup(const char *s, upb_alloc *a) {
- return upb_strdup2(s, strlen(s), a);
-}
-
-char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
- size_t n;
- char *p;
-
- /* Prevent overflow errors. */
- if (len == SIZE_MAX) return NULL;
- /* Always null-terminate, even if binary data; but don't rely on the input to
- * have a null-terminating byte since it may be a raw binary buffer. */
- n = len + 1;
- p = upb_malloc(a, n);
- if (p) {
- memcpy(p, s, len);
- p[len] = 0;
- }
- return p;
-}
-
-/* A type to represent the lookup key of either a strtable or an inttable. */
-typedef union {
- uintptr_t num;
- struct {
- const char *str;
- size_t len;
- } str;
-} lookupkey_t;
-
-static lookupkey_t strkey2(const char *str, size_t len) {
- lookupkey_t k;
- k.str.str = str;
- k.str.len = len;
- return k;
-}
-
-static lookupkey_t intkey(uintptr_t key) {
- lookupkey_t k;
- k.num = key;
- return k;
-}
-
-typedef uint32_t hashfunc_t(upb_tabkey key);
-typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
-
-/* Base table (shared code) ***************************************************/
-
-/* For when we need to cast away const. */
-static upb_tabent *mutable_entries(upb_table *t) {
- return (upb_tabent*)t->entries;
-}
-
-static bool isfull(upb_table *t) {
- if (upb_table_size(t) == 0) {
- return true;
- } else {
- return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
- }
-}
-
+/*
+** upb_table Implementation
+**
+** Implementation is heavily inspired by Lua's ltable.c.
+*/
+
+#include "upb/table.int.h"
+
+#include <string.h>
+
+#include "upb/port_def.inc"
+
+#define UPB_MAXARRSIZE 16 /* 64k. */
+
+/* From Chromium. */
+#define ARRAY_SIZE(x) \
+ ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
+
+static const double MAX_LOAD = 0.85;
+
+/* The minimum utilization of the array part of a mixed hash/array table. This
+ * is a speed/memory-usage tradeoff (though it's not straightforward because of
+ * cache effects). The lower this is, the more memory we'll use. */
+static const double MIN_DENSITY = 0.1;
+
+bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
+
+int log2ceil(uint64_t v) {
+ int ret = 0;
+ bool pow2 = is_pow2(v);
+ while (v >>= 1) ret++;
+ ret = pow2 ? ret : ret + 1; /* Ceiling. */
+ return UPB_MIN(UPB_MAXARRSIZE, ret);
+}
+
+char *upb_strdup(const char *s, upb_alloc *a) {
+ return upb_strdup2(s, strlen(s), a);
+}
+
+char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
+ size_t n;
+ char *p;
+
+ /* Prevent overflow errors. */
+ if (len == SIZE_MAX) return NULL;
+ /* Always null-terminate, even if binary data; but don't rely on the input to
+ * have a null-terminating byte since it may be a raw binary buffer. */
+ n = len + 1;
+ p = upb_malloc(a, n);
+ if (p) {
+ memcpy(p, s, len);
+ p[len] = 0;
+ }
+ return p;
+}
+
+/* A type to represent the lookup key of either a strtable or an inttable. */
+typedef union {
+ uintptr_t num;
+ struct {
+ const char *str;
+ size_t len;
+ } str;
+} lookupkey_t;
+
+static lookupkey_t strkey2(const char *str, size_t len) {
+ lookupkey_t k;
+ k.str.str = str;
+ k.str.len = len;
+ return k;
+}
+
+static lookupkey_t intkey(uintptr_t key) {
+ lookupkey_t k;
+ k.num = key;
+ return k;
+}
+
+typedef uint32_t hashfunc_t(upb_tabkey key);
+typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
+
+/* Base table (shared code) ***************************************************/
+
+/* For when we need to cast away const. */
+static upb_tabent *mutable_entries(upb_table *t) {
+ return (upb_tabent*)t->entries;
+}
+
+static bool isfull(upb_table *t) {
+ if (upb_table_size(t) == 0) {
+ return true;
+ } else {
+ return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
+ }
+}
+
static bool init(upb_table *t, uint8_t size_lg2, upb_alloc *a) {
- size_t bytes;
-
- t->count = 0;
- t->size_lg2 = size_lg2;
- t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
- bytes = upb_table_size(t) * sizeof(upb_tabent);
- if (bytes > 0) {
- t->entries = upb_malloc(a, bytes);
- if (!t->entries) return false;
- memset(mutable_entries(t), 0, bytes);
- } else {
- t->entries = NULL;
- }
- return true;
-}
-
-static void uninit(upb_table *t, upb_alloc *a) {
- upb_free(a, mutable_entries(t));
-}
-
-static upb_tabent *emptyent(upb_table *t) {
- upb_tabent *e = mutable_entries(t) + upb_table_size(t);
- while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
-}
-
-static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
- return (upb_tabent*)upb_getentry(t, hash);
-}
-
-static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
- uint32_t hash, eqlfunc_t *eql) {
- const upb_tabent *e;
-
- if (t->size_lg2 == 0) return NULL;
- e = upb_getentry(t, hash);
- if (upb_tabent_isempty(e)) return NULL;
- while (1) {
- if (eql(e->key, key)) return e;
- if ((e = e->next) == NULL) return NULL;
- }
-}
-
-static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
- uint32_t hash, eqlfunc_t *eql) {
- return (upb_tabent*)findentry(t, key, hash, eql);
-}
-
-static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
- uint32_t hash, eqlfunc_t *eql) {
- const upb_tabent *e = findentry(t, key, hash, eql);
- if (e) {
- if (v) {
+ size_t bytes;
+
+ t->count = 0;
+ t->size_lg2 = size_lg2;
+ t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
+ bytes = upb_table_size(t) * sizeof(upb_tabent);
+ if (bytes > 0) {
+ t->entries = upb_malloc(a, bytes);
+ if (!t->entries) return false;
+ memset(mutable_entries(t), 0, bytes);
+ } else {
+ t->entries = NULL;
+ }
+ return true;
+}
+
+static void uninit(upb_table *t, upb_alloc *a) {
+ upb_free(a, mutable_entries(t));
+}
+
+static upb_tabent *emptyent(upb_table *t) {
+ upb_tabent *e = mutable_entries(t) + upb_table_size(t);
+ while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
+}
+
+static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
+ return (upb_tabent*)upb_getentry(t, hash);
+}
+
+static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
+ uint32_t hash, eqlfunc_t *eql) {
+ const upb_tabent *e;
+
+ if (t->size_lg2 == 0) return NULL;
+ e = upb_getentry(t, hash);
+ if (upb_tabent_isempty(e)) return NULL;
+ while (1) {
+ if (eql(e->key, key)) return e;
+ if ((e = e->next) == NULL) return NULL;
+ }
+}
+
+static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
+ uint32_t hash, eqlfunc_t *eql) {
+ return (upb_tabent*)findentry(t, key, hash, eql);
+}
+
+static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
+ uint32_t hash, eqlfunc_t *eql) {
+ const upb_tabent *e = findentry(t, key, hash, eql);
+ if (e) {
+ if (v) {
_upb_value_setval(v, e->val.val);
- }
- return true;
- } else {
- return false;
- }
-}
-
-/* The given key must not already exist in the table. */
-static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
- upb_value val, uint32_t hash,
- hashfunc_t *hashfunc, eqlfunc_t *eql) {
- upb_tabent *mainpos_e;
- upb_tabent *our_e;
-
- UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
-
- t->count++;
- mainpos_e = getentry_mutable(t, hash);
- our_e = mainpos_e;
-
- if (upb_tabent_isempty(mainpos_e)) {
- /* Our main position is empty; use it. */
- our_e->next = NULL;
- } else {
- /* Collision. */
- upb_tabent *new_e = emptyent(t);
- /* Head of collider's chain. */
- upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
- if (chain == mainpos_e) {
- /* Existing ent is in its main posisiton (it has the same hash as us, and
- * is the head of our chain). Insert to new ent and append to this chain. */
- new_e->next = mainpos_e->next;
- mainpos_e->next = new_e;
- our_e = new_e;
- } else {
- /* Existing ent is not in its main position (it is a node in some other
- * chain). This implies that no existing ent in the table has our hash.
- * Evict it (updating its chain) and use its ent for head of our chain. */
- *new_e = *mainpos_e; /* copies next. */
- while (chain->next != mainpos_e) {
- chain = (upb_tabent*)chain->next;
- UPB_ASSERT(chain);
- }
- chain->next = new_e;
- our_e = mainpos_e;
- our_e->next = NULL;
- }
- }
- our_e->key = tabkey;
- our_e->val.val = val.val;
- UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
-}
-
-static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
- upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
- upb_tabent *chain = getentry_mutable(t, hash);
- if (upb_tabent_isempty(chain)) return false;
- if (eql(chain->key, key)) {
- /* Element to remove is at the head of its chain. */
- t->count--;
+ }
+ return true;
+ } else {
+ return false;
+ }
+}
+
+/* The given key must not already exist in the table. */
+static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
+ upb_value val, uint32_t hash,
+ hashfunc_t *hashfunc, eqlfunc_t *eql) {
+ upb_tabent *mainpos_e;
+ upb_tabent *our_e;
+
+ UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
+
+ t->count++;
+ mainpos_e = getentry_mutable(t, hash);
+ our_e = mainpos_e;
+
+ if (upb_tabent_isempty(mainpos_e)) {
+ /* Our main position is empty; use it. */
+ our_e->next = NULL;
+ } else {
+ /* Collision. */
+ upb_tabent *new_e = emptyent(t);
+ /* Head of collider's chain. */
+ upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
+ if (chain == mainpos_e) {
+ /* Existing ent is in its main posisiton (it has the same hash as us, and
+ * is the head of our chain). Insert to new ent and append to this chain. */
+ new_e->next = mainpos_e->next;
+ mainpos_e->next = new_e;
+ our_e = new_e;
+ } else {
+ /* Existing ent is not in its main position (it is a node in some other
+ * chain). This implies that no existing ent in the table has our hash.
+ * Evict it (updating its chain) and use its ent for head of our chain. */
+ *new_e = *mainpos_e; /* copies next. */
+ while (chain->next != mainpos_e) {
+ chain = (upb_tabent*)chain->next;
+ UPB_ASSERT(chain);
+ }
+ chain->next = new_e;
+ our_e = mainpos_e;
+ our_e->next = NULL;
+ }
+ }
+ our_e->key = tabkey;
+ our_e->val.val = val.val;
+ UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
+}
+
+static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
+ upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
+ upb_tabent *chain = getentry_mutable(t, hash);
+ if (upb_tabent_isempty(chain)) return false;
+ if (eql(chain->key, key)) {
+ /* Element to remove is at the head of its chain. */
+ t->count--;
if (val) _upb_value_setval(val, chain->val.val);
- if (removed) *removed = chain->key;
- if (chain->next) {
- upb_tabent *move = (upb_tabent*)chain->next;
- *chain = *move;
- move->key = 0; /* Make the slot empty. */
- } else {
- chain->key = 0; /* Make the slot empty. */
- }
- return true;
- } else {
- /* Element to remove is either in a non-head position or not in the
- * table. */
- while (chain->next && !eql(chain->next->key, key)) {
- chain = (upb_tabent*)chain->next;
- }
- if (chain->next) {
- /* Found element to remove. */
- upb_tabent *rm = (upb_tabent*)chain->next;
- t->count--;
+ if (removed) *removed = chain->key;
+ if (chain->next) {
+ upb_tabent *move = (upb_tabent*)chain->next;
+ *chain = *move;
+ move->key = 0; /* Make the slot empty. */
+ } else {
+ chain->key = 0; /* Make the slot empty. */
+ }
+ return true;
+ } else {
+ /* Element to remove is either in a non-head position or not in the
+ * table. */
+ while (chain->next && !eql(chain->next->key, key)) {
+ chain = (upb_tabent*)chain->next;
+ }
+ if (chain->next) {
+ /* Found element to remove. */
+ upb_tabent *rm = (upb_tabent*)chain->next;
+ t->count--;
if (val) _upb_value_setval(val, chain->next->val.val);
- if (removed) *removed = rm->key;
- rm->key = 0; /* Make the slot empty. */
- chain->next = rm->next;
- return true;
- } else {
- /* Element to remove is not in the table. */
- return false;
- }
- }
-}
-
-static size_t next(const upb_table *t, size_t i) {
- do {
- if (++i >= upb_table_size(t))
+ if (removed) *removed = rm->key;
+ rm->key = 0; /* Make the slot empty. */
+ chain->next = rm->next;
+ return true;
+ } else {
+ /* Element to remove is not in the table. */
+ return false;
+ }
+ }
+}
+
+static size_t next(const upb_table *t, size_t i) {
+ do {
+ if (++i >= upb_table_size(t))
return SIZE_MAX - 1; /* Distinct from -1. */
- } while(upb_tabent_isempty(&t->entries[i]));
-
- return i;
-}
-
-static size_t begin(const upb_table *t) {
- return next(t, -1);
-}
-
-
-/* upb_strtable ***************************************************************/
-
-/* A simple "subclass" of upb_table that only adds a hash function for strings. */
-
-static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
- uint32_t len = (uint32_t) k2.str.len;
- char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
- if (str == NULL) return 0;
- memcpy(str, &len, sizeof(uint32_t));
+ } while(upb_tabent_isempty(&t->entries[i]));
+
+ return i;
+}
+
+static size_t begin(const upb_table *t) {
+ return next(t, -1);
+}
+
+
+/* upb_strtable ***************************************************************/
+
+/* A simple "subclass" of upb_table that only adds a hash function for strings. */
+
+static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
+ uint32_t len = (uint32_t) k2.str.len;
+ char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
+ if (str == NULL) return 0;
+ memcpy(str, &len, sizeof(uint32_t));
if (k2.str.len) memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len);
- str[sizeof(uint32_t) + k2.str.len] = '\0';
- return (uintptr_t)str;
-}
-
-static uint32_t strhash(upb_tabkey key) {
- uint32_t len;
- char *str = upb_tabstr(key, &len);
- return upb_murmur_hash2(str, len, 0);
-}
-
-static bool streql(upb_tabkey k1, lookupkey_t k2) {
- uint32_t len;
- char *str = upb_tabstr(k1, &len);
+ str[sizeof(uint32_t) + k2.str.len] = '\0';
+ return (uintptr_t)str;
+}
+
+static uint32_t strhash(upb_tabkey key) {
+ uint32_t len;
+ char *str = upb_tabstr(key, &len);
+ return upb_murmur_hash2(str, len, 0);
+}
+
+static bool streql(upb_tabkey k1, lookupkey_t k2) {
+ uint32_t len;
+ char *str = upb_tabstr(k1, &len);
return len == k2.str.len && (len == 0 || memcmp(str, k2.str.str, len) == 0);
-}
-
-bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
+}
+
+bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
UPB_UNUSED(ctype); /* TODO(haberman): rm */
return init(&t->t, 2, a);
-}
-
+}
+
void upb_strtable_clear(upb_strtable *t) {
size_t bytes = upb_table_size(&t->t) * sizeof(upb_tabent);
t->t.count = 0;
memset((char*)t->t.entries, 0, bytes);
}
-void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
- size_t i;
- for (i = 0; i < upb_table_size(&t->t); i++)
- upb_free(a, (void*)t->t.entries[i].key);
- uninit(&t->t, a);
-}
-
-bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
- upb_strtable new_table;
- upb_strtable_iter i;
-
+void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
+ size_t i;
+ for (i = 0; i < upb_table_size(&t->t); i++)
+ upb_free(a, (void*)t->t.entries[i].key);
+ uninit(&t->t, a);
+}
+
+bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
+ upb_strtable new_table;
+ upb_strtable_iter i;
+
if (!init(&new_table.t, size_lg2, a))
- return false;
- upb_strtable_begin(&i, t);
- for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ return false;
+ upb_strtable_begin(&i, t);
+ for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
upb_strview key = upb_strtable_iter_key(&i);
- upb_strtable_insert3(
+ upb_strtable_insert3(
&new_table, key.data, key.size,
upb_strtable_iter_value(&i), a);
- }
- upb_strtable_uninit2(t, a);
- *t = new_table;
- return true;
-}
-
-bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
- upb_value v, upb_alloc *a) {
- lookupkey_t key;
- upb_tabkey tabkey;
- uint32_t hash;
-
- if (isfull(&t->t)) {
- /* Need to resize. New table of double the size, add old elements to it. */
- if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
- return false;
- }
- }
-
- key = strkey2(k, len);
- tabkey = strcopy(key, a);
- if (tabkey == 0) return false;
-
- hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
- insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
- return true;
-}
-
-bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
- upb_value *v) {
- uint32_t hash = upb_murmur_hash2(key, len, 0);
- return lookup(&t->t, strkey2(key, len), v, hash, &streql);
-}
-
-bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
- upb_value *val, upb_alloc *alloc) {
- uint32_t hash = upb_murmur_hash2(key, len, 0);
- upb_tabkey tabkey;
- if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
+ }
+ upb_strtable_uninit2(t, a);
+ *t = new_table;
+ return true;
+}
+
+bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
+ upb_value v, upb_alloc *a) {
+ lookupkey_t key;
+ upb_tabkey tabkey;
+ uint32_t hash;
+
+ if (isfull(&t->t)) {
+ /* Need to resize. New table of double the size, add old elements to it. */
+ if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
+ return false;
+ }
+ }
+
+ key = strkey2(k, len);
+ tabkey = strcopy(key, a);
+ if (tabkey == 0) return false;
+
+ hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
+ insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
+ return true;
+}
+
+bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
+ upb_value *v) {
+ uint32_t hash = upb_murmur_hash2(key, len, 0);
+ return lookup(&t->t, strkey2(key, len), v, hash, &streql);
+}
+
+bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
+ upb_value *val, upb_alloc *alloc) {
+ uint32_t hash = upb_murmur_hash2(key, len, 0);
+ upb_tabkey tabkey;
+ if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
if (alloc) {
/* Arena-based allocs don't need to free and won't pass this. */
upb_free(alloc, (void*)tabkey);
}
- return true;
- } else {
- return false;
- }
-}
-
-/* Iteration */
-
-void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
- i->t = t;
- i->index = begin(&t->t);
-}
-
-void upb_strtable_next(upb_strtable_iter *i) {
- i->index = next(&i->t->t, i->index);
-}
-
-bool upb_strtable_done(const upb_strtable_iter *i) {
- if (!i->t) return true;
- return i->index >= upb_table_size(&i->t->t) ||
- upb_tabent_isempty(str_tabent(i));
-}
-
+ return true;
+ } else {
+ return false;
+ }
+}
+
+/* Iteration */
+
+void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
+ i->t = t;
+ i->index = begin(&t->t);
+}
+
+void upb_strtable_next(upb_strtable_iter *i) {
+ i->index = next(&i->t->t, i->index);
+}
+
+bool upb_strtable_done(const upb_strtable_iter *i) {
+ if (!i->t) return true;
+ return i->index >= upb_table_size(&i->t->t) ||
+ upb_tabent_isempty(str_tabent(i));
+}
+
upb_strview upb_strtable_iter_key(const upb_strtable_iter *i) {
upb_strview key;
- uint32_t len;
- UPB_ASSERT(!upb_strtable_done(i));
+ uint32_t len;
+ UPB_ASSERT(!upb_strtable_done(i));
key.data = upb_tabstr(str_tabent(i)->key, &len);
key.size = len;
return key;
-}
-
-upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
- UPB_ASSERT(!upb_strtable_done(i));
+}
+
+upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
+ UPB_ASSERT(!upb_strtable_done(i));
return _upb_value_val(str_tabent(i)->val.val);
-}
-
-void upb_strtable_iter_setdone(upb_strtable_iter *i) {
- i->t = NULL;
- i->index = SIZE_MAX;
-}
-
-bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
- const upb_strtable_iter *i2) {
- if (upb_strtable_done(i1) && upb_strtable_done(i2))
- return true;
- return i1->t == i2->t && i1->index == i2->index;
-}
-
-
-/* upb_inttable ***************************************************************/
-
-/* For inttables we use a hybrid structure where small keys are kept in an
- * array and large keys are put in the hash table. */
-
-static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
-
-static bool inteql(upb_tabkey k1, lookupkey_t k2) {
- return k1 == k2.num;
-}
-
-static upb_tabval *mutable_array(upb_inttable *t) {
- return (upb_tabval*)t->array;
-}
-
-static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
- if (key < t->array_size) {
- return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
- } else {
- upb_tabent *e =
- findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
- return e ? &e->val : NULL;
- }
-}
-
-static const upb_tabval *inttable_val_const(const upb_inttable *t,
- uintptr_t key) {
- return inttable_val((upb_inttable*)t, key);
-}
-
-size_t upb_inttable_count(const upb_inttable *t) {
- return t->t.count + t->array_count;
-}
-
-static void check(upb_inttable *t) {
- UPB_UNUSED(t);
-#if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
- {
- /* This check is very expensive (makes inserts/deletes O(N)). */
- size_t count = 0;
- upb_inttable_iter i;
- upb_inttable_begin(&i, t);
- for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
- UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
- }
- UPB_ASSERT(count == upb_inttable_count(t));
- }
-#endif
-}
-
+}
+
+void upb_strtable_iter_setdone(upb_strtable_iter *i) {
+ i->t = NULL;
+ i->index = SIZE_MAX;
+}
+
+bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
+ const upb_strtable_iter *i2) {
+ if (upb_strtable_done(i1) && upb_strtable_done(i2))
+ return true;
+ return i1->t == i2->t && i1->index == i2->index;
+}
+
+
+/* upb_inttable ***************************************************************/
+
+/* For inttables we use a hybrid structure where small keys are kept in an
+ * array and large keys are put in the hash table. */
+
+static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
+
+static bool inteql(upb_tabkey k1, lookupkey_t k2) {
+ return k1 == k2.num;
+}
+
+static upb_tabval *mutable_array(upb_inttable *t) {
+ return (upb_tabval*)t->array;
+}
+
+static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
+ if (key < t->array_size) {
+ return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
+ } else {
+ upb_tabent *e =
+ findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
+ return e ? &e->val : NULL;
+ }
+}
+
+static const upb_tabval *inttable_val_const(const upb_inttable *t,
+ uintptr_t key) {
+ return inttable_val((upb_inttable*)t, key);
+}
+
+size_t upb_inttable_count(const upb_inttable *t) {
+ return t->t.count + t->array_count;
+}
+
+static void check(upb_inttable *t) {
+ UPB_UNUSED(t);
+#if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
+ {
+ /* This check is very expensive (makes inserts/deletes O(N)). */
+ size_t count = 0;
+ upb_inttable_iter i;
+ upb_inttable_begin(&i, t);
+ for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
+ UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
+ }
+ UPB_ASSERT(count == upb_inttable_count(t));
+ }
+#endif
+}
+
bool upb_inttable_sizedinit(upb_inttable *t, size_t asize, int hsize_lg2,
upb_alloc *a) {
- size_t array_bytes;
-
+ size_t array_bytes;
+
if (!init(&t->t, hsize_lg2, a)) return false;
- /* Always make the array part at least 1 long, so that we know key 0
- * won't be in the hash part, which simplifies things. */
- t->array_size = UPB_MAX(1, asize);
- t->array_count = 0;
- array_bytes = t->array_size * sizeof(upb_value);
- t->array = upb_malloc(a, array_bytes);
- if (!t->array) {
- uninit(&t->t, a);
- return false;
- }
- memset(mutable_array(t), 0xff, array_bytes);
- check(t);
- return true;
-}
-
-bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
+ /* Always make the array part at least 1 long, so that we know key 0
+ * won't be in the hash part, which simplifies things. */
+ t->array_size = UPB_MAX(1, asize);
+ t->array_count = 0;
+ array_bytes = t->array_size * sizeof(upb_value);
+ t->array = upb_malloc(a, array_bytes);
+ if (!t->array) {
+ uninit(&t->t, a);
+ return false;
+ }
+ memset(mutable_array(t), 0xff, array_bytes);
+ check(t);
+ return true;
+}
+
+bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
UPB_UNUSED(ctype); /* TODO(haberman): rm */
return upb_inttable_sizedinit(t, 0, 4, a);
-}
-
-void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
- uninit(&t->t, a);
- upb_free(a, mutable_array(t));
-}
-
-bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
- upb_alloc *a) {
- upb_tabval tabval;
- tabval.val = val.val;
- UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
-
- if (key < t->array_size) {
- UPB_ASSERT(!upb_arrhas(t->array[key]));
- t->array_count++;
- mutable_array(t)[key].val = val.val;
- } else {
- if (isfull(&t->t)) {
- /* Need to resize the hash part, but we re-use the array part. */
- size_t i;
- upb_table new_table;
-
+}
+
+void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
+ uninit(&t->t, a);
+ upb_free(a, mutable_array(t));
+}
+
+bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
+ upb_alloc *a) {
+ upb_tabval tabval;
+ tabval.val = val.val;
+ UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
+
+ if (key < t->array_size) {
+ UPB_ASSERT(!upb_arrhas(t->array[key]));
+ t->array_count++;
+ mutable_array(t)[key].val = val.val;
+ } else {
+ if (isfull(&t->t)) {
+ /* Need to resize the hash part, but we re-use the array part. */
+ size_t i;
+ upb_table new_table;
+
if (!init(&new_table, t->t.size_lg2 + 1, a)) {
- return false;
- }
-
- for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
- const upb_tabent *e = &t->t.entries[i];
- uint32_t hash;
- upb_value v;
-
+ return false;
+ }
+
+ for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
+ const upb_tabent *e = &t->t.entries[i];
+ uint32_t hash;
+ upb_value v;
+
_upb_value_setval(&v, e->val.val);
- hash = upb_inthash(e->key);
- insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
- }
-
- UPB_ASSERT(t->t.count == new_table.count);
-
- uninit(&t->t, a);
- t->t = new_table;
- }
- insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
- }
- check(t);
- return true;
-}
-
-bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
- const upb_tabval *table_v = inttable_val_const(t, key);
- if (!table_v) return false;
+ hash = upb_inthash(e->key);
+ insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
+ }
+
+ UPB_ASSERT(t->t.count == new_table.count);
+
+ uninit(&t->t, a);
+ t->t = new_table;
+ }
+ insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
+ }
+ check(t);
+ return true;
+}
+
+bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
+ const upb_tabval *table_v = inttable_val_const(t, key);
+ if (!table_v) return false;
if (v) _upb_value_setval(v, table_v->val);
- return true;
-}
-
-bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
- upb_tabval *table_v = inttable_val(t, key);
- if (!table_v) return false;
- table_v->val = val.val;
- return true;
-}
-
-bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
- bool success;
- if (key < t->array_size) {
- if (upb_arrhas(t->array[key])) {
- upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
- t->array_count--;
- if (val) {
+ return true;
+}
+
+bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
+ upb_tabval *table_v = inttable_val(t, key);
+ if (!table_v) return false;
+ table_v->val = val.val;
+ return true;
+}
+
+bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
+ bool success;
+ if (key < t->array_size) {
+ if (upb_arrhas(t->array[key])) {
+ upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
+ t->array_count--;
+ if (val) {
_upb_value_setval(val, t->array[key].val);
- }
- mutable_array(t)[key] = empty;
- success = true;
- } else {
- success = false;
- }
- } else {
- success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
- }
- check(t);
- return success;
-}
-
-bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
- upb_alloc *a) {
- return upb_inttable_insert2(t, (uintptr_t)key, val, a);
-}
-
-bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
- upb_value *v) {
- return upb_inttable_lookup(t, (uintptr_t)key, v);
-}
-
-bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
- return upb_inttable_remove(t, (uintptr_t)key, val);
-}
-
-void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
- /* A power-of-two histogram of the table keys. */
- size_t counts[UPB_MAXARRSIZE + 1] = {0};
-
- /* The max key in each bucket. */
- uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
-
- upb_inttable_iter i;
- size_t arr_count;
- int size_lg2;
- upb_inttable new_t;
-
- upb_inttable_begin(&i, t);
- for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
- uintptr_t key = upb_inttable_iter_key(&i);
- int bucket = log2ceil(key);
- max[bucket] = UPB_MAX(max[bucket], key);
- counts[bucket]++;
- }
-
- /* Find the largest power of two that satisfies the MIN_DENSITY
- * definition (while actually having some keys). */
- arr_count = upb_inttable_count(t);
-
- for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
- if (counts[size_lg2] == 0) {
- /* We can halve again without losing any entries. */
- continue;
- } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
- break;
- }
-
- arr_count -= counts[size_lg2];
- }
-
- UPB_ASSERT(arr_count <= upb_inttable_count(t));
-
- {
- /* Insert all elements into new, perfectly-sized table. */
- size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
- size_t hash_count = upb_inttable_count(t) - arr_count;
- size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
- int hashsize_lg2 = log2ceil(hash_size);
-
+ }
+ mutable_array(t)[key] = empty;
+ success = true;
+ } else {
+ success = false;
+ }
+ } else {
+ success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
+ }
+ check(t);
+ return success;
+}
+
+bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
+ upb_alloc *a) {
+ return upb_inttable_insert2(t, (uintptr_t)key, val, a);
+}
+
+bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
+ upb_value *v) {
+ return upb_inttable_lookup(t, (uintptr_t)key, v);
+}
+
+bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
+ return upb_inttable_remove(t, (uintptr_t)key, val);
+}
+
+void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
+ /* A power-of-two histogram of the table keys. */
+ size_t counts[UPB_MAXARRSIZE + 1] = {0};
+
+ /* The max key in each bucket. */
+ uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
+
+ upb_inttable_iter i;
+ size_t arr_count;
+ int size_lg2;
+ upb_inttable new_t;
+
+ upb_inttable_begin(&i, t);
+ for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ uintptr_t key = upb_inttable_iter_key(&i);
+ int bucket = log2ceil(key);
+ max[bucket] = UPB_MAX(max[bucket], key);
+ counts[bucket]++;
+ }
+
+ /* Find the largest power of two that satisfies the MIN_DENSITY
+ * definition (while actually having some keys). */
+ arr_count = upb_inttable_count(t);
+
+ for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
+ if (counts[size_lg2] == 0) {
+ /* We can halve again without losing any entries. */
+ continue;
+ } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
+ break;
+ }
+
+ arr_count -= counts[size_lg2];
+ }
+
+ UPB_ASSERT(arr_count <= upb_inttable_count(t));
+
+ {
+ /* Insert all elements into new, perfectly-sized table. */
+ size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
+ size_t hash_count = upb_inttable_count(t) - arr_count;
+ size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
+ int hashsize_lg2 = log2ceil(hash_size);
+
upb_inttable_sizedinit(&new_t, arr_size, hashsize_lg2, a);
- upb_inttable_begin(&i, t);
- for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
- uintptr_t k = upb_inttable_iter_key(&i);
- upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
- }
- UPB_ASSERT(new_t.array_size == arr_size);
- UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
- }
- upb_inttable_uninit2(t, a);
- *t = new_t;
-}
-
-/* Iteration. */
-
-static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
- UPB_ASSERT(!i->array_part);
- return &i->t->t.entries[i->index];
-}
-
-static upb_tabval int_arrent(const upb_inttable_iter *i) {
- UPB_ASSERT(i->array_part);
- return i->t->array[i->index];
-}
-
-void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
- i->t = t;
- i->index = -1;
- i->array_part = true;
- upb_inttable_next(i);
-}
-
-void upb_inttable_next(upb_inttable_iter *iter) {
- const upb_inttable *t = iter->t;
- if (iter->array_part) {
- while (++iter->index < t->array_size) {
- if (upb_arrhas(int_arrent(iter))) {
- return;
- }
- }
- iter->array_part = false;
- iter->index = begin(&t->t);
- } else {
- iter->index = next(&t->t, iter->index);
- }
-}
-
-bool upb_inttable_done(const upb_inttable_iter *i) {
- if (!i->t) return true;
- if (i->array_part) {
- return i->index >= i->t->array_size ||
- !upb_arrhas(int_arrent(i));
- } else {
- return i->index >= upb_table_size(&i->t->t) ||
- upb_tabent_isempty(int_tabent(i));
- }
-}
-
-uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
- UPB_ASSERT(!upb_inttable_done(i));
- return i->array_part ? i->index : int_tabent(i)->key;
-}
-
-upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
- UPB_ASSERT(!upb_inttable_done(i));
- return _upb_value_val(
+ upb_inttable_begin(&i, t);
+ for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ uintptr_t k = upb_inttable_iter_key(&i);
+ upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
+ }
+ UPB_ASSERT(new_t.array_size == arr_size);
+ UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
+ }
+ upb_inttable_uninit2(t, a);
+ *t = new_t;
+}
+
+/* Iteration. */
+
+static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
+ UPB_ASSERT(!i->array_part);
+ return &i->t->t.entries[i->index];
+}
+
+static upb_tabval int_arrent(const upb_inttable_iter *i) {
+ UPB_ASSERT(i->array_part);
+ return i->t->array[i->index];
+}
+
+void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
+ i->t = t;
+ i->index = -1;
+ i->array_part = true;
+ upb_inttable_next(i);
+}
+
+void upb_inttable_next(upb_inttable_iter *iter) {
+ const upb_inttable *t = iter->t;
+ if (iter->array_part) {
+ while (++iter->index < t->array_size) {
+ if (upb_arrhas(int_arrent(iter))) {
+ return;
+ }
+ }
+ iter->array_part = false;
+ iter->index = begin(&t->t);
+ } else {
+ iter->index = next(&t->t, iter->index);
+ }
+}
+
+bool upb_inttable_done(const upb_inttable_iter *i) {
+ if (!i->t) return true;
+ if (i->array_part) {
+ return i->index >= i->t->array_size ||
+ !upb_arrhas(int_arrent(i));
+ } else {
+ return i->index >= upb_table_size(&i->t->t) ||
+ upb_tabent_isempty(int_tabent(i));
+ }
+}
+
+uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
+ UPB_ASSERT(!upb_inttable_done(i));
+ return i->array_part ? i->index : int_tabent(i)->key;
+}
+
+upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
+ UPB_ASSERT(!upb_inttable_done(i));
+ return _upb_value_val(
i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val);
-}
-
-void upb_inttable_iter_setdone(upb_inttable_iter *i) {
- i->t = NULL;
- i->index = SIZE_MAX;
- i->array_part = false;
-}
-
-bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
- const upb_inttable_iter *i2) {
- if (upb_inttable_done(i1) && upb_inttable_done(i2))
- return true;
- return i1->t == i2->t && i1->index == i2->index &&
- i1->array_part == i2->array_part;
-}
-
-#if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
-/* -----------------------------------------------------------------------------
- * MurmurHash2, by Austin Appleby (released as public domain).
- * Reformatted and C99-ified by Joshua Haberman.
- * Note - This code makes a few assumptions about how your machine behaves -
- * 1. We can read a 4-byte value from any address without crashing
- * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
- * And it has a few limitations -
- * 1. It will not work incrementally.
- * 2. It will not produce the same results on little-endian and big-endian
- * machines. */
-uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
- /* 'm' and 'r' are mixing constants generated offline.
- * They're not really 'magic', they just happen to work well. */
- const uint32_t m = 0x5bd1e995;
- const int32_t r = 24;
-
- /* Initialize the hash to a 'random' value */
- uint32_t h = seed ^ len;
-
- /* Mix 4 bytes at a time into the hash */
- const uint8_t * data = (const uint8_t *)key;
- while(len >= 4) {
+}
+
+void upb_inttable_iter_setdone(upb_inttable_iter *i) {
+ i->t = NULL;
+ i->index = SIZE_MAX;
+ i->array_part = false;
+}
+
+bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
+ const upb_inttable_iter *i2) {
+ if (upb_inttable_done(i1) && upb_inttable_done(i2))
+ return true;
+ return i1->t == i2->t && i1->index == i2->index &&
+ i1->array_part == i2->array_part;
+}
+
+#if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
+/* -----------------------------------------------------------------------------
+ * MurmurHash2, by Austin Appleby (released as public domain).
+ * Reformatted and C99-ified by Joshua Haberman.
+ * Note - This code makes a few assumptions about how your machine behaves -
+ * 1. We can read a 4-byte value from any address without crashing
+ * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
+ * And it has a few limitations -
+ * 1. It will not work incrementally.
+ * 2. It will not produce the same results on little-endian and big-endian
+ * machines. */
+uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
+ /* 'm' and 'r' are mixing constants generated offline.
+ * They're not really 'magic', they just happen to work well. */
+ const uint32_t m = 0x5bd1e995;
+ const int32_t r = 24;
+
+ /* Initialize the hash to a 'random' value */
+ uint32_t h = seed ^ len;
+
+ /* Mix 4 bytes at a time into the hash */
+ const uint8_t * data = (const uint8_t *)key;
+ while(len >= 4) {
uint32_t k;
memcpy(&k, data, sizeof(k));
-
- k *= m;
- k ^= k >> r;
- k *= m;
-
- h *= m;
- h ^= k;
-
- data += 4;
- len -= 4;
- }
-
- /* Handle the last few bytes of the input array */
- switch(len) {
- case 3: h ^= data[2] << 16;
- case 2: h ^= data[1] << 8;
- case 1: h ^= data[0]; h *= m;
- };
-
- /* Do a few final mixes of the hash to ensure the last few
- * bytes are well-incorporated. */
- h ^= h >> 13;
- h *= m;
- h ^= h >> 15;
-
- return h;
-}
-
-#else /* !UPB_UNALIGNED_READS_OK */
-
-/* -----------------------------------------------------------------------------
- * MurmurHashAligned2, by Austin Appleby
- * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
- * on certain platforms.
- * Performance will be lower than MurmurHash2 */
-
-#define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
-
-uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
- const uint32_t m = 0x5bd1e995;
- const int32_t r = 24;
- const uint8_t * data = (const uint8_t *)key;
- uint32_t h = (uint32_t)(seed ^ len);
- uint8_t align = (uintptr_t)data & 3;
-
- if(align && (len >= 4)) {
- /* Pre-load the temp registers */
- uint32_t t = 0, d = 0;
- int32_t sl;
- int32_t sr;
-
- switch(align) {
+
+ k *= m;
+ k ^= k >> r;
+ k *= m;
+
+ h *= m;
+ h ^= k;
+
+ data += 4;
+ len -= 4;
+ }
+
+ /* Handle the last few bytes of the input array */
+ switch(len) {
+ case 3: h ^= data[2] << 16;
+ case 2: h ^= data[1] << 8;
+ case 1: h ^= data[0]; h *= m;
+ };
+
+ /* Do a few final mixes of the hash to ensure the last few
+ * bytes are well-incorporated. */
+ h ^= h >> 13;
+ h *= m;
+ h ^= h >> 15;
+
+ return h;
+}
+
+#else /* !UPB_UNALIGNED_READS_OK */
+
+/* -----------------------------------------------------------------------------
+ * MurmurHashAligned2, by Austin Appleby
+ * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
+ * on certain platforms.
+ * Performance will be lower than MurmurHash2 */
+
+#define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
+
+uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
+ const uint32_t m = 0x5bd1e995;
+ const int32_t r = 24;
+ const uint8_t * data = (const uint8_t *)key;
+ uint32_t h = (uint32_t)(seed ^ len);
+ uint8_t align = (uintptr_t)data & 3;
+
+ if(align && (len >= 4)) {
+ /* Pre-load the temp registers */
+ uint32_t t = 0, d = 0;
+ int32_t sl;
+ int32_t sr;
+
+ switch(align) {
case 1: t |= data[2] << 16; /* fallthrough */
case 2: t |= data[1] << 8; /* fallthrough */
- case 3: t |= data[0];
- }
-
- t <<= (8 * align);
-
- data += 4-align;
- len -= 4-align;
-
- sl = 8 * (4-align);
- sr = 8 * align;
-
- /* Mix */
-
- while(len >= 4) {
- uint32_t k;
-
- d = *(uint32_t *)data;
- t = (t >> sr) | (d << sl);
-
- k = t;
-
- MIX(h,k,m);
-
- t = d;
-
- data += 4;
- len -= 4;
- }
-
- /* Handle leftover data in temp registers */
-
- d = 0;
-
- if(len >= align) {
- uint32_t k;
-
- switch(align) {
+ case 3: t |= data[0];
+ }
+
+ t <<= (8 * align);
+
+ data += 4-align;
+ len -= 4-align;
+
+ sl = 8 * (4-align);
+ sr = 8 * align;
+
+ /* Mix */
+
+ while(len >= 4) {
+ uint32_t k;
+
+ d = *(uint32_t *)data;
+ t = (t >> sr) | (d << sl);
+
+ k = t;
+
+ MIX(h,k,m);
+
+ t = d;
+
+ data += 4;
+ len -= 4;
+ }
+
+ /* Handle leftover data in temp registers */
+
+ d = 0;
+
+ if(len >= align) {
+ uint32_t k;
+
+ switch(align) {
case 3: d |= data[2] << 16; /* fallthrough */
case 2: d |= data[1] << 8; /* fallthrough */
case 1: d |= data[0]; /* fallthrough */
- }
-
- k = (t >> sr) | (d << sl);
- MIX(h,k,m);
-
- data += align;
- len -= align;
-
- /* ----------
- * Handle tail bytes */
-
- switch(len) {
+ }
+
+ k = (t >> sr) | (d << sl);
+ MIX(h,k,m);
+
+ data += align;
+ len -= align;
+
+ /* ----------
+ * Handle tail bytes */
+
+ switch(len) {
case 3: h ^= data[2] << 16; /* fallthrough */
case 2: h ^= data[1] << 8; /* fallthrough */
case 1: h ^= data[0]; h *= m; /* fallthrough */
- };
- } else {
- switch(len) {
+ };
+ } else {
+ switch(len) {
case 3: d |= data[2] << 16; /* fallthrough */
case 2: d |= data[1] << 8; /* fallthrough */
case 1: d |= data[0]; /* fallthrough */
- case 0: h ^= (t >> sr) | (d << sl); h *= m;
- }
- }
-
- h ^= h >> 13;
- h *= m;
- h ^= h >> 15;
-
- return h;
- } else {
- while(len >= 4) {
- uint32_t k = *(uint32_t *)data;
-
- MIX(h,k,m);
-
- data += 4;
- len -= 4;
- }
-
- /* ----------
- * Handle tail bytes */
-
- switch(len) {
+ case 0: h ^= (t >> sr) | (d << sl); h *= m;
+ }
+ }
+
+ h ^= h >> 13;
+ h *= m;
+ h ^= h >> 15;
+
+ return h;
+ } else {
+ while(len >= 4) {
+ uint32_t k = *(uint32_t *)data;
+
+ MIX(h,k,m);
+
+ data += 4;
+ len -= 4;
+ }
+
+ /* ----------
+ * Handle tail bytes */
+
+ switch(len) {
case 3: h ^= data[2] << 16; /* fallthrough */
case 2: h ^= data[1] << 8; /* fallthrough */
- case 1: h ^= data[0]; h *= m;
- };
-
- h ^= h >> 13;
- h *= m;
- h ^= h >> 15;
-
- return h;
- }
-}
-#undef MIX
-
-#endif /* UPB_UNALIGNED_READS_OK */
+ case 1: h ^= data[0]; h *= m;
+ };
+
+ h ^= h >> 13;
+ h *= m;
+ h ^= h >> 15;
+
+ return h;
+ }
+}
+#undef MIX
+
+#endif /* UPB_UNALIGNED_READS_OK */
diff --git a/contrib/libs/grpc/third_party/upb/upb/table.int.h b/contrib/libs/grpc/third_party/upb/upb/table.int.h
index 600637eef2..5f4e753222 100644
--- a/contrib/libs/grpc/third_party/upb/upb/table.int.h
+++ b/contrib/libs/grpc/third_party/upb/upb/table.int.h
@@ -1,466 +1,466 @@
-/*
-** upb_table
-**
-** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
-** This file defines very fast int->upb_value (inttable) and string->upb_value
-** (strtable) hash tables.
-**
-** The table uses chained scatter with Brent's variation (inspired by the Lua
-** implementation of hash tables). The hash function for strings is Austin
-** Appleby's "MurmurHash."
-**
-** The inttable uses uintptr_t as its key, which guarantees it can be used to
-** store pointers or integers of at least 32 bits (upb isn't really useful on
-** systems where sizeof(void*) < 4).
-**
-** The table must be homogenous (all values of the same type). In debug
-** mode, we check this on insert and lookup.
-*/
-
-#ifndef UPB_TABLE_H_
-#define UPB_TABLE_H_
-
-#include <stdint.h>
-#include <string.h>
-#include "upb/upb.h"
-
-#include "upb/port_def.inc"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* upb_value ******************************************************************/
-
-/* A tagged union (stored untagged inside the table) so that we can check that
- * clients calling table accessors are correctly typed without having to have
- * an explosion of accessors. */
-typedef enum {
- UPB_CTYPE_INT32 = 1,
- UPB_CTYPE_INT64 = 2,
- UPB_CTYPE_UINT32 = 3,
- UPB_CTYPE_UINT64 = 4,
- UPB_CTYPE_BOOL = 5,
- UPB_CTYPE_CSTR = 6,
- UPB_CTYPE_PTR = 7,
- UPB_CTYPE_CONSTPTR = 8,
- UPB_CTYPE_FPTR = 9,
- UPB_CTYPE_FLOAT = 10,
- UPB_CTYPE_DOUBLE = 11
-} upb_ctype_t;
-
-typedef struct {
- uint64_t val;
-} upb_value;
-
-/* Like strdup(), which isn't always available since it's not ANSI C. */
-char *upb_strdup(const char *s, upb_alloc *a);
-/* Variant that works with a length-delimited rather than NULL-delimited string,
- * as supported by strtable. */
-char *upb_strdup2(const char *s, size_t len, upb_alloc *a);
-
-UPB_INLINE char *upb_gstrdup(const char *s) {
- return upb_strdup(s, &upb_alloc_global);
-}
-
+/*
+** upb_table
+**
+** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
+** This file defines very fast int->upb_value (inttable) and string->upb_value
+** (strtable) hash tables.
+**
+** The table uses chained scatter with Brent's variation (inspired by the Lua
+** implementation of hash tables). The hash function for strings is Austin
+** Appleby's "MurmurHash."
+**
+** The inttable uses uintptr_t as its key, which guarantees it can be used to
+** store pointers or integers of at least 32 bits (upb isn't really useful on
+** systems where sizeof(void*) < 4).
+**
+** The table must be homogenous (all values of the same type). In debug
+** mode, we check this on insert and lookup.
+*/
+
+#ifndef UPB_TABLE_H_
+#define UPB_TABLE_H_
+
+#include <stdint.h>
+#include <string.h>
+#include "upb/upb.h"
+
+#include "upb/port_def.inc"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* upb_value ******************************************************************/
+
+/* A tagged union (stored untagged inside the table) so that we can check that
+ * clients calling table accessors are correctly typed without having to have
+ * an explosion of accessors. */
+typedef enum {
+ UPB_CTYPE_INT32 = 1,
+ UPB_CTYPE_INT64 = 2,
+ UPB_CTYPE_UINT32 = 3,
+ UPB_CTYPE_UINT64 = 4,
+ UPB_CTYPE_BOOL = 5,
+ UPB_CTYPE_CSTR = 6,
+ UPB_CTYPE_PTR = 7,
+ UPB_CTYPE_CONSTPTR = 8,
+ UPB_CTYPE_FPTR = 9,
+ UPB_CTYPE_FLOAT = 10,
+ UPB_CTYPE_DOUBLE = 11
+} upb_ctype_t;
+
+typedef struct {
+ uint64_t val;
+} upb_value;
+
+/* Like strdup(), which isn't always available since it's not ANSI C. */
+char *upb_strdup(const char *s, upb_alloc *a);
+/* Variant that works with a length-delimited rather than NULL-delimited string,
+ * as supported by strtable. */
+char *upb_strdup2(const char *s, size_t len, upb_alloc *a);
+
+UPB_INLINE char *upb_gstrdup(const char *s) {
+ return upb_strdup(s, &upb_alloc_global);
+}
+
UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val) {
- v->val = val;
-}
-
+ v->val = val;
+}
+
UPB_INLINE upb_value _upb_value_val(uint64_t val) {
- upb_value ret;
+ upb_value ret;
_upb_value_setval(&ret, val);
- return ret;
-}
-
-/* For each value ctype, define the following set of functions:
- *
- * // Get/set an int32 from a upb_value.
- * int32_t upb_value_getint32(upb_value val);
- * void upb_value_setint32(upb_value *val, int32_t cval);
- *
- * // Construct a new upb_value from an int32.
- * upb_value upb_value_int32(int32_t val); */
-#define FUNCS(name, membername, type_t, converter, proto_type) \
- UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \
- val->val = (converter)cval; \
- } \
- UPB_INLINE upb_value upb_value_ ## name(type_t val) { \
- upb_value ret; \
- upb_value_set ## name(&ret, val); \
- return ret; \
- } \
- UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
- return (type_t)(converter)val.val; \
- }
-
-FUNCS(int32, int32, int32_t, int32_t, UPB_CTYPE_INT32)
-FUNCS(int64, int64, int64_t, int64_t, UPB_CTYPE_INT64)
-FUNCS(uint32, uint32, uint32_t, uint32_t, UPB_CTYPE_UINT32)
-FUNCS(uint64, uint64, uint64_t, uint64_t, UPB_CTYPE_UINT64)
-FUNCS(bool, _bool, bool, bool, UPB_CTYPE_BOOL)
-FUNCS(cstr, cstr, char*, uintptr_t, UPB_CTYPE_CSTR)
-FUNCS(ptr, ptr, void*, uintptr_t, UPB_CTYPE_PTR)
-FUNCS(constptr, constptr, const void*, uintptr_t, UPB_CTYPE_CONSTPTR)
-FUNCS(fptr, fptr, upb_func*, uintptr_t, UPB_CTYPE_FPTR)
-
-#undef FUNCS
-
-UPB_INLINE void upb_value_setfloat(upb_value *val, float cval) {
- memcpy(&val->val, &cval, sizeof(cval));
-}
-
-UPB_INLINE void upb_value_setdouble(upb_value *val, double cval) {
- memcpy(&val->val, &cval, sizeof(cval));
-}
-
-UPB_INLINE upb_value upb_value_float(float cval) {
- upb_value ret;
- upb_value_setfloat(&ret, cval);
- return ret;
-}
-
-UPB_INLINE upb_value upb_value_double(double cval) {
- upb_value ret;
- upb_value_setdouble(&ret, cval);
- return ret;
-}
-
-#undef SET_TYPE
-
-
-/* upb_tabkey *****************************************************************/
-
-/* Either:
- * 1. an actual integer key, or
- * 2. a pointer to a string prefixed by its uint32_t length, owned by us.
- *
- * ...depending on whether this is a string table or an int table. We would
- * make this a union of those two types, but C89 doesn't support statically
- * initializing a non-first union member. */
-typedef uintptr_t upb_tabkey;
-
-UPB_INLINE char *upb_tabstr(upb_tabkey key, uint32_t *len) {
- char* mem = (char*)key;
- if (len) memcpy(len, mem, sizeof(*len));
- return mem + sizeof(*len);
-}
-
-
-/* upb_tabval *****************************************************************/
-
-typedef struct {
- uint64_t val;
-} upb_tabval;
-
-#define UPB_TABVALUE_EMPTY_INIT {-1}
-
-/* upb_table ******************************************************************/
-
-typedef struct _upb_tabent {
- upb_tabkey key;
- upb_tabval val;
-
- /* Internal chaining. This is const so we can create static initializers for
- * tables. We cast away const sometimes, but *only* when the containing
- * upb_table is known to be non-const. This requires a bit of care, but
- * the subtlety is confined to table.c. */
- const struct _upb_tabent *next;
-} upb_tabent;
-
-typedef struct {
- size_t count; /* Number of entries in the hash part. */
- size_t mask; /* Mask to turn hash value -> bucket. */
- uint8_t size_lg2; /* Size of the hashtable part is 2^size_lg2 entries. */
-
- /* Hash table entries.
- * Making this const isn't entirely accurate; what we really want is for it to
- * have the same const-ness as the table it's inside. But there's no way to
- * declare that in C. So we have to make it const so that we can statically
- * initialize const hash tables. Then we cast away const when we have to.
- */
- const upb_tabent *entries;
-} upb_table;
-
-typedef struct {
- upb_table t;
-} upb_strtable;
-
-typedef struct {
- upb_table t; /* For entries that don't fit in the array part. */
- const upb_tabval *array; /* Array part of the table. See const note above. */
- size_t array_size; /* Array part size. */
- size_t array_count; /* Array part number of elements. */
-} upb_inttable;
-
-#define UPB_ARRAY_EMPTYENT -1
-
-UPB_INLINE size_t upb_table_size(const upb_table *t) {
- if (t->size_lg2 == 0)
- return 0;
- else
- return 1 << t->size_lg2;
-}
-
-/* Internal-only functions, in .h file only out of necessity. */
-UPB_INLINE bool upb_tabent_isempty(const upb_tabent *e) {
- return e->key == 0;
-}
-
-/* Used by some of the unit tests for generic hashing functionality. */
-uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed);
-
-UPB_INLINE uintptr_t upb_intkey(uintptr_t key) {
- return key;
-}
-
-UPB_INLINE uint32_t upb_inthash(uintptr_t key) {
- return (uint32_t)key;
-}
-
-static const upb_tabent *upb_getentry(const upb_table *t, uint32_t hash) {
- return t->entries + (hash & t->mask);
-}
-
-UPB_INLINE bool upb_arrhas(upb_tabval key) {
- return key.val != (uint64_t)-1;
-}
-
-/* Initialize and uninitialize a table, respectively. If memory allocation
- * failed, false is returned that the table is uninitialized. */
-bool upb_inttable_init2(upb_inttable *table, upb_ctype_t ctype, upb_alloc *a);
-bool upb_strtable_init2(upb_strtable *table, upb_ctype_t ctype, upb_alloc *a);
-void upb_inttable_uninit2(upb_inttable *table, upb_alloc *a);
-void upb_strtable_uninit2(upb_strtable *table, upb_alloc *a);
-
-UPB_INLINE bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype) {
- return upb_inttable_init2(table, ctype, &upb_alloc_global);
-}
-
-UPB_INLINE bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype) {
- return upb_strtable_init2(table, ctype, &upb_alloc_global);
-}
-
-UPB_INLINE void upb_inttable_uninit(upb_inttable *table) {
- upb_inttable_uninit2(table, &upb_alloc_global);
-}
-
-UPB_INLINE void upb_strtable_uninit(upb_strtable *table) {
- upb_strtable_uninit2(table, &upb_alloc_global);
-}
-
-/* Returns the number of values in the table. */
-size_t upb_inttable_count(const upb_inttable *t);
-UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) {
- return t->t.count;
-}
-
-void upb_inttable_packedsize(const upb_inttable *t, size_t *size);
-void upb_strtable_packedsize(const upb_strtable *t, size_t *size);
-upb_inttable *upb_inttable_pack(const upb_inttable *t, void *p, size_t *ofs,
- size_t size);
-upb_strtable *upb_strtable_pack(const upb_strtable *t, void *p, size_t *ofs,
- size_t size);
+ return ret;
+}
+
+/* For each value ctype, define the following set of functions:
+ *
+ * // Get/set an int32 from a upb_value.
+ * int32_t upb_value_getint32(upb_value val);
+ * void upb_value_setint32(upb_value *val, int32_t cval);
+ *
+ * // Construct a new upb_value from an int32.
+ * upb_value upb_value_int32(int32_t val); */
+#define FUNCS(name, membername, type_t, converter, proto_type) \
+ UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \
+ val->val = (converter)cval; \
+ } \
+ UPB_INLINE upb_value upb_value_ ## name(type_t val) { \
+ upb_value ret; \
+ upb_value_set ## name(&ret, val); \
+ return ret; \
+ } \
+ UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
+ return (type_t)(converter)val.val; \
+ }
+
+FUNCS(int32, int32, int32_t, int32_t, UPB_CTYPE_INT32)
+FUNCS(int64, int64, int64_t, int64_t, UPB_CTYPE_INT64)
+FUNCS(uint32, uint32, uint32_t, uint32_t, UPB_CTYPE_UINT32)
+FUNCS(uint64, uint64, uint64_t, uint64_t, UPB_CTYPE_UINT64)
+FUNCS(bool, _bool, bool, bool, UPB_CTYPE_BOOL)
+FUNCS(cstr, cstr, char*, uintptr_t, UPB_CTYPE_CSTR)
+FUNCS(ptr, ptr, void*, uintptr_t, UPB_CTYPE_PTR)
+FUNCS(constptr, constptr, const void*, uintptr_t, UPB_CTYPE_CONSTPTR)
+FUNCS(fptr, fptr, upb_func*, uintptr_t, UPB_CTYPE_FPTR)
+
+#undef FUNCS
+
+UPB_INLINE void upb_value_setfloat(upb_value *val, float cval) {
+ memcpy(&val->val, &cval, sizeof(cval));
+}
+
+UPB_INLINE void upb_value_setdouble(upb_value *val, double cval) {
+ memcpy(&val->val, &cval, sizeof(cval));
+}
+
+UPB_INLINE upb_value upb_value_float(float cval) {
+ upb_value ret;
+ upb_value_setfloat(&ret, cval);
+ return ret;
+}
+
+UPB_INLINE upb_value upb_value_double(double cval) {
+ upb_value ret;
+ upb_value_setdouble(&ret, cval);
+ return ret;
+}
+
+#undef SET_TYPE
+
+
+/* upb_tabkey *****************************************************************/
+
+/* Either:
+ * 1. an actual integer key, or
+ * 2. a pointer to a string prefixed by its uint32_t length, owned by us.
+ *
+ * ...depending on whether this is a string table or an int table. We would
+ * make this a union of those two types, but C89 doesn't support statically
+ * initializing a non-first union member. */
+typedef uintptr_t upb_tabkey;
+
+UPB_INLINE char *upb_tabstr(upb_tabkey key, uint32_t *len) {
+ char* mem = (char*)key;
+ if (len) memcpy(len, mem, sizeof(*len));
+ return mem + sizeof(*len);
+}
+
+
+/* upb_tabval *****************************************************************/
+
+typedef struct {
+ uint64_t val;
+} upb_tabval;
+
+#define UPB_TABVALUE_EMPTY_INIT {-1}
+
+/* upb_table ******************************************************************/
+
+typedef struct _upb_tabent {
+ upb_tabkey key;
+ upb_tabval val;
+
+ /* Internal chaining. This is const so we can create static initializers for
+ * tables. We cast away const sometimes, but *only* when the containing
+ * upb_table is known to be non-const. This requires a bit of care, but
+ * the subtlety is confined to table.c. */
+ const struct _upb_tabent *next;
+} upb_tabent;
+
+typedef struct {
+ size_t count; /* Number of entries in the hash part. */
+ size_t mask; /* Mask to turn hash value -> bucket. */
+ uint8_t size_lg2; /* Size of the hashtable part is 2^size_lg2 entries. */
+
+ /* Hash table entries.
+ * Making this const isn't entirely accurate; what we really want is for it to
+ * have the same const-ness as the table it's inside. But there's no way to
+ * declare that in C. So we have to make it const so that we can statically
+ * initialize const hash tables. Then we cast away const when we have to.
+ */
+ const upb_tabent *entries;
+} upb_table;
+
+typedef struct {
+ upb_table t;
+} upb_strtable;
+
+typedef struct {
+ upb_table t; /* For entries that don't fit in the array part. */
+ const upb_tabval *array; /* Array part of the table. See const note above. */
+ size_t array_size; /* Array part size. */
+ size_t array_count; /* Array part number of elements. */
+} upb_inttable;
+
+#define UPB_ARRAY_EMPTYENT -1
+
+UPB_INLINE size_t upb_table_size(const upb_table *t) {
+ if (t->size_lg2 == 0)
+ return 0;
+ else
+ return 1 << t->size_lg2;
+}
+
+/* Internal-only functions, in .h file only out of necessity. */
+UPB_INLINE bool upb_tabent_isempty(const upb_tabent *e) {
+ return e->key == 0;
+}
+
+/* Used by some of the unit tests for generic hashing functionality. */
+uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed);
+
+UPB_INLINE uintptr_t upb_intkey(uintptr_t key) {
+ return key;
+}
+
+UPB_INLINE uint32_t upb_inthash(uintptr_t key) {
+ return (uint32_t)key;
+}
+
+static const upb_tabent *upb_getentry(const upb_table *t, uint32_t hash) {
+ return t->entries + (hash & t->mask);
+}
+
+UPB_INLINE bool upb_arrhas(upb_tabval key) {
+ return key.val != (uint64_t)-1;
+}
+
+/* Initialize and uninitialize a table, respectively. If memory allocation
+ * failed, false is returned that the table is uninitialized. */
+bool upb_inttable_init2(upb_inttable *table, upb_ctype_t ctype, upb_alloc *a);
+bool upb_strtable_init2(upb_strtable *table, upb_ctype_t ctype, upb_alloc *a);
+void upb_inttable_uninit2(upb_inttable *table, upb_alloc *a);
+void upb_strtable_uninit2(upb_strtable *table, upb_alloc *a);
+
+UPB_INLINE bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype) {
+ return upb_inttable_init2(table, ctype, &upb_alloc_global);
+}
+
+UPB_INLINE bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype) {
+ return upb_strtable_init2(table, ctype, &upb_alloc_global);
+}
+
+UPB_INLINE void upb_inttable_uninit(upb_inttable *table) {
+ upb_inttable_uninit2(table, &upb_alloc_global);
+}
+
+UPB_INLINE void upb_strtable_uninit(upb_strtable *table) {
+ upb_strtable_uninit2(table, &upb_alloc_global);
+}
+
+/* Returns the number of values in the table. */
+size_t upb_inttable_count(const upb_inttable *t);
+UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) {
+ return t->t.count;
+}
+
+void upb_inttable_packedsize(const upb_inttable *t, size_t *size);
+void upb_strtable_packedsize(const upb_strtable *t, size_t *size);
+upb_inttable *upb_inttable_pack(const upb_inttable *t, void *p, size_t *ofs,
+ size_t size);
+upb_strtable *upb_strtable_pack(const upb_strtable *t, void *p, size_t *ofs,
+ size_t size);
void upb_strtable_clear(upb_strtable *t);
-
-/* Inserts the given key into the hashtable with the given value. The key must
- * not already exist in the hash table. For string tables, the key must be
- * NULL-terminated, and the table will make an internal copy of the key.
- * Inttables must not insert a value of UINTPTR_MAX.
- *
- * If a table resize was required but memory allocation failed, false is
- * returned and the table is unchanged. */
-bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
- upb_alloc *a);
-bool upb_strtable_insert3(upb_strtable *t, const char *key, size_t len,
- upb_value val, upb_alloc *a);
-
-UPB_INLINE bool upb_inttable_insert(upb_inttable *t, uintptr_t key,
- upb_value val) {
- return upb_inttable_insert2(t, key, val, &upb_alloc_global);
-}
-
-UPB_INLINE bool upb_strtable_insert2(upb_strtable *t, const char *key,
- size_t len, upb_value val) {
- return upb_strtable_insert3(t, key, len, val, &upb_alloc_global);
-}
-
-/* For NULL-terminated strings. */
-UPB_INLINE bool upb_strtable_insert(upb_strtable *t, const char *key,
- upb_value val) {
- return upb_strtable_insert2(t, key, strlen(key), val);
-}
-
-/* Looks up key in this table, returning "true" if the key was found.
- * If v is non-NULL, copies the value for this key into *v. */
-bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v);
-bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
- upb_value *v);
-
-/* For NULL-terminated strings. */
-UPB_INLINE bool upb_strtable_lookup(const upb_strtable *t, const char *key,
- upb_value *v) {
- return upb_strtable_lookup2(t, key, strlen(key), v);
-}
-
-/* Removes an item from the table. Returns true if the remove was successful,
- * and stores the removed item in *val if non-NULL. */
-bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val);
-bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
- upb_value *val, upb_alloc *alloc);
-
-UPB_INLINE bool upb_strtable_remove2(upb_strtable *t, const char *key,
- size_t len, upb_value *val) {
- return upb_strtable_remove3(t, key, len, val, &upb_alloc_global);
-}
-
-/* For NULL-terminated strings. */
-UPB_INLINE bool upb_strtable_remove(upb_strtable *t, const char *key,
- upb_value *v) {
- return upb_strtable_remove2(t, key, strlen(key), v);
-}
-
-/* Updates an existing entry in an inttable. If the entry does not exist,
- * returns false and does nothing. Unlike insert/remove, this does not
- * invalidate iterators. */
-bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val);
-
-/* Convenience routines for inttables with pointer keys. */
-bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
- upb_alloc *a);
-bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val);
-bool upb_inttable_lookupptr(
- const upb_inttable *t, const void *key, upb_value *val);
-
-UPB_INLINE bool upb_inttable_insertptr(upb_inttable *t, const void *key,
- upb_value val) {
- return upb_inttable_insertptr2(t, key, val, &upb_alloc_global);
-}
-
-/* Optimizes the table for the current set of entries, for both memory use and
- * lookup time. Client should call this after all entries have been inserted;
- * inserting more entries is legal, but will likely require a table resize. */
-void upb_inttable_compact2(upb_inttable *t, upb_alloc *a);
-
-UPB_INLINE void upb_inttable_compact(upb_inttable *t) {
- upb_inttable_compact2(t, &upb_alloc_global);
-}
-
-/* A special-case inlinable version of the lookup routine for 32-bit
- * integers. */
-UPB_INLINE bool upb_inttable_lookup32(const upb_inttable *t, uint32_t key,
- upb_value *v) {
- *v = upb_value_int32(0); /* Silence compiler warnings. */
- if (key < t->array_size) {
- upb_tabval arrval = t->array[key];
- if (upb_arrhas(arrval)) {
+
+/* Inserts the given key into the hashtable with the given value. The key must
+ * not already exist in the hash table. For string tables, the key must be
+ * NULL-terminated, and the table will make an internal copy of the key.
+ * Inttables must not insert a value of UINTPTR_MAX.
+ *
+ * If a table resize was required but memory allocation failed, false is
+ * returned and the table is unchanged. */
+bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
+ upb_alloc *a);
+bool upb_strtable_insert3(upb_strtable *t, const char *key, size_t len,
+ upb_value val, upb_alloc *a);
+
+UPB_INLINE bool upb_inttable_insert(upb_inttable *t, uintptr_t key,
+ upb_value val) {
+ return upb_inttable_insert2(t, key, val, &upb_alloc_global);
+}
+
+UPB_INLINE bool upb_strtable_insert2(upb_strtable *t, const char *key,
+ size_t len, upb_value val) {
+ return upb_strtable_insert3(t, key, len, val, &upb_alloc_global);
+}
+
+/* For NULL-terminated strings. */
+UPB_INLINE bool upb_strtable_insert(upb_strtable *t, const char *key,
+ upb_value val) {
+ return upb_strtable_insert2(t, key, strlen(key), val);
+}
+
+/* Looks up key in this table, returning "true" if the key was found.
+ * If v is non-NULL, copies the value for this key into *v. */
+bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v);
+bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
+ upb_value *v);
+
+/* For NULL-terminated strings. */
+UPB_INLINE bool upb_strtable_lookup(const upb_strtable *t, const char *key,
+ upb_value *v) {
+ return upb_strtable_lookup2(t, key, strlen(key), v);
+}
+
+/* Removes an item from the table. Returns true if the remove was successful,
+ * and stores the removed item in *val if non-NULL. */
+bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val);
+bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
+ upb_value *val, upb_alloc *alloc);
+
+UPB_INLINE bool upb_strtable_remove2(upb_strtable *t, const char *key,
+ size_t len, upb_value *val) {
+ return upb_strtable_remove3(t, key, len, val, &upb_alloc_global);
+}
+
+/* For NULL-terminated strings. */
+UPB_INLINE bool upb_strtable_remove(upb_strtable *t, const char *key,
+ upb_value *v) {
+ return upb_strtable_remove2(t, key, strlen(key), v);
+}
+
+/* Updates an existing entry in an inttable. If the entry does not exist,
+ * returns false and does nothing. Unlike insert/remove, this does not
+ * invalidate iterators. */
+bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val);
+
+/* Convenience routines for inttables with pointer keys. */
+bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
+ upb_alloc *a);
+bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val);
+bool upb_inttable_lookupptr(
+ const upb_inttable *t, const void *key, upb_value *val);
+
+UPB_INLINE bool upb_inttable_insertptr(upb_inttable *t, const void *key,
+ upb_value val) {
+ return upb_inttable_insertptr2(t, key, val, &upb_alloc_global);
+}
+
+/* Optimizes the table for the current set of entries, for both memory use and
+ * lookup time. Client should call this after all entries have been inserted;
+ * inserting more entries is legal, but will likely require a table resize. */
+void upb_inttable_compact2(upb_inttable *t, upb_alloc *a);
+
+UPB_INLINE void upb_inttable_compact(upb_inttable *t) {
+ upb_inttable_compact2(t, &upb_alloc_global);
+}
+
+/* A special-case inlinable version of the lookup routine for 32-bit
+ * integers. */
+UPB_INLINE bool upb_inttable_lookup32(const upb_inttable *t, uint32_t key,
+ upb_value *v) {
+ *v = upb_value_int32(0); /* Silence compiler warnings. */
+ if (key < t->array_size) {
+ upb_tabval arrval = t->array[key];
+ if (upb_arrhas(arrval)) {
_upb_value_setval(v, arrval.val);
- return true;
- } else {
- return false;
- }
- } else {
- const upb_tabent *e;
- if (t->t.entries == NULL) return false;
- for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) {
- if ((uint32_t)e->key == key) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ const upb_tabent *e;
+ if (t->t.entries == NULL) return false;
+ for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) {
+ if ((uint32_t)e->key == key) {
_upb_value_setval(v, e->val.val);
- return true;
- }
- if (e->next == NULL) return false;
- }
- }
-}
-
-/* Exposed for testing only. */
-bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a);
-
-/* Iterators ******************************************************************/
-
-/* Iterators for int and string tables. We are subject to some kind of unusual
- * design constraints:
- *
- * For high-level languages:
- * - we must be able to guarantee that we don't crash or corrupt memory even if
- * the program accesses an invalidated iterator.
- *
- * For C++11 range-based for:
- * - iterators must be copyable
- * - iterators must be comparable
- * - it must be possible to construct an "end" value.
- *
- * Iteration order is undefined.
- *
- * Modifying the table invalidates iterators. upb_{str,int}table_done() is
- * guaranteed to work even on an invalidated iterator, as long as the table it
- * is iterating over has not been freed. Calling next() or accessing data from
- * an invalidated iterator yields unspecified elements from the table, but it is
- * guaranteed not to crash and to return real table elements (except when done()
- * is true). */
-
-
-/* upb_strtable_iter **********************************************************/
-
-/* upb_strtable_iter i;
- * upb_strtable_begin(&i, t);
- * for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
- * const char *key = upb_strtable_iter_key(&i);
- * const upb_value val = upb_strtable_iter_value(&i);
- * // ...
- * }
- */
-
-typedef struct {
- const upb_strtable *t;
- size_t index;
-} upb_strtable_iter;
-
-void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t);
-void upb_strtable_next(upb_strtable_iter *i);
-bool upb_strtable_done(const upb_strtable_iter *i);
+ return true;
+ }
+ if (e->next == NULL) return false;
+ }
+ }
+}
+
+/* Exposed for testing only. */
+bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a);
+
+/* Iterators ******************************************************************/
+
+/* Iterators for int and string tables. We are subject to some kind of unusual
+ * design constraints:
+ *
+ * For high-level languages:
+ * - we must be able to guarantee that we don't crash or corrupt memory even if
+ * the program accesses an invalidated iterator.
+ *
+ * For C++11 range-based for:
+ * - iterators must be copyable
+ * - iterators must be comparable
+ * - it must be possible to construct an "end" value.
+ *
+ * Iteration order is undefined.
+ *
+ * Modifying the table invalidates iterators. upb_{str,int}table_done() is
+ * guaranteed to work even on an invalidated iterator, as long as the table it
+ * is iterating over has not been freed. Calling next() or accessing data from
+ * an invalidated iterator yields unspecified elements from the table, but it is
+ * guaranteed not to crash and to return real table elements (except when done()
+ * is true). */
+
+
+/* upb_strtable_iter **********************************************************/
+
+/* upb_strtable_iter i;
+ * upb_strtable_begin(&i, t);
+ * for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ * const char *key = upb_strtable_iter_key(&i);
+ * const upb_value val = upb_strtable_iter_value(&i);
+ * // ...
+ * }
+ */
+
+typedef struct {
+ const upb_strtable *t;
+ size_t index;
+} upb_strtable_iter;
+
+void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t);
+void upb_strtable_next(upb_strtable_iter *i);
+bool upb_strtable_done(const upb_strtable_iter *i);
upb_strview upb_strtable_iter_key(const upb_strtable_iter *i);
-upb_value upb_strtable_iter_value(const upb_strtable_iter *i);
-void upb_strtable_iter_setdone(upb_strtable_iter *i);
-bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
- const upb_strtable_iter *i2);
-
-
-/* upb_inttable_iter **********************************************************/
-
-/* upb_inttable_iter i;
- * upb_inttable_begin(&i, t);
- * for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
- * uintptr_t key = upb_inttable_iter_key(&i);
- * upb_value val = upb_inttable_iter_value(&i);
- * // ...
- * }
- */
-
-typedef struct {
- const upb_inttable *t;
- size_t index;
- bool array_part;
-} upb_inttable_iter;
-
+upb_value upb_strtable_iter_value(const upb_strtable_iter *i);
+void upb_strtable_iter_setdone(upb_strtable_iter *i);
+bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
+ const upb_strtable_iter *i2);
+
+
+/* upb_inttable_iter **********************************************************/
+
+/* upb_inttable_iter i;
+ * upb_inttable_begin(&i, t);
+ * for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ * uintptr_t key = upb_inttable_iter_key(&i);
+ * upb_value val = upb_inttable_iter_value(&i);
+ * // ...
+ * }
+ */
+
+typedef struct {
+ const upb_inttable *t;
+ size_t index;
+ bool array_part;
+} upb_inttable_iter;
+
UPB_INLINE const upb_tabent *str_tabent(const upb_strtable_iter *i) {
return &i->t->t.entries[i->index];
}
-void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t);
-void upb_inttable_next(upb_inttable_iter *i);
-bool upb_inttable_done(const upb_inttable_iter *i);
-uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i);
-upb_value upb_inttable_iter_value(const upb_inttable_iter *i);
-void upb_inttable_iter_setdone(upb_inttable_iter *i);
-bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
- const upb_inttable_iter *i2);
-
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include "upb/port_undef.inc"
-
-#endif /* UPB_TABLE_H_ */
+void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t);
+void upb_inttable_next(upb_inttable_iter *i);
+bool upb_inttable_done(const upb_inttable_iter *i);
+uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i);
+upb_value upb_inttable_iter_value(const upb_inttable_iter *i);
+void upb_inttable_iter_setdone(upb_inttable_iter *i);
+bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
+ const upb_inttable_iter *i2);
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include "upb/port_undef.inc"
+
+#endif /* UPB_TABLE_H_ */
diff --git a/contrib/libs/grpc/third_party/upb/upb/upb.c b/contrib/libs/grpc/third_party/upb/upb/upb.c
index 3089c059e1..916ef235fe 100644
--- a/contrib/libs/grpc/third_party/upb/upb/upb.c
+++ b/contrib/libs/grpc/third_party/upb/upb/upb.c
@@ -1,49 +1,49 @@
-
-#include "upb/upb.h"
-
-#include <errno.h>
-#include <stdarg.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "upb/port_def.inc"
-
-/* upb_status *****************************************************************/
-
-void upb_status_clear(upb_status *status) {
- if (!status) return;
- status->ok = true;
- status->msg[0] = '\0';
-}
-
-bool upb_ok(const upb_status *status) { return status->ok; }
-
-const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
-
-void upb_status_seterrmsg(upb_status *status, const char *msg) {
- if (!status) return;
- status->ok = false;
+
+#include "upb/upb.h"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "upb/port_def.inc"
+
+/* upb_status *****************************************************************/
+
+void upb_status_clear(upb_status *status) {
+ if (!status) return;
+ status->ok = true;
+ status->msg[0] = '\0';
+}
+
+bool upb_ok(const upb_status *status) { return status->ok; }
+
+const char *upb_status_errmsg(const upb_status *status) { return status->msg; }
+
+void upb_status_seterrmsg(upb_status *status, const char *msg) {
+ if (!status) return;
+ status->ok = false;
strncpy(status->msg, msg, UPB_STATUS_MAX_MESSAGE - 1);
status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
-}
-
-void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
- va_list args;
- va_start(args, fmt);
- upb_status_vseterrf(status, fmt, args);
- va_end(args);
-}
-
-void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
- if (!status) return;
- status->ok = false;
- _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
+}
+
+void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
+ va_list args;
+ va_start(args, fmt);
+ upb_status_vseterrf(status, fmt, args);
+ va_end(args);
+}
+
+void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
+ if (!status) return;
+ status->ok = false;
+ _upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
-}
-
+}
+
void upb_status_vappenderrf(upb_status *status, const char *fmt, va_list args) {
size_t len;
if (!status) return;
@@ -53,59 +53,59 @@ void upb_status_vappenderrf(upb_status *status, const char *fmt, va_list args) {
status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
}
-/* upb_alloc ******************************************************************/
-
-static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
- size_t size) {
- UPB_UNUSED(alloc);
- UPB_UNUSED(oldsize);
- if (size == 0) {
- free(ptr);
- return NULL;
- } else {
- return realloc(ptr, size);
- }
-}
-
-upb_alloc upb_alloc_global = {&upb_global_allocfunc};
-
-/* upb_arena ******************************************************************/
-
-/* Be conservative and choose 16 in case anyone is using SSE. */
-
+/* upb_alloc ******************************************************************/
+
+static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size) {
+ UPB_UNUSED(alloc);
+ UPB_UNUSED(oldsize);
+ if (size == 0) {
+ free(ptr);
+ return NULL;
+ } else {
+ return realloc(ptr, size);
+ }
+}
+
+upb_alloc upb_alloc_global = {&upb_global_allocfunc};
+
+/* upb_arena ******************************************************************/
+
+/* Be conservative and choose 16 in case anyone is using SSE. */
+
typedef struct mem_block {
struct mem_block *next;
uint32_t size;
uint32_t cleanups;
/* Data follows. */
} mem_block;
-
+
typedef struct cleanup_ent {
upb_cleanup_func *cleanup;
void *ud;
} cleanup_ent;
-struct upb_arena {
+struct upb_arena {
_upb_arena_head head;
uint32_t *cleanups;
-
- /* Allocator to allocate arena blocks. We are responsible for freeing these
- * when we are destroyed. */
- upb_alloc *block_alloc;
+
+ /* Allocator to allocate arena blocks. We are responsible for freeing these
+ * when we are destroyed. */
+ upb_alloc *block_alloc;
uint32_t last_size;
-
+
/* When multiple arenas are fused together, each arena points to a parent
* arena (root points to itself). The root tracks how many live arenas
* reference it. */
uint32_t refcount; /* Only used when a->parent == a */
struct upb_arena *parent;
-
+
/* Linked list of blocks to free/cleanup. */
mem_block *freelist, *freelist_tail;
-};
-
+};
+
static const size_t memblock_reserve = UPB_ALIGN_UP(sizeof(mem_block), 16);
-
+
static upb_arena *arena_findroot(upb_arena *a) {
/* Path splitting keeps time complexity down, see:
* https://en.wikipedia.org/wiki/Disjoint-set_data_structure */
@@ -116,11 +116,11 @@ static upb_arena *arena_findroot(upb_arena *a) {
}
return a;
}
-
+
static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size) {
- mem_block *block = ptr;
+ mem_block *block = ptr;
upb_arena *root = arena_findroot(a);
-
+
/* The block is for arena |a|, but should appear in the freelist of |root|. */
block->next = root->freelist;
block->size = (uint32_t)size;
@@ -128,83 +128,83 @@ static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size) {
root->freelist = block;
a->last_size = block->size;
if (!root->freelist_tail) root->freelist_tail = block;
-
+
a->head.ptr = UPB_PTR_AT(block, memblock_reserve, char);
a->head.end = UPB_PTR_AT(block, size, char);
a->cleanups = &block->cleanups;
-
- /* TODO(haberman): ASAN poison. */
-}
-
+
+ /* TODO(haberman): ASAN poison. */
+}
+
static bool upb_arena_allocblock(upb_arena *a, size_t size) {
size_t block_size = UPB_MAX(size, a->last_size * 2) + memblock_reserve;
- mem_block *block = upb_malloc(a->block_alloc, block_size);
-
+ mem_block *block = upb_malloc(a->block_alloc, block_size);
+
if (!block) return false;
upb_arena_addblock(a, block, block_size);
return true;
}
-
+
static bool arena_has(upb_arena *a, size_t size) {
_upb_arena_head *h = (_upb_arena_head*)a;
return (size_t)(h->end - h->ptr) >= size;
}
-
+
void *_upb_arena_slowmalloc(upb_arena *a, size_t size) {
if (!upb_arena_allocblock(a, size)) return NULL; /* Out of memory. */
UPB_ASSERT(arena_has(a, size));
return upb_arena_malloc(a, size);
-}
-
-static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
- size_t size) {
- upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
+}
+
+static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size) {
+ upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
return upb_arena_realloc(a, ptr, oldsize, size);
}
-
+
/* Public Arena API ***********************************************************/
-
+
upb_arena *arena_initslow(void *mem, size_t n, upb_alloc *alloc) {
const size_t first_block_overhead = sizeof(upb_arena) + memblock_reserve;
upb_arena *a;
-
+
/* We need to malloc the initial block. */
n = first_block_overhead + 256;
if (!alloc || !(mem = upb_malloc(alloc, n))) {
return NULL;
- }
-
+ }
+
a = UPB_PTR_AT(mem, n - sizeof(*a), upb_arena);
n -= sizeof(*a);
-
+
a->head.alloc.func = &upb_arena_doalloc;
a->block_alloc = alloc;
a->parent = a;
a->refcount = 1;
a->freelist = NULL;
a->freelist_tail = NULL;
-
+
upb_arena_addblock(a, mem, n);
-
+
return a;
-}
-
-upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
- upb_arena *a;
-
- /* Round block size down to alignof(*a) since we will allocate the arena
- * itself at the end. */
+}
+
+upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
+ upb_arena *a;
+
+ /* Round block size down to alignof(*a) since we will allocate the arena
+ * itself at the end. */
n = UPB_ALIGN_DOWN(n, UPB_ALIGN_OF(upb_arena));
-
+
if (UPB_UNLIKELY(n < sizeof(upb_arena))) {
return arena_initslow(mem, n, alloc);
- }
-
+ }
+
a = UPB_PTR_AT(mem, n - sizeof(*a), upb_arena);
- n -= sizeof(*a);
-
+ n -= sizeof(*a);
+
a->head.alloc.func = &upb_arena_doalloc;
- a->block_alloc = alloc;
+ a->block_alloc = alloc;
a->parent = a;
a->refcount = 1;
a->last_size = 128;
@@ -212,19 +212,19 @@ upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
a->head.end = UPB_PTR_AT(mem, n, char);
a->freelist = NULL;
a->cleanups = NULL;
-
- return a;
-}
-
+
+ return a;
+}
+
static void arena_dofree(upb_arena *a) {
mem_block *block = a->freelist;
UPB_ASSERT(a->parent == a);
UPB_ASSERT(a->refcount == 0);
-
- while (block) {
- /* Load first since we are deleting block. */
- mem_block *next = block->next;
-
+
+ while (block) {
+ /* Load first since we are deleting block. */
+ mem_block *next = block->next;
+
if (block->cleanups > 0) {
cleanup_ent *end = UPB_PTR_AT(block, block->size, void);
cleanup_ent *ptr = end - block->cleanups;
@@ -232,36 +232,36 @@ static void arena_dofree(upb_arena *a) {
for (; ptr < end; ptr++) {
ptr->cleanup(ptr->ud);
}
- }
-
+ }
+
upb_free(a->block_alloc, block);
- block = next;
- }
-}
-
+ block = next;
+ }
+}
+
void upb_arena_free(upb_arena *a) {
a = arena_findroot(a);
if (--a->refcount == 0) arena_dofree(a);
}
-bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
+bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
cleanup_ent *ent;
if (!a->cleanups || !arena_has(a, sizeof(cleanup_ent))) {
if (!upb_arena_allocblock(a, 128)) return false; /* Out of memory. */
UPB_ASSERT(arena_has(a, sizeof(cleanup_ent)));
- }
-
+ }
+
a->head.end -= sizeof(cleanup_ent);
ent = (cleanup_ent*)a->head.end;
(*a->cleanups)++;
- ent->cleanup = func;
- ent->ud = ud;
-
- return true;
-}
-
+ ent->cleanup = func;
+ ent->ud = ud;
+
+ return true;
+}
+
void upb_arena_fuse(upb_arena *a1, upb_arena *a2) {
upb_arena *r1 = arena_findroot(a1);
upb_arena *r2 = arena_findroot(a2);
@@ -284,4 +284,4 @@ void upb_arena_fuse(upb_arena *a1, upb_arena *a2) {
r1->freelist = r2->freelist;
}
r2->parent = r1;
-}
+}
diff --git a/contrib/libs/grpc/third_party/upb/upb/upb.h b/contrib/libs/grpc/third_party/upb/upb/upb.h
index e1d9d8cfd3..f032adac9d 100644
--- a/contrib/libs/grpc/third_party/upb/upb/upb.h
+++ b/contrib/libs/grpc/third_party/upb/upb/upb.h
@@ -1,171 +1,171 @@
-/*
-** This file contains shared definitions that are widely used across upb.
-*/
-
-#ifndef UPB_H_
-#define UPB_H_
-
-#include <assert.h>
-#include <stdarg.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
+/*
+** This file contains shared definitions that are widely used across upb.
+*/
+
+#ifndef UPB_H_
+#define UPB_H_
+
+#include <assert.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
#include "upb/port_def.inc"
-#ifdef __cplusplus
+#ifdef __cplusplus
extern "C" {
-#endif
-
-/* upb_status *****************************************************************/
-
-#define UPB_STATUS_MAX_MESSAGE 127
-
-typedef struct {
- bool ok;
- char msg[UPB_STATUS_MAX_MESSAGE]; /* Error message; NULL-terminated. */
-} upb_status;
-
-const char *upb_status_errmsg(const upb_status *status);
-bool upb_ok(const upb_status *status);
-
+#endif
+
+/* upb_status *****************************************************************/
+
+#define UPB_STATUS_MAX_MESSAGE 127
+
+typedef struct {
+ bool ok;
+ char msg[UPB_STATUS_MAX_MESSAGE]; /* Error message; NULL-terminated. */
+} upb_status;
+
+const char *upb_status_errmsg(const upb_status *status);
+bool upb_ok(const upb_status *status);
+
/* These are no-op if |status| is NULL. */
-void upb_status_clear(upb_status *status);
-void upb_status_seterrmsg(upb_status *status, const char *msg);
-void upb_status_seterrf(upb_status *status, const char *fmt, ...);
-void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args);
+void upb_status_clear(upb_status *status);
+void upb_status_seterrmsg(upb_status *status, const char *msg);
+void upb_status_seterrf(upb_status *status, const char *fmt, ...);
+void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args);
void upb_status_vappenderrf(upb_status *status, const char *fmt, va_list args);
-
-/** upb_strview ************************************************************/
-
-typedef struct {
- const char *data;
- size_t size;
-} upb_strview;
-
-UPB_INLINE upb_strview upb_strview_make(const char *data, size_t size) {
- upb_strview ret;
- ret.data = data;
- ret.size = size;
- return ret;
-}
-
-UPB_INLINE upb_strview upb_strview_makez(const char *data) {
- return upb_strview_make(data, strlen(data));
-}
-
-UPB_INLINE bool upb_strview_eql(upb_strview a, upb_strview b) {
- return a.size == b.size && memcmp(a.data, b.data, a.size) == 0;
-}
-
-#define UPB_STRVIEW_INIT(ptr, len) {ptr, len}
-
-#define UPB_STRVIEW_FORMAT "%.*s"
-#define UPB_STRVIEW_ARGS(view) (int)(view).size, (view).data
-
-/** upb_alloc *****************************************************************/
-
-/* A upb_alloc is a possibly-stateful allocator object.
- *
- * It could either be an arena allocator (which doesn't require individual
- * free() calls) or a regular malloc() (which does). The client must therefore
- * free memory unless it knows that the allocator is an arena allocator. */
-
-struct upb_alloc;
-typedef struct upb_alloc upb_alloc;
-
-/* A malloc()/free() function.
- * If "size" is 0 then the function acts like free(), otherwise it acts like
- * realloc(). Only "oldsize" bytes from a previous allocation are preserved. */
-typedef void *upb_alloc_func(upb_alloc *alloc, void *ptr, size_t oldsize,
- size_t size);
-
-struct upb_alloc {
- upb_alloc_func *func;
-};
-
-UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) {
- UPB_ASSERT(alloc);
- return alloc->func(alloc, NULL, 0, size);
-}
-
-UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize,
- size_t size) {
- UPB_ASSERT(alloc);
- return alloc->func(alloc, ptr, oldsize, size);
-}
-
-UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) {
- assert(alloc);
- alloc->func(alloc, ptr, 0, 0);
-}
-
-/* The global allocator used by upb. Uses the standard malloc()/free(). */
-
-extern upb_alloc upb_alloc_global;
-
-/* Functions that hard-code the global malloc.
- *
- * We still get benefit because we can put custom logic into our global
- * allocator, like injecting out-of-memory faults in debug/testing builds. */
-
-UPB_INLINE void *upb_gmalloc(size_t size) {
- return upb_malloc(&upb_alloc_global, size);
-}
-
-UPB_INLINE void *upb_grealloc(void *ptr, size_t oldsize, size_t size) {
- return upb_realloc(&upb_alloc_global, ptr, oldsize, size);
-}
-
-UPB_INLINE void upb_gfree(void *ptr) {
- upb_free(&upb_alloc_global, ptr);
-}
-
-/* upb_arena ******************************************************************/
-
-/* upb_arena is a specific allocator implementation that uses arena allocation.
- * The user provides an allocator that will be used to allocate the underlying
- * arena blocks. Arenas by nature do not require the individual allocations
- * to be freed. However the Arena does allow users to register cleanup
- * functions that will run when the arena is destroyed.
- *
- * A upb_arena is *not* thread-safe.
- *
- * You could write a thread-safe arena allocator that satisfies the
- * upb_alloc interface, but it would not be as efficient for the
- * single-threaded case. */
-
-typedef void upb_cleanup_func(void *ud);
-
-struct upb_arena;
-typedef struct upb_arena upb_arena;
-
+
+/** upb_strview ************************************************************/
+
+typedef struct {
+ const char *data;
+ size_t size;
+} upb_strview;
+
+UPB_INLINE upb_strview upb_strview_make(const char *data, size_t size) {
+ upb_strview ret;
+ ret.data = data;
+ ret.size = size;
+ return ret;
+}
+
+UPB_INLINE upb_strview upb_strview_makez(const char *data) {
+ return upb_strview_make(data, strlen(data));
+}
+
+UPB_INLINE bool upb_strview_eql(upb_strview a, upb_strview b) {
+ return a.size == b.size && memcmp(a.data, b.data, a.size) == 0;
+}
+
+#define UPB_STRVIEW_INIT(ptr, len) {ptr, len}
+
+#define UPB_STRVIEW_FORMAT "%.*s"
+#define UPB_STRVIEW_ARGS(view) (int)(view).size, (view).data
+
+/** upb_alloc *****************************************************************/
+
+/* A upb_alloc is a possibly-stateful allocator object.
+ *
+ * It could either be an arena allocator (which doesn't require individual
+ * free() calls) or a regular malloc() (which does). The client must therefore
+ * free memory unless it knows that the allocator is an arena allocator. */
+
+struct upb_alloc;
+typedef struct upb_alloc upb_alloc;
+
+/* A malloc()/free() function.
+ * If "size" is 0 then the function acts like free(), otherwise it acts like
+ * realloc(). Only "oldsize" bytes from a previous allocation are preserved. */
+typedef void *upb_alloc_func(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size);
+
+struct upb_alloc {
+ upb_alloc_func *func;
+};
+
+UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) {
+ UPB_ASSERT(alloc);
+ return alloc->func(alloc, NULL, 0, size);
+}
+
+UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size) {
+ UPB_ASSERT(alloc);
+ return alloc->func(alloc, ptr, oldsize, size);
+}
+
+UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) {
+ assert(alloc);
+ alloc->func(alloc, ptr, 0, 0);
+}
+
+/* The global allocator used by upb. Uses the standard malloc()/free(). */
+
+extern upb_alloc upb_alloc_global;
+
+/* Functions that hard-code the global malloc.
+ *
+ * We still get benefit because we can put custom logic into our global
+ * allocator, like injecting out-of-memory faults in debug/testing builds. */
+
+UPB_INLINE void *upb_gmalloc(size_t size) {
+ return upb_malloc(&upb_alloc_global, size);
+}
+
+UPB_INLINE void *upb_grealloc(void *ptr, size_t oldsize, size_t size) {
+ return upb_realloc(&upb_alloc_global, ptr, oldsize, size);
+}
+
+UPB_INLINE void upb_gfree(void *ptr) {
+ upb_free(&upb_alloc_global, ptr);
+}
+
+/* upb_arena ******************************************************************/
+
+/* upb_arena is a specific allocator implementation that uses arena allocation.
+ * The user provides an allocator that will be used to allocate the underlying
+ * arena blocks. Arenas by nature do not require the individual allocations
+ * to be freed. However the Arena does allow users to register cleanup
+ * functions that will run when the arena is destroyed.
+ *
+ * A upb_arena is *not* thread-safe.
+ *
+ * You could write a thread-safe arena allocator that satisfies the
+ * upb_alloc interface, but it would not be as efficient for the
+ * single-threaded case. */
+
+typedef void upb_cleanup_func(void *ud);
+
+struct upb_arena;
+typedef struct upb_arena upb_arena;
+
typedef struct {
/* We implement the allocator interface.
* This must be the first member of upb_arena!
* TODO(haberman): remove once handlers are gone. */
upb_alloc alloc;
-
+
char *ptr, *end;
} _upb_arena_head;
-/* Creates an arena from the given initial block (if any -- n may be 0).
- * Additional blocks will be allocated from |alloc|. If |alloc| is NULL, this
- * is a fixed-size arena and cannot grow. */
-upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc);
-void upb_arena_free(upb_arena *a);
-bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func);
+/* Creates an arena from the given initial block (if any -- n may be 0).
+ * Additional blocks will be allocated from |alloc|. If |alloc| is NULL, this
+ * is a fixed-size arena and cannot grow. */
+upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc);
+void upb_arena_free(upb_arena *a);
+bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func);
void upb_arena_fuse(upb_arena *a, upb_arena *b);
void *_upb_arena_slowmalloc(upb_arena *a, size_t size);
-
-UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; }
-
+
+UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; }
+
UPB_INLINE void *upb_arena_malloc(upb_arena *a, size_t size) {
_upb_arena_head *h = (_upb_arena_head*)a;
void* ret;
size = UPB_ALIGN_MALLOC(size);
-
+
if (UPB_UNLIKELY((size_t)(h->end - h->ptr) < size)) {
return _upb_arena_slowmalloc(a, size);
}
@@ -173,10 +173,10 @@ UPB_INLINE void *upb_arena_malloc(upb_arena *a, size_t size) {
ret = h->ptr;
h->ptr += size;
return ret;
-}
-
-UPB_INLINE void *upb_arena_realloc(upb_arena *a, void *ptr, size_t oldsize,
- size_t size) {
+}
+
+UPB_INLINE void *upb_arena_realloc(upb_arena *a, void *ptr, size_t oldsize,
+ size_t size) {
void *ret = upb_arena_malloc(a, size);
if (ret && oldsize > 0) {
@@ -184,71 +184,71 @@ UPB_INLINE void *upb_arena_realloc(upb_arena *a, void *ptr, size_t oldsize,
}
return ret;
-}
-
-UPB_INLINE upb_arena *upb_arena_new(void) {
- return upb_arena_init(NULL, 0, &upb_alloc_global);
-}
-
-/* Constants ******************************************************************/
-
-/* Generic function type. */
-typedef void upb_func(void);
-
-/* A list of types as they are encoded on-the-wire. */
-typedef enum {
- UPB_WIRE_TYPE_VARINT = 0,
- UPB_WIRE_TYPE_64BIT = 1,
- UPB_WIRE_TYPE_DELIMITED = 2,
- UPB_WIRE_TYPE_START_GROUP = 3,
- UPB_WIRE_TYPE_END_GROUP = 4,
- UPB_WIRE_TYPE_32BIT = 5
-} upb_wiretype_t;
-
-/* The types a field can have. Note that this list is not identical to the
- * types defined in descriptor.proto, which gives INT32 and SINT32 separate
- * types (we distinguish the two with the "integer encoding" enum below). */
-typedef enum {
- UPB_TYPE_BOOL = 1,
- UPB_TYPE_FLOAT = 2,
- UPB_TYPE_INT32 = 3,
- UPB_TYPE_UINT32 = 4,
- UPB_TYPE_ENUM = 5, /* Enum values are int32. */
+}
+
+UPB_INLINE upb_arena *upb_arena_new(void) {
+ return upb_arena_init(NULL, 0, &upb_alloc_global);
+}
+
+/* Constants ******************************************************************/
+
+/* Generic function type. */
+typedef void upb_func(void);
+
+/* A list of types as they are encoded on-the-wire. */
+typedef enum {
+ UPB_WIRE_TYPE_VARINT = 0,
+ UPB_WIRE_TYPE_64BIT = 1,
+ UPB_WIRE_TYPE_DELIMITED = 2,
+ UPB_WIRE_TYPE_START_GROUP = 3,
+ UPB_WIRE_TYPE_END_GROUP = 4,
+ UPB_WIRE_TYPE_32BIT = 5
+} upb_wiretype_t;
+
+/* The types a field can have. Note that this list is not identical to the
+ * types defined in descriptor.proto, which gives INT32 and SINT32 separate
+ * types (we distinguish the two with the "integer encoding" enum below). */
+typedef enum {
+ UPB_TYPE_BOOL = 1,
+ UPB_TYPE_FLOAT = 2,
+ UPB_TYPE_INT32 = 3,
+ UPB_TYPE_UINT32 = 4,
+ UPB_TYPE_ENUM = 5, /* Enum values are int32. */
UPB_TYPE_MESSAGE = 6,
UPB_TYPE_DOUBLE = 7,
UPB_TYPE_INT64 = 8,
UPB_TYPE_UINT64 = 9,
UPB_TYPE_STRING = 10,
UPB_TYPE_BYTES = 11
-} upb_fieldtype_t;
-
-/* The repeated-ness of each field; this matches descriptor.proto. */
-typedef enum {
- UPB_LABEL_OPTIONAL = 1,
- UPB_LABEL_REQUIRED = 2,
- UPB_LABEL_REPEATED = 3
-} upb_label_t;
-
-/* Descriptor types, as defined in descriptor.proto. */
-typedef enum {
+} upb_fieldtype_t;
+
+/* The repeated-ness of each field; this matches descriptor.proto. */
+typedef enum {
+ UPB_LABEL_OPTIONAL = 1,
+ UPB_LABEL_REQUIRED = 2,
+ UPB_LABEL_REPEATED = 3
+} upb_label_t;
+
+/* Descriptor types, as defined in descriptor.proto. */
+typedef enum {
/* Old (long) names. TODO(haberman): remove */
- UPB_DESCRIPTOR_TYPE_DOUBLE = 1,
- UPB_DESCRIPTOR_TYPE_FLOAT = 2,
- UPB_DESCRIPTOR_TYPE_INT64 = 3,
- UPB_DESCRIPTOR_TYPE_UINT64 = 4,
- UPB_DESCRIPTOR_TYPE_INT32 = 5,
- UPB_DESCRIPTOR_TYPE_FIXED64 = 6,
- UPB_DESCRIPTOR_TYPE_FIXED32 = 7,
- UPB_DESCRIPTOR_TYPE_BOOL = 8,
- UPB_DESCRIPTOR_TYPE_STRING = 9,
- UPB_DESCRIPTOR_TYPE_GROUP = 10,
- UPB_DESCRIPTOR_TYPE_MESSAGE = 11,
- UPB_DESCRIPTOR_TYPE_BYTES = 12,
- UPB_DESCRIPTOR_TYPE_UINT32 = 13,
- UPB_DESCRIPTOR_TYPE_ENUM = 14,
- UPB_DESCRIPTOR_TYPE_SFIXED32 = 15,
- UPB_DESCRIPTOR_TYPE_SFIXED64 = 16,
- UPB_DESCRIPTOR_TYPE_SINT32 = 17,
+ UPB_DESCRIPTOR_TYPE_DOUBLE = 1,
+ UPB_DESCRIPTOR_TYPE_FLOAT = 2,
+ UPB_DESCRIPTOR_TYPE_INT64 = 3,
+ UPB_DESCRIPTOR_TYPE_UINT64 = 4,
+ UPB_DESCRIPTOR_TYPE_INT32 = 5,
+ UPB_DESCRIPTOR_TYPE_FIXED64 = 6,
+ UPB_DESCRIPTOR_TYPE_FIXED32 = 7,
+ UPB_DESCRIPTOR_TYPE_BOOL = 8,
+ UPB_DESCRIPTOR_TYPE_STRING = 9,
+ UPB_DESCRIPTOR_TYPE_GROUP = 10,
+ UPB_DESCRIPTOR_TYPE_MESSAGE = 11,
+ UPB_DESCRIPTOR_TYPE_BYTES = 12,
+ UPB_DESCRIPTOR_TYPE_UINT32 = 13,
+ UPB_DESCRIPTOR_TYPE_ENUM = 14,
+ UPB_DESCRIPTOR_TYPE_SFIXED32 = 15,
+ UPB_DESCRIPTOR_TYPE_SFIXED64 = 16,
+ UPB_DESCRIPTOR_TYPE_SINT32 = 17,
UPB_DESCRIPTOR_TYPE_SINT64 = 18,
UPB_DTYPE_DOUBLE = 1,
@@ -269,10 +269,10 @@ typedef enum {
UPB_DTYPE_SFIXED64 = 16,
UPB_DTYPE_SINT32 = 17,
UPB_DTYPE_SINT64 = 18
-} upb_descriptortype_t;
-
+} upb_descriptortype_t;
+
#define UPB_MAP_BEGIN ((size_t)-1)
-
+
UPB_INLINE bool _upb_isle(void) {
int x = 1;
return *(char*)&x == 1;
@@ -299,10 +299,10 @@ UPB_INLINE uint64_t _upb_be_swap64(uint64_t val) {
}
}
-#include "upb/port_undef.inc"
-
+#include "upb/port_undef.inc"
+
#ifdef __cplusplus
} /* extern "C" */
#endif
-#endif /* UPB_H_ */
+#endif /* UPB_H_ */
diff --git a/contrib/libs/grpc/third_party/upb/ya.make b/contrib/libs/grpc/third_party/upb/ya.make
index 1dc7487601..9b0df6b95e 100644
--- a/contrib/libs/grpc/third_party/upb/ya.make
+++ b/contrib/libs/grpc/third_party/upb/ya.make
@@ -1,9 +1,9 @@
-# Generated by devtools/yamaker.
-
-LIBRARY()
-
+# Generated by devtools/yamaker.
+
+LIBRARY()
+
OWNER(g:cpp-contrib)
-
+
LICENSE(
BSD-3-Clause AND
Public-Domain
@@ -11,29 +11,29 @@ LICENSE(
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-ADDINCL(
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/third_party/upb
-)
-
-NO_COMPILER_WARNINGS()
-
+ contrib/libs/grpc
+ contrib/libs/grpc/third_party/upb
+)
+
+NO_COMPILER_WARNINGS()
+
NO_RUNTIME()
-IF (OS_LINUX OR OS_DARWIN)
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
+ENDIF()
+
+SRCS(
upb/decode.c
upb/encode.c
upb/msg.c
upb/port.c
upb/table.c
upb/upb.c
-)
-
-END()
+)
+
+END()
diff --git a/contrib/libs/grpc/tools/README.md b/contrib/libs/grpc/tools/README.md
index 3cef618179..baef04a0b5 100644
--- a/contrib/libs/grpc/tools/README.md
+++ b/contrib/libs/grpc/tools/README.md
@@ -1,23 +1,23 @@
-buildgen: Template renderer for our build system.
-
-distrib: Scripts to distribute language-specific packages and other distribution-related helper scripts.
-
-dockerfile: Docker files to test gRPC.
-
-doxygen: gRPC C/C++ documentation generation via Doxygen.
-
-gce: Scripts to help setup testing infrastructure on GCE.
-
-gcp: Helper scripts for interacting with various services on GCP (like Google
-container engine, BigQuery etc)
-
-internal_ci: Support for running tests on an internal CI platform.
-
-interop_matrix: Scripts to build, upload, and run gRPC clients in docker with various language/runtimes.
-
-jenkins: Support for running tests on Jenkins.
-
-run_tests: Scripts to run gRPC tests in parallel.
-
-run_tests/performance: See the [README](./run_tests/performance/README.md) for
-more notes on the performance tests.
+buildgen: Template renderer for our build system.
+
+distrib: Scripts to distribute language-specific packages and other distribution-related helper scripts.
+
+dockerfile: Docker files to test gRPC.
+
+doxygen: gRPC C/C++ documentation generation via Doxygen.
+
+gce: Scripts to help setup testing infrastructure on GCE.
+
+gcp: Helper scripts for interacting with various services on GCP (like Google
+container engine, BigQuery etc)
+
+internal_ci: Support for running tests on an internal CI platform.
+
+interop_matrix: Scripts to build, upload, and run gRPC clients in docker with various language/runtimes.
+
+jenkins: Support for running tests on Jenkins.
+
+run_tests: Scripts to run gRPC tests in parallel.
+
+run_tests/performance: See the [README](./run_tests/performance/README.md) for
+more notes on the performance tests.
diff --git a/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables.cc b/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables.cc
index 0e7a7b80d8..10dcce66a8 100644
--- a/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables.cc
+++ b/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables.cc
@@ -1,353 +1,353 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-/* generates constant tables for hpack.cc */
-
-#include <assert.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/support/log.h>
-#include "src/core/ext/transport/chttp2/transport/huffsyms.h"
-
-/*
- * first byte LUT generation
- */
-
-typedef struct {
- const char *call;
- /* bit prefix for the field type */
- unsigned char prefix;
- /* length of the bit prefix for the field type */
- unsigned char prefix_length;
- /* index value: 0 = all zeros, 2 = all ones, 1 otherwise */
- unsigned char index;
-} spec;
-
-static const spec fields[] = {
- {"INDEXED_FIELD", 0X80, 1, 1}, {"INDEXED_FIELD_X", 0X80, 1, 2},
- {"LITHDR_INCIDX", 0X40, 2, 1}, {"LITHDR_INCIDX_X", 0X40, 2, 2},
- {"LITHDR_INCIDX_V", 0X40, 2, 0}, {"LITHDR_NOTIDX", 0X00, 4, 1},
- {"LITHDR_NOTIDX_X", 0X00, 4, 2}, {"LITHDR_NOTIDX_V", 0X00, 4, 0},
- {"LITHDR_NVRIDX", 0X10, 4, 1}, {"LITHDR_NVRIDX_X", 0X10, 4, 2},
- {"LITHDR_NVRIDX_V", 0X10, 4, 0}, {"MAX_TBL_SIZE", 0X20, 3, 1},
- {"MAX_TBL_SIZE_X", 0X20, 3, 2},
-};
-
-static const int num_fields = sizeof(fields) / sizeof(*fields);
-
-static unsigned char prefix_mask(unsigned char prefix_len) {
- unsigned char i;
- unsigned char out = 0;
- for (i = 0; i < prefix_len; i++) {
- /* NB: the following integer arithmetic operation needs to be in its
- * expanded form due to the "integral promotion" performed (see section
- * 3.2.1.1 of the C89 draft standard). A cast to the smaller container type
- * is then required to avoid the compiler warning */
- out = (unsigned char)(out | (unsigned char)(1 << (7 - i)));
- }
- return out;
-}
-
-static unsigned char suffix_mask(unsigned char prefix_len) {
- return (unsigned char)~prefix_mask(prefix_len);
-}
-
-static void generate_first_byte_lut(void) {
- int i, j, n;
- const spec *chrspec;
- unsigned char suffix;
-
- n = printf("static CALLTYPE first_byte[256] = {");
- /* for each potential first byte of a header */
- for (i = 0; i < 256; i++) {
- /* find the field type that matches it */
- chrspec = NULL;
- for (j = 0; j < num_fields; j++) {
- if ((prefix_mask(fields[j].prefix_length) & i) == fields[j].prefix) {
- /* NB: the following integer arithmetic operation needs to be in its
- * expanded form due to the "integral promotion" performed (see section
- * 3.2.1.1 of the C89 draft standard). A cast to the smaller container
- * type is then required to avoid the compiler warning */
- suffix = (unsigned char)(suffix_mask(fields[j].prefix_length) &
- (unsigned char)i);
- if (suffix == suffix_mask(fields[j].prefix_length)) {
- if (fields[j].index != 2) continue;
- } else if (suffix == 0) {
- if (fields[j].index != 0) continue;
- } else {
- if (fields[j].index != 1) continue;
- }
- GPR_ASSERT(chrspec == NULL);
- chrspec = &fields[j];
- }
- }
- if (chrspec) {
- n += printf("%s, ", chrspec->call);
- } else {
- n += printf("ILLEGAL, ");
- }
- /* make some small effort towards readable output */
- if (n > 70) {
- printf("\n ");
- n = 2;
- }
- }
- printf("};\n");
-}
-
-/*
- * Huffman decoder table generation
- */
-
-#define MAXHUFFSTATES 1024
-
-/* represents a set of symbols as an array of booleans indicating inclusion */
-typedef struct { char included[GRPC_CHTTP2_NUM_HUFFSYMS]; } symset;
-/* represents a lookup table indexed by a nibble */
-typedef struct { unsigned values[16]; } nibblelut;
-
-#define NOT_SET (~(unsigned)0)
-
-/* returns a symset that includes all possible symbols */
-static symset symset_all(void) {
- symset x;
- memset(x.included, 1, sizeof(x.included));
- return x;
-}
-
-/* returns a symset that includes no symbols */
-static symset symset_none(void) {
- symset x;
- memset(x.included, 0, sizeof(x.included));
- return x;
-}
-
-/* returns an empty nibblelut */
-static nibblelut nibblelut_empty(void) {
- nibblelut x;
- int i;
- for (i = 0; i < 16; i++) {
- x.values[i] = NOT_SET;
- }
- return x;
-}
-
-/* counts symbols in a symset - only used for debug builds */
-#ifndef NDEBUG
-static int nsyms(symset s) {
- int i;
- int c = 0;
- for (i = 0; i < GRPC_CHTTP2_NUM_HUFFSYMS; i++) {
- c += s.included[i] != 0;
- }
- return c;
-}
-#endif
-
-/* global table of discovered huffman decoding states */
-static struct {
- /* the bit offset that this state starts at */
- unsigned bitofs;
- /* the set of symbols that this state started with */
- symset syms;
-
- /* lookup table for the next state */
- nibblelut next;
- /* lookup table for what to emit */
- nibblelut emit;
-} huffstates[MAXHUFFSTATES];
-static unsigned nhuffstates = 0;
-
-/* given a number of decoded bits and a set of symbols that are live,
- return the index into the decoder table for this state.
- set isnew to 1 if this state was previously undiscovered */
-static unsigned state_index(unsigned bitofs, symset syms, unsigned *isnew) {
- unsigned i;
- for (i = 0; i < nhuffstates; i++) {
- if (huffstates[i].bitofs != bitofs) continue;
- if (0 != memcmp(huffstates[i].syms.included, syms.included,
- GRPC_CHTTP2_NUM_HUFFSYMS))
- continue;
- *isnew = 0;
- return i;
- }
- GPR_ASSERT(nhuffstates != MAXHUFFSTATES);
-
- i = nhuffstates;
- nhuffstates++;
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+/* generates constant tables for hpack.cc */
+
+#include <assert.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/log.h>
+#include "src/core/ext/transport/chttp2/transport/huffsyms.h"
+
+/*
+ * first byte LUT generation
+ */
+
+typedef struct {
+ const char *call;
+ /* bit prefix for the field type */
+ unsigned char prefix;
+ /* length of the bit prefix for the field type */
+ unsigned char prefix_length;
+ /* index value: 0 = all zeros, 2 = all ones, 1 otherwise */
+ unsigned char index;
+} spec;
+
+static const spec fields[] = {
+ {"INDEXED_FIELD", 0X80, 1, 1}, {"INDEXED_FIELD_X", 0X80, 1, 2},
+ {"LITHDR_INCIDX", 0X40, 2, 1}, {"LITHDR_INCIDX_X", 0X40, 2, 2},
+ {"LITHDR_INCIDX_V", 0X40, 2, 0}, {"LITHDR_NOTIDX", 0X00, 4, 1},
+ {"LITHDR_NOTIDX_X", 0X00, 4, 2}, {"LITHDR_NOTIDX_V", 0X00, 4, 0},
+ {"LITHDR_NVRIDX", 0X10, 4, 1}, {"LITHDR_NVRIDX_X", 0X10, 4, 2},
+ {"LITHDR_NVRIDX_V", 0X10, 4, 0}, {"MAX_TBL_SIZE", 0X20, 3, 1},
+ {"MAX_TBL_SIZE_X", 0X20, 3, 2},
+};
+
+static const int num_fields = sizeof(fields) / sizeof(*fields);
+
+static unsigned char prefix_mask(unsigned char prefix_len) {
+ unsigned char i;
+ unsigned char out = 0;
+ for (i = 0; i < prefix_len; i++) {
+ /* NB: the following integer arithmetic operation needs to be in its
+ * expanded form due to the "integral promotion" performed (see section
+ * 3.2.1.1 of the C89 draft standard). A cast to the smaller container type
+ * is then required to avoid the compiler warning */
+ out = (unsigned char)(out | (unsigned char)(1 << (7 - i)));
+ }
+ return out;
+}
+
+static unsigned char suffix_mask(unsigned char prefix_len) {
+ return (unsigned char)~prefix_mask(prefix_len);
+}
+
+static void generate_first_byte_lut(void) {
+ int i, j, n;
+ const spec *chrspec;
+ unsigned char suffix;
+
+ n = printf("static CALLTYPE first_byte[256] = {");
+ /* for each potential first byte of a header */
+ for (i = 0; i < 256; i++) {
+ /* find the field type that matches it */
+ chrspec = NULL;
+ for (j = 0; j < num_fields; j++) {
+ if ((prefix_mask(fields[j].prefix_length) & i) == fields[j].prefix) {
+ /* NB: the following integer arithmetic operation needs to be in its
+ * expanded form due to the "integral promotion" performed (see section
+ * 3.2.1.1 of the C89 draft standard). A cast to the smaller container
+ * type is then required to avoid the compiler warning */
+ suffix = (unsigned char)(suffix_mask(fields[j].prefix_length) &
+ (unsigned char)i);
+ if (suffix == suffix_mask(fields[j].prefix_length)) {
+ if (fields[j].index != 2) continue;
+ } else if (suffix == 0) {
+ if (fields[j].index != 0) continue;
+ } else {
+ if (fields[j].index != 1) continue;
+ }
+ GPR_ASSERT(chrspec == NULL);
+ chrspec = &fields[j];
+ }
+ }
+ if (chrspec) {
+ n += printf("%s, ", chrspec->call);
+ } else {
+ n += printf("ILLEGAL, ");
+ }
+ /* make some small effort towards readable output */
+ if (n > 70) {
+ printf("\n ");
+ n = 2;
+ }
+ }
+ printf("};\n");
+}
+
+/*
+ * Huffman decoder table generation
+ */
+
+#define MAXHUFFSTATES 1024
+
+/* represents a set of symbols as an array of booleans indicating inclusion */
+typedef struct { char included[GRPC_CHTTP2_NUM_HUFFSYMS]; } symset;
+/* represents a lookup table indexed by a nibble */
+typedef struct { unsigned values[16]; } nibblelut;
+
+#define NOT_SET (~(unsigned)0)
+
+/* returns a symset that includes all possible symbols */
+static symset symset_all(void) {
+ symset x;
+ memset(x.included, 1, sizeof(x.included));
+ return x;
+}
+
+/* returns a symset that includes no symbols */
+static symset symset_none(void) {
+ symset x;
+ memset(x.included, 0, sizeof(x.included));
+ return x;
+}
+
+/* returns an empty nibblelut */
+static nibblelut nibblelut_empty(void) {
+ nibblelut x;
+ int i;
+ for (i = 0; i < 16; i++) {
+ x.values[i] = NOT_SET;
+ }
+ return x;
+}
+
+/* counts symbols in a symset - only used for debug builds */
+#ifndef NDEBUG
+static int nsyms(symset s) {
+ int i;
+ int c = 0;
+ for (i = 0; i < GRPC_CHTTP2_NUM_HUFFSYMS; i++) {
+ c += s.included[i] != 0;
+ }
+ return c;
+}
+#endif
+
+/* global table of discovered huffman decoding states */
+static struct {
+ /* the bit offset that this state starts at */
+ unsigned bitofs;
+ /* the set of symbols that this state started with */
+ symset syms;
+
+ /* lookup table for the next state */
+ nibblelut next;
+ /* lookup table for what to emit */
+ nibblelut emit;
+} huffstates[MAXHUFFSTATES];
+static unsigned nhuffstates = 0;
+
+/* given a number of decoded bits and a set of symbols that are live,
+ return the index into the decoder table for this state.
+ set isnew to 1 if this state was previously undiscovered */
+static unsigned state_index(unsigned bitofs, symset syms, unsigned *isnew) {
+ unsigned i;
+ for (i = 0; i < nhuffstates; i++) {
+ if (huffstates[i].bitofs != bitofs) continue;
+ if (0 != memcmp(huffstates[i].syms.included, syms.included,
+ GRPC_CHTTP2_NUM_HUFFSYMS))
+ continue;
+ *isnew = 0;
+ return i;
+ }
+ GPR_ASSERT(nhuffstates != MAXHUFFSTATES);
- huffstates[i].bitofs = bitofs;
- huffstates[i].syms = syms;
- huffstates[i].next = nibblelut_empty();
- huffstates[i].emit = nibblelut_empty();
- *isnew = 1;
- return i;
-}
-
-/* recursively build a decoding table
-
- state - the huffman state that we are trying to fill in
- nibble - the current nibble
- nibbits - the number of bits in the nibble that have been filled in
- bitofs - the number of bits of symbol that have been decoded
- emit - the symbol to emit on this nibble (or -1 if no symbol has been
- found)
- syms - the set of symbols that could be matched */
-static void build_dec_tbl(unsigned state, unsigned nibble, int nibbits,
- unsigned bitofs, unsigned emit, symset syms) {
- unsigned i;
- unsigned bit;
-
- /* If we have four bits in the nibble we're looking at, then we can fill in
- a slot in the lookup tables. */
- if (nibbits == 4) {
- unsigned isnew;
- /* Find the state that we are in: this may be a new state, in which case
- we recurse to fill it in, or we may have already seen this state, in
- which case the recursion terminates */
- unsigned st = state_index(bitofs, syms, &isnew);
- GPR_ASSERT(huffstates[state].next.values[nibble] == NOT_SET);
- huffstates[state].next.values[nibble] = st;
- huffstates[state].emit.values[nibble] = emit;
- if (isnew) {
- build_dec_tbl(st, 0, 0, bitofs, NOT_SET, syms);
- }
- return;
- }
-
- assert(nsyms(syms));
-
- /* A bit can be 0 or 1 */
- for (bit = 0; bit < 2; bit++) {
- /* walk over active symbols and see if they have this bit set */
- symset nextsyms = symset_none();
- for (i = 0; i < GRPC_CHTTP2_NUM_HUFFSYMS; i++) {
- if (!syms.included[i]) continue; /* disregard inactive symbols */
- if (((grpc_chttp2_huffsyms[i].bits >>
- (grpc_chttp2_huffsyms[i].length - bitofs - 1)) &
- 1) == bit) {
- /* the bit is set, include it in the next recursive set */
- if (grpc_chttp2_huffsyms[i].length == bitofs + 1) {
- /* additionally, we've gotten to the end of a symbol - this is a
- special recursion step: re-activate all the symbols, reset
- bitofs to zero, and recurse */
- build_dec_tbl(state, (nibble << 1) | bit, nibbits + 1, 0, i,
- symset_all());
- /* skip the remainder of this loop */
- goto next;
- }
- nextsyms.included[i] = 1;
- }
- }
- /* recurse down for this bit */
- build_dec_tbl(state, (nibble << 1) | bit, nibbits + 1, bitofs + 1, emit,
- nextsyms);
- next:;
- }
-}
-
-static nibblelut ctbl[MAXHUFFSTATES];
-static int nctbl;
-
-static int ctbl_idx(nibblelut x) {
- int i;
- for (i = 0; i < nctbl; i++) {
- if (0 == memcmp(&x, ctbl + i, sizeof(nibblelut))) return i;
- }
- ctbl[i] = x;
- nctbl++;
- return i;
-}
-
-static void dump_ctbl(const char *name) {
- int i, j;
- printf("static const gpr_int16 %s[%d*16] = {\n", name, nctbl);
- for (i = 0; i < nctbl; i++) {
- for (j = 0; j < 16; j++) {
- printf("%d,", ctbl[i].values[j]);
- }
- printf("\n");
- }
- printf("};\n");
-}
-
-static void generate_huff_tables(void) {
- unsigned i;
- build_dec_tbl(state_index(0, symset_all(), &i), 0, 0, 0, NOT_SET,
- symset_all());
-
- nctbl = 0;
- printf("static const gpr_uint8 next_tbl[%d] = {", nhuffstates);
- for (i = 0; i < nhuffstates; i++) {
- printf("%d,", ctbl_idx(huffstates[i].next));
- }
- printf("};\n");
- dump_ctbl("next_sub_tbl");
-
- nctbl = 0;
- printf("static const gpr_uint16 emit_tbl[%d] = {", nhuffstates);
- for (i = 0; i < nhuffstates; i++) {
- printf("%d,", ctbl_idx(huffstates[i].emit));
- }
- printf("};\n");
- dump_ctbl("emit_sub_tbl");
-}
-
-static void generate_base64_huff_encoder_table(void) {
- static const char alphabet[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- int i;
-
- printf(
- "static const struct { gpr_uint16 bits, gpr_uint8 length } "
- "base64_syms[64] = {\n");
- for (i = 0; i < 64; i++) {
- printf("{0x%x, %d},", grpc_chttp2_huffsyms[(unsigned char)alphabet[i]].bits,
- grpc_chttp2_huffsyms[(unsigned char)alphabet[i]].length);
- }
- printf("};\n");
-}
-
-static void generate_base64_inverse_table(void) {
- static const char alphabet[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- unsigned char inverse[256];
- unsigned i;
-
- memset(inverse, 255, sizeof(inverse));
- for (i = 0; i < strlen(alphabet); i++) {
- inverse[(unsigned char)alphabet[i]] = (unsigned char)i;
- }
-
- printf("static const gpr_uint8 inverse_base64[256] = {");
- for (i = 0; i < 256; i++) {
- printf("%d,", inverse[i]);
- }
- printf("};\n");
-}
-
-int main(void) {
- generate_huff_tables();
- generate_first_byte_lut();
- generate_base64_huff_encoder_table();
- generate_base64_inverse_table();
-
- return 0;
-}
+ i = nhuffstates;
+ nhuffstates++;
+
+ huffstates[i].bitofs = bitofs;
+ huffstates[i].syms = syms;
+ huffstates[i].next = nibblelut_empty();
+ huffstates[i].emit = nibblelut_empty();
+ *isnew = 1;
+ return i;
+}
+
+/* recursively build a decoding table
+
+ state - the huffman state that we are trying to fill in
+ nibble - the current nibble
+ nibbits - the number of bits in the nibble that have been filled in
+ bitofs - the number of bits of symbol that have been decoded
+ emit - the symbol to emit on this nibble (or -1 if no symbol has been
+ found)
+ syms - the set of symbols that could be matched */
+static void build_dec_tbl(unsigned state, unsigned nibble, int nibbits,
+ unsigned bitofs, unsigned emit, symset syms) {
+ unsigned i;
+ unsigned bit;
+
+ /* If we have four bits in the nibble we're looking at, then we can fill in
+ a slot in the lookup tables. */
+ if (nibbits == 4) {
+ unsigned isnew;
+ /* Find the state that we are in: this may be a new state, in which case
+ we recurse to fill it in, or we may have already seen this state, in
+ which case the recursion terminates */
+ unsigned st = state_index(bitofs, syms, &isnew);
+ GPR_ASSERT(huffstates[state].next.values[nibble] == NOT_SET);
+ huffstates[state].next.values[nibble] = st;
+ huffstates[state].emit.values[nibble] = emit;
+ if (isnew) {
+ build_dec_tbl(st, 0, 0, bitofs, NOT_SET, syms);
+ }
+ return;
+ }
+
+ assert(nsyms(syms));
+
+ /* A bit can be 0 or 1 */
+ for (bit = 0; bit < 2; bit++) {
+ /* walk over active symbols and see if they have this bit set */
+ symset nextsyms = symset_none();
+ for (i = 0; i < GRPC_CHTTP2_NUM_HUFFSYMS; i++) {
+ if (!syms.included[i]) continue; /* disregard inactive symbols */
+ if (((grpc_chttp2_huffsyms[i].bits >>
+ (grpc_chttp2_huffsyms[i].length - bitofs - 1)) &
+ 1) == bit) {
+ /* the bit is set, include it in the next recursive set */
+ if (grpc_chttp2_huffsyms[i].length == bitofs + 1) {
+ /* additionally, we've gotten to the end of a symbol - this is a
+ special recursion step: re-activate all the symbols, reset
+ bitofs to zero, and recurse */
+ build_dec_tbl(state, (nibble << 1) | bit, nibbits + 1, 0, i,
+ symset_all());
+ /* skip the remainder of this loop */
+ goto next;
+ }
+ nextsyms.included[i] = 1;
+ }
+ }
+ /* recurse down for this bit */
+ build_dec_tbl(state, (nibble << 1) | bit, nibbits + 1, bitofs + 1, emit,
+ nextsyms);
+ next:;
+ }
+}
+
+static nibblelut ctbl[MAXHUFFSTATES];
+static int nctbl;
+
+static int ctbl_idx(nibblelut x) {
+ int i;
+ for (i = 0; i < nctbl; i++) {
+ if (0 == memcmp(&x, ctbl + i, sizeof(nibblelut))) return i;
+ }
+ ctbl[i] = x;
+ nctbl++;
+ return i;
+}
+
+static void dump_ctbl(const char *name) {
+ int i, j;
+ printf("static const gpr_int16 %s[%d*16] = {\n", name, nctbl);
+ for (i = 0; i < nctbl; i++) {
+ for (j = 0; j < 16; j++) {
+ printf("%d,", ctbl[i].values[j]);
+ }
+ printf("\n");
+ }
+ printf("};\n");
+}
+
+static void generate_huff_tables(void) {
+ unsigned i;
+ build_dec_tbl(state_index(0, symset_all(), &i), 0, 0, 0, NOT_SET,
+ symset_all());
+
+ nctbl = 0;
+ printf("static const gpr_uint8 next_tbl[%d] = {", nhuffstates);
+ for (i = 0; i < nhuffstates; i++) {
+ printf("%d,", ctbl_idx(huffstates[i].next));
+ }
+ printf("};\n");
+ dump_ctbl("next_sub_tbl");
+
+ nctbl = 0;
+ printf("static const gpr_uint16 emit_tbl[%d] = {", nhuffstates);
+ for (i = 0; i < nhuffstates; i++) {
+ printf("%d,", ctbl_idx(huffstates[i].emit));
+ }
+ printf("};\n");
+ dump_ctbl("emit_sub_tbl");
+}
+
+static void generate_base64_huff_encoder_table(void) {
+ static const char alphabet[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ int i;
+
+ printf(
+ "static const struct { gpr_uint16 bits, gpr_uint8 length } "
+ "base64_syms[64] = {\n");
+ for (i = 0; i < 64; i++) {
+ printf("{0x%x, %d},", grpc_chttp2_huffsyms[(unsigned char)alphabet[i]].bits,
+ grpc_chttp2_huffsyms[(unsigned char)alphabet[i]].length);
+ }
+ printf("};\n");
+}
+
+static void generate_base64_inverse_table(void) {
+ static const char alphabet[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+ unsigned char inverse[256];
+ unsigned i;
+
+ memset(inverse, 255, sizeof(inverse));
+ for (i = 0; i < strlen(alphabet); i++) {
+ inverse[(unsigned char)alphabet[i]] = (unsigned char)i;
+ }
+
+ printf("static const gpr_uint8 inverse_base64[256] = {");
+ for (i = 0; i < 256; i++) {
+ printf("%d,", inverse[i]);
+ }
+ printf("};\n");
+}
+
+int main(void) {
+ generate_huff_tables();
+ generate_first_byte_lut();
+ generate_base64_huff_encoder_table();
+ generate_base64_inverse_table();
+
+ return 0;
+}
diff --git a/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables/ya.make b/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables/ya.make
index b0e0306ea9..71bf1c5f88 100644
--- a/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables/ya.make
+++ b/contrib/libs/grpc/tools/codegen/core/gen_hpack_tables/ya.make
@@ -1,38 +1,38 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
-
-LICENSE(Apache-2.0)
-
-PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/src/core/lib
- contrib/libs/grpc/third_party/address_sorting
+
+LICENSE(Apache-2.0)
+
+PEERDIR(
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/src/core/lib
+ contrib/libs/grpc/third_party/address_sorting
contrib/libs/grpc/third_party/upb
-)
-
-ADDINCL(
+)
+
+ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
- contrib/libs/grpc/include
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/tools/codegen/core)
-
-IF (OS_LINUX OR OS_DARWIN)
+ contrib/libs/grpc
+ contrib/libs/grpc/include
+)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/tools/codegen/core)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- gen_hpack_tables.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ gen_hpack_tables.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters.cc b/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters.cc
index fbabd2464f..90d2c8a8a8 100644
--- a/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters.cc
+++ b/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters.cc
@@ -1,66 +1,66 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-/* generates constant table for metadata.cc */
-
-#include <stdio.h>
-#include <string.h>
-
-static unsigned char legal_bits[256 / 8];
-
-static void legal(int x) {
- int byte = x / 8;
- int bit = x % 8;
- /* NB: the following integer arithmetic operation needs to be in its
- * expanded form due to the "integral promotion" performed (see section
- * 3.2.1.1 of the C89 draft standard). A cast to the smaller container type
- * is then required to avoid the compiler warning */
- legal_bits[byte] =
- (unsigned char)((legal_bits[byte] | (unsigned char)(1 << bit)));
-}
-
-static void dump(void) {
- int i;
-
- printf("static const uint8_t legal_header_bits[256/8] = ");
- for (i = 0; i < 256 / 8; i++)
- printf("%c 0x%02x", i ? ',' : '{', legal_bits[i]);
- printf(" };\n");
-}
-
-static void clear(void) { memset(legal_bits, 0, sizeof(legal_bits)); }
-
-int main(void) {
- int i;
-
- clear();
- for (i = 'a'; i <= 'z'; i++) legal(i);
- for (i = '0'; i <= '9'; i++) legal(i);
- legal('-');
- legal('_');
- legal('.');
- dump();
-
- clear();
- for (i = 32; i <= 126; i++) {
- legal(i);
- }
- dump();
-
- return 0;
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+/* generates constant table for metadata.cc */
+
+#include <stdio.h>
+#include <string.h>
+
+static unsigned char legal_bits[256 / 8];
+
+static void legal(int x) {
+ int byte = x / 8;
+ int bit = x % 8;
+ /* NB: the following integer arithmetic operation needs to be in its
+ * expanded form due to the "integral promotion" performed (see section
+ * 3.2.1.1 of the C89 draft standard). A cast to the smaller container type
+ * is then required to avoid the compiler warning */
+ legal_bits[byte] =
+ (unsigned char)((legal_bits[byte] | (unsigned char)(1 << bit)));
+}
+
+static void dump(void) {
+ int i;
+
+ printf("static const uint8_t legal_header_bits[256/8] = ");
+ for (i = 0; i < 256 / 8; i++)
+ printf("%c 0x%02x", i ? ',' : '{', legal_bits[i]);
+ printf(" };\n");
+}
+
+static void clear(void) { memset(legal_bits, 0, sizeof(legal_bits)); }
+
+int main(void) {
+ int i;
+
+ clear();
+ for (i = 'a'; i <= 'z'; i++) legal(i);
+ for (i = '0'; i <= '9'; i++) legal(i);
+ legal('-');
+ legal('_');
+ legal('.');
+ dump();
+
+ clear();
+ for (i = 32; i <= 126; i++) {
+ legal(i);
+ }
+ dump();
+
+ return 0;
+}
diff --git a/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters/ya.make b/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters/ya.make
index 1398fede78..712de445c4 100644
--- a/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters/ya.make
+++ b/contrib/libs/grpc/tools/codegen/core/gen_legal_metadata_characters/ya.make
@@ -1,30 +1,30 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
-
-LICENSE(Apache-2.0)
-
+
+LICENSE(Apache-2.0)
+
ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
contrib/libs/grpc
)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/tools/codegen/core)
-
-IF (OS_LINUX OR OS_DARWIN)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/tools/codegen/core)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- gen_legal_metadata_characters.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ gen_legal_metadata_characters.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables.cc b/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables.cc
index a99024e5ed..5ec9bef995 100644
--- a/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables.cc
+++ b/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables.cc
@@ -1,69 +1,69 @@
-/*
- *
- * Copyright 2015 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.
- *
- */
-
-/* generates constant table for metadata.cc */
-
-#include <stdio.h>
-#include <string.h>
-
-static unsigned char legal_bits[256 / 8];
-
-static void legal(int x) {
- int byte = x / 8;
- int bit = x % 8;
- /* NB: the following integer arithmetic operation needs to be in its
- * expanded form due to the "integral promotion" performed (see section
- * 3.2.1.1 of the C89 draft standard). A cast to the smaller container type
- * is then required to avoid the compiler warning */
- legal_bits[byte] =
- (unsigned char)((legal_bits[byte] | (unsigned char)(1 << bit)));
-}
-
-static void dump(const char *name) {
- int i;
-
- printf("const uint8_t %s[256/8] = ", name);
- for (i = 0; i < 256 / 8; i++)
- printf("%c 0x%02x", i ? ',' : '{', legal_bits[i]);
- printf(" };\n");
-}
-
-static void clear(void) { memset(legal_bits, 0, sizeof(legal_bits)); }
-
-int main(void) {
- int i;
-
- clear();
- for (i = 'a'; i <= 'z'; i++) legal(i);
- for (i = 'A'; i <= 'Z'; i++) legal(i);
- for (i = '0'; i <= '9'; i++) legal(i);
- legal('-');
- legal('_');
- legal('.');
- legal('~');
- dump("grpc_url_percent_encoding_unreserved_bytes");
-
- clear();
- for (i = 32; i <= 126; i++) {
- if (i == '%') continue;
- legal(i);
- }
- dump("grpc_compatible_percent_encoding_unreserved_bytes");
-
- return 0;
-}
+/*
+ *
+ * Copyright 2015 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.
+ *
+ */
+
+/* generates constant table for metadata.cc */
+
+#include <stdio.h>
+#include <string.h>
+
+static unsigned char legal_bits[256 / 8];
+
+static void legal(int x) {
+ int byte = x / 8;
+ int bit = x % 8;
+ /* NB: the following integer arithmetic operation needs to be in its
+ * expanded form due to the "integral promotion" performed (see section
+ * 3.2.1.1 of the C89 draft standard). A cast to the smaller container type
+ * is then required to avoid the compiler warning */
+ legal_bits[byte] =
+ (unsigned char)((legal_bits[byte] | (unsigned char)(1 << bit)));
+}
+
+static void dump(const char *name) {
+ int i;
+
+ printf("const uint8_t %s[256/8] = ", name);
+ for (i = 0; i < 256 / 8; i++)
+ printf("%c 0x%02x", i ? ',' : '{', legal_bits[i]);
+ printf(" };\n");
+}
+
+static void clear(void) { memset(legal_bits, 0, sizeof(legal_bits)); }
+
+int main(void) {
+ int i;
+
+ clear();
+ for (i = 'a'; i <= 'z'; i++) legal(i);
+ for (i = 'A'; i <= 'Z'; i++) legal(i);
+ for (i = '0'; i <= '9'; i++) legal(i);
+ legal('-');
+ legal('_');
+ legal('.');
+ legal('~');
+ dump("grpc_url_percent_encoding_unreserved_bytes");
+
+ clear();
+ for (i = 32; i <= 126; i++) {
+ if (i == '%') continue;
+ legal(i);
+ }
+ dump("grpc_compatible_percent_encoding_unreserved_bytes");
+
+ return 0;
+}
diff --git a/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables/ya.make b/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables/ya.make
index 7aa3a6e32e..037accb8c8 100644
--- a/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables/ya.make
+++ b/contrib/libs/grpc/tools/codegen/core/gen_percent_encoding_tables/ya.make
@@ -1,30 +1,30 @@
-# Generated by devtools/yamaker.
-
-PROGRAM()
-
+# Generated by devtools/yamaker.
+
+PROGRAM()
+
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
-
-LICENSE(Apache-2.0)
-
+
+LICENSE(Apache-2.0)
+
ADDINCL(
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
contrib/libs/grpc
)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(contrib/libs/grpc/tools/codegen/core)
-
-IF (OS_LINUX OR OS_DARWIN)
+
+NO_COMPILER_WARNINGS()
+
+SRCDIR(contrib/libs/grpc/tools/codegen/core)
+
+IF (OS_LINUX OR OS_DARWIN)
CFLAGS(
-DGRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK=1
)
-ENDIF()
-
-SRCS(
- gen_percent_encoding_tables.cc
-)
-
-END()
+ENDIF()
+
+SRCS(
+ gen_percent_encoding_tables.cc
+)
+
+END()
diff --git a/contrib/libs/grpc/ya.make b/contrib/libs/grpc/ya.make
index 29848d23ea..27b1485ed0 100644
--- a/contrib/libs/grpc/ya.make
+++ b/contrib/libs/grpc/ya.make
@@ -16,8 +16,8 @@ OWNER(
)
PEERDIR(
- contrib/libs/grpc/grpc
- contrib/libs/grpc/grpc++
+ contrib/libs/grpc/grpc
+ contrib/libs/grpc/grpc++
)
# Fix selective checkout DEVTOOLSSUPPORT-6767
@@ -26,39 +26,39 @@ SRCDIR(contrib/libs/grpc/include)
END()
RECURSE(
- grpc
- grpc++
- grpc++_error_details
- grpc++_reflection
- grpc++_unsecure
- grpc_unsecure
- grpcpp_channelz
- src/compiler/grpc_cpp_plugin
- src/compiler/grpc_plugin_support
- src/compiler/grpc_python_plugin
- src/core/lib
+ grpc
+ grpc++
+ grpc++_error_details
+ grpc++_reflection
+ grpc++_unsecure
+ grpc_unsecure
+ grpcpp_channelz
+ src/compiler/grpc_cpp_plugin
+ src/compiler/grpc_plugin_support
+ src/compiler/grpc_python_plugin
+ src/core/lib
src/cpp/common
- src/proto/grpc/core
- src/proto/grpc/channelz
- src/proto/grpc/health/v1
- src/proto/grpc/reflection/v1alpha
- src/proto/grpc/status
- src/python/grpcio_channelz
- src/python/grpcio_health_checking
- src/python/grpcio_reflection
- src/python/grpcio_status
- third_party/address_sorting
+ src/proto/grpc/core
+ src/proto/grpc/channelz
+ src/proto/grpc/health/v1
+ src/proto/grpc/reflection/v1alpha
+ src/proto/grpc/status
+ src/python/grpcio_channelz
+ src/python/grpcio_health_checking
+ src/python/grpcio_reflection
+ src/python/grpcio_status
+ third_party/address_sorting
third_party/upb
- tools/codegen/core/gen_hpack_tables
- tools/codegen/core/gen_legal_metadata_characters
- tools/codegen/core/gen_percent_encoding_tables
+ tools/codegen/core/gen_hpack_tables
+ tools/codegen/core/gen_legal_metadata_characters
+ tools/codegen/core/gen_percent_encoding_tables
)
-
-RECURSE_FOR_TESTS(
- src/proto/grpc/testing
- src/proto/grpc/testing/duplicate
+
+RECURSE_FOR_TESTS(
+ src/proto/grpc/testing
+ src/proto/grpc/testing/duplicate
src/proto/grpc/testing/xds
- src/python/grpcio_tests
- test/core/util
- test/cpp/end2end
-)
+ src/python/grpcio_tests
+ test/core/util
+ test/cpp/end2end
+)
diff --git a/contrib/libs/ya.make b/contrib/libs/ya.make
index 9c4640fdcf..51e0684a39 100644
--- a/contrib/libs/ya.make
+++ b/contrib/libs/ya.make
@@ -23,7 +23,7 @@ RECURSE(
bluez-clean-headers
breakpad
brotli
- c-ares
+ c-ares
cairo
cbc
cctools
diff --git a/contrib/python/Jinja2/py2/jinja2/loaders.py b/contrib/python/Jinja2/py2/jinja2/loaders.py
index bad1774ab0..2c9798bb57 100644
--- a/contrib/python/Jinja2/py2/jinja2/loaders.py
+++ b/contrib/python/Jinja2/py2/jinja2/loaders.py
@@ -513,6 +513,6 @@ class ResourceLoader(BaseLoader):
if self.module_loader is None:
raise TemplateNotFound(template)
try:
- return self.module_loader.get_data(os.path.join(self.prefix, template)).decode('utf-8'), None, None
+ return self.module_loader.get_data(os.path.join(self.prefix, template)).decode('utf-8'), None, None
except IOError:
raise TemplateNotFound(template)
diff --git a/contrib/python/Jinja2/py3/jinja2/loaders.py b/contrib/python/Jinja2/py3/jinja2/loaders.py
index cc58eca221..5617839609 100644
--- a/contrib/python/Jinja2/py3/jinja2/loaders.py
+++ b/contrib/python/Jinja2/py3/jinja2/loaders.py
@@ -681,6 +681,6 @@ class ResourceLoader(BaseLoader):
if self.module_loader is None:
raise TemplateNotFound(template)
try:
- return self.module_loader.get_data(os.path.join(self.prefix, template)).decode('utf-8'), None, None
+ return self.module_loader.get_data(os.path.join(self.prefix, template)).decode('utf-8'), None, None
except IOError:
raise TemplateNotFound(template)
diff --git a/contrib/python/MarkupSafe/py2/.dist-info/METADATA b/contrib/python/MarkupSafe/py2/.dist-info/METADATA
index b6d72a81d2..52da515b7e 100644
--- a/contrib/python/MarkupSafe/py2/.dist-info/METADATA
+++ b/contrib/python/MarkupSafe/py2/.dist-info/METADATA
@@ -1,103 +1,103 @@
-Metadata-Version: 2.1
-Name: MarkupSafe
-Version: 1.1.1
-Summary: Safely add untrusted strings to HTML/XML markup.
-Home-page: https://palletsprojects.com/p/markupsafe/
-Author: Armin Ronacher
-Author-email: armin.ronacher@active-4.com
-Maintainer: The Pallets Team
-Maintainer-email: contact@palletsprojects.com
-License: BSD-3-Clause
-Project-URL: Code, https://github.com/pallets/markupsafe
-Project-URL: Issue tracker, https://github.com/pallets/markupsafe/issues
-Project-URL: Documentation, https://markupsafe.palletsprojects.com/
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.4
-Classifier: Programming Language :: Python :: 3.5
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Classifier: Topic :: Text Processing :: Markup :: HTML
-Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*
-
-MarkupSafe
-==========
-
-MarkupSafe implements a text object that escapes characters so it is
-safe to use in HTML and XML. Characters that have special meanings are
-replaced so that they display as the actual characters. This mitigates
-injection attacks, meaning untrusted user input can safely be displayed
-on a page.
-
-
-Installing
-----------
-
-Install and update using `pip`_:
-
-.. code-block:: text
-
- pip install -U MarkupSafe
-
-.. _pip: https://pip.pypa.io/en/stable/quickstart/
-
-
-Examples
---------
-
-.. code-block:: pycon
-
- >>> from markupsafe import Markup, escape
- >>> # escape replaces special characters and wraps in Markup
- >>> escape('<script>alert(document.cookie);</script>')
- Markup(u'&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
- >>> # wrap in Markup to mark text "safe" and prevent escaping
- >>> Markup('<strong>Hello</strong>')
- Markup('<strong>hello</strong>')
- >>> escape(Markup('<strong>Hello</strong>'))
- Markup('<strong>hello</strong>')
- >>> # Markup is a text subclass (str on Python 3, unicode on Python 2)
- >>> # methods and operators escape their arguments
- >>> template = Markup("Hello <em>%s</em>")
- >>> template % '"World"'
- Markup('Hello <em>&#34;World&#34;</em>')
-
-
-Donate
-------
-
-The Pallets organization develops and supports MarkupSafe and other
-libraries that use it. In order to grow the community of contributors
-and users, and allow the maintainers to devote more time to the
-projects, `please donate today`_.
-
-.. _please donate today: https://palletsprojects.com/donate
-
-
-Links
------
-
-* Website: https://palletsprojects.com/p/markupsafe/
-* Documentation: https://markupsafe.palletsprojects.com/
-* License: `BSD-3-Clause <https://github.com/pallets/markupsafe/blob/master/LICENSE.rst>`_
-* Releases: https://pypi.org/project/MarkupSafe/
-* Code: https://github.com/pallets/markupsafe
-* Issue tracker: https://github.com/pallets/markupsafe/issues
-* Test status:
-
- * Linux, Mac: https://travis-ci.org/pallets/markupsafe
- * Windows: https://ci.appveyor.com/project/pallets/markupsafe
-
-* Test coverage: https://codecov.io/gh/pallets/markupsafe
-
-
+Metadata-Version: 2.1
+Name: MarkupSafe
+Version: 1.1.1
+Summary: Safely add untrusted strings to HTML/XML markup.
+Home-page: https://palletsprojects.com/p/markupsafe/
+Author: Armin Ronacher
+Author-email: armin.ronacher@active-4.com
+Maintainer: The Pallets Team
+Maintainer-email: contact@palletsprojects.com
+License: BSD-3-Clause
+Project-URL: Code, https://github.com/pallets/markupsafe
+Project-URL: Issue tracker, https://github.com/pallets/markupsafe/issues
+Project-URL: Documentation, https://markupsafe.palletsprojects.com/
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Text Processing :: Markup :: HTML
+Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*
+
+MarkupSafe
+==========
+
+MarkupSafe implements a text object that escapes characters so it is
+safe to use in HTML and XML. Characters that have special meanings are
+replaced so that they display as the actual characters. This mitigates
+injection attacks, meaning untrusted user input can safely be displayed
+on a page.
+
+
+Installing
+----------
+
+Install and update using `pip`_:
+
+.. code-block:: text
+
+ pip install -U MarkupSafe
+
+.. _pip: https://pip.pypa.io/en/stable/quickstart/
+
+
+Examples
+--------
+
+.. code-block:: pycon
+
+ >>> from markupsafe import Markup, escape
+ >>> # escape replaces special characters and wraps in Markup
+ >>> escape('<script>alert(document.cookie);</script>')
+ Markup(u'&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
+ >>> Markup('<strong>Hello</strong>')
+ Markup('<strong>hello</strong>')
+ >>> escape(Markup('<strong>Hello</strong>'))
+ Markup('<strong>hello</strong>')
+ >>> # Markup is a text subclass (str on Python 3, unicode on Python 2)
+ >>> # methods and operators escape their arguments
+ >>> template = Markup("Hello <em>%s</em>")
+ >>> template % '"World"'
+ Markup('Hello <em>&#34;World&#34;</em>')
+
+
+Donate
+------
+
+The Pallets organization develops and supports MarkupSafe and other
+libraries that use it. In order to grow the community of contributors
+and users, and allow the maintainers to devote more time to the
+projects, `please donate today`_.
+
+.. _please donate today: https://palletsprojects.com/donate
+
+
+Links
+-----
+
+* Website: https://palletsprojects.com/p/markupsafe/
+* Documentation: https://markupsafe.palletsprojects.com/
+* License: `BSD-3-Clause <https://github.com/pallets/markupsafe/blob/master/LICENSE.rst>`_
+* Releases: https://pypi.org/project/MarkupSafe/
+* Code: https://github.com/pallets/markupsafe
+* Issue tracker: https://github.com/pallets/markupsafe/issues
+* Test status:
+
+ * Linux, Mac: https://travis-ci.org/pallets/markupsafe
+ * Windows: https://ci.appveyor.com/project/pallets/markupsafe
+
+* Test coverage: https://codecov.io/gh/pallets/markupsafe
+
+
diff --git a/contrib/python/MarkupSafe/py2/.dist-info/top_level.txt b/contrib/python/MarkupSafe/py2/.dist-info/top_level.txt
index 75bf729258..ecf81b4a7b 100644
--- a/contrib/python/MarkupSafe/py2/.dist-info/top_level.txt
+++ b/contrib/python/MarkupSafe/py2/.dist-info/top_level.txt
@@ -1 +1 @@
-markupsafe
+markupsafe
diff --git a/contrib/python/MarkupSafe/py2/ya.make b/contrib/python/MarkupSafe/py2/ya.make
index 0e773ee33a..576210225d 100644
--- a/contrib/python/MarkupSafe/py2/ya.make
+++ b/contrib/python/MarkupSafe/py2/ya.make
@@ -26,12 +26,12 @@ NO_LINT()
NO_COMPILER_WARNINGS()
-RESOURCE_FILES(
+RESOURCE_FILES(
PREFIX contrib/python/MarkupSafe/py2/
- .dist-info/METADATA
- .dist-info/top_level.txt
-)
-
+ .dist-info/METADATA
+ .dist-info/top_level.txt
+)
+
END()
RECURSE_FOR_TESTS(
diff --git a/contrib/python/MarkupSafe/py3/.dist-info/METADATA b/contrib/python/MarkupSafe/py3/.dist-info/METADATA
index e87ebb99a9..fd912e0497 100644
--- a/contrib/python/MarkupSafe/py3/.dist-info/METADATA
+++ b/contrib/python/MarkupSafe/py3/.dist-info/METADATA
@@ -1,94 +1,94 @@
-Metadata-Version: 2.1
-Name: MarkupSafe
+Metadata-Version: 2.1
+Name: MarkupSafe
Version: 2.0.1
-Summary: Safely add untrusted strings to HTML/XML markup.
-Home-page: https://palletsprojects.com/p/markupsafe/
-Author: Armin Ronacher
-Author-email: armin.ronacher@active-4.com
+Summary: Safely add untrusted strings to HTML/XML markup.
+Home-page: https://palletsprojects.com/p/markupsafe/
+Author: Armin Ronacher
+Author-email: armin.ronacher@active-4.com
Maintainer: Pallets
-Maintainer-email: contact@palletsprojects.com
-License: BSD-3-Clause
+Maintainer-email: contact@palletsprojects.com
+License: BSD-3-Clause
Project-URL: Donate, https://palletsprojects.com/donate
-Project-URL: Documentation, https://markupsafe.palletsprojects.com/
+Project-URL: Documentation, https://markupsafe.palletsprojects.com/
Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
Project-URL: Source Code, https://github.com/pallets/markupsafe/
Project-URL: Issue Tracker, https://github.com/pallets/markupsafe/issues/
Project-URL: Twitter, https://twitter.com/PalletsTeam
Project-URL: Chat, https://discord.gg/pallets
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
-Classifier: Topic :: Text Processing :: Markup :: HTML
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
+Classifier: Topic :: Text Processing :: Markup :: HTML
Requires-Python: >=3.6
Description-Content-Type: text/x-rst
License-File: LICENSE.rst
-
-MarkupSafe
-==========
-
-MarkupSafe implements a text object that escapes characters so it is
-safe to use in HTML and XML. Characters that have special meanings are
-replaced so that they display as the actual characters. This mitigates
-injection attacks, meaning untrusted user input can safely be displayed
-on a page.
-
-
-Installing
-----------
-
-Install and update using `pip`_:
-
-.. code-block:: text
-
- pip install -U MarkupSafe
-
-.. _pip: https://pip.pypa.io/en/stable/quickstart/
-
-
-Examples
---------
-
-.. code-block:: pycon
-
- >>> from markupsafe import Markup, escape
-
- >>> # escape replaces special characters and wraps in Markup
+
+MarkupSafe
+==========
+
+MarkupSafe implements a text object that escapes characters so it is
+safe to use in HTML and XML. Characters that have special meanings are
+replaced so that they display as the actual characters. This mitigates
+injection attacks, meaning untrusted user input can safely be displayed
+on a page.
+
+
+Installing
+----------
+
+Install and update using `pip`_:
+
+.. code-block:: text
+
+ pip install -U MarkupSafe
+
+.. _pip: https://pip.pypa.io/en/stable/quickstart/
+
+
+Examples
+--------
+
+.. code-block:: pycon
+
+ >>> from markupsafe import Markup, escape
+
+ >>> # escape replaces special characters and wraps in Markup
>>> escape("<script>alert(document.cookie);</script>")
Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
- >>> # wrap in Markup to mark text "safe" and prevent escaping
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
>>> Markup("<strong>Hello</strong>")
- Markup('<strong>hello</strong>')
+ Markup('<strong>hello</strong>')
>>> escape(Markup("<strong>Hello</strong>"))
- Markup('<strong>hello</strong>')
+ Markup('<strong>hello</strong>')
>>> # Markup is a str subclass
- >>> # methods and operators escape their arguments
+ >>> # methods and operators escape their arguments
>>> template = Markup("Hello <em>{name}</em>")
>>> template.format(name='"World"')
- Markup('Hello <em>&#34;World&#34;</em>')
-
-
-Donate
-------
-
-The Pallets organization develops and supports MarkupSafe and other
+ Markup('Hello <em>&#34;World&#34;</em>')
+
+
+Donate
+------
+
+The Pallets organization develops and supports MarkupSafe and other
popular packages. In order to grow the community of contributors and
users, and allow the maintainers to devote more time to the projects,
`please donate today`_.
-
-.. _please donate today: https://palletsprojects.com/donate
-
-
-Links
------
-
+
+.. _please donate today: https://palletsprojects.com/donate
+
+
+Links
+-----
+
- Documentation: https://markupsafe.palletsprojects.com/
- Changes: https://markupsafe.palletsprojects.com/changes/
- PyPI Releases: https://pypi.org/project/MarkupSafe/
@@ -97,5 +97,5 @@ Links
- Website: https://palletsprojects.com/p/markupsafe/
- Twitter: https://twitter.com/PalletsTeam
- Chat: https://discord.gg/pallets
-
-
+
+
diff --git a/contrib/python/MarkupSafe/py3/.dist-info/top_level.txt b/contrib/python/MarkupSafe/py3/.dist-info/top_level.txt
index 75bf729258..ecf81b4a7b 100644
--- a/contrib/python/MarkupSafe/py3/.dist-info/top_level.txt
+++ b/contrib/python/MarkupSafe/py3/.dist-info/top_level.txt
@@ -1 +1 @@
-markupsafe
+markupsafe
diff --git a/contrib/python/MarkupSafe/py3/ya.make b/contrib/python/MarkupSafe/py3/ya.make
index 8c750e15d8..cf7035d171 100644
--- a/contrib/python/MarkupSafe/py3/ya.make
+++ b/contrib/python/MarkupSafe/py3/ya.make
@@ -27,13 +27,13 @@ PY_SRCS(
markupsafe/_speedups.pyi
)
-RESOURCE_FILES(
+RESOURCE_FILES(
PREFIX contrib/python/MarkupSafe/py3/
- .dist-info/METADATA
- .dist-info/top_level.txt
+ .dist-info/METADATA
+ .dist-info/top_level.txt
markupsafe/py.typed
-)
-
+)
+
END()
RECURSE_FOR_TESTS(
diff --git a/contrib/python/setuptools/py2/pkg_resources/__init__.py b/contrib/python/setuptools/py2/pkg_resources/__init__.py
index 649a2ce651..c44ac12129 100644
--- a/contrib/python/setuptools/py2/pkg_resources/__init__.py
+++ b/contrib/python/setuptools/py2/pkg_resources/__init__.py
@@ -3278,19 +3278,19 @@ class ResProvider(EmptyProvider):
path = os.path.normpath(path)
return self._resource_fs.get(path)
- def _listdir(self, path):
+ def _listdir(self, path):
result = self.__lookup(path)
if result is None:
return []
if isinstance(path, six.text_type) and six.PY2:
return [key.decode('utf-8') for key in result]
- else:
+ else:
return list(result)
- def _isdir(self, path):
+ def _isdir(self, path):
return bool(self.__lookup(path))
-
-
+
+
class ResDistribution(DistInfoDistribution):
def __init__(self, prefix):
super(ResDistribution, self).__init__(
diff --git a/contrib/python/setuptools/py3/pkg_resources/__init__.py b/contrib/python/setuptools/py3/pkg_resources/__init__.py
index 6b947a49a7..43b2459c60 100644
--- a/contrib/python/setuptools/py3/pkg_resources/__init__.py
+++ b/contrib/python/setuptools/py3/pkg_resources/__init__.py
@@ -3283,16 +3283,16 @@ class ResProvider(EmptyProvider):
path = os.path.normpath(path)
return self._resource_fs.get(path)
- def _listdir(self, path):
+ def _listdir(self, path):
result = self.__lookup(path)
if result is None:
return []
return list(result)
- def _isdir(self, path):
+ def _isdir(self, path):
return bool(self.__lookup(path))
-
-
+
+
class ResDistribution(DistInfoDistribution):
def __init__(self, prefix):
super(ResDistribution, self).__init__(
diff --git a/contrib/python/traitlets/py2/tests/ya.make b/contrib/python/traitlets/py2/tests/ya.make
index d2d3e3b9bf..050f5d1cc0 100644
--- a/contrib/python/traitlets/py2/tests/ya.make
+++ b/contrib/python/traitlets/py2/tests/ya.make
@@ -1,15 +1,15 @@
PY2TEST()
-
-OWNER(g:python-contrib borman nslus)
-
-PEERDIR(
+
+OWNER(g:python-contrib borman nslus)
+
+PEERDIR(
contrib/python/traitlets
-)
-
+)
+
ENV(
YA_PYTEST_DISABLE_DOCTEST=yes
)
-
+
SRCDIR(contrib/python/traitlets/py2/traitlets)
TEST_SRCS(
@@ -18,8 +18,8 @@ TEST_SRCS(
tests/test_traitlets.py
tests/test_traitlets_enum.py
tests/utils.py
-)
-
-NO_LINT()
-
-END()
+)
+
+NO_LINT()
+
+END()
diff --git a/contrib/python/traitlets/py2/traitlets/tests/_warnings.py b/contrib/python/traitlets/py2/traitlets/tests/_warnings.py
index f135d1f67e..beb3bf6ad5 100644
--- a/contrib/python/traitlets/py2/traitlets/tests/_warnings.py
+++ b/contrib/python/traitlets/py2/traitlets/tests/_warnings.py
@@ -1,107 +1,107 @@
-# From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py
-# Licensed under modified BSD license
-
-__all__ = ['all_warnings', 'expected_warnings']
-
-from contextlib import contextmanager
-import sys
-import warnings
-import inspect
-import re
-
-
-@contextmanager
-def all_warnings():
- """
- Context for use in testing to ensure that all warnings are raised.
- Examples
- --------
- >>> import warnings
- >>> def foo():
- ... warnings.warn(RuntimeWarning("bar"))
- We raise the warning once, while the warning filter is set to "once".
- Hereafter, the warning is invisible, even with custom filters:
- >>> with warnings.catch_warnings():
- ... warnings.simplefilter('once')
- ... foo()
- We can now run ``foo()`` without a warning being raised:
- >>> from numpy.testing import assert_warns
- >>> foo()
- To catch the warning, we call in the help of ``all_warnings``:
- >>> with all_warnings():
- ... assert_warns(RuntimeWarning, foo)
- """
-
- # Whenever a warning is triggered, Python adds a __warningregistry__
- # member to the *calling* module. The exercize here is to find
- # and eradicate all those breadcrumbs that were left lying around.
- #
- # We proceed by first searching all parent calling frames and explicitly
- # clearing their warning registries (necessary for the doctests above to
- # pass). Then, we search for all submodules of skimage and clear theirs
- # as well (necessary for the skimage test suite to pass).
-
- frame = inspect.currentframe()
- if frame:
- for f in inspect.getouterframes(frame):
- f[0].f_locals['__warningregistry__'] = {}
- del frame
-
- for mod_name, mod in list(sys.modules.items()):
- if 'six.moves' in mod_name:
- continue
- try:
- mod.__warningregistry__.clear()
- except AttributeError:
- pass
-
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
- yield w
-
-
-@contextmanager
-def expected_warnings(matching):
- """Context for use in testing to catch known warnings matching regexes
-
- Parameters
- ----------
- matching : list of strings or compiled regexes
- Regexes for the desired warning to catch
- Examples
- --------
- >>> from skimage import data, img_as_ubyte, img_as_float
- >>> with expected_warnings(['precision loss']):
- ... d = img_as_ubyte(img_as_float(data.coins()))
- Notes
- -----
- Uses `all_warnings` to ensure all warnings are raised.
- Upon exiting, it checks the recorded warnings for the desired matching
- pattern(s).
- Raises a ValueError if any match was not found or an unexpected
- warning was raised.
- Allows for three types of behaviors: "and", "or", and "optional" matches.
- This is done to accomodate different build enviroments or loop conditions
- that may produce different warnings. The behaviors can be combined.
- If you pass multiple patterns, you get an orderless "and", where all of the
- warnings must be raised.
- If you use the "|" operator in a pattern, you can catch one of several warnings.
- Finally, you can use "|\A\Z" in a pattern to signify it as optional.
- """
- with all_warnings() as w:
- # enter context
- yield w
- # exited user context, check the recorded warnings
- remaining = [m for m in matching if not '\A\Z' in m.split('|')]
- for warn in w:
- found = False
- for match in matching:
- if re.search(match, str(warn.message)) is not None:
- found = True
- if match in remaining:
- remaining.remove(match)
- if not found:
- raise ValueError('Unexpected warning: %s' % str(warn.message))
- if len(remaining) > 0:
- msg = 'No warning raised matching:\n%s' % '\n'.join(remaining)
- raise ValueError(msg)
+# From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py
+# Licensed under modified BSD license
+
+__all__ = ['all_warnings', 'expected_warnings']
+
+from contextlib import contextmanager
+import sys
+import warnings
+import inspect
+import re
+
+
+@contextmanager
+def all_warnings():
+ """
+ Context for use in testing to ensure that all warnings are raised.
+ Examples
+ --------
+ >>> import warnings
+ >>> def foo():
+ ... warnings.warn(RuntimeWarning("bar"))
+ We raise the warning once, while the warning filter is set to "once".
+ Hereafter, the warning is invisible, even with custom filters:
+ >>> with warnings.catch_warnings():
+ ... warnings.simplefilter('once')
+ ... foo()
+ We can now run ``foo()`` without a warning being raised:
+ >>> from numpy.testing import assert_warns
+ >>> foo()
+ To catch the warning, we call in the help of ``all_warnings``:
+ >>> with all_warnings():
+ ... assert_warns(RuntimeWarning, foo)
+ """
+
+ # Whenever a warning is triggered, Python adds a __warningregistry__
+ # member to the *calling* module. The exercize here is to find
+ # and eradicate all those breadcrumbs that were left lying around.
+ #
+ # We proceed by first searching all parent calling frames and explicitly
+ # clearing their warning registries (necessary for the doctests above to
+ # pass). Then, we search for all submodules of skimage and clear theirs
+ # as well (necessary for the skimage test suite to pass).
+
+ frame = inspect.currentframe()
+ if frame:
+ for f in inspect.getouterframes(frame):
+ f[0].f_locals['__warningregistry__'] = {}
+ del frame
+
+ for mod_name, mod in list(sys.modules.items()):
+ if 'six.moves' in mod_name:
+ continue
+ try:
+ mod.__warningregistry__.clear()
+ except AttributeError:
+ pass
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ yield w
+
+
+@contextmanager
+def expected_warnings(matching):
+ """Context for use in testing to catch known warnings matching regexes
+
+ Parameters
+ ----------
+ matching : list of strings or compiled regexes
+ Regexes for the desired warning to catch
+ Examples
+ --------
+ >>> from skimage import data, img_as_ubyte, img_as_float
+ >>> with expected_warnings(['precision loss']):
+ ... d = img_as_ubyte(img_as_float(data.coins()))
+ Notes
+ -----
+ Uses `all_warnings` to ensure all warnings are raised.
+ Upon exiting, it checks the recorded warnings for the desired matching
+ pattern(s).
+ Raises a ValueError if any match was not found or an unexpected
+ warning was raised.
+ Allows for three types of behaviors: "and", "or", and "optional" matches.
+ This is done to accomodate different build enviroments or loop conditions
+ that may produce different warnings. The behaviors can be combined.
+ If you pass multiple patterns, you get an orderless "and", where all of the
+ warnings must be raised.
+ If you use the "|" operator in a pattern, you can catch one of several warnings.
+ Finally, you can use "|\A\Z" in a pattern to signify it as optional.
+ """
+ with all_warnings() as w:
+ # enter context
+ yield w
+ # exited user context, check the recorded warnings
+ remaining = [m for m in matching if not '\A\Z' in m.split('|')]
+ for warn in w:
+ found = False
+ for match in matching:
+ if re.search(match, str(warn.message)) is not None:
+ found = True
+ if match in remaining:
+ remaining.remove(match)
+ if not found:
+ raise ValueError('Unexpected warning: %s' % str(warn.message))
+ if len(remaining) > 0:
+ msg = 'No warning raised matching:\n%s' % '\n'.join(remaining)
+ raise ValueError(msg)
diff --git a/contrib/python/traitlets/py2/traitlets/tests/test_traitlets.py b/contrib/python/traitlets/py2/traitlets/tests/test_traitlets.py
index 11b334cb60..5c0440f9ba 100644
--- a/contrib/python/traitlets/py2/traitlets/tests/test_traitlets.py
+++ b/contrib/python/traitlets/py2/traitlets/tests/test_traitlets.py
@@ -1,2419 +1,2419 @@
-# encoding: utf-8
-"""Tests for traitlets.traitlets."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-#
-# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
-# also under the terms of the Modified BSD License.
-
-import pickle
-import re
-import sys
+# encoding: utf-8
+"""Tests for traitlets.traitlets."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+#
+# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
+# also under the terms of the Modified BSD License.
+
+import pickle
+import re
+import sys
from ._warnings import expected_warnings
-
-from unittest import TestCase
-import pytest
-from pytest import mark
-
-from traitlets import (
- HasTraits, MetaHasTraits, TraitType, Any, Bool, CBytes, Dict, Enum,
- Int, CInt, Long, CLong, Integer, Float, CFloat, Complex, Bytes, Unicode,
- TraitError, Union, All, Undefined, Type, This, Instance, TCPAddress,
- List, Tuple, ObjectName, DottedObjectName, CRegExp, link, directional_link,
- ForwardDeclaredType, ForwardDeclaredInstance, validate, observe, default,
- observe_compat, BaseDescriptor, HasDescriptors,
-)
-
-import six
-
-def change_dict(*ordered_values):
- change_names = ('name', 'old', 'new', 'owner', 'type')
- return dict(zip(change_names, ordered_values))
-
-#-----------------------------------------------------------------------------
-# Helper classes for testing
-#-----------------------------------------------------------------------------
-
-
-class HasTraitsStub(HasTraits):
-
- def notify_change(self, change):
- self._notify_name = change['name']
- self._notify_old = change['old']
- self._notify_new = change['new']
- self._notify_type = change['type']
-
-
-#-----------------------------------------------------------------------------
-# Test classes
-#-----------------------------------------------------------------------------
-
-
-class TestTraitType(TestCase):
-
- def test_get_undefined(self):
- class A(HasTraits):
- a = TraitType
- a = A()
- with self.assertRaises(TraitError):
- a.a
-
- def test_set(self):
- class A(HasTraitsStub):
- a = TraitType
-
- a = A()
- a.a = 10
- self.assertEqual(a.a, 10)
- self.assertEqual(a._notify_name, 'a')
- self.assertEqual(a._notify_old, Undefined)
- self.assertEqual(a._notify_new, 10)
-
- def test_validate(self):
- class MyTT(TraitType):
- def validate(self, inst, value):
- return -1
- class A(HasTraitsStub):
- tt = MyTT
-
- a = A()
- a.tt = 10
- self.assertEqual(a.tt, -1)
-
- def test_default_validate(self):
- class MyIntTT(TraitType):
- def validate(self, obj, value):
- if isinstance(value, int):
- return value
- self.error(obj, value)
- class A(HasTraits):
- tt = MyIntTT(10)
- a = A()
- self.assertEqual(a.tt, 10)
-
- # Defaults are validated when the HasTraits is instantiated
- class B(HasTraits):
- tt = MyIntTT('bad default')
- self.assertRaises(TraitError, B)
-
- def test_info(self):
- class A(HasTraits):
- tt = TraitType
- a = A()
- self.assertEqual(A.tt.info(), 'any value')
-
- def test_error(self):
- class A(HasTraits):
- tt = TraitType
- a = A()
- self.assertRaises(TraitError, A.tt.error, a, 10)
-
- def test_deprecated_dynamic_initializer(self):
- class A(HasTraits):
- x = Int(10)
- def _x_default(self):
- return 11
- class B(A):
- x = Int(20)
- class C(A):
- def _x_default(self):
- return 21
-
- a = A()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
- b = B()
- self.assertEqual(b.x, 20)
- self.assertEqual(b._trait_values, {'x': 20})
- c = C()
- self.assertEqual(c._trait_values, {})
- self.assertEqual(c.x, 21)
- self.assertEqual(c._trait_values, {'x': 21})
- # Ensure that the base class remains unmolested when the _default
- # initializer gets overridden in a subclass.
- a = A()
- c = C()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
-
- def test_dynamic_initializer(self):
-
- class A(HasTraits):
- x = Int(10)
-
- @default('x')
- def _default_x(self):
- return 11
-
- class B(A):
- x = Int(20)
-
- class C(A):
-
- @default('x')
- def _default_x(self):
- return 21
-
- a = A()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
- b = B()
- self.assertEqual(b.x, 20)
- self.assertEqual(b._trait_values, {'x': 20})
- c = C()
- self.assertEqual(c._trait_values, {})
- self.assertEqual(c.x, 21)
- self.assertEqual(c._trait_values, {'x': 21})
- # Ensure that the base class remains unmolested when the _default
- # initializer gets overridden in a subclass.
- a = A()
- c = C()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
-
- def test_tag_metadata(self):
- class MyIntTT(TraitType):
- metadata = {'a': 1, 'b': 2}
- a = MyIntTT(10).tag(b=3, c=4)
- self.assertEqual(a.metadata, {'a': 1, 'b': 3, 'c': 4})
-
- def test_metadata_localized_instance(self):
- class MyIntTT(TraitType):
- metadata = {'a': 1, 'b': 2}
- a = MyIntTT(10)
- b = MyIntTT(10)
- a.metadata['c'] = 3
- # make sure that changing a's metadata didn't change b's metadata
- self.assertNotIn('c', b.metadata)
-
- def test_union_metadata(self):
- class Foo(HasTraits):
- bar = (Int().tag(ta=1) | Dict().tag(ta=2, ti='b')).tag(ti='a')
- foo = Foo()
- # At this point, no value has been set for bar, so value-specific
- # is not set.
- self.assertEqual(foo.trait_metadata('bar', 'ta'), None)
- self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
- foo.bar = {}
- self.assertEqual(foo.trait_metadata('bar', 'ta'), 2)
- self.assertEqual(foo.trait_metadata('bar', 'ti'), 'b')
- foo.bar = 1
- self.assertEqual(foo.trait_metadata('bar', 'ta'), 1)
- self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
-
- def test_union_default_value(self):
- class Foo(HasTraits):
- bar = Union([Dict(), Int()], default_value=1)
- foo = Foo()
- self.assertEqual(foo.bar, 1)
-
- def test_deprecated_metadata_access(self):
- class MyIntTT(TraitType):
- metadata = {'a': 1, 'b': 2}
- a = MyIntTT(10)
- with expected_warnings(["use the instance .metadata dictionary directly"]*2):
- a.set_metadata('key', 'value')
- v = a.get_metadata('key')
- self.assertEqual(v, 'value')
- with expected_warnings(["use the instance .help string directly"]*2):
- a.set_metadata('help', 'some help')
- v = a.get_metadata('help')
- self.assertEqual(v, 'some help')
-
- def test_trait_types_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = Int
-
- def test_trait_types_list_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = List(Int)
-
- def test_trait_types_tuple_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = Tuple(Int)
-
- def test_trait_types_dict_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = Dict(Int)
-
-class TestHasDescriptorsMeta(TestCase):
-
- def test_metaclass(self):
- self.assertEqual(type(HasTraits), MetaHasTraits)
-
- class A(HasTraits):
- a = Int()
-
- a = A()
- self.assertEqual(type(a.__class__), MetaHasTraits)
- self.assertEqual(a.a,0)
- a.a = 10
- self.assertEqual(a.a,10)
-
- class B(HasTraits):
- b = Int()
-
- b = B()
- self.assertEqual(b.b,0)
- b.b = 10
- self.assertEqual(b.b,10)
-
- class C(HasTraits):
- c = Int(30)
-
- c = C()
- self.assertEqual(c.c,30)
- c.c = 10
- self.assertEqual(c.c,10)
-
- def test_this_class(self):
- class A(HasTraits):
- t = This()
- tt = This()
- class B(A):
- tt = This()
- ttt = This()
- self.assertEqual(A.t.this_class, A)
- self.assertEqual(B.t.this_class, A)
- self.assertEqual(B.tt.this_class, B)
- self.assertEqual(B.ttt.this_class, B)
-
-class TestHasDescriptors(TestCase):
-
- def test_setup_instance(self):
-
- class FooDescriptor(BaseDescriptor):
-
- def instance_init(self, inst):
- foo = inst.foo # instance should have the attr
-
- class HasFooDescriptors(HasDescriptors):
-
- fd = FooDescriptor()
-
- def setup_instance(self, *args, **kwargs):
- self.foo = kwargs.get('foo', None)
- super(HasFooDescriptors, self).setup_instance(*args, **kwargs)
-
- hfd = HasFooDescriptors(foo='bar')
-
-class TestHasTraitsNotify(TestCase):
-
- def setUp(self):
- self._notify1 = []
- self._notify2 = []
-
- def notify1(self, name, old, new):
- self._notify1.append((name, old, new))
-
- def notify2(self, name, old, new):
- self._notify2.append((name, old, new))
-
- def test_notify_all(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.on_trait_change(self.notify1)
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.b = 0.0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- self.assertTrue(('a',0,10) in self._notify1)
- a.b = 10.0
- self.assertTrue(('b',0.0,10.0) in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
- self.assertRaises(TraitError,setattr,a,'b','bad string')
- self._notify1 = []
- a.on_trait_change(self.notify1,remove=True)
- a.a = 20
- a.b = 20.0
- self.assertEqual(len(self._notify1),0)
-
- def test_notify_one(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.on_trait_change(self.notify1, 'a')
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- self.assertTrue(('a',0,10) in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
-
- def test_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- self.assertEqual(b.a,0)
- self.assertEqual(b.b,0.0)
- b.a = 100
- b.b = 100.0
- self.assertEqual(b.a,100)
- self.assertEqual(b.b,100.0)
-
- def test_notify_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- b.on_trait_change(self.notify1, 'a')
- b.on_trait_change(self.notify2, 'b')
- b.a = 0
- b.b = 0.0
- self.assertEqual(len(self._notify1),0)
- self.assertEqual(len(self._notify2),0)
- b.a = 10
- b.b = 10.0
- self.assertTrue(('a',0,10) in self._notify1)
- self.assertTrue(('b',0.0,10.0) in self._notify2)
-
- def test_static_notify(self):
-
- class A(HasTraits):
- a = Int()
- _notify1 = []
- def _a_changed(self, name, old, new):
- self._notify1.append((name, old, new))
-
- a = A()
- a.a = 0
- # This is broken!!!
- self.assertEqual(len(a._notify1),0)
- a.a = 10
- self.assertTrue(('a',0,10) in a._notify1)
-
- class B(A):
- b = Float()
- _notify2 = []
- def _b_changed(self, name, old, new):
- self._notify2.append((name, old, new))
-
- b = B()
- b.a = 10
- b.b = 10.0
- self.assertTrue(('a',0,10) in b._notify1)
- self.assertTrue(('b',0.0,10.0) in b._notify2)
-
- def test_notify_args(self):
-
- def callback0():
- self.cb = ()
- def callback1(name):
- self.cb = (name,)
- def callback2(name, new):
- self.cb = (name, new)
- def callback3(name, old, new):
- self.cb = (name, old, new)
- def callback4(name, old, new, obj):
- self.cb = (name, old, new, obj)
-
- class A(HasTraits):
- a = Int()
-
- a = A()
- a.on_trait_change(callback0, 'a')
- a.a = 10
- self.assertEqual(self.cb,())
- a.on_trait_change(callback0, 'a', remove=True)
-
- a.on_trait_change(callback1, 'a')
- a.a = 100
- self.assertEqual(self.cb,('a',))
- a.on_trait_change(callback1, 'a', remove=True)
-
- a.on_trait_change(callback2, 'a')
- a.a = 1000
- self.assertEqual(self.cb,('a',1000))
- a.on_trait_change(callback2, 'a', remove=True)
-
- a.on_trait_change(callback3, 'a')
- a.a = 10000
- self.assertEqual(self.cb,('a',1000,10000))
- a.on_trait_change(callback3, 'a', remove=True)
-
- a.on_trait_change(callback4, 'a')
- a.a = 100000
- self.assertEqual(self.cb,('a',10000,100000,a))
- self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
- a.on_trait_change(callback4, 'a', remove=True)
-
- self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
-
- def test_notify_only_once(self):
-
- class A(HasTraits):
- listen_to = ['a']
-
- a = Int(0)
- b = 0
-
- def __init__(self, **kwargs):
- super(A, self).__init__(**kwargs)
- self.on_trait_change(self.listener1, ['a'])
-
- def listener1(self, name, old, new):
- self.b += 1
-
- class B(A):
-
- c = 0
- d = 0
-
- def __init__(self, **kwargs):
- super(B, self).__init__(**kwargs)
- self.on_trait_change(self.listener2)
-
- def listener2(self, name, old, new):
- self.c += 1
-
- def _a_changed(self, name, old, new):
- self.d += 1
-
- b = B()
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
-
-class TestObserveDecorator(TestCase):
-
- def setUp(self):
- self._notify1 = []
- self._notify2 = []
-
- def notify1(self, change):
- self._notify1.append(change)
-
- def notify2(self, change):
- self._notify2.append(change)
-
- def test_notify_all(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.observe(self.notify1)
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.b = 0.0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- change = change_dict('a', 0, 10, a, 'change')
- self.assertTrue(change in self._notify1)
- a.b = 10.0
- change = change_dict('b', 0.0, 10.0, a, 'change')
- self.assertTrue(change in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
- self.assertRaises(TraitError,setattr,a,'b','bad string')
- self._notify1 = []
- a.unobserve(self.notify1)
- a.a = 20
- a.b = 20.0
- self.assertEqual(len(self._notify1),0)
-
- def test_notify_one(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.observe(self.notify1, 'a')
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- change = change_dict('a', 0, 10, a, 'change')
- self.assertTrue(change in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
-
- def test_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- self.assertEqual(b.a,0)
- self.assertEqual(b.b,0.0)
- b.a = 100
- b.b = 100.0
- self.assertEqual(b.a,100)
- self.assertEqual(b.b,100.0)
-
- def test_notify_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- b.observe(self.notify1, 'a')
- b.observe(self.notify2, 'b')
- b.a = 0
- b.b = 0.0
- self.assertEqual(len(self._notify1),0)
- self.assertEqual(len(self._notify2),0)
- b.a = 10
- b.b = 10.0
- change = change_dict('a', 0, 10, b, 'change')
- self.assertTrue(change in self._notify1)
- change = change_dict('b', 0.0, 10.0, b, 'change')
- self.assertTrue(change in self._notify2)
-
- def test_static_notify(self):
-
- class A(HasTraits):
- a = Int()
- b = Int()
- _notify1 = []
- _notify_any = []
-
- @observe('a')
- def _a_changed(self, change):
- self._notify1.append(change)
-
- @observe(All)
- def _any_changed(self, change):
- self._notify_any.append(change)
-
- a = A()
- a.a = 0
- self.assertEqual(len(a._notify1),0)
- a.a = 10
- change = change_dict('a', 0, 10, a, 'change')
- self.assertTrue(change in a._notify1)
- a.b = 1
- self.assertEqual(len(a._notify_any), 2)
- change = change_dict('b', 0, 1, a, 'change')
- self.assertTrue(change in a._notify_any)
-
- class B(A):
- b = Float()
- _notify2 = []
- @observe('b')
- def _b_changed(self, change):
- self._notify2.append(change)
-
- b = B()
- b.a = 10
- b.b = 10.0
- change = change_dict('a', 0, 10, b, 'change')
- self.assertTrue(change in b._notify1)
- change = change_dict('b', 0.0, 10.0, b, 'change')
- self.assertTrue(change in b._notify2)
-
- def test_notify_args(self):
-
- def callback0():
- self.cb = ()
- def callback1(change):
- self.cb = change
-
- class A(HasTraits):
- a = Int()
-
- a = A()
- a.on_trait_change(callback0, 'a')
- a.a = 10
- self.assertEqual(self.cb,())
- a.unobserve(callback0, 'a')
-
- a.observe(callback1, 'a')
- a.a = 100
- change = change_dict('a', 10, 100, a, 'change')
- self.assertEqual(self.cb, change)
- self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
- a.unobserve(callback1, 'a')
-
- self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
-
- def test_notify_only_once(self):
-
- class A(HasTraits):
- listen_to = ['a']
-
- a = Int(0)
- b = 0
-
- def __init__(self, **kwargs):
- super(A, self).__init__(**kwargs)
- self.observe(self.listener1, ['a'])
-
- def listener1(self, change):
- self.b += 1
-
- class B(A):
-
- c = 0
- d = 0
-
- def __init__(self, **kwargs):
- super(B, self).__init__(**kwargs)
- self.observe(self.listener2)
-
- def listener2(self, change):
- self.c += 1
-
- @observe('a')
- def _a_changed(self, change):
- self.d += 1
-
- b = B()
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
-
-
-class TestHasTraits(TestCase):
-
- def test_trait_names(self):
- class A(HasTraits):
- i = Int()
- f = Float()
- a = A()
- self.assertEqual(sorted(a.trait_names()),['f','i'])
- self.assertEqual(sorted(A.class_trait_names()),['f','i'])
- self.assertTrue(a.has_trait('f'))
- self.assertFalse(a.has_trait('g'))
-
- def test_trait_metadata_deprecated(self):
- with expected_warnings(['metadata should be set using the \.tag\(\) method']):
- class A(HasTraits):
- i = Int(config_key='MY_VALUE')
- a = A()
- self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
-
- def test_trait_metadata(self):
- class A(HasTraits):
- i = Int().tag(config_key='MY_VALUE')
- a = A()
- self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
-
- def test_trait_metadata_default(self):
- class A(HasTraits):
- i = Int()
- a = A()
- self.assertEqual(a.trait_metadata('i', 'config_key'), None)
- self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default')
-
- def test_traits(self):
- class A(HasTraits):
- i = Int()
- f = Float()
- a = A()
- self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
- self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))
-
- def test_traits_metadata(self):
- class A(HasTraits):
- i = Int().tag(config_key='VALUE1', other_thing='VALUE2')
- f = Float().tag(config_key='VALUE3', other_thing='VALUE2')
- j = Int(0)
- a = A()
- self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
- traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
- self.assertEqual(traits, dict(i=A.i))
-
- # This passes, but it shouldn't because I am replicating a bug in
- # traits.
- traits = a.traits(config_key=lambda v: True)
- self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
-
- def test_traits_metadata_deprecated(self):
- with expected_warnings(['metadata should be set using the \.tag\(\) method']*2):
- class A(HasTraits):
- i = Int(config_key='VALUE1', other_thing='VALUE2')
- f = Float(config_key='VALUE3', other_thing='VALUE2')
- j = Int(0)
- a = A()
- self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
- traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
- self.assertEqual(traits, dict(i=A.i))
-
- # This passes, but it shouldn't because I am replicating a bug in
- # traits.
- traits = a.traits(config_key=lambda v: True)
- self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
-
-
- def test_init(self):
- class A(HasTraits):
- i = Int()
- x = Float()
- a = A(i=1, x=10.0)
- self.assertEqual(a.i, 1)
- self.assertEqual(a.x, 10.0)
-
- def test_positional_args(self):
- class A(HasTraits):
- i = Int(0)
- def __init__(self, i):
- super(A, self).__init__()
- self.i = i
-
- a = A(5)
- self.assertEqual(a.i, 5)
- # should raise TypeError if no positional arg given
- self.assertRaises(TypeError, A)
-
-#-----------------------------------------------------------------------------
-# Tests for specific trait types
-#-----------------------------------------------------------------------------
-
-
-class TestType(TestCase):
-
- def test_default(self):
-
- class B(object): pass
- class A(HasTraits):
- klass = Type(allow_none=True)
-
- a = A()
- self.assertEqual(a.klass, object)
-
- a.klass = B
- self.assertEqual(a.klass, B)
- self.assertRaises(TraitError, setattr, a, 'klass', 10)
-
- def test_default_options(self):
-
- class B(object): pass
- class C(B): pass
- class A(HasTraits):
- # Different possible combinations of options for default_value
- # and klass. default_value=None is only valid with allow_none=True.
- k1 = Type()
- k2 = Type(None, allow_none=True)
- k3 = Type(B)
- k4 = Type(klass=B)
- k5 = Type(default_value=None, klass=B, allow_none=True)
- k6 = Type(default_value=C, klass=B)
-
- self.assertIs(A.k1.default_value, object)
- self.assertIs(A.k1.klass, object)
- self.assertIs(A.k2.default_value, None)
- self.assertIs(A.k2.klass, object)
- self.assertIs(A.k3.default_value, B)
- self.assertIs(A.k3.klass, B)
- self.assertIs(A.k4.default_value, B)
- self.assertIs(A.k4.klass, B)
- self.assertIs(A.k5.default_value, None)
- self.assertIs(A.k5.klass, B)
- self.assertIs(A.k6.default_value, C)
- self.assertIs(A.k6.klass, B)
-
- a = A()
- self.assertIs(a.k1, object)
- self.assertIs(a.k2, None)
- self.assertIs(a.k3, B)
- self.assertIs(a.k4, B)
- self.assertIs(a.k5, None)
- self.assertIs(a.k6, C)
-
- def test_value(self):
-
- class B(object): pass
- class C(object): pass
- class A(HasTraits):
- klass = Type(B)
-
- a = A()
- self.assertEqual(a.klass, B)
- self.assertRaises(TraitError, setattr, a, 'klass', C)
- self.assertRaises(TraitError, setattr, a, 'klass', object)
- a.klass = B
-
- def test_allow_none(self):
-
- class B(object): pass
- class C(B): pass
- class A(HasTraits):
- klass = Type(B)
-
- a = A()
- self.assertEqual(a.klass, B)
- self.assertRaises(TraitError, setattr, a, 'klass', None)
- a.klass = C
- self.assertEqual(a.klass, C)
-
- def test_validate_klass(self):
-
- class A(HasTraits):
- klass = Type('no strings allowed')
-
- self.assertRaises(ImportError, A)
-
- class A(HasTraits):
- klass = Type('rub.adub.Duck')
-
- self.assertRaises(ImportError, A)
-
- def test_validate_default(self):
-
- class B(object): pass
- class A(HasTraits):
- klass = Type('bad default', B)
-
- self.assertRaises(ImportError, A)
-
- class C(HasTraits):
- klass = Type(None, B)
-
- self.assertRaises(TraitError, C)
-
- def test_str_klass(self):
-
- class A(HasTraits):
- klass = Type('ipython_genutils.ipstruct.Struct')
-
- from ipython_genutils.ipstruct import Struct
- a = A()
- a.klass = Struct
- self.assertEqual(a.klass, Struct)
-
- self.assertRaises(TraitError, setattr, a, 'klass', 10)
-
- def test_set_str_klass(self):
-
- class A(HasTraits):
- klass = Type()
-
- a = A(klass='ipython_genutils.ipstruct.Struct')
- from ipython_genutils.ipstruct import Struct
- self.assertEqual(a.klass, Struct)
-
-class TestInstance(TestCase):
-
- def test_basic(self):
- class Foo(object): pass
- class Bar(Foo): pass
- class Bah(object): pass
-
- class A(HasTraits):
- inst = Instance(Foo, allow_none=True)
-
- a = A()
- self.assertTrue(a.inst is None)
- a.inst = Foo()
- self.assertTrue(isinstance(a.inst, Foo))
- a.inst = Bar()
- self.assertTrue(isinstance(a.inst, Foo))
- self.assertRaises(TraitError, setattr, a, 'inst', Foo)
- self.assertRaises(TraitError, setattr, a, 'inst', Bar)
- self.assertRaises(TraitError, setattr, a, 'inst', Bah())
-
- def test_default_klass(self):
- class Foo(object): pass
- class Bar(Foo): pass
- class Bah(object): pass
-
- class FooInstance(Instance):
- klass = Foo
-
- class A(HasTraits):
- inst = FooInstance(allow_none=True)
-
- a = A()
- self.assertTrue(a.inst is None)
- a.inst = Foo()
- self.assertTrue(isinstance(a.inst, Foo))
- a.inst = Bar()
- self.assertTrue(isinstance(a.inst, Foo))
- self.assertRaises(TraitError, setattr, a, 'inst', Foo)
- self.assertRaises(TraitError, setattr, a, 'inst', Bar)
- self.assertRaises(TraitError, setattr, a, 'inst', Bah())
-
- def test_unique_default_value(self):
- class Foo(object): pass
- class A(HasTraits):
- inst = Instance(Foo,(),{})
-
- a = A()
- b = A()
- self.assertTrue(a.inst is not b.inst)
-
- def test_args_kw(self):
- class Foo(object):
- def __init__(self, c): self.c = c
- class Bar(object): pass
- class Bah(object):
- def __init__(self, c, d):
- self.c = c; self.d = d
-
- class A(HasTraits):
- inst = Instance(Foo, (10,))
- a = A()
- self.assertEqual(a.inst.c, 10)
-
- class B(HasTraits):
- inst = Instance(Bah, args=(10,), kw=dict(d=20))
- b = B()
- self.assertEqual(b.inst.c, 10)
- self.assertEqual(b.inst.d, 20)
-
- class C(HasTraits):
- inst = Instance(Foo, allow_none=True)
- c = C()
- self.assertTrue(c.inst is None)
-
- def test_bad_default(self):
- class Foo(object): pass
-
- class A(HasTraits):
- inst = Instance(Foo)
-
- a = A()
- with self.assertRaises(TraitError):
- a.inst
-
- def test_instance(self):
- class Foo(object): pass
-
- def inner():
- class A(HasTraits):
- inst = Instance(Foo())
-
- self.assertRaises(TraitError, inner)
-
-
-class TestThis(TestCase):
-
- def test_this_class(self):
- class Foo(HasTraits):
- this = This()
-
- f = Foo()
- self.assertEqual(f.this, None)
- g = Foo()
- f.this = g
- self.assertEqual(f.this, g)
- self.assertRaises(TraitError, setattr, f, 'this', 10)
-
- def test_this_inst(self):
- class Foo(HasTraits):
- this = This()
-
- f = Foo()
- f.this = Foo()
- self.assertTrue(isinstance(f.this, Foo))
-
- def test_subclass(self):
- class Foo(HasTraits):
- t = This()
- class Bar(Foo):
- pass
- f = Foo()
- b = Bar()
- f.t = b
- b.t = f
- self.assertEqual(f.t, b)
- self.assertEqual(b.t, f)
-
- def test_subclass_override(self):
- class Foo(HasTraits):
- t = This()
- class Bar(Foo):
- t = This()
- f = Foo()
- b = Bar()
- f.t = b
- self.assertEqual(f.t, b)
- self.assertRaises(TraitError, setattr, b, 't', f)
-
- def test_this_in_container(self):
-
- class Tree(HasTraits):
- value = Unicode()
- leaves = List(This())
-
- tree = Tree(
- value='foo',
- leaves=[Tree(value='bar'), Tree(value='buzz')]
- )
-
- with self.assertRaises(TraitError):
- tree.leaves = [1, 2]
-
-class TraitTestBase(TestCase):
- """A best testing class for basic trait types."""
-
- def assign(self, value):
- self.obj.value = value
-
- def coerce(self, value):
- return value
-
- def test_good_values(self):
- if hasattr(self, '_good_values'):
- for value in self._good_values:
- self.assign(value)
- self.assertEqual(self.obj.value, self.coerce(value))
-
- def test_bad_values(self):
- if hasattr(self, '_bad_values'):
- for value in self._bad_values:
- try:
- self.assertRaises(TraitError, self.assign, value)
- except AssertionError:
- assert False, value
-
- def test_default_value(self):
- if hasattr(self, '_default_value'):
- self.assertEqual(self._default_value, self.obj.value)
-
- def test_allow_none(self):
- if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and
- None in self._bad_values):
- trait=self.obj.traits()['value']
- try:
- trait.allow_none = True
- self._bad_values.remove(None)
- #skip coerce. Allow None casts None to None.
- self.assign(None)
- self.assertEqual(self.obj.value,None)
- self.test_good_values()
- self.test_bad_values()
- finally:
- #tear down
- trait.allow_none = False
- self._bad_values.append(None)
-
- def tearDown(self):
- # restore default value after tests, if set
- if hasattr(self, '_default_value'):
- self.obj.value = self._default_value
-
-
-class AnyTrait(HasTraits):
-
- value = Any()
-
-class AnyTraitTest(TraitTestBase):
-
- obj = AnyTrait()
-
- _default_value = None
- _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
- _bad_values = []
-
-class UnionTrait(HasTraits):
-
- value = Union([Type(), Bool()])
-
-class UnionTraitTest(TraitTestBase):
-
- obj = UnionTrait(value='ipython_genutils.ipstruct.Struct')
- _good_values = [int, float, True]
- _bad_values = [[], (0,), 1j]
-
-class OrTrait(HasTraits):
-
- value = Bool() | Unicode()
-
-class OrTraitTest(TraitTestBase):
-
- obj = OrTrait()
- _good_values = [True, False, 'ten']
- _bad_values = [[], (0,), 1j]
-
-class IntTrait(HasTraits):
-
- value = Int(99, min=-100)
-
-class TestInt(TraitTestBase):
-
- obj = IntTrait()
- _default_value = 99
- _good_values = [10, -10]
- _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None, 1j,
- 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
- u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', -200]
- if not six.PY3:
- _bad_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
-
-
-class CIntTrait(HasTraits):
- value = CInt('5')
-
-class TestCInt(TraitTestBase):
- obj = CIntTrait()
-
- _default_value = 5
- _good_values = ['10', '-10', u'10', u'-10', 10, 10.0, -10.0, 10.1]
- _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
- None, 1j, '10.1', u'10.1']
-
- def coerce(self, n):
- return int(n)
-
-
-class MinBoundCIntTrait(HasTraits):
- value = CInt('5', min=3)
-
-class TestMinBoundCInt(TestCInt):
- obj = MinBoundCIntTrait()
-
- _default_value = 5
- _good_values = [3, 3.0, '3']
- _bad_values = [2.6, 2, -3, -3.0]
-
-
-class LongTrait(HasTraits):
-
- value = Long(99 if six.PY3 else long(99))
-
-class TestLong(TraitTestBase):
-
- obj = LongTrait()
-
- _default_value = 99 if six.PY3 else long(99)
- _good_values = [10, -10]
- _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
- None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
- '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
- u'-10.1']
- if not six.PY3:
- # maxint undefined on py3, because int == long
- _good_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
- _bad_values.extend([[long(10)], (long(10),)])
-
- @mark.skipif(six.PY3, reason="not relevant on py3")
- def test_cast_small(self):
- """Long casts ints to long"""
- self.obj.value = 10
- self.assertEqual(type(self.obj.value), long)
-
-
-class MinBoundLongTrait(HasTraits):
- value = Long(99 if six.PY3 else long(99), min=5)
-
-class TestMinBoundLong(TraitTestBase):
- obj = MinBoundLongTrait()
-
- _default_value = 99 if six.PY3 else long(99)
- _good_values = [5, 10]
- _bad_values = [4, -10]
-
-
-class MaxBoundLongTrait(HasTraits):
- value = Long(5 if six.PY3 else long(5), max=10)
-
-class TestMaxBoundLong(TraitTestBase):
- obj = MaxBoundLongTrait()
-
- _default_value = 5 if six.PY3 else long(5)
- _good_values = [10, -2]
- _bad_values = [11, 20]
-
-
-class CLongTrait(HasTraits):
- value = CLong('5')
-
-class TestCLong(TraitTestBase):
- obj = CLongTrait()
-
- _default_value = 5 if six.PY3 else long(5)
- _good_values = ['10', '-10', u'10', u'-10', 10, 10.0, -10.0, 10.1]
- _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
- None, 1j, '10.1', u'10.1']
-
- def coerce(self, n):
- return int(n) if six.PY3 else long(n)
-
-
-class MaxBoundCLongTrait(HasTraits):
- value = CLong('5', max=10)
-
-class TestMaxBoundCLong(TestCLong):
- obj = MaxBoundCLongTrait()
-
- _default_value = 5 if six.PY3 else long(5)
- _good_values = [10, '10', 10.3]
- _bad_values = [11.0, '11']
-
-
-class IntegerTrait(HasTraits):
- value = Integer(1)
-
-class TestInteger(TestLong):
- obj = IntegerTrait()
- _default_value = 1
-
- def coerce(self, n):
- return int(n)
-
- @mark.skipif(six.PY3, reason="not relevant on py3")
- def test_cast_small(self):
- """Integer casts small longs to int"""
-
- self.obj.value = long(100)
- self.assertEqual(type(self.obj.value), int)
-
-
-class MinBoundIntegerTrait(HasTraits):
- value = Integer(5, min=3)
-
-class TestMinBoundInteger(TraitTestBase):
- obj = MinBoundIntegerTrait()
-
- _default_value = 5
- _good_values = 3, 20
- _bad_values = [2, -10]
-
-
-class MaxBoundIntegerTrait(HasTraits):
- value = Integer(1, max=3)
-
-class TestMaxBoundInteger(TraitTestBase):
- obj = MaxBoundIntegerTrait()
-
- _default_value = 1
- _good_values = 3, -2
- _bad_values = [4, 10]
-
-
-class FloatTrait(HasTraits):
-
- value = Float(99.0, max=200.0)
-
-class TestFloat(TraitTestBase):
-
- obj = FloatTrait()
-
- _default_value = 99.0
- _good_values = [10, -10, 10.1, -10.1]
- _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None,
- 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
- u'-10', u'10L', u'-10L', u'10.1', u'-10.1', 201.0]
- if not six.PY3:
- _bad_values.extend([long(10), long(-10)])
-
-
-class CFloatTrait(HasTraits):
-
- value = CFloat('99.0', max=200.0)
-
-class TestCFloat(TraitTestBase):
-
- obj = CFloatTrait()
-
- _default_value = 99.0
- _good_values = [10, 10.0, 10.5, '10.0', '10', '-10', '10.0', u'10']
- _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None, 1j,
- 200.1, '200.1']
-
- def coerce(self, v):
- return float(v)
-
-
-class ComplexTrait(HasTraits):
-
- value = Complex(99.0-99.0j)
-
-class TestComplex(TraitTestBase):
-
- obj = ComplexTrait()
-
- _default_value = 99.0-99.0j
- _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
- 10.1j, 10.1+10.1j, 10.1-10.1j]
- _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
- if not six.PY3:
- _bad_values.extend([long(10), long(-10)])
-
-
-class BytesTrait(HasTraits):
-
- value = Bytes(b'string')
-
-class TestBytes(TraitTestBase):
-
- obj = BytesTrait()
-
- _default_value = b'string'
- _good_values = [b'10', b'-10', b'10L',
- b'-10L', b'10.1', b'-10.1', b'string']
- _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
- ['ten'],{'ten': 10},(10,), None, u'string']
- if not six.PY3:
- _bad_values.extend([long(10), long(-10)])
-
-
-class UnicodeTrait(HasTraits):
-
- value = Unicode(u'unicode')
-
-class TestUnicode(TraitTestBase):
-
- obj = UnicodeTrait()
-
- _default_value = u'unicode'
- _good_values = ['10', '-10', '10L', '-10L', '10.1',
- '-10.1', '', u'', 'string', u'string', u"€"]
- _bad_values = [10, -10, 10.1, -10.1, 1j,
- [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
- if not six.PY3:
- _bad_values.extend([long(10), long(-10)])
-
-
-class ObjectNameTrait(HasTraits):
- value = ObjectName("abc")
-
-class TestObjectName(TraitTestBase):
- obj = ObjectNameTrait()
-
- _default_value = "abc"
- _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
- _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
- None, object(), object]
- if sys.version_info[0] < 3:
- _bad_values.append(u"þ")
- else:
- _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131).
-
-
-class DottedObjectNameTrait(HasTraits):
- value = DottedObjectName("a.b")
-
-class TestDottedObjectName(TraitTestBase):
- obj = DottedObjectNameTrait()
-
- _default_value = "a.b"
- _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
- _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]
- if sys.version_info[0] < 3:
- _bad_values.append(u"t.þ")
- else:
- _good_values.append(u"t.þ")
-
-
-class TCPAddressTrait(HasTraits):
- value = TCPAddress()
-
-class TestTCPAddress(TraitTestBase):
-
- obj = TCPAddressTrait()
-
- _default_value = ('127.0.0.1',0)
- _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
- _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]
-
-class ListTrait(HasTraits):
-
- value = List(Int())
-
-class TestList(TraitTestBase):
-
- obj = ListTrait()
-
- _default_value = []
- _good_values = [[], [1], list(range(10)), (1,2)]
- _bad_values = [10, [1,'a'], 'a']
-
- def coerce(self, value):
- if value is not None:
- value = list(value)
- return value
-
-class Foo(object):
- pass
-
-class NoneInstanceListTrait(HasTraits):
-
- value = List(Instance(Foo))
-
-class TestNoneInstanceList(TraitTestBase):
-
- obj = NoneInstanceListTrait()
-
- _default_value = []
- _good_values = [[Foo(), Foo()], []]
- _bad_values = [[None], [Foo(), None]]
-
-
-class InstanceListTrait(HasTraits):
-
- value = List(Instance(__name__+'.Foo'))
-
-class TestInstanceList(TraitTestBase):
-
- obj = InstanceListTrait()
-
- def test_klass(self):
- """Test that the instance klass is properly assigned."""
- self.assertIs(self.obj.traits()['value']._trait.klass, Foo)
-
- _default_value = []
- _good_values = [[Foo(), Foo()], []]
- _bad_values = [['1', 2,], '1', [Foo], None]
-
-class UnionListTrait(HasTraits):
-
- value = List(Int() | Bool())
-
-class TestUnionListTrait(HasTraits):
-
- obj = UnionListTrait()
-
- _default_value = []
- _good_values = [[True, 1], [False, True]]
- _bad_values = [[1, 'True'], False]
-
-
-class LenListTrait(HasTraits):
-
- value = List(Int(), [0], minlen=1, maxlen=2)
-
-class TestLenList(TraitTestBase):
-
- obj = LenListTrait()
-
- _default_value = [0]
- _good_values = [[1], [1,2], (1,2)]
- _bad_values = [10, [1,'a'], 'a', [], list(range(3))]
-
- def coerce(self, value):
- if value is not None:
- value = list(value)
- return value
-
-class TupleTrait(HasTraits):
-
- value = Tuple(Int(allow_none=True), default_value=(1,))
-
-class TestTupleTrait(TraitTestBase):
-
- obj = TupleTrait()
-
- _default_value = (1,)
- _good_values = [(1,), (0,), [1]]
- _bad_values = [10, (1, 2), ('a'), (), None]
-
- def coerce(self, value):
- if value is not None:
- value = tuple(value)
- return value
-
- def test_invalid_args(self):
- self.assertRaises(TypeError, Tuple, 5)
- self.assertRaises(TypeError, Tuple, default_value='hello')
- t = Tuple(Int(), CBytes(), default_value=(1,5))
-
-class LooseTupleTrait(HasTraits):
-
- value = Tuple((1,2,3))
-
-class TestLooseTupleTrait(TraitTestBase):
-
- obj = LooseTupleTrait()
-
- _default_value = (1,2,3)
- _good_values = [(1,), [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
- _bad_values = [10, 'hello', {}, None]
-
- def coerce(self, value):
- if value is not None:
- value = tuple(value)
- return value
-
- def test_invalid_args(self):
- self.assertRaises(TypeError, Tuple, 5)
- self.assertRaises(TypeError, Tuple, default_value='hello')
- t = Tuple(Int(), CBytes(), default_value=(1,5))
-
-
-class MultiTupleTrait(HasTraits):
-
- value = Tuple(Int(), Bytes(), default_value=[99,b'bottles'])
-
-class TestMultiTuple(TraitTestBase):
-
- obj = MultiTupleTrait()
-
- _default_value = (99,b'bottles')
- _good_values = [(1,b'a'), (2,b'b')]
- _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
-
-class CRegExpTrait(HasTraits):
-
- value = CRegExp(r'')
-
-class TestCRegExp(TraitTestBase):
-
- def coerce(self, value):
- return re.compile(value)
-
- obj = CRegExpTrait()
-
- _default_value = re.compile(r'')
- _good_values = [r'\d+', re.compile(r'\d+')]
- _bad_values = ['(', None, ()]
-
-class DictTrait(HasTraits):
- value = Dict()
-
-def test_dict_assignment():
- d = dict()
- c = DictTrait()
- c.value = d
- d['a'] = 5
- assert d == c.value
- assert c.value is d
-
-
-class UniformlyValidatedDictTrait(HasTraits):
-
- value = Dict(trait=Unicode(),
- default_value={'foo': '1'})
-
-
-class TestInstanceUniformlyValidatedDict(TraitTestBase):
-
- obj = UniformlyValidatedDictTrait()
-
- _default_value = {'foo': '1'}
- _good_values = [{'foo': '0', 'bar': '1'}]
- _bad_values = [{'foo': 0, 'bar': '1'}]
-
-
-class KeyValidatedDictTrait(HasTraits):
-
- value = Dict(traits={'foo': Int()},
- default_value={'foo': 1})
-
-
-class TestInstanceKeyValidatedDict(TraitTestBase):
-
- obj = KeyValidatedDictTrait()
-
- _default_value = {'foo': 1}
- _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 0, 'bar': 1}]
- _bad_values = [{'foo': '0', 'bar': '1'}]
-
-
-class FullyValidatedDictTrait(HasTraits):
-
- value = Dict(trait=Unicode(),
- traits={'foo': Int()},
- default_value={'foo': 1})
-
-
-class TestInstanceFullyValidatedDict(TraitTestBase):
-
- obj = FullyValidatedDictTrait()
-
- _default_value = {'foo': 1}
- _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 1, 'bar': '2'}]
- _bad_values = [{'foo': 0, 'bar': 1}, {'foo': '0', 'bar': '1'}]
-
-
-def test_dict_default_value():
- """Check that the `{}` default value of the Dict traitlet constructor is
- actually copied."""
-
- class Foo(HasTraits):
- d1 = Dict()
- d2 = Dict()
-
- foo = Foo()
- assert foo.d1 == {}
- assert foo.d2 == {}
- assert foo.d1 is not foo.d2
-
-
-class TestValidationHook(TestCase):
-
- def test_parity_trait(self):
- """Verify that the early validation hook is effective"""
-
- class Parity(HasTraits):
-
- value = Int(0)
- parity = Enum(['odd', 'even'], default_value='even')
-
- @validate('value')
- def _value_validate(self, proposal):
- value = proposal['value']
- if self.parity == 'even' and value % 2:
- raise TraitError('Expected an even number')
- if self.parity == 'odd' and (value % 2 == 0):
- raise TraitError('Expected an odd number')
- return value
-
- u = Parity()
- u.parity = 'odd'
- u.value = 1 # OK
- with self.assertRaises(TraitError):
- u.value = 2 # Trait Error
-
- u.parity = 'even'
- u.value = 2 # OK
-
- def test_multiple_validate(self):
- """Verify that we can register the same validator to multiple names"""
-
- class OddEven(HasTraits):
-
- odd = Int(1)
- even = Int(0)
-
- @validate('odd', 'even')
- def check_valid(self, proposal):
- if proposal['trait'].name == 'odd' and not proposal['value'] % 2:
- raise TraitError('odd should be odd')
- if proposal['trait'].name == 'even' and proposal['value'] % 2:
- raise TraitError('even should be even')
-
- u = OddEven()
- u.odd = 3 # OK
- with self.assertRaises(TraitError):
- u.odd = 2 # Trait Error
-
- u.even = 2 # OK
- with self.assertRaises(TraitError):
- u.even = 3 # Trait Error
-
-
-
-class TestLink(TestCase):
-
- def test_connect_same(self):
- """Verify two traitlets of the same type can be linked together using link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Conenct the two classes.
- c = link((a, 'value'), (b, 'value'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.value)
-
- # Change one of the values to make sure they stay in sync.
- a.value = 5
- self.assertEqual(a.value, b.value)
- b.value = 6
- self.assertEqual(a.value, b.value)
-
- def test_link_different(self):
- """Verify two traitlets of different types can be linked together using link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- class B(HasTraits):
- count = Int()
- a = A(value=9)
- b = B(count=8)
-
- # Conenct the two classes.
- c = link((a, 'value'), (b, 'count'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.count)
-
- # Change one of the values to make sure they stay in sync.
- a.value = 5
- self.assertEqual(a.value, b.count)
- b.count = 4
- self.assertEqual(a.value, b.count)
-
- def test_unlink(self):
- """Verify two linked traitlets can be unlinked."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Connect the two classes.
- c = link((a, 'value'), (b, 'value'))
- a.value = 4
- c.unlink()
-
- # Change one of the values to make sure they don't stay in sync.
- a.value = 5
- self.assertNotEqual(a.value, b.value)
-
- def test_callbacks(self):
- """Verify two linked traitlets have their callbacks called once."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- class B(HasTraits):
- count = Int()
- a = A(value=9)
- b = B(count=8)
-
- # Register callbacks that count.
- callback_count = []
- def a_callback(name, old, new):
- callback_count.append('a')
- a.on_trait_change(a_callback, 'value')
- def b_callback(name, old, new):
- callback_count.append('b')
- b.on_trait_change(b_callback, 'count')
-
- # Connect the two classes.
- c = link((a, 'value'), (b, 'count'))
-
- # Make sure b's count was set to a's value once.
- self.assertEqual(''.join(callback_count), 'b')
- del callback_count[:]
-
- # Make sure a's value was set to b's count once.
- b.count = 5
- self.assertEqual(''.join(callback_count), 'ba')
- del callback_count[:]
-
- # Make sure b's count was set to a's value once.
- a.value = 4
- self.assertEqual(''.join(callback_count), 'ab')
- del callback_count[:]
-
-class TestDirectionalLink(TestCase):
- def test_connect_same(self):
- """Verify two traitlets of the same type can be linked together using directional_link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Conenct the two classes.
- c = directional_link((a, 'value'), (b, 'value'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.value)
-
- # Change one the value of the source and check that it synchronizes the target.
- a.value = 5
- self.assertEqual(b.value, 5)
- # Change one the value of the target and check that it has no impact on the source
- b.value = 6
- self.assertEqual(a.value, 5)
-
- def test_tranform(self):
- """Test transform link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Conenct the two classes.
- c = directional_link((a, 'value'), (b, 'value'), lambda x: 2 * x)
-
- # Make sure the values are correct at the point of linking.
- self.assertEqual(b.value, 2 * a.value)
-
- # Change one the value of the source and check that it modifies the target.
- a.value = 5
- self.assertEqual(b.value, 10)
- # Change one the value of the target and check that it has no impact on the source
- b.value = 6
- self.assertEqual(a.value, 5)
-
- def test_link_different(self):
- """Verify two traitlets of different types can be linked together using link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- class B(HasTraits):
- count = Int()
- a = A(value=9)
- b = B(count=8)
-
- # Conenct the two classes.
- c = directional_link((a, 'value'), (b, 'count'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.count)
-
- # Change one the value of the source and check that it synchronizes the target.
- a.value = 5
- self.assertEqual(b.count, 5)
- # Change one the value of the target and check that it has no impact on the source
- b.value = 6
- self.assertEqual(a.value, 5)
-
- def test_unlink(self):
- """Verify two linked traitlets can be unlinked."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Connect the two classes.
- c = directional_link((a, 'value'), (b, 'value'))
- a.value = 4
- c.unlink()
-
- # Change one of the values to make sure they don't stay in sync.
- a.value = 5
- self.assertNotEqual(a.value, b.value)
-
-class Pickleable(HasTraits):
-
- i = Int()
- @observe('i')
- def _i_changed(self, change): pass
- @validate('i')
- def _i_validate(self, commit):
- return commit['value']
-
- j = Int()
-
- def __init__(self):
- with self.hold_trait_notifications():
- self.i = 1
- self.on_trait_change(self._i_changed, 'i')
-
-def test_pickle_hastraits():
- c = Pickleable()
- for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
- p = pickle.dumps(c, protocol)
- c2 = pickle.loads(p)
- assert c2.i == c.i
- assert c2.j == c.j
-
- c.i = 5
- for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
- p = pickle.dumps(c, protocol)
- c2 = pickle.loads(p)
- assert c2.i == c.i
- assert c2.j == c.j
-
-
-def test_hold_trait_notifications():
- changes = []
-
- class Test(HasTraits):
- a = Integer(0)
- b = Integer(0)
-
- def _a_changed(self, name, old, new):
- changes.append((old, new))
-
- def _b_validate(self, value, trait):
- if value != 0:
- raise TraitError('Only 0 is a valid value')
- return value
-
- # Test context manager and nesting
- t = Test()
- with t.hold_trait_notifications():
- with t.hold_trait_notifications():
- t.a = 1
- assert t.a == 1
- assert changes == []
- t.a = 2
- assert t.a == 2
- with t.hold_trait_notifications():
- t.a = 3
- assert t.a == 3
- assert changes == []
- t.a = 4
- assert t.a == 4
- assert changes == []
- t.a = 4
- assert t.a == 4
- assert changes == []
-
- assert changes == [(0, 4)]
- # Test roll-back
- try:
- with t.hold_trait_notifications():
- t.b = 1 # raises a Trait error
- except:
- pass
- assert t.b == 0
-
-
-class RollBack(HasTraits):
- bar = Int()
- def _bar_validate(self, value, trait):
- if value:
- raise TraitError('foobar')
- return value
-
-
-class TestRollback(TestCase):
-
- def test_roll_back(self):
-
- def assign_rollback():
- RollBack(bar=1)
-
- self.assertRaises(TraitError, assign_rollback)
-
-
-class CacheModification(HasTraits):
- foo = Int()
- bar = Int()
-
- def _bar_validate(self, value, trait):
- self.foo = value
- return value
-
- def _foo_validate(self, value, trait):
- self.bar = value
- return value
-
-
-def test_cache_modification():
- CacheModification(foo=1)
- CacheModification(bar=1)
-
-
-class OrderTraits(HasTraits):
- notified = Dict()
-
- a = Unicode()
- b = Unicode()
- c = Unicode()
- d = Unicode()
- e = Unicode()
- f = Unicode()
- g = Unicode()
- h = Unicode()
- i = Unicode()
- j = Unicode()
- k = Unicode()
- l = Unicode()
-
- def _notify(self, name, old, new):
- """check the value of all traits when each trait change is triggered
-
- This verifies that the values are not sensitive
- to dict ordering when loaded from kwargs
- """
- # check the value of the other traits
- # when a given trait change notification fires
- self.notified[name] = {
- c: getattr(self, c) for c in 'abcdefghijkl'
- }
-
- def __init__(self, **kwargs):
- self.on_trait_change(self._notify)
- super(OrderTraits, self).__init__(**kwargs)
-
-def test_notification_order():
- d = {c:c for c in 'abcdefghijkl'}
- obj = OrderTraits()
- assert obj.notified == {}
- obj = OrderTraits(**d)
- notifications = {
- c: d for c in 'abcdefghijkl'
- }
- assert obj.notified == notifications
-
-
-
-###
-# Traits for Forward Declaration Tests
-###
-class ForwardDeclaredInstanceTrait(HasTraits):
-
- value = ForwardDeclaredInstance('ForwardDeclaredBar', allow_none=True)
-
-class ForwardDeclaredTypeTrait(HasTraits):
-
- value = ForwardDeclaredType('ForwardDeclaredBar', allow_none=True)
-
-class ForwardDeclaredInstanceListTrait(HasTraits):
-
- value = List(ForwardDeclaredInstance('ForwardDeclaredBar'))
-
-class ForwardDeclaredTypeListTrait(HasTraits):
-
- value = List(ForwardDeclaredType('ForwardDeclaredBar'))
-###
-# End Traits for Forward Declaration Tests
-###
-
-###
-# Classes for Forward Declaration Tests
-###
-class ForwardDeclaredBar(object):
- pass
-
-class ForwardDeclaredBarSub(ForwardDeclaredBar):
- pass
-###
-# End Classes for Forward Declaration Tests
-###
-
-###
-# Forward Declaration Tests
-###
-class TestForwardDeclaredInstanceTrait(TraitTestBase):
-
- obj = ForwardDeclaredInstanceTrait()
- _default_value = None
- _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
- _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub]
-
-class TestForwardDeclaredTypeTrait(TraitTestBase):
-
- obj = ForwardDeclaredTypeTrait()
- _default_value = None
- _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
- _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
-
-class TestForwardDeclaredInstanceList(TraitTestBase):
-
- obj = ForwardDeclaredInstanceListTrait()
-
- def test_klass(self):
- """Test that the instance klass is properly assigned."""
- self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
-
- _default_value = []
- _good_values = [
- [ForwardDeclaredBar(), ForwardDeclaredBarSub()],
- [],
- ]
- _bad_values = [
- ForwardDeclaredBar(),
- [ForwardDeclaredBar(), 3, None],
- '1',
- # Note that this is the type, not an instance.
- [ForwardDeclaredBar],
- [None],
- None,
- ]
-
-class TestForwardDeclaredTypeList(TraitTestBase):
-
- obj = ForwardDeclaredTypeListTrait()
-
- def test_klass(self):
- """Test that the instance klass is properly assigned."""
- self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
-
- _default_value = []
- _good_values = [
- [ForwardDeclaredBar, ForwardDeclaredBarSub],
- [],
- ]
- _bad_values = [
- ForwardDeclaredBar,
- [ForwardDeclaredBar, 3],
- '1',
- # Note that this is an instance, not the type.
- [ForwardDeclaredBar()],
- [None],
- None,
- ]
-###
-# End Forward Declaration Tests
-###
-
-class TestDynamicTraits(TestCase):
-
- def setUp(self):
- self._notify1 = []
-
- def notify1(self, name, old, new):
- self._notify1.append((name, old, new))
-
- def test_notify_all(self):
-
- class A(HasTraits):
- pass
-
- a = A()
- self.assertTrue(not hasattr(a, 'x'))
- self.assertTrue(not hasattr(a, 'y'))
-
- # Dynamically add trait x.
- a.add_traits(x=Int())
- self.assertTrue(hasattr(a, 'x'))
- self.assertTrue(isinstance(a, (A, )))
-
- # Dynamically add trait y.
- a.add_traits(y=Float())
- self.assertTrue(hasattr(a, 'y'))
- self.assertTrue(isinstance(a, (A, )))
- self.assertEqual(a.__class__.__name__, A.__name__)
-
- # Create a new instance and verify that x and y
- # aren't defined.
- b = A()
- self.assertTrue(not hasattr(b, 'x'))
- self.assertTrue(not hasattr(b, 'y'))
-
- # Verify that notification works like normal.
- a.on_trait_change(self.notify1)
- a.x = 0
- self.assertEqual(len(self._notify1), 0)
- a.y = 0.0
- self.assertEqual(len(self._notify1), 0)
- a.x = 10
- self.assertTrue(('x', 0, 10) in self._notify1)
- a.y = 10.0
- self.assertTrue(('y', 0.0, 10.0) in self._notify1)
- self.assertRaises(TraitError, setattr, a, 'x', 'bad string')
- self.assertRaises(TraitError, setattr, a, 'y', 'bad string')
- self._notify1 = []
- a.on_trait_change(self.notify1, remove=True)
- a.x = 20
- a.y = 20.0
- self.assertEqual(len(self._notify1), 0)
-
-
-def test_enum_no_default():
- class C(HasTraits):
- t = Enum(['a', 'b'])
-
- c = C()
- c.t = 'a'
- assert c.t == 'a'
-
- c = C()
-
- with pytest.raises(TraitError):
- t = c.t
-
- c = C(t='b')
- assert c.t == 'b'
-
-
-def test_default_value_repr():
- class C(HasTraits):
- t = Type('traitlets.HasTraits')
- t2 = Type(HasTraits)
- n = Integer(0)
- lis = List()
- d = Dict()
-
- assert C.t.default_value_repr() == "'traitlets.HasTraits'"
- assert C.t2.default_value_repr() == "'traitlets.traitlets.HasTraits'"
- assert C.n.default_value_repr() == '0'
- assert C.lis.default_value_repr() == '[]'
- assert C.d.default_value_repr() == '{}'
-
-
-class TransitionalClass(HasTraits):
-
- d = Any()
- @default('d')
- def _d_default(self):
- return TransitionalClass
-
- parent_super = False
- calls_super = Integer(0)
-
- @default('calls_super')
- def _calls_super_default(self):
- return -1
-
- @observe('calls_super')
- @observe_compat
- def _calls_super_changed(self, change):
- self.parent_super = change
-
- parent_override = False
- overrides = Integer(0)
-
- @observe('overrides')
- @observe_compat
- def _overrides_changed(self, change):
- self.parent_override = change
-
-
-class SubClass(TransitionalClass):
- def _d_default(self):
- return SubClass
-
- subclass_super = False
- def _calls_super_changed(self, name, old, new):
- self.subclass_super = True
- super(SubClass, self)._calls_super_changed(name, old, new)
-
- subclass_override = False
- def _overrides_changed(self, name, old, new):
- self.subclass_override = True
-
-
-def test_subclass_compat():
- obj = SubClass()
- obj.calls_super = 5
- assert obj.parent_super
- assert obj.subclass_super
- obj.overrides = 5
- assert obj.subclass_override
- assert not obj.parent_override
- assert obj.d is SubClass
-
-
-class DefinesHandler(HasTraits):
- parent_called = False
-
- trait = Integer()
- @observe('trait')
- def handler(self, change):
- self.parent_called = True
-
-
-class OverridesHandler(DefinesHandler):
- child_called = False
-
- @observe('trait')
- def handler(self, change):
- self.child_called = True
-
-
-def test_subclass_override_observer():
- obj = OverridesHandler()
- obj.trait = 5
- assert obj.child_called
- assert not obj.parent_called
-
-
-class DoesntRegisterHandler(DefinesHandler):
- child_called = False
-
- def handler(self, change):
- self.child_called = True
-
-
-def test_subclass_override_not_registered():
- """Subclass that overrides observer and doesn't re-register unregisters both"""
- obj = DoesntRegisterHandler()
- obj.trait = 5
- assert not obj.child_called
- assert not obj.parent_called
-
-
-class AddsHandler(DefinesHandler):
- child_called = False
-
- @observe('trait')
- def child_handler(self, change):
- self.child_called = True
-
-def test_subclass_add_observer():
- obj = AddsHandler()
- obj.trait = 5
- assert obj.child_called
- assert obj.parent_called
-
-
-def test_observe_iterables():
-
- class C(HasTraits):
- i = Integer()
- s = Unicode()
-
- c = C()
- recorded = {}
- def record(change):
- recorded['change'] = change
-
- # observe with names=set
- c.observe(record, names={'i', 's'})
- c.i = 5
- assert recorded['change'].name == 'i'
- assert recorded['change'].new == 5
- c.s = 'hi'
- assert recorded['change'].name == 's'
- assert recorded['change'].new == 'hi'
-
- # observe with names=custom container with iter, contains
- class MyContainer(object):
- def __init__(self, container):
- self.container = container
-
- def __iter__(self):
- return iter(self.container)
-
- def __contains__(self, key):
- return key in self.container
-
- c.observe(record, names=MyContainer({'i', 's'}))
- c.i = 10
- assert recorded['change'].name == 'i'
- assert recorded['change'].new == 10
- c.s = 'ok'
- assert recorded['change'].name == 's'
- assert recorded['change'].new == 'ok'
-
-
-def test_super_args():
- class SuperRecorder(object):
- def __init__(self, *args, **kwargs):
- self.super_args = args
- self.super_kwargs = kwargs
-
- class SuperHasTraits(HasTraits, SuperRecorder):
- i = Integer()
-
- obj = SuperHasTraits('a1', 'a2', b=10, i=5, c='x')
- assert obj.i == 5
- assert not hasattr(obj, 'b')
- assert not hasattr(obj, 'c')
- assert obj.super_args == ('a1' , 'a2')
- assert obj.super_kwargs == {'b': 10 , 'c': 'x'}
-
-def test_super_bad_args():
- class SuperHasTraits(HasTraits):
- a = Integer()
-
- if sys.version_info < (3,):
- # Legacy Python, object.__init__ warns itself, instead of raising
- w = ['object.__init__']
- else:
- w = ["Passing unrecoginized arguments"]
- with expected_warnings(w):
- obj = SuperHasTraits(a=1, b=2)
- assert obj.a == 1
- assert not hasattr(obj, 'b')
+
+from unittest import TestCase
+import pytest
+from pytest import mark
+
+from traitlets import (
+ HasTraits, MetaHasTraits, TraitType, Any, Bool, CBytes, Dict, Enum,
+ Int, CInt, Long, CLong, Integer, Float, CFloat, Complex, Bytes, Unicode,
+ TraitError, Union, All, Undefined, Type, This, Instance, TCPAddress,
+ List, Tuple, ObjectName, DottedObjectName, CRegExp, link, directional_link,
+ ForwardDeclaredType, ForwardDeclaredInstance, validate, observe, default,
+ observe_compat, BaseDescriptor, HasDescriptors,
+)
+
+import six
+
+def change_dict(*ordered_values):
+ change_names = ('name', 'old', 'new', 'owner', 'type')
+ return dict(zip(change_names, ordered_values))
+
+#-----------------------------------------------------------------------------
+# Helper classes for testing
+#-----------------------------------------------------------------------------
+
+
+class HasTraitsStub(HasTraits):
+
+ def notify_change(self, change):
+ self._notify_name = change['name']
+ self._notify_old = change['old']
+ self._notify_new = change['new']
+ self._notify_type = change['type']
+
+
+#-----------------------------------------------------------------------------
+# Test classes
+#-----------------------------------------------------------------------------
+
+
+class TestTraitType(TestCase):
+
+ def test_get_undefined(self):
+ class A(HasTraits):
+ a = TraitType
+ a = A()
+ with self.assertRaises(TraitError):
+ a.a
+
+ def test_set(self):
+ class A(HasTraitsStub):
+ a = TraitType
+
+ a = A()
+ a.a = 10
+ self.assertEqual(a.a, 10)
+ self.assertEqual(a._notify_name, 'a')
+ self.assertEqual(a._notify_old, Undefined)
+ self.assertEqual(a._notify_new, 10)
+
+ def test_validate(self):
+ class MyTT(TraitType):
+ def validate(self, inst, value):
+ return -1
+ class A(HasTraitsStub):
+ tt = MyTT
+
+ a = A()
+ a.tt = 10
+ self.assertEqual(a.tt, -1)
+
+ def test_default_validate(self):
+ class MyIntTT(TraitType):
+ def validate(self, obj, value):
+ if isinstance(value, int):
+ return value
+ self.error(obj, value)
+ class A(HasTraits):
+ tt = MyIntTT(10)
+ a = A()
+ self.assertEqual(a.tt, 10)
+
+ # Defaults are validated when the HasTraits is instantiated
+ class B(HasTraits):
+ tt = MyIntTT('bad default')
+ self.assertRaises(TraitError, B)
+
+ def test_info(self):
+ class A(HasTraits):
+ tt = TraitType
+ a = A()
+ self.assertEqual(A.tt.info(), 'any value')
+
+ def test_error(self):
+ class A(HasTraits):
+ tt = TraitType
+ a = A()
+ self.assertRaises(TraitError, A.tt.error, a, 10)
+
+ def test_deprecated_dynamic_initializer(self):
+ class A(HasTraits):
+ x = Int(10)
+ def _x_default(self):
+ return 11
+ class B(A):
+ x = Int(20)
+ class C(A):
+ def _x_default(self):
+ return 21
+
+ a = A()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+ b = B()
+ self.assertEqual(b.x, 20)
+ self.assertEqual(b._trait_values, {'x': 20})
+ c = C()
+ self.assertEqual(c._trait_values, {})
+ self.assertEqual(c.x, 21)
+ self.assertEqual(c._trait_values, {'x': 21})
+ # Ensure that the base class remains unmolested when the _default
+ # initializer gets overridden in a subclass.
+ a = A()
+ c = C()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+
+ def test_dynamic_initializer(self):
+
+ class A(HasTraits):
+ x = Int(10)
+
+ @default('x')
+ def _default_x(self):
+ return 11
+
+ class B(A):
+ x = Int(20)
+
+ class C(A):
+
+ @default('x')
+ def _default_x(self):
+ return 21
+
+ a = A()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+ b = B()
+ self.assertEqual(b.x, 20)
+ self.assertEqual(b._trait_values, {'x': 20})
+ c = C()
+ self.assertEqual(c._trait_values, {})
+ self.assertEqual(c.x, 21)
+ self.assertEqual(c._trait_values, {'x': 21})
+ # Ensure that the base class remains unmolested when the _default
+ # initializer gets overridden in a subclass.
+ a = A()
+ c = C()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+
+ def test_tag_metadata(self):
+ class MyIntTT(TraitType):
+ metadata = {'a': 1, 'b': 2}
+ a = MyIntTT(10).tag(b=3, c=4)
+ self.assertEqual(a.metadata, {'a': 1, 'b': 3, 'c': 4})
+
+ def test_metadata_localized_instance(self):
+ class MyIntTT(TraitType):
+ metadata = {'a': 1, 'b': 2}
+ a = MyIntTT(10)
+ b = MyIntTT(10)
+ a.metadata['c'] = 3
+ # make sure that changing a's metadata didn't change b's metadata
+ self.assertNotIn('c', b.metadata)
+
+ def test_union_metadata(self):
+ class Foo(HasTraits):
+ bar = (Int().tag(ta=1) | Dict().tag(ta=2, ti='b')).tag(ti='a')
+ foo = Foo()
+ # At this point, no value has been set for bar, so value-specific
+ # is not set.
+ self.assertEqual(foo.trait_metadata('bar', 'ta'), None)
+ self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
+ foo.bar = {}
+ self.assertEqual(foo.trait_metadata('bar', 'ta'), 2)
+ self.assertEqual(foo.trait_metadata('bar', 'ti'), 'b')
+ foo.bar = 1
+ self.assertEqual(foo.trait_metadata('bar', 'ta'), 1)
+ self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
+
+ def test_union_default_value(self):
+ class Foo(HasTraits):
+ bar = Union([Dict(), Int()], default_value=1)
+ foo = Foo()
+ self.assertEqual(foo.bar, 1)
+
+ def test_deprecated_metadata_access(self):
+ class MyIntTT(TraitType):
+ metadata = {'a': 1, 'b': 2}
+ a = MyIntTT(10)
+ with expected_warnings(["use the instance .metadata dictionary directly"]*2):
+ a.set_metadata('key', 'value')
+ v = a.get_metadata('key')
+ self.assertEqual(v, 'value')
+ with expected_warnings(["use the instance .help string directly"]*2):
+ a.set_metadata('help', 'some help')
+ v = a.get_metadata('help')
+ self.assertEqual(v, 'some help')
+
+ def test_trait_types_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = Int
+
+ def test_trait_types_list_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = List(Int)
+
+ def test_trait_types_tuple_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = Tuple(Int)
+
+ def test_trait_types_dict_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = Dict(Int)
+
+class TestHasDescriptorsMeta(TestCase):
+
+ def test_metaclass(self):
+ self.assertEqual(type(HasTraits), MetaHasTraits)
+
+ class A(HasTraits):
+ a = Int()
+
+ a = A()
+ self.assertEqual(type(a.__class__), MetaHasTraits)
+ self.assertEqual(a.a,0)
+ a.a = 10
+ self.assertEqual(a.a,10)
+
+ class B(HasTraits):
+ b = Int()
+
+ b = B()
+ self.assertEqual(b.b,0)
+ b.b = 10
+ self.assertEqual(b.b,10)
+
+ class C(HasTraits):
+ c = Int(30)
+
+ c = C()
+ self.assertEqual(c.c,30)
+ c.c = 10
+ self.assertEqual(c.c,10)
+
+ def test_this_class(self):
+ class A(HasTraits):
+ t = This()
+ tt = This()
+ class B(A):
+ tt = This()
+ ttt = This()
+ self.assertEqual(A.t.this_class, A)
+ self.assertEqual(B.t.this_class, A)
+ self.assertEqual(B.tt.this_class, B)
+ self.assertEqual(B.ttt.this_class, B)
+
+class TestHasDescriptors(TestCase):
+
+ def test_setup_instance(self):
+
+ class FooDescriptor(BaseDescriptor):
+
+ def instance_init(self, inst):
+ foo = inst.foo # instance should have the attr
+
+ class HasFooDescriptors(HasDescriptors):
+
+ fd = FooDescriptor()
+
+ def setup_instance(self, *args, **kwargs):
+ self.foo = kwargs.get('foo', None)
+ super(HasFooDescriptors, self).setup_instance(*args, **kwargs)
+
+ hfd = HasFooDescriptors(foo='bar')
+
+class TestHasTraitsNotify(TestCase):
+
+ def setUp(self):
+ self._notify1 = []
+ self._notify2 = []
+
+ def notify1(self, name, old, new):
+ self._notify1.append((name, old, new))
+
+ def notify2(self, name, old, new):
+ self._notify2.append((name, old, new))
+
+ def test_notify_all(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.on_trait_change(self.notify1)
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ self.assertTrue(('a',0,10) in self._notify1)
+ a.b = 10.0
+ self.assertTrue(('b',0.0,10.0) in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+ self.assertRaises(TraitError,setattr,a,'b','bad string')
+ self._notify1 = []
+ a.on_trait_change(self.notify1,remove=True)
+ a.a = 20
+ a.b = 20.0
+ self.assertEqual(len(self._notify1),0)
+
+ def test_notify_one(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.on_trait_change(self.notify1, 'a')
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ self.assertTrue(('a',0,10) in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+
+ def test_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ self.assertEqual(b.a,0)
+ self.assertEqual(b.b,0.0)
+ b.a = 100
+ b.b = 100.0
+ self.assertEqual(b.a,100)
+ self.assertEqual(b.b,100.0)
+
+ def test_notify_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ b.on_trait_change(self.notify1, 'a')
+ b.on_trait_change(self.notify2, 'b')
+ b.a = 0
+ b.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ self.assertEqual(len(self._notify2),0)
+ b.a = 10
+ b.b = 10.0
+ self.assertTrue(('a',0,10) in self._notify1)
+ self.assertTrue(('b',0.0,10.0) in self._notify2)
+
+ def test_static_notify(self):
+
+ class A(HasTraits):
+ a = Int()
+ _notify1 = []
+ def _a_changed(self, name, old, new):
+ self._notify1.append((name, old, new))
+
+ a = A()
+ a.a = 0
+ # This is broken!!!
+ self.assertEqual(len(a._notify1),0)
+ a.a = 10
+ self.assertTrue(('a',0,10) in a._notify1)
+
+ class B(A):
+ b = Float()
+ _notify2 = []
+ def _b_changed(self, name, old, new):
+ self._notify2.append((name, old, new))
+
+ b = B()
+ b.a = 10
+ b.b = 10.0
+ self.assertTrue(('a',0,10) in b._notify1)
+ self.assertTrue(('b',0.0,10.0) in b._notify2)
+
+ def test_notify_args(self):
+
+ def callback0():
+ self.cb = ()
+ def callback1(name):
+ self.cb = (name,)
+ def callback2(name, new):
+ self.cb = (name, new)
+ def callback3(name, old, new):
+ self.cb = (name, old, new)
+ def callback4(name, old, new, obj):
+ self.cb = (name, old, new, obj)
+
+ class A(HasTraits):
+ a = Int()
+
+ a = A()
+ a.on_trait_change(callback0, 'a')
+ a.a = 10
+ self.assertEqual(self.cb,())
+ a.on_trait_change(callback0, 'a', remove=True)
+
+ a.on_trait_change(callback1, 'a')
+ a.a = 100
+ self.assertEqual(self.cb,('a',))
+ a.on_trait_change(callback1, 'a', remove=True)
+
+ a.on_trait_change(callback2, 'a')
+ a.a = 1000
+ self.assertEqual(self.cb,('a',1000))
+ a.on_trait_change(callback2, 'a', remove=True)
+
+ a.on_trait_change(callback3, 'a')
+ a.a = 10000
+ self.assertEqual(self.cb,('a',1000,10000))
+ a.on_trait_change(callback3, 'a', remove=True)
+
+ a.on_trait_change(callback4, 'a')
+ a.a = 100000
+ self.assertEqual(self.cb,('a',10000,100000,a))
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
+ a.on_trait_change(callback4, 'a', remove=True)
+
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
+
+ def test_notify_only_once(self):
+
+ class A(HasTraits):
+ listen_to = ['a']
+
+ a = Int(0)
+ b = 0
+
+ def __init__(self, **kwargs):
+ super(A, self).__init__(**kwargs)
+ self.on_trait_change(self.listener1, ['a'])
+
+ def listener1(self, name, old, new):
+ self.b += 1
+
+ class B(A):
+
+ c = 0
+ d = 0
+
+ def __init__(self, **kwargs):
+ super(B, self).__init__(**kwargs)
+ self.on_trait_change(self.listener2)
+
+ def listener2(self, name, old, new):
+ self.c += 1
+
+ def _a_changed(self, name, old, new):
+ self.d += 1
+
+ b = B()
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+
+class TestObserveDecorator(TestCase):
+
+ def setUp(self):
+ self._notify1 = []
+ self._notify2 = []
+
+ def notify1(self, change):
+ self._notify1.append(change)
+
+ def notify2(self, change):
+ self._notify2.append(change)
+
+ def test_notify_all(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.observe(self.notify1)
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ change = change_dict('a', 0, 10, a, 'change')
+ self.assertTrue(change in self._notify1)
+ a.b = 10.0
+ change = change_dict('b', 0.0, 10.0, a, 'change')
+ self.assertTrue(change in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+ self.assertRaises(TraitError,setattr,a,'b','bad string')
+ self._notify1 = []
+ a.unobserve(self.notify1)
+ a.a = 20
+ a.b = 20.0
+ self.assertEqual(len(self._notify1),0)
+
+ def test_notify_one(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.observe(self.notify1, 'a')
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ change = change_dict('a', 0, 10, a, 'change')
+ self.assertTrue(change in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+
+ def test_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ self.assertEqual(b.a,0)
+ self.assertEqual(b.b,0.0)
+ b.a = 100
+ b.b = 100.0
+ self.assertEqual(b.a,100)
+ self.assertEqual(b.b,100.0)
+
+ def test_notify_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ b.observe(self.notify1, 'a')
+ b.observe(self.notify2, 'b')
+ b.a = 0
+ b.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ self.assertEqual(len(self._notify2),0)
+ b.a = 10
+ b.b = 10.0
+ change = change_dict('a', 0, 10, b, 'change')
+ self.assertTrue(change in self._notify1)
+ change = change_dict('b', 0.0, 10.0, b, 'change')
+ self.assertTrue(change in self._notify2)
+
+ def test_static_notify(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Int()
+ _notify1 = []
+ _notify_any = []
+
+ @observe('a')
+ def _a_changed(self, change):
+ self._notify1.append(change)
+
+ @observe(All)
+ def _any_changed(self, change):
+ self._notify_any.append(change)
+
+ a = A()
+ a.a = 0
+ self.assertEqual(len(a._notify1),0)
+ a.a = 10
+ change = change_dict('a', 0, 10, a, 'change')
+ self.assertTrue(change in a._notify1)
+ a.b = 1
+ self.assertEqual(len(a._notify_any), 2)
+ change = change_dict('b', 0, 1, a, 'change')
+ self.assertTrue(change in a._notify_any)
+
+ class B(A):
+ b = Float()
+ _notify2 = []
+ @observe('b')
+ def _b_changed(self, change):
+ self._notify2.append(change)
+
+ b = B()
+ b.a = 10
+ b.b = 10.0
+ change = change_dict('a', 0, 10, b, 'change')
+ self.assertTrue(change in b._notify1)
+ change = change_dict('b', 0.0, 10.0, b, 'change')
+ self.assertTrue(change in b._notify2)
+
+ def test_notify_args(self):
+
+ def callback0():
+ self.cb = ()
+ def callback1(change):
+ self.cb = change
+
+ class A(HasTraits):
+ a = Int()
+
+ a = A()
+ a.on_trait_change(callback0, 'a')
+ a.a = 10
+ self.assertEqual(self.cb,())
+ a.unobserve(callback0, 'a')
+
+ a.observe(callback1, 'a')
+ a.a = 100
+ change = change_dict('a', 10, 100, a, 'change')
+ self.assertEqual(self.cb, change)
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
+ a.unobserve(callback1, 'a')
+
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
+
+ def test_notify_only_once(self):
+
+ class A(HasTraits):
+ listen_to = ['a']
+
+ a = Int(0)
+ b = 0
+
+ def __init__(self, **kwargs):
+ super(A, self).__init__(**kwargs)
+ self.observe(self.listener1, ['a'])
+
+ def listener1(self, change):
+ self.b += 1
+
+ class B(A):
+
+ c = 0
+ d = 0
+
+ def __init__(self, **kwargs):
+ super(B, self).__init__(**kwargs)
+ self.observe(self.listener2)
+
+ def listener2(self, change):
+ self.c += 1
+
+ @observe('a')
+ def _a_changed(self, change):
+ self.d += 1
+
+ b = B()
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+
+
+class TestHasTraits(TestCase):
+
+ def test_trait_names(self):
+ class A(HasTraits):
+ i = Int()
+ f = Float()
+ a = A()
+ self.assertEqual(sorted(a.trait_names()),['f','i'])
+ self.assertEqual(sorted(A.class_trait_names()),['f','i'])
+ self.assertTrue(a.has_trait('f'))
+ self.assertFalse(a.has_trait('g'))
+
+ def test_trait_metadata_deprecated(self):
+ with expected_warnings(['metadata should be set using the \.tag\(\) method']):
+ class A(HasTraits):
+ i = Int(config_key='MY_VALUE')
+ a = A()
+ self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
+
+ def test_trait_metadata(self):
+ class A(HasTraits):
+ i = Int().tag(config_key='MY_VALUE')
+ a = A()
+ self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
+
+ def test_trait_metadata_default(self):
+ class A(HasTraits):
+ i = Int()
+ a = A()
+ self.assertEqual(a.trait_metadata('i', 'config_key'), None)
+ self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default')
+
+ def test_traits(self):
+ class A(HasTraits):
+ i = Int()
+ f = Float()
+ a = A()
+ self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
+ self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))
+
+ def test_traits_metadata(self):
+ class A(HasTraits):
+ i = Int().tag(config_key='VALUE1', other_thing='VALUE2')
+ f = Float().tag(config_key='VALUE3', other_thing='VALUE2')
+ j = Int(0)
+ a = A()
+ self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
+ traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
+ self.assertEqual(traits, dict(i=A.i))
+
+ # This passes, but it shouldn't because I am replicating a bug in
+ # traits.
+ traits = a.traits(config_key=lambda v: True)
+ self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
+
+ def test_traits_metadata_deprecated(self):
+ with expected_warnings(['metadata should be set using the \.tag\(\) method']*2):
+ class A(HasTraits):
+ i = Int(config_key='VALUE1', other_thing='VALUE2')
+ f = Float(config_key='VALUE3', other_thing='VALUE2')
+ j = Int(0)
+ a = A()
+ self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
+ traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
+ self.assertEqual(traits, dict(i=A.i))
+
+ # This passes, but it shouldn't because I am replicating a bug in
+ # traits.
+ traits = a.traits(config_key=lambda v: True)
+ self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
+
+
+ def test_init(self):
+ class A(HasTraits):
+ i = Int()
+ x = Float()
+ a = A(i=1, x=10.0)
+ self.assertEqual(a.i, 1)
+ self.assertEqual(a.x, 10.0)
+
+ def test_positional_args(self):
+ class A(HasTraits):
+ i = Int(0)
+ def __init__(self, i):
+ super(A, self).__init__()
+ self.i = i
+
+ a = A(5)
+ self.assertEqual(a.i, 5)
+ # should raise TypeError if no positional arg given
+ self.assertRaises(TypeError, A)
+
+#-----------------------------------------------------------------------------
+# Tests for specific trait types
+#-----------------------------------------------------------------------------
+
+
+class TestType(TestCase):
+
+ def test_default(self):
+
+ class B(object): pass
+ class A(HasTraits):
+ klass = Type(allow_none=True)
+
+ a = A()
+ self.assertEqual(a.klass, object)
+
+ a.klass = B
+ self.assertEqual(a.klass, B)
+ self.assertRaises(TraitError, setattr, a, 'klass', 10)
+
+ def test_default_options(self):
+
+ class B(object): pass
+ class C(B): pass
+ class A(HasTraits):
+ # Different possible combinations of options for default_value
+ # and klass. default_value=None is only valid with allow_none=True.
+ k1 = Type()
+ k2 = Type(None, allow_none=True)
+ k3 = Type(B)
+ k4 = Type(klass=B)
+ k5 = Type(default_value=None, klass=B, allow_none=True)
+ k6 = Type(default_value=C, klass=B)
+
+ self.assertIs(A.k1.default_value, object)
+ self.assertIs(A.k1.klass, object)
+ self.assertIs(A.k2.default_value, None)
+ self.assertIs(A.k2.klass, object)
+ self.assertIs(A.k3.default_value, B)
+ self.assertIs(A.k3.klass, B)
+ self.assertIs(A.k4.default_value, B)
+ self.assertIs(A.k4.klass, B)
+ self.assertIs(A.k5.default_value, None)
+ self.assertIs(A.k5.klass, B)
+ self.assertIs(A.k6.default_value, C)
+ self.assertIs(A.k6.klass, B)
+
+ a = A()
+ self.assertIs(a.k1, object)
+ self.assertIs(a.k2, None)
+ self.assertIs(a.k3, B)
+ self.assertIs(a.k4, B)
+ self.assertIs(a.k5, None)
+ self.assertIs(a.k6, C)
+
+ def test_value(self):
+
+ class B(object): pass
+ class C(object): pass
+ class A(HasTraits):
+ klass = Type(B)
+
+ a = A()
+ self.assertEqual(a.klass, B)
+ self.assertRaises(TraitError, setattr, a, 'klass', C)
+ self.assertRaises(TraitError, setattr, a, 'klass', object)
+ a.klass = B
+
+ def test_allow_none(self):
+
+ class B(object): pass
+ class C(B): pass
+ class A(HasTraits):
+ klass = Type(B)
+
+ a = A()
+ self.assertEqual(a.klass, B)
+ self.assertRaises(TraitError, setattr, a, 'klass', None)
+ a.klass = C
+ self.assertEqual(a.klass, C)
+
+ def test_validate_klass(self):
+
+ class A(HasTraits):
+ klass = Type('no strings allowed')
+
+ self.assertRaises(ImportError, A)
+
+ class A(HasTraits):
+ klass = Type('rub.adub.Duck')
+
+ self.assertRaises(ImportError, A)
+
+ def test_validate_default(self):
+
+ class B(object): pass
+ class A(HasTraits):
+ klass = Type('bad default', B)
+
+ self.assertRaises(ImportError, A)
+
+ class C(HasTraits):
+ klass = Type(None, B)
+
+ self.assertRaises(TraitError, C)
+
+ def test_str_klass(self):
+
+ class A(HasTraits):
+ klass = Type('ipython_genutils.ipstruct.Struct')
+
+ from ipython_genutils.ipstruct import Struct
+ a = A()
+ a.klass = Struct
+ self.assertEqual(a.klass, Struct)
+
+ self.assertRaises(TraitError, setattr, a, 'klass', 10)
+
+ def test_set_str_klass(self):
+
+ class A(HasTraits):
+ klass = Type()
+
+ a = A(klass='ipython_genutils.ipstruct.Struct')
+ from ipython_genutils.ipstruct import Struct
+ self.assertEqual(a.klass, Struct)
+
+class TestInstance(TestCase):
+
+ def test_basic(self):
+ class Foo(object): pass
+ class Bar(Foo): pass
+ class Bah(object): pass
+
+ class A(HasTraits):
+ inst = Instance(Foo, allow_none=True)
+
+ a = A()
+ self.assertTrue(a.inst is None)
+ a.inst = Foo()
+ self.assertTrue(isinstance(a.inst, Foo))
+ a.inst = Bar()
+ self.assertTrue(isinstance(a.inst, Foo))
+ self.assertRaises(TraitError, setattr, a, 'inst', Foo)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bar)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bah())
+
+ def test_default_klass(self):
+ class Foo(object): pass
+ class Bar(Foo): pass
+ class Bah(object): pass
+
+ class FooInstance(Instance):
+ klass = Foo
+
+ class A(HasTraits):
+ inst = FooInstance(allow_none=True)
+
+ a = A()
+ self.assertTrue(a.inst is None)
+ a.inst = Foo()
+ self.assertTrue(isinstance(a.inst, Foo))
+ a.inst = Bar()
+ self.assertTrue(isinstance(a.inst, Foo))
+ self.assertRaises(TraitError, setattr, a, 'inst', Foo)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bar)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bah())
+
+ def test_unique_default_value(self):
+ class Foo(object): pass
+ class A(HasTraits):
+ inst = Instance(Foo,(),{})
+
+ a = A()
+ b = A()
+ self.assertTrue(a.inst is not b.inst)
+
+ def test_args_kw(self):
+ class Foo(object):
+ def __init__(self, c): self.c = c
+ class Bar(object): pass
+ class Bah(object):
+ def __init__(self, c, d):
+ self.c = c; self.d = d
+
+ class A(HasTraits):
+ inst = Instance(Foo, (10,))
+ a = A()
+ self.assertEqual(a.inst.c, 10)
+
+ class B(HasTraits):
+ inst = Instance(Bah, args=(10,), kw=dict(d=20))
+ b = B()
+ self.assertEqual(b.inst.c, 10)
+ self.assertEqual(b.inst.d, 20)
+
+ class C(HasTraits):
+ inst = Instance(Foo, allow_none=True)
+ c = C()
+ self.assertTrue(c.inst is None)
+
+ def test_bad_default(self):
+ class Foo(object): pass
+
+ class A(HasTraits):
+ inst = Instance(Foo)
+
+ a = A()
+ with self.assertRaises(TraitError):
+ a.inst
+
+ def test_instance(self):
+ class Foo(object): pass
+
+ def inner():
+ class A(HasTraits):
+ inst = Instance(Foo())
+
+ self.assertRaises(TraitError, inner)
+
+
+class TestThis(TestCase):
+
+ def test_this_class(self):
+ class Foo(HasTraits):
+ this = This()
+
+ f = Foo()
+ self.assertEqual(f.this, None)
+ g = Foo()
+ f.this = g
+ self.assertEqual(f.this, g)
+ self.assertRaises(TraitError, setattr, f, 'this', 10)
+
+ def test_this_inst(self):
+ class Foo(HasTraits):
+ this = This()
+
+ f = Foo()
+ f.this = Foo()
+ self.assertTrue(isinstance(f.this, Foo))
+
+ def test_subclass(self):
+ class Foo(HasTraits):
+ t = This()
+ class Bar(Foo):
+ pass
+ f = Foo()
+ b = Bar()
+ f.t = b
+ b.t = f
+ self.assertEqual(f.t, b)
+ self.assertEqual(b.t, f)
+
+ def test_subclass_override(self):
+ class Foo(HasTraits):
+ t = This()
+ class Bar(Foo):
+ t = This()
+ f = Foo()
+ b = Bar()
+ f.t = b
+ self.assertEqual(f.t, b)
+ self.assertRaises(TraitError, setattr, b, 't', f)
+
+ def test_this_in_container(self):
+
+ class Tree(HasTraits):
+ value = Unicode()
+ leaves = List(This())
+
+ tree = Tree(
+ value='foo',
+ leaves=[Tree(value='bar'), Tree(value='buzz')]
+ )
+
+ with self.assertRaises(TraitError):
+ tree.leaves = [1, 2]
+
+class TraitTestBase(TestCase):
+ """A best testing class for basic trait types."""
+
+ def assign(self, value):
+ self.obj.value = value
+
+ def coerce(self, value):
+ return value
+
+ def test_good_values(self):
+ if hasattr(self, '_good_values'):
+ for value in self._good_values:
+ self.assign(value)
+ self.assertEqual(self.obj.value, self.coerce(value))
+
+ def test_bad_values(self):
+ if hasattr(self, '_bad_values'):
+ for value in self._bad_values:
+ try:
+ self.assertRaises(TraitError, self.assign, value)
+ except AssertionError:
+ assert False, value
+
+ def test_default_value(self):
+ if hasattr(self, '_default_value'):
+ self.assertEqual(self._default_value, self.obj.value)
+
+ def test_allow_none(self):
+ if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and
+ None in self._bad_values):
+ trait=self.obj.traits()['value']
+ try:
+ trait.allow_none = True
+ self._bad_values.remove(None)
+ #skip coerce. Allow None casts None to None.
+ self.assign(None)
+ self.assertEqual(self.obj.value,None)
+ self.test_good_values()
+ self.test_bad_values()
+ finally:
+ #tear down
+ trait.allow_none = False
+ self._bad_values.append(None)
+
+ def tearDown(self):
+ # restore default value after tests, if set
+ if hasattr(self, '_default_value'):
+ self.obj.value = self._default_value
+
+
+class AnyTrait(HasTraits):
+
+ value = Any()
+
+class AnyTraitTest(TraitTestBase):
+
+ obj = AnyTrait()
+
+ _default_value = None
+ _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
+ _bad_values = []
+
+class UnionTrait(HasTraits):
+
+ value = Union([Type(), Bool()])
+
+class UnionTraitTest(TraitTestBase):
+
+ obj = UnionTrait(value='ipython_genutils.ipstruct.Struct')
+ _good_values = [int, float, True]
+ _bad_values = [[], (0,), 1j]
+
+class OrTrait(HasTraits):
+
+ value = Bool() | Unicode()
+
+class OrTraitTest(TraitTestBase):
+
+ obj = OrTrait()
+ _good_values = [True, False, 'ten']
+ _bad_values = [[], (0,), 1j]
+
+class IntTrait(HasTraits):
+
+ value = Int(99, min=-100)
+
+class TestInt(TraitTestBase):
+
+ obj = IntTrait()
+ _default_value = 99
+ _good_values = [10, -10]
+ _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None, 1j,
+ 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
+ u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', -200]
+ if not six.PY3:
+ _bad_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
+
+
+class CIntTrait(HasTraits):
+ value = CInt('5')
+
+class TestCInt(TraitTestBase):
+ obj = CIntTrait()
+
+ _default_value = 5
+ _good_values = ['10', '-10', u'10', u'-10', 10, 10.0, -10.0, 10.1]
+ _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
+ None, 1j, '10.1', u'10.1']
+
+ def coerce(self, n):
+ return int(n)
+
+
+class MinBoundCIntTrait(HasTraits):
+ value = CInt('5', min=3)
+
+class TestMinBoundCInt(TestCInt):
+ obj = MinBoundCIntTrait()
+
+ _default_value = 5
+ _good_values = [3, 3.0, '3']
+ _bad_values = [2.6, 2, -3, -3.0]
+
+
+class LongTrait(HasTraits):
+
+ value = Long(99 if six.PY3 else long(99))
+
+class TestLong(TraitTestBase):
+
+ obj = LongTrait()
+
+ _default_value = 99 if six.PY3 else long(99)
+ _good_values = [10, -10]
+ _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
+ None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
+ '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
+ u'-10.1']
+ if not six.PY3:
+ # maxint undefined on py3, because int == long
+ _good_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
+ _bad_values.extend([[long(10)], (long(10),)])
+
+ @mark.skipif(six.PY3, reason="not relevant on py3")
+ def test_cast_small(self):
+ """Long casts ints to long"""
+ self.obj.value = 10
+ self.assertEqual(type(self.obj.value), long)
+
+
+class MinBoundLongTrait(HasTraits):
+ value = Long(99 if six.PY3 else long(99), min=5)
+
+class TestMinBoundLong(TraitTestBase):
+ obj = MinBoundLongTrait()
+
+ _default_value = 99 if six.PY3 else long(99)
+ _good_values = [5, 10]
+ _bad_values = [4, -10]
+
+
+class MaxBoundLongTrait(HasTraits):
+ value = Long(5 if six.PY3 else long(5), max=10)
+
+class TestMaxBoundLong(TraitTestBase):
+ obj = MaxBoundLongTrait()
+
+ _default_value = 5 if six.PY3 else long(5)
+ _good_values = [10, -2]
+ _bad_values = [11, 20]
+
+
+class CLongTrait(HasTraits):
+ value = CLong('5')
+
+class TestCLong(TraitTestBase):
+ obj = CLongTrait()
+
+ _default_value = 5 if six.PY3 else long(5)
+ _good_values = ['10', '-10', u'10', u'-10', 10, 10.0, -10.0, 10.1]
+ _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
+ None, 1j, '10.1', u'10.1']
+
+ def coerce(self, n):
+ return int(n) if six.PY3 else long(n)
+
+
+class MaxBoundCLongTrait(HasTraits):
+ value = CLong('5', max=10)
+
+class TestMaxBoundCLong(TestCLong):
+ obj = MaxBoundCLongTrait()
+
+ _default_value = 5 if six.PY3 else long(5)
+ _good_values = [10, '10', 10.3]
+ _bad_values = [11.0, '11']
+
+
+class IntegerTrait(HasTraits):
+ value = Integer(1)
+
+class TestInteger(TestLong):
+ obj = IntegerTrait()
+ _default_value = 1
+
+ def coerce(self, n):
+ return int(n)
+
+ @mark.skipif(six.PY3, reason="not relevant on py3")
+ def test_cast_small(self):
+ """Integer casts small longs to int"""
+
+ self.obj.value = long(100)
+ self.assertEqual(type(self.obj.value), int)
+
+
+class MinBoundIntegerTrait(HasTraits):
+ value = Integer(5, min=3)
+
+class TestMinBoundInteger(TraitTestBase):
+ obj = MinBoundIntegerTrait()
+
+ _default_value = 5
+ _good_values = 3, 20
+ _bad_values = [2, -10]
+
+
+class MaxBoundIntegerTrait(HasTraits):
+ value = Integer(1, max=3)
+
+class TestMaxBoundInteger(TraitTestBase):
+ obj = MaxBoundIntegerTrait()
+
+ _default_value = 1
+ _good_values = 3, -2
+ _bad_values = [4, 10]
+
+
+class FloatTrait(HasTraits):
+
+ value = Float(99.0, max=200.0)
+
+class TestFloat(TraitTestBase):
+
+ obj = FloatTrait()
+
+ _default_value = 99.0
+ _good_values = [10, -10, 10.1, -10.1]
+ _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None,
+ 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
+ u'-10', u'10L', u'-10L', u'10.1', u'-10.1', 201.0]
+ if not six.PY3:
+ _bad_values.extend([long(10), long(-10)])
+
+
+class CFloatTrait(HasTraits):
+
+ value = CFloat('99.0', max=200.0)
+
+class TestCFloat(TraitTestBase):
+
+ obj = CFloatTrait()
+
+ _default_value = 99.0
+ _good_values = [10, 10.0, 10.5, '10.0', '10', '-10', '10.0', u'10']
+ _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None, 1j,
+ 200.1, '200.1']
+
+ def coerce(self, v):
+ return float(v)
+
+
+class ComplexTrait(HasTraits):
+
+ value = Complex(99.0-99.0j)
+
+class TestComplex(TraitTestBase):
+
+ obj = ComplexTrait()
+
+ _default_value = 99.0-99.0j
+ _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
+ 10.1j, 10.1+10.1j, 10.1-10.1j]
+ _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
+ if not six.PY3:
+ _bad_values.extend([long(10), long(-10)])
+
+
+class BytesTrait(HasTraits):
+
+ value = Bytes(b'string')
+
+class TestBytes(TraitTestBase):
+
+ obj = BytesTrait()
+
+ _default_value = b'string'
+ _good_values = [b'10', b'-10', b'10L',
+ b'-10L', b'10.1', b'-10.1', b'string']
+ _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
+ ['ten'],{'ten': 10},(10,), None, u'string']
+ if not six.PY3:
+ _bad_values.extend([long(10), long(-10)])
+
+
+class UnicodeTrait(HasTraits):
+
+ value = Unicode(u'unicode')
+
+class TestUnicode(TraitTestBase):
+
+ obj = UnicodeTrait()
+
+ _default_value = u'unicode'
+ _good_values = ['10', '-10', '10L', '-10L', '10.1',
+ '-10.1', '', u'', 'string', u'string', u"€"]
+ _bad_values = [10, -10, 10.1, -10.1, 1j,
+ [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
+ if not six.PY3:
+ _bad_values.extend([long(10), long(-10)])
+
+
+class ObjectNameTrait(HasTraits):
+ value = ObjectName("abc")
+
+class TestObjectName(TraitTestBase):
+ obj = ObjectNameTrait()
+
+ _default_value = "abc"
+ _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
+ _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
+ None, object(), object]
+ if sys.version_info[0] < 3:
+ _bad_values.append(u"þ")
+ else:
+ _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131).
+
+
+class DottedObjectNameTrait(HasTraits):
+ value = DottedObjectName("a.b")
+
+class TestDottedObjectName(TraitTestBase):
+ obj = DottedObjectNameTrait()
+
+ _default_value = "a.b"
+ _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
+ _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]
+ if sys.version_info[0] < 3:
+ _bad_values.append(u"t.þ")
+ else:
+ _good_values.append(u"t.þ")
+
+
+class TCPAddressTrait(HasTraits):
+ value = TCPAddress()
+
+class TestTCPAddress(TraitTestBase):
+
+ obj = TCPAddressTrait()
+
+ _default_value = ('127.0.0.1',0)
+ _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
+ _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]
+
+class ListTrait(HasTraits):
+
+ value = List(Int())
+
+class TestList(TraitTestBase):
+
+ obj = ListTrait()
+
+ _default_value = []
+ _good_values = [[], [1], list(range(10)), (1,2)]
+ _bad_values = [10, [1,'a'], 'a']
+
+ def coerce(self, value):
+ if value is not None:
+ value = list(value)
+ return value
+
+class Foo(object):
+ pass
+
+class NoneInstanceListTrait(HasTraits):
+
+ value = List(Instance(Foo))
+
+class TestNoneInstanceList(TraitTestBase):
+
+ obj = NoneInstanceListTrait()
+
+ _default_value = []
+ _good_values = [[Foo(), Foo()], []]
+ _bad_values = [[None], [Foo(), None]]
+
+
+class InstanceListTrait(HasTraits):
+
+ value = List(Instance(__name__+'.Foo'))
+
+class TestInstanceList(TraitTestBase):
+
+ obj = InstanceListTrait()
+
+ def test_klass(self):
+ """Test that the instance klass is properly assigned."""
+ self.assertIs(self.obj.traits()['value']._trait.klass, Foo)
+
+ _default_value = []
+ _good_values = [[Foo(), Foo()], []]
+ _bad_values = [['1', 2,], '1', [Foo], None]
+
+class UnionListTrait(HasTraits):
+
+ value = List(Int() | Bool())
+
+class TestUnionListTrait(HasTraits):
+
+ obj = UnionListTrait()
+
+ _default_value = []
+ _good_values = [[True, 1], [False, True]]
+ _bad_values = [[1, 'True'], False]
+
+
+class LenListTrait(HasTraits):
+
+ value = List(Int(), [0], minlen=1, maxlen=2)
+
+class TestLenList(TraitTestBase):
+
+ obj = LenListTrait()
+
+ _default_value = [0]
+ _good_values = [[1], [1,2], (1,2)]
+ _bad_values = [10, [1,'a'], 'a', [], list(range(3))]
+
+ def coerce(self, value):
+ if value is not None:
+ value = list(value)
+ return value
+
+class TupleTrait(HasTraits):
+
+ value = Tuple(Int(allow_none=True), default_value=(1,))
+
+class TestTupleTrait(TraitTestBase):
+
+ obj = TupleTrait()
+
+ _default_value = (1,)
+ _good_values = [(1,), (0,), [1]]
+ _bad_values = [10, (1, 2), ('a'), (), None]
+
+ def coerce(self, value):
+ if value is not None:
+ value = tuple(value)
+ return value
+
+ def test_invalid_args(self):
+ self.assertRaises(TypeError, Tuple, 5)
+ self.assertRaises(TypeError, Tuple, default_value='hello')
+ t = Tuple(Int(), CBytes(), default_value=(1,5))
+
+class LooseTupleTrait(HasTraits):
+
+ value = Tuple((1,2,3))
+
+class TestLooseTupleTrait(TraitTestBase):
+
+ obj = LooseTupleTrait()
+
+ _default_value = (1,2,3)
+ _good_values = [(1,), [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
+ _bad_values = [10, 'hello', {}, None]
+
+ def coerce(self, value):
+ if value is not None:
+ value = tuple(value)
+ return value
+
+ def test_invalid_args(self):
+ self.assertRaises(TypeError, Tuple, 5)
+ self.assertRaises(TypeError, Tuple, default_value='hello')
+ t = Tuple(Int(), CBytes(), default_value=(1,5))
+
+
+class MultiTupleTrait(HasTraits):
+
+ value = Tuple(Int(), Bytes(), default_value=[99,b'bottles'])
+
+class TestMultiTuple(TraitTestBase):
+
+ obj = MultiTupleTrait()
+
+ _default_value = (99,b'bottles')
+ _good_values = [(1,b'a'), (2,b'b')]
+ _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
+
+class CRegExpTrait(HasTraits):
+
+ value = CRegExp(r'')
+
+class TestCRegExp(TraitTestBase):
+
+ def coerce(self, value):
+ return re.compile(value)
+
+ obj = CRegExpTrait()
+
+ _default_value = re.compile(r'')
+ _good_values = [r'\d+', re.compile(r'\d+')]
+ _bad_values = ['(', None, ()]
+
+class DictTrait(HasTraits):
+ value = Dict()
+
+def test_dict_assignment():
+ d = dict()
+ c = DictTrait()
+ c.value = d
+ d['a'] = 5
+ assert d == c.value
+ assert c.value is d
+
+
+class UniformlyValidatedDictTrait(HasTraits):
+
+ value = Dict(trait=Unicode(),
+ default_value={'foo': '1'})
+
+
+class TestInstanceUniformlyValidatedDict(TraitTestBase):
+
+ obj = UniformlyValidatedDictTrait()
+
+ _default_value = {'foo': '1'}
+ _good_values = [{'foo': '0', 'bar': '1'}]
+ _bad_values = [{'foo': 0, 'bar': '1'}]
+
+
+class KeyValidatedDictTrait(HasTraits):
+
+ value = Dict(traits={'foo': Int()},
+ default_value={'foo': 1})
+
+
+class TestInstanceKeyValidatedDict(TraitTestBase):
+
+ obj = KeyValidatedDictTrait()
+
+ _default_value = {'foo': 1}
+ _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 0, 'bar': 1}]
+ _bad_values = [{'foo': '0', 'bar': '1'}]
+
+
+class FullyValidatedDictTrait(HasTraits):
+
+ value = Dict(trait=Unicode(),
+ traits={'foo': Int()},
+ default_value={'foo': 1})
+
+
+class TestInstanceFullyValidatedDict(TraitTestBase):
+
+ obj = FullyValidatedDictTrait()
+
+ _default_value = {'foo': 1}
+ _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 1, 'bar': '2'}]
+ _bad_values = [{'foo': 0, 'bar': 1}, {'foo': '0', 'bar': '1'}]
+
+
+def test_dict_default_value():
+ """Check that the `{}` default value of the Dict traitlet constructor is
+ actually copied."""
+
+ class Foo(HasTraits):
+ d1 = Dict()
+ d2 = Dict()
+
+ foo = Foo()
+ assert foo.d1 == {}
+ assert foo.d2 == {}
+ assert foo.d1 is not foo.d2
+
+
+class TestValidationHook(TestCase):
+
+ def test_parity_trait(self):
+ """Verify that the early validation hook is effective"""
+
+ class Parity(HasTraits):
+
+ value = Int(0)
+ parity = Enum(['odd', 'even'], default_value='even')
+
+ @validate('value')
+ def _value_validate(self, proposal):
+ value = proposal['value']
+ if self.parity == 'even' and value % 2:
+ raise TraitError('Expected an even number')
+ if self.parity == 'odd' and (value % 2 == 0):
+ raise TraitError('Expected an odd number')
+ return value
+
+ u = Parity()
+ u.parity = 'odd'
+ u.value = 1 # OK
+ with self.assertRaises(TraitError):
+ u.value = 2 # Trait Error
+
+ u.parity = 'even'
+ u.value = 2 # OK
+
+ def test_multiple_validate(self):
+ """Verify that we can register the same validator to multiple names"""
+
+ class OddEven(HasTraits):
+
+ odd = Int(1)
+ even = Int(0)
+
+ @validate('odd', 'even')
+ def check_valid(self, proposal):
+ if proposal['trait'].name == 'odd' and not proposal['value'] % 2:
+ raise TraitError('odd should be odd')
+ if proposal['trait'].name == 'even' and proposal['value'] % 2:
+ raise TraitError('even should be even')
+
+ u = OddEven()
+ u.odd = 3 # OK
+ with self.assertRaises(TraitError):
+ u.odd = 2 # Trait Error
+
+ u.even = 2 # OK
+ with self.assertRaises(TraitError):
+ u.even = 3 # Trait Error
+
+
+
+class TestLink(TestCase):
+
+ def test_connect_same(self):
+ """Verify two traitlets of the same type can be linked together using link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Conenct the two classes.
+ c = link((a, 'value'), (b, 'value'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.value)
+
+ # Change one of the values to make sure they stay in sync.
+ a.value = 5
+ self.assertEqual(a.value, b.value)
+ b.value = 6
+ self.assertEqual(a.value, b.value)
+
+ def test_link_different(self):
+ """Verify two traitlets of different types can be linked together using link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ class B(HasTraits):
+ count = Int()
+ a = A(value=9)
+ b = B(count=8)
+
+ # Conenct the two classes.
+ c = link((a, 'value'), (b, 'count'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.count)
+
+ # Change one of the values to make sure they stay in sync.
+ a.value = 5
+ self.assertEqual(a.value, b.count)
+ b.count = 4
+ self.assertEqual(a.value, b.count)
+
+ def test_unlink(self):
+ """Verify two linked traitlets can be unlinked."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Connect the two classes.
+ c = link((a, 'value'), (b, 'value'))
+ a.value = 4
+ c.unlink()
+
+ # Change one of the values to make sure they don't stay in sync.
+ a.value = 5
+ self.assertNotEqual(a.value, b.value)
+
+ def test_callbacks(self):
+ """Verify two linked traitlets have their callbacks called once."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ class B(HasTraits):
+ count = Int()
+ a = A(value=9)
+ b = B(count=8)
+
+ # Register callbacks that count.
+ callback_count = []
+ def a_callback(name, old, new):
+ callback_count.append('a')
+ a.on_trait_change(a_callback, 'value')
+ def b_callback(name, old, new):
+ callback_count.append('b')
+ b.on_trait_change(b_callback, 'count')
+
+ # Connect the two classes.
+ c = link((a, 'value'), (b, 'count'))
+
+ # Make sure b's count was set to a's value once.
+ self.assertEqual(''.join(callback_count), 'b')
+ del callback_count[:]
+
+ # Make sure a's value was set to b's count once.
+ b.count = 5
+ self.assertEqual(''.join(callback_count), 'ba')
+ del callback_count[:]
+
+ # Make sure b's count was set to a's value once.
+ a.value = 4
+ self.assertEqual(''.join(callback_count), 'ab')
+ del callback_count[:]
+
+class TestDirectionalLink(TestCase):
+ def test_connect_same(self):
+ """Verify two traitlets of the same type can be linked together using directional_link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Conenct the two classes.
+ c = directional_link((a, 'value'), (b, 'value'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.value)
+
+ # Change one the value of the source and check that it synchronizes the target.
+ a.value = 5
+ self.assertEqual(b.value, 5)
+ # Change one the value of the target and check that it has no impact on the source
+ b.value = 6
+ self.assertEqual(a.value, 5)
+
+ def test_tranform(self):
+ """Test transform link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Conenct the two classes.
+ c = directional_link((a, 'value'), (b, 'value'), lambda x: 2 * x)
+
+ # Make sure the values are correct at the point of linking.
+ self.assertEqual(b.value, 2 * a.value)
+
+ # Change one the value of the source and check that it modifies the target.
+ a.value = 5
+ self.assertEqual(b.value, 10)
+ # Change one the value of the target and check that it has no impact on the source
+ b.value = 6
+ self.assertEqual(a.value, 5)
+
+ def test_link_different(self):
+ """Verify two traitlets of different types can be linked together using link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ class B(HasTraits):
+ count = Int()
+ a = A(value=9)
+ b = B(count=8)
+
+ # Conenct the two classes.
+ c = directional_link((a, 'value'), (b, 'count'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.count)
+
+ # Change one the value of the source and check that it synchronizes the target.
+ a.value = 5
+ self.assertEqual(b.count, 5)
+ # Change one the value of the target and check that it has no impact on the source
+ b.value = 6
+ self.assertEqual(a.value, 5)
+
+ def test_unlink(self):
+ """Verify two linked traitlets can be unlinked."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Connect the two classes.
+ c = directional_link((a, 'value'), (b, 'value'))
+ a.value = 4
+ c.unlink()
+
+ # Change one of the values to make sure they don't stay in sync.
+ a.value = 5
+ self.assertNotEqual(a.value, b.value)
+
+class Pickleable(HasTraits):
+
+ i = Int()
+ @observe('i')
+ def _i_changed(self, change): pass
+ @validate('i')
+ def _i_validate(self, commit):
+ return commit['value']
+
+ j = Int()
+
+ def __init__(self):
+ with self.hold_trait_notifications():
+ self.i = 1
+ self.on_trait_change(self._i_changed, 'i')
+
+def test_pickle_hastraits():
+ c = Pickleable()
+ for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+ p = pickle.dumps(c, protocol)
+ c2 = pickle.loads(p)
+ assert c2.i == c.i
+ assert c2.j == c.j
+
+ c.i = 5
+ for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+ p = pickle.dumps(c, protocol)
+ c2 = pickle.loads(p)
+ assert c2.i == c.i
+ assert c2.j == c.j
+
+
+def test_hold_trait_notifications():
+ changes = []
+
+ class Test(HasTraits):
+ a = Integer(0)
+ b = Integer(0)
+
+ def _a_changed(self, name, old, new):
+ changes.append((old, new))
+
+ def _b_validate(self, value, trait):
+ if value != 0:
+ raise TraitError('Only 0 is a valid value')
+ return value
+
+ # Test context manager and nesting
+ t = Test()
+ with t.hold_trait_notifications():
+ with t.hold_trait_notifications():
+ t.a = 1
+ assert t.a == 1
+ assert changes == []
+ t.a = 2
+ assert t.a == 2
+ with t.hold_trait_notifications():
+ t.a = 3
+ assert t.a == 3
+ assert changes == []
+ t.a = 4
+ assert t.a == 4
+ assert changes == []
+ t.a = 4
+ assert t.a == 4
+ assert changes == []
+
+ assert changes == [(0, 4)]
+ # Test roll-back
+ try:
+ with t.hold_trait_notifications():
+ t.b = 1 # raises a Trait error
+ except:
+ pass
+ assert t.b == 0
+
+
+class RollBack(HasTraits):
+ bar = Int()
+ def _bar_validate(self, value, trait):
+ if value:
+ raise TraitError('foobar')
+ return value
+
+
+class TestRollback(TestCase):
+
+ def test_roll_back(self):
+
+ def assign_rollback():
+ RollBack(bar=1)
+
+ self.assertRaises(TraitError, assign_rollback)
+
+
+class CacheModification(HasTraits):
+ foo = Int()
+ bar = Int()
+
+ def _bar_validate(self, value, trait):
+ self.foo = value
+ return value
+
+ def _foo_validate(self, value, trait):
+ self.bar = value
+ return value
+
+
+def test_cache_modification():
+ CacheModification(foo=1)
+ CacheModification(bar=1)
+
+
+class OrderTraits(HasTraits):
+ notified = Dict()
+
+ a = Unicode()
+ b = Unicode()
+ c = Unicode()
+ d = Unicode()
+ e = Unicode()
+ f = Unicode()
+ g = Unicode()
+ h = Unicode()
+ i = Unicode()
+ j = Unicode()
+ k = Unicode()
+ l = Unicode()
+
+ def _notify(self, name, old, new):
+ """check the value of all traits when each trait change is triggered
+
+ This verifies that the values are not sensitive
+ to dict ordering when loaded from kwargs
+ """
+ # check the value of the other traits
+ # when a given trait change notification fires
+ self.notified[name] = {
+ c: getattr(self, c) for c in 'abcdefghijkl'
+ }
+
+ def __init__(self, **kwargs):
+ self.on_trait_change(self._notify)
+ super(OrderTraits, self).__init__(**kwargs)
+
+def test_notification_order():
+ d = {c:c for c in 'abcdefghijkl'}
+ obj = OrderTraits()
+ assert obj.notified == {}
+ obj = OrderTraits(**d)
+ notifications = {
+ c: d for c in 'abcdefghijkl'
+ }
+ assert obj.notified == notifications
+
+
+
+###
+# Traits for Forward Declaration Tests
+###
+class ForwardDeclaredInstanceTrait(HasTraits):
+
+ value = ForwardDeclaredInstance('ForwardDeclaredBar', allow_none=True)
+
+class ForwardDeclaredTypeTrait(HasTraits):
+
+ value = ForwardDeclaredType('ForwardDeclaredBar', allow_none=True)
+
+class ForwardDeclaredInstanceListTrait(HasTraits):
+
+ value = List(ForwardDeclaredInstance('ForwardDeclaredBar'))
+
+class ForwardDeclaredTypeListTrait(HasTraits):
+
+ value = List(ForwardDeclaredType('ForwardDeclaredBar'))
+###
+# End Traits for Forward Declaration Tests
+###
+
+###
+# Classes for Forward Declaration Tests
+###
+class ForwardDeclaredBar(object):
+ pass
+
+class ForwardDeclaredBarSub(ForwardDeclaredBar):
+ pass
+###
+# End Classes for Forward Declaration Tests
+###
+
+###
+# Forward Declaration Tests
+###
+class TestForwardDeclaredInstanceTrait(TraitTestBase):
+
+ obj = ForwardDeclaredInstanceTrait()
+ _default_value = None
+ _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
+ _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub]
+
+class TestForwardDeclaredTypeTrait(TraitTestBase):
+
+ obj = ForwardDeclaredTypeTrait()
+ _default_value = None
+ _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
+ _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
+
+class TestForwardDeclaredInstanceList(TraitTestBase):
+
+ obj = ForwardDeclaredInstanceListTrait()
+
+ def test_klass(self):
+ """Test that the instance klass is properly assigned."""
+ self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
+
+ _default_value = []
+ _good_values = [
+ [ForwardDeclaredBar(), ForwardDeclaredBarSub()],
+ [],
+ ]
+ _bad_values = [
+ ForwardDeclaredBar(),
+ [ForwardDeclaredBar(), 3, None],
+ '1',
+ # Note that this is the type, not an instance.
+ [ForwardDeclaredBar],
+ [None],
+ None,
+ ]
+
+class TestForwardDeclaredTypeList(TraitTestBase):
+
+ obj = ForwardDeclaredTypeListTrait()
+
+ def test_klass(self):
+ """Test that the instance klass is properly assigned."""
+ self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
+
+ _default_value = []
+ _good_values = [
+ [ForwardDeclaredBar, ForwardDeclaredBarSub],
+ [],
+ ]
+ _bad_values = [
+ ForwardDeclaredBar,
+ [ForwardDeclaredBar, 3],
+ '1',
+ # Note that this is an instance, not the type.
+ [ForwardDeclaredBar()],
+ [None],
+ None,
+ ]
+###
+# End Forward Declaration Tests
+###
+
+class TestDynamicTraits(TestCase):
+
+ def setUp(self):
+ self._notify1 = []
+
+ def notify1(self, name, old, new):
+ self._notify1.append((name, old, new))
+
+ def test_notify_all(self):
+
+ class A(HasTraits):
+ pass
+
+ a = A()
+ self.assertTrue(not hasattr(a, 'x'))
+ self.assertTrue(not hasattr(a, 'y'))
+
+ # Dynamically add trait x.
+ a.add_traits(x=Int())
+ self.assertTrue(hasattr(a, 'x'))
+ self.assertTrue(isinstance(a, (A, )))
+
+ # Dynamically add trait y.
+ a.add_traits(y=Float())
+ self.assertTrue(hasattr(a, 'y'))
+ self.assertTrue(isinstance(a, (A, )))
+ self.assertEqual(a.__class__.__name__, A.__name__)
+
+ # Create a new instance and verify that x and y
+ # aren't defined.
+ b = A()
+ self.assertTrue(not hasattr(b, 'x'))
+ self.assertTrue(not hasattr(b, 'y'))
+
+ # Verify that notification works like normal.
+ a.on_trait_change(self.notify1)
+ a.x = 0
+ self.assertEqual(len(self._notify1), 0)
+ a.y = 0.0
+ self.assertEqual(len(self._notify1), 0)
+ a.x = 10
+ self.assertTrue(('x', 0, 10) in self._notify1)
+ a.y = 10.0
+ self.assertTrue(('y', 0.0, 10.0) in self._notify1)
+ self.assertRaises(TraitError, setattr, a, 'x', 'bad string')
+ self.assertRaises(TraitError, setattr, a, 'y', 'bad string')
+ self._notify1 = []
+ a.on_trait_change(self.notify1, remove=True)
+ a.x = 20
+ a.y = 20.0
+ self.assertEqual(len(self._notify1), 0)
+
+
+def test_enum_no_default():
+ class C(HasTraits):
+ t = Enum(['a', 'b'])
+
+ c = C()
+ c.t = 'a'
+ assert c.t == 'a'
+
+ c = C()
+
+ with pytest.raises(TraitError):
+ t = c.t
+
+ c = C(t='b')
+ assert c.t == 'b'
+
+
+def test_default_value_repr():
+ class C(HasTraits):
+ t = Type('traitlets.HasTraits')
+ t2 = Type(HasTraits)
+ n = Integer(0)
+ lis = List()
+ d = Dict()
+
+ assert C.t.default_value_repr() == "'traitlets.HasTraits'"
+ assert C.t2.default_value_repr() == "'traitlets.traitlets.HasTraits'"
+ assert C.n.default_value_repr() == '0'
+ assert C.lis.default_value_repr() == '[]'
+ assert C.d.default_value_repr() == '{}'
+
+
+class TransitionalClass(HasTraits):
+
+ d = Any()
+ @default('d')
+ def _d_default(self):
+ return TransitionalClass
+
+ parent_super = False
+ calls_super = Integer(0)
+
+ @default('calls_super')
+ def _calls_super_default(self):
+ return -1
+
+ @observe('calls_super')
+ @observe_compat
+ def _calls_super_changed(self, change):
+ self.parent_super = change
+
+ parent_override = False
+ overrides = Integer(0)
+
+ @observe('overrides')
+ @observe_compat
+ def _overrides_changed(self, change):
+ self.parent_override = change
+
+
+class SubClass(TransitionalClass):
+ def _d_default(self):
+ return SubClass
+
+ subclass_super = False
+ def _calls_super_changed(self, name, old, new):
+ self.subclass_super = True
+ super(SubClass, self)._calls_super_changed(name, old, new)
+
+ subclass_override = False
+ def _overrides_changed(self, name, old, new):
+ self.subclass_override = True
+
+
+def test_subclass_compat():
+ obj = SubClass()
+ obj.calls_super = 5
+ assert obj.parent_super
+ assert obj.subclass_super
+ obj.overrides = 5
+ assert obj.subclass_override
+ assert not obj.parent_override
+ assert obj.d is SubClass
+
+
+class DefinesHandler(HasTraits):
+ parent_called = False
+
+ trait = Integer()
+ @observe('trait')
+ def handler(self, change):
+ self.parent_called = True
+
+
+class OverridesHandler(DefinesHandler):
+ child_called = False
+
+ @observe('trait')
+ def handler(self, change):
+ self.child_called = True
+
+
+def test_subclass_override_observer():
+ obj = OverridesHandler()
+ obj.trait = 5
+ assert obj.child_called
+ assert not obj.parent_called
+
+
+class DoesntRegisterHandler(DefinesHandler):
+ child_called = False
+
+ def handler(self, change):
+ self.child_called = True
+
+
+def test_subclass_override_not_registered():
+ """Subclass that overrides observer and doesn't re-register unregisters both"""
+ obj = DoesntRegisterHandler()
+ obj.trait = 5
+ assert not obj.child_called
+ assert not obj.parent_called
+
+
+class AddsHandler(DefinesHandler):
+ child_called = False
+
+ @observe('trait')
+ def child_handler(self, change):
+ self.child_called = True
+
+def test_subclass_add_observer():
+ obj = AddsHandler()
+ obj.trait = 5
+ assert obj.child_called
+ assert obj.parent_called
+
+
+def test_observe_iterables():
+
+ class C(HasTraits):
+ i = Integer()
+ s = Unicode()
+
+ c = C()
+ recorded = {}
+ def record(change):
+ recorded['change'] = change
+
+ # observe with names=set
+ c.observe(record, names={'i', 's'})
+ c.i = 5
+ assert recorded['change'].name == 'i'
+ assert recorded['change'].new == 5
+ c.s = 'hi'
+ assert recorded['change'].name == 's'
+ assert recorded['change'].new == 'hi'
+
+ # observe with names=custom container with iter, contains
+ class MyContainer(object):
+ def __init__(self, container):
+ self.container = container
+
+ def __iter__(self):
+ return iter(self.container)
+
+ def __contains__(self, key):
+ return key in self.container
+
+ c.observe(record, names=MyContainer({'i', 's'}))
+ c.i = 10
+ assert recorded['change'].name == 'i'
+ assert recorded['change'].new == 10
+ c.s = 'ok'
+ assert recorded['change'].name == 's'
+ assert recorded['change'].new == 'ok'
+
+
+def test_super_args():
+ class SuperRecorder(object):
+ def __init__(self, *args, **kwargs):
+ self.super_args = args
+ self.super_kwargs = kwargs
+
+ class SuperHasTraits(HasTraits, SuperRecorder):
+ i = Integer()
+
+ obj = SuperHasTraits('a1', 'a2', b=10, i=5, c='x')
+ assert obj.i == 5
+ assert not hasattr(obj, 'b')
+ assert not hasattr(obj, 'c')
+ assert obj.super_args == ('a1' , 'a2')
+ assert obj.super_kwargs == {'b': 10 , 'c': 'x'}
+
+def test_super_bad_args():
+ class SuperHasTraits(HasTraits):
+ a = Integer()
+
+ if sys.version_info < (3,):
+ # Legacy Python, object.__init__ warns itself, instead of raising
+ w = ['object.__init__']
+ else:
+ w = ["Passing unrecoginized arguments"]
+ with expected_warnings(w):
+ obj = SuperHasTraits(a=1, b=2)
+ assert obj.a == 1
+ assert not hasattr(obj, 'b')
diff --git a/contrib/python/traitlets/py2/traitlets/tests/test_traitlets_enum.py b/contrib/python/traitlets/py2/traitlets/tests/test_traitlets_enum.py
index 82259ae6c5..234466ac99 100644
--- a/contrib/python/traitlets/py2/traitlets/tests/test_traitlets_enum.py
+++ b/contrib/python/traitlets/py2/traitlets/tests/test_traitlets_enum.py
@@ -1,181 +1,181 @@
-# -*- coding: UTF-8 -*-
-# pylint: disable=missing-docstring, too-few-public-methods
-"""
-Test the trait-type ``UseEnum``.
-"""
-
-import unittest
-import enum
-from ipython_genutils.py3compat import string_types
-from traitlets import HasTraits, TraitError, UseEnum
-
-
-# -----------------------------------------------------------------------------
-# TEST SUPPORT:
-# -----------------------------------------------------------------------------
-class Color(enum.Enum):
- red = 1
- green = 2
- blue = 3
- yellow = 4
-
-class OtherColor(enum.Enum):
- red = 0
- green = 1
-
-
-# -----------------------------------------------------------------------------
-# TESTSUITE:
-# -----------------------------------------------------------------------------
-class TestUseEnum(unittest.TestCase):
- # pylint: disable=invalid-name
-
- class Example(HasTraits):
- color = UseEnum(Color, help="Color enum")
-
- def test_assign_enum_value(self):
- example = self.Example()
- example.color = Color.green
- self.assertEqual(example.color, Color.green)
-
- def test_assign_all_enum_values(self):
- # pylint: disable=no-member
- enum_values = [value for value in Color.__members__.values()]
- for value in enum_values:
- self.assertIsInstance(value, Color)
- example = self.Example()
- example.color = value
- self.assertEqual(example.color, value)
- self.assertIsInstance(value, Color)
-
- def test_assign_enum_value__with_other_enum_raises_error(self):
- example = self.Example()
- with self.assertRaises(TraitError):
- example.color = OtherColor.green
-
- def test_assign_enum_name_1(self):
- # -- CONVERT: string => Enum value (item)
- example = self.Example()
- example.color = "red"
- self.assertEqual(example.color, Color.red)
-
- def test_assign_enum_value_name(self):
- # -- CONVERT: string => Enum value (item)
- # pylint: disable=no-member
- enum_names = [enum_val.name for enum_val in Color.__members__.values()]
- for value in enum_names:
- self.assertIsInstance(value, string_types)
- example = self.Example()
- enum_value = Color.__members__.get(value)
- example.color = value
- self.assertIs(example.color, enum_value)
- self.assertEqual(example.color.name, value)
-
- def test_assign_scoped_enum_value_name(self):
- # -- CONVERT: string => Enum value (item)
- scoped_names = ["Color.red", "Color.green", "Color.blue", "Color.yellow"]
- for value in scoped_names:
- example = self.Example()
- example.color = value
- self.assertIsInstance(example.color, Color)
- self.assertEqual(str(example.color), value)
-
- def test_assign_bad_enum_value_name__raises_error(self):
- # -- CONVERT: string => Enum value (item)
- bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
- for value in bad_enum_names:
- example = self.Example()
- with self.assertRaises(TraitError):
- example.color = value
-
- def test_assign_enum_value_number_1(self):
- # -- CONVERT: number => Enum value (item)
- example = self.Example()
- example.color = 1 # == Color.red.value
- example.color = Color.red.value
- self.assertEqual(example.color, Color.red)
-
- def test_assign_enum_value_number(self):
- # -- CONVERT: number => Enum value (item)
- # pylint: disable=no-member
- enum_numbers = [enum_val.value
- for enum_val in Color.__members__.values()]
- for value in enum_numbers:
- self.assertIsInstance(value, int)
- example = self.Example()
- example.color = value
- self.assertIsInstance(example.color, Color)
- self.assertEqual(example.color.value, value)
-
- def test_assign_bad_enum_value_number__raises_error(self):
- # -- CONVERT: number => Enum value (item)
- bad_numbers = [-1, 0, 5]
- for value in bad_numbers:
- self.assertIsInstance(value, int)
- assert UseEnum(Color).select_by_number(value, None) is None
- example = self.Example()
- with self.assertRaises(TraitError):
- example.color = value
-
- def test_ctor_without_default_value(self):
- # -- IMPLICIT: default_value = Color.red (first enum-value)
- class Example2(HasTraits):
- color = UseEnum(Color)
-
- example = Example2()
- self.assertEqual(example.color, Color.red)
-
- def test_ctor_with_default_value_as_enum_value(self):
- # -- CONVERT: number => Enum value (item)
- class Example2(HasTraits):
- color = UseEnum(Color, default_value=Color.green)
-
- example = Example2()
- self.assertEqual(example.color, Color.green)
-
-
- def test_ctor_with_default_value_none_and_not_allow_none(self):
- # -- IMPLICIT: default_value = Color.red (first enum-value)
- class Example2(HasTraits):
- color1 = UseEnum(Color, default_value=None, allow_none=False)
- color2 = UseEnum(Color, default_value=None)
- example = Example2()
- self.assertEqual(example.color1, Color.red)
- self.assertEqual(example.color2, Color.red)
-
- def test_ctor_with_default_value_none_and_allow_none(self):
- class Example2(HasTraits):
- color1 = UseEnum(Color, default_value=None, allow_none=True)
- color2 = UseEnum(Color, allow_none=True)
-
- example = Example2()
- self.assertIs(example.color1, None)
- self.assertIs(example.color2, None)
-
- def test_assign_none_without_allow_none_resets_to_default_value(self):
- class Example2(HasTraits):
- color1 = UseEnum(Color, allow_none=False)
- color2 = UseEnum(Color)
-
- example = Example2()
- example.color1 = None
- example.color2 = None
- self.assertIs(example.color1, Color.red)
- self.assertIs(example.color2, Color.red)
-
- def test_assign_none_to_enum_or_none(self):
- class Example2(HasTraits):
- color = UseEnum(Color, allow_none=True)
-
- example = Example2()
- example.color = None
- self.assertIs(example.color, None)
-
- def test_assign_bad_value_with_to_enum_or_none(self):
- class Example2(HasTraits):
- color = UseEnum(Color, allow_none=True)
-
- example = Example2()
- with self.assertRaises(TraitError):
- example.color = "BAD_VALUE"
-
+# -*- coding: UTF-8 -*-
+# pylint: disable=missing-docstring, too-few-public-methods
+"""
+Test the trait-type ``UseEnum``.
+"""
+
+import unittest
+import enum
+from ipython_genutils.py3compat import string_types
+from traitlets import HasTraits, TraitError, UseEnum
+
+
+# -----------------------------------------------------------------------------
+# TEST SUPPORT:
+# -----------------------------------------------------------------------------
+class Color(enum.Enum):
+ red = 1
+ green = 2
+ blue = 3
+ yellow = 4
+
+class OtherColor(enum.Enum):
+ red = 0
+ green = 1
+
+
+# -----------------------------------------------------------------------------
+# TESTSUITE:
+# -----------------------------------------------------------------------------
+class TestUseEnum(unittest.TestCase):
+ # pylint: disable=invalid-name
+
+ class Example(HasTraits):
+ color = UseEnum(Color, help="Color enum")
+
+ def test_assign_enum_value(self):
+ example = self.Example()
+ example.color = Color.green
+ self.assertEqual(example.color, Color.green)
+
+ def test_assign_all_enum_values(self):
+ # pylint: disable=no-member
+ enum_values = [value for value in Color.__members__.values()]
+ for value in enum_values:
+ self.assertIsInstance(value, Color)
+ example = self.Example()
+ example.color = value
+ self.assertEqual(example.color, value)
+ self.assertIsInstance(value, Color)
+
+ def test_assign_enum_value__with_other_enum_raises_error(self):
+ example = self.Example()
+ with self.assertRaises(TraitError):
+ example.color = OtherColor.green
+
+ def test_assign_enum_name_1(self):
+ # -- CONVERT: string => Enum value (item)
+ example = self.Example()
+ example.color = "red"
+ self.assertEqual(example.color, Color.red)
+
+ def test_assign_enum_value_name(self):
+ # -- CONVERT: string => Enum value (item)
+ # pylint: disable=no-member
+ enum_names = [enum_val.name for enum_val in Color.__members__.values()]
+ for value in enum_names:
+ self.assertIsInstance(value, string_types)
+ example = self.Example()
+ enum_value = Color.__members__.get(value)
+ example.color = value
+ self.assertIs(example.color, enum_value)
+ self.assertEqual(example.color.name, value)
+
+ def test_assign_scoped_enum_value_name(self):
+ # -- CONVERT: string => Enum value (item)
+ scoped_names = ["Color.red", "Color.green", "Color.blue", "Color.yellow"]
+ for value in scoped_names:
+ example = self.Example()
+ example.color = value
+ self.assertIsInstance(example.color, Color)
+ self.assertEqual(str(example.color), value)
+
+ def test_assign_bad_enum_value_name__raises_error(self):
+ # -- CONVERT: string => Enum value (item)
+ bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
+ for value in bad_enum_names:
+ example = self.Example()
+ with self.assertRaises(TraitError):
+ example.color = value
+
+ def test_assign_enum_value_number_1(self):
+ # -- CONVERT: number => Enum value (item)
+ example = self.Example()
+ example.color = 1 # == Color.red.value
+ example.color = Color.red.value
+ self.assertEqual(example.color, Color.red)
+
+ def test_assign_enum_value_number(self):
+ # -- CONVERT: number => Enum value (item)
+ # pylint: disable=no-member
+ enum_numbers = [enum_val.value
+ for enum_val in Color.__members__.values()]
+ for value in enum_numbers:
+ self.assertIsInstance(value, int)
+ example = self.Example()
+ example.color = value
+ self.assertIsInstance(example.color, Color)
+ self.assertEqual(example.color.value, value)
+
+ def test_assign_bad_enum_value_number__raises_error(self):
+ # -- CONVERT: number => Enum value (item)
+ bad_numbers = [-1, 0, 5]
+ for value in bad_numbers:
+ self.assertIsInstance(value, int)
+ assert UseEnum(Color).select_by_number(value, None) is None
+ example = self.Example()
+ with self.assertRaises(TraitError):
+ example.color = value
+
+ def test_ctor_without_default_value(self):
+ # -- IMPLICIT: default_value = Color.red (first enum-value)
+ class Example2(HasTraits):
+ color = UseEnum(Color)
+
+ example = Example2()
+ self.assertEqual(example.color, Color.red)
+
+ def test_ctor_with_default_value_as_enum_value(self):
+ # -- CONVERT: number => Enum value (item)
+ class Example2(HasTraits):
+ color = UseEnum(Color, default_value=Color.green)
+
+ example = Example2()
+ self.assertEqual(example.color, Color.green)
+
+
+ def test_ctor_with_default_value_none_and_not_allow_none(self):
+ # -- IMPLICIT: default_value = Color.red (first enum-value)
+ class Example2(HasTraits):
+ color1 = UseEnum(Color, default_value=None, allow_none=False)
+ color2 = UseEnum(Color, default_value=None)
+ example = Example2()
+ self.assertEqual(example.color1, Color.red)
+ self.assertEqual(example.color2, Color.red)
+
+ def test_ctor_with_default_value_none_and_allow_none(self):
+ class Example2(HasTraits):
+ color1 = UseEnum(Color, default_value=None, allow_none=True)
+ color2 = UseEnum(Color, allow_none=True)
+
+ example = Example2()
+ self.assertIs(example.color1, None)
+ self.assertIs(example.color2, None)
+
+ def test_assign_none_without_allow_none_resets_to_default_value(self):
+ class Example2(HasTraits):
+ color1 = UseEnum(Color, allow_none=False)
+ color2 = UseEnum(Color)
+
+ example = Example2()
+ example.color1 = None
+ example.color2 = None
+ self.assertIs(example.color1, Color.red)
+ self.assertIs(example.color2, Color.red)
+
+ def test_assign_none_to_enum_or_none(self):
+ class Example2(HasTraits):
+ color = UseEnum(Color, allow_none=True)
+
+ example = Example2()
+ example.color = None
+ self.assertIs(example.color, None)
+
+ def test_assign_bad_value_with_to_enum_or_none(self):
+ class Example2(HasTraits):
+ color = UseEnum(Color, allow_none=True)
+
+ example = Example2()
+ with self.assertRaises(TraitError):
+ example.color = "BAD_VALUE"
+
diff --git a/contrib/python/traitlets/py2/traitlets/tests/utils.py b/contrib/python/traitlets/py2/traitlets/tests/utils.py
index 88845d8519..4efe85358a 100644
--- a/contrib/python/traitlets/py2/traitlets/tests/utils.py
+++ b/contrib/python/traitlets/py2/traitlets/tests/utils.py
@@ -1,39 +1,39 @@
-import sys
-
-from subprocess import Popen, PIPE
-
-def get_output_error_code(cmd):
- """Get stdout, stderr, and exit code from running a command"""
+import sys
+
+from subprocess import Popen, PIPE
+
+def get_output_error_code(cmd):
+ """Get stdout, stderr, and exit code from running a command"""
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
- out, err = p.communicate()
- out = out.decode('utf8', 'replace')
- err = err.decode('utf8', 'replace')
- return out, err, p.returncode
-
-
-def check_help_output(pkg, subcommand=None):
- """test that `python -m PKG [subcommand] -h` works"""
- cmd = [sys.executable, '-m', pkg]
- if subcommand:
- cmd.extend(subcommand)
- cmd.append('-h')
- out, err, rc = get_output_error_code(cmd)
- assert rc == 0, err
- assert "Traceback" not in err
- assert "Options" in out
- assert "--help-all" in out
- return out, err
-
-
-def check_help_all_output(pkg, subcommand=None):
- """test that `python -m PKG --help-all` works"""
- cmd = [sys.executable, '-m', pkg]
- if subcommand:
- cmd.extend(subcommand)
- cmd.append('--help-all')
- out, err, rc = get_output_error_code(cmd)
- assert rc == 0, err
- assert "Traceback" not in err
- assert "Options" in out
- assert "Class parameters" in out
- return out, err
+ out, err = p.communicate()
+ out = out.decode('utf8', 'replace')
+ err = err.decode('utf8', 'replace')
+ return out, err, p.returncode
+
+
+def check_help_output(pkg, subcommand=None):
+ """test that `python -m PKG [subcommand] -h` works"""
+ cmd = [sys.executable, '-m', pkg]
+ if subcommand:
+ cmd.extend(subcommand)
+ cmd.append('-h')
+ out, err, rc = get_output_error_code(cmd)
+ assert rc == 0, err
+ assert "Traceback" not in err
+ assert "Options" in out
+ assert "--help-all" in out
+ return out, err
+
+
+def check_help_all_output(pkg, subcommand=None):
+ """test that `python -m PKG --help-all` works"""
+ cmd = [sys.executable, '-m', pkg]
+ if subcommand:
+ cmd.extend(subcommand)
+ cmd.append('--help-all')
+ out, err, rc = get_output_error_code(cmd)
+ assert rc == 0, err
+ assert "Traceback" not in err
+ assert "Options" in out
+ assert "Class parameters" in out
+ return out, err
diff --git a/contrib/python/traitlets/py2/ya.make b/contrib/python/traitlets/py2/ya.make
index 4a60107101..ed668b5d34 100644
--- a/contrib/python/traitlets/py2/ya.make
+++ b/contrib/python/traitlets/py2/ya.make
@@ -44,7 +44,7 @@ RESOURCE_FILES(
)
END()
-
-RECURSE_FOR_TESTS(
+
+RECURSE_FOR_TESTS(
tests
-)
+)
diff --git a/contrib/python/traitlets/py3/traitlets/tests/_warnings.py b/contrib/python/traitlets/py3/traitlets/tests/_warnings.py
index 05e916806f..eb80d0a936 100644
--- a/contrib/python/traitlets/py3/traitlets/tests/_warnings.py
+++ b/contrib/python/traitlets/py3/traitlets/tests/_warnings.py
@@ -1,110 +1,110 @@
-# From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py
-# Licensed under modified BSD license
-
-__all__ = ['all_warnings', 'expected_warnings']
-
+# From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py
+# Licensed under modified BSD license
+
+__all__ = ['all_warnings', 'expected_warnings']
+
import inspect
import os
import re
-import sys
-import warnings
+import sys
+import warnings
from contextlib import contextmanager
from unittest import mock
-
-
-@contextmanager
-def all_warnings():
- """
- Context for use in testing to ensure that all warnings are raised.
- Examples
- --------
- >>> import warnings
- >>> def foo():
- ... warnings.warn(RuntimeWarning("bar"))
- We raise the warning once, while the warning filter is set to "once".
- Hereafter, the warning is invisible, even with custom filters:
- >>> with warnings.catch_warnings():
- ... warnings.simplefilter('once')
- ... foo()
- We can now run ``foo()`` without a warning being raised:
- >>> from numpy.testing import assert_warns
- >>> foo()
- To catch the warning, we call in the help of ``all_warnings``:
- >>> with all_warnings():
- ... assert_warns(RuntimeWarning, foo)
- """
-
- # Whenever a warning is triggered, Python adds a __warningregistry__
- # member to the *calling* module. The exercize here is to find
- # and eradicate all those breadcrumbs that were left lying around.
- #
- # We proceed by first searching all parent calling frames and explicitly
- # clearing their warning registries (necessary for the doctests above to
- # pass). Then, we search for all submodules of skimage and clear theirs
- # as well (necessary for the skimage test suite to pass).
-
- frame = inspect.currentframe()
- if frame:
- for f in inspect.getouterframes(frame):
- f[0].f_locals['__warningregistry__'] = {}
- del frame
-
- for mod_name, mod in list(sys.modules.items()):
- try:
- mod.__warningregistry__.clear()
- except AttributeError:
- pass
-
+
+
+@contextmanager
+def all_warnings():
+ """
+ Context for use in testing to ensure that all warnings are raised.
+ Examples
+ --------
+ >>> import warnings
+ >>> def foo():
+ ... warnings.warn(RuntimeWarning("bar"))
+ We raise the warning once, while the warning filter is set to "once".
+ Hereafter, the warning is invisible, even with custom filters:
+ >>> with warnings.catch_warnings():
+ ... warnings.simplefilter('once')
+ ... foo()
+ We can now run ``foo()`` without a warning being raised:
+ >>> from numpy.testing import assert_warns
+ >>> foo()
+ To catch the warning, we call in the help of ``all_warnings``:
+ >>> with all_warnings():
+ ... assert_warns(RuntimeWarning, foo)
+ """
+
+ # Whenever a warning is triggered, Python adds a __warningregistry__
+ # member to the *calling* module. The exercize here is to find
+ # and eradicate all those breadcrumbs that were left lying around.
+ #
+ # We proceed by first searching all parent calling frames and explicitly
+ # clearing their warning registries (necessary for the doctests above to
+ # pass). Then, we search for all submodules of skimage and clear theirs
+ # as well (necessary for the skimage test suite to pass).
+
+ frame = inspect.currentframe()
+ if frame:
+ for f in inspect.getouterframes(frame):
+ f[0].f_locals['__warningregistry__'] = {}
+ del frame
+
+ for mod_name, mod in list(sys.modules.items()):
+ try:
+ mod.__warningregistry__.clear()
+ except AttributeError:
+ pass
+
with warnings.catch_warnings(record=True) as w, \
mock.patch.dict(os.environ, {'TRAITLETS_ALL_DEPRECATIONS': '1'}):
- warnings.simplefilter("always")
- yield w
-
-
-@contextmanager
-def expected_warnings(matching):
+ warnings.simplefilter("always")
+ yield w
+
+
+@contextmanager
+def expected_warnings(matching):
r"""Context for use in testing to catch known warnings matching regexes
- Parameters
- ----------
- matching : list of strings or compiled regexes
- Regexes for the desired warning to catch
+ Parameters
+ ----------
+ matching : list of strings or compiled regexes
+ Regexes for the desired warning to catch
- Examples
- --------
- >>> from skimage import data, img_as_ubyte, img_as_float
+ Examples
+ --------
+ >>> from skimage import data, img_as_ubyte, img_as_float
>>> with expected_warnings(["precision loss"]):
- ... d = img_as_ubyte(img_as_float(data.coins()))
+ ... d = img_as_ubyte(img_as_float(data.coins()))
- Notes
- -----
- Uses `all_warnings` to ensure all warnings are raised.
- Upon exiting, it checks the recorded warnings for the desired matching
- pattern(s).
- Raises a ValueError if any match was not found or an unexpected
- warning was raised.
- Allows for three types of behaviors: "and", "or", and "optional" matches.
- This is done to accomodate different build enviroments or loop conditions
- that may produce different warnings. The behaviors can be combined.
- If you pass multiple patterns, you get an orderless "and", where all of the
- warnings must be raised.
- If you use the "|" operator in a pattern, you can catch one of several warnings.
- Finally, you can use "|\A\Z" in a pattern to signify it as optional.
- """
- with all_warnings() as w:
- # enter context
- yield w
- # exited user context, check the recorded warnings
+ Notes
+ -----
+ Uses `all_warnings` to ensure all warnings are raised.
+ Upon exiting, it checks the recorded warnings for the desired matching
+ pattern(s).
+ Raises a ValueError if any match was not found or an unexpected
+ warning was raised.
+ Allows for three types of behaviors: "and", "or", and "optional" matches.
+ This is done to accomodate different build enviroments or loop conditions
+ that may produce different warnings. The behaviors can be combined.
+ If you pass multiple patterns, you get an orderless "and", where all of the
+ warnings must be raised.
+ If you use the "|" operator in a pattern, you can catch one of several warnings.
+ Finally, you can use "|\A\Z" in a pattern to signify it as optional.
+ """
+ with all_warnings() as w:
+ # enter context
+ yield w
+ # exited user context, check the recorded warnings
remaining = [m for m in matching if not r'\A\Z' in m.split('|')]
- for warn in w:
- found = False
- for match in matching:
- if re.search(match, str(warn.message)) is not None:
- found = True
- if match in remaining:
- remaining.remove(match)
- if not found:
- raise ValueError('Unexpected warning: %s' % str(warn.message))
- if len(remaining) > 0:
- msg = 'No warning raised matching:\n%s' % '\n'.join(remaining)
- raise ValueError(msg)
+ for warn in w:
+ found = False
+ for match in matching:
+ if re.search(match, str(warn.message)) is not None:
+ found = True
+ if match in remaining:
+ remaining.remove(match)
+ if not found:
+ raise ValueError('Unexpected warning: %s' % str(warn.message))
+ if len(remaining) > 0:
+ msg = 'No warning raised matching:\n%s' % '\n'.join(remaining)
+ raise ValueError(msg)
diff --git a/contrib/python/traitlets/py3/traitlets/tests/test_traitlets.py b/contrib/python/traitlets/py3/traitlets/tests/test_traitlets.py
index e42dbc01d0..ece95f6108 100644
--- a/contrib/python/traitlets/py3/traitlets/tests/test_traitlets.py
+++ b/contrib/python/traitlets/py3/traitlets/tests/test_traitlets.py
@@ -1,20 +1,20 @@
-# encoding: utf-8
-"""Tests for traitlets.traitlets."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# encoding: utf-8
+"""Tests for traitlets.traitlets."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
#
-# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
-# also under the terms of the Modified BSD License.
-
-import pickle
-import re
+# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
+# also under the terms of the Modified BSD License.
+
+import pickle
+import re
from unittest import TestCase
-
-import pytest
-
+
+import pytest
+
from traitlets.tests._warnings import expected_warnings
-from traitlets import (
+from traitlets import (
HasTraits,
MetaHasTraits,
TraitType,
@@ -60,121 +60,121 @@ from traitlets import (
BaseDescriptor,
HasDescriptors,
CUnicode,
-)
+)
from traitlets.utils import cast_unicode
-
-
-def change_dict(*ordered_values):
- change_names = ('name', 'old', 'new', 'owner', 'type')
- return dict(zip(change_names, ordered_values))
-
-#-----------------------------------------------------------------------------
-# Helper classes for testing
-#-----------------------------------------------------------------------------
-
-
-class HasTraitsStub(HasTraits):
-
- def notify_change(self, change):
- self._notify_name = change['name']
- self._notify_old = change['old']
- self._notify_new = change['new']
- self._notify_type = change['type']
-
-
-#-----------------------------------------------------------------------------
-# Test classes
-#-----------------------------------------------------------------------------
-
-
-class TestTraitType(TestCase):
-
- def test_get_undefined(self):
- class A(HasTraits):
- a = TraitType
- a = A()
+
+
+def change_dict(*ordered_values):
+ change_names = ('name', 'old', 'new', 'owner', 'type')
+ return dict(zip(change_names, ordered_values))
+
+#-----------------------------------------------------------------------------
+# Helper classes for testing
+#-----------------------------------------------------------------------------
+
+
+class HasTraitsStub(HasTraits):
+
+ def notify_change(self, change):
+ self._notify_name = change['name']
+ self._notify_old = change['old']
+ self._notify_new = change['new']
+ self._notify_type = change['type']
+
+
+#-----------------------------------------------------------------------------
+# Test classes
+#-----------------------------------------------------------------------------
+
+
+class TestTraitType(TestCase):
+
+ def test_get_undefined(self):
+ class A(HasTraits):
+ a = TraitType
+ a = A()
assert a.a is Undefined
-
- def test_set(self):
- class A(HasTraitsStub):
- a = TraitType
-
- a = A()
- a.a = 10
- self.assertEqual(a.a, 10)
- self.assertEqual(a._notify_name, 'a')
- self.assertEqual(a._notify_old, Undefined)
- self.assertEqual(a._notify_new, 10)
-
- def test_validate(self):
- class MyTT(TraitType):
- def validate(self, inst, value):
- return -1
- class A(HasTraitsStub):
- tt = MyTT
-
- a = A()
- a.tt = 10
- self.assertEqual(a.tt, -1)
-
- def test_default_validate(self):
- class MyIntTT(TraitType):
- def validate(self, obj, value):
- if isinstance(value, int):
- return value
- self.error(obj, value)
- class A(HasTraits):
- tt = MyIntTT(10)
- a = A()
- self.assertEqual(a.tt, 10)
-
- # Defaults are validated when the HasTraits is instantiated
- class B(HasTraits):
- tt = MyIntTT('bad default')
+
+ def test_set(self):
+ class A(HasTraitsStub):
+ a = TraitType
+
+ a = A()
+ a.a = 10
+ self.assertEqual(a.a, 10)
+ self.assertEqual(a._notify_name, 'a')
+ self.assertEqual(a._notify_old, Undefined)
+ self.assertEqual(a._notify_new, 10)
+
+ def test_validate(self):
+ class MyTT(TraitType):
+ def validate(self, inst, value):
+ return -1
+ class A(HasTraitsStub):
+ tt = MyTT
+
+ a = A()
+ a.tt = 10
+ self.assertEqual(a.tt, -1)
+
+ def test_default_validate(self):
+ class MyIntTT(TraitType):
+ def validate(self, obj, value):
+ if isinstance(value, int):
+ return value
+ self.error(obj, value)
+ class A(HasTraits):
+ tt = MyIntTT(10)
+ a = A()
+ self.assertEqual(a.tt, 10)
+
+ # Defaults are validated when the HasTraits is instantiated
+ class B(HasTraits):
+ tt = MyIntTT('bad default')
self.assertRaises(TraitError, getattr, B(), 'tt')
-
- def test_info(self):
- class A(HasTraits):
- tt = TraitType
- a = A()
- self.assertEqual(A.tt.info(), 'any value')
-
- def test_error(self):
- class A(HasTraits):
+
+ def test_info(self):
+ class A(HasTraits):
+ tt = TraitType
+ a = A()
+ self.assertEqual(A.tt.info(), 'any value')
+
+ def test_error(self):
+ class A(HasTraits):
tt = TraitType()
- a = A()
- self.assertRaises(TraitError, A.tt.error, a, 10)
-
- def test_deprecated_dynamic_initializer(self):
- class A(HasTraits):
- x = Int(10)
- def _x_default(self):
- return 11
- class B(A):
- x = Int(20)
- class C(A):
- def _x_default(self):
- return 21
-
- a = A()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
- b = B()
- self.assertEqual(b.x, 20)
- self.assertEqual(b._trait_values, {'x': 20})
- c = C()
- self.assertEqual(c._trait_values, {})
- self.assertEqual(c.x, 21)
- self.assertEqual(c._trait_values, {'x': 21})
- # Ensure that the base class remains unmolested when the _default
- # initializer gets overridden in a subclass.
- a = A()
- c = C()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
-
+ a = A()
+ self.assertRaises(TraitError, A.tt.error, a, 10)
+
+ def test_deprecated_dynamic_initializer(self):
+ class A(HasTraits):
+ x = Int(10)
+ def _x_default(self):
+ return 11
+ class B(A):
+ x = Int(20)
+ class C(A):
+ def _x_default(self):
+ return 21
+
+ a = A()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+ b = B()
+ self.assertEqual(b.x, 20)
+ self.assertEqual(b._trait_values, {'x': 20})
+ c = C()
+ self.assertEqual(c._trait_values, {})
+ self.assertEqual(c.x, 21)
+ self.assertEqual(c._trait_values, {'x': 21})
+ # Ensure that the base class remains unmolested when the _default
+ # initializer gets overridden in a subclass.
+ a = A()
+ c = C()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+
def test_deprecated_method_warnings(self):
with expected_warnings([]):
@@ -215,79 +215,79 @@ class TestTraitType(TestCase):
assert obj.x == 5
- def test_dynamic_initializer(self):
-
- class A(HasTraits):
- x = Int(10)
-
- @default('x')
- def _default_x(self):
- return 11
-
- class B(A):
- x = Int(20)
-
- class C(A):
-
- @default('x')
- def _default_x(self):
- return 21
-
- a = A()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
- b = B()
- self.assertEqual(b.x, 20)
- self.assertEqual(b._trait_values, {'x': 20})
- c = C()
- self.assertEqual(c._trait_values, {})
- self.assertEqual(c.x, 21)
- self.assertEqual(c._trait_values, {'x': 21})
- # Ensure that the base class remains unmolested when the _default
- # initializer gets overridden in a subclass.
- a = A()
- c = C()
- self.assertEqual(a._trait_values, {})
- self.assertEqual(a.x, 11)
- self.assertEqual(a._trait_values, {'x': 11})
-
- def test_tag_metadata(self):
- class MyIntTT(TraitType):
- metadata = {'a': 1, 'b': 2}
- a = MyIntTT(10).tag(b=3, c=4)
- self.assertEqual(a.metadata, {'a': 1, 'b': 3, 'c': 4})
-
- def test_metadata_localized_instance(self):
- class MyIntTT(TraitType):
- metadata = {'a': 1, 'b': 2}
- a = MyIntTT(10)
- b = MyIntTT(10)
- a.metadata['c'] = 3
- # make sure that changing a's metadata didn't change b's metadata
- self.assertNotIn('c', b.metadata)
-
- def test_union_metadata(self):
- class Foo(HasTraits):
- bar = (Int().tag(ta=1) | Dict().tag(ta=2, ti='b')).tag(ti='a')
- foo = Foo()
- # At this point, no value has been set for bar, so value-specific
- # is not set.
- self.assertEqual(foo.trait_metadata('bar', 'ta'), None)
- self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
- foo.bar = {}
- self.assertEqual(foo.trait_metadata('bar', 'ta'), 2)
- self.assertEqual(foo.trait_metadata('bar', 'ti'), 'b')
- foo.bar = 1
- self.assertEqual(foo.trait_metadata('bar', 'ta'), 1)
- self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
-
- def test_union_default_value(self):
- class Foo(HasTraits):
- bar = Union([Dict(), Int()], default_value=1)
- foo = Foo()
- self.assertEqual(foo.bar, 1)
-
+ def test_dynamic_initializer(self):
+
+ class A(HasTraits):
+ x = Int(10)
+
+ @default('x')
+ def _default_x(self):
+ return 11
+
+ class B(A):
+ x = Int(20)
+
+ class C(A):
+
+ @default('x')
+ def _default_x(self):
+ return 21
+
+ a = A()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+ b = B()
+ self.assertEqual(b.x, 20)
+ self.assertEqual(b._trait_values, {'x': 20})
+ c = C()
+ self.assertEqual(c._trait_values, {})
+ self.assertEqual(c.x, 21)
+ self.assertEqual(c._trait_values, {'x': 21})
+ # Ensure that the base class remains unmolested when the _default
+ # initializer gets overridden in a subclass.
+ a = A()
+ c = C()
+ self.assertEqual(a._trait_values, {})
+ self.assertEqual(a.x, 11)
+ self.assertEqual(a._trait_values, {'x': 11})
+
+ def test_tag_metadata(self):
+ class MyIntTT(TraitType):
+ metadata = {'a': 1, 'b': 2}
+ a = MyIntTT(10).tag(b=3, c=4)
+ self.assertEqual(a.metadata, {'a': 1, 'b': 3, 'c': 4})
+
+ def test_metadata_localized_instance(self):
+ class MyIntTT(TraitType):
+ metadata = {'a': 1, 'b': 2}
+ a = MyIntTT(10)
+ b = MyIntTT(10)
+ a.metadata['c'] = 3
+ # make sure that changing a's metadata didn't change b's metadata
+ self.assertNotIn('c', b.metadata)
+
+ def test_union_metadata(self):
+ class Foo(HasTraits):
+ bar = (Int().tag(ta=1) | Dict().tag(ta=2, ti='b')).tag(ti='a')
+ foo = Foo()
+ # At this point, no value has been set for bar, so value-specific
+ # is not set.
+ self.assertEqual(foo.trait_metadata('bar', 'ta'), None)
+ self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
+ foo.bar = {}
+ self.assertEqual(foo.trait_metadata('bar', 'ta'), 2)
+ self.assertEqual(foo.trait_metadata('bar', 'ti'), 'b')
+ foo.bar = 1
+ self.assertEqual(foo.trait_metadata('bar', 'ta'), 1)
+ self.assertEqual(foo.trait_metadata('bar', 'ti'), 'a')
+
+ def test_union_default_value(self):
+ class Foo(HasTraits):
+ bar = Union([Dict(), Int()], default_value=1)
+ foo = Foo()
+ self.assertEqual(foo.bar, 1)
+
def test_union_validation_priority(self):
class Foo(HasTraits):
bar = Union([CInt(), Unicode()])
@@ -301,506 +301,506 @@ class TestTraitType(TestCase):
bar = Union([Dict(), Int()])
self.assertEqual(Foo().bar, {})
- def test_deprecated_metadata_access(self):
- class MyIntTT(TraitType):
- metadata = {'a': 1, 'b': 2}
- a = MyIntTT(10)
- with expected_warnings(["use the instance .metadata dictionary directly"]*2):
- a.set_metadata('key', 'value')
- v = a.get_metadata('key')
- self.assertEqual(v, 'value')
- with expected_warnings(["use the instance .help string directly"]*2):
- a.set_metadata('help', 'some help')
- v = a.get_metadata('help')
- self.assertEqual(v, 'some help')
-
- def test_trait_types_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = Int
-
- def test_trait_types_list_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = List(Int)
-
- def test_trait_types_tuple_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = Tuple(Int)
-
- def test_trait_types_dict_deprecated(self):
- with expected_warnings(["Traits should be given as instances"]):
- class C(HasTraits):
- t = Dict(Int)
-
-class TestHasDescriptorsMeta(TestCase):
-
- def test_metaclass(self):
- self.assertEqual(type(HasTraits), MetaHasTraits)
-
- class A(HasTraits):
- a = Int()
-
- a = A()
- self.assertEqual(type(a.__class__), MetaHasTraits)
- self.assertEqual(a.a,0)
- a.a = 10
- self.assertEqual(a.a,10)
-
- class B(HasTraits):
- b = Int()
-
- b = B()
- self.assertEqual(b.b,0)
- b.b = 10
- self.assertEqual(b.b,10)
-
- class C(HasTraits):
- c = Int(30)
-
- c = C()
- self.assertEqual(c.c,30)
- c.c = 10
- self.assertEqual(c.c,10)
-
- def test_this_class(self):
- class A(HasTraits):
- t = This()
- tt = This()
- class B(A):
- tt = This()
- ttt = This()
- self.assertEqual(A.t.this_class, A)
- self.assertEqual(B.t.this_class, A)
- self.assertEqual(B.tt.this_class, B)
- self.assertEqual(B.ttt.this_class, B)
-
-class TestHasDescriptors(TestCase):
-
- def test_setup_instance(self):
-
- class FooDescriptor(BaseDescriptor):
-
- def instance_init(self, inst):
- foo = inst.foo # instance should have the attr
-
- class HasFooDescriptors(HasDescriptors):
-
- fd = FooDescriptor()
-
- def setup_instance(self, *args, **kwargs):
- self.foo = kwargs.get('foo', None)
- super(HasFooDescriptors, self).setup_instance(*args, **kwargs)
-
- hfd = HasFooDescriptors(foo='bar')
-
-class TestHasTraitsNotify(TestCase):
-
- def setUp(self):
- self._notify1 = []
- self._notify2 = []
-
- def notify1(self, name, old, new):
- self._notify1.append((name, old, new))
-
- def notify2(self, name, old, new):
- self._notify2.append((name, old, new))
-
- def test_notify_all(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.on_trait_change(self.notify1)
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.b = 0.0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- self.assertTrue(('a',0,10) in self._notify1)
- a.b = 10.0
- self.assertTrue(('b',0.0,10.0) in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
- self.assertRaises(TraitError,setattr,a,'b','bad string')
- self._notify1 = []
- a.on_trait_change(self.notify1,remove=True)
- a.a = 20
- a.b = 20.0
- self.assertEqual(len(self._notify1),0)
-
- def test_notify_one(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.on_trait_change(self.notify1, 'a')
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- self.assertTrue(('a',0,10) in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
-
- def test_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- self.assertEqual(b.a,0)
- self.assertEqual(b.b,0.0)
- b.a = 100
- b.b = 100.0
- self.assertEqual(b.a,100)
- self.assertEqual(b.b,100.0)
-
- def test_notify_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- b.on_trait_change(self.notify1, 'a')
- b.on_trait_change(self.notify2, 'b')
- b.a = 0
- b.b = 0.0
- self.assertEqual(len(self._notify1),0)
- self.assertEqual(len(self._notify2),0)
- b.a = 10
- b.b = 10.0
- self.assertTrue(('a',0,10) in self._notify1)
- self.assertTrue(('b',0.0,10.0) in self._notify2)
-
- def test_static_notify(self):
-
- class A(HasTraits):
- a = Int()
- _notify1 = []
- def _a_changed(self, name, old, new):
- self._notify1.append((name, old, new))
-
- a = A()
- a.a = 0
- # This is broken!!!
- self.assertEqual(len(a._notify1),0)
- a.a = 10
- self.assertTrue(('a',0,10) in a._notify1)
-
- class B(A):
- b = Float()
- _notify2 = []
- def _b_changed(self, name, old, new):
- self._notify2.append((name, old, new))
-
- b = B()
- b.a = 10
- b.b = 10.0
- self.assertTrue(('a',0,10) in b._notify1)
- self.assertTrue(('b',0.0,10.0) in b._notify2)
-
- def test_notify_args(self):
-
- def callback0():
- self.cb = ()
- def callback1(name):
- self.cb = (name,)
- def callback2(name, new):
- self.cb = (name, new)
- def callback3(name, old, new):
- self.cb = (name, old, new)
- def callback4(name, old, new, obj):
- self.cb = (name, old, new, obj)
-
- class A(HasTraits):
- a = Int()
-
- a = A()
- a.on_trait_change(callback0, 'a')
- a.a = 10
- self.assertEqual(self.cb,())
- a.on_trait_change(callback0, 'a', remove=True)
-
- a.on_trait_change(callback1, 'a')
- a.a = 100
- self.assertEqual(self.cb,('a',))
- a.on_trait_change(callback1, 'a', remove=True)
-
- a.on_trait_change(callback2, 'a')
- a.a = 1000
- self.assertEqual(self.cb,('a',1000))
- a.on_trait_change(callback2, 'a', remove=True)
-
- a.on_trait_change(callback3, 'a')
- a.a = 10000
- self.assertEqual(self.cb,('a',1000,10000))
- a.on_trait_change(callback3, 'a', remove=True)
-
- a.on_trait_change(callback4, 'a')
- a.a = 100000
- self.assertEqual(self.cb,('a',10000,100000,a))
- self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
- a.on_trait_change(callback4, 'a', remove=True)
-
- self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
-
- def test_notify_only_once(self):
-
- class A(HasTraits):
- listen_to = ['a']
-
- a = Int(0)
- b = 0
-
- def __init__(self, **kwargs):
- super(A, self).__init__(**kwargs)
- self.on_trait_change(self.listener1, ['a'])
-
- def listener1(self, name, old, new):
- self.b += 1
-
- class B(A):
-
- c = 0
- d = 0
-
- def __init__(self, **kwargs):
- super(B, self).__init__(**kwargs)
- self.on_trait_change(self.listener2)
-
- def listener2(self, name, old, new):
- self.c += 1
-
- def _a_changed(self, name, old, new):
- self.d += 1
-
- b = B()
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
-
-class TestObserveDecorator(TestCase):
-
- def setUp(self):
- self._notify1 = []
- self._notify2 = []
-
- def notify1(self, change):
- self._notify1.append(change)
-
- def notify2(self, change):
- self._notify2.append(change)
-
- def test_notify_all(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.observe(self.notify1)
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.b = 0.0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- change = change_dict('a', 0, 10, a, 'change')
- self.assertTrue(change in self._notify1)
- a.b = 10.0
- change = change_dict('b', 0.0, 10.0, a, 'change')
- self.assertTrue(change in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
- self.assertRaises(TraitError,setattr,a,'b','bad string')
- self._notify1 = []
- a.unobserve(self.notify1)
- a.a = 20
- a.b = 20.0
- self.assertEqual(len(self._notify1),0)
-
- def test_notify_one(self):
-
- class A(HasTraits):
- a = Int()
- b = Float()
-
- a = A()
- a.observe(self.notify1, 'a')
- a.a = 0
- self.assertEqual(len(self._notify1),0)
- a.a = 10
- change = change_dict('a', 0, 10, a, 'change')
- self.assertTrue(change in self._notify1)
- self.assertRaises(TraitError,setattr,a,'a','bad string')
-
- def test_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- self.assertEqual(b.a,0)
- self.assertEqual(b.b,0.0)
- b.a = 100
- b.b = 100.0
- self.assertEqual(b.a,100)
- self.assertEqual(b.b,100.0)
-
- def test_notify_subclass(self):
-
- class A(HasTraits):
- a = Int()
-
- class B(A):
- b = Float()
-
- b = B()
- b.observe(self.notify1, 'a')
- b.observe(self.notify2, 'b')
- b.a = 0
- b.b = 0.0
- self.assertEqual(len(self._notify1),0)
- self.assertEqual(len(self._notify2),0)
- b.a = 10
- b.b = 10.0
- change = change_dict('a', 0, 10, b, 'change')
- self.assertTrue(change in self._notify1)
- change = change_dict('b', 0.0, 10.0, b, 'change')
- self.assertTrue(change in self._notify2)
-
- def test_static_notify(self):
-
- class A(HasTraits):
- a = Int()
- b = Int()
- _notify1 = []
- _notify_any = []
-
- @observe('a')
- def _a_changed(self, change):
- self._notify1.append(change)
-
- @observe(All)
- def _any_changed(self, change):
- self._notify_any.append(change)
-
- a = A()
- a.a = 0
- self.assertEqual(len(a._notify1),0)
- a.a = 10
- change = change_dict('a', 0, 10, a, 'change')
- self.assertTrue(change in a._notify1)
- a.b = 1
- self.assertEqual(len(a._notify_any), 2)
- change = change_dict('b', 0, 1, a, 'change')
- self.assertTrue(change in a._notify_any)
-
- class B(A):
- b = Float()
- _notify2 = []
- @observe('b')
- def _b_changed(self, change):
- self._notify2.append(change)
-
- b = B()
- b.a = 10
- b.b = 10.0
- change = change_dict('a', 0, 10, b, 'change')
- self.assertTrue(change in b._notify1)
- change = change_dict('b', 0.0, 10.0, b, 'change')
- self.assertTrue(change in b._notify2)
-
- def test_notify_args(self):
-
- def callback0():
- self.cb = ()
- def callback1(change):
- self.cb = change
-
- class A(HasTraits):
- a = Int()
-
- a = A()
- a.on_trait_change(callback0, 'a')
- a.a = 10
- self.assertEqual(self.cb,())
- a.unobserve(callback0, 'a')
-
- a.observe(callback1, 'a')
- a.a = 100
- change = change_dict('a', 10, 100, a, 'change')
- self.assertEqual(self.cb, change)
- self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
- a.unobserve(callback1, 'a')
-
- self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
-
- def test_notify_only_once(self):
-
- class A(HasTraits):
- listen_to = ['a']
-
- a = Int(0)
- b = 0
-
- def __init__(self, **kwargs):
- super(A, self).__init__(**kwargs)
- self.observe(self.listener1, ['a'])
-
- def listener1(self, change):
- self.b += 1
-
- class B(A):
-
- c = 0
- d = 0
-
- def __init__(self, **kwargs):
- super(B, self).__init__(**kwargs)
- self.observe(self.listener2)
-
- def listener2(self, change):
- self.c += 1
-
- @observe('a')
- def _a_changed(self, change):
- self.d += 1
-
- b = B()
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
- b.a += 1
- self.assertEqual(b.b, b.c)
- self.assertEqual(b.b, b.d)
-
-
-class TestHasTraits(TestCase):
-
- def test_trait_names(self):
- class A(HasTraits):
- i = Int()
- f = Float()
- a = A()
- self.assertEqual(sorted(a.trait_names()),['f','i'])
- self.assertEqual(sorted(A.class_trait_names()),['f','i'])
- self.assertTrue(a.has_trait('f'))
- self.assertFalse(a.has_trait('g'))
-
+ def test_deprecated_metadata_access(self):
+ class MyIntTT(TraitType):
+ metadata = {'a': 1, 'b': 2}
+ a = MyIntTT(10)
+ with expected_warnings(["use the instance .metadata dictionary directly"]*2):
+ a.set_metadata('key', 'value')
+ v = a.get_metadata('key')
+ self.assertEqual(v, 'value')
+ with expected_warnings(["use the instance .help string directly"]*2):
+ a.set_metadata('help', 'some help')
+ v = a.get_metadata('help')
+ self.assertEqual(v, 'some help')
+
+ def test_trait_types_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = Int
+
+ def test_trait_types_list_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = List(Int)
+
+ def test_trait_types_tuple_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = Tuple(Int)
+
+ def test_trait_types_dict_deprecated(self):
+ with expected_warnings(["Traits should be given as instances"]):
+ class C(HasTraits):
+ t = Dict(Int)
+
+class TestHasDescriptorsMeta(TestCase):
+
+ def test_metaclass(self):
+ self.assertEqual(type(HasTraits), MetaHasTraits)
+
+ class A(HasTraits):
+ a = Int()
+
+ a = A()
+ self.assertEqual(type(a.__class__), MetaHasTraits)
+ self.assertEqual(a.a,0)
+ a.a = 10
+ self.assertEqual(a.a,10)
+
+ class B(HasTraits):
+ b = Int()
+
+ b = B()
+ self.assertEqual(b.b,0)
+ b.b = 10
+ self.assertEqual(b.b,10)
+
+ class C(HasTraits):
+ c = Int(30)
+
+ c = C()
+ self.assertEqual(c.c,30)
+ c.c = 10
+ self.assertEqual(c.c,10)
+
+ def test_this_class(self):
+ class A(HasTraits):
+ t = This()
+ tt = This()
+ class B(A):
+ tt = This()
+ ttt = This()
+ self.assertEqual(A.t.this_class, A)
+ self.assertEqual(B.t.this_class, A)
+ self.assertEqual(B.tt.this_class, B)
+ self.assertEqual(B.ttt.this_class, B)
+
+class TestHasDescriptors(TestCase):
+
+ def test_setup_instance(self):
+
+ class FooDescriptor(BaseDescriptor):
+
+ def instance_init(self, inst):
+ foo = inst.foo # instance should have the attr
+
+ class HasFooDescriptors(HasDescriptors):
+
+ fd = FooDescriptor()
+
+ def setup_instance(self, *args, **kwargs):
+ self.foo = kwargs.get('foo', None)
+ super(HasFooDescriptors, self).setup_instance(*args, **kwargs)
+
+ hfd = HasFooDescriptors(foo='bar')
+
+class TestHasTraitsNotify(TestCase):
+
+ def setUp(self):
+ self._notify1 = []
+ self._notify2 = []
+
+ def notify1(self, name, old, new):
+ self._notify1.append((name, old, new))
+
+ def notify2(self, name, old, new):
+ self._notify2.append((name, old, new))
+
+ def test_notify_all(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.on_trait_change(self.notify1)
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ self.assertTrue(('a',0,10) in self._notify1)
+ a.b = 10.0
+ self.assertTrue(('b',0.0,10.0) in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+ self.assertRaises(TraitError,setattr,a,'b','bad string')
+ self._notify1 = []
+ a.on_trait_change(self.notify1,remove=True)
+ a.a = 20
+ a.b = 20.0
+ self.assertEqual(len(self._notify1),0)
+
+ def test_notify_one(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.on_trait_change(self.notify1, 'a')
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ self.assertTrue(('a',0,10) in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+
+ def test_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ self.assertEqual(b.a,0)
+ self.assertEqual(b.b,0.0)
+ b.a = 100
+ b.b = 100.0
+ self.assertEqual(b.a,100)
+ self.assertEqual(b.b,100.0)
+
+ def test_notify_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ b.on_trait_change(self.notify1, 'a')
+ b.on_trait_change(self.notify2, 'b')
+ b.a = 0
+ b.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ self.assertEqual(len(self._notify2),0)
+ b.a = 10
+ b.b = 10.0
+ self.assertTrue(('a',0,10) in self._notify1)
+ self.assertTrue(('b',0.0,10.0) in self._notify2)
+
+ def test_static_notify(self):
+
+ class A(HasTraits):
+ a = Int()
+ _notify1 = []
+ def _a_changed(self, name, old, new):
+ self._notify1.append((name, old, new))
+
+ a = A()
+ a.a = 0
+ # This is broken!!!
+ self.assertEqual(len(a._notify1),0)
+ a.a = 10
+ self.assertTrue(('a',0,10) in a._notify1)
+
+ class B(A):
+ b = Float()
+ _notify2 = []
+ def _b_changed(self, name, old, new):
+ self._notify2.append((name, old, new))
+
+ b = B()
+ b.a = 10
+ b.b = 10.0
+ self.assertTrue(('a',0,10) in b._notify1)
+ self.assertTrue(('b',0.0,10.0) in b._notify2)
+
+ def test_notify_args(self):
+
+ def callback0():
+ self.cb = ()
+ def callback1(name):
+ self.cb = (name,)
+ def callback2(name, new):
+ self.cb = (name, new)
+ def callback3(name, old, new):
+ self.cb = (name, old, new)
+ def callback4(name, old, new, obj):
+ self.cb = (name, old, new, obj)
+
+ class A(HasTraits):
+ a = Int()
+
+ a = A()
+ a.on_trait_change(callback0, 'a')
+ a.a = 10
+ self.assertEqual(self.cb,())
+ a.on_trait_change(callback0, 'a', remove=True)
+
+ a.on_trait_change(callback1, 'a')
+ a.a = 100
+ self.assertEqual(self.cb,('a',))
+ a.on_trait_change(callback1, 'a', remove=True)
+
+ a.on_trait_change(callback2, 'a')
+ a.a = 1000
+ self.assertEqual(self.cb,('a',1000))
+ a.on_trait_change(callback2, 'a', remove=True)
+
+ a.on_trait_change(callback3, 'a')
+ a.a = 10000
+ self.assertEqual(self.cb,('a',1000,10000))
+ a.on_trait_change(callback3, 'a', remove=True)
+
+ a.on_trait_change(callback4, 'a')
+ a.a = 100000
+ self.assertEqual(self.cb,('a',10000,100000,a))
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
+ a.on_trait_change(callback4, 'a', remove=True)
+
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
+
+ def test_notify_only_once(self):
+
+ class A(HasTraits):
+ listen_to = ['a']
+
+ a = Int(0)
+ b = 0
+
+ def __init__(self, **kwargs):
+ super(A, self).__init__(**kwargs)
+ self.on_trait_change(self.listener1, ['a'])
+
+ def listener1(self, name, old, new):
+ self.b += 1
+
+ class B(A):
+
+ c = 0
+ d = 0
+
+ def __init__(self, **kwargs):
+ super(B, self).__init__(**kwargs)
+ self.on_trait_change(self.listener2)
+
+ def listener2(self, name, old, new):
+ self.c += 1
+
+ def _a_changed(self, name, old, new):
+ self.d += 1
+
+ b = B()
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+
+class TestObserveDecorator(TestCase):
+
+ def setUp(self):
+ self._notify1 = []
+ self._notify2 = []
+
+ def notify1(self, change):
+ self._notify1.append(change)
+
+ def notify2(self, change):
+ self._notify2.append(change)
+
+ def test_notify_all(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.observe(self.notify1)
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ change = change_dict('a', 0, 10, a, 'change')
+ self.assertTrue(change in self._notify1)
+ a.b = 10.0
+ change = change_dict('b', 0.0, 10.0, a, 'change')
+ self.assertTrue(change in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+ self.assertRaises(TraitError,setattr,a,'b','bad string')
+ self._notify1 = []
+ a.unobserve(self.notify1)
+ a.a = 20
+ a.b = 20.0
+ self.assertEqual(len(self._notify1),0)
+
+ def test_notify_one(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Float()
+
+ a = A()
+ a.observe(self.notify1, 'a')
+ a.a = 0
+ self.assertEqual(len(self._notify1),0)
+ a.a = 10
+ change = change_dict('a', 0, 10, a, 'change')
+ self.assertTrue(change in self._notify1)
+ self.assertRaises(TraitError,setattr,a,'a','bad string')
+
+ def test_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ self.assertEqual(b.a,0)
+ self.assertEqual(b.b,0.0)
+ b.a = 100
+ b.b = 100.0
+ self.assertEqual(b.a,100)
+ self.assertEqual(b.b,100.0)
+
+ def test_notify_subclass(self):
+
+ class A(HasTraits):
+ a = Int()
+
+ class B(A):
+ b = Float()
+
+ b = B()
+ b.observe(self.notify1, 'a')
+ b.observe(self.notify2, 'b')
+ b.a = 0
+ b.b = 0.0
+ self.assertEqual(len(self._notify1),0)
+ self.assertEqual(len(self._notify2),0)
+ b.a = 10
+ b.b = 10.0
+ change = change_dict('a', 0, 10, b, 'change')
+ self.assertTrue(change in self._notify1)
+ change = change_dict('b', 0.0, 10.0, b, 'change')
+ self.assertTrue(change in self._notify2)
+
+ def test_static_notify(self):
+
+ class A(HasTraits):
+ a = Int()
+ b = Int()
+ _notify1 = []
+ _notify_any = []
+
+ @observe('a')
+ def _a_changed(self, change):
+ self._notify1.append(change)
+
+ @observe(All)
+ def _any_changed(self, change):
+ self._notify_any.append(change)
+
+ a = A()
+ a.a = 0
+ self.assertEqual(len(a._notify1),0)
+ a.a = 10
+ change = change_dict('a', 0, 10, a, 'change')
+ self.assertTrue(change in a._notify1)
+ a.b = 1
+ self.assertEqual(len(a._notify_any), 2)
+ change = change_dict('b', 0, 1, a, 'change')
+ self.assertTrue(change in a._notify_any)
+
+ class B(A):
+ b = Float()
+ _notify2 = []
+ @observe('b')
+ def _b_changed(self, change):
+ self._notify2.append(change)
+
+ b = B()
+ b.a = 10
+ b.b = 10.0
+ change = change_dict('a', 0, 10, b, 'change')
+ self.assertTrue(change in b._notify1)
+ change = change_dict('b', 0.0, 10.0, b, 'change')
+ self.assertTrue(change in b._notify2)
+
+ def test_notify_args(self):
+
+ def callback0():
+ self.cb = ()
+ def callback1(change):
+ self.cb = change
+
+ class A(HasTraits):
+ a = Int()
+
+ a = A()
+ a.on_trait_change(callback0, 'a')
+ a.a = 10
+ self.assertEqual(self.cb,())
+ a.unobserve(callback0, 'a')
+
+ a.observe(callback1, 'a')
+ a.a = 100
+ change = change_dict('a', 10, 100, a, 'change')
+ self.assertEqual(self.cb, change)
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 1)
+ a.unobserve(callback1, 'a')
+
+ self.assertEqual(len(a._trait_notifiers['a']['change']), 0)
+
+ def test_notify_only_once(self):
+
+ class A(HasTraits):
+ listen_to = ['a']
+
+ a = Int(0)
+ b = 0
+
+ def __init__(self, **kwargs):
+ super(A, self).__init__(**kwargs)
+ self.observe(self.listener1, ['a'])
+
+ def listener1(self, change):
+ self.b += 1
+
+ class B(A):
+
+ c = 0
+ d = 0
+
+ def __init__(self, **kwargs):
+ super(B, self).__init__(**kwargs)
+ self.observe(self.listener2)
+
+ def listener2(self, change):
+ self.c += 1
+
+ @observe('a')
+ def _a_changed(self, change):
+ self.d += 1
+
+ b = B()
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+ b.a += 1
+ self.assertEqual(b.b, b.c)
+ self.assertEqual(b.b, b.d)
+
+
+class TestHasTraits(TestCase):
+
+ def test_trait_names(self):
+ class A(HasTraits):
+ i = Int()
+ f = Float()
+ a = A()
+ self.assertEqual(sorted(a.trait_names()),['f','i'])
+ self.assertEqual(sorted(A.class_trait_names()),['f','i'])
+ self.assertTrue(a.has_trait('f'))
+ self.assertFalse(a.has_trait('g'))
+
def test_trait_has_value(self):
class A(HasTraits):
i = Int()
@@ -813,438 +813,438 @@ class TestHasTraits(TestCase):
self.assertTrue(a.trait_has_value('i'))
self.assertTrue(a.trait_has_value('f'))
- def test_trait_metadata_deprecated(self):
+ def test_trait_metadata_deprecated(self):
with expected_warnings([r'metadata should be set using the \.tag\(\) method']):
- class A(HasTraits):
- i = Int(config_key='MY_VALUE')
- a = A()
- self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
-
- def test_trait_metadata(self):
- class A(HasTraits):
- i = Int().tag(config_key='MY_VALUE')
- a = A()
- self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
-
- def test_trait_metadata_default(self):
- class A(HasTraits):
- i = Int()
- a = A()
- self.assertEqual(a.trait_metadata('i', 'config_key'), None)
- self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default')
-
- def test_traits(self):
- class A(HasTraits):
- i = Int()
- f = Float()
- a = A()
- self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
- self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))
-
- def test_traits_metadata(self):
- class A(HasTraits):
- i = Int().tag(config_key='VALUE1', other_thing='VALUE2')
- f = Float().tag(config_key='VALUE3', other_thing='VALUE2')
- j = Int(0)
- a = A()
- self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
- traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
- self.assertEqual(traits, dict(i=A.i))
-
- # This passes, but it shouldn't because I am replicating a bug in
- # traits.
- traits = a.traits(config_key=lambda v: True)
- self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
-
- def test_traits_metadata_deprecated(self):
+ class A(HasTraits):
+ i = Int(config_key='MY_VALUE')
+ a = A()
+ self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
+
+ def test_trait_metadata(self):
+ class A(HasTraits):
+ i = Int().tag(config_key='MY_VALUE')
+ a = A()
+ self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
+
+ def test_trait_metadata_default(self):
+ class A(HasTraits):
+ i = Int()
+ a = A()
+ self.assertEqual(a.trait_metadata('i', 'config_key'), None)
+ self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default')
+
+ def test_traits(self):
+ class A(HasTraits):
+ i = Int()
+ f = Float()
+ a = A()
+ self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
+ self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))
+
+ def test_traits_metadata(self):
+ class A(HasTraits):
+ i = Int().tag(config_key='VALUE1', other_thing='VALUE2')
+ f = Float().tag(config_key='VALUE3', other_thing='VALUE2')
+ j = Int(0)
+ a = A()
+ self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
+ traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
+ self.assertEqual(traits, dict(i=A.i))
+
+ # This passes, but it shouldn't because I am replicating a bug in
+ # traits.
+ traits = a.traits(config_key=lambda v: True)
+ self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
+
+ def test_traits_metadata_deprecated(self):
with expected_warnings([r'metadata should be set using the \.tag\(\) method']*2):
- class A(HasTraits):
- i = Int(config_key='VALUE1', other_thing='VALUE2')
- f = Float(config_key='VALUE3', other_thing='VALUE2')
- j = Int(0)
- a = A()
- self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
- traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
- self.assertEqual(traits, dict(i=A.i))
-
- # This passes, but it shouldn't because I am replicating a bug in
- # traits.
- traits = a.traits(config_key=lambda v: True)
- self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
-
-
- def test_init(self):
- class A(HasTraits):
- i = Int()
- x = Float()
- a = A(i=1, x=10.0)
- self.assertEqual(a.i, 1)
- self.assertEqual(a.x, 10.0)
-
- def test_positional_args(self):
- class A(HasTraits):
- i = Int(0)
- def __init__(self, i):
- super(A, self).__init__()
- self.i = i
-
- a = A(5)
- self.assertEqual(a.i, 5)
- # should raise TypeError if no positional arg given
- self.assertRaises(TypeError, A)
-
-#-----------------------------------------------------------------------------
-# Tests for specific trait types
-#-----------------------------------------------------------------------------
-
-
-class TestType(TestCase):
-
- def test_default(self):
-
- class B(object): pass
- class A(HasTraits):
- klass = Type(allow_none=True)
-
- a = A()
- self.assertEqual(a.klass, object)
-
- a.klass = B
- self.assertEqual(a.klass, B)
- self.assertRaises(TraitError, setattr, a, 'klass', 10)
-
- def test_default_options(self):
-
- class B(object): pass
- class C(B): pass
- class A(HasTraits):
- # Different possible combinations of options for default_value
- # and klass. default_value=None is only valid with allow_none=True.
- k1 = Type()
- k2 = Type(None, allow_none=True)
- k3 = Type(B)
- k4 = Type(klass=B)
- k5 = Type(default_value=None, klass=B, allow_none=True)
- k6 = Type(default_value=C, klass=B)
-
- self.assertIs(A.k1.default_value, object)
- self.assertIs(A.k1.klass, object)
- self.assertIs(A.k2.default_value, None)
- self.assertIs(A.k2.klass, object)
- self.assertIs(A.k3.default_value, B)
- self.assertIs(A.k3.klass, B)
- self.assertIs(A.k4.default_value, B)
- self.assertIs(A.k4.klass, B)
- self.assertIs(A.k5.default_value, None)
- self.assertIs(A.k5.klass, B)
- self.assertIs(A.k6.default_value, C)
- self.assertIs(A.k6.klass, B)
-
- a = A()
- self.assertIs(a.k1, object)
- self.assertIs(a.k2, None)
- self.assertIs(a.k3, B)
- self.assertIs(a.k4, B)
- self.assertIs(a.k5, None)
- self.assertIs(a.k6, C)
-
- def test_value(self):
-
- class B(object): pass
- class C(object): pass
- class A(HasTraits):
- klass = Type(B)
-
- a = A()
- self.assertEqual(a.klass, B)
- self.assertRaises(TraitError, setattr, a, 'klass', C)
- self.assertRaises(TraitError, setattr, a, 'klass', object)
- a.klass = B
-
- def test_allow_none(self):
-
- class B(object): pass
- class C(B): pass
- class A(HasTraits):
- klass = Type(B)
-
- a = A()
- self.assertEqual(a.klass, B)
- self.assertRaises(TraitError, setattr, a, 'klass', None)
- a.klass = C
- self.assertEqual(a.klass, C)
-
- def test_validate_klass(self):
-
- class A(HasTraits):
- klass = Type('no strings allowed')
-
- self.assertRaises(ImportError, A)
-
- class A(HasTraits):
- klass = Type('rub.adub.Duck')
-
- self.assertRaises(ImportError, A)
-
- def test_validate_default(self):
-
- class B(object): pass
- class A(HasTraits):
- klass = Type('bad default', B)
-
- self.assertRaises(ImportError, A)
-
- class C(HasTraits):
- klass = Type(None, B)
-
+ class A(HasTraits):
+ i = Int(config_key='VALUE1', other_thing='VALUE2')
+ f = Float(config_key='VALUE3', other_thing='VALUE2')
+ j = Int(0)
+ a = A()
+ self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
+ traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
+ self.assertEqual(traits, dict(i=A.i))
+
+ # This passes, but it shouldn't because I am replicating a bug in
+ # traits.
+ traits = a.traits(config_key=lambda v: True)
+ self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
+
+
+ def test_init(self):
+ class A(HasTraits):
+ i = Int()
+ x = Float()
+ a = A(i=1, x=10.0)
+ self.assertEqual(a.i, 1)
+ self.assertEqual(a.x, 10.0)
+
+ def test_positional_args(self):
+ class A(HasTraits):
+ i = Int(0)
+ def __init__(self, i):
+ super(A, self).__init__()
+ self.i = i
+
+ a = A(5)
+ self.assertEqual(a.i, 5)
+ # should raise TypeError if no positional arg given
+ self.assertRaises(TypeError, A)
+
+#-----------------------------------------------------------------------------
+# Tests for specific trait types
+#-----------------------------------------------------------------------------
+
+
+class TestType(TestCase):
+
+ def test_default(self):
+
+ class B(object): pass
+ class A(HasTraits):
+ klass = Type(allow_none=True)
+
+ a = A()
+ self.assertEqual(a.klass, object)
+
+ a.klass = B
+ self.assertEqual(a.klass, B)
+ self.assertRaises(TraitError, setattr, a, 'klass', 10)
+
+ def test_default_options(self):
+
+ class B(object): pass
+ class C(B): pass
+ class A(HasTraits):
+ # Different possible combinations of options for default_value
+ # and klass. default_value=None is only valid with allow_none=True.
+ k1 = Type()
+ k2 = Type(None, allow_none=True)
+ k3 = Type(B)
+ k4 = Type(klass=B)
+ k5 = Type(default_value=None, klass=B, allow_none=True)
+ k6 = Type(default_value=C, klass=B)
+
+ self.assertIs(A.k1.default_value, object)
+ self.assertIs(A.k1.klass, object)
+ self.assertIs(A.k2.default_value, None)
+ self.assertIs(A.k2.klass, object)
+ self.assertIs(A.k3.default_value, B)
+ self.assertIs(A.k3.klass, B)
+ self.assertIs(A.k4.default_value, B)
+ self.assertIs(A.k4.klass, B)
+ self.assertIs(A.k5.default_value, None)
+ self.assertIs(A.k5.klass, B)
+ self.assertIs(A.k6.default_value, C)
+ self.assertIs(A.k6.klass, B)
+
+ a = A()
+ self.assertIs(a.k1, object)
+ self.assertIs(a.k2, None)
+ self.assertIs(a.k3, B)
+ self.assertIs(a.k4, B)
+ self.assertIs(a.k5, None)
+ self.assertIs(a.k6, C)
+
+ def test_value(self):
+
+ class B(object): pass
+ class C(object): pass
+ class A(HasTraits):
+ klass = Type(B)
+
+ a = A()
+ self.assertEqual(a.klass, B)
+ self.assertRaises(TraitError, setattr, a, 'klass', C)
+ self.assertRaises(TraitError, setattr, a, 'klass', object)
+ a.klass = B
+
+ def test_allow_none(self):
+
+ class B(object): pass
+ class C(B): pass
+ class A(HasTraits):
+ klass = Type(B)
+
+ a = A()
+ self.assertEqual(a.klass, B)
+ self.assertRaises(TraitError, setattr, a, 'klass', None)
+ a.klass = C
+ self.assertEqual(a.klass, C)
+
+ def test_validate_klass(self):
+
+ class A(HasTraits):
+ klass = Type('no strings allowed')
+
+ self.assertRaises(ImportError, A)
+
+ class A(HasTraits):
+ klass = Type('rub.adub.Duck')
+
+ self.assertRaises(ImportError, A)
+
+ def test_validate_default(self):
+
+ class B(object): pass
+ class A(HasTraits):
+ klass = Type('bad default', B)
+
+ self.assertRaises(ImportError, A)
+
+ class C(HasTraits):
+ klass = Type(None, B)
+
self.assertRaises(TraitError, getattr, C(), 'klass')
-
- def test_str_klass(self):
-
- class A(HasTraits):
+
+ def test_str_klass(self):
+
+ class A(HasTraits):
klass = Type("traitlets.config.Config")
-
+
from traitlets.config import Config
- a = A()
+ a = A()
a.klass = Config
self.assertEqual(a.klass, Config)
-
- self.assertRaises(TraitError, setattr, a, 'klass', 10)
-
- def test_set_str_klass(self):
-
- class A(HasTraits):
- klass = Type()
-
+
+ self.assertRaises(TraitError, setattr, a, 'klass', 10)
+
+ def test_set_str_klass(self):
+
+ class A(HasTraits):
+ klass = Type()
+
a = A(klass="traitlets.config.Config")
from traitlets.config import Config
-
+
self.assertEqual(a.klass, Config)
-class TestInstance(TestCase):
-
- def test_basic(self):
- class Foo(object): pass
- class Bar(Foo): pass
- class Bah(object): pass
-
- class A(HasTraits):
- inst = Instance(Foo, allow_none=True)
-
- a = A()
- self.assertTrue(a.inst is None)
- a.inst = Foo()
- self.assertTrue(isinstance(a.inst, Foo))
- a.inst = Bar()
- self.assertTrue(isinstance(a.inst, Foo))
- self.assertRaises(TraitError, setattr, a, 'inst', Foo)
- self.assertRaises(TraitError, setattr, a, 'inst', Bar)
- self.assertRaises(TraitError, setattr, a, 'inst', Bah())
-
- def test_default_klass(self):
- class Foo(object): pass
- class Bar(Foo): pass
- class Bah(object): pass
-
- class FooInstance(Instance):
- klass = Foo
-
- class A(HasTraits):
- inst = FooInstance(allow_none=True)
-
- a = A()
- self.assertTrue(a.inst is None)
- a.inst = Foo()
- self.assertTrue(isinstance(a.inst, Foo))
- a.inst = Bar()
- self.assertTrue(isinstance(a.inst, Foo))
- self.assertRaises(TraitError, setattr, a, 'inst', Foo)
- self.assertRaises(TraitError, setattr, a, 'inst', Bar)
- self.assertRaises(TraitError, setattr, a, 'inst', Bah())
-
- def test_unique_default_value(self):
- class Foo(object): pass
- class A(HasTraits):
- inst = Instance(Foo,(),{})
-
- a = A()
- b = A()
- self.assertTrue(a.inst is not b.inst)
-
- def test_args_kw(self):
- class Foo(object):
- def __init__(self, c): self.c = c
- class Bar(object): pass
- class Bah(object):
- def __init__(self, c, d):
- self.c = c; self.d = d
-
- class A(HasTraits):
- inst = Instance(Foo, (10,))
- a = A()
- self.assertEqual(a.inst.c, 10)
-
- class B(HasTraits):
- inst = Instance(Bah, args=(10,), kw=dict(d=20))
- b = B()
- self.assertEqual(b.inst.c, 10)
- self.assertEqual(b.inst.d, 20)
-
- class C(HasTraits):
- inst = Instance(Foo, allow_none=True)
- c = C()
- self.assertTrue(c.inst is None)
-
- def test_bad_default(self):
- class Foo(object): pass
-
- class A(HasTraits):
- inst = Instance(Foo)
-
- a = A()
- with self.assertRaises(TraitError):
- a.inst
-
- def test_instance(self):
- class Foo(object): pass
-
- def inner():
- class A(HasTraits):
- inst = Instance(Foo())
-
- self.assertRaises(TraitError, inner)
-
-
-class TestThis(TestCase):
-
- def test_this_class(self):
- class Foo(HasTraits):
- this = This()
-
- f = Foo()
- self.assertEqual(f.this, None)
- g = Foo()
- f.this = g
- self.assertEqual(f.this, g)
- self.assertRaises(TraitError, setattr, f, 'this', 10)
-
- def test_this_inst(self):
- class Foo(HasTraits):
- this = This()
-
- f = Foo()
- f.this = Foo()
- self.assertTrue(isinstance(f.this, Foo))
-
- def test_subclass(self):
- class Foo(HasTraits):
- t = This()
- class Bar(Foo):
- pass
- f = Foo()
- b = Bar()
- f.t = b
- b.t = f
- self.assertEqual(f.t, b)
- self.assertEqual(b.t, f)
-
- def test_subclass_override(self):
- class Foo(HasTraits):
- t = This()
- class Bar(Foo):
- t = This()
- f = Foo()
- b = Bar()
- f.t = b
- self.assertEqual(f.t, b)
- self.assertRaises(TraitError, setattr, b, 't', f)
-
- def test_this_in_container(self):
-
- class Tree(HasTraits):
- value = Unicode()
- leaves = List(This())
-
- tree = Tree(
- value='foo',
- leaves=[Tree(value='bar'), Tree(value='buzz')]
- )
-
- with self.assertRaises(TraitError):
- tree.leaves = [1, 2]
-
-class TraitTestBase(TestCase):
- """A best testing class for basic trait types."""
-
- def assign(self, value):
- self.obj.value = value
-
- def coerce(self, value):
- return value
-
- def test_good_values(self):
- if hasattr(self, '_good_values'):
- for value in self._good_values:
- self.assign(value)
- self.assertEqual(self.obj.value, self.coerce(value))
-
- def test_bad_values(self):
- if hasattr(self, '_bad_values'):
- for value in self._bad_values:
- try:
- self.assertRaises(TraitError, self.assign, value)
- except AssertionError:
- assert False, value
-
- def test_default_value(self):
- if hasattr(self, '_default_value'):
- self.assertEqual(self._default_value, self.obj.value)
-
- def test_allow_none(self):
- if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and
- None in self._bad_values):
- trait=self.obj.traits()['value']
- try:
- trait.allow_none = True
- self._bad_values.remove(None)
- #skip coerce. Allow None casts None to None.
- self.assign(None)
- self.assertEqual(self.obj.value,None)
- self.test_good_values()
- self.test_bad_values()
- finally:
- #tear down
- trait.allow_none = False
- self._bad_values.append(None)
-
- def tearDown(self):
- # restore default value after tests, if set
- if hasattr(self, '_default_value'):
- self.obj.value = self._default_value
-
-
-class AnyTrait(HasTraits):
-
- value = Any()
-
-class AnyTraitTest(TraitTestBase):
-
- obj = AnyTrait()
-
- _default_value = None
+class TestInstance(TestCase):
+
+ def test_basic(self):
+ class Foo(object): pass
+ class Bar(Foo): pass
+ class Bah(object): pass
+
+ class A(HasTraits):
+ inst = Instance(Foo, allow_none=True)
+
+ a = A()
+ self.assertTrue(a.inst is None)
+ a.inst = Foo()
+ self.assertTrue(isinstance(a.inst, Foo))
+ a.inst = Bar()
+ self.assertTrue(isinstance(a.inst, Foo))
+ self.assertRaises(TraitError, setattr, a, 'inst', Foo)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bar)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bah())
+
+ def test_default_klass(self):
+ class Foo(object): pass
+ class Bar(Foo): pass
+ class Bah(object): pass
+
+ class FooInstance(Instance):
+ klass = Foo
+
+ class A(HasTraits):
+ inst = FooInstance(allow_none=True)
+
+ a = A()
+ self.assertTrue(a.inst is None)
+ a.inst = Foo()
+ self.assertTrue(isinstance(a.inst, Foo))
+ a.inst = Bar()
+ self.assertTrue(isinstance(a.inst, Foo))
+ self.assertRaises(TraitError, setattr, a, 'inst', Foo)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bar)
+ self.assertRaises(TraitError, setattr, a, 'inst', Bah())
+
+ def test_unique_default_value(self):
+ class Foo(object): pass
+ class A(HasTraits):
+ inst = Instance(Foo,(),{})
+
+ a = A()
+ b = A()
+ self.assertTrue(a.inst is not b.inst)
+
+ def test_args_kw(self):
+ class Foo(object):
+ def __init__(self, c): self.c = c
+ class Bar(object): pass
+ class Bah(object):
+ def __init__(self, c, d):
+ self.c = c; self.d = d
+
+ class A(HasTraits):
+ inst = Instance(Foo, (10,))
+ a = A()
+ self.assertEqual(a.inst.c, 10)
+
+ class B(HasTraits):
+ inst = Instance(Bah, args=(10,), kw=dict(d=20))
+ b = B()
+ self.assertEqual(b.inst.c, 10)
+ self.assertEqual(b.inst.d, 20)
+
+ class C(HasTraits):
+ inst = Instance(Foo, allow_none=True)
+ c = C()
+ self.assertTrue(c.inst is None)
+
+ def test_bad_default(self):
+ class Foo(object): pass
+
+ class A(HasTraits):
+ inst = Instance(Foo)
+
+ a = A()
+ with self.assertRaises(TraitError):
+ a.inst
+
+ def test_instance(self):
+ class Foo(object): pass
+
+ def inner():
+ class A(HasTraits):
+ inst = Instance(Foo())
+
+ self.assertRaises(TraitError, inner)
+
+
+class TestThis(TestCase):
+
+ def test_this_class(self):
+ class Foo(HasTraits):
+ this = This()
+
+ f = Foo()
+ self.assertEqual(f.this, None)
+ g = Foo()
+ f.this = g
+ self.assertEqual(f.this, g)
+ self.assertRaises(TraitError, setattr, f, 'this', 10)
+
+ def test_this_inst(self):
+ class Foo(HasTraits):
+ this = This()
+
+ f = Foo()
+ f.this = Foo()
+ self.assertTrue(isinstance(f.this, Foo))
+
+ def test_subclass(self):
+ class Foo(HasTraits):
+ t = This()
+ class Bar(Foo):
+ pass
+ f = Foo()
+ b = Bar()
+ f.t = b
+ b.t = f
+ self.assertEqual(f.t, b)
+ self.assertEqual(b.t, f)
+
+ def test_subclass_override(self):
+ class Foo(HasTraits):
+ t = This()
+ class Bar(Foo):
+ t = This()
+ f = Foo()
+ b = Bar()
+ f.t = b
+ self.assertEqual(f.t, b)
+ self.assertRaises(TraitError, setattr, b, 't', f)
+
+ def test_this_in_container(self):
+
+ class Tree(HasTraits):
+ value = Unicode()
+ leaves = List(This())
+
+ tree = Tree(
+ value='foo',
+ leaves=[Tree(value='bar'), Tree(value='buzz')]
+ )
+
+ with self.assertRaises(TraitError):
+ tree.leaves = [1, 2]
+
+class TraitTestBase(TestCase):
+ """A best testing class for basic trait types."""
+
+ def assign(self, value):
+ self.obj.value = value
+
+ def coerce(self, value):
+ return value
+
+ def test_good_values(self):
+ if hasattr(self, '_good_values'):
+ for value in self._good_values:
+ self.assign(value)
+ self.assertEqual(self.obj.value, self.coerce(value))
+
+ def test_bad_values(self):
+ if hasattr(self, '_bad_values'):
+ for value in self._bad_values:
+ try:
+ self.assertRaises(TraitError, self.assign, value)
+ except AssertionError:
+ assert False, value
+
+ def test_default_value(self):
+ if hasattr(self, '_default_value'):
+ self.assertEqual(self._default_value, self.obj.value)
+
+ def test_allow_none(self):
+ if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and
+ None in self._bad_values):
+ trait=self.obj.traits()['value']
+ try:
+ trait.allow_none = True
+ self._bad_values.remove(None)
+ #skip coerce. Allow None casts None to None.
+ self.assign(None)
+ self.assertEqual(self.obj.value,None)
+ self.test_good_values()
+ self.test_bad_values()
+ finally:
+ #tear down
+ trait.allow_none = False
+ self._bad_values.append(None)
+
+ def tearDown(self):
+ # restore default value after tests, if set
+ if hasattr(self, '_default_value'):
+ self.obj.value = self._default_value
+
+
+class AnyTrait(HasTraits):
+
+ value = Any()
+
+class AnyTraitTest(TraitTestBase):
+
+ obj = AnyTrait()
+
+ _default_value = None
_good_values = [10.0, 'ten', [10], {'ten': 10},(10,), None, 1j]
- _bad_values = []
-
-class UnionTrait(HasTraits):
-
- value = Union([Type(), Bool()])
-
-class UnionTraitTest(TraitTestBase):
-
+ _bad_values = []
+
+class UnionTrait(HasTraits):
+
+ value = Union([Type(), Bool()])
+
+class UnionTraitTest(TraitTestBase):
+
obj = UnionTrait(value="traitlets.config.Config")
- _good_values = [int, float, True]
- _bad_values = [[], (0,), 1j]
-
+ _good_values = [int, float, True]
+ _bad_values = [[], (0,), 1j]
+
class CallableTrait(HasTraits):
value = Callable()
@@ -1255,407 +1255,407 @@ class CallableTraitTest(TraitTestBase):
_good_values = [int, sorted, lambda x: print(x)]
_bad_values = [[], 1, '']
-class OrTrait(HasTraits):
-
- value = Bool() | Unicode()
-
-class OrTraitTest(TraitTestBase):
-
- obj = OrTrait()
- _good_values = [True, False, 'ten']
- _bad_values = [[], (0,), 1j]
-
-class IntTrait(HasTraits):
-
- value = Int(99, min=-100)
-
-class TestInt(TraitTestBase):
-
- obj = IntTrait()
- _default_value = 99
- _good_values = [10, -10]
+class OrTrait(HasTraits):
+
+ value = Bool() | Unicode()
+
+class OrTraitTest(TraitTestBase):
+
+ obj = OrTrait()
+ _good_values = [True, False, 'ten']
+ _bad_values = [[], (0,), 1j]
+
+class IntTrait(HasTraits):
+
+ value = Int(99, min=-100)
+
+class TestInt(TraitTestBase):
+
+ obj = IntTrait()
+ _default_value = 99
+ _good_values = [10, -10]
_bad_values = ['ten', [10], {'ten': 10}, (10,), None, 1j,
10.1, -10.1, '10L', '-10L', '10.1', '-10.1',
'10', '-10', -200]
-
-
-class CIntTrait(HasTraits):
- value = CInt('5')
-
-class TestCInt(TraitTestBase):
- obj = CIntTrait()
-
- _default_value = 5
+
+
+class CIntTrait(HasTraits):
+ value = CInt('5')
+
+class TestCInt(TraitTestBase):
+ obj = CIntTrait()
+
+ _default_value = 5
_good_values = ['10', '-10', 10, 10.0, -10.0, 10.1]
_bad_values = ['ten', [10], {'ten': 10},(10,),
None, 1j, '10.1']
-
- def coerce(self, n):
- return int(n)
-
-
-class MinBoundCIntTrait(HasTraits):
- value = CInt('5', min=3)
-
-class TestMinBoundCInt(TestCInt):
- obj = MinBoundCIntTrait()
-
- _default_value = 5
- _good_values = [3, 3.0, '3']
- _bad_values = [2.6, 2, -3, -3.0]
-
-
-class LongTrait(HasTraits):
-
+
+ def coerce(self, n):
+ return int(n)
+
+
+class MinBoundCIntTrait(HasTraits):
+ value = CInt('5', min=3)
+
+class TestMinBoundCInt(TestCInt):
+ obj = MinBoundCIntTrait()
+
+ _default_value = 5
+ _good_values = [3, 3.0, '3']
+ _bad_values = [2.6, 2, -3, -3.0]
+
+
+class LongTrait(HasTraits):
+
value = Long(99)
-
-class TestLong(TraitTestBase):
-
- obj = LongTrait()
-
+
+class TestLong(TraitTestBase):
+
+ obj = LongTrait()
+
_default_value = 99
- _good_values = [10, -10]
+ _good_values = [10, -10]
_bad_values = ['ten', [10], {'ten': 10},(10,),
- None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
+ None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
'-10.1']
-
-
-class MinBoundLongTrait(HasTraits):
+
+
+class MinBoundLongTrait(HasTraits):
value = Long(99, min=5)
-
-class TestMinBoundLong(TraitTestBase):
- obj = MinBoundLongTrait()
-
+
+class TestMinBoundLong(TraitTestBase):
+ obj = MinBoundLongTrait()
+
_default_value = 99
- _good_values = [5, 10]
- _bad_values = [4, -10]
-
-
-class MaxBoundLongTrait(HasTraits):
+ _good_values = [5, 10]
+ _bad_values = [4, -10]
+
+
+class MaxBoundLongTrait(HasTraits):
value = Long(5, max=10)
-
-class TestMaxBoundLong(TraitTestBase):
- obj = MaxBoundLongTrait()
-
+
+class TestMaxBoundLong(TraitTestBase):
+ obj = MaxBoundLongTrait()
+
_default_value = 5
- _good_values = [10, -2]
- _bad_values = [11, 20]
-
-
-class CLongTrait(HasTraits):
- value = CLong('5')
-
-class TestCLong(TraitTestBase):
- obj = CLongTrait()
-
+ _good_values = [10, -2]
+ _bad_values = [11, 20]
+
+
+class CLongTrait(HasTraits):
+ value = CLong('5')
+
+class TestCLong(TraitTestBase):
+ obj = CLongTrait()
+
_default_value = 5
_good_values = ['10', '-10', 10, 10.0, -10.0, 10.1]
_bad_values = ['ten', [10], {'ten': 10},(10,),
None, 1j, '10.1']
-
- def coerce(self, n):
+
+ def coerce(self, n):
return int(n)
-
-
-class MaxBoundCLongTrait(HasTraits):
- value = CLong('5', max=10)
-
-class TestMaxBoundCLong(TestCLong):
- obj = MaxBoundCLongTrait()
-
- _default_value = 5
- _good_values = [10, '10', 10.3]
- _bad_values = [11.0, '11']
-
-
-class IntegerTrait(HasTraits):
- value = Integer(1)
-
-class TestInteger(TestLong):
- obj = IntegerTrait()
- _default_value = 1
-
- def coerce(self, n):
- return int(n)
-
-
-class MinBoundIntegerTrait(HasTraits):
- value = Integer(5, min=3)
-
-class TestMinBoundInteger(TraitTestBase):
- obj = MinBoundIntegerTrait()
-
+
+
+class MaxBoundCLongTrait(HasTraits):
+ value = CLong('5', max=10)
+
+class TestMaxBoundCLong(TestCLong):
+ obj = MaxBoundCLongTrait()
+
_default_value = 5
- _good_values = 3, 20
- _bad_values = [2, -10]
-
-
-class MaxBoundIntegerTrait(HasTraits):
- value = Integer(1, max=3)
-
-class TestMaxBoundInteger(TraitTestBase):
- obj = MaxBoundIntegerTrait()
-
- _default_value = 1
- _good_values = 3, -2
- _bad_values = [4, 10]
-
-
-class FloatTrait(HasTraits):
-
- value = Float(99.0, max=200.0)
-
-class TestFloat(TraitTestBase):
-
- obj = FloatTrait()
-
- _default_value = 99.0
- _good_values = [10, -10, 10.1, -10.1]
+ _good_values = [10, '10', 10.3]
+ _bad_values = [11.0, '11']
+
+
+class IntegerTrait(HasTraits):
+ value = Integer(1)
+
+class TestInteger(TestLong):
+ obj = IntegerTrait()
+ _default_value = 1
+
+ def coerce(self, n):
+ return int(n)
+
+
+class MinBoundIntegerTrait(HasTraits):
+ value = Integer(5, min=3)
+
+class TestMinBoundInteger(TraitTestBase):
+ obj = MinBoundIntegerTrait()
+
+ _default_value = 5
+ _good_values = 3, 20
+ _bad_values = [2, -10]
+
+
+class MaxBoundIntegerTrait(HasTraits):
+ value = Integer(1, max=3)
+
+class TestMaxBoundInteger(TraitTestBase):
+ obj = MaxBoundIntegerTrait()
+
+ _default_value = 1
+ _good_values = 3, -2
+ _bad_values = [4, 10]
+
+
+class FloatTrait(HasTraits):
+
+ value = Float(99.0, max=200.0)
+
+class TestFloat(TraitTestBase):
+
+ obj = FloatTrait()
+
+ _default_value = 99.0
+ _good_values = [10, -10, 10.1, -10.1]
_bad_values = ['ten', [10], {'ten': 10}, (10,), None,
1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', 201.0]
-
-
-class CFloatTrait(HasTraits):
-
- value = CFloat('99.0', max=200.0)
-
-class TestCFloat(TraitTestBase):
-
- obj = CFloatTrait()
-
- _default_value = 99.0
+
+
+class CFloatTrait(HasTraits):
+
+ value = CFloat('99.0', max=200.0)
+
+class TestCFloat(TraitTestBase):
+
+ obj = CFloatTrait()
+
+ _default_value = 99.0
_good_values = [10, 10.0, 10.5, '10.0', '10', '-10']
_bad_values = ['ten', [10], {'ten': 10}, (10,), None, 1j,
- 200.1, '200.1']
-
- def coerce(self, v):
- return float(v)
-
-
-class ComplexTrait(HasTraits):
-
- value = Complex(99.0-99.0j)
-
-class TestComplex(TraitTestBase):
-
- obj = ComplexTrait()
-
- _default_value = 99.0-99.0j
- _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
- 10.1j, 10.1+10.1j, 10.1-10.1j]
+ 200.1, '200.1']
+
+ def coerce(self, v):
+ return float(v)
+
+
+class ComplexTrait(HasTraits):
+
+ value = Complex(99.0-99.0j)
+
+class TestComplex(TraitTestBase):
+
+ obj = ComplexTrait()
+
+ _default_value = 99.0-99.0j
+ _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
+ 10.1j, 10.1+10.1j, 10.1-10.1j]
_bad_values = ['10L', '-10L', 'ten', [10], {'ten': 10},(10,), None]
-
-
-class BytesTrait(HasTraits):
-
- value = Bytes(b'string')
-
-class TestBytes(TraitTestBase):
-
- obj = BytesTrait()
-
- _default_value = b'string'
- _good_values = [b'10', b'-10', b'10L',
- b'-10L', b'10.1', b'-10.1', b'string']
- _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
+
+
+class BytesTrait(HasTraits):
+
+ value = Bytes(b'string')
+
+class TestBytes(TraitTestBase):
+
+ obj = BytesTrait()
+
+ _default_value = b'string'
+ _good_values = [b'10', b'-10', b'10L',
+ b'-10L', b'10.1', b'-10.1', b'string']
+ _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
['ten'],{'ten': 10},(10,), None, 'string']
-
-
-class UnicodeTrait(HasTraits):
-
+
+
+class UnicodeTrait(HasTraits):
+
value = Unicode('unicode')
+
-
-class TestUnicode(TraitTestBase):
-
- obj = UnicodeTrait()
-
+class TestUnicode(TraitTestBase):
+
+ obj = UnicodeTrait()
+
_default_value = 'unicode'
- _good_values = ['10', '-10', '10L', '-10L', '10.1',
+ _good_values = ['10', '-10', '10L', '-10L', '10.1',
'-10.1', '', 'string', "€", b"bytestring"]
- _bad_values = [10, -10, 10.1, -10.1, 1j,
+ _bad_values = [10, -10, 10.1, -10.1, 1j,
[10], ['ten'], {'ten': 10},(10,), None]
-
+
def coerce(self, v):
return cast_unicode(v)
-
-
-class ObjectNameTrait(HasTraits):
- value = ObjectName("abc")
-
-class TestObjectName(TraitTestBase):
- obj = ObjectNameTrait()
-
- _default_value = "abc"
+
+
+class ObjectNameTrait(HasTraits):
+ value = ObjectName("abc")
+
+class TestObjectName(TraitTestBase):
+ obj = ObjectNameTrait()
+
+ _default_value = "abc"
_good_values = ["a", "gh", "g9", "g_", "_G", "a345_"]
_bad_values = [1, "", "€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
- None, object(), object]
+ None, object(), object]
_good_values.append("þ") # þ=1 is valid in Python 3 (PEP 3131).
-
-
-class DottedObjectNameTrait(HasTraits):
- value = DottedObjectName("a.b")
-
-class TestDottedObjectName(TraitTestBase):
- obj = DottedObjectNameTrait()
-
- _default_value = "a.b"
+
+
+class DottedObjectNameTrait(HasTraits):
+ value = DottedObjectName("a.b")
+
+class TestDottedObjectName(TraitTestBase):
+ obj = DottedObjectNameTrait()
+
+ _default_value = "a.b"
_good_values = ["A", "y.t", "y765.__repr__", "os.path.join"]
_bad_values = [1, "abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]
-
+
_good_values.append("t.þ")
-
-
-class TCPAddressTrait(HasTraits):
- value = TCPAddress()
-
-class TestTCPAddress(TraitTestBase):
-
- obj = TCPAddressTrait()
-
- _default_value = ('127.0.0.1',0)
- _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
- _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]
-
-
-class ListTrait(HasTraits):
-
- value = List(Int())
-
-
-class TestList(TraitTestBase):
-
- obj = ListTrait()
-
- _default_value = []
- _good_values = [[], [1], list(range(10)), (1,2)]
- _bad_values = [10, [1,'a'], 'a']
-
- def coerce(self, value):
- if value is not None:
- value = list(value)
- return value
-
-
-class Foo(object):
- pass
-
-class NoneInstanceListTrait(HasTraits):
-
- value = List(Instance(Foo))
-
-class TestNoneInstanceList(TraitTestBase):
-
- obj = NoneInstanceListTrait()
-
- _default_value = []
- _good_values = [[Foo(), Foo()], []]
- _bad_values = [[None], [Foo(), None]]
-
-
-class InstanceListTrait(HasTraits):
-
- value = List(Instance(__name__+'.Foo'))
-
-class TestInstanceList(TraitTestBase):
-
- obj = InstanceListTrait()
-
- def test_klass(self):
- """Test that the instance klass is properly assigned."""
- self.assertIs(self.obj.traits()['value']._trait.klass, Foo)
-
- _default_value = []
- _good_values = [[Foo(), Foo()], []]
- _bad_values = [['1', 2,], '1', [Foo], None]
-
-class UnionListTrait(HasTraits):
-
- value = List(Int() | Bool())
-
+
+
+class TCPAddressTrait(HasTraits):
+ value = TCPAddress()
+
+class TestTCPAddress(TraitTestBase):
+
+ obj = TCPAddressTrait()
+
+ _default_value = ('127.0.0.1',0)
+ _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
+ _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]
+
+
+class ListTrait(HasTraits):
+
+ value = List(Int())
+
+
+class TestList(TraitTestBase):
+
+ obj = ListTrait()
+
+ _default_value = []
+ _good_values = [[], [1], list(range(10)), (1,2)]
+ _bad_values = [10, [1,'a'], 'a']
+
+ def coerce(self, value):
+ if value is not None:
+ value = list(value)
+ return value
+
+
+class Foo(object):
+ pass
+
+class NoneInstanceListTrait(HasTraits):
+
+ value = List(Instance(Foo))
+
+class TestNoneInstanceList(TraitTestBase):
+
+ obj = NoneInstanceListTrait()
+
+ _default_value = []
+ _good_values = [[Foo(), Foo()], []]
+ _bad_values = [[None], [Foo(), None]]
+
+
+class InstanceListTrait(HasTraits):
+
+ value = List(Instance(__name__+'.Foo'))
+
+class TestInstanceList(TraitTestBase):
+
+ obj = InstanceListTrait()
+
+ def test_klass(self):
+ """Test that the instance klass is properly assigned."""
+ self.assertIs(self.obj.traits()['value']._trait.klass, Foo)
+
+ _default_value = []
+ _good_values = [[Foo(), Foo()], []]
+ _bad_values = [['1', 2,], '1', [Foo], None]
+
+class UnionListTrait(HasTraits):
+
+ value = List(Int() | Bool())
+
class TestUnionListTrait(TraitTestBase):
-
- obj = UnionListTrait()
-
- _default_value = []
- _good_values = [[True, 1], [False, True]]
- _bad_values = [[1, 'True'], False]
-
-
-class LenListTrait(HasTraits):
-
- value = List(Int(), [0], minlen=1, maxlen=2)
-
-class TestLenList(TraitTestBase):
-
- obj = LenListTrait()
-
- _default_value = [0]
- _good_values = [[1], [1,2], (1,2)]
- _bad_values = [10, [1,'a'], 'a', [], list(range(3))]
-
- def coerce(self, value):
- if value is not None:
- value = list(value)
- return value
-
-class TupleTrait(HasTraits):
-
- value = Tuple(Int(allow_none=True), default_value=(1,))
-
-class TestTupleTrait(TraitTestBase):
-
- obj = TupleTrait()
-
+
+ obj = UnionListTrait()
+
+ _default_value = []
+ _good_values = [[True, 1], [False, True]]
+ _bad_values = [[1, 'True'], False]
+
+
+class LenListTrait(HasTraits):
+
+ value = List(Int(), [0], minlen=1, maxlen=2)
+
+class TestLenList(TraitTestBase):
+
+ obj = LenListTrait()
+
+ _default_value = [0]
+ _good_values = [[1], [1,2], (1,2)]
+ _bad_values = [10, [1,'a'], 'a', [], list(range(3))]
+
+ def coerce(self, value):
+ if value is not None:
+ value = list(value)
+ return value
+
+class TupleTrait(HasTraits):
+
+ value = Tuple(Int(allow_none=True), default_value=(1,))
+
+class TestTupleTrait(TraitTestBase):
+
+ obj = TupleTrait()
+
_default_value = (1,)
- _good_values = [(1,), (0,), [1]]
- _bad_values = [10, (1, 2), ('a'), (), None]
-
- def coerce(self, value):
- if value is not None:
- value = tuple(value)
- return value
-
- def test_invalid_args(self):
- self.assertRaises(TypeError, Tuple, 5)
- self.assertRaises(TypeError, Tuple, default_value='hello')
- t = Tuple(Int(), CBytes(), default_value=(1,5))
-
-class LooseTupleTrait(HasTraits):
-
- value = Tuple((1,2,3))
-
-class TestLooseTupleTrait(TraitTestBase):
-
- obj = LooseTupleTrait()
-
- _default_value = (1,2,3)
- _good_values = [(1,), [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
- _bad_values = [10, 'hello', {}, None]
-
- def coerce(self, value):
- if value is not None:
- value = tuple(value)
- return value
-
- def test_invalid_args(self):
- self.assertRaises(TypeError, Tuple, 5)
- self.assertRaises(TypeError, Tuple, default_value='hello')
- t = Tuple(Int(), CBytes(), default_value=(1,5))
-
-
-class MultiTupleTrait(HasTraits):
-
- value = Tuple(Int(), Bytes(), default_value=[99,b'bottles'])
-
-class TestMultiTuple(TraitTestBase):
-
- obj = MultiTupleTrait()
-
- _default_value = (99,b'bottles')
- _good_values = [(1,b'a'), (2,b'b')]
+ _good_values = [(1,), (0,), [1]]
+ _bad_values = [10, (1, 2), ('a'), (), None]
+
+ def coerce(self, value):
+ if value is not None:
+ value = tuple(value)
+ return value
+
+ def test_invalid_args(self):
+ self.assertRaises(TypeError, Tuple, 5)
+ self.assertRaises(TypeError, Tuple, default_value='hello')
+ t = Tuple(Int(), CBytes(), default_value=(1,5))
+
+class LooseTupleTrait(HasTraits):
+
+ value = Tuple((1,2,3))
+
+class TestLooseTupleTrait(TraitTestBase):
+
+ obj = LooseTupleTrait()
+
+ _default_value = (1,2,3)
+ _good_values = [(1,), [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
+ _bad_values = [10, 'hello', {}, None]
+
+ def coerce(self, value):
+ if value is not None:
+ value = tuple(value)
+ return value
+
+ def test_invalid_args(self):
+ self.assertRaises(TypeError, Tuple, 5)
+ self.assertRaises(TypeError, Tuple, default_value='hello')
+ t = Tuple(Int(), CBytes(), default_value=(1,5))
+
+
+class MultiTupleTrait(HasTraits):
+
+ value = Tuple(Int(), Bytes(), default_value=[99,b'bottles'])
+
+class TestMultiTuple(TraitTestBase):
+
+ obj = MultiTupleTrait()
+
+ _default_value = (99,b'bottles')
+ _good_values = [(1,b'a'), (2,b'b')]
_bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, 'a'))
-
+
@pytest.mark.parametrize(
"Trait", (List, Tuple, Set, Dict, Integer, Unicode,),
@@ -1707,64 +1707,64 @@ def test_subclass_default_value(Trait, default_value):
assert c.t == default_value
-class CRegExpTrait(HasTraits):
-
- value = CRegExp(r'')
-
-
-class TestCRegExp(TraitTestBase):
-
- def coerce(self, value):
- return re.compile(value)
-
- obj = CRegExpTrait()
-
- _default_value = re.compile(r'')
- _good_values = [r'\d+', re.compile(r'\d+')]
- _bad_values = ['(', None, ()]
-
-class DictTrait(HasTraits):
- value = Dict()
-
-def test_dict_assignment():
- d = dict()
- c = DictTrait()
- c.value = d
- d['a'] = 5
+class CRegExpTrait(HasTraits):
+
+ value = CRegExp(r'')
+
+
+class TestCRegExp(TraitTestBase):
+
+ def coerce(self, value):
+ return re.compile(value)
+
+ obj = CRegExpTrait()
+
+ _default_value = re.compile(r'')
+ _good_values = [r'\d+', re.compile(r'\d+')]
+ _bad_values = ['(', None, ()]
+
+class DictTrait(HasTraits):
+ value = Dict()
+
+def test_dict_assignment():
+ d = dict()
+ c = DictTrait()
+ c.value = d
+ d['a'] = 5
assert d == c.value
- assert c.value is d
-
-
+ assert c.value is d
+
+
class UniformlyValueValidatedDictTrait(HasTraits):
-
- value = Dict(trait=Unicode(),
- default_value={'foo': '1'})
-
-
+
+ value = Dict(trait=Unicode(),
+ default_value={'foo': '1'})
+
+
class TestInstanceUniformlyValueValidatedDict(TraitTestBase):
-
+
obj = UniformlyValueValidatedDictTrait()
-
- _default_value = {'foo': '1'}
- _good_values = [{'foo': '0', 'bar': '1'}]
- _bad_values = [{'foo': 0, 'bar': '1'}]
-
-
+
+ _default_value = {'foo': '1'}
+ _good_values = [{'foo': '0', 'bar': '1'}]
+ _bad_values = [{'foo': 0, 'bar': '1'}]
+
+
class NonuniformlyValueValidatedDictTrait(HasTraits):
-
- value = Dict(traits={'foo': Int()},
- default_value={'foo': 1})
-
-
+
+ value = Dict(traits={'foo': Int()},
+ default_value={'foo': 1})
+
+
class TestInstanceNonuniformlyValueValidatedDict(TraitTestBase):
-
+
obj = NonuniformlyValueValidatedDictTrait()
-
- _default_value = {'foo': 1}
- _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 0, 'bar': 1}]
- _bad_values = [{'foo': '0', 'bar': '1'}]
-
-
+
+ _default_value = {'foo': 1}
+ _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 0, 'bar': 1}]
+ _bad_values = [{'foo': '0', 'bar': '1'}]
+
+
class KeyValidatedDictTrait(HasTraits):
value = Dict(key_trait=Unicode(),
@@ -1780,196 +1780,196 @@ class TestInstanceKeyValidatedDict(TraitTestBase):
_bad_values = [{'foo': '0', 0: '1'}]
-class FullyValidatedDictTrait(HasTraits):
-
- value = Dict(trait=Unicode(),
+class FullyValidatedDictTrait(HasTraits):
+
+ value = Dict(trait=Unicode(),
key_trait=Unicode(),
- traits={'foo': Int()},
- default_value={'foo': 1})
-
-
-class TestInstanceFullyValidatedDict(TraitTestBase):
-
- obj = FullyValidatedDictTrait()
-
- _default_value = {'foo': 1}
- _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 1, 'bar': '2'}]
+ traits={'foo': Int()},
+ default_value={'foo': 1})
+
+
+class TestInstanceFullyValidatedDict(TraitTestBase):
+
+ obj = FullyValidatedDictTrait()
+
+ _default_value = {'foo': 1}
+ _good_values = [{'foo': 0, 'bar': '1'}, {'foo': 1, 'bar': '2'}]
_bad_values = [{'foo': 0, 'bar': 1}, {'foo': '0', 'bar': '1'}, {'foo': 0, 0: '1'}]
-
-
-def test_dict_default_value():
- """Check that the `{}` default value of the Dict traitlet constructor is
- actually copied."""
-
- class Foo(HasTraits):
- d1 = Dict()
- d2 = Dict()
-
- foo = Foo()
- assert foo.d1 == {}
- assert foo.d2 == {}
- assert foo.d1 is not foo.d2
-
-
-class TestValidationHook(TestCase):
-
- def test_parity_trait(self):
- """Verify that the early validation hook is effective"""
-
- class Parity(HasTraits):
-
- value = Int(0)
- parity = Enum(['odd', 'even'], default_value='even')
-
- @validate('value')
- def _value_validate(self, proposal):
- value = proposal['value']
- if self.parity == 'even' and value % 2:
- raise TraitError('Expected an even number')
- if self.parity == 'odd' and (value % 2 == 0):
- raise TraitError('Expected an odd number')
- return value
-
- u = Parity()
- u.parity = 'odd'
- u.value = 1 # OK
- with self.assertRaises(TraitError):
- u.value = 2 # Trait Error
-
- u.parity = 'even'
- u.value = 2 # OK
-
- def test_multiple_validate(self):
- """Verify that we can register the same validator to multiple names"""
-
- class OddEven(HasTraits):
-
- odd = Int(1)
- even = Int(0)
-
- @validate('odd', 'even')
- def check_valid(self, proposal):
- if proposal['trait'].name == 'odd' and not proposal['value'] % 2:
- raise TraitError('odd should be odd')
- if proposal['trait'].name == 'even' and proposal['value'] % 2:
- raise TraitError('even should be even')
-
- u = OddEven()
- u.odd = 3 # OK
- with self.assertRaises(TraitError):
- u.odd = 2 # Trait Error
-
- u.even = 2 # OK
- with self.assertRaises(TraitError):
- u.even = 3 # Trait Error
-
-
-
-class TestLink(TestCase):
-
- def test_connect_same(self):
- """Verify two traitlets of the same type can be linked together using link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Conenct the two classes.
- c = link((a, 'value'), (b, 'value'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.value)
-
- # Change one of the values to make sure they stay in sync.
- a.value = 5
- self.assertEqual(a.value, b.value)
- b.value = 6
- self.assertEqual(a.value, b.value)
-
- def test_link_different(self):
- """Verify two traitlets of different types can be linked together using link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- class B(HasTraits):
- count = Int()
- a = A(value=9)
- b = B(count=8)
-
- # Conenct the two classes.
- c = link((a, 'value'), (b, 'count'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.count)
-
- # Change one of the values to make sure they stay in sync.
- a.value = 5
- self.assertEqual(a.value, b.count)
- b.count = 4
- self.assertEqual(a.value, b.count)
-
+
+
+def test_dict_default_value():
+ """Check that the `{}` default value of the Dict traitlet constructor is
+ actually copied."""
+
+ class Foo(HasTraits):
+ d1 = Dict()
+ d2 = Dict()
+
+ foo = Foo()
+ assert foo.d1 == {}
+ assert foo.d2 == {}
+ assert foo.d1 is not foo.d2
+
+
+class TestValidationHook(TestCase):
+
+ def test_parity_trait(self):
+ """Verify that the early validation hook is effective"""
+
+ class Parity(HasTraits):
+
+ value = Int(0)
+ parity = Enum(['odd', 'even'], default_value='even')
+
+ @validate('value')
+ def _value_validate(self, proposal):
+ value = proposal['value']
+ if self.parity == 'even' and value % 2:
+ raise TraitError('Expected an even number')
+ if self.parity == 'odd' and (value % 2 == 0):
+ raise TraitError('Expected an odd number')
+ return value
+
+ u = Parity()
+ u.parity = 'odd'
+ u.value = 1 # OK
+ with self.assertRaises(TraitError):
+ u.value = 2 # Trait Error
+
+ u.parity = 'even'
+ u.value = 2 # OK
+
+ def test_multiple_validate(self):
+ """Verify that we can register the same validator to multiple names"""
+
+ class OddEven(HasTraits):
+
+ odd = Int(1)
+ even = Int(0)
+
+ @validate('odd', 'even')
+ def check_valid(self, proposal):
+ if proposal['trait'].name == 'odd' and not proposal['value'] % 2:
+ raise TraitError('odd should be odd')
+ if proposal['trait'].name == 'even' and proposal['value'] % 2:
+ raise TraitError('even should be even')
+
+ u = OddEven()
+ u.odd = 3 # OK
+ with self.assertRaises(TraitError):
+ u.odd = 2 # Trait Error
+
+ u.even = 2 # OK
+ with self.assertRaises(TraitError):
+ u.even = 3 # Trait Error
+
+
+
+class TestLink(TestCase):
+
+ def test_connect_same(self):
+ """Verify two traitlets of the same type can be linked together using link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Conenct the two classes.
+ c = link((a, 'value'), (b, 'value'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.value)
+
+ # Change one of the values to make sure they stay in sync.
+ a.value = 5
+ self.assertEqual(a.value, b.value)
+ b.value = 6
+ self.assertEqual(a.value, b.value)
+
+ def test_link_different(self):
+ """Verify two traitlets of different types can be linked together using link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ class B(HasTraits):
+ count = Int()
+ a = A(value=9)
+ b = B(count=8)
+
+ # Conenct the two classes.
+ c = link((a, 'value'), (b, 'count'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.count)
+
+ # Change one of the values to make sure they stay in sync.
+ a.value = 5
+ self.assertEqual(a.value, b.count)
+ b.count = 4
+ self.assertEqual(a.value, b.count)
+
def test_unlink_link(self):
"""Verify two linked traitlets can be unlinked and relinked."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Connect the two classes.
- c = link((a, 'value'), (b, 'value'))
- a.value = 4
- c.unlink()
-
- # Change one of the values to make sure they don't stay in sync.
- a.value = 5
- self.assertNotEqual(a.value, b.value)
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Connect the two classes.
+ c = link((a, 'value'), (b, 'value'))
+ a.value = 4
+ c.unlink()
+
+ # Change one of the values to make sure they don't stay in sync.
+ a.value = 5
+ self.assertNotEqual(a.value, b.value)
c.link()
self.assertEqual(a.value, b.value)
a.value += 1
self.assertEqual(a.value, b.value)
-
- def test_callbacks(self):
- """Verify two linked traitlets have their callbacks called once."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- class B(HasTraits):
- count = Int()
- a = A(value=9)
- b = B(count=8)
-
- # Register callbacks that count.
- callback_count = []
- def a_callback(name, old, new):
- callback_count.append('a')
- a.on_trait_change(a_callback, 'value')
- def b_callback(name, old, new):
- callback_count.append('b')
- b.on_trait_change(b_callback, 'count')
-
- # Connect the two classes.
- c = link((a, 'value'), (b, 'count'))
-
- # Make sure b's count was set to a's value once.
- self.assertEqual(''.join(callback_count), 'b')
- del callback_count[:]
-
- # Make sure a's value was set to b's count once.
- b.count = 5
- self.assertEqual(''.join(callback_count), 'ba')
- del callback_count[:]
-
- # Make sure b's count was set to a's value once.
- a.value = 4
- self.assertEqual(''.join(callback_count), 'ab')
- del callback_count[:]
-
+
+ def test_callbacks(self):
+ """Verify two linked traitlets have their callbacks called once."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ class B(HasTraits):
+ count = Int()
+ a = A(value=9)
+ b = B(count=8)
+
+ # Register callbacks that count.
+ callback_count = []
+ def a_callback(name, old, new):
+ callback_count.append('a')
+ a.on_trait_change(a_callback, 'value')
+ def b_callback(name, old, new):
+ callback_count.append('b')
+ b.on_trait_change(b_callback, 'count')
+
+ # Connect the two classes.
+ c = link((a, 'value'), (b, 'count'))
+
+ # Make sure b's count was set to a's value once.
+ self.assertEqual(''.join(callback_count), 'b')
+ del callback_count[:]
+
+ # Make sure a's value was set to b's count once.
+ b.count = 5
+ self.assertEqual(''.join(callback_count), 'ba')
+ del callback_count[:]
+
+ # Make sure b's count was set to a's value once.
+ a.value = 4
+ self.assertEqual(''.join(callback_count), 'ab')
+ del callback_count[:]
+
def test_tranform(self):
"""Test transform link."""
@@ -2020,610 +2020,610 @@ class TestLink(TestCase):
l = link((mc, "i"), (mc, "j"))
self.assertRaises(TraitError, setattr, mc, 'j', 2)
-class TestDirectionalLink(TestCase):
- def test_connect_same(self):
- """Verify two traitlets of the same type can be linked together using directional_link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Conenct the two classes.
- c = directional_link((a, 'value'), (b, 'value'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.value)
-
- # Change one the value of the source and check that it synchronizes the target.
- a.value = 5
- self.assertEqual(b.value, 5)
- # Change one the value of the target and check that it has no impact on the source
- b.value = 6
- self.assertEqual(a.value, 5)
-
- def test_tranform(self):
- """Test transform link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Conenct the two classes.
- c = directional_link((a, 'value'), (b, 'value'), lambda x: 2 * x)
-
- # Make sure the values are correct at the point of linking.
- self.assertEqual(b.value, 2 * a.value)
-
- # Change one the value of the source and check that it modifies the target.
- a.value = 5
- self.assertEqual(b.value, 10)
- # Change one the value of the target and check that it has no impact on the source
- b.value = 6
- self.assertEqual(a.value, 5)
-
- def test_link_different(self):
- """Verify two traitlets of different types can be linked together using link."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- class B(HasTraits):
- count = Int()
- a = A(value=9)
- b = B(count=8)
-
- # Conenct the two classes.
- c = directional_link((a, 'value'), (b, 'count'))
-
- # Make sure the values are the same at the point of linking.
- self.assertEqual(a.value, b.count)
-
- # Change one the value of the source and check that it synchronizes the target.
- a.value = 5
- self.assertEqual(b.count, 5)
- # Change one the value of the target and check that it has no impact on the source
- b.value = 6
- self.assertEqual(a.value, 5)
-
+class TestDirectionalLink(TestCase):
+ def test_connect_same(self):
+ """Verify two traitlets of the same type can be linked together using directional_link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Conenct the two classes.
+ c = directional_link((a, 'value'), (b, 'value'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.value)
+
+ # Change one the value of the source and check that it synchronizes the target.
+ a.value = 5
+ self.assertEqual(b.value, 5)
+ # Change one the value of the target and check that it has no impact on the source
+ b.value = 6
+ self.assertEqual(a.value, 5)
+
+ def test_tranform(self):
+ """Test transform link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Conenct the two classes.
+ c = directional_link((a, 'value'), (b, 'value'), lambda x: 2 * x)
+
+ # Make sure the values are correct at the point of linking.
+ self.assertEqual(b.value, 2 * a.value)
+
+ # Change one the value of the source and check that it modifies the target.
+ a.value = 5
+ self.assertEqual(b.value, 10)
+ # Change one the value of the target and check that it has no impact on the source
+ b.value = 6
+ self.assertEqual(a.value, 5)
+
+ def test_link_different(self):
+ """Verify two traitlets of different types can be linked together using link."""
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ class B(HasTraits):
+ count = Int()
+ a = A(value=9)
+ b = B(count=8)
+
+ # Conenct the two classes.
+ c = directional_link((a, 'value'), (b, 'count'))
+
+ # Make sure the values are the same at the point of linking.
+ self.assertEqual(a.value, b.count)
+
+ # Change one the value of the source and check that it synchronizes the target.
+ a.value = 5
+ self.assertEqual(b.count, 5)
+ # Change one the value of the target and check that it has no impact on the source
+ b.value = 6
+ self.assertEqual(a.value, 5)
+
def test_unlink_link(self):
"""Verify two linked traitlets can be unlinked and relinked."""
-
- # Create two simple classes with Int traitlets.
- class A(HasTraits):
- value = Int()
- a = A(value=9)
- b = A(value=8)
-
- # Connect the two classes.
- c = directional_link((a, 'value'), (b, 'value'))
- a.value = 4
- c.unlink()
-
- # Change one of the values to make sure they don't stay in sync.
- a.value = 5
- self.assertNotEqual(a.value, b.value)
+
+ # Create two simple classes with Int traitlets.
+ class A(HasTraits):
+ value = Int()
+ a = A(value=9)
+ b = A(value=8)
+
+ # Connect the two classes.
+ c = directional_link((a, 'value'), (b, 'value'))
+ a.value = 4
+ c.unlink()
+
+ # Change one of the values to make sure they don't stay in sync.
+ a.value = 5
+ self.assertNotEqual(a.value, b.value)
c.link()
self.assertEqual(a.value, b.value)
a.value += 1
self.assertEqual(a.value, b.value)
-
-class Pickleable(HasTraits):
-
- i = Int()
- @observe('i')
- def _i_changed(self, change): pass
- @validate('i')
- def _i_validate(self, commit):
- return commit['value']
-
- j = Int()
-
- def __init__(self):
- with self.hold_trait_notifications():
- self.i = 1
- self.on_trait_change(self._i_changed, 'i')
-
-def test_pickle_hastraits():
- c = Pickleable()
- for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
- p = pickle.dumps(c, protocol)
- c2 = pickle.loads(p)
- assert c2.i == c.i
- assert c2.j == c.j
-
- c.i = 5
- for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
- p = pickle.dumps(c, protocol)
- c2 = pickle.loads(p)
- assert c2.i == c.i
- assert c2.j == c.j
-
-
-def test_hold_trait_notifications():
- changes = []
-
- class Test(HasTraits):
- a = Integer(0)
- b = Integer(0)
-
- def _a_changed(self, name, old, new):
- changes.append((old, new))
-
- def _b_validate(self, value, trait):
- if value != 0:
- raise TraitError('Only 0 is a valid value')
- return value
-
- # Test context manager and nesting
- t = Test()
- with t.hold_trait_notifications():
- with t.hold_trait_notifications():
- t.a = 1
- assert t.a == 1
- assert changes == []
- t.a = 2
- assert t.a == 2
- with t.hold_trait_notifications():
- t.a = 3
- assert t.a == 3
- assert changes == []
- t.a = 4
- assert t.a == 4
- assert changes == []
- t.a = 4
- assert t.a == 4
- assert changes == []
-
- assert changes == [(0, 4)]
- # Test roll-back
- try:
- with t.hold_trait_notifications():
- t.b = 1 # raises a Trait error
- except:
- pass
- assert t.b == 0
-
-
-class RollBack(HasTraits):
- bar = Int()
- def _bar_validate(self, value, trait):
- if value:
- raise TraitError('foobar')
- return value
-
-
-class TestRollback(TestCase):
-
- def test_roll_back(self):
-
- def assign_rollback():
- RollBack(bar=1)
-
- self.assertRaises(TraitError, assign_rollback)
-
-
-class CacheModification(HasTraits):
- foo = Int()
- bar = Int()
-
- def _bar_validate(self, value, trait):
- self.foo = value
- return value
-
- def _foo_validate(self, value, trait):
- self.bar = value
- return value
-
-
-def test_cache_modification():
- CacheModification(foo=1)
- CacheModification(bar=1)
-
-
-class OrderTraits(HasTraits):
- notified = Dict()
-
- a = Unicode()
- b = Unicode()
- c = Unicode()
- d = Unicode()
- e = Unicode()
- f = Unicode()
- g = Unicode()
- h = Unicode()
- i = Unicode()
- j = Unicode()
- k = Unicode()
- l = Unicode()
-
- def _notify(self, name, old, new):
- """check the value of all traits when each trait change is triggered
-
- This verifies that the values are not sensitive
- to dict ordering when loaded from kwargs
- """
- # check the value of the other traits
- # when a given trait change notification fires
- self.notified[name] = {
- c: getattr(self, c) for c in 'abcdefghijkl'
- }
-
- def __init__(self, **kwargs):
- self.on_trait_change(self._notify)
- super(OrderTraits, self).__init__(**kwargs)
-
-def test_notification_order():
- d = {c:c for c in 'abcdefghijkl'}
- obj = OrderTraits()
- assert obj.notified == {}
- obj = OrderTraits(**d)
- notifications = {
- c: d for c in 'abcdefghijkl'
- }
- assert obj.notified == notifications
-
-
-
-###
-# Traits for Forward Declaration Tests
-###
-class ForwardDeclaredInstanceTrait(HasTraits):
-
- value = ForwardDeclaredInstance('ForwardDeclaredBar', allow_none=True)
-
-class ForwardDeclaredTypeTrait(HasTraits):
-
- value = ForwardDeclaredType('ForwardDeclaredBar', allow_none=True)
-
-class ForwardDeclaredInstanceListTrait(HasTraits):
-
- value = List(ForwardDeclaredInstance('ForwardDeclaredBar'))
-
-class ForwardDeclaredTypeListTrait(HasTraits):
-
- value = List(ForwardDeclaredType('ForwardDeclaredBar'))
-###
-# End Traits for Forward Declaration Tests
-###
-
-###
-# Classes for Forward Declaration Tests
-###
-class ForwardDeclaredBar(object):
- pass
-
-class ForwardDeclaredBarSub(ForwardDeclaredBar):
- pass
-###
-# End Classes for Forward Declaration Tests
-###
-
-###
-# Forward Declaration Tests
-###
-class TestForwardDeclaredInstanceTrait(TraitTestBase):
-
- obj = ForwardDeclaredInstanceTrait()
- _default_value = None
- _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
- _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub]
-
-class TestForwardDeclaredTypeTrait(TraitTestBase):
-
- obj = ForwardDeclaredTypeTrait()
- _default_value = None
- _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
- _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
-
-class TestForwardDeclaredInstanceList(TraitTestBase):
-
- obj = ForwardDeclaredInstanceListTrait()
-
- def test_klass(self):
- """Test that the instance klass is properly assigned."""
- self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
-
- _default_value = []
- _good_values = [
- [ForwardDeclaredBar(), ForwardDeclaredBarSub()],
- [],
- ]
- _bad_values = [
- ForwardDeclaredBar(),
- [ForwardDeclaredBar(), 3, None],
- '1',
- # Note that this is the type, not an instance.
- [ForwardDeclaredBar],
- [None],
- None,
- ]
-
-class TestForwardDeclaredTypeList(TraitTestBase):
-
- obj = ForwardDeclaredTypeListTrait()
-
- def test_klass(self):
- """Test that the instance klass is properly assigned."""
- self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
-
- _default_value = []
- _good_values = [
- [ForwardDeclaredBar, ForwardDeclaredBarSub],
- [],
- ]
- _bad_values = [
- ForwardDeclaredBar,
- [ForwardDeclaredBar, 3],
- '1',
- # Note that this is an instance, not the type.
- [ForwardDeclaredBar()],
- [None],
- None,
- ]
-###
-# End Forward Declaration Tests
-###
-
-class TestDynamicTraits(TestCase):
-
- def setUp(self):
- self._notify1 = []
-
- def notify1(self, name, old, new):
- self._notify1.append((name, old, new))
-
- def test_notify_all(self):
-
- class A(HasTraits):
- pass
-
- a = A()
- self.assertTrue(not hasattr(a, 'x'))
- self.assertTrue(not hasattr(a, 'y'))
-
- # Dynamically add trait x.
- a.add_traits(x=Int())
- self.assertTrue(hasattr(a, 'x'))
- self.assertTrue(isinstance(a, (A, )))
-
- # Dynamically add trait y.
- a.add_traits(y=Float())
- self.assertTrue(hasattr(a, 'y'))
- self.assertTrue(isinstance(a, (A, )))
- self.assertEqual(a.__class__.__name__, A.__name__)
-
- # Create a new instance and verify that x and y
- # aren't defined.
- b = A()
- self.assertTrue(not hasattr(b, 'x'))
- self.assertTrue(not hasattr(b, 'y'))
-
- # Verify that notification works like normal.
- a.on_trait_change(self.notify1)
- a.x = 0
- self.assertEqual(len(self._notify1), 0)
- a.y = 0.0
- self.assertEqual(len(self._notify1), 0)
- a.x = 10
- self.assertTrue(('x', 0, 10) in self._notify1)
- a.y = 10.0
- self.assertTrue(('y', 0.0, 10.0) in self._notify1)
- self.assertRaises(TraitError, setattr, a, 'x', 'bad string')
- self.assertRaises(TraitError, setattr, a, 'y', 'bad string')
- self._notify1 = []
- a.on_trait_change(self.notify1, remove=True)
- a.x = 20
- a.y = 20.0
- self.assertEqual(len(self._notify1), 0)
-
-
-def test_enum_no_default():
- class C(HasTraits):
- t = Enum(['a', 'b'])
-
- c = C()
- c.t = 'a'
- assert c.t == 'a'
-
- c = C()
-
- with pytest.raises(TraitError):
- t = c.t
-
- c = C(t='b')
- assert c.t == 'b'
-
-
-def test_default_value_repr():
- class C(HasTraits):
- t = Type('traitlets.HasTraits')
- t2 = Type(HasTraits)
- n = Integer(0)
- lis = List()
- d = Dict()
-
- assert C.t.default_value_repr() == "'traitlets.HasTraits'"
- assert C.t2.default_value_repr() == "'traitlets.traitlets.HasTraits'"
- assert C.n.default_value_repr() == '0'
- assert C.lis.default_value_repr() == '[]'
- assert C.d.default_value_repr() == '{}'
-
-
-class TransitionalClass(HasTraits):
-
- d = Any()
- @default('d')
- def _d_default(self):
- return TransitionalClass
-
- parent_super = False
- calls_super = Integer(0)
-
- @default('calls_super')
- def _calls_super_default(self):
- return -1
-
- @observe('calls_super')
- @observe_compat
- def _calls_super_changed(self, change):
- self.parent_super = change
-
- parent_override = False
- overrides = Integer(0)
-
- @observe('overrides')
- @observe_compat
- def _overrides_changed(self, change):
- self.parent_override = change
-
-
-class SubClass(TransitionalClass):
- def _d_default(self):
- return SubClass
-
- subclass_super = False
- def _calls_super_changed(self, name, old, new):
- self.subclass_super = True
- super(SubClass, self)._calls_super_changed(name, old, new)
-
- subclass_override = False
- def _overrides_changed(self, name, old, new):
- self.subclass_override = True
-
-
-def test_subclass_compat():
- obj = SubClass()
- obj.calls_super = 5
- assert obj.parent_super
- assert obj.subclass_super
- obj.overrides = 5
- assert obj.subclass_override
- assert not obj.parent_override
- assert obj.d is SubClass
-
-
-class DefinesHandler(HasTraits):
- parent_called = False
-
- trait = Integer()
- @observe('trait')
- def handler(self, change):
- self.parent_called = True
-
-
-class OverridesHandler(DefinesHandler):
- child_called = False
-
- @observe('trait')
- def handler(self, change):
- self.child_called = True
-
-
-def test_subclass_override_observer():
- obj = OverridesHandler()
- obj.trait = 5
- assert obj.child_called
- assert not obj.parent_called
-
-
-class DoesntRegisterHandler(DefinesHandler):
- child_called = False
-
- def handler(self, change):
- self.child_called = True
-
-
-def test_subclass_override_not_registered():
- """Subclass that overrides observer and doesn't re-register unregisters both"""
- obj = DoesntRegisterHandler()
- obj.trait = 5
- assert not obj.child_called
- assert not obj.parent_called
-
-
-class AddsHandler(DefinesHandler):
- child_called = False
-
- @observe('trait')
- def child_handler(self, change):
- self.child_called = True
-
-def test_subclass_add_observer():
- obj = AddsHandler()
- obj.trait = 5
- assert obj.child_called
- assert obj.parent_called
-
-
-def test_observe_iterables():
-
- class C(HasTraits):
- i = Integer()
- s = Unicode()
-
- c = C()
- recorded = {}
- def record(change):
- recorded['change'] = change
-
- # observe with names=set
- c.observe(record, names={'i', 's'})
- c.i = 5
- assert recorded['change'].name == 'i'
- assert recorded['change'].new == 5
- c.s = 'hi'
- assert recorded['change'].name == 's'
- assert recorded['change'].new == 'hi'
-
- # observe with names=custom container with iter, contains
- class MyContainer(object):
- def __init__(self, container):
- self.container = container
-
- def __iter__(self):
- return iter(self.container)
-
- def __contains__(self, key):
- return key in self.container
-
- c.observe(record, names=MyContainer({'i', 's'}))
- c.i = 10
- assert recorded['change'].name == 'i'
- assert recorded['change'].new == 10
- c.s = 'ok'
- assert recorded['change'].name == 's'
- assert recorded['change'].new == 'ok'
-
-
-def test_super_args():
- class SuperRecorder(object):
- def __init__(self, *args, **kwargs):
- self.super_args = args
- self.super_kwargs = kwargs
-
- class SuperHasTraits(HasTraits, SuperRecorder):
- i = Integer()
-
- obj = SuperHasTraits('a1', 'a2', b=10, i=5, c='x')
- assert obj.i == 5
- assert not hasattr(obj, 'b')
- assert not hasattr(obj, 'c')
- assert obj.super_args == ('a1' , 'a2')
- assert obj.super_kwargs == {'b': 10 , 'c': 'x'}
-
-def test_super_bad_args():
- class SuperHasTraits(HasTraits):
- a = Integer()
+
+class Pickleable(HasTraits):
+
+ i = Int()
+ @observe('i')
+ def _i_changed(self, change): pass
+ @validate('i')
+ def _i_validate(self, commit):
+ return commit['value']
+
+ j = Int()
+
+ def __init__(self):
+ with self.hold_trait_notifications():
+ self.i = 1
+ self.on_trait_change(self._i_changed, 'i')
+
+def test_pickle_hastraits():
+ c = Pickleable()
+ for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+ p = pickle.dumps(c, protocol)
+ c2 = pickle.loads(p)
+ assert c2.i == c.i
+ assert c2.j == c.j
+
+ c.i = 5
+ for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+ p = pickle.dumps(c, protocol)
+ c2 = pickle.loads(p)
+ assert c2.i == c.i
+ assert c2.j == c.j
+
+
+def test_hold_trait_notifications():
+ changes = []
+
+ class Test(HasTraits):
+ a = Integer(0)
+ b = Integer(0)
+
+ def _a_changed(self, name, old, new):
+ changes.append((old, new))
+
+ def _b_validate(self, value, trait):
+ if value != 0:
+ raise TraitError('Only 0 is a valid value')
+ return value
+
+ # Test context manager and nesting
+ t = Test()
+ with t.hold_trait_notifications():
+ with t.hold_trait_notifications():
+ t.a = 1
+ assert t.a == 1
+ assert changes == []
+ t.a = 2
+ assert t.a == 2
+ with t.hold_trait_notifications():
+ t.a = 3
+ assert t.a == 3
+ assert changes == []
+ t.a = 4
+ assert t.a == 4
+ assert changes == []
+ t.a = 4
+ assert t.a == 4
+ assert changes == []
+
+ assert changes == [(0, 4)]
+ # Test roll-back
+ try:
+ with t.hold_trait_notifications():
+ t.b = 1 # raises a Trait error
+ except:
+ pass
+ assert t.b == 0
+
+
+class RollBack(HasTraits):
+ bar = Int()
+ def _bar_validate(self, value, trait):
+ if value:
+ raise TraitError('foobar')
+ return value
+
+
+class TestRollback(TestCase):
+
+ def test_roll_back(self):
+
+ def assign_rollback():
+ RollBack(bar=1)
+
+ self.assertRaises(TraitError, assign_rollback)
+
+
+class CacheModification(HasTraits):
+ foo = Int()
+ bar = Int()
+
+ def _bar_validate(self, value, trait):
+ self.foo = value
+ return value
+
+ def _foo_validate(self, value, trait):
+ self.bar = value
+ return value
+
+
+def test_cache_modification():
+ CacheModification(foo=1)
+ CacheModification(bar=1)
+
+
+class OrderTraits(HasTraits):
+ notified = Dict()
+
+ a = Unicode()
+ b = Unicode()
+ c = Unicode()
+ d = Unicode()
+ e = Unicode()
+ f = Unicode()
+ g = Unicode()
+ h = Unicode()
+ i = Unicode()
+ j = Unicode()
+ k = Unicode()
+ l = Unicode()
+
+ def _notify(self, name, old, new):
+ """check the value of all traits when each trait change is triggered
+
+ This verifies that the values are not sensitive
+ to dict ordering when loaded from kwargs
+ """
+ # check the value of the other traits
+ # when a given trait change notification fires
+ self.notified[name] = {
+ c: getattr(self, c) for c in 'abcdefghijkl'
+ }
+
+ def __init__(self, **kwargs):
+ self.on_trait_change(self._notify)
+ super(OrderTraits, self).__init__(**kwargs)
+
+def test_notification_order():
+ d = {c:c for c in 'abcdefghijkl'}
+ obj = OrderTraits()
+ assert obj.notified == {}
+ obj = OrderTraits(**d)
+ notifications = {
+ c: d for c in 'abcdefghijkl'
+ }
+ assert obj.notified == notifications
+
+
+
+###
+# Traits for Forward Declaration Tests
+###
+class ForwardDeclaredInstanceTrait(HasTraits):
+
+ value = ForwardDeclaredInstance('ForwardDeclaredBar', allow_none=True)
+
+class ForwardDeclaredTypeTrait(HasTraits):
+
+ value = ForwardDeclaredType('ForwardDeclaredBar', allow_none=True)
+
+class ForwardDeclaredInstanceListTrait(HasTraits):
+
+ value = List(ForwardDeclaredInstance('ForwardDeclaredBar'))
+
+class ForwardDeclaredTypeListTrait(HasTraits):
+
+ value = List(ForwardDeclaredType('ForwardDeclaredBar'))
+###
+# End Traits for Forward Declaration Tests
+###
+
+###
+# Classes for Forward Declaration Tests
+###
+class ForwardDeclaredBar(object):
+ pass
+
+class ForwardDeclaredBarSub(ForwardDeclaredBar):
+ pass
+###
+# End Classes for Forward Declaration Tests
+###
+
+###
+# Forward Declaration Tests
+###
+class TestForwardDeclaredInstanceTrait(TraitTestBase):
+
+ obj = ForwardDeclaredInstanceTrait()
+ _default_value = None
+ _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
+ _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub]
+
+class TestForwardDeclaredTypeTrait(TraitTestBase):
+
+ obj = ForwardDeclaredTypeTrait()
+ _default_value = None
+ _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
+ _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
+
+class TestForwardDeclaredInstanceList(TraitTestBase):
+
+ obj = ForwardDeclaredInstanceListTrait()
+
+ def test_klass(self):
+ """Test that the instance klass is properly assigned."""
+ self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
+
+ _default_value = []
+ _good_values = [
+ [ForwardDeclaredBar(), ForwardDeclaredBarSub()],
+ [],
+ ]
+ _bad_values = [
+ ForwardDeclaredBar(),
+ [ForwardDeclaredBar(), 3, None],
+ '1',
+ # Note that this is the type, not an instance.
+ [ForwardDeclaredBar],
+ [None],
+ None,
+ ]
+
+class TestForwardDeclaredTypeList(TraitTestBase):
+
+ obj = ForwardDeclaredTypeListTrait()
+
+ def test_klass(self):
+ """Test that the instance klass is properly assigned."""
+ self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
+
+ _default_value = []
+ _good_values = [
+ [ForwardDeclaredBar, ForwardDeclaredBarSub],
+ [],
+ ]
+ _bad_values = [
+ ForwardDeclaredBar,
+ [ForwardDeclaredBar, 3],
+ '1',
+ # Note that this is an instance, not the type.
+ [ForwardDeclaredBar()],
+ [None],
+ None,
+ ]
+###
+# End Forward Declaration Tests
+###
+
+class TestDynamicTraits(TestCase):
+
+ def setUp(self):
+ self._notify1 = []
+
+ def notify1(self, name, old, new):
+ self._notify1.append((name, old, new))
+
+ def test_notify_all(self):
+
+ class A(HasTraits):
+ pass
+
+ a = A()
+ self.assertTrue(not hasattr(a, 'x'))
+ self.assertTrue(not hasattr(a, 'y'))
+
+ # Dynamically add trait x.
+ a.add_traits(x=Int())
+ self.assertTrue(hasattr(a, 'x'))
+ self.assertTrue(isinstance(a, (A, )))
+
+ # Dynamically add trait y.
+ a.add_traits(y=Float())
+ self.assertTrue(hasattr(a, 'y'))
+ self.assertTrue(isinstance(a, (A, )))
+ self.assertEqual(a.__class__.__name__, A.__name__)
+
+ # Create a new instance and verify that x and y
+ # aren't defined.
+ b = A()
+ self.assertTrue(not hasattr(b, 'x'))
+ self.assertTrue(not hasattr(b, 'y'))
+
+ # Verify that notification works like normal.
+ a.on_trait_change(self.notify1)
+ a.x = 0
+ self.assertEqual(len(self._notify1), 0)
+ a.y = 0.0
+ self.assertEqual(len(self._notify1), 0)
+ a.x = 10
+ self.assertTrue(('x', 0, 10) in self._notify1)
+ a.y = 10.0
+ self.assertTrue(('y', 0.0, 10.0) in self._notify1)
+ self.assertRaises(TraitError, setattr, a, 'x', 'bad string')
+ self.assertRaises(TraitError, setattr, a, 'y', 'bad string')
+ self._notify1 = []
+ a.on_trait_change(self.notify1, remove=True)
+ a.x = 20
+ a.y = 20.0
+ self.assertEqual(len(self._notify1), 0)
+
+
+def test_enum_no_default():
+ class C(HasTraits):
+ t = Enum(['a', 'b'])
+
+ c = C()
+ c.t = 'a'
+ assert c.t == 'a'
+
+ c = C()
+
+ with pytest.raises(TraitError):
+ t = c.t
+
+ c = C(t='b')
+ assert c.t == 'b'
+
+
+def test_default_value_repr():
+ class C(HasTraits):
+ t = Type('traitlets.HasTraits')
+ t2 = Type(HasTraits)
+ n = Integer(0)
+ lis = List()
+ d = Dict()
+
+ assert C.t.default_value_repr() == "'traitlets.HasTraits'"
+ assert C.t2.default_value_repr() == "'traitlets.traitlets.HasTraits'"
+ assert C.n.default_value_repr() == '0'
+ assert C.lis.default_value_repr() == '[]'
+ assert C.d.default_value_repr() == '{}'
+
+
+class TransitionalClass(HasTraits):
+
+ d = Any()
+ @default('d')
+ def _d_default(self):
+ return TransitionalClass
+
+ parent_super = False
+ calls_super = Integer(0)
+
+ @default('calls_super')
+ def _calls_super_default(self):
+ return -1
+
+ @observe('calls_super')
+ @observe_compat
+ def _calls_super_changed(self, change):
+ self.parent_super = change
+
+ parent_override = False
+ overrides = Integer(0)
+
+ @observe('overrides')
+ @observe_compat
+ def _overrides_changed(self, change):
+ self.parent_override = change
+
+
+class SubClass(TransitionalClass):
+ def _d_default(self):
+ return SubClass
+
+ subclass_super = False
+ def _calls_super_changed(self, name, old, new):
+ self.subclass_super = True
+ super(SubClass, self)._calls_super_changed(name, old, new)
+
+ subclass_override = False
+ def _overrides_changed(self, name, old, new):
+ self.subclass_override = True
+
+
+def test_subclass_compat():
+ obj = SubClass()
+ obj.calls_super = 5
+ assert obj.parent_super
+ assert obj.subclass_super
+ obj.overrides = 5
+ assert obj.subclass_override
+ assert not obj.parent_override
+ assert obj.d is SubClass
+
+
+class DefinesHandler(HasTraits):
+ parent_called = False
+
+ trait = Integer()
+ @observe('trait')
+ def handler(self, change):
+ self.parent_called = True
+
+
+class OverridesHandler(DefinesHandler):
+ child_called = False
+
+ @observe('trait')
+ def handler(self, change):
+ self.child_called = True
+
+
+def test_subclass_override_observer():
+ obj = OverridesHandler()
+ obj.trait = 5
+ assert obj.child_called
+ assert not obj.parent_called
+
+
+class DoesntRegisterHandler(DefinesHandler):
+ child_called = False
+
+ def handler(self, change):
+ self.child_called = True
+
+
+def test_subclass_override_not_registered():
+ """Subclass that overrides observer and doesn't re-register unregisters both"""
+ obj = DoesntRegisterHandler()
+ obj.trait = 5
+ assert not obj.child_called
+ assert not obj.parent_called
+
+
+class AddsHandler(DefinesHandler):
+ child_called = False
+
+ @observe('trait')
+ def child_handler(self, change):
+ self.child_called = True
+
+def test_subclass_add_observer():
+ obj = AddsHandler()
+ obj.trait = 5
+ assert obj.child_called
+ assert obj.parent_called
+
+
+def test_observe_iterables():
+
+ class C(HasTraits):
+ i = Integer()
+ s = Unicode()
+
+ c = C()
+ recorded = {}
+ def record(change):
+ recorded['change'] = change
+
+ # observe with names=set
+ c.observe(record, names={'i', 's'})
+ c.i = 5
+ assert recorded['change'].name == 'i'
+ assert recorded['change'].new == 5
+ c.s = 'hi'
+ assert recorded['change'].name == 's'
+ assert recorded['change'].new == 'hi'
+
+ # observe with names=custom container with iter, contains
+ class MyContainer(object):
+ def __init__(self, container):
+ self.container = container
+
+ def __iter__(self):
+ return iter(self.container)
+
+ def __contains__(self, key):
+ return key in self.container
+
+ c.observe(record, names=MyContainer({'i', 's'}))
+ c.i = 10
+ assert recorded['change'].name == 'i'
+ assert recorded['change'].new == 10
+ c.s = 'ok'
+ assert recorded['change'].name == 's'
+ assert recorded['change'].new == 'ok'
+
+
+def test_super_args():
+ class SuperRecorder(object):
+ def __init__(self, *args, **kwargs):
+ self.super_args = args
+ self.super_kwargs = kwargs
+
+ class SuperHasTraits(HasTraits, SuperRecorder):
+ i = Integer()
+
+ obj = SuperHasTraits('a1', 'a2', b=10, i=5, c='x')
+ assert obj.i == 5
+ assert not hasattr(obj, 'b')
+ assert not hasattr(obj, 'c')
+ assert obj.super_args == ('a1' , 'a2')
+ assert obj.super_kwargs == {'b': 10 , 'c': 'x'}
+
+def test_super_bad_args():
+ class SuperHasTraits(HasTraits):
+ a = Integer()
w = ["Passing unrecognized arguments"]
- with expected_warnings(w):
- obj = SuperHasTraits(a=1, b=2)
+ with expected_warnings(w):
+ obj = SuperHasTraits(a=1, b=2)
assert obj.a == 1
- assert not hasattr(obj, 'b')
+ assert not hasattr(obj, 'b')
def test_default_mro():
diff --git a/contrib/python/traitlets/py3/traitlets/tests/test_traitlets_enum.py b/contrib/python/traitlets/py3/traitlets/tests/test_traitlets_enum.py
index 769e830b33..6a074aadfb 100644
--- a/contrib/python/traitlets/py3/traitlets/tests/test_traitlets_enum.py
+++ b/contrib/python/traitlets/py3/traitlets/tests/test_traitlets_enum.py
@@ -1,28 +1,28 @@
-# pylint: disable=missing-docstring, too-few-public-methods
-"""
-Test the trait-type ``UseEnum``.
-"""
-
-import unittest
-import enum
+# pylint: disable=missing-docstring, too-few-public-methods
+"""
+Test the trait-type ``UseEnum``.
+"""
+
+import unittest
+import enum
from traitlets import HasTraits, TraitError, Enum, UseEnum, CaselessStrEnum, FuzzyEnum
-
-
-# -----------------------------------------------------------------------------
-# TEST SUPPORT:
-# -----------------------------------------------------------------------------
-
-class Color(enum.Enum):
- red = 1
- green = 2
- blue = 3
- yellow = 4
-
-class OtherColor(enum.Enum):
- red = 0
- green = 1
-
-
+
+
+# -----------------------------------------------------------------------------
+# TEST SUPPORT:
+# -----------------------------------------------------------------------------
+
+class Color(enum.Enum):
+ red = 1
+ green = 2
+ blue = 3
+ yellow = 4
+
+class OtherColor(enum.Enum):
+ red = 0
+ green = 1
+
+
class CSColor(enum.Enum):
red = 1
Green = 2
@@ -33,161 +33,161 @@ class CSColor(enum.Enum):
color_choices = 'red Green BLUE YeLLoW'.split()
-# -----------------------------------------------------------------------------
-# TESTSUITE:
-# -----------------------------------------------------------------------------
-class TestUseEnum(unittest.TestCase):
- # pylint: disable=invalid-name
-
- class Example(HasTraits):
- color = UseEnum(Color, help="Color enum")
-
- def test_assign_enum_value(self):
- example = self.Example()
- example.color = Color.green
- self.assertEqual(example.color, Color.green)
-
- def test_assign_all_enum_values(self):
- # pylint: disable=no-member
- enum_values = [value for value in Color.__members__.values()]
- for value in enum_values:
- self.assertIsInstance(value, Color)
- example = self.Example()
- example.color = value
- self.assertEqual(example.color, value)
- self.assertIsInstance(value, Color)
-
- def test_assign_enum_value__with_other_enum_raises_error(self):
- example = self.Example()
- with self.assertRaises(TraitError):
- example.color = OtherColor.green
-
- def test_assign_enum_name_1(self):
- # -- CONVERT: string => Enum value (item)
- example = self.Example()
- example.color = "red"
- self.assertEqual(example.color, Color.red)
-
- def test_assign_enum_value_name(self):
- # -- CONVERT: string => Enum value (item)
- # pylint: disable=no-member
- enum_names = [enum_val.name for enum_val in Color.__members__.values()]
- for value in enum_names:
+# -----------------------------------------------------------------------------
+# TESTSUITE:
+# -----------------------------------------------------------------------------
+class TestUseEnum(unittest.TestCase):
+ # pylint: disable=invalid-name
+
+ class Example(HasTraits):
+ color = UseEnum(Color, help="Color enum")
+
+ def test_assign_enum_value(self):
+ example = self.Example()
+ example.color = Color.green
+ self.assertEqual(example.color, Color.green)
+
+ def test_assign_all_enum_values(self):
+ # pylint: disable=no-member
+ enum_values = [value for value in Color.__members__.values()]
+ for value in enum_values:
+ self.assertIsInstance(value, Color)
+ example = self.Example()
+ example.color = value
+ self.assertEqual(example.color, value)
+ self.assertIsInstance(value, Color)
+
+ def test_assign_enum_value__with_other_enum_raises_error(self):
+ example = self.Example()
+ with self.assertRaises(TraitError):
+ example.color = OtherColor.green
+
+ def test_assign_enum_name_1(self):
+ # -- CONVERT: string => Enum value (item)
+ example = self.Example()
+ example.color = "red"
+ self.assertEqual(example.color, Color.red)
+
+ def test_assign_enum_value_name(self):
+ # -- CONVERT: string => Enum value (item)
+ # pylint: disable=no-member
+ enum_names = [enum_val.name for enum_val in Color.__members__.values()]
+ for value in enum_names:
self.assertIsInstance(value, str)
- example = self.Example()
- enum_value = Color.__members__.get(value)
- example.color = value
- self.assertIs(example.color, enum_value)
- self.assertEqual(example.color.name, value)
-
- def test_assign_scoped_enum_value_name(self):
- # -- CONVERT: string => Enum value (item)
- scoped_names = ["Color.red", "Color.green", "Color.blue", "Color.yellow"]
- for value in scoped_names:
- example = self.Example()
- example.color = value
- self.assertIsInstance(example.color, Color)
+ example = self.Example()
+ enum_value = Color.__members__.get(value)
+ example.color = value
+ self.assertIs(example.color, enum_value)
+ self.assertEqual(example.color.name, value)
+
+ def test_assign_scoped_enum_value_name(self):
+ # -- CONVERT: string => Enum value (item)
+ scoped_names = ["Color.red", "Color.green", "Color.blue", "Color.yellow"]
+ for value in scoped_names:
+ example = self.Example()
+ example.color = value
+ self.assertIsInstance(example.color, Color)
self.assertEqual(str(example.color), value)
-
- def test_assign_bad_enum_value_name__raises_error(self):
- # -- CONVERT: string => Enum value (item)
- bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
- for value in bad_enum_names:
- example = self.Example()
- with self.assertRaises(TraitError):
- example.color = value
-
- def test_assign_enum_value_number_1(self):
- # -- CONVERT: number => Enum value (item)
- example = self.Example()
- example.color = 1 # == Color.red.value
- example.color = Color.red.value
- self.assertEqual(example.color, Color.red)
-
- def test_assign_enum_value_number(self):
- # -- CONVERT: number => Enum value (item)
- # pylint: disable=no-member
- enum_numbers = [enum_val.value
- for enum_val in Color.__members__.values()]
- for value in enum_numbers:
- self.assertIsInstance(value, int)
- example = self.Example()
- example.color = value
- self.assertIsInstance(example.color, Color)
- self.assertEqual(example.color.value, value)
-
- def test_assign_bad_enum_value_number__raises_error(self):
- # -- CONVERT: number => Enum value (item)
- bad_numbers = [-1, 0, 5]
- for value in bad_numbers:
- self.assertIsInstance(value, int)
- assert UseEnum(Color).select_by_number(value, None) is None
- example = self.Example()
- with self.assertRaises(TraitError):
- example.color = value
-
- def test_ctor_without_default_value(self):
- # -- IMPLICIT: default_value = Color.red (first enum-value)
- class Example2(HasTraits):
- color = UseEnum(Color)
-
- example = Example2()
- self.assertEqual(example.color, Color.red)
-
- def test_ctor_with_default_value_as_enum_value(self):
- # -- CONVERT: number => Enum value (item)
- class Example2(HasTraits):
- color = UseEnum(Color, default_value=Color.green)
-
- example = Example2()
- self.assertEqual(example.color, Color.green)
-
-
- def test_ctor_with_default_value_none_and_not_allow_none(self):
- # -- IMPLICIT: default_value = Color.red (first enum-value)
- class Example2(HasTraits):
- color1 = UseEnum(Color, default_value=None, allow_none=False)
- color2 = UseEnum(Color, default_value=None)
- example = Example2()
- self.assertEqual(example.color1, Color.red)
- self.assertEqual(example.color2, Color.red)
-
- def test_ctor_with_default_value_none_and_allow_none(self):
- class Example2(HasTraits):
- color1 = UseEnum(Color, default_value=None, allow_none=True)
- color2 = UseEnum(Color, allow_none=True)
-
- example = Example2()
- self.assertIs(example.color1, None)
- self.assertIs(example.color2, None)
-
- def test_assign_none_without_allow_none_resets_to_default_value(self):
- class Example2(HasTraits):
- color1 = UseEnum(Color, allow_none=False)
- color2 = UseEnum(Color)
-
- example = Example2()
- example.color1 = None
- example.color2 = None
- self.assertIs(example.color1, Color.red)
- self.assertIs(example.color2, Color.red)
-
- def test_assign_none_to_enum_or_none(self):
- class Example2(HasTraits):
- color = UseEnum(Color, allow_none=True)
-
- example = Example2()
- example.color = None
- self.assertIs(example.color, None)
-
- def test_assign_bad_value_with_to_enum_or_none(self):
- class Example2(HasTraits):
- color = UseEnum(Color, allow_none=True)
-
- example = Example2()
- with self.assertRaises(TraitError):
- example.color = "BAD_VALUE"
-
+
+ def test_assign_bad_enum_value_name__raises_error(self):
+ # -- CONVERT: string => Enum value (item)
+ bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
+ for value in bad_enum_names:
+ example = self.Example()
+ with self.assertRaises(TraitError):
+ example.color = value
+
+ def test_assign_enum_value_number_1(self):
+ # -- CONVERT: number => Enum value (item)
+ example = self.Example()
+ example.color = 1 # == Color.red.value
+ example.color = Color.red.value
+ self.assertEqual(example.color, Color.red)
+
+ def test_assign_enum_value_number(self):
+ # -- CONVERT: number => Enum value (item)
+ # pylint: disable=no-member
+ enum_numbers = [enum_val.value
+ for enum_val in Color.__members__.values()]
+ for value in enum_numbers:
+ self.assertIsInstance(value, int)
+ example = self.Example()
+ example.color = value
+ self.assertIsInstance(example.color, Color)
+ self.assertEqual(example.color.value, value)
+
+ def test_assign_bad_enum_value_number__raises_error(self):
+ # -- CONVERT: number => Enum value (item)
+ bad_numbers = [-1, 0, 5]
+ for value in bad_numbers:
+ self.assertIsInstance(value, int)
+ assert UseEnum(Color).select_by_number(value, None) is None
+ example = self.Example()
+ with self.assertRaises(TraitError):
+ example.color = value
+
+ def test_ctor_without_default_value(self):
+ # -- IMPLICIT: default_value = Color.red (first enum-value)
+ class Example2(HasTraits):
+ color = UseEnum(Color)
+
+ example = Example2()
+ self.assertEqual(example.color, Color.red)
+
+ def test_ctor_with_default_value_as_enum_value(self):
+ # -- CONVERT: number => Enum value (item)
+ class Example2(HasTraits):
+ color = UseEnum(Color, default_value=Color.green)
+
+ example = Example2()
+ self.assertEqual(example.color, Color.green)
+
+
+ def test_ctor_with_default_value_none_and_not_allow_none(self):
+ # -- IMPLICIT: default_value = Color.red (first enum-value)
+ class Example2(HasTraits):
+ color1 = UseEnum(Color, default_value=None, allow_none=False)
+ color2 = UseEnum(Color, default_value=None)
+ example = Example2()
+ self.assertEqual(example.color1, Color.red)
+ self.assertEqual(example.color2, Color.red)
+
+ def test_ctor_with_default_value_none_and_allow_none(self):
+ class Example2(HasTraits):
+ color1 = UseEnum(Color, default_value=None, allow_none=True)
+ color2 = UseEnum(Color, allow_none=True)
+
+ example = Example2()
+ self.assertIs(example.color1, None)
+ self.assertIs(example.color2, None)
+
+ def test_assign_none_without_allow_none_resets_to_default_value(self):
+ class Example2(HasTraits):
+ color1 = UseEnum(Color, allow_none=False)
+ color2 = UseEnum(Color)
+
+ example = Example2()
+ example.color1 = None
+ example.color2 = None
+ self.assertIs(example.color1, Color.red)
+ self.assertIs(example.color2, Color.red)
+
+ def test_assign_none_to_enum_or_none(self):
+ class Example2(HasTraits):
+ color = UseEnum(Color, allow_none=True)
+
+ example = Example2()
+ example.color = None
+ self.assertIs(example.color, None)
+
+ def test_assign_bad_value_with_to_enum_or_none(self):
+ class Example2(HasTraits):
+ color = UseEnum(Color, allow_none=True)
+
+ example = Example2()
+ with self.assertRaises(TraitError):
+ example.color = "BAD_VALUE"
+
def test_info(self):
import sys
diff --git a/contrib/python/traitlets/py3/traitlets/tests/utils.py b/contrib/python/traitlets/py3/traitlets/tests/utils.py
index c5ac591435..7cb76bfa2c 100644
--- a/contrib/python/traitlets/py3/traitlets/tests/utils.py
+++ b/contrib/python/traitlets/py3/traitlets/tests/utils.py
@@ -1,42 +1,42 @@
from subprocess import Popen, PIPE
import sys
-import os
-
-
-def get_output_error_code(cmd):
- """Get stdout, stderr, and exit code from running a command"""
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- p = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env)
- out, err = p.communicate()
- out = out.decode('utf8', 'replace')
- err = err.decode('utf8', 'replace')
- return out, err, p.returncode
-
-
-def check_help_output(pkg, subcommand=None):
- """test that `python -m PKG [subcommand] -h` works"""
- cmd = [sys.executable, '-m', pkg]
- if subcommand:
- cmd.extend(subcommand)
- cmd.append('-h')
- out, err, rc = get_output_error_code(cmd)
- assert rc == 0, err
- assert "Traceback" not in err
- assert "Options" in out
- assert "--help-all" in out
- return out, err
-
-
-def check_help_all_output(pkg, subcommand=None):
- """test that `python -m PKG --help-all` works"""
- cmd = [sys.executable, '-m', pkg]
- if subcommand:
- cmd.extend(subcommand)
- cmd.append('--help-all')
- out, err, rc = get_output_error_code(cmd)
- assert rc == 0, err
- assert "Traceback" not in err
- assert "Options" in out
+import os
+
+
+def get_output_error_code(cmd):
+ """Get stdout, stderr, and exit code from running a command"""
+ env = os.environ.copy()
+ env['Y_PYTHON_ENTRY_POINT'] = ':main'
+ p = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env)
+ out, err = p.communicate()
+ out = out.decode('utf8', 'replace')
+ err = err.decode('utf8', 'replace')
+ return out, err, p.returncode
+
+
+def check_help_output(pkg, subcommand=None):
+ """test that `python -m PKG [subcommand] -h` works"""
+ cmd = [sys.executable, '-m', pkg]
+ if subcommand:
+ cmd.extend(subcommand)
+ cmd.append('-h')
+ out, err, rc = get_output_error_code(cmd)
+ assert rc == 0, err
+ assert "Traceback" not in err
+ assert "Options" in out
+ assert "--help-all" in out
+ return out, err
+
+
+def check_help_all_output(pkg, subcommand=None):
+ """test that `python -m PKG --help-all` works"""
+ cmd = [sys.executable, '-m', pkg]
+ if subcommand:
+ cmd.extend(subcommand)
+ cmd.append('--help-all')
+ out, err, rc = get_output_error_code(cmd)
+ assert rc == 0, err
+ assert "Traceback" not in err
+ assert "Options" in out
assert "Class options" in out
- return out, err
+ return out, err
diff --git a/contrib/python/traitlets/py3/ya.make b/contrib/python/traitlets/py3/ya.make
index 46980f21b3..ea546d53e4 100644
--- a/contrib/python/traitlets/py3/ya.make
+++ b/contrib/python/traitlets/py3/ya.make
@@ -44,7 +44,7 @@ RESOURCE_FILES(
)
END()
-
-RECURSE_FOR_TESTS(
+
+RECURSE_FOR_TESTS(
tests
-)
+)
diff --git a/contrib/python/traitlets/ya.make b/contrib/python/traitlets/ya.make
index 3156aae8c5..97655f153c 100644
--- a/contrib/python/traitlets/ya.make
+++ b/contrib/python/traitlets/ya.make
@@ -13,8 +13,8 @@ ENDIF()
NO_LINT()
END()
-
+
RECURSE(
py2
py3
-)
+)
diff --git a/contrib/python/ya.make b/contrib/python/ya.make
index d01ced9f3a..e86f722200 100644
--- a/contrib/python/ya.make
+++ b/contrib/python/ya.make
@@ -173,7 +173,7 @@ RECURSE(
constantly
contextdecorator
contextlib2
- convertdate
+ convertdate
cookies
cov-core
coverage
@@ -197,7 +197,7 @@ RECURSE(
databases
dataclasses-json
datadiff
- dateparser
+ dateparser
dateutil
DAWG-Python
dbf_light
@@ -340,7 +340,7 @@ RECURSE(
environ-config
environs
envoy
- ephem
+ ephem
escapism
etcd3
excel-formulas-calculator
@@ -620,7 +620,7 @@ RECURSE(
meld3
memory-profiler
mercurial
- mistune
+ mistune
mitmproxy
mkdocs
mkdocs-material
@@ -641,14 +641,14 @@ RECURSE(
mpmath
msal
msgpack
- mujson
+ mujson
multidict
multitasking
munch
murmurhash
mutablerecords
- mypy
- mypy-extensions
+ mypy
+ mypy-extensions
mypy-protobuf
mypy-zope
MySQL-python
@@ -656,8 +656,8 @@ RECURSE(
namedlist
natsort
nbclient
- nbconvert
- nbformat
+ nbconvert
+ nbformat
ncclient
ndg-httpsclient
nest-asyncio
@@ -668,7 +668,7 @@ RECURSE(
nltk
normality
nose
- notebook
+ notebook
num2words
numpy
oauth2client
@@ -704,7 +704,7 @@ RECURSE(
panamap
panamap_proto
pandas
- pandocfilters
+ pandocfilters
papermill
parameterized
paramiko
@@ -728,7 +728,7 @@ RECURSE(
paypalrestsdk
pdbpp
pdfminer.six
- pecan
+ pecan
peewee
peewee/playhouse
pefile
@@ -752,7 +752,7 @@ RECURSE(
ply
plyvel
polib
- portalocker
+ portalocker
portpicker
ppdeep
pq
@@ -787,7 +787,7 @@ RECURSE(
py-radix
py3c
py4j
- pyaes
+ pyaes
pyahocorasick
pyaml
pyasn1
@@ -895,7 +895,7 @@ RECURSE(
python-decouple
python-docx
python-dotenv
- python-editor
+ python-editor
python-geohash
python-gnupg
python-hglib
@@ -910,7 +910,7 @@ RECURSE(
python-multipart
python-pptx
python-prctl
- python-rapidjson
+ python-rapidjson
python-saml
python-slugify
python-telegram-bot
@@ -954,7 +954,7 @@ RECURSE(
rfc3986-validator
RPi.GPIO
RPI-ST7789
- rsa
+ rsa
rstr
ruamel.std.pathlib
ruamel.yaml
@@ -985,7 +985,7 @@ RECURSE(
selenium
semantic-version
semver
- Send2Trash
+ Send2Trash
sentinels
sentry-sdk
service-identity
@@ -1051,13 +1051,13 @@ RECURSE(
tablib
tabulate
tblib
- Telethon
+ Telethon
tenacity
tensorflow-estimator
termcolor
- terminado
+ terminado
terminaltables
- testpath
+ testpath
text-unidecode
textdata
texttable
@@ -1094,11 +1094,11 @@ RECURSE(
txredisapi
typecode
typed-argument-parser
- typed-ast
+ typed-ast
typeguard
typer
typing
- typing-extensions
+ typing-extensions
typing-inspect
tzlocal
ua-parser
@@ -1106,7 +1106,7 @@ RECURSE(
uhashring
ujson
ulid2
- umalqurra
+ umalqurra
umongo
unicodecsv
Unidecode
diff --git a/contrib/restricted/boost/libs/filesystem/ya.make b/contrib/restricted/boost/libs/filesystem/ya.make
index bfad363675..7eeccca3f7 100644
--- a/contrib/restricted/boost/libs/filesystem/ya.make
+++ b/contrib/restricted/boost/libs/filesystem/ya.make
@@ -25,7 +25,7 @@ ENDIF()
PEERDIR(
${BOOST_ROOT}/libs/system
)
-
+
SRCS(
src/codecvt_error_category.cpp
src/operations.cpp
diff --git a/contrib/restricted/boost/libs/python/ya.make b/contrib/restricted/boost/libs/python/ya.make
index 8a9607986f..387da91185 100644
--- a/contrib/restricted/boost/libs/python/ya.make
+++ b/contrib/restricted/boost/libs/python/ya.make
@@ -11,7 +11,7 @@ OWNER(
)
INCLUDE(${ARCADIA_ROOT}/contrib/restricted/boost/boost_common.inc)
-
+
CFLAGS(
GLOBAL -DBOOST_PYTHON_STATIC_LIB
)
diff --git a/contrib/restricted/googletest/googlemock/gmock_main/ya.make b/contrib/restricted/googletest/googlemock/gmock_main/ya.make
index eb95d44b72..fd75cce10b 100644
--- a/contrib/restricted/googletest/googlemock/gmock_main/ya.make
+++ b/contrib/restricted/googletest/googlemock/gmock_main/ya.make
@@ -1,5 +1,5 @@
-# Generated by devtools/yamaker.
-
+# Generated by devtools/yamaker.
+
LIBRARY()
OWNER(
@@ -7,7 +7,7 @@ OWNER(
g:cpp-contrib
)
-LICENSE(BSD-3-Clause)
+LICENSE(BSD-3-Clause)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
@@ -22,21 +22,21 @@ ADDINCL(
contrib/restricted/googletest/googlemock
contrib/restricted/googletest/googletest
)
-
-NO_COMPILER_WARNINGS()
-
-NO_UTIL()
-
-CFLAGS(
- GLOBAL -DGTEST_HAS_ABSL=0
- GLOBAL -DGTEST_OS_FUCHSIA=0
- GLOBAL -DGTEST_HAS_STD_WSTRING=1
+
+NO_COMPILER_WARNINGS()
+
+NO_UTIL()
+
+CFLAGS(
+ GLOBAL -DGTEST_HAS_ABSL=0
+ GLOBAL -DGTEST_OS_FUCHSIA=0
+ GLOBAL -DGTEST_HAS_STD_WSTRING=1
)
SRCDIR(contrib/restricted/googletest/googlemock/src)
-
+
SRCS(
- GLOBAL gmock_main.cc
+ GLOBAL gmock_main.cc
)
END()
diff --git a/contrib/restricted/googletest/googlemock/ya.make b/contrib/restricted/googletest/googlemock/ya.make
index 38649ba5fc..39e5c6b2bf 100644
--- a/contrib/restricted/googletest/googlemock/ya.make
+++ b/contrib/restricted/googletest/googlemock/ya.make
@@ -1,5 +1,5 @@
-# Generated by devtools/yamaker.
-
+# Generated by devtools/yamaker.
+
LIBRARY()
OWNER(
@@ -25,16 +25,16 @@ ADDINCL(
contrib/restricted/googletest/googletest
)
-NO_COMPILER_WARNINGS()
-
-NO_UTIL()
-
-CFLAGS(
- GLOBAL -DGTEST_HAS_ABSL=0
- GLOBAL -DGTEST_OS_FUCHSIA=0
- GLOBAL -DGTEST_HAS_STD_WSTRING=1
-)
-
+NO_COMPILER_WARNINGS()
+
+NO_UTIL()
+
+CFLAGS(
+ GLOBAL -DGTEST_HAS_ABSL=0
+ GLOBAL -DGTEST_OS_FUCHSIA=0
+ GLOBAL -DGTEST_HAS_STD_WSTRING=1
+)
+
SRCS(
src/gmock-all.cc
)
diff --git a/contrib/restricted/googletest/googletest/gtest_main/ya.make b/contrib/restricted/googletest/googletest/gtest_main/ya.make
index 98edf7262a..c35257b695 100644
--- a/contrib/restricted/googletest/googletest/gtest_main/ya.make
+++ b/contrib/restricted/googletest/googletest/gtest_main/ya.make
@@ -1,5 +1,5 @@
-# Generated by devtools/yamaker.
-
+# Generated by devtools/yamaker.
+
LIBRARY()
OWNER(
@@ -7,8 +7,8 @@ OWNER(
g:cpp-contrib
)
-LICENSE(BSD-3-Clause)
-
+LICENSE(BSD-3-Clause)
+
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
PEERDIR(
@@ -20,18 +20,18 @@ ADDINCL(
contrib/restricted/googletest/googletest
)
-NO_COMPILER_WARNINGS()
-
-NO_UTIL()
-
-CFLAGS(
- GLOBAL -DGTEST_HAS_ABSL=0
- GLOBAL -DGTEST_OS_FUCHSIA=0
- GLOBAL -DGTEST_HAS_STD_WSTRING=1
+NO_COMPILER_WARNINGS()
+
+NO_UTIL()
+
+CFLAGS(
+ GLOBAL -DGTEST_HAS_ABSL=0
+ GLOBAL -DGTEST_OS_FUCHSIA=0
+ GLOBAL -DGTEST_HAS_STD_WSTRING=1
)
SRCDIR(contrib/restricted/googletest/googletest/src)
-
+
SRCS(
GLOBAL gtest_main.cc
)
diff --git a/contrib/restricted/googletest/googletest/src/gtest-death-test.cc b/contrib/restricted/googletest/googletest/src/gtest-death-test.cc
index 0d184ad24a..67a02012d8 100644
--- a/contrib/restricted/googletest/googletest/src/gtest-death-test.cc
+++ b/contrib/restricted/googletest/googletest/src/gtest-death-test.cc
@@ -66,17 +66,17 @@
# endif // GTEST_OS_QNX
# if GTEST_OS_FUCHSIA
-# error #include <lib/fdio/fd.h>
-# error #include <lib/fdio/io.h>
-# error #include <lib/fdio/spawn.h>
-# error #include <lib/zx/channel.h>
-# error #include <lib/zx/port.h>
-# error #include <lib/zx/process.h>
-# error #include <lib/zx/socket.h>
-# error #include <zircon/processargs.h>
-# error #include <zircon/syscalls.h>
-# error #include <zircon/syscalls/policy.h>
-# error #include <zircon/syscalls/port.h>
+# error #include <lib/fdio/fd.h>
+# error #include <lib/fdio/io.h>
+# error #include <lib/fdio/spawn.h>
+# error #include <lib/zx/channel.h>
+# error #include <lib/zx/port.h>
+# error #include <lib/zx/process.h>
+# error #include <lib/zx/socket.h>
+# error #include <zircon/processargs.h>
+# error #include <zircon/syscalls.h>
+# error #include <zircon/syscalls/policy.h>
+# error #include <zircon/syscalls/port.h>
# endif // GTEST_OS_FUCHSIA
#endif // GTEST_HAS_DEATH_TEST
diff --git a/contrib/restricted/googletest/googletest/src/gtest-port.cc b/contrib/restricted/googletest/googletest/src/gtest-port.cc
index da65822d98..aa7daca68b 100644
--- a/contrib/restricted/googletest/googletest/src/gtest-port.cc
+++ b/contrib/restricted/googletest/googletest/src/gtest-port.cc
@@ -76,8 +76,8 @@
#endif // GTEST_OS_AIX
#if GTEST_OS_FUCHSIA
-# error #include <zircon/process.h>
-# error #include <zircon/syscalls.h>
+# error #include <zircon/process.h>
+# error #include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA
#include "gtest/gtest-spi.h"
diff --git a/contrib/restricted/googletest/googletest/src/gtest.cc b/contrib/restricted/googletest/googletest/src/gtest.cc
index 856da12edb..4bef8ccf93 100644
--- a/contrib/restricted/googletest/googletest/src/gtest.cc
+++ b/contrib/restricted/googletest/googletest/src/gtest.cc
@@ -128,10 +128,10 @@
#endif
#if GTEST_HAS_ABSL
-#error #include "absl/debugging/failure_signal_handler.h"
-#error #include "absl/debugging/stacktrace.h"
-#error #include "absl/debugging/symbolize.h"
-#error #include "absl/strings/str_cat.h"
+#error #include "absl/debugging/failure_signal_handler.h"
+#error #include "absl/debugging/stacktrace.h"
+#error #include "absl/debugging/symbolize.h"
+#error #include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
namespace testing {
diff --git a/contrib/restricted/googletest/googletest/ya.make b/contrib/restricted/googletest/googletest/ya.make
index fd0915ff2c..7121f8d6d4 100644
--- a/contrib/restricted/googletest/googletest/ya.make
+++ b/contrib/restricted/googletest/googletest/ya.make
@@ -1,5 +1,5 @@
-# Generated by devtools/yamaker.
-
+# Generated by devtools/yamaker.
+
LIBRARY()
OWNER(
@@ -15,19 +15,19 @@ PEERDIR(
contrib/libs/re2
)
-ADDINCL(
+ADDINCL(
GLOBAL contrib/restricted/googletest/googletest/include
contrib/restricted/googletest/googletest
-)
-
+)
+
NO_COMPILER_WARNINGS()
-NO_UTIL()
-
+NO_UTIL()
+
CFLAGS(
- GLOBAL -DGTEST_HAS_ABSL=0
- GLOBAL -DGTEST_OS_FUCHSIA=0
- GLOBAL -DGTEST_HAS_STD_WSTRING=1
+ GLOBAL -DGTEST_HAS_ABSL=0
+ GLOBAL -DGTEST_OS_FUCHSIA=0
+ GLOBAL -DGTEST_HAS_STD_WSTRING=1
)
SRCS(
diff --git a/contrib/tools/protoc/plugins/grpc_cpp/ya.make b/contrib/tools/protoc/plugins/grpc_cpp/ya.make
index 7add4ebbad..90dc1dc94b 100644
--- a/contrib/tools/protoc/plugins/grpc_cpp/ya.make
+++ b/contrib/tools/protoc/plugins/grpc_cpp/ya.make
@@ -1,6 +1,6 @@
-# Copy of contrib/libs/grpc/src/compiler/grpc_cpp_plugin
-# Generated by devtools/yamaker.
-
+# Copy of contrib/libs/grpc/src/compiler/grpc_cpp_plugin
+# Generated by devtools/yamaker.
+
OWNER(akastornov g:contrib g:cpp-contrib)
IF (USE_PREBUILT_TOOLS)
diff --git a/contrib/tools/protoc/plugins/grpc_python/ya.make b/contrib/tools/protoc/plugins/grpc_python/ya.make
index 1852d8b6fd..3632059e72 100644
--- a/contrib/tools/protoc/plugins/grpc_python/ya.make
+++ b/contrib/tools/protoc/plugins/grpc_python/ya.make
@@ -1,6 +1,6 @@
-# Copy of contrib/libs/grpc/src/compiler/grpc_python_plugin
-# Generated by devtools/yamaker.
-
+# Copy of contrib/libs/grpc/src/compiler/grpc_python_plugin
+# Generated by devtools/yamaker.
+
OWNER(akastornov g:contrib g:cpp-contrib)
IF (USE_PREBUILT_TOOLS)
diff --git a/contrib/tools/yasm/frontends/yasm/yasm.c b/contrib/tools/yasm/frontends/yasm/yasm.c
index 2bd08890df..57911326b0 100644
--- a/contrib/tools/yasm/frontends/yasm/yasm.c
+++ b/contrib/tools/yasm/frontends/yasm/yasm.c
@@ -50,9 +50,9 @@
/*@null@*/ /*@only@*/ static char *global_prefix = NULL, *global_suffix = NULL;
/*@null@*/ /*@only@*/ static char *list_filename = NULL, *map_filename = NULL;
/*@null@*/ /*@only@*/ static char *machine_name = NULL;
-static char **replace_params;
-static int replace_size = 0;
-static int replace_capacity = 0;
+static char **replace_params;
+static int replace_size = 0;
+static int replace_capacity = 0;
static int special_options = 0;
/*@null@*/ /*@dependent@*/ static yasm_arch *cur_arch = NULL;
/*@null@*/ /*@dependent@*/ static const yasm_arch_module *
@@ -110,7 +110,7 @@ static int opt_preproc_option(char *cmd, /*@null@*/ char *param, int extra);
static int opt_ewmsg_handler(char *cmd, /*@null@*/ char *param, int extra);
static int opt_makedep_handler(char *cmd, /*@null@*/ char *param, int extra);
static int opt_prefix_handler(char *cmd, /*@null@*/ char *param, int extra);
-static int opt_replace_handler(char *cmd, /*@null@*/ char *param, int extra);
+static int opt_replace_handler(char *cmd, /*@null@*/ char *param, int extra);
static int opt_suffix_handler(char *cmd, /*@null@*/ char *param, int extra);
#if defined(CMAKE_BUILD) && defined(BUILD_SHARED_LIBS)
static int opt_plugin_handler(char *cmd, /*@null@*/ char *param, int extra);
@@ -118,7 +118,7 @@ static int opt_plugin_handler(char *cmd, /*@null@*/ char *param, int extra);
#if defined(CMAKE_BUILD) && !defined(BUILD_SHARED_LIBS)
void yasm_init_plugin(void);
-void yasm_plugin_set_replace(const char* replace[], int size);
+void yasm_plugin_set_replace(const char* replace[], int size);
#endif
static /*@only@*/ char *replace_extension(const char *orig, /*@null@*/
@@ -217,8 +217,8 @@ static opt_option options[] =
{ 'N', "plugin", 1, opt_plugin_handler, 0,
N_("load plugin module"), N_("plugin") },
#endif
- { 0, "replace", 1, opt_replace_handler, 0,
- N_("replace names"), N_("replace") },
+ { 0, "replace", 1, opt_replace_handler, 0,
+ N_("replace names"), N_("replace") },
};
/* version message */
@@ -663,10 +663,10 @@ main(int argc, char *argv[])
return EXIT_FAILURE;
}
-#if defined(CMAKE_BUILD) && !defined(BUILD_SHARED_LIBS)
- yasm_plugin_set_replace(replace_params, replace_size);
-#endif
-
+#if defined(CMAKE_BUILD) && !defined(BUILD_SHARED_LIBS)
+ yasm_plugin_set_replace(replace_params, replace_size);
+#endif
+
/* If not already specified, default to bin as the object format. */
if (!cur_objfmt_module) {
if (!objfmt_keyword)
@@ -1199,33 +1199,33 @@ opt_prefix_handler(/*@unused@*/ char *cmd, char *param, /*@unused@*/ int extra)
return 0;
}
-static void
-opt_free_replace(void)
-{
- yasm_xfree(replace_params);
- replace_capacity = 0;
- replace_size = 0;
-}
-
-static int
-opt_replace_handler(/*@unused@*/ char *cmd, char *param, /*@unused@*/ int extra)
-{
- if (replace_capacity == 0) {
- atexit(opt_free_replace);
- }
- if (replace_size == replace_capacity) {
- replace_capacity += 10;
- replace_params = yasm_xrealloc(replace_params, replace_capacity);
- }
-
- assert(param != NULL);
- replace_params[replace_size] = yasm__xstrdup(param);
- ++replace_size;
-
- return 0;
-}
-
+static void
+opt_free_replace(void)
+{
+ yasm_xfree(replace_params);
+ replace_capacity = 0;
+ replace_size = 0;
+}
+
static int
+opt_replace_handler(/*@unused@*/ char *cmd, char *param, /*@unused@*/ int extra)
+{
+ if (replace_capacity == 0) {
+ atexit(opt_free_replace);
+ }
+ if (replace_size == replace_capacity) {
+ replace_capacity += 10;
+ replace_params = yasm_xrealloc(replace_params, replace_capacity);
+ }
+
+ assert(param != NULL);
+ replace_params[replace_size] = yasm__xstrdup(param);
+ ++replace_size;
+
+ return 0;
+}
+
+static int
opt_suffix_handler(/*@unused@*/ char *cmd, char *param, /*@unused@*/ int extra)
{
if (global_suffix)
diff --git a/contrib/tools/yasm/libyasm/dbgfmt.h b/contrib/tools/yasm/libyasm/dbgfmt.h
index 2e5ea867ee..fb5bf4cfbb 100644
--- a/contrib/tools/yasm/libyasm/dbgfmt.h
+++ b/contrib/tools/yasm/libyasm/dbgfmt.h
@@ -69,15 +69,15 @@ struct yasm_dbgfmt_module {
*/
void (*generate) (yasm_object *object, yasm_linemap *linemap,
yasm_errwarns *errwarns);
-
- /**
- * --replace params
- */
- const char** replace_map;
- /**
- * Number of elements in replace_map
- */
- int replace_map_size;
+
+ /**
+ * --replace params
+ */
+ const char** replace_map;
+ /**
+ * Number of elements in replace_map
+ */
+ int replace_map_size;
};
/** Get the keyword used to select a debug format.
diff --git a/contrib/tools/yasm/libyasm/objfmt.h b/contrib/tools/yasm/libyasm/objfmt.h
index a8b5f8a161..48e26a7ce9 100644
--- a/contrib/tools/yasm/libyasm/objfmt.h
+++ b/contrib/tools/yasm/libyasm/objfmt.h
@@ -123,15 +123,15 @@ struct yasm_objfmt_module {
/*@observer@*/ /*@null@*/ yasm_symrec *
(*get_special_sym)(yasm_object *object, const char *name,
const char *parser);
-
- /**
- * --replace params
- */
- const char** replace_map;
- /**
- * Number of elements in replace_map
- */
- int replace_map_size;
+
+ /**
+ * --replace params
+ */
+ const char** replace_map;
+ /**
+ * Number of elements in replace_map
+ */
+ int replace_map_size;
};
/** Create object format.
diff --git a/contrib/tools/yasm/libyasm/replace_path.c b/contrib/tools/yasm/libyasm/replace_path.c
index 0deba70a6b..b0301ef705 100644
--- a/contrib/tools/yasm/libyasm/replace_path.c
+++ b/contrib/tools/yasm/libyasm/replace_path.c
@@ -1,54 +1,54 @@
-/*
- * Copyright (c) 1988, 1993, 2019
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-#include "util.h"
-
-char * yasm_replace_path(const char* replace_map[], int size, const char* str, int pref_len) {
- int i;
- for (i=0; i<size; i++) {
- const char* pos = strchr(replace_map[i], '=');
- if (!pos) {
- continue;
- }
- int repl_size = pos - replace_map[i];
- if (pref_len < repl_size) {
- continue;
- }
- if (strncmp(replace_map[i], str, repl_size)) {
- continue;
- }
- int subs_size = strlen(replace_map[i]) - (repl_size + 1);
- int size = subs_size + pref_len - repl_size + 1;
- char* out = yasm_xmalloc(size);
- strncpy(out, pos + 1, subs_size);
- strncpy(out + subs_size, str + repl_size, pref_len - repl_size);
- out[size - 1] = '\0';
- return out;
- }
- return yasm__xstrndup(str, pref_len);
-}
+/*
+ * Copyright (c) 1988, 1993, 2019
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+#include "util.h"
+
+char * yasm_replace_path(const char* replace_map[], int size, const char* str, int pref_len) {
+ int i;
+ for (i=0; i<size; i++) {
+ const char* pos = strchr(replace_map[i], '=');
+ if (!pos) {
+ continue;
+ }
+ int repl_size = pos - replace_map[i];
+ if (pref_len < repl_size) {
+ continue;
+ }
+ if (strncmp(replace_map[i], str, repl_size)) {
+ continue;
+ }
+ int subs_size = strlen(replace_map[i]) - (repl_size + 1);
+ int size = subs_size + pref_len - repl_size + 1;
+ char* out = yasm_xmalloc(size);
+ strncpy(out, pos + 1, subs_size);
+ strncpy(out + subs_size, str + repl_size, pref_len - repl_size);
+ out[size - 1] = '\0';
+ return out;
+ }
+ return yasm__xstrndup(str, pref_len);
+}
diff --git a/contrib/tools/yasm/libyasm/section.c b/contrib/tools/yasm/libyasm/section.c
index 729d7770a4..903d3eb1fe 100644
--- a/contrib/tools/yasm/libyasm/section.c
+++ b/contrib/tools/yasm/libyasm/section.c
@@ -220,7 +220,7 @@ yasm_object_create(const char *src_filename, const char *obj_filename,
int matched, i;
object->src_filename = yasm__xstrdup(src_filename);
- object->deb_filename = NULL;
+ object->deb_filename = NULL;
object->obj_filename = yasm__xstrdup(obj_filename);
/* No prefix/suffix */
@@ -385,8 +385,8 @@ yasm_object_set_source_fn(yasm_object *object, const char *src_filename)
{
yasm_xfree(object->src_filename);
object->src_filename = yasm__xstrdup(src_filename);
- yasm_xfree(object->deb_filename);
- object->deb_filename = NULL;
+ yasm_xfree(object->deb_filename);
+ object->deb_filename = NULL;
}
void
@@ -483,7 +483,7 @@ yasm_object_destroy(yasm_object *object)
/* Delete associated filenames */
yasm_xfree(object->src_filename);
- yasm_xfree(object->deb_filename);
+ yasm_xfree(object->deb_filename);
yasm_xfree(object->obj_filename);
/* Delete symbol table */
diff --git a/contrib/tools/yasm/libyasm/section.h b/contrib/tools/yasm/libyasm/section.h
index 521031f3a5..7ed9696725 100644
--- a/contrib/tools/yasm/libyasm/section.h
+++ b/contrib/tools/yasm/libyasm/section.h
@@ -48,7 +48,7 @@ struct yasm_reloc {
/** An object. This is the internal representation of an object file. */
struct yasm_object {
/*@owned@*/ char *src_filename; /**< Source filename */
- /*@owned@*/ char *deb_filename; /**< Debug filename */
+ /*@owned@*/ char *deb_filename; /**< Debug filename */
/*@owned@*/ char *obj_filename; /**< Object filename */
/*@owned@*/ yasm_symtab *symtab; /**< Symbol table */
diff --git a/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-info.c b/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-info.c
index 96d24db06a..667665e89c 100644
--- a/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-info.c
+++ b/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-info.c
@@ -326,21 +326,21 @@ yasm_dwarf2__generate_info(yasm_object *object, yasm_section *debug_line,
/* input filename */
abc->len += dwarf2_add_abbrev_attr(abbrev, DW_AT_name, DW_FORM_string);
- if (!object->deb_filename) {
- object->deb_filename = yasm_replace_path(
- dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
- object->src_filename, strlen(object->src_filename));
- }
- dwarf2_append_str(debug_info, object->deb_filename);
+ if (!object->deb_filename) {
+ object->deb_filename = yasm_replace_path(
+ dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
+ object->src_filename, strlen(object->src_filename));
+ }
+ dwarf2_append_str(debug_info, object->deb_filename);
/* compile directory (current working directory) */
abc->len += dwarf2_add_abbrev_attr(abbrev, DW_AT_comp_dir, DW_FORM_string);
buf = yasm__getcwd();
- char * new_cwd_name = yasm_replace_path(
- dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
- buf, strlen(buf));
- dwarf2_append_str(debug_info, new_cwd_name);
- yasm_xfree(new_cwd_name);
+ char * new_cwd_name = yasm_replace_path(
+ dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
+ buf, strlen(buf));
+ dwarf2_append_str(debug_info, new_cwd_name);
+ yasm_xfree(new_cwd_name);
yasm_xfree(buf);
/* producer - assembler name */
diff --git a/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-line.c b/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-line.c
index 14639ca429..8f21363be9 100644
--- a/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-line.c
+++ b/contrib/tools/yasm/modules/dbgfmts/dwarf2/dwarf2-line.c
@@ -532,21 +532,21 @@ dwarf2_generate_line_bc(yasm_bytecode *bc, /*@null@*/ void *d)
yasm_linemap_lookup(info->linemap, bc->line, &pathname, &info->loc.line);
dirlen = yasm__splitpath(pathname, &filename);
- char * new_dir_name = yasm_replace_path(
- dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
- pathname, dirlen);
- dirlen = strlen(new_dir_name);
+ char * new_dir_name = yasm_replace_path(
+ dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
+ pathname, dirlen);
+ dirlen = strlen(new_dir_name);
/* Find file index; just linear search it unless it was the last used */
if (info->lastfile > 0
&& dwarf2_filename_equals(&dbgfmt_dwarf2->filenames[info->lastfile-1],
- dbgfmt_dwarf2->dirs, new_dir_name, dirlen,
+ dbgfmt_dwarf2->dirs, new_dir_name, dirlen,
filename))
info->loc.file = info->lastfile;
else {
for (i=0; i<dbgfmt_dwarf2->filenames_size; i++) {
if (dwarf2_filename_equals(&dbgfmt_dwarf2->filenames[i],
- dbgfmt_dwarf2->dirs, new_dir_name, dirlen,
+ dbgfmt_dwarf2->dirs, new_dir_name, dirlen,
filename))
break;
}
@@ -555,7 +555,7 @@ dwarf2_generate_line_bc(yasm_bytecode *bc, /*@null@*/ void *d)
info->loc.file = i+1;
info->lastfile = i+1;
}
- yasm_xfree(new_dir_name);
+ yasm_xfree(new_dir_name);
if (dwarf2_dbgfmt_gen_line_op(info->debug_line, info->state, &info->loc,
NULL))
return 1;
@@ -682,11 +682,11 @@ static int
dwarf2_generate_filename(const char *filename, void *d)
{
yasm_dbgfmt_dwarf2 *dbgfmt_dwarf2 = (yasm_dbgfmt_dwarf2 *)d;
- char *deb_name = yasm_replace_path(
- dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
- filename, strlen(filename));
- dwarf2_dbgfmt_add_file(dbgfmt_dwarf2, 0, deb_name);
- yasm_xfree(deb_name);
+ char *deb_name = yasm_replace_path(
+ dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
+ filename, strlen(filename));
+ dwarf2_dbgfmt_add_file(dbgfmt_dwarf2, 0, deb_name);
+ yasm_xfree(deb_name);
return 0;
}
@@ -1130,9 +1130,9 @@ yasm_dwarf2__dir_file(yasm_object *object, yasm_valparamhead *valparams,
if (yasm_vp_string(vp)) {
/* Just a bare filename */
yasm_object_set_source_fn(object, yasm_vp_string(vp));
- object->deb_filename = yasm_replace_path(
- dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
- yasm_vp_string(vp), strlen(yasm_vp_string(vp)));
+ object->deb_filename = yasm_replace_path(
+ dbgfmt_dwarf2->dbgfmt.module->replace_map, dbgfmt_dwarf2->dbgfmt.module->replace_map_size,
+ yasm_vp_string(vp), strlen(yasm_vp_string(vp)));
return;
}
diff --git a/contrib/tools/yasm/modules/init_plugin.c b/contrib/tools/yasm/modules/init_plugin.c
index 86ae4c53f9..e4ca32da7f 100644
--- a/contrib/tools/yasm/modules/init_plugin.c
+++ b/contrib/tools/yasm/modules/init_plugin.c
@@ -64,23 +64,23 @@ yasm_init_plugin(void)
yasm_register_module(YASM_MODULE_OBJFMT, "xdf", &yasm_xdf_LTX_objfmt);
}
-void
-yasm_plugin_set_replace(const char* replace_params[], int size) {
- yasm_dwarf2_LTX_dbgfmt.replace_map = replace_params;
- yasm_dwarf2_LTX_dbgfmt.replace_map_size = size;
- yasm_elf_LTX_objfmt.replace_map = replace_params;
- yasm_elf_LTX_objfmt.replace_map_size = size;
- yasm_elf32_LTX_objfmt.replace_map = replace_params;
- yasm_elf32_LTX_objfmt.replace_map_size = size;
- yasm_elf64_LTX_objfmt.replace_map = replace_params;
- yasm_elf64_LTX_objfmt.replace_map_size = size;
- yasm_elfx32_LTX_objfmt.replace_map = replace_params;
- yasm_elfx32_LTX_objfmt.replace_map_size = size;
-
- yasm_macho_LTX_objfmt.replace_map = replace_params;
- yasm_macho_LTX_objfmt.replace_map_size = size;
- yasm_macho32_LTX_objfmt.replace_map = replace_params;
- yasm_macho32_LTX_objfmt.replace_map_size = size;
- yasm_macho64_LTX_objfmt.replace_map = replace_params;
- yasm_macho64_LTX_objfmt.replace_map_size = size;
-}
+void
+yasm_plugin_set_replace(const char* replace_params[], int size) {
+ yasm_dwarf2_LTX_dbgfmt.replace_map = replace_params;
+ yasm_dwarf2_LTX_dbgfmt.replace_map_size = size;
+ yasm_elf_LTX_objfmt.replace_map = replace_params;
+ yasm_elf_LTX_objfmt.replace_map_size = size;
+ yasm_elf32_LTX_objfmt.replace_map = replace_params;
+ yasm_elf32_LTX_objfmt.replace_map_size = size;
+ yasm_elf64_LTX_objfmt.replace_map = replace_params;
+ yasm_elf64_LTX_objfmt.replace_map_size = size;
+ yasm_elfx32_LTX_objfmt.replace_map = replace_params;
+ yasm_elfx32_LTX_objfmt.replace_map_size = size;
+
+ yasm_macho_LTX_objfmt.replace_map = replace_params;
+ yasm_macho_LTX_objfmt.replace_map_size = size;
+ yasm_macho32_LTX_objfmt.replace_map = replace_params;
+ yasm_macho32_LTX_objfmt.replace_map_size = size;
+ yasm_macho64_LTX_objfmt.replace_map = replace_params;
+ yasm_macho64_LTX_objfmt.replace_map_size = size;
+}
diff --git a/contrib/tools/yasm/modules/objfmts/coff/coff-objfmt.c b/contrib/tools/yasm/modules/objfmts/coff/coff-objfmt.c
index 388b09af32..9f7e76bd30 100644
--- a/contrib/tools/yasm/modules/objfmts/coff/coff-objfmt.c
+++ b/contrib/tools/yasm/modules/objfmts/coff/coff-objfmt.c
@@ -1192,13 +1192,13 @@ coff_objfmt_output(yasm_object *object, FILE *f, int all_syms,
if (objfmt_coff->filesym_data->aux[0].fname)
yasm_xfree(objfmt_coff->filesym_data->aux[0].fname);
- if (!object->deb_filename) {
- object->deb_filename = yasm_replace_path(
- objfmt_coff->objfmt.module->replace_map, objfmt_coff->objfmt.module->replace_map_size,
- object->src_filename, strlen(object->src_filename));
- }
+ if (!object->deb_filename) {
+ object->deb_filename = yasm_replace_path(
+ objfmt_coff->objfmt.module->replace_map, objfmt_coff->objfmt.module->replace_map_size,
+ object->src_filename, strlen(object->src_filename));
+ }
objfmt_coff->filesym_data->aux[0].fname =
- yasm__xstrdup(object->deb_filename);
+ yasm__xstrdup(object->deb_filename);
/* Force all syms for win64 because they're needed for relocations.
* FIXME: Not *all* syms need to be output, only the ones needed for
diff --git a/contrib/tools/yasm/modules/objfmts/elf/elf-objfmt.c b/contrib/tools/yasm/modules/objfmts/elf/elf-objfmt.c
index 6874a1689f..20fc1dec0d 100644
--- a/contrib/tools/yasm/modules/objfmts/elf/elf-objfmt.c
+++ b/contrib/tools/yasm/modules/objfmts/elf/elf-objfmt.c
@@ -370,14 +370,14 @@ elf_objfmt_create_common(yasm_object *object, yasm_objfmt_module *module,
/* FIXME: misuse of NULL bytecode here; it works, but only barely. */
filesym = yasm_symtab_define_label(object->symtab, ".file", NULL, 0, 0);
- if (!object->deb_filename) {
- object->deb_filename = yasm_replace_path(
- module->replace_map, module->replace_map_size,
- object->src_filename, strlen(object->src_filename));
- }
+ if (!object->deb_filename) {
+ object->deb_filename = yasm_replace_path(
+ module->replace_map, module->replace_map_size,
+ object->src_filename, strlen(object->src_filename));
+ }
/* Put in current input filename; we'll replace it in output() */
objfmt_elf->file_strtab_entry =
- elf_strtab_append_str(objfmt_elf->strtab, object->deb_filename);
+ elf_strtab_append_str(objfmt_elf->strtab, object->deb_filename);
entry = elf_symtab_entry_create(objfmt_elf->file_strtab_entry, filesym);
yasm_symrec_add_data(filesym, &elf_symrec_data, entry);
elf_symtab_set_nonzero(entry, NULL, SHN_ABS, STB_LOCAL, STT_FILE, NULL,
@@ -758,14 +758,14 @@ elf_objfmt_output(yasm_object *object, FILE *f, int all_syms,
info.f = f;
info.GOT_sym = yasm_symtab_get(object->symtab, "_GLOBAL_OFFSET_TABLE_");
- if (!object->deb_filename) {
- object->deb_filename = yasm_replace_path(
- objfmt_elf->objfmt.module->replace_map, objfmt_elf->objfmt.module->replace_map_size,
- object->src_filename, strlen(object->src_filename));
- }
+ if (!object->deb_filename) {
+ object->deb_filename = yasm_replace_path(
+ objfmt_elf->objfmt.module->replace_map, objfmt_elf->objfmt.module->replace_map_size,
+ object->src_filename, strlen(object->src_filename));
+ }
/* Update filename strtab */
elf_strtab_entry_set_str(objfmt_elf->file_strtab_entry,
- object->deb_filename);
+ object->deb_filename);
/* Allocate space for Ehdr by seeking forward */
if (fseek(f, (long)(elf_proghead_get_size()), SEEK_SET) < 0) {
diff --git a/contrib/tools/yasm/util.h b/contrib/tools/yasm/util.h
index 4174648a22..48c77a2555 100644
--- a/contrib/tools/yasm/util.h
+++ b/contrib/tools/yasm/util.h
@@ -162,6 +162,6 @@ __asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
#define NELEMS(array) (sizeof(array) / sizeof(array[0]))
#endif
-char * yasm_replace_path(const char* replace_map[], int size, const char* str, int pref_len);
-
+char * yasm_replace_path(const char* replace_map[], int size, const char* str, int pref_len);
+
#endif
diff --git a/library/cpp/grpc/client/grpc_client_low.h b/library/cpp/grpc/client/grpc_client_low.h
index ab0a0627be..f7aba62b69 100644
--- a/library/cpp/grpc/client/grpc_client_low.h
+++ b/library/cpp/grpc/client/grpc_client_low.h
@@ -4,8 +4,8 @@
#include <util/thread/factory.h>
#include <grpc++/grpc++.h>
-#include <grpc++/support/async_stream.h>
-#include <grpc++/support/async_unary_call.h>
+#include <grpc++/support/async_stream.h>
+#include <grpc++/support/async_unary_call.h>
#include <deque>
#include <typeindex>
diff --git a/library/cpp/grpc/server/grpc_request.h b/library/cpp/grpc/server/grpc_request.h
index 5bd8d3902b..ea48222562 100644
--- a/library/cpp/grpc/server/grpc_request.h
+++ b/library/cpp/grpc/server/grpc_request.h
@@ -19,8 +19,8 @@
#include <grpc++/server.h>
#include <grpc++/server_context.h>
-#include <grpc++/support/async_stream.h>
-#include <grpc++/support/async_unary_call.h>
+#include <grpc++/support/async_stream.h>
+#include <grpc++/support/async_unary_call.h>
#include <grpc++/support/byte_buffer.h>
#include <grpc++/impl/codegen/async_stream.h>
diff --git a/library/cpp/svnversion/svn_interface.c b/library/cpp/svnversion/svn_interface.c
index 12884956b1..c3e2f7bb9c 100644
--- a/library/cpp/svnversion/svn_interface.c
+++ b/library/cpp/svnversion/svn_interface.c
@@ -1 +1 @@
-// See build/scripts/c_templates/svn_interface.c instead.
+// See build/scripts/c_templates/svn_interface.c instead.
diff --git a/library/cpp/svnversion/svnversion.h b/library/cpp/svnversion/svnversion.h
index b99615daa9..6beae68969 100644
--- a/library/cpp/svnversion/svnversion.h
+++ b/library/cpp/svnversion/svnversion.h
@@ -7,7 +7,7 @@
#define PRINT_VERSION_EX(opts) PrintSvnVersionAndExitEx(argc, (char**)argv, opts)
#endif
-#include <util/system/compiler.h>
-
-// Automatically generated functions.
-#include "build/scripts/c_templates/svnversion.h"
+#include <util/system/compiler.h>
+
+// Automatically generated functions.
+#include "build/scripts/c_templates/svnversion.h"
diff --git a/library/cpp/svnversion/test/main.cpp b/library/cpp/svnversion/test/main.cpp
index 3c8209047f..916e4ef6ca 100644
--- a/library/cpp/svnversion/test/main.cpp
+++ b/library/cpp/svnversion/test/main.cpp
@@ -1,30 +1,30 @@
-#include <build/scripts/c_templates/svnversion.h>
-#include <util/stream/str.h>
-#include <util/system/compiler.h>
-#include <util/stream/output.h>
-
+#include <build/scripts/c_templates/svnversion.h>
+#include <util/stream/str.h>
+#include <util/system/compiler.h>
+#include <util/stream/output.h>
+
// ya make -DFORCE_VCS_INFO_UPDATE --vcs-file=<vcs.json> library/cpp/svnversion/test/
-// ./library/svnversion/test/test[.exe]
-int main() {
- Cout << "GetProgramSvnVersion(): " << GetProgramSvnVersion() << Endl;
- Cout << "PrintProgramSvnVersion(): " << Endl; PrintProgramSvnVersion();
- Cout << "GetArcadiaSourcePath(): " << GetArcadiaSourcePath() << Endl;
- Cout << "GetArcadiaSourceUrl(): " << GetArcadiaSourceUrl() << Endl;
- Cout << "GetArcadiaLastChange(): " << GetArcadiaLastChange() << Endl;
- Cout << "GetArcadiaLastChangeNum(): " << GetArcadiaLastChangeNum() << Endl;
- Cout << "GetArcadiaLastAuthor(): " << GetArcadiaLastAuthor() << Endl;
- Cout << "GetProgramSvnRevision(): " << GetProgramSvnRevision() << Endl;
- Cout << "GetProgramHash(): " << GetProgramHash() << Endl;
- Cout << "GetProgramCommitId(): " << GetProgramCommitId() << Endl;
- Cout << "GetProgramScmData(): " << GetProgramScmData() << Endl;
- Cout << "GetProgramBuildUser(): " << GetProgramBuildUser() << Endl;
- Cout << "GetProgramBuildHost(): " << GetProgramBuildHost() << Endl;
- Cout << "GetProgramBuildDate(): " << GetProgramBuildDate() << Endl;
- Cout << "GetVCS(): " << GetVCS() << Endl;
- Cout << "GetBranch(): " << GetBranch() << Endl;
- Cout << "GetTag(): " << GetTag() << Endl;
- Cout << "GetArcadiaPatchNumber(): " << GetArcadiaPatchNumber() << Endl;
+// ./library/svnversion/test/test[.exe]
+int main() {
+ Cout << "GetProgramSvnVersion(): " << GetProgramSvnVersion() << Endl;
+ Cout << "PrintProgramSvnVersion(): " << Endl; PrintProgramSvnVersion();
+ Cout << "GetArcadiaSourcePath(): " << GetArcadiaSourcePath() << Endl;
+ Cout << "GetArcadiaSourceUrl(): " << GetArcadiaSourceUrl() << Endl;
+ Cout << "GetArcadiaLastChange(): " << GetArcadiaLastChange() << Endl;
+ Cout << "GetArcadiaLastChangeNum(): " << GetArcadiaLastChangeNum() << Endl;
+ Cout << "GetArcadiaLastAuthor(): " << GetArcadiaLastAuthor() << Endl;
+ Cout << "GetProgramSvnRevision(): " << GetProgramSvnRevision() << Endl;
+ Cout << "GetProgramHash(): " << GetProgramHash() << Endl;
+ Cout << "GetProgramCommitId(): " << GetProgramCommitId() << Endl;
+ Cout << "GetProgramScmData(): " << GetProgramScmData() << Endl;
+ Cout << "GetProgramBuildUser(): " << GetProgramBuildUser() << Endl;
+ Cout << "GetProgramBuildHost(): " << GetProgramBuildHost() << Endl;
+ Cout << "GetProgramBuildDate(): " << GetProgramBuildDate() << Endl;
+ Cout << "GetVCS(): " << GetVCS() << Endl;
+ Cout << "GetBranch(): " << GetBranch() << Endl;
+ Cout << "GetTag(): " << GetTag() << Endl;
+ Cout << "GetArcadiaPatchNumber(): " << GetArcadiaPatchNumber() << Endl;
Cout << "GetVCSDirty(): " << GetVCSDirty() << Endl;
- return 0;
-}
-
+ return 0;
+}
+
diff --git a/library/cpp/svnversion/test/ya.make b/library/cpp/svnversion/test/ya.make
index 59c0a2d970..38649c24e7 100644
--- a/library/cpp/svnversion/test/ya.make
+++ b/library/cpp/svnversion/test/ya.make
@@ -1,6 +1,6 @@
OWNER(g:cpp-contrib)
-PROGRAM()
+PROGRAM()
PEERDIR(library/cpp/svnversion)
-SRCS(main.cpp)
-END()
+SRCS(main.cpp)
+END()
diff --git a/library/cpp/svnversion/ya.make b/library/cpp/svnversion/ya.make
index 04e1a4c4fd..c6880e172a 100644
--- a/library/cpp/svnversion/ya.make
+++ b/library/cpp/svnversion/ya.make
@@ -4,9 +4,9 @@ LIBRARY()
SRCS(
svnversion.cpp
- svn_interface.c
+ svn_interface.c
)
END()
-RECURSE(
- test
-)
+RECURSE(
+ test
+)
diff --git a/library/python/fs/__init__.py b/library/python/fs/__init__.py
index b1b7cde079..3c596f0e42 100644
--- a/library/python/fs/__init__.py
+++ b/library/python/fs/__init__.py
@@ -6,7 +6,7 @@ import logging
import os
import random
import shutil
-import six
+import six
import stat
import sys
@@ -128,7 +128,7 @@ def remove_dir(path):
def fix_path_encoding(path):
- return library.python.strings.to_str(path, library.python.strings.fs_encoding())
+ return library.python.strings.to_str(path, library.python.strings.fs_encoding())
# File/directory remove
@@ -201,7 +201,7 @@ def hardlink_or_copy(src, lnk):
def should_fallback_to_copy(exc):
if WindowsError is not None and isinstance(exc, WindowsError) and exc.winerror == 1142: # too many hardlinks
return True
- # cross-device hardlink or too many hardlinks, or some known WSL error
+ # cross-device hardlink or too many hardlinks, or some known WSL error
if isinstance(exc, OSError) and exc.errno in (
errno.EXDEV,
errno.EMLINK,
@@ -217,7 +217,7 @@ def hardlink_or_copy(src, lnk):
except Exception as e:
logger.debug('Failed to hardlink %s to %s with error %s, will copy it', src, lnk, repr(e))
if should_fallback_to_copy(e):
- copy2(src, lnk, follow_symlinks=False)
+ copy2(src, lnk, follow_symlinks=False)
else:
raise
@@ -234,19 +234,19 @@ def symlink(src, lnk):
os.symlink(src, lnk)
-# shutil.copy2 with follow_symlinks=False parameter (Unix only)
-def copy2(src, lnk, follow_symlinks=True):
- if six.PY3:
- shutil.copy2(src, lnk, follow_symlinks=follow_symlinks)
- return
-
- if follow_symlinks or not os.path.islink(src):
- shutil.copy2(src, lnk)
- return
-
- symlink(os.readlink(src), lnk)
-
-
+# shutil.copy2 with follow_symlinks=False parameter (Unix only)
+def copy2(src, lnk, follow_symlinks=True):
+ if six.PY3:
+ shutil.copy2(src, lnk, follow_symlinks=follow_symlinks)
+ return
+
+ if follow_symlinks or not os.path.islink(src):
+ shutil.copy2(src, lnk)
+ return
+
+ symlink(os.readlink(src), lnk)
+
+
# Recursively hardlink directory
# Uses plain hardlink for files
# Dst must not exist
@@ -299,12 +299,12 @@ def read_file(path, binary=True):
@errorfix_win
def read_file_unicode(path, binary=True, enc='utf-8'):
if not binary:
- if six.PY2:
- with open(path, 'r') as f:
- return library.python.strings.to_unicode(f.read(), enc)
- else:
- with open(path, 'r', encoding=enc) as f:
- return f.read()
+ if six.PY2:
+ with open(path, 'r') as f:
+ return library.python.strings.to_unicode(f.read(), enc)
+ else:
+ with open(path, 'r', encoding=enc) as f:
+ return f.read()
# codecs.open is always binary
with codecs.open(path, 'r', encoding=enc, errors=library.python.strings.ENCODING_ERRORS_POLICY) as f:
return f.read()
@@ -417,9 +417,9 @@ def copytree3(
else:
ignored_names = set()
- if not (dirs_exist_ok and os.path.isdir(dst)):
- os.makedirs(dst)
-
+ if not (dirs_exist_ok and os.path.isdir(dst)):
+ os.makedirs(dst)
+
errors = []
for name in names:
if name in ignored_names:
@@ -441,7 +441,7 @@ def copytree3(
# otherwise let the copy occurs. copy2 will raise an error
copy_function(srcname, dstname)
elif os.path.isdir(srcname):
- copytree3(srcname, dstname, symlinks, ignore, copy_function, dirs_exist_ok=dirs_exist_ok)
+ copytree3(srcname, dstname, symlinks, ignore, copy_function, dirs_exist_ok=dirs_exist_ok)
else:
# Will raise a SpecialFileError for unsupported file types
copy_function(srcname, dstname)
diff --git a/library/python/fs/test/test_fs.py b/library/python/fs/test/test_fs.py
index 9e2c70c069..00bd7e3d29 100644
--- a/library/python/fs/test/test_fs.py
+++ b/library/python/fs/test/test_fs.py
@@ -4,10 +4,10 @@ import errno
import os
import pytest
import shutil
-import six
+import six
import library.python.fs
-import library.python.strings
+import library.python.strings
import library.python.tmp
import library.python.windows
@@ -23,7 +23,7 @@ def in_env(case):
def mkfile(path, data=''):
- with open(path, 'wb') as f:
+ with open(path, 'wb') as f:
if data:
f.write(data) if isinstance(data, six.binary_type) else f.write(
data.encode(library.python.strings.fs_encoding())
@@ -40,8 +40,8 @@ def mktree_example(path, name):
def file_data(path):
- with open(path, 'rb') as f:
- return f.read().decode('utf-8')
+ with open(path, 'rb') as f:
+ return f.read().decode('utf-8')
def serialize_tree(path):
@@ -92,8 +92,8 @@ def test_errorfix_win():
erroneous_func()
assert errinfo.value.errno == errno.EACCES
assert errinfo.value.filename == 'unknown/file'
- # See transcode_error, which encodes strerror, in library/python/windows/__init__.py
- assert isinstance(errinfo.value.strerror, (six.binary_type, six.text_type))
+ # See transcode_error, which encodes strerror, in library/python/windows/__init__.py
+ assert isinstance(errinfo.value.strerror, (six.binary_type, six.text_type))
assert errinfo.value.strerror
@@ -101,8 +101,8 @@ def test_custom_fs_error():
with pytest.raises(OSError) as errinfo:
raise library.python.fs.CustomFsError(errno.EACCES, filename='some/file')
assert errinfo.value.errno == errno.EACCES
- # See transcode_error, which encodes strerror, in library/python/windows/__init__.py
- assert isinstance(errinfo.value.strerror, (six.binary_type, six.text_type))
+ # See transcode_error, which encodes strerror, in library/python/windows/__init__.py
+ assert isinstance(errinfo.value.strerror, (six.binary_type, six.text_type))
assert errinfo.value.filename == 'some/file'
@@ -806,14 +806,14 @@ def test_copy_tree_file_exists(path):
@in_env
def test_read_file(path):
mkfile(path('src'), 'SRC')
- assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == 'SRC'
+ assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == 'SRC'
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC'
@in_env
def test_read_file_empty(path):
mkfile(path('src'))
- assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == ''
+ assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == ''
assert library.python.fs.read_file(path('src'), binary=False) == ''
@@ -834,7 +834,7 @@ def test_read_file_multiline_crlf(path):
library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding())
== 'SRC line 1\r\nSRC line 2\r\n'
)
- if library.python.windows.on_win() or six.PY3: # universal newlines are by default in text mode in python3
+ if library.python.windows.on_win() or six.PY3: # universal newlines are by default in text mode in python3
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC line 1\nSRC line 2\n'
else:
assert library.python.fs.read_file(path('src'), binary=False) == 'SRC line 1\r\nSRC line 2\r\n'
@@ -879,7 +879,7 @@ def test_read_file_unicode_multiline_crlf(path):
mkfile(path('src_cp1251'), s.encode('cp1251'))
assert library.python.fs.read_file_unicode(path('src')) == s
assert library.python.fs.read_file_unicode(path('src_cp1251'), enc='cp1251') == s
- if library.python.windows.on_win() or six.PY3: # universal newlines are by default in text mode in python3
+ if library.python.windows.on_win() or six.PY3: # universal newlines are by default in text mode in python3
assert library.python.fs.read_file_unicode(path('src'), binary=False) == u'АБВ\nИ еще\n'
assert library.python.fs.read_file_unicode(path('src_cp1251'), binary=False, enc='cp1251') == u'АБВ\nИ еще\n'
else:
@@ -984,14 +984,14 @@ def test_hardlink_or_copy():
def test_remove_tree_unicode():
path = u"test_remove_tree_unicode/русский".encode("utf-8")
os.makedirs(path)
- library.python.fs.remove_tree(six.text_type("test_remove_tree_unicode"))
+ library.python.fs.remove_tree(six.text_type("test_remove_tree_unicode"))
assert not os.path.exists("test_remove_tree_unicode")
def test_remove_tree_safe_unicode():
path = u"test_remove_tree_safe_unicode/русский".encode("utf-8")
os.makedirs(path)
- library.python.fs.remove_tree_safe(six.text_type("test_remove_tree_safe_unicode"))
+ library.python.fs.remove_tree_safe(six.text_type("test_remove_tree_safe_unicode"))
assert not os.path.exists("test_remove_tree_safe_unicode")
@@ -1011,14 +1011,14 @@ def test_copy_tree_custom_copy_function():
assert len(copied) == 2
assert yatest.common.work_path("test_copy_tree_dst/deepper/deepper.txt") in copied
assert yatest.common.work_path("test_copy_tree_dst/deepper/inner/inner.txt") in copied
-
-
-def test_copy2():
- library.python.fs.symlink("non-existent", "link")
- library.python.fs.copy2("link", "link2", follow_symlinks=False)
-
- assert os.path.islink("link2")
- assert os.readlink("link2") == "non-existent"
+
+
+def test_copy2():
+ library.python.fs.symlink("non-existent", "link")
+ library.python.fs.copy2("link", "link2", follow_symlinks=False)
+
+ assert os.path.islink("link2")
+ assert os.readlink("link2") == "non-existent"
def test_commonpath():
diff --git a/library/python/fs/test/ya.make b/library/python/fs/test/ya.make
index 33e3f5b4ff..b0e636c446 100644
--- a/library/python/fs/test/ya.make
+++ b/library/python/fs/test/ya.make
@@ -1,6 +1,6 @@
OWNER(g:yatool)
-PY23_TEST()
+PY23_TEST()
TEST_SRCS(
test_fs.py
diff --git a/library/python/pytest/plugins/ya.py b/library/python/pytest/plugins/ya.py
index 1bde03042d..60bb08cfeb 100644
--- a/library/python/pytest/plugins/ya.py
+++ b/library/python/pytest/plugins/ya.py
@@ -98,31 +98,31 @@ class YaTestLoggingFileHandler(logging.FileHandler):
pass
-class _TokenFilterFormatter(logging.Formatter):
- def __init__(self, fmt):
- super(_TokenFilterFormatter, self).__init__(fmt)
- self._replacements = []
- if not self._replacements:
- if six.PY2:
- for k, v in os.environ.iteritems():
- if k.endswith('TOKEN') and v:
- self._replacements.append(v)
- elif six.PY3:
- for k, v in os.environ.items():
- if k.endswith('TOKEN') and v:
- self._replacements.append(v)
- self._replacements = sorted(self._replacements)
-
- def _filter(self, s):
- for r in self._replacements:
- s = s.replace(r, "[SECRET]")
-
- return s
-
- def format(self, record):
- return self._filter(super(_TokenFilterFormatter, self).format(record))
-
-
+class _TokenFilterFormatter(logging.Formatter):
+ def __init__(self, fmt):
+ super(_TokenFilterFormatter, self).__init__(fmt)
+ self._replacements = []
+ if not self._replacements:
+ if six.PY2:
+ for k, v in os.environ.iteritems():
+ if k.endswith('TOKEN') and v:
+ self._replacements.append(v)
+ elif six.PY3:
+ for k, v in os.environ.items():
+ if k.endswith('TOKEN') and v:
+ self._replacements.append(v)
+ self._replacements = sorted(self._replacements)
+
+ def _filter(self, s):
+ for r in self._replacements:
+ s = s.replace(r, "[SECRET]")
+
+ return s
+
+ def format(self, record):
+ return self._filter(super(_TokenFilterFormatter, self).format(record))
+
+
def setup_logging(log_path, level=logging.DEBUG, *other_logs):
logs = [log_path] + list(other_logs)
root_logger = logging.getLogger()
@@ -133,7 +133,7 @@ def setup_logging(log_path, level=logging.DEBUG, *other_logs):
for log_file in logs:
file_handler = YaTestLoggingFileHandler(log_file)
log_format = '%(asctime)s - %(levelname)s - %(name)s - %(funcName)s: %(message)s'
- file_handler.setFormatter(_TokenFilterFormatter(log_format))
+ file_handler.setFormatter(_TokenFilterFormatter(log_format))
file_handler.setLevel(level)
root_logger.addHandler(file_handler)
diff --git a/library/python/runtime_py3/importer.pxi b/library/python/runtime_py3/importer.pxi
index 904f94dea2..e352bced50 100644
--- a/library/python/runtime_py3/importer.pxi
+++ b/library/python/runtime_py3/importer.pxi
@@ -234,7 +234,7 @@ class ResourceImporter(object):
abspath = resfs_resolve(path)
if abspath:
return file_bytes(abspath)
- path = path.replace(_b('\\'), _b('/'))
+ path = path.replace(_b('\\'), _b('/'))
data = resfs_read(path, builtin=True)
if data is None:
raise IOError(path) # Y_PYTHON_ENTRY_POINT=:resource_files
diff --git a/library/python/strings/strings.py b/library/python/strings/strings.py
index 5bfddfe78a..2e018ae038 100644
--- a/library/python/strings/strings.py
+++ b/library/python/strings/strings.py
@@ -1,6 +1,6 @@
import locale
import logging
-import six
+import six
import sys
import codecs
@@ -23,15 +23,15 @@ def left_strip(el, prefix):
# Explicit to-text conversion
-# Chooses between str/unicode, i.e. six.binary_type/six.text_type
+# Chooses between str/unicode, i.e. six.binary_type/six.text_type
def to_basestring(value):
- if isinstance(value, (six.binary_type, six.text_type)):
+ if isinstance(value, (six.binary_type, six.text_type)):
return value
try:
- if six.PY2:
- return unicode(value)
- else:
- return str(value)
+ if six.PY2:
+ return unicode(value)
+ else:
+ return str(value)
except UnicodeDecodeError:
try:
return str(value)
@@ -41,35 +41,35 @@ to_text = to_basestring
def to_unicode(value, from_enc=DEFAULT_ENCODING):
- if isinstance(value, six.text_type):
+ if isinstance(value, six.text_type):
return value
- if isinstance(value, six.binary_type):
- if six.PY2:
- return unicode(value, from_enc, ENCODING_ERRORS_POLICY)
- else:
- return value.decode(from_enc, errors=ENCODING_ERRORS_POLICY)
- return six.text_type(value)
+ if isinstance(value, six.binary_type):
+ if six.PY2:
+ return unicode(value, from_enc, ENCODING_ERRORS_POLICY)
+ else:
+ return value.decode(from_enc, errors=ENCODING_ERRORS_POLICY)
+ return six.text_type(value)
# Optional from_enc enables transcoding
def to_str(value, to_enc=DEFAULT_ENCODING, from_enc=None):
- if isinstance(value, six.binary_type):
+ if isinstance(value, six.binary_type):
if from_enc is None or to_enc == from_enc:
# Unknown input encoding or input and output encoding are the same
return value
value = to_unicode(value, from_enc=from_enc)
- if isinstance(value, six.text_type):
+ if isinstance(value, six.text_type):
return value.encode(to_enc, ENCODING_ERRORS_POLICY)
- return six.binary_type(value)
+ return six.binary_type(value)
def _convert_deep(x, enc, convert, relaxed=True):
if x is None:
return None
- if isinstance(x, (six.text_type, six.binary_type)):
+ if isinstance(x, (six.text_type, six.binary_type)):
return convert(x, enc)
if isinstance(x, dict):
- return {convert(k, enc): _convert_deep(v, enc, convert, relaxed) for k, v in six.iteritems(x)}
+ return {convert(k, enc): _convert_deep(v, enc, convert, relaxed) for k, v in six.iteritems(x)}
if isinstance(x, list):
return [_convert_deep(e, enc, convert, relaxed) for e in x]
if isinstance(x, tuple):
@@ -91,13 +91,13 @@ def stringize_deep(x, enc=DEFAULT_ENCODING, relaxed=True):
@library.python.func.memoize()
def locale_encoding():
try:
- loc = locale.getdefaultlocale()[1]
- if loc:
- codecs.lookup(loc)
- return loc
- except LookupError as e:
- logger.debug('Cannot get system locale: %s', e)
- return None
+ loc = locale.getdefaultlocale()[1]
+ if loc:
+ codecs.lookup(loc)
+ return loc
+ except LookupError as e:
+ logger.debug('Cannot get system locale: %s', e)
+ return None
except ValueError as e:
logger.warn('Cannot get system locale: %s', e)
return None
@@ -124,6 +124,6 @@ def get_stream_encoding(stream):
def encode(value, encoding=DEFAULT_ENCODING):
- if isinstance(value, six.binary_type):
+ if isinstance(value, six.binary_type):
value = value.decode(encoding, errors='ignore')
return value.encode(encoding)
diff --git a/library/python/strings/ut/test_strings.py b/library/python/strings/ut/test_strings.py
index dd0c694ee1..9a862ed060 100644
--- a/library/python/strings/ut/test_strings.py
+++ b/library/python/strings/ut/test_strings.py
@@ -1,7 +1,7 @@
# coding=utf-8
import pytest
-import six
+import six
import library.python.strings
@@ -34,11 +34,11 @@ class NonConvertible(ConvertibleToUnicodeOnly, ConvertibleToStrOnly):
def test_to_basestring():
assert library.python.strings.to_basestring('str') == 'str'
assert library.python.strings.to_basestring(u'юникод') == u'юникод'
- if six.PY2: # __str__ should return str not bytes in Python3
- assert library.python.strings.to_basestring(Convertible()) == Convertible.text
- assert library.python.strings.to_basestring(ConvertibleToUnicodeOnly()) == Convertible.text
- assert library.python.strings.to_basestring(ConvertibleToStrOnly()) == Convertible.text_utf8
- assert library.python.strings.to_basestring(NonConvertible())
+ if six.PY2: # __str__ should return str not bytes in Python3
+ assert library.python.strings.to_basestring(Convertible()) == Convertible.text
+ assert library.python.strings.to_basestring(ConvertibleToUnicodeOnly()) == Convertible.text
+ assert library.python.strings.to_basestring(ConvertibleToStrOnly()) == Convertible.text_utf8
+ assert library.python.strings.to_basestring(NonConvertible())
def test_to_unicode():
@@ -46,13 +46,13 @@ def test_to_unicode():
assert library.python.strings.to_unicode('str') == u'str'
assert library.python.strings.to_unicode(u'строка'.encode('utf-8')) == u'строка'
assert library.python.strings.to_unicode(u'строка'.encode('cp1251'), 'cp1251') == u'строка'
- if six.PY2: # __str__ should return str not bytes in Python3
- assert library.python.strings.to_unicode(Convertible()) == Convertible.text
- assert library.python.strings.to_unicode(ConvertibleToUnicodeOnly()) == Convertible.text
- with pytest.raises(UnicodeDecodeError):
- library.python.strings.to_unicode(ConvertibleToStrOnly())
- with pytest.raises(UnicodeDecodeError):
- library.python.strings.to_unicode(NonConvertible())
+ if six.PY2: # __str__ should return str not bytes in Python3
+ assert library.python.strings.to_unicode(Convertible()) == Convertible.text
+ assert library.python.strings.to_unicode(ConvertibleToUnicodeOnly()) == Convertible.text
+ with pytest.raises(UnicodeDecodeError):
+ library.python.strings.to_unicode(ConvertibleToStrOnly())
+ with pytest.raises(UnicodeDecodeError):
+ library.python.strings.to_unicode(NonConvertible())
def test_to_unicode_errors_replace():
@@ -61,17 +61,17 @@ def test_to_unicode_errors_replace():
def test_to_str():
- assert library.python.strings.to_str('str') == 'str' if six.PY2 else b'str'
- assert library.python.strings.to_str(u'unicode') == 'unicode' if six.PY2 else b'unicode'
+ assert library.python.strings.to_str('str') == 'str' if six.PY2 else b'str'
+ assert library.python.strings.to_str(u'unicode') == 'unicode' if six.PY2 else b'unicode'
assert library.python.strings.to_str(u'юникод') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод', 'cp1251') == u'юникод'.encode('cp1251')
- if six.PY2:
- assert library.python.strings.to_str(Convertible()) == Convertible.text_utf8
- with pytest.raises(UnicodeEncodeError):
- library.python.strings.to_str(ConvertibleToUnicodeOnly())
- assert library.python.strings.to_str(ConvertibleToStrOnly()) == Convertible.text_utf8
- with pytest.raises(UnicodeEncodeError):
- library.python.strings.to_str(NonConvertible())
+ if six.PY2:
+ assert library.python.strings.to_str(Convertible()) == Convertible.text_utf8
+ with pytest.raises(UnicodeEncodeError):
+ library.python.strings.to_str(ConvertibleToUnicodeOnly())
+ assert library.python.strings.to_str(ConvertibleToStrOnly()) == Convertible.text_utf8
+ with pytest.raises(UnicodeEncodeError):
+ library.python.strings.to_str(NonConvertible())
def test_to_str_errors_replace():
@@ -80,8 +80,8 @@ def test_to_str_errors_replace():
def test_to_str_transcode():
- assert library.python.strings.to_str('str', from_enc='ascii') == 'str' if six.PY2 else b'str'
- assert library.python.strings.to_str('str', from_enc='utf-8') == 'str' if six.PY2 else b'str'
+ assert library.python.strings.to_str('str', from_enc='ascii') == 'str' if six.PY2 else b'str'
+ assert library.python.strings.to_str('str', from_enc='utf-8') == 'str' if six.PY2 else b'str'
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), from_enc='utf-8') == u'юникод'.encode('utf-8')
assert library.python.strings.to_str(u'юникод'.encode('utf-8'), to_enc='utf-8', from_enc='utf-8') == u'юникод'.encode('utf-8')
@@ -117,9 +117,9 @@ def test_stringize_deep():
u'ключ 2': u'значение 2',
'list': [u'ключ 2', 'key 1', (u'к', 2)]
}) == {
- 'key 1' if six.PY2 else b'key 1': 'value 1' if six.PY2 else b'value 1',
+ 'key 1' if six.PY2 else b'key 1': 'value 1' if six.PY2 else b'value 1',
u'ключ 2'.encode('utf-8'): u'значение 2'.encode('utf-8'),
- 'list' if six.PY2 else b'list': [u'ключ 2'.encode('utf-8'), 'key 1' if six.PY2 else b'key 1', (u'к'.encode('utf-8'), 2)]
+ 'list' if six.PY2 else b'list': [u'ключ 2'.encode('utf-8'), 'key 1' if six.PY2 else b'key 1', (u'к'.encode('utf-8'), 2)]
}
@@ -141,16 +141,16 @@ def test_stringize_deep_nested():
u'подключ 2': u'value 2',
},
}) == {
- 'key 1' if six.PY2 else b'key 1': 'value 1' if six.PY2 else b'value 1',
+ 'key 1' if six.PY2 else b'key 1': 'value 1' if six.PY2 else b'value 1',
u'ключ 2'.encode('utf-8'): {
- 'subkey 1' if six.PY2 else b'subkey 1': 'value 1' if six.PY2 else b'value 1',
+ 'subkey 1' if six.PY2 else b'subkey 1': 'value 1' if six.PY2 else b'value 1',
u'подключ 2'.encode('utf-8'): u'value 2'.encode('utf-8'),
},
}
def test_stringize_deep_plain():
- assert library.python.strings.stringize_deep('str') == 'str' if six.PY2 else b'str'
+ assert library.python.strings.stringize_deep('str') == 'str' if six.PY2 else b'str'
assert library.python.strings.stringize_deep(u'юникод') == u'юникод'.encode('utf-8')
assert library.python.strings.stringize_deep(u'юникод'.encode('utf-8')) == u'юникод'.encode('utf-8')
diff --git a/library/python/strings/ut/ya.make b/library/python/strings/ut/ya.make
index dfacb226c7..30800efd37 100644
--- a/library/python/strings/ut/ya.make
+++ b/library/python/strings/ut/ya.make
@@ -1,6 +1,6 @@
OWNER(g:yatool)
-PY23_TEST()
+PY23_TEST()
TEST_SRCS(test_strings.py)
diff --git a/library/python/strings/ya.make b/library/python/strings/ya.make
index 7e0b033717..49d4fa9b04 100644
--- a/library/python/strings/ya.make
+++ b/library/python/strings/ya.make
@@ -10,7 +10,7 @@ PY_SRCS(
PEERDIR(
library/python/func
- contrib/python/six
+ contrib/python/six
)
END()
diff --git a/library/python/svn_version/__init__.py b/library/python/svn_version/__init__.py
index 7ef7d6dac7..d2a6dc1a49 100644
--- a/library/python/svn_version/__init__.py
+++ b/library/python/svn_version/__init__.py
@@ -1 +1 @@
-from .__svn_version import svn_version, commit_id, svn_revision, svn_last_revision, hash, svn_branch, svn_tag, patch_number # noqa
+from .__svn_version import svn_version, commit_id, svn_revision, svn_last_revision, hash, svn_branch, svn_tag, patch_number # noqa
diff --git a/library/python/svn_version/__svn_version.pyx b/library/python/svn_version/__svn_version.pyx
index d66bc09d24..4be75f808d 100644
--- a/library/python/svn_version/__svn_version.pyx
+++ b/library/python/svn_version/__svn_version.pyx
@@ -3,12 +3,12 @@ import future.utils as fu
cdef extern from "library/cpp/svnversion/svnversion.h":
cdef const char* GetProgramSvnVersion() except +;
cdef int GetProgramSvnRevision() except +;
- cdef int GetArcadiaLastChangeNum() except +;
- cdef const char* GetProgramCommitId() except +;
+ cdef int GetArcadiaLastChangeNum() except +;
+ cdef const char* GetProgramCommitId() except +;
cdef const char* GetProgramHash() except +;
cdef const char* GetBranch() except +;
cdef const char* GetTag() except +;
- cdef int GetArcadiaPatchNumber() except +;
+ cdef int GetArcadiaPatchNumber() except +;
def svn_version():
return fu.bytes_to_native_str(GetProgramSvnVersion())
@@ -16,12 +16,12 @@ def svn_version():
def svn_revision():
return GetProgramSvnRevision()
-def svn_last_revision():
- return GetArcadiaLastChangeNum()
-
-def commit_id():
- return fu.bytes_to_native_str(GetProgramCommitId())
-
+def svn_last_revision():
+ return GetArcadiaLastChangeNum()
+
+def commit_id():
+ return fu.bytes_to_native_str(GetProgramCommitId())
+
def hash():
return fu.bytes_to_native_str(GetProgramHash())
@@ -30,6 +30,6 @@ def svn_branch():
def svn_tag():
return fu.bytes_to_native_str(GetTag())
-
-def patch_number():
- return GetArcadiaPatchNumber()
+
+def patch_number():
+ return GetArcadiaPatchNumber()
diff --git a/library/python/svn_version/ut/lib/test_simple.py b/library/python/svn_version/ut/lib/test_simple.py
index 2c27af6c68..c1218895c1 100644
--- a/library/python/svn_version/ut/lib/test_simple.py
+++ b/library/python/svn_version/ut/lib/test_simple.py
@@ -6,11 +6,11 @@ def test_simple():
assert isinstance(sv.svn_version(), str)
assert sv.svn_revision()
assert isinstance(sv.svn_revision(), int)
- assert sv.svn_last_revision()
- assert isinstance(sv.svn_last_revision(), int)
- assert sv.svn_last_revision() > 0
- assert sv.commit_id()
- assert isinstance(sv.commit_id(), str)
- assert len(sv.commit_id()) > 0
+ assert sv.svn_last_revision()
+ assert isinstance(sv.svn_last_revision(), int)
+ assert sv.svn_last_revision() > 0
+ assert sv.commit_id()
+ assert isinstance(sv.commit_id(), str)
+ assert len(sv.commit_id()) > 0
assert isinstance(sv.hash(), str)
- assert isinstance(sv.patch_number(), int)
+ assert isinstance(sv.patch_number(), int)
diff --git a/library/python/symbols/libc/syms.cpp b/library/python/symbols/libc/syms.cpp
index 6c04a7ef6e..fa43606557 100644
--- a/library/python/symbols/libc/syms.cpp
+++ b/library/python/symbols/libc/syms.cpp
@@ -42,7 +42,7 @@
#if defined(_linux_)
#include <sys/inotify.h>
-#include <sys/mman.h>
+#include <sys/mman.h>
#endif
namespace {
@@ -137,7 +137,7 @@ SYM(sem_timedwait)
SYM(inotify_init)
SYM(inotify_add_watch)
SYM(inotify_rm_watch)
-SYM(mlockall)
+SYM(mlockall)
#endif
#if defined(_darwin_)
diff --git a/library/python/testing/yatest_common/ya.make b/library/python/testing/yatest_common/ya.make
index 5662db4c5d..7d4abfe704 100644
--- a/library/python/testing/yatest_common/ya.make
+++ b/library/python/testing/yatest_common/ya.make
@@ -28,7 +28,7 @@ PEERDIR(
contrib/python/six
library/python/cores
library/python/filelock
- library/python/fs
+ library/python/fs
)
IF (NOT CATBOOST_OPENSOURCE)
diff --git a/library/python/testing/yatest_common/yatest/common/path.py b/library/python/testing/yatest_common/yatest/common/path.py
index 6fed7dda8a..1d08f72e62 100644
--- a/library/python/testing/yatest_common/yatest/common/path.py
+++ b/library/python/testing/yatest_common/yatest/common/path.py
@@ -1,13 +1,13 @@
# coding=utf-8
-import errno
+import errno
import os
import shutil
import contextlib
-import library.python.fs as lpf
-
+import library.python.fs as lpf
+
def replace_in_file(path, old, new):
"""
Replace text occurrences in a file
@@ -18,7 +18,7 @@ def replace_in_file(path, old, new):
with open(path) as fp:
content = fp.read()
- lpf.ensure_removed(path)
+ lpf.ensure_removed(path)
with open(path, 'w') as fp:
fp.write(content.replace(old, new))
@@ -56,35 +56,35 @@ def copytree(src, dst, symlinks=False, ignore=None, postprocessing=None):
postprocessing(os.path.join(root, path), True)
-def get_unique_file_path(dir_path, file_pattern, create_file=True, max_suffix=10000):
- def atomic_file_create(path):
- try:
+def get_unique_file_path(dir_path, file_pattern, create_file=True, max_suffix=10000):
+ def atomic_file_create(path):
+ try:
fd = os.open(path, os.O_CREAT | os.O_EXCL, 0o644)
- os.close(fd)
- return True
- except OSError as e:
- if e.errno in [errno.EEXIST, errno.EISDIR, errno.ETXTBSY]:
- return False
- # Access issue with file itself, not parent directory.
- if e.errno == errno.EACCES and os.path.exists(path):
- return False
- raise e
-
- def atomic_dir_create(path):
- try:
- os.mkdir(path)
- return True
- except OSError as e:
- if e.errno == errno.EEXIST:
- return False
- raise e
-
+ os.close(fd)
+ return True
+ except OSError as e:
+ if e.errno in [errno.EEXIST, errno.EISDIR, errno.ETXTBSY]:
+ return False
+ # Access issue with file itself, not parent directory.
+ if e.errno == errno.EACCES and os.path.exists(path):
+ return False
+ raise e
+
+ def atomic_dir_create(path):
+ try:
+ os.mkdir(path)
+ return True
+ except OSError as e:
+ if e.errno == errno.EEXIST:
+ return False
+ raise e
+
file_path = os.path.join(dir_path, file_pattern)
- lpf.ensure_dir(os.path.dirname(file_path))
+ lpf.ensure_dir(os.path.dirname(file_path))
file_counter = 0
- handler = atomic_file_create if create_file else atomic_dir_create
- while os.path.exists(file_path) or not handler(file_path):
+ handler = atomic_file_create if create_file else atomic_dir_create
+ while os.path.exists(file_path) or not handler(file_path):
file_path = os.path.join(dir_path, file_pattern + ".{}".format(file_counter))
file_counter += 1
- assert file_counter < max_suffix
+ assert file_counter < max_suffix
return file_path
diff --git a/library/python/testing/yatest_common/yatest/common/runtime.py b/library/python/testing/yatest_common/yatest/common/runtime.py
index e55e193446..95d96b468a 100644
--- a/library/python/testing/yatest_common/yatest/common/runtime.py
+++ b/library/python/testing/yatest_common/yatest/common/runtime.py
@@ -2,14 +2,14 @@ import errno
import functools
import json
import os
-import threading
+import threading
import six
-_lock = threading.Lock()
-
-
+_lock = threading.Lock()
+
+
def _get_ya_config():
try:
import library.python.pytest.plugins.ya as ya_plugin
@@ -263,13 +263,13 @@ def global_resources():
def _register_core(name, binary_path, core_path, bt_path, pbt_path):
config = _get_ya_config()
-
- with _lock:
+
+ with _lock:
if not hasattr(config, 'test_cores_count'):
config.test_cores_count = 0
- config.test_cores_count += 1
- count_str = '' if config.test_cores_count == 1 else str(config.test_cores_count)
-
+ config.test_cores_count += 1
+ count_str = '' if config.test_cores_count == 1 else str(config.test_cores_count)
+
log_entry = config.test_logs[config.current_item_nodeid]
if binary_path:
log_entry['{} binary{}'.format(name, count_str)] = binary_path
diff --git a/tools/rescompressor/main.cpp b/tools/rescompressor/main.cpp
index 9aba1002c5..c09d65c4c1 100644
--- a/tools/rescompressor/main.cpp
+++ b/tools/rescompressor/main.cpp
@@ -76,75 +76,75 @@ private:
}
};
-static TString CompressPath(const TVector<TStringBuf>& replacements, TStringBuf in) {
- for (auto r : replacements) {
- TStringBuf from, to;
- r.Split('=', from, to);
- if (in.StartsWith(from)) {
- return Compress(TString(to) + in.SubStr(from.Size()));
- }
- }
-
- return Compress(in);
-}
-
+static TString CompressPath(const TVector<TStringBuf>& replacements, TStringBuf in) {
+ for (auto r : replacements) {
+ TStringBuf from, to;
+ r.Split('=', from, to);
+ if (in.StartsWith(from)) {
+ return Compress(TString(to) + in.SubStr(from.Size()));
+ }
+ }
+
+ return Compress(in);
+}
+
int main(int argc, char** argv) {
- int ind = 0;
+ int ind = 0;
if (argc < 4) {
- Cerr << "usage: " << argv[ind] << "asm_output --prefix? [-? origin_resource ro_resource]+" << Endl;
+ Cerr << "usage: " << argv[ind] << "asm_output --prefix? [-? origin_resource ro_resource]+" << Endl;
return 1;
}
- TVector<TStringBuf> replacements;
-
- ind++;
- TFixedBufferFileOutput asmout(argv[ind]);
- ind++;
+ TVector<TStringBuf> replacements;
+
+ ind++;
+ TFixedBufferFileOutput asmout(argv[ind]);
+ ind++;
TString prefix;
- if (TStringBuf(argv[ind]) == "--prefix") {
+ if (TStringBuf(argv[ind]) == "--prefix") {
prefix = "_";
- ind++;
+ ind++;
}
else {
prefix = "";
}
- while (TStringBuf(argv[ind]).StartsWith("--replace=")) {
+ while (TStringBuf(argv[ind]).StartsWith("--replace=")) {
replacements.push_back(TStringBuf(argv[ind]).SubStr(TStringBuf("--replace=").Size()));
- ind++;
- }
-
+ ind++;
+ }
+
TAsmWriter aw(asmout, prefix);
bool raw;
- bool error = false;
- while (ind < argc) {
+ bool error = false;
+ while (ind < argc) {
TString compressed;
if ("-"sv == argv[ind]) {
- ind++;
- if (ind >= argc) {
- error = true;
- break;
- }
- compressed = CompressPath(replacements, TStringBuf(argv[ind]));
+ ind++;
+ if (ind >= argc) {
+ error = true;
+ break;
+ }
+ compressed = CompressPath(replacements, TStringBuf(argv[ind]));
raw = true;
}
else {
- TUnbufferedFileInput inp(argv[ind]);
+ TUnbufferedFileInput inp(argv[ind]);
TString data = inp.ReadAll();
compressed = Compress(TStringBuf(data.data(), data.size()));
raw = false;
}
- ind++;
- if (ind >= argc) {
- error = true;
- break;
- }
- aw.Write(argv[ind], compressed, raw);
- ind++;
- }
- if (error) {
- Cerr << "Incorrect number of parameters at argument " << ind - 1 << argv[ind-1] << Endl;
- return 1;
+ ind++;
+ if (ind >= argc) {
+ error = true;
+ break;
+ }
+ aw.Write(argv[ind], compressed, raw);
+ ind++;
}
+ if (error) {
+ Cerr << "Incorrect number of parameters at argument " << ind - 1 << argv[ind-1] << Endl;
+ return 1;
+ }
return 0;
}
diff --git a/util/folder/dirut.cpp b/util/folder/dirut.cpp
index ffc9b09f96..953532ec70 100644
--- a/util/folder/dirut.cpp
+++ b/util/folder/dirut.cpp
@@ -379,7 +379,7 @@ const char* GetDirectorySeparatorS() {
void RemoveDirWithContents(TString dirName) {
SlashFolderLocal(dirName);
- TDirIterator dir(dirName, TDirIterator::TOptions(FTS_NOSTAT));
+ TDirIterator dir(dirName, TDirIterator::TOptions(FTS_NOSTAT));
for (auto it = dir.begin(); it != dir.end(); ++it) {
switch (it->fts_info) {
diff --git a/util/network/pair.cpp b/util/network/pair.cpp
index 9751ef5c96..e3610aee77 100644
--- a/util/network/pair.cpp
+++ b/util/network/pair.cpp
@@ -1,12 +1,12 @@
#include "pair.h"
-int SocketPair(SOCKET socks[2], bool overlapped, bool cloexec) {
+int SocketPair(SOCKET socks[2], bool overlapped, bool cloexec) {
#if defined(_win_)
struct sockaddr_in addr;
SOCKET listener;
int e;
int addrlen = sizeof(addr);
- DWORD flags = (overlapped ? WSA_FLAG_OVERLAPPED : 0) | (cloexec ? WSA_FLAG_NO_HANDLE_INHERIT : 0);
+ DWORD flags = (overlapped ? WSA_FLAG_OVERLAPPED : 0) | (cloexec ? WSA_FLAG_NO_HANDLE_INHERIT : 0);
if (socks == 0) {
WSASetLastError(WSAEINVAL);
@@ -75,23 +75,23 @@ int SocketPair(SOCKET socks[2], bool overlapped, bool cloexec) {
(void)overlapped;
#if defined(_linux_)
- return socketpair(AF_LOCAL, SOCK_STREAM | (cloexec ? SOCK_CLOEXEC : 0), 0, socks);
+ return socketpair(AF_LOCAL, SOCK_STREAM | (cloexec ? SOCK_CLOEXEC : 0), 0, socks);
#else
- int r = socketpair(AF_LOCAL, SOCK_STREAM, 0, socks);
- // Non-atomic wrt exec
- if (r == 0 && cloexec) {
- for (int i = 0; i < 2; ++i) {
- int flags = fcntl(socks[i], F_GETFD, 0);
- if (flags < 0) {
- return flags;
- }
- r = fcntl(socks[i], F_SETFD, flags | FD_CLOEXEC);
- if (r < 0) {
- return r;
- }
- }
- }
- return r;
+ int r = socketpair(AF_LOCAL, SOCK_STREAM, 0, socks);
+ // Non-atomic wrt exec
+ if (r == 0 && cloexec) {
+ for (int i = 0; i < 2; ++i) {
+ int flags = fcntl(socks[i], F_GETFD, 0);
+ if (flags < 0) {
+ return flags;
+ }
+ r = fcntl(socks[i], F_SETFD, flags | FD_CLOEXEC);
+ if (r < 0) {
+ return r;
+ }
+ }
+ }
+ return r;
#endif
#endif
}
diff --git a/util/network/pair.h b/util/network/pair.h
index 0d4506f880..64d81bcc7d 100644
--- a/util/network/pair.h
+++ b/util/network/pair.h
@@ -5,5 +5,5 @@
int SocketPair(SOCKET socks[2], bool overlapped, bool cloexec = false);
static inline int SocketPair(SOCKET socks[2]) {
- return SocketPair(socks, false, false);
+ return SocketPair(socks, false, false);
}
diff --git a/util/system/daemon.cpp b/util/system/daemon.cpp
index 130e6c8f45..5020720206 100644
--- a/util/system/daemon.cpp
+++ b/util/system/daemon.cpp
@@ -17,18 +17,18 @@
#ifdef _unix_
using namespace NDaemonMaker;
-static bool Fork(EParent parent) {
+static bool Fork(EParent parent) {
pid_t pid = fork();
if (pid > 0) {
- int status = 0;
- while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
- }
- if (parent == callExitFromParent) {
+ int status = 0;
+ while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
+ }
+ if (parent == callExitFromParent) {
_exit(0);
- } else {
- return true;
- }
+ } else {
+ return true;
+ }
} else if (pid < 0) {
ythrow TSystemError() << "Cannot fork";
}
@@ -44,7 +44,7 @@ static bool Fork(EParent parent) {
} else if (pid < 0) {
ythrow TSystemError() << "Cannot second fork";
}
- return false;
+ return false;
}
#endif
@@ -75,15 +75,15 @@ static void CloseFromToExcept(int from, int to, const int* except) {
#endif /* _unix_ */
}
-bool NDaemonMaker::MakeMeDaemon(ECloseDescriptors cd, EStdIoDescriptors iod, EChDir chd, EParent parent) {
+bool NDaemonMaker::MakeMeDaemon(ECloseDescriptors cd, EStdIoDescriptors iod, EChDir chd, EParent parent) {
(void)cd;
(void)iod;
(void)chd;
#ifdef _unix_
- if (Fork(parent)) {
- return true;
- }
+ if (Fork(parent)) {
+ return true;
+ }
if (chd == chdirRoot) {
if (chdir("/")) {
@@ -156,9 +156,9 @@ bool NDaemonMaker::MakeMeDaemon(ECloseDescriptors cd, EStdIoDescriptors iod, ECh
default:
break;
}
- return false;
-#else
- return true;
+ return false;
+#else
+ return true;
#endif
}
diff --git a/util/system/daemon.h b/util/system/daemon.h
index b00793b9c9..c9cc73fc44 100644
--- a/util/system/daemon.h
+++ b/util/system/daemon.h
@@ -17,11 +17,11 @@ namespace NDaemonMaker {
chdirRoot
};
- enum EParent {
- callExitFromParent = 0,
- returnFromParent
- };
-
- bool MakeMeDaemon(ECloseDescriptors cd = closeAll, EStdIoDescriptors iod = openDevNull, EChDir chd = chdirRoot, EParent parent = callExitFromParent);
+ enum EParent {
+ callExitFromParent = 0,
+ returnFromParent
+ };
+
+ bool MakeMeDaemon(ECloseDescriptors cd = closeAll, EStdIoDescriptors iod = openDevNull, EChDir chd = chdirRoot, EParent parent = callExitFromParent);
void CloseFrom(int fd);
}
diff --git a/util/system/daemon_ut.cpp b/util/system/daemon_ut.cpp
index f93b9a9645..fd80f3ba8c 100644
--- a/util/system/daemon_ut.cpp
+++ b/util/system/daemon_ut.cpp
@@ -1,94 +1,94 @@
-#include "daemon.h"
-
+#include "daemon.h"
+
#include <library/cpp/testing/unittest/registar.h>
-
-#include <util/network/pair.h>
-#include <util/network/socket.h>
-#include <util/system/pipe.h>
-
-Y_UNIT_TEST_SUITE(TDaemonTest) {
-#ifdef _unix_
- template <typename Func>
+
+#include <util/network/pair.h>
+#include <util/network/socket.h>
+#include <util/system/pipe.h>
+
+Y_UNIT_TEST_SUITE(TDaemonTest) {
+#ifdef _unix_
+ template <typename Func>
static bool ProcessBuffer(Func&& func, void* bufin, size_t size) {
- char* buf = (char*)bufin;
- do {
- const ssize_t bytesDone = func(buf, size);
- if (bytesDone == 0) {
- return false;
- }
-
- if (bytesDone < 0) {
- if (errno == EAGAIN || errno == EINTR) {
- continue;
- } else {
- return false;
- }
- }
-
- buf += bytesDone;
- size -= bytesDone;
- } while (size != 0);
-
- return true;
- }
-
- const int size = 1024 * 4;
- const int pagesSize = sizeof(int) * size;
-
- Y_UNIT_TEST(WaitForMessageSocket) {
- using namespace NDaemonMaker;
- SOCKET sockets[2];
- SocketPair(sockets, false, true);
- TSocket sender(sockets[0]);
- TSocket receiver(sockets[1]);
-
- int status = -1;
- int* pages = new int[size];
-
- memset(pages, 0, pagesSize);
- if (MakeMeDaemon(closeStdIoOnly, openDevNull, chdirNone, returnFromParent)) {
- sender.Close();
- UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Recv(ptr, sz); }, &status, sizeof(status)));
- UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Recv(ptr, sz); }, pages, pagesSize));
- UNIT_ASSERT(memchr(pages, 0, pagesSize) == nullptr);
- } else {
- receiver.Close();
- status = 0;
- UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Send(ptr, sz); }, &status, sizeof(status)));
- memset(pages, 1, pagesSize);
- UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Send(ptr, sz); }, pages, pagesSize));
- exit(0);
- }
- UNIT_ASSERT(status == 0);
-
- delete[] pages;
- }
-
- Y_UNIT_TEST(WaitForMessagePipe) {
- using namespace NDaemonMaker;
- TPipeHandle sender;
- TPipeHandle receiver;
- TPipeHandle::Pipe(receiver, sender);
-
- int status = -1;
- int* pages = new int[size];
- memset(pages, 0, pagesSize);
- if (MakeMeDaemon(closeStdIoOnly, openDevNull, chdirNone, returnFromParent)) {
- sender.Close();
- UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Read(ptr, sz); }, &status, sizeof(status)));
- UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Read(ptr, sz); }, pages, pagesSize));
- UNIT_ASSERT(memchr(pages, 0, pagesSize) == nullptr);
- } else {
- receiver.Close();
- status = 0;
- UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Write(ptr, sz); }, &status, sizeof(status)));
- memset(pages, 1, pagesSize);
- UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Write(ptr, sz); }, pages, pagesSize));
- exit(0);
- }
- UNIT_ASSERT(status == 0);
-
- delete[] pages;
- }
-#endif
-}
+ char* buf = (char*)bufin;
+ do {
+ const ssize_t bytesDone = func(buf, size);
+ if (bytesDone == 0) {
+ return false;
+ }
+
+ if (bytesDone < 0) {
+ if (errno == EAGAIN || errno == EINTR) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+
+ buf += bytesDone;
+ size -= bytesDone;
+ } while (size != 0);
+
+ return true;
+ }
+
+ const int size = 1024 * 4;
+ const int pagesSize = sizeof(int) * size;
+
+ Y_UNIT_TEST(WaitForMessageSocket) {
+ using namespace NDaemonMaker;
+ SOCKET sockets[2];
+ SocketPair(sockets, false, true);
+ TSocket sender(sockets[0]);
+ TSocket receiver(sockets[1]);
+
+ int status = -1;
+ int* pages = new int[size];
+
+ memset(pages, 0, pagesSize);
+ if (MakeMeDaemon(closeStdIoOnly, openDevNull, chdirNone, returnFromParent)) {
+ sender.Close();
+ UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Recv(ptr, sz); }, &status, sizeof(status)));
+ UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Recv(ptr, sz); }, pages, pagesSize));
+ UNIT_ASSERT(memchr(pages, 0, pagesSize) == nullptr);
+ } else {
+ receiver.Close();
+ status = 0;
+ UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Send(ptr, sz); }, &status, sizeof(status)));
+ memset(pages, 1, pagesSize);
+ UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Send(ptr, sz); }, pages, pagesSize));
+ exit(0);
+ }
+ UNIT_ASSERT(status == 0);
+
+ delete[] pages;
+ }
+
+ Y_UNIT_TEST(WaitForMessagePipe) {
+ using namespace NDaemonMaker;
+ TPipeHandle sender;
+ TPipeHandle receiver;
+ TPipeHandle::Pipe(receiver, sender);
+
+ int status = -1;
+ int* pages = new int[size];
+ memset(pages, 0, pagesSize);
+ if (MakeMeDaemon(closeStdIoOnly, openDevNull, chdirNone, returnFromParent)) {
+ sender.Close();
+ UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Read(ptr, sz); }, &status, sizeof(status)));
+ UNIT_ASSERT(ProcessBuffer([&receiver](char* ptr, size_t sz) -> size_t { return receiver.Read(ptr, sz); }, pages, pagesSize));
+ UNIT_ASSERT(memchr(pages, 0, pagesSize) == nullptr);
+ } else {
+ receiver.Close();
+ status = 0;
+ UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Write(ptr, sz); }, &status, sizeof(status)));
+ memset(pages, 1, pagesSize);
+ UNIT_ASSERT(ProcessBuffer([&sender](char* ptr, size_t sz) -> size_t { return sender.Write(ptr, sz); }, pages, pagesSize));
+ exit(0);
+ }
+ UNIT_ASSERT(status == 0);
+
+ delete[] pages;
+ }
+#endif
+}
diff --git a/util/system/file.cpp b/util/system/file.cpp
index 4a261d020c..f677819de6 100644
--- a/util/system/file.cpp
+++ b/util/system/file.cpp
@@ -238,9 +238,9 @@ TFileHandle::TFileHandle(const TString& fName, EOpenMode oMode) noexcept {
permMode |= S_IRUSR;
}
- do {
- Fd_ = ::open(fName.data(), fcMode, permMode);
- } while (Fd_ == -1 && errno == EINTR);
+ do {
+ Fd_ = ::open(fName.data(), fcMode, permMode);
+ } while (Fd_ == -1 && errno == EINTR);
#if HAVE_POSIX_FADVISE
if (Fd_ >= 0) {
diff --git a/util/system/file_lock.cpp b/util/system/file_lock.cpp
index 45d91282c5..4af6110011 100644
--- a/util/system/file_lock.cpp
+++ b/util/system/file_lock.cpp
@@ -15,7 +15,7 @@ namespace {
default:
Y_UNREACHABLE();
}
- Y_UNREACHABLE();
+ Y_UNREACHABLE();
}
}
diff --git a/util/system/flock.cpp b/util/system/flock.cpp
index fe88fecaff..480ae18369 100644
--- a/util/system/flock.cpp
+++ b/util/system/flock.cpp
@@ -55,7 +55,7 @@ extern "C" {
break;
default:
break;
- }
+ }
errno = EINVAL;
return -1;
}
diff --git a/util/system/pipe.cpp b/util/system/pipe.cpp
index a543bd7472..d16d6830b7 100644
--- a/util/system/pipe.cpp
+++ b/util/system/pipe.cpp
@@ -32,12 +32,12 @@ bool TPipeHandle::Close() noexcept {
return ok;
}
-void TPipeHandle::Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode) {
+void TPipeHandle::Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode) {
PIPEHANDLE fds[2];
#ifdef _win_
- int r = SocketPair(fds, false /* non-overlapped */, mode & CloseOnExec /* cloexec */);
-#elif defined(_linux_)
- int r = pipe2(fds, mode & CloseOnExec ? O_CLOEXEC : 0);
+ int r = SocketPair(fds, false /* non-overlapped */, mode & CloseOnExec /* cloexec */);
+#elif defined(_linux_)
+ int r = pipe2(fds, mode & CloseOnExec ? O_CLOEXEC : 0);
#else
int r = pipe(fds);
#endif
@@ -45,22 +45,22 @@ void TPipeHandle::Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode)
ythrow TFileError() << "failed to create a pipe";
}
-#if !defined(_win_) && !defined(_linux_)
- // Non-atomic wrt exec
- if (mode & CloseOnExec) {
- for (int i = 0; i < 2; ++i) {
- int flags = fcntl(fds[i], F_GETFD, 0);
- if (flags < 0) {
- ythrow TFileError() << "failed to get flags";
- }
- int r = fcntl(fds[i], F_SETFD, flags | FD_CLOEXEC);
- if (r < 0) {
- ythrow TFileError() << "failed to set flags";
- }
- }
- }
-#endif
-
+#if !defined(_win_) && !defined(_linux_)
+ // Non-atomic wrt exec
+ if (mode & CloseOnExec) {
+ for (int i = 0; i < 2; ++i) {
+ int flags = fcntl(fds[i], F_GETFD, 0);
+ if (flags < 0) {
+ ythrow TFileError() << "failed to get flags";
+ }
+ int r = fcntl(fds[i], F_SETFD, flags | FD_CLOEXEC);
+ if (r < 0) {
+ ythrow TFileError() << "failed to set flags";
+ }
+ }
+ }
+#endif
+
TPipeHandle(fds[0]).Swap(reader);
TPipeHandle(fds[1]).Swap(writer);
}
@@ -150,11 +150,11 @@ size_t TPipe::Write(const void* buf, size_t len) const {
return Impl_->Write(buf, len);
}
-void TPipe::Pipe(TPipe& reader, TPipe& writer, EOpenMode mode) {
+void TPipe::Pipe(TPipe& reader, TPipe& writer, EOpenMode mode) {
TImplRef r(new TImpl());
TImplRef w(new TImpl());
- TPipeHandle::Pipe(r->GetHandle(), w->GetHandle(), mode);
+ TPipeHandle::Pipe(r->GetHandle(), w->GetHandle(), mode);
r.Swap(reader.Impl_);
w.Swap(writer.Impl_);
diff --git a/util/system/pipe.h b/util/system/pipe.h
index 75d0360049..60e6440be3 100644
--- a/util/system/pipe.h
+++ b/util/system/pipe.h
@@ -6,7 +6,7 @@
#endif
#include "defaults.h"
-#include "file.h"
+#include "file.h"
#include <util/generic/ptr.h>
#include <util/network/pair.h>
#include <util/generic/noncopyable.h>
@@ -54,8 +54,8 @@ public:
ssize_t Read(void* buffer, size_t byteCount) const noexcept;
ssize_t Write(const void* buffer, size_t byteCount) const noexcept;
- // Only CloseOnExec is supported
- static void Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode = 0);
+ // Only CloseOnExec is supported
+ static void Pipe(TPipeHandle& reader, TPipeHandle& writer, EOpenMode mode = 0);
private:
PIPEHANDLE Fd_;
@@ -76,8 +76,8 @@ public:
size_t Read(void* buf, size_t len) const;
size_t Write(const void* buf, size_t len) const;
- // Only CloseOnExec is supported
- static void Pipe(TPipe& reader, TPipe& writer, EOpenMode mode = 0);
+ // Only CloseOnExec is supported
+ static void Pipe(TPipe& reader, TPipe& writer, EOpenMode mode = 0);
private:
class TImpl;
diff --git a/util/system/shellcommand.cpp b/util/system/shellcommand.cpp
index b1989b5c8c..099840f684 100644
--- a/util/system/shellcommand.cpp
+++ b/util/system/shellcommand.cpp
@@ -168,10 +168,10 @@ public:
return doneBytes;
}
- static void Pipe(TRealPipeHandle& reader, TRealPipeHandle& writer, EOpenMode mode) {
- (void)mode;
+ static void Pipe(TRealPipeHandle& reader, TRealPipeHandle& writer, EOpenMode mode) {
+ (void)mode;
REALPIPEHANDLE fds[2];
- if (!CreatePipe(&fds[0], &fds[1], nullptr /* handles are not inherited */, 0))
+ if (!CreatePipe(&fds[0], &fds[1], nullptr /* handles are not inherited */, 0))
ythrow TFileError() << "failed to create a pipe";
TRealPipeHandle(fds[0]).Swap(reader);
TRealPipeHandle(fds[1]).Swap(writer);
@@ -254,9 +254,9 @@ private:
if (ErrorPipeFd[1].IsOpen()) {
ErrorPipeFd[1].Close();
}
- if (InputPipeFd[1].IsOpen()) {
+ if (InputPipeFd[1].IsOpen()) {
InputPipeFd[0].Close();
- }
+ }
}
void ReleaseParents() {
InputPipeFd[1].Release();
@@ -763,13 +763,13 @@ void TShellCommand::TImpl::Run() {
TPipes pipes;
if (OutputMode != TShellCommandOptions::HANDLE_INHERIT) {
- TRealPipeHandle::Pipe(pipes.OutputPipeFd[0], pipes.OutputPipeFd[1], CloseOnExec);
+ TRealPipeHandle::Pipe(pipes.OutputPipeFd[0], pipes.OutputPipeFd[1], CloseOnExec);
}
if (ErrorMode != TShellCommandOptions::HANDLE_INHERIT) {
- TRealPipeHandle::Pipe(pipes.ErrorPipeFd[0], pipes.ErrorPipeFd[1], CloseOnExec);
+ TRealPipeHandle::Pipe(pipes.ErrorPipeFd[0], pipes.ErrorPipeFd[1], CloseOnExec);
}
if (InputMode != TShellCommandOptions::HANDLE_INHERIT) {
- TRealPipeHandle::Pipe(pipes.InputPipeFd[0], pipes.InputPipeFd[1], CloseOnExec);
+ TRealPipeHandle::Pipe(pipes.InputPipeFd[0], pipes.InputPipeFd[1], CloseOnExec);
}
AtomicSet(ExecutionStatus, SHELL_RUNNING);
diff --git a/util/system/ut/ya.make b/util/system/ut/ya.make
index 127e7c261e..a15826cb0d 100644
--- a/util/system/ut/ya.make
+++ b/util/system/ut/ya.make
@@ -35,7 +35,7 @@ SRCS(
system/condvar_ut.cpp
system/cpu_id_ut.cpp
system/datetime_ut.cpp
- system/daemon_ut.cpp
+ system/daemon_ut.cpp
system/direct_io_ut.cpp
system/env_ut.cpp
system/error_ut.cpp
diff --git a/ya.bat b/ya.bat
index 4e897c1045..16e773382e 100755
--- a/ya.bat
+++ b/ya.bat
@@ -1,86 +1,86 @@
-@echo off
-rem Ya Simple Windows launcher
-setlocal
-call :dbg Ya Simple Windows Launcher (Debug)
-call :find_ya
-if ERRORLEVEL 1 exit /b 1
-call :dbg Ya: %YA_BAT_REAL%
-call :fix_env
-call :find_python
-if ERRORLEVEL 1 exit /b 1
-call :dbg Python: "%YA_BAT_PYTHON%"
-call "%YA_BAT_PYTHON%" "%YA_BAT_REAL%" %*
-exit /b %ERRORLEVEL%
-
-:find_ya
-call :dbg Searching for ya near ya.bat...
-set YA_BAT_REAL=%~dp0ya
-if exist "%YA_BAT_REAL%" exit /b 0
-call :err Ya not found
-exit /b 1
-
-:fix_env
-call :dbg Fixing environment...
-for /f "delims=: tokens=2" %%F in ('chcp') do (
- if "%%F" == " 65001" (
- call :dbg -- Forcing I/O encoding for python: utf-8
- set PYTHONIOENCODING=utf-8
- )
-)
-exit /b 0
-
-:find_python
-call :dbg Searching for python in PATH...
-for /f "delims=" %%F in ('where python 2^>nul') do (
- call :test_python %%~sF
- if not ERRORLEVEL 1 (
- set YA_BAT_PYTHON=%%F
- exit /b 0
- )
-)
-call :dbg Searching for python in ftypes...
-for /f delims^=^=^"^ tokens^=2 %%F in ('ftype Python.File 2^>nul') do (
- call :test_python %%F
- if not ERRORLEVEL 1 (
- set YA_BAT_PYTHON=%%F
- exit /b 0
- )
-)
-call :dbg Searching for python manually...
-for %%F in (
- C:\Python27\python.exe
- C:\Python26\python.exe
-) do (
- call :test_python %%F
- if not ERRORLEVEL 1 (
- set YA_BAT_PYTHON=%%F
- exit /b 0
- )
-)
-call :err Python not found
-exit /b 1
-
-:test_python
-call :dbg -- Checking python: %1
-if not exist %1 (
- call :dbg ---- Not found
- exit /b 1
-)
-for /f %%P in ('%1 -c "import os, sys; sys.stdout.write(os.name + '\n')" 2^>nul') do set YA_BAT_PYTHON_PLATFORM=%%P
-if not defined YA_BAT_PYTHON_PLATFORM (
- call :dbg ---- Not runnable
- exit /b 2
-)
-if not "%YA_BAT_PYTHON_PLATFORM%"=="nt" (
- call :dbg ---- Non-windows: %YA_BAT_PYTHON_PLATFORM%
- exit /b 3
-)
-exit /b 0
-
-:dbg
-if defined YA_BAT_DEBUG echo [ya.bat] %* 1>&2
-exit /b 0
-
-:err
-echo [ya.bat] Error: %* 1>&2
-exit /b 0
+@echo off
+rem Ya Simple Windows launcher
+setlocal
+call :dbg Ya Simple Windows Launcher (Debug)
+call :find_ya
+if ERRORLEVEL 1 exit /b 1
+call :dbg Ya: %YA_BAT_REAL%
+call :fix_env
+call :find_python
+if ERRORLEVEL 1 exit /b 1
+call :dbg Python: "%YA_BAT_PYTHON%"
+call "%YA_BAT_PYTHON%" "%YA_BAT_REAL%" %*
+exit /b %ERRORLEVEL%
+
+:find_ya
+call :dbg Searching for ya near ya.bat...
+set YA_BAT_REAL=%~dp0ya
+if exist "%YA_BAT_REAL%" exit /b 0
+call :err Ya not found
+exit /b 1
+
+:fix_env
+call :dbg Fixing environment...
+for /f "delims=: tokens=2" %%F in ('chcp') do (
+ if "%%F" == " 65001" (
+ call :dbg -- Forcing I/O encoding for python: utf-8
+ set PYTHONIOENCODING=utf-8
+ )
+)
+exit /b 0
+
+:find_python
+call :dbg Searching for python in PATH...
+for /f "delims=" %%F in ('where python 2^>nul') do (
+ call :test_python %%~sF
+ if not ERRORLEVEL 1 (
+ set YA_BAT_PYTHON=%%F
+ exit /b 0
+ )
+)
+call :dbg Searching for python in ftypes...
+for /f delims^=^=^"^ tokens^=2 %%F in ('ftype Python.File 2^>nul') do (
+ call :test_python %%F
+ if not ERRORLEVEL 1 (
+ set YA_BAT_PYTHON=%%F
+ exit /b 0
+ )
+)
+call :dbg Searching for python manually...
+for %%F in (
+ C:\Python27\python.exe
+ C:\Python26\python.exe
+) do (
+ call :test_python %%F
+ if not ERRORLEVEL 1 (
+ set YA_BAT_PYTHON=%%F
+ exit /b 0
+ )
+)
+call :err Python not found
+exit /b 1
+
+:test_python
+call :dbg -- Checking python: %1
+if not exist %1 (
+ call :dbg ---- Not found
+ exit /b 1
+)
+for /f %%P in ('%1 -c "import os, sys; sys.stdout.write(os.name + '\n')" 2^>nul') do set YA_BAT_PYTHON_PLATFORM=%%P
+if not defined YA_BAT_PYTHON_PLATFORM (
+ call :dbg ---- Not runnable
+ exit /b 2
+)
+if not "%YA_BAT_PYTHON_PLATFORM%"=="nt" (
+ call :dbg ---- Non-windows: %YA_BAT_PYTHON_PLATFORM%
+ exit /b 3
+)
+exit /b 0
+
+:dbg
+if defined YA_BAT_DEBUG echo [ya.bat] %* 1>&2
+exit /b 0
+
+:err
+echo [ya.bat] Error: %* 1>&2
+exit /b 0
diff --git a/ydb/core/grpc_streaming/grpc_streaming.h b/ydb/core/grpc_streaming/grpc_streaming.h
index ecac6fcf17..17968b4eac 100644
--- a/ydb/core/grpc_streaming/grpc_streaming.h
+++ b/ydb/core/grpc_streaming/grpc_streaming.h
@@ -9,8 +9,8 @@
#include <library/cpp/actors/core/actorsystem.h>
#include <library/cpp/actors/core/log.h>
-#include <contrib/libs/grpc/include/grpcpp/support/async_stream.h>
-#include <contrib/libs/grpc/include/grpcpp/support/async_unary_call.h>
+#include <contrib/libs/grpc/include/grpcpp/support/async_stream.h>
+#include <contrib/libs/grpc/include/grpcpp/support/async_unary_call.h>
#include <google/protobuf/text_format.h>
#include <atomic>
diff --git a/ydb/core/grpc_streaming/grpc_streaming_ut.cpp b/ydb/core/grpc_streaming/grpc_streaming_ut.cpp
index fe0b6aec6a..653c14e57f 100644
--- a/ydb/core/grpc_streaming/grpc_streaming_ut.cpp
+++ b/ydb/core/grpc_streaming/grpc_streaming_ut.cpp
@@ -307,7 +307,7 @@ public:
ReadFinished.Signal();
// It should be possible to reply with an OK status here
- Context->Finish(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "Everything is A-OK"));
+ Context->Finish(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "Everything is A-OK"));
}
void Handle(IContext::TEvNotifiedWhenDone::TPtr& ev, const TActorContext& ctx) {
@@ -455,7 +455,7 @@ Y_UNIT_TEST_SUITE(TGRpcStreamingTest) {
// Read failed on the server, but it's OK reply should reach us
auto status = stream->Finish();
- UNIT_ASSERT(status.error_code() == grpc::StatusCode::FAILED_PRECONDITION);
+ UNIT_ASSERT(status.error_code() == grpc::StatusCode::FAILED_PRECONDITION);
UNIT_ASSERT_VALUES_EQUAL(status.error_message(), "Everything is A-OK");
}